Programs & Examples On #Avurlasset

This tag should be used for questions about the AVURLAsset class of the AVFoundation framework used in iOS, macOS, and tvOS.

How to keep footer at bottom of screen

use this style

min-height:250px;
height:auto;

How to JSON serialize sets?

Shortened version of @AnttiHaapala:

json.dumps(dict_with_sets, default=lambda x: list(x) if isinstance(x, set) else x)

Get int from String, also containing letters, in Java

Perhaps get the size of the string and loop through each character and call isDigit() on each character. If it is a digit, then add it to a string that only collects the numbers before calling Integer.parseInt().

Something like:

    String something = "423e";
    int length = something.length();
    String result = "";
    for (int i = 0; i < length; i++) {
        Character character = something.charAt(i);
        if (Character.isDigit(character)) {
            result += character;
        }
    }
    System.out.println("result is: " + result);

System.drawing namespace not found under console application

For,Adding System.Drawing Follow some steps: Firstly, right click on the solution and click on add Reference. Secondly, Select the .NET Folder. And then double click on the Using.System.Drawing;

What is the difference between rb and r+b modes in file objects

On Windows, 'b' appended to the mode opens the file in binary mode, so there are also modes like 'rb', 'wb', and 'r+b'. Python on Windows makes a distinction between text and binary files; the end-of-line characters in text files are automatically altered slightly when data is read or written. This behind-the-scenes modification to file data is fine for ASCII text files, but it’ll corrupt binary data like that in JPEG or EXE files. Be very careful to use binary mode when reading and writing such files. On Unix, it doesn’t hurt to append a 'b' to the mode, so you can use it platform-independently for all binary files.

Source: Reading and Writing Files

What's the shebang/hashbang (#!) in Facebook and new Twitter URLs for?

I always assumed the ! just indicated that the hash fragment that followed corresponded to a URL, with ! taking the place of the site root or domain. It could be anything, in theory, but it seems the Google AJAX Crawling API likes it this way.

The hash, of course, just indicates that no real page reload is occurring, so yes, it’s for AJAX purposes. Edit: Raganwald does a lovely job explaining this in more detail.

How to convert BigDecimal to Double in Java?

You need to use the doubleValue() method to get the double value from a BigDecimal object.

BigDecimal bd; // the value you get
double d = bd.doubleValue(); // The double you want

Export HTML table to pdf using jspdf

You can also use the jsPDF-AutoTable plugin. You can check out a demo here that uses the following code.

var doc = new jsPDF('p', 'pt');
var elem = document.getElementById("basic-table");
var res = doc.autoTableHtmlToJson(elem);
doc.autoTable(res.columns, res.data);
doc.save("table.pdf");

Is mathematics necessary for programming?

IMO, you probably need an aptitude for mathematics, without necessarily having much knowledge in the field. So the things you require to be good at maths are similar to the things you require to be good at programming.

But in general, I can't remember the last time I used any sort of advanced maths in day-to-day programming, so no.

How do I handle Database Connections with Dapper in .NET?

Microsoft.AspNetCore.All: v2.0.3 | Dapper: v1.50.2

I am not sure if I am using the best practices correctly or not, but I am doing it this way, in order to handle multiple connection strings.

It's easy if you have only 1 connection string

Startup.cs

using System.Data;
using System.Data.SqlClient;

namespace DL.SO.Project.Web.UI
{
    public class Startup
    {
        public IConfiguration Configuration { get; private set; }

        // ......

        public void ConfigureServices(IServiceCollection services)
        {
            // Read the connection string from appsettings.
            string dbConnectionString = this.Configuration.GetConnectionString("dbConnection1");

            // Inject IDbConnection, with implementation from SqlConnection class.
            services.AddTransient<IDbConnection>((sp) => new SqlConnection(dbConnectionString));

            // Register your regular repositories
            services.AddScoped<IDiameterRepository, DiameterRepository>();

            // ......
        }
    }
}

DiameterRepository.cs

using Dapper;
using System.Data;

namespace DL.SO.Project.Persistence.Dapper.Repositories
{
    public class DiameterRepository : IDiameterRepository
    {
        private readonly IDbConnection _dbConnection;

        public DiameterRepository(IDbConnection dbConnection)
        {
            _dbConnection = dbConnection;
        }

        public IEnumerable<Diameter> GetAll()
        {
            const string sql = @"SELECT * FROM TABLE";

            // No need to use using statement. Dapper will automatically
            // open, close and dispose the connection for you.
            return _dbConnection.Query<Diameter>(sql);
        }

        // ......
    }
}

Problems if you have more than 1 connection string

Since Dapper utilizes IDbConnection, you need to think of a way to differentiate different database connections.

I tried to create multiple interfaces, 'inherited' from IDbConnection, corresponding to different database connections, and inject SqlConnection with different database connection strings on Startup.

That failed because SqlConnection inherits from DbConnection, and DbConnection inplements not only IDbConnection but also Component class. So your custom interfaces won't be able to use just the SqlConnection implenentation.

I also tried to create my own DbConnection class that takes different connection string. That's too complicated because you have to implement all the methods from DbConnection class. You lost the help from SqlConnection.

What I end up doing

  1. During Startup, I loaded all connection string values into a dictionary. I also created an enum for all the database connection names to avoid magic strings.
  2. I injected the dictionary as Singleton.
  3. Instead of injecting IDbConnection, I created IDbConnectionFactory and injected that as Transient for all repositories. Now all repositories take IDbConnectionFactory instead of IDbConnection.
  4. When to pick the right connection? In the constructor of all repositories! To make things clean, I created repository base classes and have the repositories inherit from the base classes. The right connection string selection can happen in the base classes.

DatabaseConnectionName.cs

namespace DL.SO.Project.Domain.Repositories
{
    public enum DatabaseConnectionName
    {
        Connection1,
        Connection2
    }
}

IDbConnectionFactory.cs

using System.Data;

namespace DL.SO.Project.Domain.Repositories
{
    public interface IDbConnectionFactory
    {
        IDbConnection CreateDbConnection(DatabaseConnectionName connectionName);
    }
}

DapperDbConenctionFactory - my own factory implementation

namespace DL.SO.Project.Persistence.Dapper
{
    public class DapperDbConnectionFactory : IDbConnectionFactory
    {
        private readonly IDictionary<DatabaseConnectionName, string> _connectionDict;

        public DapperDbConnectionFactory(IDictionary<DatabaseConnectionName, string> connectionDict)
        {
            _connectionDict = connectionDict;
        }

        public IDbConnection CreateDbConnection(DatabaseConnectionName connectionName)
        {
            string connectionString = null;
            if (_connectDict.TryGetValue(connectionName, out connectionString))
            {
                return new SqlConnection(connectionString);
            }

            throw new ArgumentNullException();
        }
    }
}

Startup.cs

namespace DL.SO.Project.Web.UI
{
    public class Startup
    {
        // ......

        public void ConfigureServices(IServiceCollection services)
        {
            var connectionDict = new Dictionary<DatabaseConnectionName, string>
            {
                { DatabaseConnectionName.Connection1, this.Configuration.GetConnectionString("dbConnection1") },
                { DatabaseConnectionName.Connection2, this.Configuration.GetConnectionString("dbConnection2") }
            };

            // Inject this dict
            services.AddSingleton<IDictionary<DatabaseConnectionName, string>>(connectionDict);

            // Inject the factory
            services.AddTransient<IDbConnectionFactory, DapperDbConnectionFactory>();

            // Register your regular repositories
            services.AddScoped<IDiameterRepository, DiameterRepository>();

            // ......
        }
    }
}

DiameterRepository.cs

using Dapper;
using System.Data;

namespace DL.SO.Project.Persistence.Dapper.Repositories
{
    // Move the responsibility of picking the right connection string
    //   into an abstract base class so that I don't have to duplicate
    //   the right connection selection code in each repository.
    public class DiameterRepository : DbConnection1RepositoryBase, IDiameterRepository
    {
        public DiameterRepository(IDbConnectionFactory dbConnectionFactory)
            : base(dbConnectionFactory) { }

        public IEnumerable<Diameter> GetAll()
        {
            const string sql = @"SELECT * FROM TABLE";

            // No need to use using statement. Dapper will automatically
            // open, close and dispose the connection for you.
            return base.DbConnection.Query<Diameter>(sql);
        }

        // ......
    }
}

DbConnection1RepositoryBase.cs

using System.Data;
using DL.SO.Project.Domain.Repositories;

namespace DL.SO.Project.Persistence.Dapper
{
    public abstract class DbConnection1RepositoryBase
    {
        public IDbConnection DbConnection { get; private set; }

        public DbConnection1RepositoryBase(IDbConnectionFactory dbConnectionFactory)
        {
            // Now it's the time to pick the right connection string!
            // Enum is used. No magic string!
            this.DbConnection = dbConnectionFactory.CreateDbConnection(DatabaseConnectionName.Connection1);
        }
    }
}

Then for other repositories that need to talk to the other connections, you can create a different repository base class for them.

using System.Data;
using DL.SO.Project.Domain.Repositories;

namespace DL.SO.Project.Persistence.Dapper
{
    public abstract class DbConnection2RepositoryBase
    {
        public IDbConnection DbConnection { get; private set; }

        public DbConnection2RepositoryBase(IDbConnectionFactory dbConnectionFactory)
        {
            this.DbConnection = dbConnectionFactory.CreateDbConnection(DatabaseConnectionName.Connection2);
        }
    }
}

using Dapper;
using System.Data;

namespace DL.SO.Project.Persistence.Dapper.Repositories
{
    public class ParameterRepository : DbConnection2RepositoryBase, IParameterRepository
    {
        public ParameterRepository (IDbConnectionFactory dbConnectionFactory)
            : base(dbConnectionFactory) { }

        public IEnumerable<Parameter> GetAll()
        {
            const string sql = @"SELECT * FROM TABLE";
            return base.DbConnection.Query<Parameter>(sql);
        }

        // ......
    }
}

Hope all these help.

How do I get information about an index and table owner in Oracle?

According to the docs, you can just do:

select INDEX_NAME, TABLE_OWNER, TABLE_NAME, UNIQUENESS from USER_INDEXES

or

select INDEX_NAME, TABLE_OWNER, TABLE_NAME, UNIQUENESS from ALL_INDEXES

if you want all indexes...

Get current URL from IFRAME

If your iframe is from another domain, (cross domain), the other answers are not going to help you... you will simply need to use this:

var currentUrl = document.referrer;

and - here you've got the main url!

SQL Inner Join On Null Values

You could also use the coalesce function. I tested this in PostgreSQL, but it should also work for MySQL or MS SQL server.

INNER JOIN x ON coalesce(x.qid, -1) = coalesce(y.qid, -1)

This will replace NULL with -1 before evaluating it. Hence there must be no -1 in qid.

String.equals versus ==

The == operator checks if the two references point to the same object or not.
.equals() checks for the actual string content (value).

Note that the .equals() method belongs to class Object (super class of all classes). You need to override it as per you class requirement, but for String it is already implemented and it checks whether two strings have the same value or not.

Case1)
String s1 = "Stack Overflow";
String s2 = "Stack Overflow";
s1 == s1;      // true
s1.equals(s2); // true
Reason: String literals created without null are stored in the string pool in the permgen area of the heap. So both s1 and s2 point to the same object in the pool.
Case2)
String s1 = new String("Stack Overflow");
String s2 = new String("Stack Overflow");
s1 == s2;      // false
s1.equals(s2); // true
Reason: If you create a String object using the `new` keyword a separate space is allocated to it on the heap.

Dynamically Add Variable Name Value Pairs to JSON Object

`enter code here`

Create Object from JSON String

_x000D_
_x000D_
var txt = '{"cart":{"sType":1, "produto":[{"pType":1, "pName":"produto original", "valor": 10.00},{"pType":1, "pName":"produto selecionado", "valor": 11.00}]}}';

var obj = JSON.parse(txt);
obj.cart.produto[0]['pName']='nome alterado';
obj.cart.produto[obj.cart.produto.length]={"pType":9, "pName":"produto adicionado", "valor": 19.00};

console.log(obj);

console.log(JSON.stringify(obj));



// compondo objeto JSON
var txt = '{"cart":{"sType":1, "product":[{"pType":1, "pName":"product genuine1", "pValue": 10.00},{"pType":1, "pName":"product genuine2", "pValue": 11.00}]}}';

// criando o objeto
var obj = JSON.parse(txt);

console.log('//log do objeto original');
console.log(obj);

// alterando o valor de uma "key", no caso a pName do produto[0]
obj.cart.product[0]['pName']='nome alterado';

// adicionando uma nova array
obj.cart.product[obj.cart.product.length]={"pType":9, "pName":"produto adicionado", "pValue": 19.00};

console.log('//log do objeto alterado');
console.log(obj);

console.log('//log do objeto alterado em txt');
console.log(JSON.stringify(obj));

// no html
document.getElementById('print').innerText = JSON.stringify(obj);
_x000D_
<html>
<body>

<h2>Manipulando um objeto</h2>
<p id="print"></p>
</body>
</html>
_x000D_
_x000D_
_x000D_

Room - Schema export directory is not provided to the annotation processor so we cannot export the schema

I use .kts Gradle files (Kotlin Gradle DSL) and the kotlin-kapt plugin but I still get a script compilation error when I use Ivanov Maksim's answer.

Unresolved reference: kapt

For me this was the only thing which worked:

android {
    defaultConfig {
        javaCompileOptions {
            annotationProcessorOptions {
                arguments = mapOf("room.schemaLocation" to "$projectDir/schemas")
            }
        }
    }
}

How to remove square brackets from list in Python?

You could convert it to a string instead of printing the list directly:

print(", ".join(LIST))

If the elements in the list aren't strings, you can convert them to string using either repr (if you want quotes around strings) or str (if you don't), like so:

LIST = [1, "foo", 3.5, { "hello": "bye" }]
print( ", ".join( repr(e) for e in LIST ) )

Which gives the output:

1, 'foo', 3.5, {'hello': 'bye'}

How to extract week number in sql

Try to replace 'w' for 'iw'. For example:

SELECT to_char(to_date(TRANSDATE, 'dd-mm-yyyy'), 'iw') as weeknumber from YOUR_TABLE;

Using bootstrap with bower

There is a prebuilt bootstrap bower package called bootstrap-css. I think this is what you (and I) were hoping to find.

bower install bootstrap-css

Thanks Nico.

How can I scroll up more (increase the scroll buffer) in iTerm2?

macOS default termianl

macOS 10.15.7

  1. open Terminal
  2. click Prefrences...
  3. select Window tab
  4. just change Scrollback to Limit number of rows to: what your wanted.

my screenshots

enter image description here

enter image description here

enter image description here

Match groups in Python

