Programs & Examples On #Multi dimensional scaling

Declaring variables in Excel Cells

The lingo in excel is different, you don't "declare variables", you "name" cells or arrays.

A good overview of how you do that is below: http://office.microsoft.com/en-001/excel-help/define-and-use-names-in-formulas-HA010342417.aspx

How to run a jar file in a linux commandline

Running a from class inside your JAR file load.jar is possible via

java -jar load.jar

When doing so, you have to define the application entry point. Usually this is done by providing a manifest file that contains the Main-Class tag. For documentation and examples have a look at this page. The argument load=2 can be supplied like in a normal Java applications:

java -jar load.jar load=2

Having also the current directory contained in the classpath, required to also make use of the Class-Path tag. See here for more information.

How do I add a newline to a TextView in Android?

One way of doing this is using Html tags::

txtTitlevalue.setText(Html.fromHtml("Line1"+"<br>"+"Line2" + " <br>"+"Line3"));

git switch branch without discarding local changes

You could use --merge/-m git checkout option: git checkout -m <another-branch>

-m --merge

When switching branches, if you have local modifications to one or more files that are different between the current branch and the branch to which you are switching, the command refuses to switch branches in order to preserve your modifications in context. However, with this option, a three-way merge between the current branch, your working tree contents, and the new branch is done, and you will be on the new branch.

Source: https://git-scm.com/docs/git-checkout

Oracle PL/SQL - How to create a simple array variable?

You can also use an oracle defined collection

DECLARE 
  arrayvalues sys.odcivarchar2list;
BEGIN
  arrayvalues := sys.odcivarchar2list('Matt','Joanne','Robert');
  FOR x IN ( SELECT m.column_value m_value
               FROM table(arrayvalues) m )
  LOOP
    dbms_output.put_line (x.m_value||' is a good pal');
  END LOOP;
END;

I would use in-memory array. But with the .COUNT improvement suggested by uziberia:

DECLARE
  TYPE t_people IS TABLE OF varchar2(10) INDEX BY PLS_INTEGER;
  arrayvalues t_people;
BEGIN
  SELECT *
   BULK COLLECT INTO arrayvalues
   FROM (select 'Matt' m_value from dual union all
         select 'Joanne'       from dual union all
         select 'Robert'       from dual
    )
  ;
  --
  FOR i IN 1 .. arrayvalues.COUNT
  LOOP
    dbms_output.put_line(arrayvalues(i)||' is my friend');
  END LOOP;
END;

Another solution would be to use a Hashmap like @Jchomel did here.

NB:

With Oracle 12c you can even query arrays directly now!

Convert txt to csv python script

This is how I do it:

 with open(txtfile, 'r') as infile, open(csvfile, 'w') as outfile:
        stripped = (line.strip() for line in infile)
        lines = (line.split(",") for line in stripped if line)
        writer = csv.writer(outfile)
        writer.writerows(lines)

Hope it helps!

Select All as default value for Multivalue parameter

Using dataset with default values is one way, but you must use query for Available values and for Default Values, if values are hard coded in Available values tab, then you must define default values as expressions. Pictures should explain everything

Create Parameter (if not automaticly created)

Create Parameter

Define values - wrong way example

Define values - wrong way

Define values - correct way example

Define values - correct way

Set default values - you must define all default values reflecting available values to make "Select All" by default, if you won't define all only those defined will be selected by default.

Set default values

The Result

The result

One picture for Data type: Int

One picture for Data type Int

How to create a printable Twitter-Bootstrap page

Bootstrap 3.2 update: (current release)

Current stable Bootstrap version is 3.2.0.
With version 3.2 visible-print deprecated, so you should use like this:

Class                        Browser    Print
 -------------------------------------------------
.visible-print-block         Hidden        Visible (as block)
.visible-print-inline        Hidden        Visible (as inline)
.visible-print-inline-block  Hidden        Visible (as inline-block)
.hidden-print                Visible       Hidden

Bootstrap 3 update:

Print classes are now in documents: http://getbootstrap.com/css/#responsive-utilities-print

Similar to the regular responsive classes,
       use these for toggling content for print.

Class            Browser    Print
 ----------------------------------------
.visible-print   Hidden     Visible
.hidden-print    Visible    Hidden

Bootstrap 2.3.1 version:

After adding bootstrap.css file into your HTML,
Find the parts that you don't want to print and add hidden-print class into tags. Because css file includes this:

@media print {
  .visible-print  { display: inherit !important; }
  .hidden-print   { display: none !important; }
}

Reading output of a command into an array in Bash

The other answers will break if output of command contains spaces (which is rather frequent) or glob characters like *, ?, [...].

To get the output of a command in an array, with one line per element, there are essentially 3 ways:

  1. With Bash=4 use mapfile—it's the most efficient:

    mapfile -t my_array < <( my_command )
    
  2. Otherwise, a loop reading the output (slower, but safe):

    my_array=()
    while IFS= read -r line; do
        my_array+=( "$line" )
    done < <( my_command )
    
  3. As suggested by Charles Duffy in the comments (thanks!), the following might perform better than the loop method in number 2:

    IFS=$'\n' read -r -d '' -a my_array < <( my_command && printf '\0' )
    

    Please make sure you use exactly this form, i.e., make sure you have the following:

    • IFS=$'\n' on the same line as the read statement: this will only set the environment variable IFS for the read statement only. So it won't affect the rest of your script at all. The purpose of this variable is to tell read to break the stream at the EOL character \n.
    • -r: this is important. It tells read to not interpret the backslashes as escape sequences.
    • -d '': please note the space between the -d option and its argument ''. If you don't leave a space here, the '' will never be seen, as it will disappear in the quote removal step when Bash parses the statement. This tells read to stop reading at the nil byte. Some people write it as -d $'\0', but it is not really necessary. -d '' is better.
    • -a my_array tells read to populate the array my_array while reading the stream.
    • You must use the printf '\0' statement after my_command, so that read returns 0; it's actually not a big deal if you don't (you'll just get an return code 1, which is okay if you don't use set -e – which you shouldn't anyway), but just bear that in mind. It's cleaner and more semantically correct. Note that this is different from printf '', which doesn't output anything. printf '\0' prints a null byte, needed by read to happily stop reading there (remember the -d '' option?).

If you can, i.e., if you're sure your code will run on Bash=4, use the first method. And you can see it's shorter too.

If you want to use read, the loop (method 2) might have an advantage over method 3 if you want to do some processing as the lines are read: you have direct access to it (via the $line variable in the example I gave), and you also have access to the lines already read (via the array ${my_array[@]} in the example I gave).

Note that mapfile provides a way to have a callback eval'd on each line read, and in fact you can even tell it to only call this callback every N lines read; have a look at help mapfile and the options -C and -c therein. (My opinion about this is that it's a little bit clunky, but can be used sometimes if you only have simple things to do — I don't really understand why this was even implemented in the first place!).


Now I'm going to tell you why the following method:

my_array=( $( my_command) )

is broken when there are spaces:

$ # I'm using this command to test:
$ echo "one two"; echo "three four"
one two
three four
$ # Now I'm going to use the broken method:
$ my_array=( $( echo "one two"; echo "three four" ) )
$ declare -p my_array
declare -a my_array='([0]="one" [1]="two" [2]="three" [3]="four")'
$ # As you can see, the fields are not the lines
$
$ # Now look at the correct method:
$ mapfile -t my_array < <(echo "one two"; echo "three four")
$ declare -p my_array
declare -a my_array='([0]="one two" [1]="three four")'
$ # Good!

Then some people will then recommend using IFS=$'\n' to fix it:

$ IFS=$'\n'
$ my_array=( $(echo "one two"; echo "three four") )
$ declare -p my_array
declare -a my_array='([0]="one two" [1]="three four")'
$ # It works!

But now let's use another command, with globs:

$ echo "* one two"; echo "[three four]"
* one two
[three four]
$ IFS=$'\n'
$ my_array=( $(echo "* one two"; echo "[three four]") )
$ declare -p my_array
declare -a my_array='([0]="* one two" [1]="t")'
$ # What?

That's because I have a file called t in the current directory… and this filename is matched by the glob [three four]… at this point some people would recommend using set -f to disable globbing: but look at it: you have to change IFS and use set -f to be able to fix a broken technique (and you're not even fixing it really)! when doing that we're really fighting against the shell, not working with the shell.

$ mapfile -t my_array < <( echo "* one two"; echo "[three four]")
$ declare -p my_array
declare -a my_array='([0]="* one two" [1]="[three four]")'

here we're working with the shell!

How to compare two columns in Excel and if match, then copy the cell next to it

try this formula in column E:

=IF( AND( ISNUMBER(D2), D2=G2), H2, "")

your error is the number test, ISNUMBER( ISMATCH(D2,G:G,0) )