Starting Python 3.8, and the introduction of assignment expressions (PEP 572) (:= operator), we can now capture the condition value re.search(pattern, statement) in a variable (let's all it match) in order to both check if it's not None and then re-use it within the body of the condition:

if match := re.search('I love (\w+)', statement):
  print(f'He loves {match.group(1)}')
elif match := re.search("Ich liebe (\w+)", statement):
  print(f'Er liebt {match.group(1)}')
elif match := re.search("Je t'aime (\w+)", statement):
  print(f'Il aime {match.group(1)}')

How to execute a command in a remote computer?

IMO, in your case you can try this:

  1. Map the shared folder to a drive or folder on your machine. (here's how)
  2. Access the mapped drive/folder as you normally would local files.

Nothing needs to be installed. No services need to be running except those that enable folder sharing.

If you can access the shared folder and maps it on your machine, most things should work just like local files, including command prompts and all explorer-enhancement tools.

This is different from using PsExec (or RDP-ing in) in that you do not need to have administrative rights and/or remote desktop/terminal services connection rights on the remote server, you just need to be able to access those shared folders.

Also make sure you have all the necessary security permissions to run whatever commands/tools you want to run on those shared folders as well.


If, however you wish the processing to be done on the target machine, then you can try PsExec as @divo and @recursive pointed out, something alongs:

PsExec \\yourServerName -u yourUserName cmd.exe

Which will brings gives you a command prompt at the remote machine. And from there you can execute whatever you want.

I am not sure but I think you need either the Server (lanmanserver) or the Terminal Services (TermService) service to be running (which should have already be running).

Is there a way to split a widescreen monitor in to two or more virtual monitors?

The next version of Windows (Windows 7) will be able to snap windows to the left or right half of the screen. Doesn't help right now, but it's something to look forward to.

http://arstechnica.com/news.ars/post/20081028-first-look-at-windows-7.html

PHP Pass by reference in foreach

I got here just by accident and the OP's question got my attention. Unfortunately I do not understand any of the explanations from the top. Seems to me like everybody knows it, gets it, accetps it, just cannot explain.

Luckily, a pure sentence from PHP documentation on foreach makes this completely clear:

Warning: Reference of a $value and the last array element remain even after the foreach loop. It is recommended to destroy it by unset().

Flex-box: Align last row to grid

As other posters have mentioned - there's no clean way to left-align the last row with flexbox (at least as per the current spec)

However, for what it's worth: With the CSS Grid Layout Module this is surprisingly easy to produce:

Basically the relevant code boils down to this:

ul {
  display: grid; /* 1 */
  grid-template-columns: repeat(auto-fill, 100px); /* 2 */
  grid-gap: 1rem; /* 3 */
  justify-content: space-between; /* 4 */
}

1) Make the container element a grid container

2) Set the grid with auto columns of width 100px. (Note the use of auto-fill (as apposed to auto-fit - which (for a 1-row layout) collapses empty tracks to 0 - causing the items to expand to take up the remaining space. This would result in a justified 'space-between' layout when grid has only one row which in our case is not what we want. (check out this demo to see the difference between them)).

3) Set gaps/gutters for the grid rows and columns - here, since want a 'space-between' layout - the gap will actually be a minimum gap because it will grow as necessary.

4) Similar to flexbox.

_x000D_
_x000D_
ul {_x000D_
  display: grid;_x000D_
  grid-template-columns: repeat(auto-fill, 100px);_x000D_
  grid-gap: 1rem;_x000D_
  justify-content: space-between;_x000D_
  _x000D_
  /* boring properties */_x000D_
  list-style: none;_x000D_
  background: wheat;_x000D_
  padding: 2rem;_x000D_
  width: 80vw;_x000D_
  margin: 0 auto;_x000D_
}_x000D_
_x000D_
li {_x000D_
  height: 50px;_x000D_
  border: 1px solid green;_x000D_
}
_x000D_
<ul>_x000D_
  <li></li>_x000D_
  <li></li>_x000D_
  <li></li>_x000D_
  <li></li>_x000D_
  <li></li>_x000D_
  <li></li>_x000D_
  <li></li>_x000D_
</ul>
_x000D_
_x000D_
_x000D_

Codepen Demo (Resize to see the effect)

Do you know the Maven profile for mvnrepository.com?

Please use this profile

  <profiles>
    <profile>
        <repositories>
            <repository>
                <id>mvnrepository</id>
                <name>mvnrepository</name>
                <url>http://www.mvnrepository.com</url>
            </repository>
        </repositories>
    </profile>
  </profiles>
  <activeProfiles>
    <activeProfile>mvnrepository</activeProfile>
  </activeProfiles>

Is it possible to force Excel recognize UTF-8 CSV files automatically?

Just for help users interested on opening the file on Excel that achieve this thread like me.

I have used the wizard below and it worked fine for me, importing an UTF-8 file. Not transparent, but useful if you already have the file.

  1. Open Microsoft Excel 2007.
  2. Click on the Data menu bar option.
  3. Click on the From Text icon.
  4. Navigate to the location of the file that you want to import. Click on the filename and then click on the Import button. The Text Import Wizard - Step 1 or 3 window will now appear on the screen.
  5. Choose the file type that best describes your data - Delimited or Fixed Width.
  6. Choose 65001: Unicode (UTF-8) from the drop-down list that appears next to File origin.
  7. Click on the Next button to display the Text Import Wizard - Step 2 or 3 window.
  8. Place a checkmark next to the delimiter that was used in the file you wish to import into Microsoft Excel 2007. The Data preview window will show you how your data will appear based on the delimiter that you chose.
  9. Click on the Next button to display the Text Import Wizard - Step 3 of 3.
  10. Choose the appropriate data format for each column of data that you want to import. You also have the option to not import one or more columns of data if you want.
  11. Click on the Finish button to finish importing your data into Microsoft Excel 2007.

Source: https://www.itg.ias.edu/content/how-import-csv-file-uses-utf-8-character-encoding-0

What happened to Lodash _.pluck?

Or try pure ES6 nonlodash method like this

const reducer = (array, object) => {
  array.push(object.a)
  return array
}

var objects = [{ 'a': 1 }, { 'a': 2 }];
objects.reduce(reducer, [])

Tools to selectively Copy HTML+CSS+JS From A Specific Element of DOM

Just copy the part you want from the webpage and paste it in the wysiwyg editor. Check the html source by clicking on the "source" button on the editor toolbar.

I've found this most easiest way when I was working on a Drupal site. I use wysiwyg CKeditor.

Algorithm to convert RGB to HSV and HSV to RGB in range 0-255 for both

This isn't C, but it's certainly does work. All the other methods I see here work by casing everything into parts of a hexagon, and approximating "angles" from that. By instead starting with a different equation using cosines, and solving for h s and v, you get a lot nicer relationship between hsv and rgb, and tweening becomes smoother (at the cost of it being way slower).

Assume everything is floating point. If r g and b go from 0 to 1, h goes from 0 to 2pi, v goes from 0 to 4/3, and s goes from 0 to 2/3.

The following code is written in Lua. It's easily translatable into anything else.

local hsv do
    hsv         ={}
    local atan2 =math.atan2
    local cos   =math.cos
    local sin   =math.sin

    function hsv.fromrgb(r,b,g)
        local c=r+g+b
        if c<1e-4 then
            return 0,2/3,0
        else
            local p=2*(b*b+g*g+r*r-g*r-b*g-b*r)^0.5
            local h=atan2(b-g,(2*r-b-g)/3^0.5)
            local s=p/(c+p)
            local v=(c+p)/3
            return h,s,v
        end
    end

    function hsv.torgb(h,s,v)
        local r=v*(1+s*(cos(h)-1))
        local g=v*(1+s*(cos(h-2.09439)-1))
        local b=v*(1+s*(cos(h+2.09439)-1))
        return r,g,b
    end

    function hsv.tween(h0,s0,v0,h1,s1,v1,t)
        local dh=(h1-h0+3.14159)%6.28318-3.14159
        local h=h0+t*dh
        local s=s0+t*(s1-s0)
        local v=v0+t*(v1-v0)
        return h,s,v
    end
end

git: Your branch is ahead by X commits

I think you’re misreading the message — your branch isn’t ahead of master, it is master. It’s ahead of origin/master, which is a remote tracking branch that records the status of the remote repository from your last push, pull, or fetch. It’s telling you exactly what you did; you got ahead of the remote and it’s reminding you to push.

How do I inject a controller into another controller in AngularJS

you can also use $rootScope to call a function/method of 1st controller from second controller like this,

.controller('ctrl1', function($rootScope, $scope) {
     $rootScope.methodOf2ndCtrl();
     //Your code here. 
})

.controller('ctrl2', function($rootScope, $scope) {
     $rootScope.methodOf2ndCtrl = function() {
     //Your code here. 
}
})

How to use the ProGuard in Android Studio?

The other answers here are great references on using proguard. However, I haven't seen an issue discussed that I ran into that was a mind bender. After you generate a signed release .apk, it's put in the /release folder in your app but my app had an apk that wasn't in the /release folder. Hence, I spent hours decompiling the wrong apk wondering why my proguard changes were having no affect. Hope this helps someone!

How to run a PowerShell script from a batch file

You need the -ExecutionPolicy parameter:

Powershell.exe -executionpolicy remotesigned -File  C:\Users\SE\Desktop\ps.ps1

Otherwise PowerShell considers the arguments a line to execute and while Set-ExecutionPolicy is a cmdlet, it has no -File parameter.

How to input a path with a white space?

SOME_PATH=/mnt/someProject/some\ path

should work

presenting ViewController with NavigationViewController swift

The accepted answer is great. This is not answer, but just an illustration of the issue.

I present a viewController like this:

inside vc1:

func showVC2() {
    if let navController = self.navigationController{
        navController.present(vc2, animated: true)
    }
}

inside vc2:

func returnFromVC2() {
    if let navController = self.navigationController {
        navController.popViewController(animated: true)
    }else{
        print("navigationController is nil") <-- I was reaching here!
    }
}

As 'stefandouganhyde' has said: "it is not contained by your UINavigationController or any other"

new solution:

func returnFromVC2() {
    dismiss(animated: true, completion: nil)
}

How to stop java process gracefully?

Thanks for you answers. Shutdown hooks seams like something that would work in my case. But I also bumped into the thing called Monitoring and Management beans:
http://java.sun.com/j2se/1.5.0/docs/guide/management/overview.html
That gives some nice possibilities, for remote monitoring, and manipulation of the java process. (Was introduced in Java 5)

In Perl, how can I concisely check if a $variable is defined and contains a non zero length string?

How about

if (length ($name || '')) {
  # do something with $name
}

This isn't quite equivalent to your original version, as it will also return false if $name is the numeric value 0 or the string '0', but will behave the same in all other cases.

In perl 5.10 (or later), the appropriate approach would be to use the defined-or operator instead:

use feature ':5.10';
if (length ($name // '')) {
  # do something with $name
}

This will decide what to get the length of based on whether $name is defined, rather than whether it's true, so 0/'0' will handle those cases correctly, but it requires a more recent version of perl than many people have available.

Searching a list of objects in Python

filter(lambda x: x.n == 5, myList)

Passing Arrays to Function in C++

The simple answer is that arrays are ALWAYS passed by reference and the int arg[] simply lets the compiler know to expect an array

How do I copy to the clipboard in JavaScript?

I found the following solution:

I have the text in a hidden input. Because setSelectionRange doesn't work on hidden inputs, I changed temporarily the type to text, copied the text, and then made it hidden again. If you want to copy the text from an element, you can pass it to the function and save its content in the target variable.

jQuery('#copy').on('click', function () {
    copyToClipboard();
});

function copyToClipboard() {
    var target = jQuery('#hidden_text');

    // Make it visible, so can be focused
    target.attr('type', 'text');
    target.focus();
    // Select all the text
    target[0].setSelectionRange(0, target.val().length);

    // Copy the selection
    var succeed;
    try {
        succeed = document.execCommand("copy");
    }
    catch (e) {
        succeed = false;
    }

    // Hide input again
    target.attr('type', 'hidden');

    return succeed;
}

getting integer values from textfield

As You're getting values from textfield as jTextField3.getText();.

As it is a textField it will return you string format as its format says:

String getText()

      Returns the text contained in this TextComponent.

So, convert your String to Integer as:

int jml = Integer.parseInt(jTextField3.getText());

instead of directly setting

   int jml = jTextField3.getText();

Programmatically check Play Store for app updates

There's AppUpdater library. How to include:

  1. Add the repository to your project build.gradle:
allprojects {
    repositories {
        jcenter()
        maven {
            url "https://jitpack.io"
        }
    }
}
  1. Add the library to your module build.gradle:
dependencies {
    compile 'com.github.javiersantos:AppUpdater:2.6.4'
}
  1. Add INTERNET and ACCESS_NETWORK_STATE permissions to your app's Manifest:
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
  1. Add this to your activity:
AppUpdater appUpdater = new AppUpdater(this); 
appUpdater.start();

What do pty and tty mean?

A tty is a physical terminal-teletype port on a computer (usually a serial port).

The word teletype is a shorting of the telegraph typewriter, or teletypewriter device from the 1930s - itself an electromagnetic device which replaced the telegraph encoding machines of the 1830s and 1840s.

Teletypewriter
TTY - Teletypewriter 1930s

A pty is a pseudo-teletype port provided by a computer Operating System Kernel to connect software programs emulating terminals, such as ssh, xterm, or screen.

enter image description here
PTY - PseudoTeletype

A terminal is simply a computer's user interface that uses text for input and output.


OS Implementations

These use pseudo-teletype ports however, their naming and implementations have diverged a little.

Linux mounts a special file system devpts on /dev (the 's' presumably standing for serial) that creates a corresponding entry in /dev/pts for every new terminal window you open, e.g. /dev/pts/0


macOS/FreeBSD also use the /dev file structure however, they use a numbered TTY naming convention ttys for every new terminal window you open e.g. /dev/ttys002


Microsoft Windows still has the concept of an LPT port for Line Printer Terminals within it's Command Shell for output to a printer.

Preventing form resubmission

Well I found nobody mentioned this trick.

Without redirection, you can still prevent the form confirmation when refresh.

By default, form code is like this:

<form method="post" action="test.php">

now, change it to <form method="post" action="test.php?nonsense=1">

You will see the magic.

I guess its because browsers won't trigger the confirmation alert popup if it gets a GET method (query string) in the url.

In Chrome 55, prevent showing Download button for HTML 5 video

As of Chrome58 you can now use controlsList to remove controls you don't want shown. This is available for both <audio> and <video> tags.

If you want to remove the download button in the controls do this:

<audio controls controlsList="nodownload">

upgade python version using pip

pip is designed to upgrade python packages and not to upgrade python itself. pip shouldn't try to upgrade python when you ask it to do so.

Don't type pip install python but use an installer instead.

How can I run a directive after the dom has finished rendering?

It depends on how your $('site-header') is constructed.

You can try to use $timeout with 0 delay. Something like:

return function(scope, element, attrs) {
    $timeout(function(){
        $('.main').height( $('.site-header').height() -  $('.site-footer').height() );
    });        
}

Explanations how it works: one, two.

Don't forget to inject $timeout in your directive:

.directive('sticky', function($timeout)

Reshape an array in NumPy

a = np.arange(18).reshape(9,2)
b = a.reshape(3,3,2).swapaxes(0,2)

# a: 
array([[ 0,  1],
       [ 2,  3],
       [ 4,  5],
       [ 6,  7],
       [ 8,  9],
       [10, 11],
       [12, 13],
       [14, 15],
       [16, 17]])


# b:
array([[[ 0,  6, 12],
        [ 2,  8, 14],
        [ 4, 10, 16]],

       [[ 1,  7, 13],
        [ 3,  9, 15],
        [ 5, 11, 17]]])

How do I set hostname in docker-compose?

As of docker-compose version 3 and later, you can just use the hostname key:

version: '3'
services:
  dns:
    hostname: 'your-name'

How to get all privileges back to the root user in MySQL?

This worked for me on Ubuntu:

Stop MySQL server:

/etc/init.d/mysql stop

Start MySQL from the commandline:

/usr/sbin/mysqld

In another terminal enter mysql and issue:

grant all privileges on *.* to 'root'@'%' with grant option;

You may also want to add

grant all privileges on *.* to 'root'@'localhost' with grant option;

and optionally use a password as well.

flush privileges;

and then exit your MySQL prompt and then kill the mysqld server running in the foreground. Restart with

/etc/init.d/mysql start  

css - position div to bottom of containing div

Add position: relative to .outside. (https://developer.mozilla.org/en-US/docs/CSS/position)

Elements that are positioned relatively are still considered to be in the normal flow of elements in the document. In contrast, an element that is positioned absolutely is taken out of the flow and thus takes up no space when placing other elements. The absolutely positioned element is positioned relative to nearest positioned ancestor. If a positioned ancestor doesn't exist, the initial container is used.

The "initial container" would be <body>, but adding the above makes .outside positioned.

git with development, staging and production branches

The thought process here is that you spend most of your time in development. When in development, you create a feature branch (off of development), complete the feature, and then merge back into development. This can then be added to the final production version by merging into production.

See A Successful Git Branching Model for more detail on this approach.

Read Numeric Data from a Text File in C++

Repeat >> reads in loop.

#include <iostream>
#include <fstream>
int main(int argc, char * argv[])
{
    std::fstream myfile("D:\\data.txt", std::ios_base::in);

    float a;
    while (myfile >> a)
    {
        printf("%f ", a);
    }

    getchar();

    return 0;
}

Result:

45.779999 67.900002 87.000000 34.889999 346.000000 0.980000

If you know exactly, how many elements there are in a file, you can chain >> operator:

int main(int argc, char * argv[])
{
    std::fstream myfile("D:\\data.txt", std::ios_base::in);

    float a, b, c, d, e, f;

    myfile >> a >> b >> c >> d >> e >> f;

    printf("%f\t%f\t%f\t%f\t%f\t%f\n", a, b, c, d, e, f);

    getchar();

    return 0;
}

Edit: In response to your comments in main question.

You have two options.

  • You can run previous code in a loop (or two loops) and throw away a defined number of values - for example, if you need the value at point (97, 60), you have to skip 5996 (= 60 * 100 + 96) values and use the last one. This will work if you're interested only in specified value.
  • You can load the data into an array - as Jerry Coffin sugested. He already gave you quite nice class, which will solve the problem. Alternatively, you can use simple array to store the data.

Edit: How to skip values in file

To choose the 1234th value, use the following code:

int skipped = 1233;
for (int i = 0; i < skipped; i++)
{
    float tmp;
    myfile >> tmp;
}
myfile >> value;

XML Schema How to Restrict Attribute by Enumeration

New answer to old question

None of the existing answers to this old question address the real problem.

The real problem was that xs:complexType cannot directly have a xs:extension as a child in XSD. The fix is to use xs:simpleContent first. Details follow...


Your XML,

<price currency="euros">20000.00</price>

will be valid against either of the following corrected XSDs:

Locally defined attribute type

<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">

  <xs:element name="price">
    <xs:complexType>
      <xs:simpleContent>
        <xs:extension base="xs:decimal">
          <xs:attribute name="currency">
            <xs:simpleType>
              <xs:restriction base="xs:string">
                <xs:enumeration value="pounds" />
                <xs:enumeration value="euros" />
                <xs:enumeration value="dollars" />
              </xs:restriction>
            </xs:simpleType>
          </xs:attribute>
        </xs:extension>
      </xs:simpleContent>
    </xs:complexType>
  </xs:element>
</xs:schema>

Globally defined attribute type

<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">

  <xs:simpleType name="currencyType">
    <xs:restriction base="xs:string">
      <xs:enumeration value="pounds" />
      <xs:enumeration value="euros" />
      <xs:enumeration value="dollars" />
    </xs:restriction>
  </xs:simpleType>

  <xs:element name="price">
    <xs:complexType>
      <xs:simpleContent>
        <xs:extension base="xs:decimal">
          <xs:attribute name="currency" type="currencyType"/>
        </xs:extension>
      </xs:simpleContent>
    </xs:complexType>
  </xs:element>
</xs:schema>

Notes

  • As commented by @Paul, these do change the content type of price from xs:string to xs:decimal, but this is not strictly necessary and was not the real problem.
  • As answered by @user998692, you could separate out the definition of currency, and you could change to xs:decimal, but this too was not the real problem.

The real problem was that xs:complexType cannot directly have a xs:extension as a child in XSD; xs:simpleContent is needed first.

A related matter (that wasn't asked but may have confused other answers):

How could price be restricted given that it has an attribute?

In this case, a separate, global definition of priceType would be needed; it is not possible to do this with only local type definitions.

How to restrict element content when element has attribute

<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">

  <xs:simpleType name="priceType">  
    <xs:restriction base="xs:decimal">  
      <xs:minInclusive value="0.00"/>  
      <xs:maxInclusive value="99999.99"/>  
    </xs:restriction>  
  </xs:simpleType>

  <xs:element name="price">
    <xs:complexType>
      <xs:simpleContent>
        <xs:extension base="priceType">
          <xs:attribute name="currency">
            <xs:simpleType>
              <xs:restriction base="xs:string">
                <xs:enumeration value="pounds" />
                <xs:enumeration value="euros" />
                <xs:enumeration value="dollars" />
              </xs:restriction>
            </xs:simpleType>
          </xs:attribute>
        </xs:extension>
      </xs:simpleContent>
    </xs:complexType>
  </xs:element>
</xs:schema>

How to import csv file in PHP?

$row = 1;
    $arrResult  = array();
    if (($handle = fopen("ifsc_code.csv", "r")) !== FALSE) {
        while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
            $num = count($data);
            DB::table('banks')->insert(
                array('bank_name' => $data[1], 'ifsc' => $data[2], 'micr' => $data[3], 'branch_name' => $data[4],'address' => $data[5], 'contact' => $data[6], 'city' => $data[7],'district' => $data[8],'state' => $data[9])
            );
        }
        fclose($handle);
    }

is of a type that is invalid for use as a key column in an index

A solution would be to declare your key as nvarchar(20).

library not found for -lPods

Not a solution worked for me, this is really unbearable, there's a file libpods.a(which was red coloured) I removed it and everything working fine! Cheers to me ;)

ORA-01017 Invalid Username/Password when connecting to 11g database from 9i client

I am not an expert. If you are getting ORA-01017 while trying to connect HR schema from SQL Developer in Oracle 11g Please try to unlock the HR as follows

alter user HR identified by hr DEFAULT tablespace users temporary tablespace temp account unlock;

Android Studio : How to uninstall APK (or execute adb command) automatically before Run or Debug?

This command with --user 0 do the job:

adb uninstall --user 0 <package_name>

What does "wrong number of arguments (1 for 0)" mean in Ruby?

If you change from using a lambda with one argument to a function with one argument, you will get this error.

For example:

You had:

foobar = lambda do |baz|
  puts baz
end

and you changed the definition to

def foobar(baz)
  puts baz
end

And you left your invocation as:

foobar.call(baz)

And then you got the message

ArgumentError: wrong number of arguments (0 for 1)

when you really meant:

foobar(baz)

Why is there no Char.Empty like String.Empty?

A char, unlike a string, is a discrete thing with a fixed size. A string is really a container of chars.

So, Char.Empty doesn't really make sense in that context. If you have a char, it's not empty.

The SELECT permission was denied on the object 'sysobjects', database 'mssqlsystemresource', schema 'sys'

It looks like someone might have revoked the permissions on sys.configurations for the public role. Or denied access to this view to this particular user. Or the user has been created after the public role was removed from the sys.configurations tables.

Provide SELECT permission to public user sys.configurations object.

css h1 - only as wide as the text

This is because your <h1> is the width of the centercol. Specify a width on the <h1> and use margin: 0 auto; if you want it centered.

Or, alternatively, you could float the <h1>, which would make it only exactly as wide as the text.

Fluid or fixed grid system, in responsive design, based on Twitter Bootstrap

Source - http://coding.smashingmagazine.com/2009/06/02/fixed-vs-fluid-vs-elastic-layout-whats-the-right-one-for-you/

Pros

  • Fixed-width layouts are much easier to use and easier to customize in terms of design.
  • Widths are the same for every browser, so there is less hassle with images, forms, video and other content that are fixed-width.
  • There is no need for min-width or max-width, which isn’t supported by every browser anyway.
  • Even if a website is designed to be compatible with the smallest screen resolution, 800×600, the content will still be wide enough at a larger resolution to be easily legible.

Cons

  • A fixed-width layout may create excessive white space for users with larger screen resolutions, thus upsetting “divine proportion,” the “Rule of Thirds,” overall balance and other design principles.
  • Smaller screen resolutions may require a horizontal scroll bar, depending the fixed layout’s width.
  • Seamless textures, patterns and image continuation are needed to accommodate those with larger resolutions.
  • Fixed-width layouts generally have a lower overall score when it comes to usability.

In C/C++ what's the simplest way to reverse the order of bits in a byte?

I think this is simple enough

uint8_t reverse(uint8_t a)
{
  unsigned w = ((a << 7) & 0x0880) | ((a << 5) & 0x0440) | ((a << 3) & 0x0220) | ((a << 1) & 0x0110);
  return static_cast<uint8_t>(w | (w>>8));
}

or

uint8_t reverse(uint8_t a)
{
  unsigned w = ((a & 0x11) << 7) | ((a & 0x22) << 5) | ((a & 0x44) << 3) | ((a & 0x88) << 1);
  return static_cast<uint8_t>(w | (w>>8));
}

Android App Not Install. An existing package by the same name with a conflicting signature is already installed

If above solutions did not work for you then you may have doing something as following ..

1) installing the app from Appstore.
2) updating it with sign APK with same package name updated version.

So basically there are two kinds if APK's.

1) you uploaded on playstore known as original APK.
2) download from playstore known as derived APK.

In this case basically you are downloading derived apk and updating it with original APK.

For let it work fine uploaded new signed released APK in the internal test mode on the Google Play Store and download the derived APK to check the update scenario.

enter image description here

How do I change the default port (9000) that Play uses when I execute the "run" command?

From the play console, you just need to type run 8888, if you want to run it from port 8888.

play> run 8888

How do you validate a URL with a regular expression in Python?

urlfinders = [
    re.compile("([0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}|(((news|telnet|nttp|file|http|ftp|https)://)|(www|ftp)[-A-Za-z0-9]*\\.)[-A-Za-z0-9\\.]+)(:[0-9]*)?/[-A-Za-z0-9_\\$\\.\\+\\!\\*\\(\\),;:@&=\\?/~\\#\\%]*[^]'\\.}>\\),\\\"]"),
    re.compile("([0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}|(((news|telnet|nttp|file|http|ftp|https)://)|(www|ftp)[-A-Za-z0-9]*\\.)[-A-Za-z0-9\\.]+)(:[0-9]*)?"),
    re.compile("(~/|/|\\./)([-A-Za-z0-9_\\$\\.\\+\\!\\*\\(\\),;:@&=\\?/~\\#\\%]|\\\\
)+"),
    re.compile("'\\<((mailto:)|)[-A-Za-z0-9\\.]+@[-A-Za-z0-9\\.]+"),
]

NOTE: As ugly as it looks in your browser just copy paste and the formatting should be good

Found at the python mailing lists and used for the gnome-terminal

source: http://mail.python.org/pipermail/python-list/2007-January/595436.html

Tesseract running error

Add this to your code :

instance.setDatapath("C:\\somepath\\tessdata");

instance.setLanguage("eng");

Use images instead of radio buttons