you do check if ismatch is-a-number, (i.e. isNumber("true") or isNumber("false"), which is not!.

I hope you understand my explanation.

Creating a copy of a database in PostgreSQL

Don't know about pgAdmin, but pgdump gives you a dump of the database in SQL. You only need to create a database by the same name and do

psql mydatabase < my dump

to restore all of the tables and their data and all access privileges.

Find and replace - Add carriage return OR Newline

If you want to avoid the hassle of escaping the special characters in your search and replacement string when using regular expressions, do the following steps:

  1. Search for your original string, and replace it with "UniqueString42", with regular expressions off.
  2. Search for "UniqueString42" and replace it with "UniqueString42\nUniqueString1337", with regular expressions on
  3. Search for "UniqueString42" and replace it with the first line of your replacement (often your original string), with regular expressions off.
  4. Search for "UniqueString42" and replace it with the second line of your replacement, with regular expressions off.

Note that even if you want to manually pich matches for the first search and replace, you can safely use "replace all" for the three last steps.

Example

For example, if you want to replace this:

public IFoo SomeField { get { return this.SomeField; } }

with that:

public IFoo Foo { get { return this.MyFoo; } }
public IBar Bar { get { return this.MyBar; } }

You would do the following substitutions:

  1. public IFoo SomeField { get { return this.SomeField; } } ? XOXOXOXO (regex off).
  2. XOXOXOXO ? XOXOXOXO\nHUHUHUHU (regex on).
  3. XOXOXOXO ? public IFoo Foo { get { return this.MyFoo; } } (regex off).
  4. HUHUHUHU ? public IFoo Bar { get { return this.MyBar; } } (regex off).

How can I change the default Mysql connection timeout when connecting through python?

Do:

con.query('SET GLOBAL connect_timeout=28800')
con.query('SET GLOBAL interactive_timeout=28800')
con.query('SET GLOBAL wait_timeout=28800')

Parameter meaning (taken from MySQL Workbench in Navigator: Instance > Options File > Tab "Networking" > Section "Timeout Settings")

  • connect_timeout: Number of seconds the mysqld server waits for a connect packet before responding with 'Bad handshake'
  • interactive_timeout Number of seconds the server waits for activity on an interactive connection before closing it
  • wait_timeout Number of seconds the server waits for activity on a connection before closing it

BTW: 28800 seconds are 8 hours, so for a 10 hour execution time these values should be actually higher.

comparing strings in vb

I know this has been answered, but in VB.net above 2013 (the lowest I've personally used) you can just compare strings with an = operator. This is the easiest way.

So basically:

If string1 = string2 Then
    'do a thing
End If

How to cin to a vector

If you know the size of the vector you can do it like this:

#include <bits/stdc++.h>
using namespace std;

int main() {
    int n;
    cin >> n;
    vector<int> v(n);
    for (auto &it : v) {
        cin >> it;
    }
}

Index all *except* one item in python

If you are using numpy, the closest, I can think of is using a mask

>>> import numpy as np
>>> arr = np.arange(1,10)
>>> mask = np.ones(arr.shape,dtype=bool)
>>> mask[5]=0
>>> arr[mask]
array([1, 2, 3, 4, 5, 7, 8, 9])

Something similar can be achieved using itertools without numpy

>>> from itertools import compress
>>> arr = range(1,10)
>>> mask = [1]*len(arr)
>>> mask[5]=0
>>> list(compress(arr,mask))
[1, 2, 3, 4, 5, 7, 8, 9]

How Should I Declare Foreign Key Relationships Using Code First Entity Framework (4.1) in MVC3?

You can define foreign key by:

public class Parent
{
   public int Id { get; set; }
   public virtual ICollection<Child> Childs { get; set; }
}

public class Child
{
   public int Id { get; set; }
   // This will be recognized as FK by NavigationPropertyNameForeignKeyDiscoveryConvention
   public int ParentId { get; set; } 
   public virtual Parent Parent { get; set; }
}

Now ParentId is foreign key property and defines required relation between child and existing parent. Saving the child without exsiting parent will throw exception.

If your FK property name doesn't consists of the navigation property name and parent PK name you must either use ForeignKeyAttribute data annotation or fluent API to map the relation

Data annotation:

// The name of related navigation property
[ForeignKey("Parent")]
public int ParentId { get; set; }

Fluent API:

modelBuilder.Entity<Child>()
            .HasRequired(c => c.Parent)
            .WithMany(p => p.Childs)
            .HasForeignKey(c => c.ParentId);

Other types of constraints can be enforced by data annotations and model validation.

Edit:

You will get an exception if you don't set ParentId. It is required property (not nullable). If you just don't set it it will most probably try to send default value to the database. Default value is 0 so if you don't have customer with Id = 0 you will get an exception.

CSS "and" and "or"

To select properties a AND b of a X element:

X[a][b]

To select properties a OR b of a X element:

X[a],X[b]

Append key/value pair to hash with << in Ruby

No, I don't think you can append key/value pairs. The only thing closest that I am aware of is using the store method:

h = {}
h.store("key", "value")

Math.random() versus Random.nextInt(int)

According to this example Random.nextInt(n) has less predictable output then Math.random() * n. According to [sorted array faster than an unsorted array][1] I think we can say Random.nextInt(n) is hard to predict.

usingRandomClass : time:328 milesecond.

usingMathsRandom : time:187 milesecond.

package javaFuction;
import java.util.Random;
public class RandomFuction 
{
    static int array[] = new int[9999];
    static long sum = 0;
    public static void usingMathsRandom() {
        for (int i = 0; i < 9999; i++) {
         array[i] = (int) (Math.random() * 256);
       }

        for (int i = 0; i < 9999; i++) {
            for (int j = 0; j < 9999; j++) {
                if (array[j] >= 128) {
                    sum += array[j];
                }
            }
        }
    }

    public static void usingRandomClass() {
        Random random = new Random();
        for (int i = 0; i < 9999; i++) {
            array[i] = random.nextInt(256);
        }

        for (int i = 0; i < 9999; i++) {
            for (int j = 0; j < 9999; j++) {
                if (array[j] >= 128) {
                    sum += array[j];
                }
            }

        }

    }

    public static void main(String[] args) {
        long start = System.currentTimeMillis();
        usingRandomClass();
        long end = System.currentTimeMillis();
        System.out.println("usingRandomClass " + (end - start));
        start = System.currentTimeMillis();
        usingMathsRandom();
        end = System.currentTimeMillis();
        System.out.println("usingMathsRandom " + (end - start));

    }

}

CSS div 100% height

Set the html tag, too. This way no weird position hacks are required.

html, body {height: 100%}

Using python PIL to turn a RGB image into a pure black and white image

A simple way to do it using python :

Python
import numpy as np
import imageio

image = imageio.imread(r'[image-path]', as_gray=True)

# getting the threshold value
thresholdValue = np.mean(image)

# getting the dimensions of the image
xDim, yDim = image.shape

# turn the image into a black and white image
for i in range(xDim):
    for j in range(yDim):
        if (image[i][j] > thresholdValue):
            image[i][j] = 255
        else:
            image[i][j] = 0

Relative instead of Absolute paths in Excel VBA

Just to clarify what yalestar said, this will give you the relative path:

Workbooks.Open FileName:= ThisWorkbook.Path & "\TRICATEndurance Summary.html"

Target class controller does not exist - Laravel 8

I got the same error when I installed Laravel version 8.27.0: The error is as follow:

The Error that I got:

But when I saw my app/Providers/RouteServiceProvider.php I have namespaces inside my boot method, then I just uncommented this => "protected $namespace = 'App\Http\Controllers';"

Just Uncomment The protected $namespace = 'App\Http\Controllers';';

Now My Project is working:

Project is working safe and sound

What is java pojo class, java bean, normal class?

  1. Normal Class: A Java class

  2. Java Beans:

    • All properties private (use getters/setters)
    • A public no-argument constructor
    • Implements Serializable.
  3. Pojo: Plain Old Java Object is a Java object not bound by any restriction other than those forced by the Java Language Specification. I.e., a POJO should not have to

    • Extend prespecified classes
    • Implement prespecified interface
    • Contain prespecified annotations

How to get date representing the first day of a month?

Very simple piece of code to do this

$date - extract(day from $date) + 1

two ways to do this:

  1. my_date - extract(day from my_date) + 1

  2. '2014/01/21' - extract(day from '2014/01/21') + 1

In Visual Basic how do you create a block comment

In Visual Studio .NET you can do Ctrl + K then C to comment, Crtl + K then U to uncomment a block.

Is there a Python equivalent to Ruby's string interpolation?

Python 3.6 will add literal string interpolation similar to Ruby's string interpolation. Starting with that version of Python (which is scheduled to be released by the end of 2016), you will be able to include expressions in "f-strings", e.g.

name = "Spongebob Squarepants"
print(f"Who lives in a Pineapple under the sea? {name}.")

Prior to 3.6, the closest you can get to this is

name = "Spongebob Squarepants"
print("Who lives in a Pineapple under the sea? %(name)s." % locals())

The % operator can be used for string interpolation in Python. The first operand is the string to be interpolated, the second can have different types including a "mapping", mapping field names to the values to be interpolated. Here I used the dictionary of local variables locals() to map the field name name to its value as a local variable.

The same code using the .format() method of recent Python versions would look like this:

name = "Spongebob Squarepants"
print("Who lives in a Pineapple under the sea? {name!s}.".format(**locals()))

There is also the string.Template class:

tmpl = string.Template("Who lives in a Pineapple under the sea? $name.")
print(tmpl.substitute(name="Spongebob Squarepants"))

Copy and paste content from one file to another file in vi

Here's one way to do it;

  • Start Vim and open file1 which is the file you're working on.
  • :e file2 which will bring up file2, the file you want to copy lines from.
  • locate the lines you want to copy. If it's three lines, you hit 3yy
  • :b1 this will switch to buffer 1, where file1 is
  • figure out where you want to insert the lines you yanked, and hit p

You could have both files viewable too. Split the screen with e.g. Ctrl + w s.

As for cutting, d cuts and places the cut stuff in the yank buffer. dd will "cut" a line.

How to execute 16-bit installer on 64-bit Win7?

16 bit installer will not work on windows 7 it's no longer supported by win 7 the most recent supported version of windows that can run 16 bit installer is vista 32-bit even vista 64-bit doesn't support 16-bit installer.... reference http://support.microsoft.com/kb/946765

Find out who is locking a file on a network share

Close the file e:\gestion\yourfile.dat, open by any user (/a *)

openfiles /disconnect /a * /op "e:\gestion\yourfile.dat"

more in: http://dosprompt.info/commands/openfiles.asp

'Property does not exist on type 'never'

if you write Component as React.FC, and using useState(),

just write like this would be helpful:

const [arr, setArr] = useState<any[]>([])

C++ Loop through Map

You can achieve this like following :

map<string, int>::iterator it;

for (it = symbolTable.begin(); it != symbolTable.end(); it++)
{
    std::cout << it->first    // string (key)
              << ':'
              << it->second   // string's value 
              << std::endl;
}

With C++11 ( and onwards ),

for (auto const& x : symbolTable)
{
    std::cout << x.first  // string (key)
              << ':' 
              << x.second // string's value 
              << std::endl;
}

With C++17 ( and onwards ),

for (auto const& [key, val] : symbolTable)
{
    std::cout << key        // string (key)
              << ':'  
              << val        // string's value
              << std::endl;
}

Fatal error: Call to undefined function: ldap_connect()

  • [Your Drive]:\xampp\php\php.ini: In this file uncomment the following line:

    extension=php_ldap.dll

  • Move the file: libsasl.dll, from [Your Drive]:\xampp\php to [Your Drive]:\xampp\apache\bin Restart Apache. You can now use functions of the LDAP Module!

How do you rename a MongoDB database?

In the case you put all your data in the admin database (you shouldn't), you'll notice db.copyDatabase() won't work because your user requires a lot of privileges you probably don't want to give it. Here is a script to copy the database manually:

use old_db
db.getCollectionNames().forEach(function(collName) {
    db[collName].find().forEach(function(d){
        db.getSiblingDB('new_db')[collName].insert(d); 
    }) 
});

How to call a Parent Class's method from Child Class in Python?

class a(object):
    def my_hello(self):
        print "hello ravi"

class b(a):
    def my_hello(self):
    super(b,self).my_hello()
    print "hi"

obj = b()
obj.my_hello()

Why "no projects found to import"?

One solution to this is to use Maven. From the project root folder do mvn eclipse:clean followed by mvn eclipse:eclipse. This will generate the .project and .classpath files required by eclipse.

In C# check that filename is *possibly* valid (not that it exists)

There are several methods you could use that exist in the System.IO namespace:

Directory.GetLogicalDrives() // Returns an array of strings like "c:\"
Path.GetInvalidFileNameChars() // Returns an array of characters that cannot be used in a file name
Path.GetInvalidPathChars() // Returns an array of characters that cannot be used in a path.

As suggested you could then do this:

bool IsValidFilename(string testName) {
    string regexString = "[" + Regex.Escape(Path.GetInvalidPathChars()) + "]";
    Regex containsABadCharacter = new Regex(regexString);
    if (containsABadCharacter.IsMatch(testName)) {
        return false;
    }

    // Check for drive
    string pathRoot = Path.GetPathRoot(testName);
    if (Directory.GetLogicalDrives().Contains(pathRoot)) {
        // etc
    }

    // other checks for UNC, drive-path format, etc

    return true;
}

Can anyone confirm that phpMyAdmin AllowNoPassword works with MySQL databases?

Others may find, as I did, (working in OS X 10.10.1) that the situation for MAMP PRO (at least in the current release, 3.0.7.3, is different.

All my attempts to apply the remedies suggested here failed. Upon examining the PHP error log I discovered that the index.php that is operating (in /Libary/Application Support/appsolute/MAMP PRO/index.php -- at line 43, is deciding NOT to go to the config.inc.php that is discussed here (at /Applications/MAMP/bin/phpMyAdmin/config.inc.php) but rather to /Library/Application Support/appsolute/MAMP PRO/phpMyAdmin/config.inc.php.

Furthermore, there is no such file there (after a 'successful' install of MAMP PRO), so I'm stuck with the error, and furtherfuthermore, every time I try to put the correct file there, when I restart MAMP PRO, it is not there anymore - something is automatically refreshed to eliminate the config.inc.php I'm putting there. My workaround for now is to do this in MAMP instead of MAMP PRO.

Fitting empirical distribution to theoretical ones with Scipy (Python)?

Distribution Fitting with Sum of Square Error (SSE)

This is an update and modification to Saullo's answer, that uses the full list of the current scipy.stats distributions and returns the distribution with the least SSE between the distribution's histogram and the data's histogram.

Example Fitting

Using the El Niño dataset from statsmodels, the distributions are fit and error is determined. The distribution with the least error is returned.

All Distributions

All Fitted Distributions

Best Fit Distribution

Best Fit Distribution

Example Code

%matplotlib inline

import warnings
import numpy as np
import pandas as pd
import scipy.stats as st
import statsmodels as sm
import matplotlib
import matplotlib.pyplot as plt

matplotlib.rcParams['figure.figsize'] = (16.0, 12.0)
matplotlib.style.use('ggplot')

# Create models from data
def best_fit_distribution(data, bins=200, ax=None):
    """Model data by finding best fit distribution to data"""
    # Get histogram of original data
    y, x = np.histogram(data, bins=bins, density=True)
    x = (x + np.roll(x, -1))[:-1] / 2.0

    # Distributions to check
    DISTRIBUTIONS = [        
        st.alpha,st.anglit,st.arcsine,st.beta,st.betaprime,st.bradford,st.burr,st.cauchy,st.chi,st.chi2,st.cosine,
        st.dgamma,st.dweibull,st.erlang,st.expon,st.exponnorm,st.exponweib,st.exponpow,st.f,st.fatiguelife,st.fisk,
        st.foldcauchy,st.foldnorm,st.frechet_r,st.frechet_l,st.genlogistic,st.genpareto,st.gennorm,st.genexpon,
        st.genextreme,st.gausshyper,st.gamma,st.gengamma,st.genhalflogistic,st.gilbrat,st.gompertz,st.gumbel_r,
        st.gumbel_l,st.halfcauchy,st.halflogistic,st.halfnorm,st.halfgennorm,st.hypsecant,st.invgamma,st.invgauss,
        st.invweibull,st.johnsonsb,st.johnsonsu,st.ksone,st.kstwobign,st.laplace,st.levy,st.levy_l,st.levy_stable,
        st.logistic,st.loggamma,st.loglaplace,st.lognorm,st.lomax,st.maxwell,st.mielke,st.nakagami,st.ncx2,st.ncf,
        st.nct,st.norm,st.pareto,st.pearson3,st.powerlaw,st.powerlognorm,st.powernorm,st.rdist,st.reciprocal,
        st.rayleigh,st.rice,st.recipinvgauss,st.semicircular,st.t,st.triang,st.truncexpon,st.truncnorm,st.tukeylambda,
        st.uniform,st.vonmises,st.vonmises_line,st.wald,st.weibull_min,st.weibull_max,st.wrapcauchy
    ]

    # Best holders
    best_distribution = st.norm
    best_params = (0.0, 1.0)
    best_sse = np.inf

    # Estimate distribution parameters from data
    for distribution in DISTRIBUTIONS:

        # Try to fit the distribution
        try:
            # Ignore warnings from data that can't be fit
            with warnings.catch_warnings():
                warnings.filterwarnings('ignore')

                # fit dist to data
                params = distribution.fit(data)

                # Separate parts of parameters
                arg = params[:-2]
                loc = params[-2]
                scale = params[-1]

                # Calculate fitted PDF and error with fit in distribution
                pdf = distribution.pdf(x, loc=loc, scale=scale, *arg)
                sse = np.sum(np.power(y - pdf, 2.0))

                # if axis pass in add to plot
                try:
                    if ax:
                        pd.Series(pdf, x).plot(ax=ax)
                    end
                except Exception:
                    pass

                # identify if this distribution is better
                if best_sse > sse > 0:
                    best_distribution = distribution
                    best_params = params
                    best_sse = sse

        except Exception:
            pass

    return (best_distribution.name, best_params)

def make_pdf(dist, params, size=10000):
    """Generate distributions's Probability Distribution Function """

    # Separate parts of parameters
    arg = params[:-2]
    loc = params[-2]
    scale = params[-1]

    # Get sane start and end points of distribution
    start = dist.ppf(0.01, *arg, loc=loc, scale=scale) if arg else dist.ppf(0.01, loc=loc, scale=scale)
    end = dist.ppf(0.99, *arg, loc=loc, scale=scale) if arg else dist.ppf(0.99, loc=loc, scale=scale)

    # Build PDF and turn into pandas Series
    x = np.linspace(start, end, size)
    y = dist.pdf(x, loc=loc, scale=scale, *arg)
    pdf = pd.Series(y, x)

    return pdf

# Load data from statsmodels datasets
data = pd.Series(sm.datasets.elnino.load_pandas().data.set_index('YEAR').values.ravel())

# Plot for comparison
plt.figure(figsize=(12,8))
ax = data.plot(kind='hist', bins=50, normed=True, alpha=0.5, color=plt.rcParams['axes.color_cycle'][1])
# Save plot limits
dataYLim = ax.get_ylim()

# Find best fit distribution
best_fit_name, best_fit_params = best_fit_distribution(data, 200, ax)
best_dist = getattr(st, best_fit_name)

# Update plots
ax.set_ylim(dataYLim)
ax.set_title(u'El Niño sea temp.\n All Fitted Distributions')
ax.set_xlabel(u'Temp (°C)')
ax.set_ylabel('Frequency')

# Make PDF with best params 
pdf = make_pdf(best_dist, best_fit_params)

# Display
plt.figure(figsize=(12,8))
ax = pdf.plot(lw=2, label='PDF', legend=True)
data.plot(kind='hist', bins=50, normed=True, alpha=0.5, label='Data', legend=True, ax=ax)

param_names = (best_dist.shapes + ', loc, scale').split(', ') if best_dist.shapes else ['loc', 'scale']
param_str = ', '.join(['{}={:0.2f}'.format(k,v) for k,v in zip(param_names, best_fit_params)])
dist_str = '{}({})'.format(best_fit_name, param_str)

ax.set_title(u'El Niño sea temp. with best fit distribution \n' + dist_str)
ax.set_xlabel(u'Temp. (°C)')
ax.set_ylabel('Frequency')

Are multiple `.gitignore`s frowned on?

There are many scenarios where you want to commit a directory to your Git repo but without the files in it, for example the logs, cache, uploads directories etc.

So what I always do is to add a .gitignore file in those directories with the following content:

*
!.gitignore

With this .gitignore file, Git will not track any files in those directories yet still allow me to add the .gitignore file and hence the directory itself to the repo.

How can I check if a string only contains letters in Python?

Actually, we're now in globalized world of 21st century and people no longer communicate using ASCII only so when anwering question about "is it letters only" you need to take into account letters from non-ASCII alphabets as well. Python has a pretty cool unicodedata library which among other things allows categorization of Unicode characters:

unicodedata.category('?')
'Lo'

unicodedata.category('A')
'Lu'

unicodedata.category('1')
'Nd'

unicodedata.category('a')
'Ll'

The categories and their abbreviations are defined in the Unicode standard. From here you can quite easily you can come up with a function like this:

def only_letters(s):
    for c in s:
        cat = unicodedata.category(c)
        if cat not in ('Ll','Lu','Lo'):
            return False
    return True

And then:

only_letters('Bzdrezylo')
True

only_letters('He7lo')
False

As you can see the whitelisted categories can be quite easily controlled by the tuple inside the function. See this article for a more detailed discussion.

Checking if a folder exists using a .bat file

I think the answer is here (possibly duplicate):

How to test if a file is a directory in a batch script?

IF EXIST %VAR%\NUL ECHO It's a directory

Replace %VAR% with your directory. Please read the original answer because includes details about handling white spaces in the folder name.

As foxidrive said, this might not be reliable on NT class windows. It works for me, but I know it has some limitations (which you can find in the referenced question)

if exist "c:\folder\" echo folder exists 

should be enough for modern windows.

Two constructors

Let's, just as example:

public class Test {     public Test() {         System.out.println("NO ARGS");     }      public Test(String s) {         this();         System.out.println("1 ARG");     }      public static void main(String args[])     {         Test t = new Test("s");     } } 

It will print

>>> NO ARGS >>> 1 ARG 

The correct way to call the constructor is by:

this(); 

'do...while' vs. 'while'

do-while is better if the compiler isn't competent at optimization. do-while has only a single conditional jump, as opposed to for and while which have a conditional jump and an unconditional jump. For CPUs which are pipelined and don't do branch prediction, this can make a big difference in the performance of a tight loop.

Also, since most compilers are smart enough to perform this optimization, all loops found in decompiled code will usually be do-while (if the decompiler even bothers to reconstruct loops from backward local gotos at all).

IntelliJ can't recognize JavaFX 11 with OpenJDK 11

The issue that JavaFX is no longer part of JDK 11. The following solution works using IntelliJ (haven't tried it with NetBeans):

  1. Add JavaFX Global Library as a dependency:

    Settings -> Project Structure -> Module. In module go to the Dependencies tab, and click the add "+" sign -> Library -> Java-> choose JavaFX from the list and click Add Selected, then Apply settings.

  2. Right click source file (src) in your JavaFX project, and create a new module-info.java file. Inside the file write the following code :

    module YourProjectName { 
        requires javafx.fxml;
        requires javafx.controls;
        requires javafx.graphics;
        opens sample;
    }
    

    These 2 steps will solve all your issues with JavaFX, I assure you.

Reference : There's a You Tube tutorial made by The Learn Programming channel, will explain all the details above in just 5 minutes. I also recommend watching it to solve your problem: https://www.youtube.com/watch?v=WtOgoomDewo

How do I compile with -Xlint:unchecked?

For IntelliJ 13.1, go to File -> Settings -> Project Settings -> Compiler -> Java Compiler, and on the right-hand side, for Additional command line parameters enter "-Xlint:unchecked".

python numpy vector math

You can just use numpy arrays. Look at the numpy for matlab users page for a detailed overview of the pros and cons of arrays w.r.t. matrices.

As I mentioned in the comment, having to use the dot() function or method for mutiplication of vectors is the biggest pitfall. But then again, numpy arrays are consistent. All operations are element-wise. So adding or subtracting arrays and multiplication with a scalar all work as expected of vectors.

Edit2: Starting with Python 3.5 and numpy 1.10 you can use the @ infix-operator for matrix multiplication, thanks to pep 465.

Edit: Regarding your comment:

  1. Yes. The whole of numpy is based on arrays.

  2. Yes. linalg.norm(v) is a good way to get the length of a vector. But what you get depends on the possible second argument to norm! Read the docs.

  3. To normalize a vector, just divide it by the length you calculated in (2). Division of arrays by a scalar is also element-wise.

    An example in ipython:

    In [1]: import math
    
    In [2]: import numpy as np
    
    In [3]: a = np.array([4,2,7])
    
    In [4]: np.linalg.norm(a)
    Out[4]: 8.3066238629180749
    
    In [5]: math.sqrt(sum([n**2 for n in a]))
    Out[5]: 8.306623862918075
    
    In [6]: b = a/np.linalg.norm(a)
    
    In [7]: np.linalg.norm(b)
    Out[7]: 1.0
    

    Note that In [5] is an alternative way to calculate the length. In [6] shows normalizing the vector.

C# ListView Column Width Auto

Use this:

yourListView.AutoResizeColumns(ColumnHeaderAutoResizeStyle.ColumnContent);
yourListView.AutoResizeColumns(ColumnHeaderAutoResizeStyle.HeaderSize);

from here

Alternative to file_get_contents?

If you have it available, using curl is your best option.

You can see if it is enabled by doing phpinfo() and searching the page for curl.

If it is enabled, try this:

$curl_handle=curl_init();
curl_setopt($curl_handle, CURLOPT_URL, SITE_PATH . 'cms/data.php');
$xml_file = curl_exec($curl_handle);
curl_close($curl_handle);

Compare every item to every other item in ArrayList

for (int i = 0; i < list.size(); i++) {
  for (int j = i+1; j < list.size(); j++) {
    // compare list.get(i) and list.get(j)
  }
}

ImportError: No module named 'bottle' - PyCharm

The settings are changed for PyCharm 5+.

  • Go to File > Default Settings
  • In left sidebar, click Default Project > Project Interpreter
  • At bottom of window, click + to install or - to uninstall.
  • If we click +, a new window opens where we can decrease the results by entering the package name/keyword.
  • Install the package.
  • Go to File > Invalidate caches/restart and click Invalidate and Restart to apply changes and restart PyCharm.

    Settings

    Install package

Selenium WebDriver.get(url) does not open the URL

@Neeraj

I've resolved this problem, but i'm not sure if you are the same reason.

In general, my problem was caused by some permission issues.

I tried to move my whole project into ~/:

mv xxx/ ~/

and then i change give it the 777 permission:

chmod -R 777 xxx/

I'm not familiar with linux permission so i just do this to make sure i have permission to execute the program.

Even you don't have permission, the selenium program will not prompt you.

So, good luck.

How to iterate a loop with index and element in Swift

Using .enumerate() works, but it does not provide the true index of the element; it only provides an Int beginning with 0 and incrementing by 1 for each successive element. This is usually irrelevant, but there is the potential for unexpected behavior when used with the ArraySlice type. Take the following code:

let a = ["a", "b", "c", "d", "e"]
a.indices //=> 0..<5

let aSlice = a[1..<4] //=> ArraySlice with ["b", "c", "d"]
aSlice.indices //=> 1..<4

var test = [Int: String]()
for (index, element) in aSlice.enumerate() {
    test[index] = element
}
test //=> [0: "b", 1: "c", 2: "d"] // indices presented as 0..<3, but they are actually 1..<4
test[0] == aSlice[0] // ERROR: out of bounds

It's a somewhat contrived example, and it's not a common issue in practice but still I think it's worth knowing this can happen.

How to append text to an existing file in Java?

FileOutputStream fos = new FileOutputStream("File_Name", true);
fos.write(data);

the true allows to append the data in the existing file. If we will write

FileOutputStream fos = new FileOutputStream("File_Name");

It will overwrite the existing file. So go for first approach.

Django 1.7 throws django.core.exceptions.AppRegistryNotReady: Models aren't loaded yet

Do you have a Python virtual environment that you need to enter before you run manage.py?

I ran into this error myself, and that was the problem.

Play an audio file using jQuery when a button is clicked

JSFiddle Demonstration

This is what I use with JQuery:

$('.button').on('click', function () { 
    var obj = document.createElement("audio");
        obj.src = "linktoyourfile.wav"; 
        obj.play(); 
});

Python import csv to list

Unfortunately I find none of the existing answers particularly satisfying.

Here is a straightforward and complete Python 3 solution, using the csv module.

import csv

with open('../resources/temp_in.csv', newline='') as f:
    reader = csv.reader(f, skipinitialspace=True)
    rows = list(reader)

print(rows)

Notice the skipinitialspace=True argument. This is necessary since, unfortunately, OP's CSV contains whitespace after each comma.

Output:

[['This is the first line', 'Line1'], ['This is the second line', 'Line2'], ['This is the third line', 'Line3']]

How to see the changes between two commits without commits in-between?

To compare two git commits 12345 and abcdef as patches one can use the diff command as

diff <(git show 123456) <(git show abcdef)

How do I raise an exception in Rails so it behaves like other Rails exceptions?

You don't have to do anything special, it should just be working.

When I have a fresh rails app with this controller:

class FooController < ApplicationController
  def index
    raise "error"
  end
end

and go to http://127.0.0.1:3000/foo/

I am seeing the exception with a stack trace.

You might not see the whole stacktrace in the console log because Rails (since 2.3) filters lines from the stack trace that come from the framework itself.

See config/initializers/backtrace_silencers.rb in your Rails project

Set focus on TextBox in WPF from view model

The problem is that once the IsUserNameFocused is set to true, it will never be false. This solves it by handling the GotFocus and LostFocus for the FrameworkElement.

I was having trouble with the source code formatting so here is a link

Retrofit 2.0 how to get deserialised error response.body

Create a model of the Error response & user Gson to convert the response to it. This will just work fine.

APIError.java

public class APIError {
    private String message;

    public String getMessage() {
        return message;
    }
}

MainActivity.java (inside request onResponse)

if (response.isSuccessful()) {
    // Do your success stuff...

} else {
    APIError message = new Gson().fromJson(response.errorBody().charStream(), APIError.class);
    Toast.makeText(MainActivity.this, "" + message.getMessage(), Toast.LENGTH_SHORT).show();
}

How to detect when keyboard is shown and hidden

Swift 5

There answers above are correct. Although I would prefer to create a helper to wrap up the notification's observers.

The benefit:

  1. You don't have to repeat each time you handle the keyboard behaviors.
  2. You can extend other notification by implement other enum value
  3. It's useful when you have to deal with keyboard in several controllers.

Sample code:

extension KeyboardHelper {
    enum Animation {
        case keyboardWillShow
        case keyboardWillHide
    }

    typealias HandleBlock = (_ animation: Animation, _ keyboardFrame: CGRect, _ duration: TimeInterval) -> Void
}

final class KeyboardHelper {
    private let handleBlock: HandleBlock

    init(handleBlock: @escaping HandleBlock) {
        self.handleBlock = handleBlock
        setupNotification()
    }

    deinit {
        NotificationCenter.default.removeObserver(self)
    }

    private func setupNotification() {
        _ = NotificationCenter.default
            .addObserver(forName: UIResponder.keyboardWillShowNotification, object: nil, queue: .main) { [weak self] notification in
                self?.handle(animation: .keyboardWillShow, notification: notification)
            }

        _ = NotificationCenter.default
            .addObserver(forName: UIResponder.keyboardWillHideNotification, object: nil, queue: .main) { [weak self] notification in
                self?.handle(animation: .keyboardWillHide, notification: notification)
            }
    }

    private func handle(animation: Animation, notification: Notification) {
        guard let userInfo = notification.userInfo,
            let keyboardFrame = (userInfo[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue,
            let duration = userInfo[UIResponder.keyboardAnimationDurationUserInfoKey] as? Double
        else { return }

        handleBlock(animation, keyboardFrame, duration)
    }
}

How to use:

private var keyboardHelper: KeyboardHelper?
...

override func viewDidLoad() {
   ...
   keyboardHelper = KeyboardHelper { [unowned self] animation, keyboardFrame, duration in
        switch animation {
        case .keyboardWillShow:
            print("keyboard will show")
        case .keyboardWillHide:
            print("keyboard will hide")
        }
    }

}

How to use bitmask?

Bitmasks are used when you want to encode multiple layers of information in a single number.

So (assuming unix file permissions) if you want to store 3 levels of access restriction (read, write, execute) you could check for each level by checking the corresponding bit.

rwx
---
110

110 in base 2 translates to 6 in base 10.

So you can easily check if someone is allowed to e.g. read the file by and'ing the permission field with the wanted permission.

Pseudocode:

PERM_READ = 4
PERM_WRITE = 2
PERM_EXEC = 1

user_permissions = 6

if (user_permissions & PERM_READ == TRUE) then
  // this will be reached, as 6 & 4 is true
fi

You need a working understanding of binary representation of numbers and logical operators to understand bit fields.

Show only two digit after decimal

I think the best and simplest solution is (KISS):

double i = 348842;
double i2 = i/60000;
float k = (float) Math.round(i2 * 100) / 100;

How do you extract classes' source code from a dll file?

You can use Reflector and also use Add-In FileGenerator to extract source code into a project.

What is size_t in C?

size_t and int are not interchangeable. For instance on 64-bit Linux size_t is 64-bit in size (i.e. sizeof(void*)) but int is 32-bit.

Also note that size_t is unsigned. If you need signed version then there is ssize_t on some platforms and it would be more relevant to your example.

As a general rule I would suggest using int for most general cases and only use size_t/ssize_t when there is a specific need for it (with mmap() for example).

Why does my sorting loop seem to append an element where it shouldn't?

To begin with, your problem is that you use the method `compareTo() which is case sensitive. That means that the Capital letters are sorted apart from the lower case. The reason is that it translated in Unicode where the capital letters are presented with numbers which are less than the presented number of lower case. Thus you should use `compareToIgnoreCase()` as many also mentioned in previous posts.

This is my full example approach of how you can do it effecively

After you create an object of the Comparator you can pass it in this version of `sort()` which defined in java.util.Arrays.

static<T>void sort(T[]array,Comparator<?super T>comp)

take a close look at super. This makes sure that the array which is passed into is combatible with the type of comparator.

The magic part of this way is that you can easily sort the array of strings in Reverse order you can easily do by:

return strB.compareToIgnoreCase(strA);

import java.util.Comparator;

    public class IgnoreCaseComp implements Comparator<String> {

        @Override
        public int compare(String strA, String strB) {
            return strA.compareToIgnoreCase(strB);
        }

    }

  import java.util.Arrays;

    public class IgnoreCaseSort {

        public static void main(String[] args) {
            String strs[] = {" Hello ", " This ", "is ", "Sorting ", "Example"};
            System.out.print("Initial order: ");

            for (String s : strs) {
                System.out.print(s + " ");
            }

            System.out.println("\n");

            IgnoreCaseComp icc = new IgnoreCaseComp();

            Arrays.sort(strs, icc);

            System.out.print("Case-insesitive sorted order:  ");
            for (String s : strs) {
                System.out.print(s + " ");
            }

            System.out.println("\n");

            Arrays.sort(strs);

            System.out.print("Default, case-sensitive sorted order: ");
            for (String s : strs) {
                System.out.print(s + " ");
            }

            System.out.println("\n");
        }

    }

 run:
    Initial order:  Hello   This  is  Sorting  Example 

    Case-insesitive sorted order:   Hello   This  Example is  Sorting  

    Default, case-sensitive sorted order:  Hello   This  Example Sorting  is  

    BUILD SUCCESSFUL (total time: 0 seconds)

Alternative Choice

The method compareToIgnoreCase(), although it works well with many occasions(just like compare string in english),it will wont work well with all languages and locations. This automatically makes it an unfit choice for use. To make sure that it will be suppoorted everywhere you should use compare() from java.text.Collator.

You can find a collator for your location by calling the method getInstance(). After that you should set this Collator's strength property. This can be done with the setStrength() method together with Collator.PRIMARY as parameter. With this alternative choise the IgnocaseComp can be written just like below. This version of code will generate the same output independently of the location

import java.text.Collator;
import java.util.Comparator;

//this comparator uses one Collator to determine 
//the right sort usage with no sensitive type 
//of the 2 given strings
public class IgnoreCaseComp implements Comparator<String> {

    Collator col;

    IgnoreCaseComp() {
        //default locale
        col = Collator.getInstance();

        //this will consider only PRIMARY difference ("a" vs "b")
        col.setStrength(Collator.PRIMARY);
    }

    @Override
    public int compare(String strA, String strB) {
        return col.compare(strA, strB);
    }

}

Angular2 RC5: Can't bind to 'Property X' since it isn't a known property of 'Child Component'

There are multiple possible causes for this error:

1) When you put the property 'x' inside brackets you are trying to bind to it. Therefore first thing to check is if the property 'x' is defined in your component with an Input() decorator

Your html file:

<body [x]="...">

Your class file:

export class YourComponentClass {

  @Input()
  x: string;
  ...
}

(make sure you also have the parentheses)

2) Make sure you registered your component/directive/pipe classes in NgModule:

@NgModule({
  ...
  declarations: [
    ...,
    YourComponentClass
  ],
  ...
})

See https://angular.io/guide/ngmodule#declare-directives for more details about declare directives.

3) Also happens if you have a typo in your angular directive. For example:

<div *ngif="...">
     ^^^^^

Instead of:

<div *ngIf="...">

This happens because under the hood angular converts the asterisk syntax to:

<div [ngIf]="...">

How do you convert a JavaScript date to UTC?

Using moment package, you can easily convert a date string of UTC to a new Date object:

const moment = require('moment');
let b = new Date(moment.utc('2014-02-20 00:00:00.000000'));
let utc = b.toUTCString();
b.getTime();

This specially helps when your server do not support timezone and you want to store UTC date always in server and get it back as a new Date object. Above code worked for my requirement of similar issue that this thread is for. Sharing here so that it can help others. I do not see exactly above solution in any answer. Thanks.

Encode/Decode URLs in C++

string urlDecode(string &SRC) {
    string ret;
    char ch;
    int i, ii;
    for (i=0; i<SRC.length(); i++) {
        if (int(SRC[i])==37) {
            sscanf(SRC.substr(i+1,2).c_str(), "%x", &ii);
            ch=static_cast<char>(ii);
            ret+=ch;
            i=i+2;
        } else {
            ret+=SRC[i];
        }
    }
    return (ret);
}

not the best, but working fine ;-)

Spring,Request method 'POST' not supported

In Jsp:

action="profile/proffiesional"

In Controller

@RequestMapping(value = "proffessional", method = RequestMethod.POST)

Spelling MisMatch !

Purpose of returning by const value?

It's pretty pointless to return a const value from a function.

It's difficult to get it to have any effect on your code:

const int foo() {
   return 3;
}

int main() {
   int x = foo();  // copies happily
   x = 4;
}

and:

const int foo() {
   return 3;
}

int main() {
   foo() = 4;  // not valid anyway for built-in types
}

// error: lvalue required as left operand of assignment

Though you can notice if the return type is a user-defined type:

struct T {};

const T foo() {
   return T();
}

int main() {
   foo() = T();
}

// error: passing ‘const T’ as ‘this’ argument of ‘T& T::operator=(const T&)’ discards qualifiers

it's questionable whether this is of any benefit to anyone.

Returning a reference is different, but unless Object is some template parameter, you're not doing that.

How can I generate Javadoc comments in Eclipse?

For me the /**<NEWLINE> or Shift-Alt-J (or ?-?-J on a Mac) approach works best.

I dislike seeing Javadoc comments in source code that have been auto-generated and have not been updated with real content. As far as I am concerned, such javadocs are nothing more than a waste of screen space.

IMO, it is much much better to generate the Javadoc comment skeletons one by one as you are about to fill in the details.

What is the difference between printf() and puts() in C?

Besides formatting, puts returns a nonnegative integer if successful or EOF if unsuccessful; while printf returns the number of characters printed (not including the trailing null).

Bind a function to Twitter Bootstrap Modal Close

I've seen many answers regarding the bootstrap events such as hide.bs.modal which triggers when the modal closes.

There's a problem with those events: any popups in the modal (popovers, tooltips, etc) will trigger that event.

There is another way to catch the event when a modal closes.

$(document).on('hidden','#modal:not(.in)', function(){} );

Bootstrap uses the in class when the modal is open. It is very important to use the hidden event since the class in is still defined when the event hideis triggered.

This solution will not work in IE8 since IE8 does not support the Jquery :not() selector.

Swift Set to Array

call this method and pass your set

func getArrayFromSet(set:NSSet)-> NSArray {

return set.map ({ String($0) })
}

Like This :

var letters:Set = Set<String>(arrayLiteral: "test","test") // your set
print(self.getArrayFromSet(letters))

fatal error LNK1104: cannot open file 'kernel32.lib'

In Visual Studio 2017, I went to Project Properties -> Configuration Properties -> General, Selected All Platforms (1), then chose the dropdown (2) under Windows SDK Version and updated from 10.0.14393.0 to one that was installed (3). For me, that was 10.0.15063.0.

enter image description here

Additional details: This corrected the error in my case because Windows SDK Version helps VS select the correct paths. VC++ Directories -> Library Directories -> Edit -> Macros -> shows that macro $(WindowsSDK_LibraryPath_x86) has a path with the version number selected above.

Submitting a form on 'Enter' with jQuery?

In addition to return false as Jason Cohen mentioned. You may have to also preventDefault

e.preventDefault();

Displaying unicode symbols in HTML

Make sure that you actually save the file as UTF-8, alternatively use HTML entities (&#nnn;) for the special characters.

Subversion ignoring "--password" and "--username" options

I had this same issue and solved it by setting up my ~/.ssh/config file to explicitly use the correct username (i.e. the one you use to login to the server, not your local machine). So, for example:

Host server.hostname
  User username

I found this blog post helpful: http://www.highlevelbits.com/2007/04/svn-over-ssh-prompts-for-wrong-username.html

Initializing a two dimensional std::vector

Use the std::vector::vector(count, value) constructor that accepts an initial size and a default value:

std::vector<std::vector<int> > fog(
    ROW_COUNT,
    std::vector<int>(COLUMN_COUNT)); // Defaults to zero initial value

If a value other than zero, say 4 for example, was required to be the default then:

std::vector<std::vector<int> > fog(
    ROW_COUNT,
    std::vector<int>(COLUMN_COUNT, 4));

I should also mention uniform initialization was introduced in C++11, which permits the initialization of vector, and other containers, using {}:

std::vector<std::vector<int> > fog { { 1, 1, 1 },
                                    { 2, 2, 2 } };
                           

Video file formats supported in iPhone

Short answer: H.264 MPEG (MP4)

Long answer from Apple.com:

Video formats supported: H.264 video, up to 1.5 Mbps, 640 by 480 pixels, 30 frames per second,

Low-Complexity version of the H.264 Baseline Profile with AAC-LC audio up to 160 Kbps, 48kHz, stereo audio in .m4v, .mp4, and .mov file formats; H.264 video, up to 2.5 Mbps, 640 by 480 pixels, 30 frames per second,

Baseline Profile up to Level 3.0 with AAC-LC audio up to 160 Kbps, 48kHz, stereo audio in .m4v, .mp4, and .mov file formats; MPEG-4 video, up to 2.5 Mbps, 640 by 480 pixels, 30 frames per second,

Simple Profile with AAC-LC audio up to 160 Kbps, 48kHz, stereo audio in .m4v, .mp4, and .mov file formats

http://www.apple.com/iphone/specs.html

UITableViewCell Selected Background Color on Multiple Selection

You can use standard UITableViewDelegate methods

- (nullable NSIndexPath *)tableView:(UITableView *)tableView willSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    EntityTableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    [cell selectMe];
    return indexPath;
}

- (nullable NSIndexPath *)tableView:(UITableView *)tableView willDeselectRowAtIndexPath:(NSIndexPath *)indexPath {
    EntityTableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    [cell deSelectMe];
    return indexPath;
}

in my situation this works, cause we need to select cell, change color, and when user taps 2 times on the selected cell further navigation should be performed.

keycode and charcode

Handling key events consistently is not at all easy.

Firstly, there are two different types of codes: keyboard codes (a number representing the key on the keyboard the user pressed) and character codes (a number representing a Unicode character). You can only reliably get character codes in the keypress event. Do not try to get character codes for keyup and keydown events.

Secondly, you get different sets of values in a keypress event to what you get in a keyup or keydown event.

I recommend this page as a useful resource. As a summary:

If you're interested in detecting a user typing a character, use the keypress event. IE bizarrely only stores the character code in keyCode while all other browsers store it in which. Some (but not all) browsers also store it in charCode and/or keyCode. An example keypress handler:

function(evt) {
  evt = evt || window.event;
  var charCode = evt.which || evt.keyCode;
  var charStr = String.fromCharCode(charCode);
  alert(charStr);
}

If you're interested in detecting a non-printable key (such as a cursor key), use the keydown event. Here keyCode is always the property to use. Note that keyup events have the same properties.

function(evt) {
  evt = evt || window.event;
  var keyCode = evt.keyCode;

  // Check for left arrow key
  if (keyCode == 37) {
    alert("Left arrow");
  }
}

How do I erase an element from std::vector<> by index?

here is one more way to do this if you want to delete a element by finding this with its value in vector,you just need to do this on vector.

vector<int> ar(n);
ar.erase(remove(ar.begin(), ar.end()), (place your value here from vector array));

it will remove your value from here. thanks

Python JSON dump / append to .txt with each variable on new line

Your question is a little unclear. If you're generating hostDict in a loop:

with open('data.txt', 'a') as outfile:
    for hostDict in ....:
        json.dump(hostDict, outfile)
        outfile.write('\n')

If you mean you want each variable within hostDict to be on a new line:

with open('data.txt', 'a') as outfile:
    json.dump(hostDict, outfile, indent=2)

When the indent keyword argument is set it automatically adds newlines.

How long to brute force a salted SHA-512 hash? (salt provided)

I want to know the time to brute force for when the password is a dictionary word and also when it is not a dictionary word.

Dictionary password

Ballpark figure: there are about 1,000,000 English words, and if a hacker can compute about 10,000 SHA-512 hashes a second (update: see comment by CodesInChaos, this estimate is very low), 1,000,000 / 10,000 = 100 seconds. So it would take just over a minute to crack a single-word dictionary password for a single user. If the user concatenates two dictionary words, you're in the area of a few days, but still very possible if the attacker is cares enough. More than that and it starts getting tough.

Random password

If the password is a truly random sequence of alpha-numeric characters, upper and lower case, then the number of possible passwords of length N is 60^N (there are 60 possible characters). We'll do the calculation the other direction this time; we'll ask: What length of password could we crack given a specific length of time? Just use this formula:

N = Log60(t * 10,000) where t is the time spent calculating hashes in seconds (again assuming 10,000 hashes a second).

1 minute:    3.2
5 minute:    3.6
30 minutes:  4.1
2 hours:     4.4
3 days:      5.2

So given a 3 days we'd be able to crack the password if it's 5 characters long.

This is all very ball-park, but you get the idea. Update: see comment below, it's actually possible to crack much longer passwords than this.

What's going on here?

Let's clear up some misconceptions:

  • The salt doesn't make it slower to calculate hashes, it just means they have to crack each user's password individually, and pre-computed hash tables (buzz-word: rainbow tables) are made completely useless. If you don't have a precomputed hash-table, and you're only cracking one password hash, salting doesn't make any difference.

  • SHA-512 isn't designed to be hard to brute-force. Better hashing algorithms like BCrypt, PBKDF2 or SCrypt can be configured to take much longer to compute, and an average computer might only be able to compute 10-20 hashes a second. Read This excellent answer about password hashing if you haven't already.

  • update: As written in the comment by CodesInChaos, even high entropy passwords (around 10 characters) could be bruteforced if using the right hardware to calculate SHA-512 hashes.


Notes on accepted answer:

The accepted answer as of September 2014 is incorrect and dangerously wrong:

In your case, breaking the hash algorithm is equivalent to finding a collision in the hash algorithm. That means you don't need to find the password itself (which would be a preimage attack)... Finding a collision using a birthday attack takes O(2^n/2) time, where n is the output length of the hash function in bits.

The birthday attack is completely irrelevant to cracking a given hash. And this is in fact a perfect example of a preimage attack. That formula and the next couple of paragraphs result in dangerously high and completely meaningless values for an attack time. As demonstrated above it's perfectly possible to crack salted dictionary passwords in minutes.

The low entropy of typical passwords makes it possible that there is a relatively high chance of one of your users using a password from a relatively small database of common passwords...

That's why generally hashing and salting alone is not enough, you need to install other safety mechanisms as well. You should use an artificially slowed down entropy-enducing method such as PBKDF2 described in PKCS#5...

Yes, please use an algorithm that is slow to compute, but what is "entropy-enducing"? Putting a low entropy password through a hash doesn't increase entropy. It should preserve entropy, but you can't make a rubbish password better with a hash, it doesn't work like that. A weak password put through PBKDF2 is still a weak password.

Cannot implicitly convert type 'System.Linq.IQueryable' to 'System.Collections.Generic.IList'

SonarQube reported Return an empty collection instead of null. and I had a problem with the error with casting as in the title of this question. I was able to get rid of both only using return XYZ.ToList().AsQueryable(); in a method with IQueryable like so:

public IQueryable<SomeType> MethodName (...) {
  IQueryable<SomeType> XYZ;
  ...
  return XYZ.ToList().AsQueryable();
}

Hope so it helps for those in a similar scenario(s).

Good ways to manage a changelog using git?

You can use some flavor of git log to help you out:

git log --pretty=%s                 # only print the subject

If you name your branches nicely, so that a merge to master shows up as something like "Merged branch feature-foobar", you can shorten things by only showing that message, and not all the little commits that you merged, which together form the feature:

git log --pretty=%s --first-parent  # only follow first parent of merges

You might be able to augment this with a script of your own, which could do things like strip out the "Merged branch" bits, normalize formatting, etc. At some point you have to write it yourself though, of course.

Then you could create a new section for the changelog once per version:

git log [opts] vX.X.X..vX.X.Y | helper-script > changelogs/X.X.Y

and commit that in your version release commit.

If your problem is that those commit subjects aren't anything like what you'd want to put in a changelog, you pretty much have two options: keep doing everything manually (and try to keep up with it more regularly instead of playing catch-up at release time), or fix up your commit message style. One option, if the subjects aren't going to do it for you, would be to place lines like "change: added feature foobar" in the bodies of your commit messages, so that later you could do something like git log --pretty=%B | grep ^change: to grab only those super-important bits of the messages.

I'm not entirely sure how much more than that git could really help you create your changelogs. Maybe I've misinterpreted what you mean by "manage"?

How to get the number of threads in a Java process

ManagementFactory.getThreadMXBean().getThreadCount() doesn't limit itself to thread groups as Thread.activeCount() does.

How to change working directory in Jupyter Notebook?

Open jupyter notebook click upper right corner new and select terminal then type cd + your desired working path and press enter this will change your dir. It worked for me

How to detect running app using ADB command

If you want to directly get the package name of the current app in focus, use this adb command -

adb shell dumpsys window windows | grep -E 'mFocusedApp'| cut -d / -f 1 | cut -d " " -f 7

Extra info from the result of the adb command is removed using the cut command. Original solution from here.

Get Current date & time with [NSDate date]

NSLocale* currentLocale = [NSLocale currentLocale];
[[NSDate date] descriptionWithLocale:currentLocale];  

or use

NSDateFormatter *dateFormatter=[[NSDateFormatter alloc] init]; 
[dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
// or @"yyyy-MM-dd hh:mm:ss a" if you prefer the time with AM/PM 
NSLog(@"%@",[dateFormatter stringFromDate:[NSDate date]]);

How to declare a global variable in a .js file

Have you tried it?

If you do:

var HI = 'Hello World';

In global.js. And then do:

alert(HI);

In js1.js it will alert it fine. You just have to include global.js prior to the rest in the HTML document.

The only catch is that you have to declare it in the window's scope (not inside any functions).

You could just nix the var part and create them that way, but it's not good practice.

Download TS files from video stream

While this shouldn't have ever been asked on SO and got through the vetting processing in the first place, I have no idea... but I'm giving my answer anyway.

After exploring basically all of the options presented here, it turns out the simplest is often the best.

First download ffmpeg from: https://evermeet.cx/ffmpeg/

Next, after you have got your .m3u8 playlist file (most probably from the webpage source or network traffic), run this command:

ffmpeg -i "http://host/folder/file.m3u8" -bsf:a aac_adtstoasc -vcodec copy -c copy -crf 50 file.mp4

I tried running it from a locally saved m4u8 file, and it didn't work, because the ffmpeg download procedure downloads the chunks which are relative to the URL, so make sure you use the website url.

Convert a number range to another range, maintaining ratio

I used this solution in a problem I was solving in js, so I thought I would share the translation. Thanks for the explanation and solution.

function remap( x, oMin, oMax, nMin, nMax ){
//range check
if (oMin == oMax){
    console.log("Warning: Zero input range");
    return None;
};

if (nMin == nMax){
    console.log("Warning: Zero output range");
    return None
}

//check reversed input range
var reverseInput = false;
oldMin = Math.min( oMin, oMax );
oldMax = Math.max( oMin, oMax );
if (oldMin != oMin){
    reverseInput = true;
}

//check reversed output range
var reverseOutput = false;  
newMin = Math.min( nMin, nMax )
newMax = Math.max( nMin, nMax )
if (newMin != nMin){
    reverseOutput = true;
};

var portion = (x-oldMin)*(newMax-newMin)/(oldMax-oldMin)
if (reverseInput){
    portion = (oldMax-x)*(newMax-newMin)/(oldMax-oldMin);
};

var result = portion + newMin
if (reverseOutput){
    result = newMax - portion;
}

return result;
}

What's the safest way to iterate through the keys of a Perl hash?

I always use method 2 as well. The only benefit of using each is if you're just reading (rather than re-assigning) the value of the hash entry, you're not constantly de-referencing the hash.

jQuery each loop in table row

Use immediate children selector >:

$('#tblOne > tbody  > tr')

Description: Selects all direct child elements specified by "child" of elements specified by "parent".

How to create my json string by using C#?

The json is kind of odd, it's like the students are properties of the "GetQuestion" object, it should be easy to be a List.....

About the libraries you could use are.

And there could be many more, but that are what I've used

About the json I don't now maybe something like this

public class GetQuestions
{
    public List<Student> Questions { get; set; }
}

public class Student
{
    public string Code { get; set; }
    public string Questions { get; set; }
}

void Main()
{
    var gq = new GetQuestions
    {
        Questions = new List<Student>
        {
            new Student {Code = "s1", Questions = "Q1,Q2"},
            new Student {Code = "s2", Questions = "Q1,Q2,Q3"},
            new Student {Code = "s3", Questions = "Q1,Q2,Q4"},
            new Student {Code = "s4", Questions = "Q1,Q2,Q5"},
        }
    };

    //Using Newtonsoft.json. Dump is an extension method of [Linqpad][4]
    JsonConvert.SerializeObject(gq).Dump();
}

Linqpad

and the result is this

{
     "Questions":[
        {"Code":"s1","Questions":"Q1,Q2"},
        {"Code":"s2","Questions":"Q1,Q2,Q3"},
        {"Code":"s3","Questions":"Q1,Q2,Q4"},
        {"Code":"s4","Questions":"Q1,Q2,Q5"}
      ]
 }

Yes I know the json is different, but the json that you want with dictionary.

void Main()
{
    var f = new Foo
    {
        GetQuestions = new Dictionary<string, string>
                {
                    {"s1", "Q1,Q2"},
                    {"s2", "Q1,Q2,Q3"},
                    {"s3", "Q1,Q2,Q4"},
                    {"s4", "Q1,Q2,Q4,Q6"},
                }
    };

    JsonConvert.SerializeObject(f).Dump();
}

class Foo
{
    public Dictionary<string, string> GetQuestions { get; set; }
}

And with Dictionary is as you want it.....

{
      "GetQuestions":
       {
              "s1":"Q1,Q2",
              "s2":"Q1,Q2,Q3",
              "s3":"Q1,Q2,Q4",
              "s4":"Q1,Q2,Q4,Q6"
       }
 }

Why fragments, and when to use fragments instead of activities?

I know this was already discussed to death, but I'd like to add some more points:

  • Frags can be used to populate Menus and can handle MenuItem clicks on their own. Thus giving futher modulation options for your Activities. You can do ContextualActionBar stuff and so on without your Activity knowing about it and can basically decouple it from the basic stuff your Activity handles (Navigation/Settings/About).

  • A parent Frag with child Frags can give you further options to modulize your components. E.g. you can easily swap Frags around, put new Frags inside a Pager or remove them, rearrange them. All without your Activity knowing anything about it just focusing on the higher level stuff.

Random character generator with a range of (A..Z, 0..9) and punctuation

  1. Pick a random number between [0, x), where x is the number of different symbols. Hopefully the choice is uniformly chosen and not predictable :-)

  2. Now choose the symbol representing x.

  3. Profit!

I would start reading up Pseudorandomness and then some common Pseudo-random number generators. Of course, your language hopefully already has a suitable "random" function :-)

Check whether $_POST-value is empty

To check if the property is present, irrespective of the value, use:

if (array_key_exists('userName', $_POST)) {}

To check if the property is set (property is present and value is not null or false), use:

if (isset($_POST['userName'])) {}

To check if the property is set and not empty (not an empty string, 0 (integer), 0.0 (float), '0' (string), null, false or [] (empty array)), use:

if (!empty($_POST['userName'])) {}

How to get a barplot with several variables side by side grouped by a factor

Using reshape2 and dplyr. Your data:

df <- read.table(text=
"tea                coke            beer             water           gender
14.55              26.50793651     22.53968254      40              1
24.92997199        24.50980392     26.05042017      24.50980393     2
23.03732304        30.63063063     25.41827542      20.91377091     1   
225.51781276       24.6064623      24.85501243      50.80645161     1
24.53662842        26.03706973     25.24271845      24.18358341     2", header=TRUE)

Getting data into correct form:

library(reshape2)
library(dplyr)
df.melt <- melt(df, id="gender")
bar <- group_by(df.melt, variable, gender)%.%summarise(mean=mean(value))

Plotting:

library(ggplot2)
ggplot(bar, aes(x=variable, y=mean, fill=factor(gender)))+
  geom_bar(position="dodge", stat="identity")

enter image description here

Set an environment variable in git bash

Creating a .bashrc file in your home directory also works. That way you don't have to copy your .bash_profile every time you install a new version of git bash.

Where can I find System.Web.Helpers, System.Web.WebPages, and System.Web.Razor?

On VS2017 I installed the NuGet package: Microsoft.AspNet.WebPages

That did the trick.

Invalid self signed SSL cert - "Subject Alternative Name Missing"

The Issue

As others have mentioned, the NET::ERR_CERT_COMMON_NAME_INVALID error is occurring because the generated certificate does not include the SAN (subjectAltName) field.

RFC2818 has deprecated falling back to the commonName field since May of 2000. The use of the subjectAltName field has been enforced in Chrome since version 58 (see Chrome 58 deprecations).

OpenSSL accepts x509v3 configuration files to add extended configurations to certificates (see the subjectAltName field for configuration options).


Bash Script

I created a self-signed-tls bash script with straightforward options to make it easy to generate certificate authorities and sign x509 certificates with OpenSSL (valid in Chrome using the subjectAltName field).

The script will guide you through a series of questions to include the necessary information (including the subjectAltName field). You can reference the README.md for more details and options for automation.

Be sure to restart chrome after installing new certificates.

chrome://restart

Other Resources

  • The Docker documentation has a great straightforward example for creating a self-signed certificate authority and signing certificates with OpenSSL.
  • cfssl is also a very robust tool that is widely used and worth checking out.

Convert Bitmap to File

Try this:

bitmap.compress(Bitmap.CompressFormat.PNG, quality, outStream);

See this

How do I include a JavaScript script file in Angular and call a function from that script?

You can either

import * as abc from './abc';
abc.xyz();

or

import { xyz } from './abc';
xyz()

php exec command (or similar) to not wait for result

I know this question has been answered but the answers i found here didn't work for my scenario ( or for Windows ).

I am using windows 10 laptop with PHP 7.2 in Xampp v3.2.4.

$command = 'php Cron.php send_email "'. $id .'"';
if ( substr(php_uname(), 0, 7) == "Windows" )
{
    //windows
    pclose(popen("start /B " . $command . " 1> temp/update_log 2>&1 &", "r"));
}
else
{
    //linux
    shell_exec( $command . " > /dev/null 2>&1 &" );
}

This worked perfectly for me.

I hope it will help someone with windows. Cheers.

Keyboard shortcut to comment lines in Sublime Text 2

I'd like to add, that on my mac by default block comment toggle shortcut is cmd+alt+/

Retrieving a Foreign Key value with django-rest-framework serializers

In the DRF version 3.6.3 this worked for me

class ItemSerializer(serializers.ModelSerializer):
    category_name = serializers.CharField(source='category.name')

    class Meta:
        model = Item
        fields = ('id', 'name', 'category_name')

More info can be found here: Serializer Fields core arguments

What is the purpose of a plus symbol before a variable?

The + operator returns the numeric representation of the object. So in your particular case, it would appear to be predicating the if on whether or not d is a non-zero number.

Reference here. And, as pointed out in comments, here.

For loop in Objective-C

You mean fast enumeration? You question is very unclear.

A normal for loop would look a bit like this:

unsigned int i, cnt = [someArray count];
for(i = 0; i < cnt; i++)
{ 
   // do loop stuff
   id someObject = [someArray objectAtIndex:i];
}

And a loop with fast enumeration, which is optimized by the compiler, would look like this:

for(id someObject in someArray)
{
   // do stuff with object
}

Keep in mind that you cannot change the array you are using in fast enumeration, thus no deleting nor adding when using fast enumeration

How to include External CSS and JS file in Laravel 5

At first, you have to put your .css or .js files in the public folder of your project. You may create subfolders to it and move the files into the subfolder. Then you have to do the followings

<link rel="stylesheet" href="{{asset('css/your_css_file.css')}}">
<script src="{{asset('js/your_js_file.js')}}"></script>

In my example, I have created two subfolders called css and js. I put all of the .css and .js files in corresponding folders and use them where ever I want them. Thank you and hope this helps you.

Python: What OS am I running on?

Dang -- lbrandy beat me to the punch, but that doesn't mean I can't provide you with the system results for Vista!

>>> import os
>>> os.name
'nt'
>>> import platform
>>> platform.system()
'Windows'
>>> platform.release()
'Vista'

...and I can’t believe no one’s posted one for Windows 10 yet:

>>> import os
>>> os.name
'nt'
>>> import platform
>>> platform.system()
'Windows'
>>> platform.release()
'10'

How to iterate through two lists in parallel?

You can bundle the nth elements into a tuple or list using comprehension, then pass them out with a generator function.

def iterate_multi(*lists):
    for i in range(min(map(len,lists))):
        yield tuple(l[i] for l in lists)

for l1, l2, l3 in iterate_multi([1,2,3],[4,5,6],[7,8,9]):
    print(str(l1)+","+str(l2)+","+str(l3))

Converting <br /> into a new line for use in a text area

EDIT: previous answer was backwards of what you wanted. Use str_replace. replace <br> with \n

echo str_replace('<br>', "\n", $var1);

Is it possible to create a remote repo on GitHub from the CLI without opening browser?

To Quickly Create the Remote Repository by Using a Bash Shell

It is cumbersome to type the complete code every time a repository is to be created

curl -u 'USER' https://api.github.com/user/repos -d '{"name":"REPO"}' git remote add origin [email protected]:USER/REPO.git git push origin master

An easier approach is:

  1. create a shell script in a directory i.e. /home/USER_NAME/Desktop/my_scripts named githubscript.sh
  2. Modify and save the following code to the githubscript.sh file
#!bin/bash
curl -u 'YOUR_GITHUB_USER_NAME' https://api.github.com/user/repos -d "{\"name\":\"$1\"}";
git init;
git remote add origin [email protected]:YOUR_GITHUB_USER_NAME/$1.git;

N.B. Here $1 is the repository name that is passed as an argument when invoking the script Change YOUR_GITHUB_USER_NAME before saving the script.

  1. Set required permissions to the script file chmod 755 githubscript.sh

  2. Include the scripts directory in the environment configuration file. nano ~/.profile; export PATH="$PATH:$HOME/Desktop/my_scripts"

  3. Also set an alias to run the githubscript.sh file. nano ~/.bashrc; alias githubrepo="bash githubscript.sh"

  4. Now reload the .bashrc and .profile files in the terminal. source ~/.bashrc ~/.profile;

  5. Now to create a new repository i.e. demo: githubrepo demo;

Disable vertical scroll bar on div overflow: auto

These two CSS properties can be used to hide the scrollbars:

overflow-y: hidden; // hide vertical
overflow-x: hidden; // hide horizontal

appcompat-v7:21.0.0': No resource found that matches the given name: attr 'android:actionModeShareDrawable'

I had added another project to my workspace and was trying to reference an activity from it in the manifest file, and I was getting this error. The problem is I was referencing the library incorrectly. This is how I fixed the problem:

  • Right click on project
  • Select Properties
  • Click on Android on left menu
  • Click on Add
  • Please select a Library Project

The jar went into Android Dependencies folder and this error was fixed.

Java: Calculating the angle between two points in degrees

The javadoc for Math.atan(double) is pretty clear that the returning value can range from -pi/2 to pi/2. So you need to compensate for that return value.

Display alert message and redirect after click on accept

The redirect function cleans the output buffer and does a header('Location:...'); redirection and exits script execution. The part you are trying to echo will never be outputted.

You should either notify on the download page or notify on the page you redirect to about the missing data.

Formatting Numbers by padding with leading zeros in SQL Server

I am posting all at one place, all works for me to pad with 4 leading zero :)

declare @number int =  1;
print right('0000' + cast(@number as varchar(4)) , 4)
print right('0000' + convert(varchar(4), @number) , 4)
print right(replicate('0',4) + convert(varchar(4), @number) , 4)
print  cast(replace(str(@number,4),' ','0')as char(4))
print format(@number,'0000')

Why use #define instead of a variable

Most common use (other than to declare constants) is an include guard.

Javascript Equivalent to C# LINQ Select

You can try manipula package, which implement all of C# LINQ methods and save its syntax: https://github.com/litichevskiydv/manipula

https://www.npmjs.com/package/manipula

Your example selectedFruits.select(fruit=>fruit.id); will be implemented with manipula as

Manipula.from(selectedFruits).select(fruit=>fruit.id);

Android and setting width and height programmatically in dp units

I know this is an old question however I've found a much neater way of doing this conversion.

Java

TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 65, getResources().getDisplayMetrics());

Kotlin

TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 65f, resources.displayMetrics)

Programmatically Creating UILabel

In Swift -

var label:UILabel = UILabel(frame: CGRectMake(0, 0, 70, 20))
label.center = CGPointMake(50, 70)
label.textAlignment = NSTextAlignment.Center
label.text = "message"
label.textColor = UIColor.blackColor()
self.view.addSubview(label)

How to reject in async/await syntax?

I have a suggestion to properly handle rejects in a novel approach, without having multiple try-catch blocks.

import to from './to';

async foo(id: string): Promise<A> {
    let err, result;
    [err, result] = await to(someAsyncPromise()); // notice the to() here
    if (err) {
        return 400;
    }
    return 200;
}

Where the to.ts function should be imported from:

export default function to(promise: Promise<any>): Promise<any> {
    return promise.then(data => {
        return [null, data];
    }).catch(err => [err]);
}

Credits go to Dima Grossman in the following link.

How do I use checkboxes in an IF-THEN statement in Excel VBA 2010?

I found that I could access the checkbox directly using Worksheets("SheetName").CB_Checkboxname.value directly without relating to additional objects.

How to ignore HTML element from tabindex?

The way to do this is by adding tabindex="-1". By adding this to a specific element, it becomes unreachable by the keyboard navigation. There is a great article here that will help you further understand tabindex.

For files in directory, only echo filename (no path)

You can either use what SiegeX said above or if you aren't interested in learning/using parameter expansion, you can use:

for filename in $(ls /home/user/);
do
    echo $filename
done;

Postgres - Transpose Rows to Columns

If anyone else that finds this question and needs a dynamic solution for this where you have an undefined number of columns to transpose to and not exactly 3, you can find a nice solution here: https://github.com/jumpstarter-io/colpivot

How to copy file from HDFS to the local file system

1.- Remember the name you gave to the file and instead of using hdfs dfs -put. Use 'get' instead. See below.

$hdfs dfs -get /output-fileFolderName-In-hdfs

Why are empty catch blocks a bad idea?

Empty catch blocks are usually put in because the coder doesn't really know what they are doing. At my organization, an empty catch block must include a comment as to why doing nothing with the exception is a good idea.

On a related note, most people don't know that a try{} block can be followed with either a catch{} or a finally{}, only one is required.

Disable a link in Bootstrap

It seems that Bootstrap doesn't support disabled links. Instead of trying to add a Bootstrap class, you could add a class by your own and add some styling to it, just like this:

_x000D_
_x000D_
a.disabled {_x000D_
  /* Make the disabled links grayish*/_x000D_
  color: gray;_x000D_
  /* And disable the pointer events */_x000D_
  pointer-events: none;_x000D_
}
_x000D_
<!-- Make the disabled links unfocusable as well -->_x000D_
<a href="#" class="disabled" tabindex="-1">Link to disable</a><br/>_x000D_
<a href="#">Non-disabled Link</a>
_x000D_
_x000D_
_x000D_

What are Long-Polling, Websockets, Server-Sent Events (SSE) and Comet?

I have tried to make note about these and have collected and written examples from a java perspective.

HTTP for Java Developers

Reverse Ajax - Old style

Async Handling on server side

Reverse Ajax - New style

Server Sent Events

Putting it here for any java developer who is looking into the same subject.

Is List<Dog> a subclass of List<Animal>? Why are Java generics not implicitly polymorphic?

I would say the whole point of Generics is that it doesn't allow that. Consider the situation with arrays, which do allow that type of covariance:

  Object[] objects = new String[10];
  objects[0] = Boolean.FALSE;

That code compiles fine, but throws a runtime error (java.lang.ArrayStoreException: java.lang.Boolean in the second line). It is not typesafe. The point of Generics is to add the compile time type safety, otherwise you could just stick with a plain class without generics.

Now there are times where you need to be more flexible and that is what the ? super Class and ? extends Class are for. The former is when you need to insert into a type Collection (for example), and the latter is for when you need to read from it, in a type safe manner. But the only way to do both at the same time is to have a specific type.

How to make ng-repeat filter out duplicate results

UPDATE

I was recomending the use of Set but sorry this doesn't work for ng-repeat, nor Map since ng-repeat only works with array. So ignore this answer. anyways if you need to filter out duplicates one way is as other has said using angular filters, here is the link for it to the getting started section.


Old answer

Yo can use the ECMAScript 2015 (ES6) standard Set Data structure, instead of an Array Data Structure this way you filter repeated values when adding to the Set. (Remember sets don't allow repeated values). Really easy to use:

var mySet = new Set();

mySet.add(1);
mySet.add(5);
mySet.add("some text");
var o = {a: 1, b: 2};
mySet.add(o);

mySet.has(1); // true
mySet.has(3); // false, 3 has not been added to the set
mySet.has(5);              // true
mySet.has(Math.sqrt(25));  // true
mySet.has("Some Text".toLowerCase()); // true
mySet.has(o); // true

mySet.size; // 4

mySet.delete(5); // removes 5 from the set
mySet.has(5);    // false, 5 has been removed

mySet.size; // 3, we just removed one value

How do you explicitly set a new property on `window` in TypeScript?

The accepted answer is what I used to use, but with TypeScript 0.9.* it no longer works. The new definition of the Window interface seems to completely replace the built-in definition, instead of augmenting it.

I have taken to doing this instead:

interface MyWindow extends Window {
    myFunction(): void;
}

declare var window: MyWindow;

UPDATE: With TypeScript 0.9.5 the accepted answer is working again.

Can't get Python to import from a different folder

I believe you need to create a file called __init__.py in the Models directory so that python treats it as a module.

Then you can do:

from Models.user import User

You can include code in the __init__.py (for instance initialization code that a few different classes need) or leave it blank. But it must be there.

text-overflow: ellipsis not working

You may try using ellipsis by adding the following in CSS:

.truncate {
  width: 250px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

But it seems like this code just applies to one-line trim. More ways to trim text and show ellipsis can be found in this website: http://blog.sanuker.com/?p=631

What is the difference between an int and an Integer in Java and C#?

(Java Version) In Simple words int is primitive and Integer is wrapper object for int.

One example where to use Integer vs int, When you want to compare and int variable again null it will throw error.

int a;
//assuming a value you are getting from data base which is null
if(a ==null) // this is wrong - cannot compare primitive to null
{
do something...}

Instead you will use,
Integer a;
//assuming a value you are getting from data base which is null
if(a ==null) // this is correct/legal
{ do something...}

Jenkins pipeline how to change to another folder

Use WORKSPACE environment variable to change workspace directory.

If doing using Jenkinsfile, use following code :

dir("${env.WORKSPACE}/aQA"){
    sh "pwd"
}

Spring Boot War deployed to Tomcat

Hey make sure to do this changes to the pom.xml

<packaging>war</packaging>

in the dependencies section make sure to indicated the tomcat is provided so you dont need the embeded tomcat plugin.

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-tomcat</artifactId>
        <scope>provided</scope>
    </dependency>       

    <dependency>
        <groupId>org.apache.tomcat.embed</groupId>
        <artifactId>tomcat-embed-jasper</artifactId>
        <scope>provided</scope>
    </dependency>       

This is the whole pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.example</groupId>
    <artifactId>demo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>war</packaging>

    <name>demo</name>
    <description>Demo project for Spring Boot</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.4.0.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
        <start-class>com.example.Application</start-class>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-tomcat</artifactId>
            <scope>provided</scope>
        </dependency>       

        <dependency>
            <groupId>org.apache.tomcat.embed</groupId>
            <artifactId>tomcat-embed-jasper</artifactId>
            <scope>provided</scope>
        </dependency>       

    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>


</project>

And the Application class should be like this

Application.java

package com.example;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.support.SpringBootServletInitializer;

@SpringBootApplication
public class Application extends SpringBootServletInitializer {


    /**
     * Used when run as JAR
     */
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }

    /**
     * Used when run as WAR
     */
    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
        return builder.sources(Application.class);
    }

}

And you can add a controller for testing MyController.java

package com.example;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class MyController {

    @RequestMapping("/hi")
    public @ResponseBody String hiThere(){
        return "hello world!";
    }
}

Then you can run the project in a tomcat 8 version and access the controller like this

http://localhost:8080/demo/hi

If for some reason you are not able to add the project to tomcat do a right click in the project and then go to the Build Path->configure build path->Project Faces

make sure only this 3 are selected

Dynamic web Module 3.1 Java 1.8 Javascript 1.0

Count of "Defined" Array Elements

An array length is not the number of elements in a array, it is the highest index + 1. length property will report correct element count only if there are valid elements in consecutive indices.

var a = [];
a[23] = 'foo';
a.length;  // 24

Saying that, there is no way to exclude undefined elements from count without using any form of a loop.

Is there a MySQL option/feature to track history of changes to records?

Why not simply use bin log files? If the replication is set on the Mysql server, and binlog file format is set to ROW, then all the changes could be captured.

A good python library called noplay can be used. More info here.

Error:(1, 0) Plugin with id 'com.android.application' not found

I still got the error

 Could not find com.android.tools.build:gradle:3.0.0.

Problem: jcenter() did not have the required libs

Solution: add google() as repo

buildscript {
    repositories {
        google()
        jcenter()

    }
    dependencies {

        classpath "com.android.tools.build:gradle:3.0.0"
    }
}

XSLT equivalent for JSON

I wrote my own small library around this, recently, which tries to stay as close to

5.1 Processing Model (XSLT REC) https://www.w3.org/TR/xslt#section-Processing-Model

as is possible (as I could anyway), in a few lines of JavaScript code.

Here are a few not-completely-trivial examples of use...

1. JSON-to-some-markup:

Fiddle: https://jsfiddle.net/YSharpLanguage/kj9pk8oz/10

(inspired by D.1 Document Example (XSLT REC) https://www.w3.org/TR/xslt#section-Document-Example)

where this:

var D1document = {
    type: "document", title: [ "Document Title" ],
    "": [
      { type: "chapter", title: [ "Chapter Title" ],
        "": [
        { type: "section", title: [ "Section Title" ],
          "": [
            { type: "para", "": [ "This is a test." ] },
            { type: "note", "": [ "This is a note." ] }
        ] },
        { type: "section", title: [ "Another Section Title" ],
          "": [
            { type: "para", "": [ "This is ", { emph: "another" }, " test." ] },
            { type: "note", "": [ "This is another note." ] }
        ] }
      ] }
    ] };

var D1toHTML = { $: [
  [ [ function(node) { return node.type === "document"; } ],
    function(root) {
      return "<html>\r\n\
  <head>\r\n\
    <title>\r\n\
      {title}\r\n".of(root) + "\
    </title>\r\n\
  </head>\r\n\
  <body>\r\n\
{*}".of(root[""].through(this)) + "\
  </body>\r\n\
</html>";
    }
  ],
  [ [ function(node) { return node.type === "chapter"; } ],
    function(chapter) {
      return "    <h2>{title}</h2>\r\n".of(chapter) + "{*}".of(chapter[""].through(this));
    }
  ],
  [ [ function(node) { return node.type === "section"; } ],
    function(section) {
      return "    <h3>{title}</h3>\r\n".of(section) + "{*}".of(section[""].through(this));
    }
  ],
  [ [ function(node) { return node.type === "para"; } ],
    function(para) {
      return "    <p>{*}</p>\r\n".of(para[""].through(this));
    }
  ],
  [ [ function(node) { return node.type === "note"; } ],
    function(note) {
      return '    <p class="note"><b>NOTE: </b>{*}</p>\r\n'.of(note[""].through(this));
    }
  ],
  [ [ function(node) { return node.emph; } ],
    function(emph) {
      return "<em>{emph}</em>".of(emph);
    }
  ]
] };

console.log(D1document.through(D1toHTML));

... gives:

<html>
  <head>
    <title>
      Document Title
    </title>
  </head>
  <body>
    <h2>Chapter Title</h2>
    <h3>Section Title</h3>
    <p>This is a test.</p>
    <p class="note"><b>NOTE: </b>This is a note.</p>
    <h3>Another Section Title</h3>
    <p>This is <em>another</em> test.</p>
    <p class="note"><b>NOTE: </b>This is another note.</p>
  </body>
</html>

and

2. JSON-to-JSON:

Fiddle: https://jsfiddle.net/YSharpLanguage/ppfmmu15/10

where this:

// (A "Company" is just an object with a "Team")
function Company(obj) {
  return obj.team && Team(obj.team);
}

// (A "Team" is just a non-empty array that contains at least one "Member")
function Team(obj) {
  return ({ }.toString.call(obj) === "[object Array]") &&
         obj.length &&
         obj.find(function(item) { return Member(item); });
}

// (A "Member" must have first and last names, and a gender)
function Member(obj) {
  return obj.first && obj.last && obj.sex;
}

function Dude(obj) {
  return Member(obj) && (obj.sex === "Male");
}

function Girl(obj) {
  return Member(obj) && (obj.sex === "Female");
}

var data = { team: [
  { first: "John", last: "Smith", sex: "Male" },
  { first: "Vaio", last: "Sony" },
  { first: "Anna", last: "Smith", sex: "Female" },
  { first: "Peter", last: "Olsen", sex: "Male" }
] };

var TO_SOMETHING_ELSE = { $: [

  [ [ Company ],
    function(company) {
      return { some_virtual_dom: {
        the_dudes: { ul: company.team.select(Dude).through(this) },
        the_grrls: { ul: company.team.select(Girl).through(this) }
      } }
    } ],

  [ [ Member ],
    function(member) {
      return { li: "{first} {last} ({sex})".of(member) };
    } ]

] };

console.log(JSON.stringify(data.through(TO_SOMETHING_ELSE), null, 4));

... gives:

{
    "some_virtual_dom": {
        "the_dudes": {
            "ul": [
                {
                    "li": "John Smith (Male)"
                },
                {
                    "li": "Peter Olsen (Male)"
                }
            ]
        },
        "the_grrls": {
            "ul": [
                {
                    "li": "Anna Smith (Female)"
                }
            ]
        }
    }
}

3. XSLT vs. JavaScript:

A JavaScript equivalent of...

XSLT 3.0 REC Section 14.4 Example: Grouping Nodes based on Common Values

(at: http://jsfiddle.net/YSharpLanguage/8bqcd0ey/1)

Cf. https://www.w3.org/TR/xslt-30/#grouping-examples

where...

var cities = [
  { name: "Milano",  country: "Italia",      pop: 5 },
  { name: "Paris",   country: "France",      pop: 7 },
  { name: "München", country: "Deutschland", pop: 4 },
  { name: "Lyon",    country: "France",      pop: 2 },
  { name: "Venezia", country: "Italia",      pop: 1 }
];

/*
  Cf.
  XSLT 3.0 REC Section 14.4
  Example: Grouping Nodes based on Common Values

  https://www.w3.org/TR/xslt-30/#grouping-examples
*/
var output = "<table>\r\n\
  <tr>\r\n\
    <th>Position</th>\r\n\
    <th>Country</th>\r\n\
    <th>City List</th>\r\n\
    <th>Population</th>\r\n\
  </tr>{*}\r\n\
</table>".of
  (
    cities.select().groupBy("country")(function(byCountry, index) {
      var country = byCountry[0],
          cities = byCountry[1].select().orderBy("name");
      return "\r\n\
  <tr>\r\n\
    <td>{position}</td>\r\n\
    <td>{country}</td>\r\n\
    <td>{cities}</td>\r\n\
    <td>{population}</td>\r\n\
  </tr>".
        of({ position: index + 1, country: country,
             cities: cities.map(function(city) { return city.name; }).join(", "),
             population: cities.reduce(function(sum, city) { return sum += city.pop; }, 0)
           });
    })
  );

... gives:

<table>
  <tr>
    <th>Position</th>
    <th>Country</th>
    <th>City List</th>
    <th>Population</th>
  </tr>
  <tr>
    <td>1</td>
    <td>Italia</td>
    <td>Milano, Venezia</td>
    <td>6</td>
  </tr>
  <tr>
    <td>2</td>
    <td>France</td>
    <td>Lyon, Paris</td>
    <td>9</td>
  </tr>
  <tr>
    <td>3</td>
    <td>Deutschland</td>
    <td>München</td>
    <td>4</td>
  </tr>
</table>

4. JSONiq vs. JavaScript:

A JavaScript equivalent of...

JSONiq Use Cases Section 1.1.2. Grouping Queries for JSON

(at: https://jsfiddle.net/YSharpLanguage/hvo24hmk/3)

Cf. http://jsoniq.org/docs/JSONiq-usecases/html-single/index.html#jsongrouping

where...

/*
  1.1.2. Grouping Queries for JSON
  http://jsoniq.org/docs/JSONiq-usecases/html-single/index.html#jsongrouping
*/
var sales = [
  { "product" : "broiler", "store number" : 1, "quantity" : 20  },
  { "product" : "toaster", "store number" : 2, "quantity" : 100 },
  { "product" : "toaster", "store number" : 2, "quantity" : 50 },
  { "product" : "toaster", "store number" : 3, "quantity" : 50 },
  { "product" : "blender", "store number" : 3, "quantity" : 100 },
  { "product" : "blender", "store number" : 3, "quantity" : 150 },
  { "product" : "socks", "store number" : 1, "quantity" : 500 },
  { "product" : "socks", "store number" : 2, "quantity" : 10 },
  { "product" : "shirt", "store number" : 3, "quantity" : 10 }
];

var products = [
  { "name" : "broiler", "category" : "kitchen", "price" : 100, "cost" : 70 },
  { "name" : "toaster", "category" : "kitchen", "price" : 30, "cost" : 10 },
  { "name" : "blender", "category" : "kitchen", "price" : 50, "cost" : 25 },
  {  "name" : "socks", "category" : "clothes", "price" : 5, "cost" : 2 },
  { "name" : "shirt", "category" : "clothes", "price" : 10, "cost" : 3 }
];

var stores = [
  { "store number" : 1, "state" : "CA" },
  { "store number" : 2, "state" : "CA" },
  { "store number" : 3, "state" : "MA" },
  { "store number" : 4, "state" : "MA" }
];

var nestedGroupingAndAggregate = stores.select().orderBy("state").groupBy("state")
( function(byState) {
    var state = byState[0],
        stateStores = byState[1];
    byState = { };
    return (
      (
        byState[state] =
        products.select().orderBy("category").groupBy("category")
        ( function(byCategory) {
            var category = byCategory[0],
                categoryProducts = byCategory[1],
                categorySales = sales.filter(function(sale) {
                  return stateStores.find(function(store) { return sale["store number"] === store["store number"]; }) &&
                         categoryProducts.find(function(product) { return sale.product === product.name; });
                });
            byCategory = { };
            return (
              (
                byCategory[category] =
                categorySales.select().orderBy("product").groupBy("product")
                ( function(byProduct) {
                    var soldProduct = byProduct[0],
                        soldQuantities = byProduct[1];
                    byProduct = { };
                    return (
                      (
                        byProduct[soldProduct] =
                        soldQuantities.reduce(function(sum, sale) { return sum += sale.quantity; }, 0)
                      ),
                      byProduct
                    );
                } ) // byProduct()
              ),
              byCategory
            );
        } ) // byCategory()
      ),
      byState
    );
} ); // byState()

... gives:

[
  {
    "CA": [
      {
        "clothes": [
          {
            "socks": 510
          }
        ]
      },
      {
        "kitchen": [
          {
            "broiler": 20
          },
          {
            "toaster": 150
          }
        ]
      }
    ]
  },
  {
    "MA": [
      {
        "clothes": [
          {
            "shirt": 10
          }
        ]
      },
      {
        "kitchen": [
          {
            "blender": 250
          },
          {
            "toaster": 50
          }
        ]
      }
    ]
  }
]

It is also useful to overcome the limitations of JSONPath wrt. querying against the ancestor axis, as raised by this SO question (and certainly others).

E.g., how to get the discount of a grocery item knowing its brand id, in

{
 "prods": [
    {
        "info": {
              "rate": 85
                },
        "grocery": [
                 {
                  "brand": "C",
                  "brand_id": "984"
                 },
                 {
                  "brand": "D",
                  "brand_id": "254"
                 }
                 ],
         "discount": "15"
    },
    {
        "info": {
              "rate": 100
                },
        "grocery": [
                 {
                  "brand": "A",
                  "brand_id": "983"
                 },
                 {
                  "brand": "B",
                  "brand_id": "253"
                 }
                 ],
         "discount": "20"
     }
 ]
}

?

A possible solution is:

var products = {
     "prods": [
        {
            "info": {
                  "rate": 85
                    },
            "grocery": [
                     {
                      "brand": "C",
                      "brand_id": "984"
                     },
                     {
                      "brand": "D",
                      "brand_id": "254"
                     }
                     ],
             "discount": "15"
        },
        {
            "info": {
                  "rate": 100
                    },
            "grocery": [
                     {
                      "brand": "A",
                      "brand_id": "983"
                     },
                     {
                      "brand": "B",
                      "brand_id": "253"
                     }
                     ],
             "discount": "20"
         }
     ]
};

function GroceryItem(obj) {
  return (typeof obj.brand === "string") && (typeof obj.brand_id === "string");
}

    // last parameter set to "true", to grab all the "GroceryItem" instances
    // at any depth:
var itemsAndDiscounts = [ products ].nodeset(GroceryItem, true).
    map(
      function(node) {
        var item = node.value, // node.value: the current "GroceryItem" (aka "$.prods[*].grocery[*]")

            discount = node.parent. // node.parent: the array of "GroceryItem" (aka "$.prods[*].grocery")
                       parent. // node.parent.parent: the product (aka "$.prods[*]")
                       discount; // node.parent.parent.discount: the product discount

        // finally, project into an easy-to-filter form:
        return { id: item.brand_id, discount: discount };
      }
    ),
    discountOfItem983;

discountOfItem983 = itemsAndDiscounts.
  filter
  (
    function(mapped) {
      return mapped.id === "983";
    }
  )
  [0].discount;

console.log("Discount of #983: " + discountOfItem983);

... which gives:

Discount of #983: 20

'HTH,

How to copy file from host to container using Dockerfile

I got the following error using Docker 19.03.8 on CentOS 7:

COPY failed: stat /var/lib/docker/tmp/docker-builderXXXXXXX/abc.txt: no such file or directory

The solution for me was to build from Docker file with docker build . instead of docker build - < Dockerfile.

What are the rules about using an underscore in a C++ identifier?

The rules (which did not change in C++11):

  • Reserved in any scope, including for use as implementation macros:
    • identifiers beginning with an underscore followed immediately by an uppercase letter
    • identifiers containing adjacent underscores (or "double underscore")
  • Reserved in the global namespace:
    • identifiers beginning with an underscore
  • Also, everything in the std namespace is reserved. (You are allowed to add template specializations, though.)

From the 2003 C++ Standard:

17.4.3.1.2 Global names [lib.global.names]

Certain sets of names and function signatures are always reserved to the implementation:

  • Each name that contains a double underscore (__) or begins with an underscore followed by an uppercase letter (2.11) is reserved to the implementation for any use.
  • Each name that begins with an underscore is reserved to the implementation for use as a name in the global namespace.165

165) Such names are also reserved in namespace ::std (17.4.3.1).

Because C++ is based on the C standard (1.1/2, C++03) and C99 is a normative reference (1.2/1, C++03) these also apply, from the 1999 C Standard:

7.1.3 Reserved identifiers

Each header declares or defines all identifiers listed in its associated subclause, and optionally declares or defines identifiers listed in its associated future library directions subclause and identifiers which are always reserved either for any use or for use as file scope identifiers.

  • All identifiers that begin with an underscore and either an uppercase letter or another underscore are always reserved for any use.
  • All identifiers that begin with an underscore are always reserved for use as identifiers with file scope in both the ordinary and tag name spaces.
  • Each macro name in any of the following subclauses (including the future library directions) is reserved for use as specified if any of its associated headers is included; unless explicitly stated otherwise (see 7.1.4).
  • All identifiers with external linkage in any of the following subclauses (including the future library directions) are always reserved for use as identifiers with external linkage.154
  • Each identifier with file scope listed in any of the following subclauses (including the future library directions) is reserved for use as a macro name and as an identifier with file scope in the same name space if any of its associated headers is included.

No other identifiers are reserved. If the program declares or defines an identifier in a context in which it is reserved (other than as allowed by 7.1.4), or defines a reserved identifier as a macro name, the behavior is undefined.

If the program removes (with #undef) any macro definition of an identifier in the first group listed above, the behavior is undefined.

154) The list of reserved identifiers with external linkage includes errno, math_errhandling, setjmp, and va_end.

Other restrictions might apply. For example, the POSIX standard reserves a lot of identifiers that are likely to show up in normal code:

  • Names beginning with a capital E followed a digit or uppercase letter:
    • may be used for additional error code names.
  • Names that begin with either is or to followed by a lowercase letter
    • may be used for additional character testing and conversion functions.
  • Names that begin with LC_ followed by an uppercase letter
    • may be used for additional macros specifying locale attributes.
  • Names of all existing mathematics functions suffixed with f or l are reserved
    • for corresponding functions that operate on float and long double arguments, respectively.
  • Names that begin with SIG followed by an uppercase letter are reserved
    • for additional signal names.
  • Names that begin with SIG_ followed by an uppercase letter are reserved
    • for additional signal actions.
  • Names beginning with str, mem, or wcs followed by a lowercase letter are reserved
    • for additional string and array functions.
  • Names beginning with PRI or SCN followed by any lowercase letter or X are reserved
    • for additional format specifier macros
  • Names that end with _t are reserved
    • for additional type names.

While using these names for your own purposes right now might not cause a problem, they do raise the possibility of conflict with future versions of that standard.


Personally I just don't start identifiers with underscores. New addition to my rule: Don't use double underscores anywhere, which is easy as I rarely use underscore.

After doing research on this article I no longer end my identifiers with _t as this is reserved by the POSIX standard.

The rule about any identifier ending with _t surprised me a lot. I think that is a POSIX standard (not sure yet) looking for clarification and official chapter and verse. This is from the GNU libtool manual, listing reserved names.

CesarB provided the following link to the POSIX 2004 reserved symbols and notes 'that many other reserved prefixes and suffixes ... can be found there'. The POSIX 2008 reserved symbols are defined here. The restrictions are somewhat more nuanced than those above.

How to create a table from select query result in SQL Server 2008

Please be careful, MSSQL: "SELECT * INTO NewTable FROM OldTable"

is not always the same as MYSQL: "create table temp AS select.."

I think that there are occasions when this (in MSSQL) does not guarantee that all the fields in the new table are of the same type as the old.

For example :

create table oldTable (field1 varchar(10), field2 integer, field3 float)
insert into oldTable (field1,field2,field3) values ('1', 1, 1)
select top 1 * into newTable from oldTable

does not always yield:

create table newTable (field1 varchar(10), field2 integer, field3 float)

but may be:

create table newTable (field1 varchar(10), field2 integer, field3 integer)

jQuery: serialize() form and other parameters

I dont know but none of the above worked for me, Then i used this and it worked :

In form's serialized array it is stored as key value pair

We pushed the new value or values here in form variable and then we can pass this variable directly now.

var form = $('form.sigPad').serializeArray();
var uniquekey = {
      name: "uniquekey",
      value: $('#UniqueKey').val()
};
form.push(uniquekey);

Message "Async callback was not invoked within the 5000 ms timeout specified by jest.setTimeout"

// In jest.setup.js
jest.setTimeout(30000)

If on Jest <= 23:

// In jest.config.js
module.exports = {
  setupTestFrameworkScriptFile: './jest.setup.js'
}

If on Jest > 23:

// In jest.config.js
module.exports = {
  setupFilesAfterEnv: ['./jest.setup.js']
}

How to change the CHARACTER SET (and COLLATION) throughout a database?

change database collation:

ALTER DATABASE <database_name> CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci;

change table collation:

ALTER TABLE <table_name> CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci;

change column collation:

ALTER TABLE <table_name> MODIFY <column_name> VARCHAR(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci;

What do the parts of utf8mb4_0900_ai_ci mean?

3 bytes -- utf8
4 bytes -- utf8mb4 (new)
v4.0 --   _unicode_
v5.20 --  _unicode_520_
v9.0 --   _0900_ (new)
_bin      -- just compare the bits; don't consider case folding, accents, etc
_ci       -- explicitly case insensitive (A=a) and implicitly accent insensitive (a=á)
_ai_ci    -- explicitly case insensitive and accent insensitive
_as (etc) -- accent-sensitive (etc)
_bin         -- simple, fast
_general_ci  -- fails to compare multiple letters; eg ss=ß, somewhat fast
...          -- slower
_0900_       -- (8.0) much faster because of a rewrite

More info:

How do I write stderr to a file while using "tee" with a pipe?

I'm assuming you want to still see STDERR and STDOUT on the terminal. You could go for Josh Kelley's answer, but I find keeping a tail around in the background which outputs your log file very hackish and cludgy. Notice how you need to keep an exra FD and do cleanup afterward by killing it and technically should be doing that in a trap '...' EXIT.

There is a better way to do this, and you've already discovered it: tee.

Only, instead of just using it for your stdout, have a tee for stdout and one for stderr. How will you accomplish this? Process substitution and file redirection:

command > >(tee -a stdout.log) 2> >(tee -a stderr.log >&2)

Let's split it up and explain:

> >(..)

>(...) (process substitution) creates a FIFO and lets tee listen on it. Then, it uses > (file redirection) to redirect the STDOUT of command to the FIFO that your first tee is listening on.

Same thing for the second:

2> >(tee -a stderr.log >&2)

We use process substitution again to make a tee process that reads from STDIN and dumps it into stderr.log. tee outputs its input back on STDOUT, but since its input is our STDERR, we want to redirect tee's STDOUT to our STDERR again. Then we use file redirection to redirect command's STDERR to the FIFO's input (tee's STDIN).

See http://mywiki.wooledge.org/BashGuide/InputAndOutput

Process substitution is one of those really lovely things you get as a bonus of choosing bash as your shell as opposed to sh (POSIX or Bourne).


In sh, you'd have to do things manually:

out="${TMPDIR:-/tmp}/out.$$" err="${TMPDIR:-/tmp}/err.$$"
mkfifo "$out" "$err"
trap 'rm "$out" "$err"' EXIT
tee -a stdout.log < "$out" &
tee -a stderr.log < "$err" >&2 &
command >"$out" 2>"$err"

How to save username and password with Mercurial?

You can make an auth section in your .hgrc or Mercurial.ini file, like so:

[auth]
bb.prefix = https://bitbucket.org/repo/path
bb.username = foo
bb.password = foo_passwd

The ‘bb’ part is an arbitrary identifier and is used to match prefix with username and password - handy for managing different username/password combos with different sites (prefix)

You can also only specify the user name, then you will just have to type your password when you push.

I would also recommend to take a look at the keyring extension. Because it stores the password in your system’s key ring instead of a plain text file, it is more secure. It is bundled with TortoiseHg on Windows, and there is currently a discussion about distributing it as a bundled extension on all platforms.

Set maxlength in Html Textarea

$(function(){  
  $("#id").keypress(function() {  
    var maxlen = 100;
    if ($(this).val().length > maxlen) {  
      return false;
    }  
  })
});  

IntelliJ, can't start simple web application: Unable to ping server at localhost:1099

In windows environment just check the PATH environment variable if Oracle JRE runtime refreshed the path and put himself at the very beginning of the path. In this case even if the JAVA_HOME AND JRE_HOME points to the correct JDK, the JRE will have precedence. And this case IntelliJ will not start Tomcat instance with the mentioned error message.

What is the difference between supervised learning and unsupervised learning?

Supervised Learning: You give variously labelled example data as input, along with the correct answers. This algorithm will learn from it, and start predicting correct results based on the inputs thereafter. Example: Email Spam filter

Unsupervised Learning: You just give data and don't tell anything - like labels or correct answers. Algorithm automatically analyses patterns in the data. Example: Google News

Fatal error: Class 'PHPMailer' not found

PHPMailerAutoload needs to be in the same folder as class.phpmailer.php

This is the PHPMailerAutoload code that I assume this:

 $filename = dirname(__FILE__).DIRECTORY_SEPARATOR.'class.'.strtolower($classname).'.php';

Spring Data JPA findOne() change to Optional how to use this?

I always write a default method "findByIdOrError" in widely used CrudRepository repos/interfaces.

@Repository 
public interface RequestRepository extends CrudRepository<Request, Integer> {

    default Request findByIdOrError(Integer id) {
        return findById(id).orElseThrow(EntityNotFoundException::new);
    } 
}

How to make child process die after parent exits?

I have achieved this in the past by running the "original" code in the "child" and the "spawned" code in the "parent" (that is: you reverse the usual sense of the test after fork()). Then trap SIGCHLD in the "spawned" code...

May not be possible in your case, but cute when it works.

Python AttributeError: 'module' object has no attribute 'Serial'

I accidentally installed 'serial' (sudo python -m pip install serial) instead of 'pySerial' (sudo python -m pip install pyserial), which lead to the same error.

If the previously mentioned solutions did not work for you, double check if you installed the correct library.

Spring MVC + JSON = 406 Not Acceptable

See the problem is with the extension. Depending upon the extension, spring could figure out the content-type. If your url ends with .com then it sends text/html as the content-type header. If you want to change this behavior of Spring, please use the below code:

@Configuration
@Import(HibernateConfig.class)
@EnableWebMvc
// @EnableAsync()
// @EnableAspectJAutoProxy
@ComponentScan(basePackages = "com.azim.web.service.*",  basePackageClasses = { WebSecurityConfig.class }, excludeFilters = { @ComponentScan.Filter(Configuration.class) })
public class WebConfig extends WebMvcConfigurerAdapter {

    @Override
    public void configureContentNegotiation(ContentNegotiationConfigurer configurer) {
        configurer.favorPathExtension(false).favorParameter(true).parameterName("mediaType").ignoreAcceptHeader(true).useJaf(false)
                .defaultContentType(MediaType.APPLICATION_JSON).mediaType("xml", MediaType.APPLICATION_XML).mediaType("json", MediaType.APPLICATION_JSON);
    }

    @Bean(name = "validator")
    public Validator validator() {
        return new LocalValidatorFactoryBean();
    }
}

Here, we are setting favorPathExtension to false and Default Content-type to Application/json. Note: HibernateConfig class contains all the beans.

Adding a UISegmentedControl to UITableView

   self.tableView.tableHeaderView = segmentedControl; 

If you want it to obey your width and height properly though enclose your segmentedControl in a UIView first as the tableView likes to mangle your view a bit to fit the width.

enter image description here enter image description here

Select from one table where not in another

You can LEFT JOIN the two tables. If there is no corresponding row in the second table, the values will be NULL.

SELECT id FROM partmaster LEFT JOIN product_details ON (...) WHERE product_details.part_num IS NULL

SQL: Combine Select count(*) from multiple tables

SELECT 
(select count(*) from foo1 where ID = '00123244552000258')
+
(select count(*) from foo2 where ID = '00123244552000258')
+
(select count(*) from foo3 where ID = '00123244552000258')

This is an easy way.

Calling one method from another within same class in Python

To call the method, you need to qualify function with self.. In addition to that, if you want to pass a filename, add a filename parameter (or other name you want).

class MyHandler(FileSystemEventHandler):

    def on_any_event(self, event):
        srcpath = event.src_path
        print (srcpath, 'has been ',event.event_type)
        print (datetime.datetime.now())
        filename = srcpath[12:]
        self.dropbox_fn(filename) # <----

    def dropbox_fn(self, filename):  # <-----
        print('In dropbox_fn:', filename)

Add alternating row color to SQL Server Reporting services report

I have changed @Catch22's solution A bit as I do not like the idea of having to go into each field if I decide I want to change one of the colors. This is especially important in reports where the are numerous fields that would need to have the color variable changed.

'*************************************************************************
' -- Display alternate color banding (defined below) in detail rows
' -- Call from BackgroundColor property of all detail row textboxes
'*************************************************************************
Function AlternateColor(Byval rowNumber as integer) As String
    Dim OddColor As String = "Green"
    Dim EvenColor As String = "White"

    If rowNumber mod 2 = 0 then 
        Return EvenColor
    Else
        Return OddColor
    End If
End Function

Noticed that I have change the function from one that accepts the colors to one that contains the colors to be used.

Then in each field add:

=Code.AlternateColor(rownumber(nothing))

This is much more robust than manually changing the color in each fields' background color.

How do you count the elements of an array in java

If you wish to have an Array in which you will not be allocating all of the elements, you will have to do your own bookkeeping to ensure how many elements you have placed in it via some other variable. If you'd like to avoid doing this while also getting an "Array" that can grow capacities after its initial instantiation, you can create an ArrayList

ArrayList<Integer> theArray = new ArrayList<Integer>();
theArray.add(5); // places at index 0
theArray.size(); // returns length of 1
int answer = theArray.get(0); // index 0 = 5

Don't forget to import it at the top of the file:

import java.util.ArrayList;

glob exclude pattern

How about skipping the particular file while iterating over all the files in the folder! Below code would skip all excel files that start with 'eph'

import glob
import re
for file in glob.glob('*.xlsx'):
    if re.match('eph.*\.xlsx',file):
        continue
    else:
        #do your stuff here
        print(file)

This way you can use more complex regex patterns to include/exclude a particular set of files in a folder.

Styling text input caret

'Caret' is the word you are looking for. I do believe though, that it is part of the browsers design, and not within the grasp of css.

However, here is an interesting write up on simulating a caret change using Javascript and CSS http://www.dynamicdrive.com/forums/showthread.php?t=17450 It seems a bit hacky to me, but probably the only way to accomplish the task. The main point of the article is:

We will have a plain textarea somewhere in the screen out of the view of the viewer and when the user clicks on our "fake terminal" we will focus into the textarea and when the user starts typing we will simply append the data typed into the textarea to our "terminal" and that's that.

HERE is a demo in action


2018 update

There is a new css property caret-color which applies to the caret of an input or contenteditable area. The support is growing but not 100%, and this only affects color, not width or other types of appearance.

_x000D_
_x000D_
input{_x000D_
  caret-color: rgb(0, 200, 0);_x000D_
}
_x000D_
<input type="text"/>
_x000D_
_x000D_
_x000D_

How to install the current version of Go in Ubuntu Precise

[Updated (previous answer no longer applied)]

For fetching the latest version:

sudo add-apt-repository ppa:longsleep/golang-backports
sudo apt update
sudo apt install golang-go

Also see the wiki

How to link to specific line number on github

Don't just link to the line numbers! Be sure to use the canonical URL too. Otherwise when that file is updated, you'll have a URL that points to the wrong lines!

How to make a permanent link to the right lines:

Click on the line number you want (like line 18), and the URL in your browser will get a #L18 tacked onto the end. You literally click on the 18 at the left side, not the line of code. Looks like this:

line 18 selected

And now your browser's URL looks like this:

https://github.com/git/git/blob/master/README#L18

If you want multiple lines selected, simply hold down the shift key and click a second line number, like line 20. Looks like this:

enter image description here

And now your browser's URL looks like this:

https://github.com/git/git/blob/master/README#L18-L20

Here's the important part:

Now get the canonical url for that particular commit by pressing the y key. The URL in your browser will change to become something like this:

https://github.com/git/git/blob/5bdb7a78adf2a2656a1915e6fa656aecb45c1fc3/README#L18-L20

That link contains the actual SHA hash for that particular commit, rather than the current version of the file on master. That means that this link will work forever and not point to lines 18-20 of whatever future version of that file might contain.

Now bask in the glow of your new permanent link. ;-)

update 9/29/2017: As pointed out by @watashiSHUN, github has now made it easier to get the permanent link by providing a ... menu on the left after you select one or more lines. Please upvote @watashiSHUN's answer too.

GitHub permalink menu

update 3/25/2016: Case in point — in the example above, I referred to the "README" file in the URL. Those non-canonical urls actually worked when this answer was written. But now those urls no longer work since README was moved to README.md. But the canonical URL with SHA hash still works, just as expected.

Checking on a thread / remove from list

Better way is to use Queue class: http://docs.python.org/library/queue.html

Look at the good example code in the bottom of documentation page:

def worker():
    while True:
        item = q.get()
        do_work(item)
        q.task_done()

q = Queue()
for i in range(num_worker_threads):
     t = Thread(target=worker)
     t.daemon = True
     t.start()

for item in source():
    q.put(item)

q.join()       # block until all tasks are done

How do you change the text in the Titlebar in Windows Forms?

You can change the text in the titlebar in Windows Forms by using the Text property.

For C#

// This class is added to the namespace containing the Form1 class.
class MainApplication
{
   public static void Main()
   {
      // Instantiate a new instance of Form1.
      Form1 f1 = new Form1();

      // Display a messagebox. This shows the application
      // is running, yet there is nothing shown to the user.
      // This is the point at which you customize your form.
      System.Windows.Forms.MessageBox.Show("The application "
         + "is running now, but no forms have been shown.");

      // Customize the form.
      f1.Text = "Running Form";

      // Show the instance of the form modally.
      f1.ShowDialog();
   }
}

for each loop in groovy

Your code works fine.

def list = [["c":"d"], ["e":"f"], ["g":"h"]]
Map tmpHM = [1:"second (e:f)", 0:"first (c:d)", 2:"third (g:h)"]

for (objKey in tmpHM.keySet()) {   
    HashMap objHM = (HashMap) list.get(objKey);
    print("objHM: ${objHM}  , ")
}

prints objHM: [e:f] , objHM: [c:d] , objHM: [g:h] ,

See https://groovyconsole.appspot.com/script/5135817529884672

Then click "edit in console", "execute script"

bootstrap multiselect get selected values

In my case i was using jQuery validation rules with

submitHandler function and submitting the data as new FormData(form);

Select Option

<select class="selectpicker" id="branch" name="branch" multiple="multiple" title="Of Branch" data-size="6" required>
  <option disabled>Multiple Branch Select</option>
  <option value="Computer">Computer</option>
  <option value="Civil">Civil</option>
  <option value="EXTC">EXTC</option>
  <option value="ETRX">ETRX</option>
  <option value="Mechinical">Mechinical</option>
</select>

<input type="hidden" name="new_branch" id="new_branch">

Get the multiple selected value and set to new_branch input value & while submitting the form get value from new_branch

Just replace hidden with text to view on the output

<input type="text" name="new_branch" id="new_branch">

Script (jQuery / Ajax)

<script>
    $(document).ready(function() {

      $('#branch').on('change', function(){
          var selected = $(this).find("option:selected"); //get current selected value
          var arrSelected = []; //Array to store your multiple value in stack
          selected.each(function(){
            arrSelected.push($(this).val()); //Stack the value
          });
          $('#new_branch').val(arrSelected); //It will set the multiple selected value to input new_branch
      });

    });
</script>

javascript change background color on click

You can sets the body's background colour using document.body.style.backgroundColor = "red"; so this can be put into a function that's called when the user clicks. The next part can be done by using document.getElementByID("divID").style.backgroundColor = "red"; window.setTimeout("yourFunction()",10000); which calls yourFunction in 10 seconds to change the colour back.

C# Java HashMap equivalent

Check out the documentation on MSDN for the Hashtable class.

Represents a collection of key-and-value pairs that are organized based on the hash code of the key.

Also, keep in mind that this is not thread-safe.

Force index use in Oracle

You can use optimizer hints

select /*+ INDEX(table_name index_name) */ from table etc...

More on using optimizer hints: http://download.oracle.com/docs/cd/B19306_01/server.102/b14211/hintsref.htm

How to do error logging in CodeIgniter (PHP)

To simply put a line in the server's error log, use PHP's error_log() function. However, that method will not send an e-mail.

First, to trigger an error:

trigger_error("Error message here", E_USER_ERROR);

By default, this will go in the server's error log file. See the ErrorLog directive for Apache. To set your own log file:

ini_set('error_log', 'path/to/log/file');

Note that the log file you choose must already exist and be writable by the server process. The simplest way to make the file writable is to make the server user the owner of the file. (The server user may be nobody, _www, apache, or something else, depending on your OS distribution.)

To e-mail the error, you need to set up a custom error handler:

function mail_error($errno, $errstr, $errfile, $errline) {
  $message = "[Error $errno] $errstr - Error on line $errline in file $errfile";
  error_log($message); // writes the error to the log file
  mail('[email protected]', 'I have an error', $message);
}
set_error_handler('mail_error', E_ALL^E_NOTICE);

Please see the relevant PHP documentation for more info.

Get selected value/text from Select on change

_x000D_
_x000D_
function test(a) {_x000D_
    var x = (a.value || a.options[a.selectedIndex].value);  //crossbrowser solution =)_x000D_
    alert(x);_x000D_
}
_x000D_
<select onchange="test(this)" id="select_id">_x000D_
    <option value="0">-Select-</option>_x000D_
    <option value="1">Communication</option>_x000D_
    <option value="2">Communication</option>_x000D_
    <option value="3">Communication</option>_x000D_
</select>
_x000D_
_x000D_
_x000D_

What is the difference between JOIN and JOIN FETCH when using JPA and Hibernate

JOIN

When using JOIN against an entity associations, JPA will generate a JOIN between the parent entity and the child entity tables in the generated SQL statement.

So, taking your example, when executing this JPQL query:

FROM Employee emp
JOIN emp.department dep

Hibernate is going to generate the following SQL statement:

SELECT emp.*
FROM employee emp
JOIN department dep ON emp.department_id = dep.id

Note that the SQL SELECT clause contains only the employee table columns, and not the department ones. To fetch the department table columns, we need to use JOIN FETCH instead of JOIN.

JOIN FETCH

So, compared to JOIN, the JOIN FETCH allows you to project the joining table columns in the SELECT clause of the generated SQL statement.

So, in your example, when executing this JPQL query:

FROM Employee emp
JOIN FETCH emp.department dep

Hibernate is going to generate the following SQL statement:

SELECT emp.*, dept.*
FROM employee emp
JOIN department dep ON emp.department_id = dep.id

Note that, this time, the department table columns are selected as well, not just the ones associated with the entity listed in the FROM JPQL clause.

Also, JOIN FETCH is a great way to address the LazyInitializationException when using Hibernate as you can initialize entity associations using the FetchType.LAZY fetching strategy along with the main entity you are fetching.

How to remove focus around buttons on click

For AngularJS developers I use from the solution:

var element = $window.document.getElementById("export-button");
    if (element){
        element.blur();
    }

Remember to inject $window.

How to change maven logging level to display only warning and errors?

you can achieve this by using below in the commandline itself

_x000D_
_x000D_
 -e for error_x000D_
-X for debug_x000D_
-q for only error
_x000D_
_x000D_
_x000D_

e.g :

_x000D_
_x000D_
mvn test -X -DsomeProperties='SomeValue' [For Debug level Logs]_x000D_
mvn test -e -DsomeProperties='SomeValue' [For Error level Logs]_x000D_
mvn test -q -DsomeProperties='SomeValue' [For Only Error Logs]
_x000D_
_x000D_
_x000D_

Entity Framework: One Database, Multiple DbContexts. Is this a bad idea?

Another bit of "wisdom". I have a database facing both, the internet and an internal app. I have a context for each face. That helps me to keep a disciplined, secured segregation.

Change label text using JavaScript

Because the script will get executed first.. When the script will get executed, at that time controls are not getting loaded. So after loading controls you write a script.

It will work.

CMD: Export all the screen content to a text file

Just see this page

in cmd type:

Command | clip

Then open a *.Txt file and Paste. That's it. Done.

Making macOS Installer Packages which are Developer ID ready

There is one very interesting application by Stéphane Sudre which does all of this for you, is scriptable / supports building from the command line, has a super nice GUI and is FREE. Sad thing is: it's called "Packages" which makes it impossible to find in google.

http://s.sudre.free.fr/Software/Packages/about.html

I wished I had known about it before I started handcrafting my own scripts.

Packages application screenshot

Change Active Menu Item on Page Scroll?

It's done by binding to the scroll event of the container (usually window).

Quick example:

// Cache selectors
var topMenu = $("#top-menu"),
    topMenuHeight = topMenu.outerHeight()+15,
    // All list items
    menuItems = topMenu.find("a"),
    // Anchors corresponding to menu items
    scrollItems = menuItems.map(function(){
      var item = $($(this).attr("href"));
      if (item.length) { return item; }
    });

// Bind to scroll
$(window).scroll(function(){
   // Get container scroll position
   var fromTop = $(this).scrollTop()+topMenuHeight;

   // Get id of current scroll item
   var cur = scrollItems.map(function(){
     if ($(this).offset().top < fromTop)
       return this;
   });
   // Get the id of the current element
   cur = cur[cur.length-1];
   var id = cur && cur.length ? cur[0].id : "";
   // Set/remove active class
   menuItems
     .parent().removeClass("active")
     .end().filter("[href='#"+id+"']").parent().addClass("active");
});?

See the above in action at jsFiddle including scroll animation.

ExecutorService, how to wait for all tasks to finish

Just use

latch = new CountDownLatch(noThreads)

In each thread

latch.countDown();

and as barrier

latch.await();

How to draw a standard normal distribution in R

Something like this perhaps?

x<-rnorm(100000,mean=10, sd=2)
hist(x,breaks=150,xlim=c(0,20),freq=FALSE)
abline(v=10, lwd=5)
abline(v=c(4,6,8,12,14,16), lwd=3,lty=3)

Turning Sonar off for certain code

I recommend you try to suppress specific warnings by using @SuppressWarnings("squid:S2078").

For suppressing multiple warnings you can do it like this @SuppressWarnings({"squid:S2078", "squid:S2076"})

There is also the //NOSONAR comment that tells SonarQube to ignore all errors for a specific line.

Finally if you have the proper rights for the user interface you can issue a flag as a false positive directly from the interface.

The reason why I recommend suppression of specific warnings is that it's a better practice to block a specific issue instead of using //NOSONAR and risk a Sonar issue creeping in your code by accident.

You can read more about this in the FAQ

Edit: 6/30/16 SonarQube is now called SonarLint

In case you are wondering how to find the squid number. Just click on the Sonar message (ex. Remove this method to simply inherit it.) and the Sonar issue will expand.

On the bottom left it will have the squid number (ex. squid:S1185 Maintainability > Understandability)

So then you can suppress it by @SuppressWarnings("squid:S1185")

Ansible playbook shell output

I found using the minimal stdout_callback with ansible-playbook gave similar output to using ad-hoc ansible.

In your ansible.cfg (Note that I'm on OS X so modify the callback_plugins path to suit your install)

stdout_callback     = minimal
callback_plugins    = /Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/ansible/plugins/callback

So that a ansible-playbook task like yours

---
-
  hosts: example
  gather_facts: no
  tasks:
    - shell: ps -eo pcpu,user,args | sort -r -k1 | head -n5

Gives output like this, like an ad-hoc command would

example | SUCCESS | rc=0 >>
%CPU USER     COMMAND
 0.2 root     sshd: root@pts/3
 0.1 root     /usr/sbin/CROND -n
 0.0 root     [xfs-reclaim/vda]
 0.0 root     [xfs_mru_cache]

I'm using ansible-playbook 2.2.1.0