$spinTime: 3;
html, body { height: 100%; }
* { user-select: none; }
body {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    font-family: 'Raleway', sans-serif;
    font-size: 72px;
    input {
        display: none;
        + div > span {
            display: inline-block;
            position: relative;
            white-space: nowrap;
            color: rgba(#fff, 0);
            transition: all 0.5s ease-in-out;
            span {
                display: inline-block;
                position: absolute;
                left: 50%;
                text-align: center;
                color: rgba(#000, 1);
                transform: translateX(-50%);
                transform-origin: left;
                transition: all 0.5s ease-in-out;
                &:first-of-type {
                    transform: rotateY(0deg) translateX(-50%);
                }
                &:last-of-type {
                    transform: rotateY(0deg) translateX(0%) scaleX(0.75) skew(23deg,0deg);
                }
            }
        }
        &#fat:checked ~ div > span span {
            &:first-of-type {
                transform: rotateY(0deg) translateX(-50%);
            }
            &:last-of-type {
                transform: rotateY(0deg) translateX(0%) scaleX(0.75) skew(23deg,0deg);
            }
        }
        &#fit:checked ~ div > span {
            margin: 0 -10px;
            span {
                &:first-of-type {
                    transform: rotateY(90deg) translateX(-50%);
                }
                &:last-of-type {
                    transform: rotateY(0deg) translateX(-50%) scaleX(1) skew(0deg,0deg);
                }
            }
        }
        + div + div {
            width: 280px;
            margin-top: 10px;
            label {
                display: block;
                padding: 20px 10px;
                text-align: center;
                transition: all 0.15s ease-in-out;
                background: #fff;
                border-radius: 10px;
                box-sizing: border-box;
                width: 48%;
                font-size: 64px;
                cursor: pointer;
                &:first-child {
                    float: left;
                    box-shadow:
                        inset 0 0 0 4px #1597ff,
                        0 15px 15px -10px rgba(darken(#1597ff, 10%), 0.375);
                }
                &:last-child { float: right; }
            }
        }
        &#fat:checked ~ div + div label {
            &:first-child {
                box-shadow:
                    inset 0 0 0 4px #1597ff,
                    0 15px 15px -10px rgba(darken(#1597ff, 10%), 0.375);
            }
            &:last-child {
                box-shadow:
                    inset 0 0 0 0px #1597ff,
                    0 10px 15px -20px rgba(#1597ff, 0);
            }
        }
        &#fit:checked ~ div + div label {
            &:first-child {
                box-shadow:
                    inset 0 0 0 0px #1597ff,
                    0 10px 15px -20px rgba(#1597ff, 0);
            }
            &:last-child {
                box-shadow:
                    inset 0 0 0 4px #1597ff,
                    0 15px 15px -10px rgba(darken(#1597ff, 10%), 0.375);
            }
        }
    }
}


<input type="radio" id="fat" name="fatfit">
<input type="radio" id="fit" name="fatfit">
<div>
    GET F<span>A<span>A</span><span>I</span></span>T
</div>
<div>
    <label for="fat"></label>
    <label for="fit"></label>
</div>

psql: server closed the connection unexepectedly

If your Postgres was working and suddenly you encountered with this error, my problem was resolved just by restarting Postgres service or container.

Does hosts file exist on the iPhone? How to change it?

No, an iPhone application can only change stuff within its own little sandbox. (And even there there are things that you can't change on the fly.)

Your best bet is probably to use the servers IP address rather than hostname. Slightly harder, but not that hard if you just need to resolve a single address, would be to put a DNS server on your Mac and configure your iPhone to use that.

Difference between "read commited" and "repeatable read"

Read committed is an isolation level that guarantees that any data read was committed at the moment is read. It simply restricts the reader from seeing any intermediate, uncommitted, 'dirty' read. It makes no promise whatsoever that if the transaction re-issues the read, will find the Same data, data is free to change after it was read.

Repeatable read is a higher isolation level, that in addition to the guarantees of the read committed level, it also guarantees that any data read cannot change, if the transaction reads the same data again, it will find the previously read data in place, unchanged, and available to read.

The next isolation level, serializable, makes an even stronger guarantee: in addition to everything repeatable read guarantees, it also guarantees that no new data can be seen by a subsequent read.

Say you have a table T with a column C with one row in it, say it has the value '1'. And consider you have a simple task like the following:

BEGIN TRANSACTION;
SELECT * FROM T;
WAITFOR DELAY '00:01:00'
SELECT * FROM T;
COMMIT;

That is a simple task that issue two reads from table T, with a delay of 1 minute between them.

  • under READ COMMITTED, the second SELECT may return any data. A concurrent transaction may update the record, delete it, insert new records. The second select will always see the new data.
  • under REPEATABLE READ the second SELECT is guaranteed to display at least the rows that were returned from the first SELECT unchanged. New rows may be added by a concurrent transaction in that one minute, but the existing rows cannot be deleted nor changed.
  • under SERIALIZABLE reads the second select is guaranteed to see exactly the same rows as the first. No row can change, nor deleted, nor new rows could be inserted by a concurrent transaction.

If you follow the logic above you can quickly realize that SERIALIZABLE transactions, while they may make life easy for you, are always completely blocking every possible concurrent operation, since they require that nobody can modify, delete nor insert any row. The default transaction isolation level of the .Net System.Transactions scope is serializable, and this usually explains the abysmal performance that results.

And finally, there is also the SNAPSHOT isolation level. SNAPSHOT isolation level makes the same guarantees as serializable, but not by requiring that no concurrent transaction can modify the data. Instead, it forces every reader to see its own version of the world (it's own 'snapshot'). This makes it very easy to program against as well as very scalable as it does not block concurrent updates. However, that benefit comes with a price: extra server resource consumption.

Supplemental reads:

libxml install error using pip

I was having this issue with a pip install of lxml. My CentOS instance was using python 2.6 which was throwing this error.

To get around this I did the following to run with Python 2.7:

  1. Run: sudo yum install python-devel
  2. Run sudo yum install libxslt-devel libxml2-devel
  3. Use Python 2.7 to run your command by using /usr/bin/python2.7 YOUR_PYTHON_COMMAND (For me it was /usr/bin/python2.7 -m pip install lxml)

Difference between DataFrame, Dataset, and RDD in Spark

First thing is DataFrame was evolved from SchemaRDD.

depreated method toSchemaRDD

Yes.. conversion between Dataframe and RDD is absolutely possible.

Below are some sample code snippets.

  • df.rdd is RDD[Row]

Below are some of options to create dataframe.

  • 1) yourrddOffrow.toDF converts to DataFrame.

  • 2) Using createDataFrame of sql context

    val df = spark.createDataFrame(rddOfRow, schema)

where schema can be from some of below options as described by nice SO post..
From scala case class and scala reflection api

import org.apache.spark.sql.catalyst.ScalaReflection
val schema = ScalaReflection.schemaFor[YourScalacaseClass].dataType.asInstanceOf[StructType]

OR using Encoders

import org.apache.spark.sql.Encoders
val mySchema = Encoders.product[MyCaseClass].schema

as described by Schema can also be created using StructType and StructField

val schema = new StructType()
  .add(StructField("id", StringType, true))
  .add(StructField("col1", DoubleType, true))
  .add(StructField("col2", DoubleType, true)) etc...

image description

In fact there Are Now 3 Apache Spark APIs..

enter image description here

  1. RDD API :

The RDD (Resilient Distributed Dataset) API has been in Spark since the 1.0 release.

The RDD API provides many transformation methods, such as map(), filter(), and reduce() for performing computations on the data. Each of these methods results in a new RDD representing the transformed data. However, these methods are just defining the operations to be performed and the transformations are not performed until an action method is called. Examples of action methods are collect() and saveAsObjectFile().

RDD Example:

rdd.filter(_.age > 21) // transformation
   .map(_.last)// transformation
.saveAsObjectFile("under21.bin") // action

Example: Filter by attribute with RDD

rdd.filter(_.age > 21)
  1. DataFrame API

Spark 1.3 introduced a new DataFrame API as part of the Project Tungsten initiative which seeks to improve the performance and scalability of Spark. The DataFrame API introduces the concept of a schema to describe the data, allowing Spark to manage the schema and only pass data between nodes, in a much more efficient way than using Java serialization.

The DataFrame API is radically different from the RDD API because it is an API for building a relational query plan that Spark’s Catalyst optimizer can then execute. The API is natural for developers who are familiar with building query plans

Example SQL style :

df.filter("age > 21");

Limitations : Because the code is referring to data attributes by name, it is not possible for the compiler to catch any errors. If attribute names are incorrect then the error will only detected at runtime, when the query plan is created.

Another downside with the DataFrame API is that it is very scala-centric and while it does support Java, the support is limited.

For example, when creating a DataFrame from an existing RDD of Java objects, Spark’s Catalyst optimizer cannot infer the schema and assumes that any objects in the DataFrame implement the scala.Product interface. Scala case class works out the box because they implement this interface.

  1. Dataset API

The Dataset API, released as an API preview in Spark 1.6, aims to provide the best of both worlds; the familiar object-oriented programming style and compile-time type-safety of the RDD API but with the performance benefits of the Catalyst query optimizer. Datasets also use the same efficient off-heap storage mechanism as the DataFrame API.

When it comes to serializing data, the Dataset API has the concept of encoders which translate between JVM representations (objects) and Spark’s internal binary format. Spark has built-in encoders which are very advanced in that they generate byte code to interact with off-heap data and provide on-demand access to individual attributes without having to de-serialize an entire object. Spark does not yet provide an API for implementing custom encoders, but that is planned for a future release.

Additionally, the Dataset API is designed to work equally well with both Java and Scala. When working with Java objects, it is important that they are fully bean-compliant.

Example Dataset API SQL style :

dataset.filter(_.age < 21);

Evaluations diff. between DataFrame & DataSet : enter image description here

Catalist level flow..(Demystifying DataFrame and Dataset presentation from spark summit) enter image description here

Further reading... databricks article - A Tale of Three Apache Spark APIs: RDDs vs DataFrames and Datasets

ValueError : I/O operation on closed file

Same error can raise by mixing: tabs + spaces.

with open('/foo', 'w') as f:
 (spaces OR  tab) print f       <-- success
 (spaces AND tab) print f       <-- fail

PHP Multidimensional Array Searching (Find key by specific value)

Very simple:

function myfunction($products, $field, $value)
{
   foreach($products as $key => $product)
   {
      if ( $product[$field] === $value )
         return $key;
   }
   return false;
}

Copying data from one SQLite database to another

Consider a example where I have two databases namely allmsa.db and atlanta.db. Say the database allmsa.db has tables for all msas in US and database atlanta.db is empty.

Our target is to copy the table atlanta from allmsa.db to atlanta.db.

Steps

  1. sqlite3 atlanta.db(to go into atlanta database)
  2. Attach allmsa.db. This can be done using the command ATTACH '/mnt/fastaccessDS/core/csv/allmsa.db' AS AM; note that we give the entire path of the database to be attached.
  3. check the database list using sqlite> .databases you can see the output as
seq  name             file                                                      
---  ---------------  ----------------------------------------------------------
0    main             /mnt/fastaccessDS/core/csv/atlanta.db                  
2    AM               /mnt/fastaccessDS/core/csv/allmsa.db 
  1. now you come to your actual target. Use the command INSERT INTO atlanta SELECT * FROM AM.atlanta;

This should serve your purpose.

Javascript Equivalent to PHP Explode()

Just a little addition to psycho brm´s answer (his version doesn't work in IE<=8). This code is cross-browser compatible:

function explode (s, separator, limit)
{
    var arr = s.split(separator);
    if (limit) {
        arr.push(arr.splice(limit-1, (arr.length-(limit-1))).join(separator));
    }
    return arr;
}

How to set Java environment path in Ubuntu

Let me Simplify , first download JDK from Oracle Website : Link

2] Then Extract it

3] Create a folder (jvm) in /usr/lib/ i.e /usr/lib/jvm

4] move the extracted folder from the jdk to /usr/lib/jvm/

*Note : use terminal , sudo , mv command i.e. sudo mv

5] Create a .sh file at /etc/profile.d/ eg: /etc/profile.d/myenvvar.sh

6] In the .sh file type

export JAVA_HOME=/usr/lib/jvm/jdk1.7.0

export PATH=$PATH:$JAVA_HOME/bin

*Note : use terminal , gedit and sudo eg: sudo gedit myenvvar.sh

7] Turn Off the Computer, after all these steps and Restart it

8]Open Terminal , and type

java -version

9] Check the output , then type

echo $JAVA_HOME

10] Check the output and be happy :)

Python in Xcode 4+?

This thread is old, but to chime in for Xcode Version 8.3.3, Tyler Crompton's method in the accepted answer still works (some of the names are very slightly different, but not enough to matter).

2 points where I struggled slightly:

Step 16: If the python executable you want is greyed out, right click it and select quick look. Then close the quick look window, and it should now be selectable.

Step 19: If this isn’t working for you, you can enter the name of just the python file in the Arguments tab, and then enter the project root directory explicitly in the Options tab under Working Directory--check the “Use custom working directory” box, and type in your project root directory in the field below it.

Calling a JavaScript function returned from an Ajax response

I think to correctly interpret your question under this form: "OK, I'm already done with all the Ajax stuff; I just wish to know if the JavaScript function my Ajax callback inserted into the DIV is callable at any time from that moment on, that is, I do not want to call it contextually to the callback return".

OK, if you mean something like this the answer is yes, you can invoke your new code by that moment at any time during the page persistence within the browser, under the following conditions:

1) Your JavaScript code returned by Ajax callback must be syntactically OK;
2) Even if your function declaration is inserted into a <script> block within an existing <div> element, the browser won't know the new function exists, as the declaration code has never been executed. So, you must eval() your declaration code returned by the Ajax callback, in order to effectively declare your new function and have it available during the whole page lifetime.

Even if quite dummy, this code explains the idea:

<html>
    <body>
        <div id="div1">
        </div>
        <div id="div2">
            <input type="button" value="Go!" onclick="go()" />
        </div>
        <script type="text/javascript">
            var newsc = '<script id="sc1" type="text/javascript">function go() { alert("GO!") }<\/script>';
            var e = document.getElementById('div1');
            e.innerHTML = newsc;
            eval(document.getElementById('sc1').innerHTML);
        </script>
    </body>
</html>

I didn't use Ajax, but the concept is the same (even if the example I chose sure isn't much smart :-)

Generally speaking, I do not question your solution design, i.e. whether it is more or less appropriate to externalize + generalize the function in a separate .js file and the like, but please take note that such a solution could raise further problems, especially if your Ajax invocations should repeat, i.e. if the context of the same function should change or in case the declared function persistence should be concerned, so maybe you should seriously consider to change your design to one of the suggested examples in this thread.

Finally, if I misunderstood your question, and you're talking about contextual invocation of the function when your Ajax callback returns, then my feeling is to suggest the Prototype approach described by krosenvold, as it is cross-browser, tested and fully functional, and this can give you a better roadmap for future implementations.

How is a CSS "display: table-column" supposed to work?

The "table-column" display type means it acts like the <col> tag in HTML - i.e. an invisible element whose width* governs the width of the corresponding physical column of the enclosing table.

See the W3C standard for more information about the CSS table model.

* And a few other properties like borders, backgrounds.

Switch android x86 screen resolution

Based on my experience, it's enough to use the following additional boot options:

UVESA_MODE=320x480 DPI=160

No need to add vga definition. Watch out for DPI value! As bigger one makes your icons bigger.

To add the previous boot options, go to debug mode (during grub menu selection)

mount -o remount,rw /mnt
vi /mnt/grub/menu.lst

Now edit on this line:

kernel /android-2.3-RC1/kernel quiet root=/dev/ram0 androidboot_hardware=eeepc acpi_sleep=s3_bios,s3_mode SRC=/android-2.3-RC1 SDCARD=/data/sdcard.img UVESA_MODE=320x480 DPI=160

Reboot

Set HTML dropdown selected option using JSTL

In Servlet do:

String selectedRole = "rat"; // Or "cat" or whatever you'd like.
request.setAttribute("selectedRole", selectedRole);

Then in JSP do:

<select name="roleName">
    <c:forEach items="${roleNames}" var="role">
        <option value="${role}" ${role == selectedRole ? 'selected' : ''}>${role}</option>
    </c:forEach>
</select>

It will print the selected attribute of the HTML <option> element so that you end up like:

<select name="roleName">
    <option value="cat">cat</option>
    <option value="rat" selected>rat</option>
    <option value="unicorn">unicorn</option>
</select>

Apart from the problem: this is not a combo box. This is a dropdown. A combo box is an editable dropdown.

Create a copy of a table within the same database DB2

CREATE TABLE NEW_TABLENAME LIKE OLD_TABLENAME;

Works for DB2 V 9.7

How do I see the current encoding of a file in Sublime Text?

For my part, and without any plug-in, simply saving the file either from the File menu or with keyboards shortcuts

CTRL + S (Windows, Linux) or CMD + S (Mac OS)

briefly displays the current encoding - between parentheses - in the status bar, at the bottom of the editor's window. This suggestion works in Sublime Text 2 and 3.

Note that the displayed encoding to the right in the status bar of Sublime Text 3, may display the wrong encoding of the file if you have attempted to save the file with an encoding that can't represent all the characters in your file. In this case you would have seen an informational dialog and Sublime telling you it's falling back to UTF-8. This may not be the case, so be careful.

Append an int to a std::string

I have a feeling that your ClientID is not of a string type (zero-terminated char* or std::string) but some integral type (e.g. int) so you need to convert number to the string first:

std::stringstream ss;
ss << ClientID;
query.append(ss.str());

But you can use operator+ as well (instead of append):

query += ss.str();

Use JsonReader.setLenient(true) to accept malformed JSON at line 1 column 1 path $

I solved this problem very easily after finding out this happens when you aren't outputting a proper JSON object, I simply used the echo json_encode($arrayName); instead of print_r($arrayName); With my php api.

Every programming language or at least most programming languages should have their own version of the json_encode() and json_decode() functions.

Create boolean column in MySQL with false as default value?

If you are making the boolean column as not null then the default 'default' value is false; you don't have to explicitly specify it.

Read the current full URL with React?

this.props.location is a react-router feature, you'll have to install if you want to use it.

Note: doesn't return the full url.

vba listbox multicolumn add

Simplified example (with counter):

With Me.lstbox
    .ColumnCount = 2
    .ColumnWidths = "60;60"
    .AddItem
    .List(i, 0) = Company_ID
    .List(i, 1) = Company_name 
    i = i + 1

end with

Make sure to start the counter with 0, not 1 to fill up a listbox.

How can I simulate an array variable in MySQL?

I would try something like this for multiple collections. I'm a MySQL beginner. Sorry about the function names, couldn't decide on what names would be best.

delimiter //

drop  procedure init_
//
create procedure init_()
begin
  CREATE TEMPORARY TABLE if not exists 
    val_store(  
    realm  varchar(30) 
    ,  id  varchar(30) 
    ,  val   varchar(255) 
    ,  primary key ( realm , id )
    );
end;
//

drop function if exists get_
//
create function get_( p_realm varchar(30) , p_id varchar(30) )
  returns varchar(255)
  reads sql data
begin 
  declare ret_val varchar(255);
  declare continue handler for 1146 set ret_val = null;
  select val into ret_val from val_store where id = p_id;
  return ret_val;
end;
//

drop procedure if exists set_
//
create procedure set_( p_realm varchar(30) , p_id varchar(30) , p_val varchar(255) )
begin
  call init_(); 
  insert into val_store (realm,id,val) values (p_realm , p_id , p_val) on duplicate key update val = p_val;
end;
//

drop   procedure if exists remove_
//
create procedure remove_( p_realm varchar(30) , p_id varchar(30) )
begin
  call init_();
  delete from val_store where realm = p_realm and id = p_id;
end;
//

drop   procedure if exists erase_
//
create procedure erase_( p_realm varchar(30) ) 
begin
  call init_();
  delete from val_store where realm = p_realm;
end;
//

call set_('my_array_table_name','my_key','my_value');

select get_('my_array_table_name','my_key');

Bash: Echoing a echo command with a variable in bash

The immediate problem is you have is with quoting: by using double quotes ("..."), your variable references are instantly expanded, which is probably not what you want.

Use single quotes instead - strings inside single quotes are not expanded or interpreted in any way by the shell.

(If you want selective expansion inside a string - i.e., expand some variable references, but not others - do use double quotes, but prefix the $ of references you do not want expanded with \; e.g., \$var).

However, you're better off using a single here-doc[ument], which allows you to create multi-line stdin input on the spot, bracketed by two instances of a self-chosen delimiter, the opening one prefixed by <<, and the closing one on a line by itself - starting at the very first column; search for Here Documents in man bash or at http://www.gnu.org/software/bash/manual/html_node/Redirections.html.

If you quote the here-doc delimiter (EOF in the code below), variable references are also not expanded. As @chepner points out, you're free to choose the method of quoting in this case: enclose the delimiter in single quotes or double quotes, or even simply arbitrarily escape one character in the delimiter with \:

echo "creating new script file."

cat <<'EOF'  > "$servfile"
#!/bin/bash
read -p "Please enter a service: " ser
servicetest=`getsebool -a | grep ${ser}` 
if [ $servicetest > /dev/null ]; then 
  echo "we are now going to work with ${ser}"
else
  exit 1
fi
EOF

As @BruceK notes, you can prefix your here-doc delimiter with - (applied to this example: <<-"EOF") in order to have leading tabs stripped, allowing for indentation that makes the actual content of the here-doc easier to discern. Note, however, that this only works with actual tab characters, not leading spaces.

Employing this technique combined with the afterthoughts regarding the script's content below, we get (again, note that actual tab chars. must be used to lead each here-doc content line for them to get stripped):

cat <<-'EOF' > "$servfile"
    #!/bin/bash
    read -p "Please enter a service name: " ser
    if [[ -n $(getsebool -a | grep "${ser}") ]]; then 
      echo "We are now going to work with ${ser}."
    else
      exit 1
    fi
EOF

Finally, note that in bash even normal single- or double-quoted strings can span multiple lines, but you won't get the benefits of tab-stripping or line-block scoping, as everything inside the quotes becomes part of the string.

Thus, note how in the following #!/bin/bash has to follow the opening ' immediately in order to become the first line of output:

echo '#!/bin/bash
read -p "Please enter a service: " ser
servicetest=$(getsebool -a | grep "${ser}")
if [[ -n $servicetest ]]; then 
  echo "we are now going to work with ${ser}"
else
  exit 1
fi' > "$servfile"

Afterthoughts regarding the contents of your script:

  • The syntax $(...) is preferred over `...` for command substitution nowadays.
  • You should double-quote ${ser} in the grep command, as the command will likely break if the value contains embedded spaces (alternatively, make sure that the valued read contains no spaces or other shell metacharacters).
  • Use [[ -n $servicetest ]] to test whether $servicetest is empty (or perform the command substitution directly inside the conditional) - [[ ... ]] - the preferred form in bash - protects you from breaking the conditional if the $servicetest happens to have embedded spaces; there's NEVER a need to suppress stdout output inside a conditional (whether [ ... ] or [[ ... ]], as no stdout output is passed through; thus, the > /dev/null is redundant (that said, with a command substitution inside a conditional, stderr output IS passed through).

Equivalent of SQL ISNULL in LINQ?

Since aa is the set/object that might be null, can you check aa == null ?

(aa / xx might be interchangeable (a typo in the question); the original question talks about xx but only defines aa)

i.e.

select new {
    AssetID = x.AssetID,
    Status = aa == null ? (bool?)null : aa.Online; // a Nullable<bool>
}

or if you want the default to be false (not null):

select new {
    AssetID = x.AssetID,
    Status = aa == null ? false : aa.Online;
}

Update; in response to the downvote, I've investigated more... the fact is, this is the right approach! Here's an example on Northwind:

        using(var ctx = new DataClasses1DataContext())
        {
            ctx.Log = Console.Out;
            var qry = from boss in ctx.Employees
                      join grunt in ctx.Employees
                          on boss.EmployeeID equals grunt.ReportsTo into tree
                      from tmp in tree.DefaultIfEmpty()
                      select new
                             {
                                 ID = boss.EmployeeID,
                                 Name = tmp == null ? "" : tmp.FirstName
                        };
            foreach(var row in qry)
            {
                Console.WriteLine("{0}: {1}", row.ID, row.Name);
            }
        }

And here's the TSQL - pretty much what we want (it isn't ISNULL, but it is close enough):

SELECT [t0].[EmployeeID] AS [ID],
    (CASE
        WHEN [t2].[test] IS NULL THEN CONVERT(NVarChar(10),@p0)
        ELSE [t2].[FirstName]
     END) AS [Name]
FROM [dbo].[Employees] AS [t0]
LEFT OUTER JOIN (
    SELECT 1 AS [test], [t1].[FirstName], [t1].[ReportsTo]
    FROM [dbo].[Employees] AS [t1]
    ) AS [t2] ON ([t0].[EmployeeID]) = [t2].[ReportsTo]
-- @p0: Input NVarChar (Size = 0; Prec = 0; Scale = 0) []
-- Context: SqlProvider(Sql2008) Model: AttributedMetaModel Build: 3.5.30729.1

QED?

Programmatically add new column to DataGridView

Add new column to DataTable and use column Expression property to set your Status expression.

Here you can find good example: DataColumn.Expression Property

DataTable and DataColumn Expressions in ADO.NET - Calculated Columns

UPDATE

Code sample:

DataTable dt = new DataTable();
dt.Columns.Add(new DataColumn("colBestBefore", typeof(DateTime)));
dt.Columns.Add(new DataColumn("colStatus", typeof(string)));

dt.Columns["colStatus"].Expression = String.Format("IIF(colBestBefore < #{0}#, 'Ok','Not ok')", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));

dt.Rows.Add(DateTime.Now.AddDays(-1));
dt.Rows.Add(DateTime.Now.AddDays(1));
dt.Rows.Add(DateTime.Now.AddDays(2));
dt.Rows.Add(DateTime.Now.AddDays(-2));

demoGridView.DataSource = dt;

UPDATE #2

dt.Columns["colStatus"].Expression = String.Format("IIF(CONVERT(colBestBefore, 'System.DateTime') < #{0}#, 'Ok','Not ok')", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));

How to crop an image using PIL?

There is a crop() method:

w, h = yourImage.size
yourImage.crop((0, 30, w, h-30)).save(...)

Convert double/float to string

I know maybe it is unnecessary, but I made a function which converts float to string:

CODE:

#include <stdio.h>

/** Number on countu **/

int n_tu(int number, int count)
{
    int result = 1;
    while(count-- > 0)
        result *= number;

    return result;
}

/*** Convert float to string ***/
void float_to_string(float f, char r[])
{
    long long int length, length2, i, number, position, sign;
    float number2;

    sign = -1;   // -1 == positive number
    if (f < 0)
    {
        sign = '-';
        f *= -1;
    }

    number2 = f;
    number = f;
    length = 0;  // Size of decimal part
    length2 = 0; // Size of tenth

    /* Calculate length2 tenth part */
    while( (number2 - (float)number) != 0.0 && !((number2 - (float)number) < 0.0) )
    {
         number2 = f * (n_tu(10.0, length2 + 1));
         number = number2;

         length2++;
    }

    /* Calculate length decimal part */
    for (length = (f > 1) ? 0 : 1; f > 1; length++)
        f /= 10;

    position = length;
    length = length + 1 + length2;
    number = number2;
    if (sign == '-')
    {
        length++;
        position++;
    }

    for (i = length; i >= 0 ; i--)
    {
        if (i == (length))
            r[i] = '\0';
        else if(i == (position))
            r[i] = '.';
        else if(sign == '-' && i == 0)
            r[i] = '-';
        else
        {
            r[i] = (number % 10) + '0';
            number /=10;
        }
    }
}

How can I select the first day of a month in SQL?

In addition to all the above answer, a way based on a function introduced in sql 2012

SELECT DATEFROMPARTS(YEAR(@mydate),MONTH(@mydate),1)

Core Data: Quickest way to delete all instances of an entity

    func deleteAll(entityName: String) {

    let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: entityName)
    let deleteRequest = NSBatchDeleteRequest(fetchRequest: fetchRequest)
    deleteRequest.resultType = .resultTypeObjectIDs
    guard let context = self.container?.viewContext
        else { print("error in deleteAll")
            return }

    do {
        let result = try context.execute(deleteRequest) as? NSBatchDeleteResult
        let objectIDArray = result?.result as? [NSManagedObjectID]
        let changes: [AnyHashable : Any] = [NSDeletedObjectsKey : objectIDArray as Any]
        NSManagedObjectContext.mergeChanges(fromRemoteContextSave: changes, into: [context])
    } catch {
        print(error.localizedDescription)
    }
}

How to unlock android phone through ADB

This command helps you to unlock phone using ADB

adb shell input keyevent 82 # unlock

Show Current Location and Nearby Places and Route between two places using Google Maps API in Android

Lots of answers so far, which are all excellent pointers to API's and tutorials. One thing I'd like to add is that I work out how far the markers are from my location using something like:

float distance = (float) loc.distanceTo(loc2);

Hope this helps refine the detail for your problem. It returns a rough estimate of distance (in m) between points, and is useful for getting rid of POI that might be too far away - good to declutter your map?

Using underscores in Java variables and method names

"Bad style" is very subjective. If a certain conventions works for you and your team, I think that will qualify a bad/good style.

To answer your question: I use a leading underscore to mark private variables. I find it clear and I can scan through code fast and find out what's going on.

(I almost never use "this" though, except to prevent a name clash.)

cannot call member function without object

You need to instantiate an object in order to call its member functions. The member functions need an object to operate on; they can't just be used on their own. The main() function could, for example, look like this:

int main()
{
   Name_pairs np;
   cout << "Enter names and ages. Use 0 to cancel.\n";
   while(np.test())
   {
      np.read_names();
      np.read_ages();
   }
   np.print();
   keep_window_open();
}

Disable Button in Angular 2

Change ng-disabled="!contractTypeValid" to [disabled]="!contractTypeValid"

using sql count in a case statement

SELECT 
    COUNT(CASE WHEN rsp_ind = 0 then 1 ELSE NULL END) as "New",
    COUNT(CASE WHEN rsp_ind = 1 then 1 ELSE NULL END) as "Accepted"
from tb_a

You can see the output for this request HERE

Plugin with id 'com.google.gms.google-services' not found

In the app build.gradle dependency, you must add the following code

classpath 'com.google.gms:google-services:$last_version'

And then please check the Google Play Service SDK tools installing status.

How do I iterate through children elements of a div using jQuery?

If you need to loop through child elements recursively:

function recursiveEach($element){
    $element.children().each(function () {
        var $currentElement = $(this);
        // Show element
        console.info($currentElement);
        // Show events handlers of current element
        console.info($currentElement.data('events'));
        // Loop her children
        recursiveEach($currentElement);
    });
}

// Parent div
recursiveEach($("#div"));   

NOTE: In this example I show the events handlers registered with an object.

Pass a simple string from controller to a view MVC3

@Steve Hobbs' answer is probably the best, but some of your other solutions could have worked. For example, @Html.Label(ViewBag.CurrentPath); will probably work with an explicit cast, like @Html.Label((string)ViewBag.CurrentPath);. Also, your reference to currentPath in @Html.Label(ViewData["CurrentPath"].ToString()); is capitalized, wherein your other code it is not, which is probably why you were getting null reference exceptions.

Delete first character of a string in Javascript

var test = '0test';
test = test.replace(/0(.*)/, '$1');

Multiple inheritance for an anonymous class

Anonymous classes must extend or implement something, like any other Java class, even if it's just java.lang.Object.

For example:

Runnable r = new Runnable() {
   public void run() { ... }
};

Here, r is an object of an anonymous class which implements Runnable.

An anonymous class can extend another class using the same syntax:

SomeClass x = new SomeClass() {
   ...
};

What you can't do is implement more than one interface. You need a named class to do that. Neither an anonymous inner class, nor a named class, however, can extend more than one class.

How do you add PostgreSQL Driver as a dependency in Maven?

From site PostgreSQL, of date 02/04/2016 (https://jdbc.postgresql.org/download.html):

"This is the current version of the driver. Unless you have unusual requirements (running old applications or JVMs), this is the driver you should be using. It supports Postgresql 7.2 or newer and requires a 1.6 or newer JVM. It contains support for SSL and the javax.sql package. If you are using the 1.6 then you should use the JDBC4 version. If you are using 1.7 then you should use the JDBC41 version. If you are using 1.8 then you should use the JDBC42 versionIf you are using a java version older than 1.6 then you will need to use a JDBC3 version of the driver, which will by necessity not be current"

Converting DateTime format using razor

This is solution:

@item.Published.Value.ToString("dd. MM. yyyy")

Before ToString() use Value.

Tomcat 8 throwing - org.apache.catalina.webresources.Cache.getResource Unable to add the resource

This isn’t a solution in the sense that it doesn’t resolve the conditions which cause the message to appear in the logs, but the message can be suppressed by appending the following to conf/logging.properties:

org.apache.catalina.webresources.Cache.level = SEVERE

This filters out the “Unable to add the resource” logs, which are at level WARNING.

In my view a WARNING is not necessarily an error that needs to be addressed, but rather can be ignored if desired.

Python 3 turn range to a list

in Python 3.x, the range() function got its own type. so in this case you must use iterator

list(range(1000))

Can Powershell Run Commands in Parallel?

You can execute parallel jobs in Powershell 2 using Background Jobs. Check out Start-Job and the other job cmdlets.

# Loop through the server list
Get-Content "ServerList.txt" | %{

  # Define what each job does
  $ScriptBlock = {
    param($pipelinePassIn) 
    Test-Path "\\$pipelinePassIn\c`$\Something"
    Start-Sleep 60
  }

  # Execute the jobs in parallel
  Start-Job $ScriptBlock -ArgumentList $_
}

Get-Job

# Wait for it all to complete
While (Get-Job -State "Running")
{
  Start-Sleep 10
}

# Getting the information back from the jobs
Get-Job | Receive-Job

Gradle does not find tools.jar

If you use terminal to build and you have this error you can point to jdk bundled with android studio in your gradle.properties file:

org.gradle.java.home=/usr/local/android-studio/jre

Bootstrap button - remove outline on Chrome OS X

It worked for my bootstrap button after a such stress

.btn:focus,
.btn:active:focus,
.btn.active:focus,
.btn.focus,
.btn:active.focus,
.btn.active.focus {
    outline: none!important;
    box-shadow: none;
}

How can I move all the files from one folder to another using the command line?

Lookup move /? on Windows and man mv on Unix systems

Why can't I have abstract static methods in C#?

Static methods cannot be inherited or overridden, and that is why they can't be abstract. Since static methods are defined on the type, not the instance, of a class, they must be called explicitly on that type. So when you want to call a method on a child class, you need to use its name to call it. This makes inheritance irrelevant.

Assume you could, for a moment, inherit static methods. Imagine this scenario:

public static class Base
{
    public static virtual int GetNumber() { return 5; }
}

public static class Child1 : Base
{
    public static override int GetNumber() { return 1; }
}

public static class Child2 : Base
{
    public static override int GetNumber() { return 2; }
}

If you call Base.GetNumber(), which method would be called? Which value returned? It's pretty easy to see that without creating instances of objects, inheritance is rather hard. Abstract methods without inheritance are just methods that don't have a body, so can't be called.

How can I selectively merge or pick changes from another branch in Git?

It is not exactly what you were looking for, but it was useful to me:

git checkout -p <branch> -- <paths> ...

It is a mix of some answers.

Use jquery click to handle anchor onClick()

<div class = "solTitle"> <a href = "#"  id = "solution0" onClick = "openSolution();">Solution0 </a></div> <br>

<div class= "solTitle"> <a href = "#"  id = "solution1" onClick = "openSolution();">Solution1 </a></div> <br>



$(document).ready(function(){
    $('.solTitle a').click(function(e) {
        e.preventDefault();
        alert('here in');
         var divId = 'summary' +$(this).attr('id');

        document.getElementById(divId).className = ''; /* or $('#'+divid).removeAttr('class'); */

    });
 });

I changed few things:

  1. remove the onclick attr and bind click event inside the document.ready
  2. changed solTitle to be an ID to a CLASS: id cant be repeated

What is a "callable"?

From Python's sources object.c:

/* Test whether an object can be called */

int
PyCallable_Check(PyObject *x)
{
    if (x == NULL)
        return 0;
    if (PyInstance_Check(x)) {
        PyObject *call = PyObject_GetAttrString(x, "__call__");
        if (call == NULL) {
            PyErr_Clear();
            return 0;
        }
        /* Could test recursively but don't, for fear of endless
           recursion if some joker sets self.__call__ = self */
        Py_DECREF(call);
        return 1;
    }
    else {
        return x->ob_type->tp_call != NULL;
    }
}

It says:

  1. If an object is an instance of some class then it is callable iff it has __call__ attribute.
  2. Else the object x is callable iff x->ob_type->tp_call != NULL

Desciption of tp_call field:

ternaryfunc tp_call An optional pointer to a function that implements calling the object. This should be NULL if the object is not callable. The signature is the same as for PyObject_Call(). This field is inherited by subtypes.

You can always use built-in callable function to determine whether given object is callable or not; or better yet just call it and catch TypeError later. callable is removed in Python 3.0 and 3.1, use callable = lambda o: hasattr(o, '__call__') or isinstance(o, collections.Callable).

Example, a simplistic cache implementation:

class Cached:
    def __init__(self, function):
        self.function = function
        self.cache = {}

    def __call__(self, *args):
        try: return self.cache[args]
        except KeyError:
            ret = self.cache[args] = self.function(*args)
            return ret    

Usage:

@Cached
def ack(x, y):
    return ack(x-1, ack(x, y-1)) if x*y else (x + y + 1) 

Example from standard library, file site.py, definition of built-in exit() and quit() functions:

class Quitter(object):
    def __init__(self, name):
        self.name = name
    def __repr__(self):
        return 'Use %s() or %s to exit' % (self.name, eof)
    def __call__(self, code=None):
        # Shells like IDLE catch the SystemExit, but listen when their
        # stdin wrapper is closed.
        try:
            sys.stdin.close()
        except:
            pass
        raise SystemExit(code)
__builtin__.quit = Quitter('quit')
__builtin__.exit = Quitter('exit')

How do I set the version information for an existing .exe, .dll?

While it's not a batch process, Visual Studio can also add/edit file resources.

Just use File->Open->File on the .EXE or .DLL. This is handy for fixing version information post-build, or adding it to files that don't have these resources to begin with.

What's the best visual merge tool for Git?

I hear good things about kdiff3.

AttributeError: 'list' object has no attribute 'encode'

You need to do encode on tmp[0], not on tmp.

tmp is not a string. It contains a (Unicode) string.

Try running type(tmp) and print dir(tmp) to see it for yourself.

Error when testing on iOS simulator: Couldn't register with the bootstrap server

I'm having this problem very often recently. What would prevent this from occurring? Logging out and in fixes the problem but.. it's annoying to do so every so often.

EDIT:

I just found the cause. I had a bug in ApplicationWillTerminate method. So when i click stop button on Xcode window, app couldn't properly terminate and started to hang.

check Activity Monitor to see if your app is on the list. force quit if possible.

How do I find files with a path length greater than 260 characters in Windows?

From http://www.powershellmagazine.com/2012/07/24/jaap-brassers-favorite-powershell-tips-and-tricks/:

Get-ChildItem –Force –Recurse –ErrorAction SilentlyContinue –ErrorVariable AccessDenied

the first part just iterates through this and sub-folders; using -ErrorVariable AccessDenied means push the offending items into the powershell variable AccessDenied.

You can then scan through the variable like so

$AccessDenied |
Where-Object { $_.Exception -match "must be less than 260 characters" } |
ForEach-Object { $_.TargetObject }

If you don't care about these files (may be applicable in some cases), simply drop the -ErrorVariable AccessDenied part.

How to use ConcurrentLinkedQueue?

Just use it as you would a non-concurrent collection. The Concurrent[Collection] classes wrap the regular collections so that you don't have to think about synchronizing access.

Edit: ConcurrentLinkedList isn't actually just a wrapper, but rather a better concurrent implementation. Either way, you don't have to worry about synchronization.

H2 database error: Database may be already in use: "Locked by another process"

H2 is still running (I can guarantee it). You need to use a TCP connection for multiple users such as ->

<property name="javax.persistence.jdbc.url" value="jdbc:h2:tcp://localhost/C:\Database\Data\production;"/>

OR

DriverManager.getConnection("jdbc:h2:tcp://localhost/server~/dbname","username","password");

It also means you need to start the server in TCP mode. Honesetly, it is pretty straight forward in the documentation.

Force kill the process (javaw.exe for Windows), and make sure that any application that might have started it is shut down. You have an active lock.

Error: request entity too large

After ?o many tries I got my solution

I have commented this line

app.use(bodyParser.json());

and I put

app.use(bodyParser.json({limit: '50mb'}))

Then it works

How do I add multiple conditions to "ng-disabled"?

You can try something like this.

<button class="button" ng-disabled="(!data.var1 && !data.var2) ? false : true">
</button>

Its working fine for me.

How to determine the installed webpack version

Put webpack -v into your package.json:

{
  "name": "js",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "build": "webpack -v",
    "dev": "webpack --watch"
  }
}

Then enter in the console:

npm run build

Expected output should look like:

> npm run build

> [email protected] build /home/user/repositories/myproject/js
> webpack -v

4.42.0

How to prevent browser to invoke basic auth popup and handle 401 error using Jquery?

As others have pointed out, the only way to change the browser's behavior is to make sure the response either does not contain a 401 status code or if it does, not include the WWW-Authenticate: Basic header. Since changing the status code is not very semantic and undesirable, a good approach is to remove the WWW-Authenticate header. If you can't or don't want to modify your web server application, you can always serve or proxy it through Apache (if you are not using Apache already).

Here is a configuration for Apache to rewrite the response to remove the WWW-Authenticate header IFF the request contains contains the header X-Requested-With: XMLHttpRequest (which is set by default by major Javascript frameworks such as JQuery/AngularJS, etc...) AND the response contains the header WWW-Authenticate: Basic.

Tested on Apache 2.4 (not sure if it works with 2.2). This relies on the mod_headers module being installed. (On Debian/Ubuntu, sudo a2enmod headers and restart Apache)

    <Location />
            # Make sure that if it is an XHR request,
            # we don't send back basic authentication header.
            # This is to prevent the browser from displaying a basic auth login dialog.
            Header unset WWW-Authenticate "expr=req('X-Requested-With') == 'XMLHttpRequest' && resp('WWW-Authenticate') =~ /^Basic/"
    </Location>   

reading a line from ifstream into a string variable

Use the std::getline() from <string>.

 istream & getline(istream & is,std::string& str)

So, for your case it would be:

std::getline(read,x);

How to check all versions of python installed on osx and centos

Here is a cleaner way to show them (technically without symbolic links):

ls -1 /usr/bin/python* | grep '[2-3].[0-9]$'

Where grep filters the output of ls that that has that numeric pattern at the end ($).

Or using find:

find /usr/bin/python* ! -type l

Which shows all the different (!) of symbolic link type (-type l).

How to quickly and conveniently disable all console.log statements in my code?

This a hybrid of answers from SolutionYogi and Chris S. It maintains the console.log line numbers and file name. Example jsFiddle.

// Avoid global functions via a self calling anonymous one (uses jQuery)
(function(MYAPP, $, undefined) {
    // Prevent errors in browsers without console.log
    if (!window.console) window.console = {};
    if (!window.console.log) window.console.log = function(){};

    //Private var
    var console_log = console.log;  

    //Public methods
    MYAPP.enableLog = function enableLogger() { console.log = console_log; };   
    MYAPP.disableLog = function disableLogger() { console.log = function() {}; };

}(window.MYAPP = window.MYAPP || {}, jQuery));


// Example Usage:
$(function() {    
    MYAPP.disableLog();    
    console.log('this should not show');

    MYAPP.enableLog();
    console.log('This will show');
});

How to increase Bootstrap Modal Width?

I suppose this happens due to the max-width of a modal being set to 500px and max-width of modal-lg is 800px I suppose setting it to auto will make your modal responsive

How to check if a network port is open on linux?

If you only care about the local machine, you can rely on the psutil package. You can either:

  1. Check all ports used by a specific pid:

    proc = psutil.Process(pid)
    print proc.connections()
    
  2. Check all ports used on the local machine:

    print psutil.net_connections()
    

It works on Windows too.

https://github.com/giampaolo/psutil

Immutable vs Mutable types

A mutable object has to have at least a method able to mutate the object. For example, the list object has the append method, which will actually mutate the object:

>>> a = [1,2,3]
>>> a.append('hello') # `a` has mutated but is still the same object
>>> a
[1, 2, 3, 'hello']

but the class float has no method to mutate a float object. You can do:

>>> b = 5.0 
>>> b = b + 0.1
>>> b
5.1

but the = operand is not a method. It just make a bind between the variable and whatever is to the right of it, nothing else. It never changes or creates objects. It is a declaration of what the variable will point to, since now on.

When you do b = b + 0.1 the = operand binds the variable to a new float, wich is created with te result of 5 + 0.1.

When you assign a variable to an existent object, mutable or not, the = operand binds the variable to that object. And nothing more happens

In either case, the = just make the bind. It doesn't change or create objects.

When you do a = 1.0, the = operand is not wich create the float, but the 1.0 part of the line. Actually when you write 1.0 it is a shorthand for float(1.0) a constructor call returning a float object. (That is the reason why if you type 1.0 and press enter you get the "echo" 1.0 printed below; that is the return value of the constructor function you called)

Now, if b is a float and you assign a = b, both variables are pointing to the same object, but actually the variables can't comunicate betweem themselves, because the object is inmutable, and if you do b += 1, now b point to a new object, and a is still pointing to the oldone and cannot know what b is pointing to.

but if c is, let's say, a list, and you assign a = c, now a and c can "comunicate", because list is mutable, and if you do c.append('msg'), then just checking a you get the message.

(By the way, every object has an unique id number asociated to, wich you can get with id(x). So you can check if an object is the same or not checking if its unique id has changed.)

How to make <input type="file"/> accept only these types?

As stated on w3schools:

audio/* - All sound files are accepted

video/* - All video files are accepted

image/* - All image files are accepted

MIME_type - A valid MIME type, with no parameters. Look at IANA MIME types for a complete list of standard MIME types

How to add row in JTable?

Use:

DefaultTableModel model = new DefaultTableModel(); 
JTable table = new JTable(model); 

// Create a couple of columns 
model.addColumn("Col1"); 
model.addColumn("Col2"); 

// Append a row 
model.addRow(new Object[]{"v1", "v2"});

Object does not support item assignment error

Another way would be adding __getitem__, __setitem__ function

def __getitem__(self, key):
    return getattr(self, key)

You can use self[key] to access now.

Find the division remainder of a number

We can solve this by using modulus operator (%)

26 % 7 = 5;

but 26 / 7 = 3 because it will give quotient but % operator will give remainder.

Find IP address of directly connected device

You can also get information from directly connected networking devices, such as network switches with LDWin, a portable and free Windows program published on github:

http://www.sysadmit.com/2016/11/windows-como-saber-la-ip-del-switch-al-que-estoy-conectado.html

LDWin supports the following methods of link discovery: CDP (Cisco Discovery Protocol) and LLDP (Link Layer Discovery Protocol).

You can obtain the model, management IP, VLAN identifier, Port identifier, firmware version, etc.

Error in <my code> : object of type 'closure' is not subsettable

In case of this similar error Warning: Error in $: object of type 'closure' is not subsettable [No stack trace available]

Just add corresponding package name using :: e.g.

instead of tags(....)

write shiny::tags(....)

Eclipse says: “Workspace in use or cannot be created, chose a different one.” How do I unlock a workspace?

The answer @Boris gave is correct 99% of the time, however it can also happen if you open the workspace in an older version of Eclipse. A workspace imported into/created with Juno will throw this error when opened in Galileo.

Style disabled button with CSS

input[type="button"]:disabled,
input[type="submit"]:disabled,
input[type="reset"]:disabled,
{
  //  apply css here what u like it will definitely work...
}

Convert all strings in a list to int

Here is a simple solution with explanation for your query.

 a=['1','2','3','4','5'] #The integer represented as a string in this list
 b=[] #Fresh list
 for i in a: #Declaring variable (i) as an item in the list (a).
     b.append(int(i)) #Look below for explanation
 print(b)

Here, append() is used to add items ( i.e integer version of string (i) in this program ) to the end of the list (b).

Note: int() is a function that helps to convert an integer in the form of string, back to its integer form.

Output console:

[1, 2, 3, 4, 5]

So, we can convert the string items in the list to an integer only if the given string is entirely composed of numbers or else an error will be generated.

Switching a DIV background image with jQuery

Here is how I do it:

CSS

#button{
   background-image: url("initial_image.png");
}

#button.toggled{
  background-image:url("toggled_image.png");
}

JS

$('#button').click(function(){
  $('#my_content').toggle();
  $(this).toggleClass('toggled');
});

How can I test a PDF document if it is PDF/A compliant?

Do you have Adobe PDFL or Acrobat Professional? You can use preflight operation if you do.

Comparing two dictionaries and checking how many (key, value) pairs are equal

The easiest way (and one of the more robust at that) to do a deep comparison of two dictionaries is to serialize them in JSON format, sorting the keys, and compare the string results:

import json
if json.dumps(x, sort_keys=True) == json.dumps(y, sort_keys=True):
   ... Do something ...

Extract string between two strings in java

Your regex looks correct, but you're splitting with it instead of matching with it. You want something like this:

// Untested code
Matcher matcher = Pattern.compile("<%=(.*?)%>").matcher(str);
while (matcher.find()) {
    System.out.println(matcher.group());
}

How to randomly pick an element from an array

Since you have java 8, another solution is to use Stream API.

new Random().ints(1, 500).limit(500).forEach(p -> System.out.println(list[p]));

Where 1 is the lowest int generated (inclusive) and 500 is the highest (exclusive). limit means that your stream will have a length of 500.

 int[] list = new int[] {1,2,3,4,5,6};
 new Random().ints(0, list.length).limit(10).forEach(p -> System.out.println(list[p])); 

Random is from java.util package.

How do you do the "therefore" (?) symbol on a Mac or in Textmate?

From System Preferences, turn on the "Show Keyboard & Character Viewer in menu bar" setting.

Then, the "Character Viewer" menu will pop up a tool that will let you search for any unicode character (by name) and insert it ? you're all set.

How to copy an object in Objective-C

This is probably unpopular way. But here how I do it:

object1 = // object to copy

YourClass *object2 = [[YourClass alloc] init];
object2.property1 = object1.property1;
object2.property2 = object1.property2;
..
etc.

Quite simple and straight forward. :P

replacing NA's with 0's in R dataframe

dataset <- matrix(sample(c(NA, 1:5), 25, replace = TRUE), 5);
data <- as.data.frame(dataset)
[,1] [,2] [,3] [,4] [,5] 
[1,]    2    3    5    5    4
[2,]    2    4    3    2    4
[3,]    2   NA   NA   NA    2
[4,]    2    3   NA    5    5
[5,]    2    3    2    2    3
data[is.na(data)] <- 0

What do &lt; and &gt; stand for?

Others have noted the correct answer, but have not clearly explained the all-important reason:

  • why do we need this?

What do < and > stand for?

  • &lt; stands for the < sign. Just remember: lt == less than
  • &gt; stands for the > Just remember: gt == greater than

Why can’t we simply use the < and > characters in HTML?

  • This is because the > and < characters are ‘reserved’ characters in HTML.
  • HTML is a mark up language: The < and > are used to denote the starting and ending of different elements: e.g. <h1> and not for the displaying of the greater than or less than symbols. But what if you wanted to actually display those symbols? You would simply use &lt; and &gt; and the browser will know exactly how to display it.

Twitter Bootstrap Tabs: Go to Specific Tab on Page Reload or Hyperlink

Combining peices from other answers, here is a solution that can open many levels of nested tabs:

// opens all tabs down to the specified tab
var hash = location.hash.split('?')[0];
if(hash) {
  var $link = $('[href=' + hash + ']');
  var parents = $link.parents('.tab-pane').get();
  $(parents.reverse()).each(function() {
    $('[href=#' + this.id + ']').tab('show') ;
  });
  $link.tab('show');
}

ASP.NET MVC 404 Error Handling

In IIS, you can specify a redirect to "certain" page based on error code. In you example, you can configure 404 - > Your customized 404 error page.

Copying formula to the next row when inserting a new row

One other key thing that I found regarding copying rows within a table, is that the worksheet you are working on needs to be activated. If you have a workbook with multiple sheets, you need to save the sheet you called the macro from, and then activate the sheet with the table. Once you are done, you can re-activate the original sheet.

You can use Application.ScreenUpdating = False to make sure the user doesn't see that you are switching worksheets within your macro.

If you don't have the worksheet activated, the copy doesn't seem to work properly, i.e. some stuff seem to work, and other stuff doesn't ??

Homebrew install specific version of formula?

On the newest version of homebrew (0.9.5 as of this writing) there will be a specific recipe for the version of the homebrew keg you want to install. Example:

$ brew search mongodb
mongodb    mongodb24  mongodb26

Then just do brew install mongodb26 like normal.

In the case that you had already installed the latest version, make sure to unlink the latest version and link the desired version: brew unlink mongodb && brew link mongodb26.

Illegal pattern character 'T' when parsing a date string to java.util.Date

Update for Java 8 and higher

You can now simply do Instant.parse("2015-04-28T14:23:38.521Z") and get the correct thing now, especially since you should be using Instant instead of the broken java.util.Date with the most recent versions of Java.

You should be using DateTimeFormatter instead of SimpleDateFormatter as well.

Original Answer:

The explanation below is still valid as as what the format represents. But it was written before Java 8 was ubiquitous so it uses the old classes that you should not be using if you are using Java 8 or higher.

This works with the input with the trailing Z as demonstrated:

In the pattern the T is escaped with ' on either side.

The pattern for the Z at the end is actually XXX as documented in the JavaDoc for SimpleDateFormat, it is just not very clear on actually how to use it since Z is the marker for the old TimeZone information as well.

Q2597083.java

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.TimeZone;

public class Q2597083
{
    /**
     * All Dates are normalized to UTC, it is up the client code to convert to the appropriate TimeZone.
     */
    public static final TimeZone UTC;

    /**
     * @see <a href="http://en.wikipedia.org/wiki/ISO_8601#Combined_date_and_time_representations">Combined Date and Time Representations</a>
     */
    public static final String ISO_8601_24H_FULL_FORMAT = "yyyy-MM-dd'T'HH:mm:ss.SSSXXX";

    /**
     * 0001-01-01T00:00:00.000Z
     */
    public static final Date BEGINNING_OF_TIME;

    /**
     * 292278994-08-17T07:12:55.807Z
     */
    public static final Date END_OF_TIME;

    static
    {
        UTC = TimeZone.getTimeZone("UTC");
        TimeZone.setDefault(UTC);
        final Calendar c = new GregorianCalendar(UTC);
        c.set(1, 0, 1, 0, 0, 0);
        c.set(Calendar.MILLISECOND, 0);
        BEGINNING_OF_TIME = c.getTime();
        c.setTime(new Date(Long.MAX_VALUE));
        END_OF_TIME = c.getTime();
    }

    public static void main(String[] args) throws Exception
    {

        final SimpleDateFormat sdf = new SimpleDateFormat(ISO_8601_24H_FULL_FORMAT);
        sdf.setTimeZone(UTC);
        System.out.println("sdf.format(BEGINNING_OF_TIME) = " + sdf.format(BEGINNING_OF_TIME));
        System.out.println("sdf.format(END_OF_TIME) = " + sdf.format(END_OF_TIME));
        System.out.println("sdf.format(new Date()) = " + sdf.format(new Date()));
        System.out.println("sdf.parse(\"2015-04-28T14:23:38.521Z\") = " + sdf.parse("2015-04-28T14:23:38.521Z"));
        System.out.println("sdf.parse(\"0001-01-01T00:00:00.000Z\") = " + sdf.parse("0001-01-01T00:00:00.000Z"));
        System.out.println("sdf.parse(\"292278994-08-17T07:12:55.807Z\") = " + sdf.parse("292278994-08-17T07:12:55.807Z"));
    }
}

Produces the following output:

sdf.format(BEGINNING_OF_TIME) = 0001-01-01T00:00:00.000Z
sdf.format(END_OF_TIME) = 292278994-08-17T07:12:55.807Z
sdf.format(new Date()) = 2015-04-28T14:38:25.956Z
sdf.parse("2015-04-28T14:23:38.521Z") = Tue Apr 28 14:23:38 UTC 2015
sdf.parse("0001-01-01T00:00:00.000Z") = Sat Jan 01 00:00:00 UTC 1
sdf.parse("292278994-08-17T07:12:55.807Z") = Sun Aug 17 07:12:55 UTC 292278994

Python regex to match dates

Instead of using regex, it is generally better to parse the string as a datetime.datetime object:

In [140]: datetime.datetime.strptime("11/12/98","%m/%d/%y")
Out[140]: datetime.datetime(1998, 11, 12, 0, 0)

In [141]: datetime.datetime.strptime("11/12/98","%d/%m/%y")
Out[141]: datetime.datetime(1998, 12, 11, 0, 0)

You could then access the day, month, and year (and hour, minutes, and seconds) as attributes of the datetime.datetime object:

In [143]: date.year
Out[143]: 1998

In [144]: date.month
Out[144]: 11

In [145]: date.day
Out[145]: 12

To test if a sequence of digits separated by forward-slashes represents a valid date, you could use a try..except block. Invalid dates will raise a ValueError:

In [159]: try:
   .....:     datetime.datetime.strptime("99/99/99","%m/%d/%y")
   .....: except ValueError as err:
   .....:     print(err)
   .....:     
   .....:     
time data '99/99/99' does not match format '%m/%d/%y'

If you need to search a longer string for a date, you could use regex to search for digits separated by forward-slashes:

In [146]: import re
In [152]: match = re.search(r'(\d+/\d+/\d+)','The date is 11/12/98')

In [153]: match.group(1)
Out[153]: '11/12/98'

Of course, invalid dates will also match:

In [154]: match = re.search(r'(\d+/\d+/\d+)','The date is 99/99/99')

In [155]: match.group(1)
Out[155]: '99/99/99'

To check that match.group(1) returns a valid date string, you could then parsing it using datetime.datetime.strptime as shown above.

data.frame Group By column

Using dplyr:

require(dplyr)    
df <- data.frame(A = c(1, 1, 2, 3, 3), B = c(2, 3, 3, 5, 6))
df %>% group_by(A) %>% summarise(B = sum(B))

## Source: local data frame [3 x 2]
## 
##   A  B
## 1 1  5
## 2 2  3
## 3 3 11

With sqldf:

library(sqldf)
sqldf('SELECT A, SUM(B) AS B FROM df GROUP BY A')

How to fix Invalid byte 1 of 1-byte UTF-8 sequence

How to fix this issue ?

Read the data using the correct character encoding. The error message means that you are trying to read the data as UTF-8 (either deliberately or because that is the default encoding for an XML file that does not specify <?xml version="1.0" encoding="somethingelse"?>) but it is actually in a different encoding such as ISO-8859-1 or Windows-1252.

To be able to advise on how you should do this I'd have to see the code you're currently using to read the XML.

How can I have grep not print out 'No such file or directory' errors?

I usually don't let grep do the recursion itself. There are usually a few directories you want to skip (.git, .svn...)

You can do clever aliases with stances like that one:

find . \( -name .svn -o -name .git \) -prune -o -type f -exec grep -Hn pattern {} \;

It may seem overkill at first glance, but when you need to filter out some patterns it is quite handy.

make a header full screen (width) css

Set the max-width:1250px; that is currently on your body on your #container. This way your header will be 100% of his parent (body) :)

How do I run .sh or .bat files from Terminal?

Based on IsmailS' comment the command which worked for me on OSX was:

sudo sh ./startup.sh

Where can I find the Java SDK in Linux after installing it?

Use find to located it. It should be under /usr somewhere:

find /usr -name java

When running the command, if there are too many "Permission denied" message obfuscating the actual found results then, simply redirect stderr to /dev/null

find /usr -name java 2> /dev/null

Python unicode equal comparison failed

You may use the == operator to compare unicode objects for equality.

>>> s1 = u'Hello'
>>> s2 = unicode("Hello")
>>> type(s1), type(s2)
(<type 'unicode'>, <type 'unicode'>)
>>> s1==s2
True
>>> 
>>> s3='Hello'.decode('utf-8')
>>> type(s3)
<type 'unicode'>
>>> s1==s3
True
>>> 

But, your error message indicates that you aren't comparing unicode objects. You are probably comparing a unicode object to a str object, like so:

>>> u'Hello' == 'Hello'
True
>>> u'Hello' == '\x81\x01'
__main__:1: UnicodeWarning: Unicode equal comparison failed to convert both arguments to Unicode - interpreting them as being unequal
False

See how I have attempted to compare a unicode object against a string which does not represent a valid UTF8 encoding.

Your program, I suppose, is comparing unicode objects with str objects, and the contents of a str object is not a valid UTF8 encoding. This seems likely the result of you (the programmer) not knowing which variable holds unicide, which variable holds UTF8 and which variable holds the bytes read in from a file.

I recommend http://nedbatchelder.com/text/unipain.html, especially the advice to create a "Unicode Sandwich."

Make index.html default, but allow index.php to be visited if typed in

By default, the DirectoryIndex is set to:

DirectoryIndex index.html index.htm default.htm index.php index.php3 index.phtml index.php5 index.shtml mwindex.phtml

Apache will look for each of the above files, in order, and serve the first one it finds when a visitor requests just a directory. If the webserver finds no files in the current directory that match names in the DirectoryIndex directive, then a directory listing will be displayed to the browser, showing all files in the current directory.

The order should be DirectoryIndex index.html index.php // default is index.html

Reference: Here.

Get age from Birthdate

JsFiddle

You can calculate with Dates.

var birthdate = new Date("1990/1/1");
var cur = new Date();
var diff = cur-birthdate; // This is the difference in milliseconds
var age = Math.floor(diff/31557600000); // Divide by 1000*60*60*24*365.25

How to concatenate two IEnumerable<T> into a new IEnumerable<T>?

The Concat method will return an object which implements IEnumerable<T> by returning an object (call it Cat) whose enumerator will attempt to use the two passed-in enumerable items (call them A and B) in sequence. If the passed-in enumerables represent sequences which will not change during the lifetime of Cat, and which can be read from without side-effects, then Cat may be used directly. Otherwise, it may be a good idea to call ToList() on Cat and use the resulting List<T> (which will represent a snapshot of the contents of A and B).

Some enumerables take a snapshot when enumeration begins, and will return data from that snapshot if the collection is modified during enumeration. If B is such an enumerable, then any change to B which occurs before Cat has reached the end of A will show up in Cat's enumeration, but changes which occur after that will not. Such semantics may likely be confusing; taking a snapshot of Cat can avoid such issues.

How to call a web service from jQuery

Incase people have a problem like myself following Marwan Aouida's answer ... the code has a small typo. Instead of "success" it says "sucess" change the spelling and the code works fine.

"No resource identifier found for attribute 'showAsAction' in package 'android'"

Add compat library compilation to the build.gradle file:

compile 'com.android.support:appcompat-v7:19.+'

Post a json object to mvc controller with jquery and ajax

What am I doing incorrectly?

You have to convert html to javascript object, and then as a second step to json throug JSON.Stringify.

How can I receive a json object in the controller?

View:

<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
<script src="https://raw.githubusercontent.com/marioizquierdo/jquery.serializeJSON/master/jquery.serializejson.js"></script>

var obj = $("#form1").serializeJSON({ useIntKeysAsArrayIndex: true });
$.post("http://localhost:52161/Default/PostRawJson/", { json: JSON.stringify(obj) });

<form id="form1" method="post">
<input name="OrderDate" type="text" /><br />
<input name="Item[0][Id]" type="text" /><br />
<input name="Item[1][Id]" type="text" /><br />
<button id="btn" onclick="btnClick()">Button</button>
</form>

Controller:

public void PostRawJson(string json)
{
    var order = System.Web.Helpers.Json.Decode(json);
    var orderDate = order.OrderDate;
    var secondOrderId = order.Item[1].Id;
}

#1130 - Host ‘localhost’ is not allowed to connect to this MySQL server

Use the IP instead:

DROP USER 'root'@'127.0.0.1'; GRANT ALL PRIVILEGES ON . TO 'root'@'%';

For more possibilities, see this link.

To create the root user, seeing as MySQL is local & all, execute the following from the command line (Start > Run > "cmd" without quotes):

mysqladmin -u root password 'mynewpassword'

Documentation, and Lost root access in MySQL.

Partly cherry-picking a commit with Git

I know I'm answering an old question, but it looks like there's a new way to do this with interactively checking out:

git checkout -p bc66559

Credit to Can I interactively pick hunks from another git commit?

form action with javascript

It has been almost 8 years since the question was asked, but I will venture an answer not previously given. The OP said this doesn't work:

action="javascript:simpleCart.checkout()"

And the OP said that this code continued to fail despite trying all the good advice he got. So I will venture a guess. The action is calling checkout() as a static method of the simpleCart class; but maybe checkout() is actually an instance member, and not static. It depends how he defined checkout().

By the way, simpleCart is presumably a class name, and by convention class names have an initial capital letter, so let's use that convention, here. Let's use the name SimpleCart.

Here is some sample code that illustrates defining checkout() as an instance member. This was the correct way to do it, prior to ECMA-6:

function SimpleCart() {
    ...
}
SimpleCart.prototype.checkout = function() { ... };

Many people have used a different technique, as illustrated in the following. This was popular, and it worked, but I advocate against it, because instances are supposed to be defined on the prototype, just once, while the following technique defines the member on this and does so repeatedly, with every instantiation.

function SimpleCart() {
    ...
    this.checkout = function() { ... };
}

And here is an instance definition in ECMA-6, using an official class:

class SimpleCart {
    constructor() { ... }
    ...
    checkout()    { ... }
}

Compare to a static definition in ECMA-6. The difference is just one word:

class SimpleCart {
    constructor() { ... }
    ...
    static checkout()    { ... }
}

And here is a static definition the old way, pre-ECMA-6. Note that the checkout() method is defined outside of the function. It is a member of the function object, not the prototype object, and that's what makes it static.

function SimpleCart() {
    ...
}
SimpleCart.checkout = function() { ... };

Because of the way it is defined, a static function will have a different concept of what the keyword this references. Note that instance member functions are called using the this keyword:

this.checkout();

Static member functions are called using the class name:

SimpleCart.checkout();

The problem is that the OP wants to put the call into HTML, where it will be in global scope. He can't use the keyword this because this would refer to the global scope (which is window).

action="javascript:this.checkout()" // not as intended
action="javascript:window.checkout()" // same thing

There is no easy way to use an instance member function in HTML. You can do stuff in combination with JavaScript, creating a registry in the static scope of the Class, and then calling a surrogate static method, while passing an argument to that surrogate that gives the index into the registry of your instance, and then having the surrogate call the actual instance member function. Something like this:

// In Javascript:
SimpleCart.registry[1234] = new SimpleCart();

// In HTML
action="javascript:SimpleCart.checkout(1234);"

// In Javascript
SimpleCart.checkout = function(myIndex) {
    var myThis = SimpleCart.registry[myIndex];
    myThis.checkout();
}

You could also store the index as an attribute on the element.

But usually it is easier to just do nothing in HTML and do everything in JavaScript with .addEventListener() and use the .bind() capability.

How to read a file without newlines?

def getText():
    file=open("ex1.txt","r");

    names=file.read().split("\n");
    for x,word in enumerate(names):
        if(len(word)>=20):
            return 0;
            print "length of ",word,"is over 20"
            break;
        if(x==20):
            return 0;
            break;
    else:
        return names;


def show(names):
    for word in names:
        len_set=len(set(word))
        print word," ",len_set


for i in range(1):

    names=getText();
    if(names!=0):
        show(names);
    else:
        break;

NOT IN vs NOT EXISTS

I have a table which has about 120,000 records and need to select only those which does not exist (matched with a varchar column) in four other tables with number of rows approx 1500, 4000, 40000, 200. All the involved tables have unique index on the concerned Varchar column.

NOT IN took about 10 mins, NOT EXISTS took 4 secs.

I have a recursive query which might had some untuned section which might have contributed to the 10 mins, but the other option taking 4 secs explains, atleast to me that NOT EXISTS is far better or at least that IN and EXISTS are not exactly the same and always worth a check before going ahead with code.

What range of values can integer types store in C++

Other folks here will post links to data_sizes and precisions etc.
I'm going to tell you how to figure it out yourself.
Write a small app that will do the following.

unsigned int ui;
std::cout <<  sizeof(ui));

this will (depending on compiler and archicture) print 2, 4 or 8, saying 2 bytes long, 4 bytes long etc.

Lets assume it's 4.

You now want the maximum value 4 bytes can store, the max value for one byte is (in hex)0xFF. The max value of four bytes is 0x followed by 8 f's (one pair of f's for each byte, the 0x tells the compiler that the following string is a hex number). Now change your program to assign that value and print the result

unsigned int ui = 0xFFFFFFFF;
std::cout <<  ui;

Thats the max value an unsigned int can hold, shown in base 10 representation.

Now do that for long's, shorts and any other INTEGER value you're curious about.

NB: This approach will not work for floating point numbers (i.e. double or float).

Hope this helps

How can I set the max-width of a table cell using percentages?

According to the definition of max-width in the CSS 2.1 spec, “the effect of 'min-width' and 'max-width' on tables, inline tables, table cells, table columns, and column groups is undefined.” So you cannot directly set max-width on a td element.

If you just want the second column to take up at most 67%, then you can set the width (which is in effect minimum width, for table cells) to 33%, e.g. in the example case

td:first-child { width: 33% ;}

Setting that for both columns won’t work that well, since it tends to make browsers give the columns equal width.

Order by multiple columns with Doctrine

You have to add the order direction right after the column name:

$qb->orderBy('column1 ASC, column2 DESC');

As you have noted, multiple calls to orderBy do not stack, but you can make multiple calls to addOrderBy:

$qb->addOrderBy('column1', 'ASC')
   ->addOrderBy('column2', 'DESC');

How to use BOOLEAN type in SELECT statement

PL/SQL is complaining that TRUE is not a valid identifier, or variable. Set up a local variable, set it to TRUE, and pass it into the get_something function.

Android Studio 3.0 Execution failed for task: unable to merge dex

I tried many solutions as mentioned above including the multiDexEnabled true but none of that worked for me.

Here is the solution which worked for me - copy this code in app\build.gradle file

configurations.all {
    resolutionStrategy.eachDependency { DependencyResolveDetails details ->
        def requested = details.requested
        if (requested.group == 'com.android.support' && requested.name != 'multidex') {
            details.useVersion "${rootProject.ext.supportLibVersion}"
        }
    }
}

Make sure to run gradlew clean before running the code

Error when using scp command "bash: scp: command not found"

Issue is with remote server, can you login to the remote server and check if "scp" works

probable causes: - scp is not in path - openssh client not installed correctly

for more details http://www.linuxquestions.org/questions/linux-newbie-8/bash-scp-command-not-found-920513/

Android Studio - local path doesn't exist

like wrote here:

I just ran into this problem, even without transferring from Eclipse, and was frustrated because I kept showing no compile or packageDebug errors. Somehow it all fixes itself if you clean and THEN run packageDebug. Don't worry about the deprecated method statement - it seems to be a generic notice to developers.

Open up a commandline, and in your project's root directory, run:

./gradlew clean packageDebug

Obviously, if either of these steps shows errors, you should fix those...But when they both succeed you should now be able to find the apk when you navigate the local path -- and even better, your program should install/run on the device/emulator!

Map implementation with duplicate keys

You could simply pass an array of values for the value in a regular HashMap, thus simulating duplicate keys, and it would be up to you to decide what data to use.

You may also just use a MultiMap, although I do not like the idea of duplicate keys myself.

Send auto email programmatically

Sending email programmatically with Kotlin.

  • simple email sending, not all the other features (like attachments).
  • TLS is always on
  • Only 1 gradle email dependency needed also.

I also found this list of email POP services really helpful:

https://support.office.com/en-gb/article/pop-and-imap-email-settings-for-outlook-8361e398-8af4-4e97-b147-6c6c4ac95353

How to use:

    val auth = EmailService.UserPassAuthenticator("yourUser", "yourPass")
    val to = listOf(InternetAddress("[email protected]"))
    val from = InternetAddress("[email protected]")
    val email = EmailService.Email(auth, to, from, "Test Subject", "Hello Body World")
    val emailService = EmailService("yourSmtpServer", 587)

    GlobalScope.launch { // or however you do background threads
        emailService.send(email)
    }

The code:

import java.util.*
import javax.mail.*
import javax.mail.internet.InternetAddress
import javax.mail.internet.MimeBodyPart
import javax.mail.internet.MimeMessage
import javax.mail.internet.MimeMultipart

class EmailService(private var server: String, private var port: Int) {

    data class Email(
        val auth: Authenticator,
        val toList: List<InternetAddress>,
        val from: Address,
        val subject: String,
        val body: String
    )

    class UserPassAuthenticator(private val username: String, private val password: String) : Authenticator() {
        override fun getPasswordAuthentication(): PasswordAuthentication {
            return PasswordAuthentication(username, password)
        }
    }

    fun send(email: Email) {
        val props = Properties()
        props["mail.smtp.auth"] = "true"
        props["mail.user"] = email.from
        props["mail.smtp.host"] = server
        props["mail.smtp.port"] = port
        props["mail.smtp.starttls.enable"] = "true"
        props["mail.smtp.ssl.trust"] = server
        props["mail.mime.charset"] = "UTF-8"
        val msg: Message = MimeMessage(Session.getDefaultInstance(props, email.auth))
        msg.setFrom(email.from)
        msg.sentDate = Calendar.getInstance().time
        msg.setRecipients(Message.RecipientType.TO, email.toList.toTypedArray())
//      msg.setRecipients(Message.RecipientType.CC, email.ccList.toTypedArray())
//      msg.setRecipients(Message.RecipientType.BCC, email.bccList.toTypedArray())
        msg.replyTo = arrayOf(email.from)

        msg.addHeader("X-Mailer", CLIENT_NAME)
        msg.addHeader("Precedence", "bulk")
        msg.subject = email.subject

        msg.setContent(MimeMultipart().apply {
            addBodyPart(MimeBodyPart().apply {
                setText(email.body, "iso-8859-1")
                //setContent(email.htmlBody, "text/html; charset=UTF-8")
            })
        })
        Transport.send(msg)
    }

    companion object {
        const val CLIENT_NAME = "Android StackOverflow programmatic email"
    }
}

Gradle:

dependencies {
    implementation 'com.sun.mail:android-mail:1.6.4'
    implementation "org.jetbrains.kotlinx:kotlinx-coroutines-core:1.3.3"
}

AndroidManifest:

<uses-permission name="android.permission.INTERNET" />

How do I search for an object by its ObjectId in the mongo console?

Not strange at all, people do this all the time. Make sure the collection name is correct (case matters) and that the ObjectId is exact.

Documentation is here

> db.test.insert({x: 1})

> db.test.find()                                               // no criteria
{ "_id" : ObjectId("4ecc05e55dd98a436ddcc47c"), "x" : 1 }      

> db.test.find({"_id" : ObjectId("4ecc05e55dd98a436ddcc47c")}) // explicit
{ "_id" : ObjectId("4ecc05e55dd98a436ddcc47c"), "x" : 1 }

> db.test.find(ObjectId("4ecc05e55dd98a436ddcc47c"))           // shortcut
{ "_id" : ObjectId("4ecc05e55dd98a436ddcc47c"), "x" : 1 }