Programs & Examples On #Double

Double precision floating-point format is a (most often) 64 bit data type used for storing fractional numbers.

Swift double to string

In swift 3 it is simple as given below

let stringDouble =  String(describing: double)

Convert float to double without losing precision

It's not that you're actually getting extra precision - it's that the float didn't accurately represent the number you were aiming for originally. The double is representing the original float accurately; toString is showing the "extra" data which was already present.

For example (and these numbers aren't right, I'm just making things up) suppose you had:

float f = 0.1F;
double d = f;

Then the value of f might be exactly 0.100000234523. d will have exactly the same value, but when you convert it to a string it will "trust" that it's accurate to a higher precision, so won't round off as early, and you'll see the "extra digits" which were already there, but hidden from you.

When you convert to a string and back, you're ending up with a double value which is closer to the string value than the original float was - but that's only good if you really believe that the string value is what you really wanted.

Are you sure that float/double are the appropriate types to use here instead of BigDecimal? If you're trying to use numbers which have precise decimal values (e.g. money), then BigDecimal is a more appropriate type IMO.

Dealing with float precision in Javascript

> var x = 0.1
> var y = 0.2
> var cf = 10
> x * y
0.020000000000000004
> (x * cf) * (y * cf) / (cf * cf)
0.02

Quick solution:

var _cf = (function() {
  function _shift(x) {
    var parts = x.toString().split('.');
    return (parts.length < 2) ? 1 : Math.pow(10, parts[1].length);
  }
  return function() { 
    return Array.prototype.reduce.call(arguments, function (prev, next) { return prev === undefined || next === undefined ? undefined : Math.max(prev, _shift (next)); }, -Infinity);
  };
})();

Math.a = function () {
  var f = _cf.apply(null, arguments); if(f === undefined) return undefined;
  function cb(x, y, i, o) { return x + f * y; }
  return Array.prototype.reduce.call(arguments, cb, 0) / f;
};

Math.s = function (l,r) { var f = _cf(l,r); return (l * f - r * f) / f; };

Math.m = function () {
  var f = _cf.apply(null, arguments);
  function cb(x, y, i, o) { return (x*f) * (y*f) / (f * f); }
  return Array.prototype.reduce.call(arguments, cb, 1);
};

Math.d = function (l,r) { var f = _cf(l,r); return (l * f) / (r * f); };

> Math.m(0.1, 0.2)
0.02

You can check the full explanation here.

Comparing double values in C#

Double (called float in some languages) is fraut with problems due to rounding issues, it's good only if you need approximate values.

The Decimal data type does what you want.

For reference decimal and Decimal are the same in .NET C#, as are the double and Double types, they both refer to the same type (decimal and double are very different though, as you've seen).

Beware that the Decimal data type has some costs associated with it, so use it with caution if you're looking at loops etc.

Converting double to string with N decimals, dot as decimal separator, and no thousand separator

double value = 3.14159D;
string v = value.ToString().Replace(",", ".");
Console.WriteLine(v);

Output: 3.14159

Python Replace \\ with \

There's no need to use replace for this.

What you have is a encoded string (using the string_escape encoding) and you want to decode it:

>>> s = r"Escaped\nNewline"
>>> print s
Escaped\nNewline
>>> s.decode('string_escape')
'Escaped\nNewline'
>>> print s.decode('string_escape')
Escaped
Newline
>>> "a\\nb".decode('string_escape')
'a\nb'

In Python 3:

>>> import codecs
>>> codecs.decode('\\n\\x21', 'unicode_escape')
'\n!'

Converting a double to an int in C#

ToInt32 rounds. Casting to int just throws away the non-integer component.

Round a double to 2 decimal places

Rounding a double is usually not what one wants. Instead, use String.format() to represent it in the desired format.

Formatting a double to two decimal places

I would recomment the Fixed-Point ("F") format specifier (as mentioned by Ehsan). See the Standard Numeric Format Strings.

With this option you can even have a configurable number of decimal places:

public string ValueAsString(double value, int decimalPlaces)
{
    return value.ToString($"F{decimalPlaces}");
}

How to implement infinity in Java?

Since the class Number is not final, here is an idea, that I don't find yet in the other posts. Namely to subclass the class Number.

This would somehow deliver an object that can be treated as infinity for Integer, Long, Double, Float, BigInteger and BigDecimal.

Since there are only two values, we could use the singleton pattern:

public final class Infinity extends Number {
    public final static Infinity POSITIVE = new Infinity(false);
    public final static Infinity NEGATIVE = new Infinity(true);
    private boolean negative;
    private Infinity(boolean n) {
        negative = n;
    }
}

Somehow I think the remaining methods intValue(), longValue() etc.. should then be overriden to throw an exceptions. So that the infinity value cannot be used without further precautions.

Double decimal formatting in Java

An alternative method is use the setMinimumFractionDigits method from the NumberFormat class.

Here you basically specify how many numbers you want to appear after the decimal point.

So an input of 4.0 would produce 4.00, assuming your specified amount was 2.

But, if your Double input contains more than the amount specified, it will take the minimum amount specified, then add one more digit rounded up/down

For example, 4.15465454 with a minimum amount of 2 specified will produce 4.155

NumberFormat nf = NumberFormat.getInstance();
nf.setMinimumFractionDigits(2);
Double myVal = 4.15465454;
System.out.println(nf.format(myVal));

Try it online

How to nicely format floating numbers to string without unnecessary decimal 0's

String s = "1.210000";
while (s.endsWith("0")){
    s = (s.substring(0, s.length() - 1));
}

This will make the string to drop the tailing 0-s.

Java double.MAX_VALUE?

Resurrecting the dead here, but just in case someone stumbles against this like myself. I know where to get the maximum value of a double, the (more) interesting part was to how did they get to that number.

double has 64 bits. The first one is reserved for the sign.

Next 11 represent the exponent (that is 1023 biased). It's just another way to represent the positive/negative values. If there are 11 bits then the max value is 1023.

Then there are 52 bits that hold the mantissa.

This is easily computed like this for example:

public static void main(String[] args) {

    String test = Strings.repeat("1", 52);

    double first = 0.5;
    double result = 0.0;
    for (char c : test.toCharArray()) {
        result += first;
        first = first / 2;
    }

    System.out.println(result); // close approximation of 1
    System.out.println(Math.pow(2, 1023) * (1 + result));
    System.out.println(Double.MAX_VALUE);

} 

You can also prove this in reverse order :

    String max = "0" + Long.toBinaryString(Double.doubleToLongBits(Double.MAX_VALUE));

    String sign = max.substring(0, 1);
    String exponent = max.substring(1, 12); // 11111111110
    String mantissa = max.substring(12, 64);

    System.out.println(sign); // 0 - positive
    System.out.println(exponent); // 2046 - 1023 = 1023
    System.out.println(mantissa); // 0.99999...8

Convert String to double in Java

Try this, BigDecimal bdVal = new BigDecimal(str);

If you want Double only then try Double d = Double.valueOf(str); System.out.println(String.format("%.3f", new BigDecimal(d)));

JAVA How to remove trailing zeros from a double

You should use DecimalFormat("0.#")


For 4.3000

Double price = 4.3000;
DecimalFormat format = new DecimalFormat("0.#");
System.out.println(format.format(price));

output is:

4.3

In case of 5.000 we have

Double price = 5.000;
DecimalFormat format = new DecimalFormat("0.#");
System.out.println(format.format(price));

And the output is:

5

How to return a value from try, catch, and finally?

The problem is what happens when you get NumberFormatexception thrown? You print it and return nothing.

Note: You don't need to catch and throw an Exception back. Usually it is done to wrap it or print stack trace and ignore for example.

catch(RangeException e) {
     throw e;
}

Scala Doubles, and Precision

A bit strange but nice. I use String and not BigDecimal

def round(x: Double)(p: Int): Double = {
    var A = x.toString().split('.')
    (A(0) + "." + A(1).substring(0, if (p > A(1).length()) A(1).length() else p)).toDouble
}

biggest integer that can be stored in a double

The biggest/largest integer that can be stored in a double without losing precision is the same as the largest possible value of a double. That is, DBL_MAX or approximately 1.8 × 10308 (if your double is an IEEE 754 64-bit double). It's an integer. It's represented exactly. What more do you want?

Go on, ask me what the largest integer is, such that it and all smaller integers can be stored in IEEE 64-bit doubles without losing precision. An IEEE 64-bit double has 52 bits of mantissa, so I think it's 253:

  • 253 + 1 cannot be stored, because the 1 at the start and the 1 at the end have too many zeros in between.
  • Anything less than 253 can be stored, with 52 bits explicitly stored in the mantissa, and then the exponent in effect giving you another one.
  • 253 obviously can be stored, since it's a small power of 2.

Or another way of looking at it: once the bias has been taken off the exponent, and ignoring the sign bit as irrelevant to the question, the value stored by a double is a power of 2, plus a 52-bit integer multiplied by 2exponent - 52. So with exponent 52 you can store all values from 252 through to 253 - 1. Then with exponent 53, the next number you can store after 253 is 253 + 1 × 253 - 52. So loss of precision first occurs with 253 + 1.

How do you test to see if a double is equal to NaN?

You might want to consider also checking if a value is finite via Double.isFinite(value). Since Java 8 there is a new method in Double class where you can check at once if a value is not NaN and infinity.

/**
 * Returns {@code true} if the argument is a finite floating-point
 * value; returns {@code false} otherwise (for NaN and infinity
 * arguments).
 *
 * @param d the {@code double} value to be tested
 * @return {@code true} if the argument is a finite
 * floating-point value, {@code false} otherwise.
 * @since 1.8
 */
public static boolean isFinite(double d)

How do I print a double value without scientific notation using Java?

You can try it with DecimalFormat. With this class you are very flexible in parsing your numbers.
You can exactly set the pattern you want to use.
In your case for example:

double test = 12345678;
DecimalFormat df = new DecimalFormat("#");
df.setMaximumFractionDigits(0);
System.out.println(df.format(test)); //12345678

How do I convert a double into a string in C++?

// The C way:
char buffer[32];
snprintf(buffer, sizeof(buffer), "%g", myDoubleVar);

// The C++03 way:
std::ostringstream sstream;
sstream << myDoubleVar;
std::string varAsString = sstream.str();

// The C++11 way:
std::string varAsString = std::to_string(myDoubleVar);

// The boost way:
std::string varAsString = boost::lexical_cast<std::string>(myDoubleVar);

Convert double to float in Java

This is a nice way to do it:

Double d = 0.5;
float f = d.floatValue();

if you have d as a primitive type just add one line:

double d = 0.5;
Double D = Double.valueOf(d);
float f = D.floatValue();

DOUBLE vs DECIMAL in MySQL

"are there any issue we should expect from only storing and retreiving a money amount in a DOUBLE column ?"

It sounds like no rounding errors can be produced in your scenario and if there were, they would be truncated by the conversion to BigDecimal.

So I would say no.

However, there is no guarantee that some change in the future will not introduce a problem.

Float and double datatype in Java

This example illustrates how to extract the sign (the leftmost bit), exponent (the 8 following bits) and mantissa (the 23 rightmost bits) from a float in Java.

int bits = Float.floatToIntBits(-0.005f);
int sign = bits >>> 31;
int exp = (bits >>> 23 & ((1 << 8) - 1)) - ((1 << 7) - 1);
int mantissa = bits & ((1 << 23) - 1);
System.out.println(sign + " " + exp + " " + mantissa + " " +
  Float.intBitsToFloat((sign << 31) | (exp + ((1 << 7) - 1)) << 23 | mantissa));

The same approach can be used for double’s (11 bit exponent and 52 bit mantissa).

long bits = Double.doubleToLongBits(-0.005);
long sign = bits >>> 63;
long exp = (bits >>> 52 & ((1 << 11) - 1)) - ((1 << 10) - 1);
long mantissa = bits & ((1L << 52) - 1);
System.out.println(sign + " " + exp + " " + mantissa + " " +
  Double.longBitsToDouble((sign << 63) | (exp + ((1 << 10) - 1)) << 52 | mantissa));

Credit: http://s-j.github.io/java-float/

Converting string to double in C#

In your string I see: 15.5859949000000662452.23862099999999 which is not a double (it has two decimal points). Perhaps it's just a legitimate input error?

You may also want to figure out if your last String will be empty, and account for that situation.

Retain precision with double in Java

Multiply everything by 100 and store it in a long as cents.

Convert double to BigDecimal and set BigDecimal Precision

Why not :

b = b.setScale(2, RoundingMode.HALF_UP);

How to get the Power of some Integer in Swift language?

It turns out you can also use pow(). For example, you can use the following to express 10 to the 9th.

pow(10, 9)

Along with pow, powf() returns a float instead of a double. I have only tested this on Swift 4 and macOS 10.13.

C++ string to double conversion

If you are reading from a file then you should hear the advice given and just put it into a double.

On the other hand, if you do have, say, a string you could use boost's lexical_cast.

Here is a (very simple) example:

int Foo(std::string anInt)
{
   return lexical_cast<int>(anInt);
}

How to print a double with two decimals in Android?

You can use a DecimalFormat, or String.format("%.2f", a);

How to check if a double is null?

I would recommend using a Double not a double as your type then you check against null.

Convert double to string C++?

You can't do it directly. There are a number of ways to do it:

  1. Use a std::stringstream:

    std::ostringstream s;
    s << "(" << c1 << ", " << c2 << ")";
    storedCorrect[count] = s.str()
    
  2. Use boost::lexical_cast:

    storedCorrect[count] = "(" + boost::lexical_cast<std::string>(c1) + ", " + boost::lexical_cast<std::string>(c2) + ")";
    
  3. Use std::snprintf:

    char buffer[256];  // make sure this is big enough!!!
    snprintf(buffer, sizeof(buffer), "(%g, %g)", c1, c2);
    storedCorrect[count] = buffer;
    

There are a number of other ways, using various double-to-string conversion functions, but these are the main ways you'll see it done.

Difference between int and double

Operations on integers are exact. double is a floating point data type, and floating point operations are approximate whenever there's a fraction.

double also takes up twice as much space as int in many implementations (e.g. most 32-bit systems) .

Double vs. BigDecimal?

If you are dealing with calculation, there are laws on how you should calculate and what precision you should use. If you fail that you will be doing something illegal. The only real reason is that the bit representation of decimal cases are not precise. As Basil simply put, an example is the best explanation. Just to complement his example, here's what happens:

static void theDoubleProblem1() {
    double d1 = 0.3;
    double d2 = 0.2;
    System.out.println("Double:\t 0,3 - 0,2 = " + (d1 - d2));

    float f1 = 0.3f;
    float f2 = 0.2f;
    System.out.println("Float:\t 0,3 - 0,2 = " + (f1 - f2));

    BigDecimal bd1 = new BigDecimal("0.3");
    BigDecimal bd2 = new BigDecimal("0.2");
    System.out.println("BigDec:\t 0,3 - 0,2 = " + (bd1.subtract(bd2)));
}

Output:

Double:  0,3 - 0,2 = 0.09999999999999998
Float:   0,3 - 0,2 = 0.10000001
BigDec:  0,3 - 0,2 = 0.1

Also we have that:

static void theDoubleProblem2() {
    double d1 = 10;
    double d2 = 3;
    System.out.println("Double:\t 10 / 3 = " + (d1 / d2));

    float f1 = 10f;
    float f2 = 3f;
    System.out.println("Float:\t 10 / 3 = " + (f1 / f2));

    // Exception! 
    BigDecimal bd3 = new BigDecimal("10");
    BigDecimal bd4 = new BigDecimal("3");
    System.out.println("BigDec:\t 10 / 3 = " + (bd3.divide(bd4)));
}

Gives us the output:

Double:  10 / 3 = 3.3333333333333335
Float:   10 / 3 = 3.3333333
Exception in thread "main" java.lang.ArithmeticException: Non-terminating decimal expansion

But:

static void theDoubleProblem2() {
    BigDecimal bd3 = new BigDecimal("10");
    BigDecimal bd4 = new BigDecimal("3");
    System.out.println("BigDec:\t 10 / 3 = " + (bd3.divide(bd4, 4, BigDecimal.ROUND_HALF_UP)));
}

Has the output:

BigDec:  10 / 3 = 3.3333 

How to get absolute value from double - c-language

  //use fabs()
  double sum_primary_diagonal=0;
  double sum_secondary_diagonal=0;
  double difference = fabs(sum_primary_diagonal - sum_secondary_diagonal);

Scanf/Printf double variable C

When a float is passed to printf, it is automatically converted to a double. This is part of the default argument promotions, which apply to functions that have a variable parameter list (containing ...), largely for historical reasons. Therefore, the “natural” specifier for a float, %f, must work with a double argument. So the %f and %lf specifiers for printf are the same; they both take a double value.

When scanf is called, pointers are passed, not direct values. A pointer to float is not converted to a pointer to double (this could not work since the pointed-to object cannot change when you change the pointer type). So, for scanf, the argument for %f must be a pointer to float, and the argument for %lf must be a pointer to double.

Checking if a double (or float) is NaN in C++

You can use the isnan() function, but you need to include the C math library.

#include <cmath>

As this function is part of C99, it is not available everywhere. If your vendor does not supply the function, you can also define your own variant for compatibility.

inline bool isnan(double x) {
    return x != x;
}

How do I round a double to two decimal places in Java?

Just use: (easy as pie)

double number = 651.5176515121351;

number = Math.round(number * 100);
number = number/100;

The output will be 651.52

Difference between decimal, float and double in .NET?

Integers, as was mentioned, are whole numbers. They can't store the point something, like .7, .42, and .007. If you need to store numbers that are not whole numbers, you need a different type of variable. You can use the double type or the float type. You set these types of variables up in exactly the same way: instead of using the word int, you type double or float. Like this:

float myFloat;
double myDouble;

(float is short for "floating point", and just means a number with a point something on the end.)

The difference between the two is in the size of the numbers that they can hold. For float, you can have up to 7 digits in your number. For doubles, you can have up to 16 digits. To be more precise, here's the official size:

float:  1.5 × 10^-45  to 3.4 × 10^38  
double: 5.0 × 10^-324 to 1.7 × 10^308

float is a 32-bit number, and double is a 64-bit number.

Double click your new button to get at the code. Add the following three lines to your button code:

double myDouble;
myDouble = 0.007;
MessageBox.Show(myDouble.ToString());

Halt your program and return to the coding window. Change this line:

myDouble = 0.007;
myDouble = 12345678.1234567;

Run your programme and click your double button. The message box correctly displays the number. Add another number on the end, though, and C# will again round up or down. The moral is if you want accuracy, be careful of rounding!

How to cast from List<Double> to double[] in Java?

Guava has a method to do this for you: double[] Doubles.toArray(Collection<Double>)

This isn't necessarily going to be any faster than just looping through the Collection and adding each Double object to the array, but it's a lot less for you to write.

Rounding a double value to x number of decimal places in swift

If you want to round Double values, you might want to use Swift Decimal so you don't introduce any errors that can crop up when trying to math with these rounded values. If you use Decimal, it can accurately represent decimal values of that rounded floating point value.

So you can do:

extension Double {
    /// Convert `Double` to `Decimal`, rounding it to `scale` decimal places.
    ///
    /// - Parameters:
    ///   - scale: How many decimal places to round to. Defaults to `0`.
    ///   - mode:  The preferred rounding mode. Defaults to `.plain`.
    /// - Returns: The rounded `Decimal` value.

    func roundedDecimal(to scale: Int = 0, mode: NSDecimalNumber.RoundingMode = .plain) -> Decimal {
        var decimalValue = Decimal(self)
        var result = Decimal()
        NSDecimalRound(&result, &decimalValue, scale, mode)
        return result
    }
}

Then, you can get the rounded Decimal value like so:

let foo = 427.3000000002
let value = foo.roundedDecimal(to: 2) // results in 427.30

And if you want to display it with a specified number of decimal places (as well as localize the string for the user's current locale), you can use a NumberFormatter:

let formatter = NumberFormatter()
formatter.maximumFractionDigits = 2
formatter.minimumFractionDigits = 2

if let string = formatter.string(for: value) {
    print(string)
}

decimal vs double! - Which one should I use and when?

Decimal is for exact values. Double is for approximate values.

USD: $12,345.67 USD (Decimal)
CAD: $13,617.27 (Decimal)
Exchange Rate: 1.102932 (Double)

How to check if a double value has no decimal part

Interesting little problem. It is a bit tricky, since real numbers, not always represent exact integers, even if they are meant to, so it's important to allow a tolerance.

For instance tolerance could be 1E-6, in the unit tests, I kept a rather coarse tolerance to have shorter numbers.

None of the answers that I can read now works in this way, so here is my solution:

public boolean isInteger(double n, double tolerance) {
    double absN = Math.abs(n);
    return Math.abs(absN - Math.round(absN)) <= tolerance;
}

And the unit test, to make sure it works:

@Test
public void checkIsInteger() {
    final double TOLERANCE = 1E-2;
    assertThat(solver.isInteger(1, TOLERANCE), is(true));

    assertThat(solver.isInteger(0.999, TOLERANCE), is(true));
    assertThat(solver.isInteger(0.9, TOLERANCE), is(false));

    assertThat(solver.isInteger(1.001, TOLERANCE), is(true));
    assertThat(solver.isInteger(1.1, TOLERANCE), is(false));

    assertThat(solver.isInteger(-1, TOLERANCE), is(true));

    assertThat(solver.isInteger(-0.999, TOLERANCE), is(true));
    assertThat(solver.isInteger(-0.9, TOLERANCE), is(false));

    assertThat(solver.isInteger(-1.001, TOLERANCE), is(true));        
    assertThat(solver.isInteger(-1.1, TOLERANCE), is(false));
}

How can I divide two integers to get a double?

I have went through most of the answers and im pretty sure that it's unachievable. Whatever you try to divide two int into double or float is not gonna happen. But you have tons of methods to make the calculation happen, just cast them into float or double before the calculation will be fine.

C# Double - ToString() formatting with two decimal places but no rounding

To what is worth, for showing currency, you can use "C":

double cost = 1.99;
m_CostText.text = cost.ToString("C"); /*C: format as currentcy */

Output: $1.99

C: convert double to float, preserving decimal point precision

A float generally has about 7 digits of precision, regardless of the position of the decimal point. So if you want 5 digits of precision after the decimal, you'll need to limit the range of the numbers to less than somewhere around +/-100.

Converting double to integer in Java

For the datatype Double to int, you can use the following:

Double double = 5.00;

int integer = double.intValue();

How do I get DOUBLE_MAX?

You get the integer limits in <limits.h> or <climits>. Floating point characteristics are defined in <float.h> for C. In C++, the preferred version is usually std::numeric_limits<double>::max() (for which you #include <limits>).

As to your original question, if you want a larger integer type than long, you should probably consider long long. This isn't officially included in C++98 or C++03, but is part of C99 and C++11, so all reasonably current compilers support it.

Convert String to Double - VB

I simple used Eval(string) and it evaluated as Double.

Double.TryParse or Convert.ToDouble - which is faster and safer?

Double.TryParse IMO.

It is easier for you to handle, You'll know exactly where the error occurred.

Then you can deal with it how you see fit if it returns false (i.e could not convert).

How do I parse a string with a decimal point to a double?

The below is less efficient, but I use this logic. This is valid only if you have two digits after decimal point.

double val;

if (temp.Text.Split('.').Length > 1)
{
    val = double.Parse(temp.Text.Split('.')[0]);

    if (temp.Text.Split('.')[1].Length == 1)
        val += (0.1 * double.Parse(temp.Text.Split('.')[1]));
    else
        val += (0.01 * double.Parse(temp.Text.Split('.')[1]));
}
else
    val = double.Parse(RR(temp.Text));

Correct format specifier for double in printf

%Lf (note the capital L) is the format specifier for long doubles.

For plain doubles, either %e, %E, %f, %g or %G will do.

Converting String to Double in Android

String sc1="0.0";
Double s1=Double.parseDouble(sc1.toString());

How to change symbol for decimal point in double.ToString()?

You can change the decimal separator by changing the culture used to display the number. Beware however that this will change everything else about the number (eg. grouping separator, grouping sizes, number of decimal places). From your question, it looks like you are defaulting to a culture that uses a comma as a decimal separator.

To change just the decimal separator without changing the culture, you can modify the NumberDecimalSeparator property of the current culture's NumberFormatInfo.

Thread.CurrentCulture.NumberFormat.NumberDecimalSeparator = ".";

This will modify the current culture of the thread. All output will now be altered, meaning that you can just use value.ToString() to output the format you want, without worrying about changing the culture each time you output a number.

(Note that a neutral culture cannot have its decimal separator changed.)

How do I limit the number of decimals printed for a double?

Use a DecimalFormatter:

double number = 0.9999999999999;
DecimalFormat numberFormat = new DecimalFormat("#.00");
System.out.println(numberFormat.format(number));

Will give you "0.99". You can add or subtract 0 on the right side to get more or less decimals.

Or use '#' on the right to make the additional digits optional, as in with #.## (0.30) would drop the trailing 0 to become (0.3).

Double array initialization in Java

If you can accept Double Objects than this post is helpful: Initialization of an ArrayList in one line

List<Double> y = Arrays.asList(null, 1.0, 2.0);
Double x = y.get(1);

How to cast the size_t to double or int C++

A cast, as Blaz Bratanic suggested:

size_t data = 99999999;
int convertdata = static_cast<int>(data);

is likely to silence the warning (though in principle a compiler can warn about anything it likes, even if there's a cast).

But it doesn't solve the problem that the warning was telling you about, namely that a conversion from size_t to int really could overflow.

If at all possible, design your program so you don't need to convert a size_t value to int. Just store it in a size_t variable (as you've already done) and use that.

Converting to double will not cause an overflow, but it could result in a loss of precision for a very large size_t value. Again, it doesn't make a lot of sense to convert a size_t to a double; you're still better off keeping the value in a size_t variable.

(R Sahu's answer has some suggestions if you can't avoid the cast, such as throwing an exception on overflow.)

Java ArrayList of Doubles

Using guava

Doubles.asList(1.2, 5.6, 10.1);

or immutable list

ImmutableList.of(1.2, 5.6, 10.1);

Double value to round up in Java

You can use format like here,

  public static double getDoubleValue(String value,int digit){
    if(value==null){
        value="0";
     }
    double i=0;
     try {
         DecimalFormat digitformat = new DecimalFormat("#.##");
         digitformat.setMaximumFractionDigits(digit);
        return Double.valueOf(digitformat.format(Double.parseDouble(value)));

    } catch (NumberFormatException numberFormatExp) {
        return i;   
    }
}

How to round a Double to the nearest Int in swift?

**In Swift**

var a = 14.123456789
var b = 14.123456789
var c = 14.123456789
var d = 14.123456789
var e = 14.123456789
var f = 14.123456789

a.rounded(.up)                      //15
b.rounded(.down)                    //14
c.rounded(.awayFromZero)            //15
d.rounded(.towardZero)              //14
e.rounded(.toNearestOrAwayFromZero) //14
f.rounded(.toNearestOrEven)         //14

How do I convert a string to a double in Python?

>>> x = "2342.34"
>>> float(x)
2342.3400000000001

There you go. Use float (which behaves like and has the same precision as a C,C++, or Java double).

What exactly does Double mean in java?

A double is an IEEE754 double-precision floating point number, similar to a float but with a larger range and precision.

IEEE754 single precision numbers have 32 bits (1 sign, 8 exponent and 23 mantissa bits) while double precision numbers have 64 bits (1 sign, 11 exponent and 52 mantissa bits).

A Double in Java is the class version of the double basic type - you can use doubles but, if you want to do something with them that requires them to be an object (such as put them in a collection), you'll need to box them up in a Double object.

What is the inclusive range of float and double in Java?

Java's Primitive Data Types

boolean: 1-bit. May take on the values true and false only.

byte: 1 signed byte (two's complement). Covers values from -128 to 127.

short: 2 bytes, signed (two's complement), -32,768 to 32,767

int: 4 bytes, signed (two's complement). -2,147,483,648 to 2,147,483,647.

long: 8 bytes signed (two's complement). Ranges from -9,223,372,036,854,775,808 to +9,223,372,036,854,775,807.

float: 4 bytes, IEEE 754. Covers a range from 1.40129846432481707e-45 to 3.40282346638528860e+38 (positive or negative).

double: 8 bytes IEEE 754. Covers a range from 4.94065645841246544e-324d to 1.79769313486231570e+308d (positive or negative).

char: 2 bytes, unsigned, Unicode, 0 to 65,535

Java correct way convert/cast object to Double

I tried this and it worked:

Object obj = 10;
String str = obj.toString(); 
double d = Double.valueOf(str).doubleValue();

Round up double to 2 decimal places

Just single line of code:

 let obj = self.arrayResult[indexPath.row]
 let str = String(format: "%.2f", arguments: [Double((obj.mainWeight)!)!])

How to manipulate arrays. Find the average. Beginner Java

Best way to find the average of some numbers is trying Classes ......

public static void main(String[] args) {
    average(1,2,5,4);

}

public static void average(int...numbers){
    int total = 0;
    for(int x: numbers){
        total+=x;
    }
    System.out.println("Average is: "+(double)total/numbers.length);

}

Rounding a double to turn it into an int (java)

Documentation of Math.round says:

Returns the result of rounding the argument to an integer. The result is equivalent to (int) Math.floor(f+0.5).

No need to cast to int. Maybe it was changed from the past.

Limiting double to 3 decimal places

You can use:

double example = 12.34567;
double output = ( (double) ( (int) (example * 1000.0) ) ) / 1000.0 ;

Why does dividing two int not yield the right value when assigned to double?

The important thing is one of the elements of calculation be a float-double type. Then to get a double result you need to cast this element like shown below:

c = static_cast<double>(a) / b;

or c = a / static_cast(b);

Or you can create it directly::

c = 7.0 / 3;

Note that one of elements of calculation must have the '.0' to indicate a division of a float-double type by an integer. Otherwise, despite the c variable be a double, the result will be zero too (an integer).

How can I truncate a double to only two decimal places in Java?

Maybe following :

double roundTwoDecimals(double d) { 
      DecimalFormat twoDForm = new DecimalFormat("#.##"); 
      return Double.valueOf(twoDForm.format(d));
}  

Round double in two decimal places in C#?

Use Math.Round

value = Math.Round(48.485, 2);

What is the equivalent of bigint in C#?

I was handling a bigint datatype to be shown in a DataGridView and made it like this

something = (int)(Int64)data_reader[0];

How to install MinGW-w64 and MSYS2?

Unfortunately, the MinGW-w64 installer you used sometimes has this issue. I myself am not sure about why this happens (I think it has something to do with Sourceforge URL redirection or whatever that the installer currently can't handle properly enough).

Anyways, if you're already planning on using MSYS2, there's no need for that installer.

  1. Download MSYS2 from this page (choose 32 or 64-bit according to what version of Windows you are going to use it on, not what kind of executables you want to build, both versions can build both 32 and 64-bit binaries).

  2. After the install completes, click on the newly created "MSYS2 Shell" option under either MSYS2 64-bit or MSYS2 32-bit in the Start menu. Update MSYS2 according to the wiki (although I just do a pacman -Syu, ignore all errors and close the window and open a new one, this is not recommended and you should do what the wiki page says).

  3. Install a toolchain

    a) for 32-bit:

    pacman -S mingw-w64-i686-gcc
    

    b) for 64-bit:

    pacman -S mingw-w64-x86_64-gcc
    
  4. install any libraries/tools you may need. You can search the repositories by doing

    pacman -Ss name_of_something_i_want_to_install
    

    e.g.

    pacman -Ss gsl
    

    and install using

    pacman -S package_name_of_something_i_want_to_install
    

    e.g.

    pacman -S mingw-w64-x86_64-gsl
    

    and from then on the GSL library is automatically found by your MinGW-w64 64-bit compiler!

  5. Open a MinGW-w64 shell:

    a) To build 32-bit things, open the "MinGW-w64 32-bit Shell"

    b) To build 64-bit things, open the "MinGW-w64 64-bit Shell"

  6. Verify that the compiler is working by doing

    gcc -v
    

If you want to use the toolchains (with installed libraries) outside of the MSYS2 environment, all you need to do is add <MSYS2 root>/mingw32/bin or <MSYS2 root>/mingw64/bin to your PATH.

Adding placeholder text to textbox

Here I come with this solution inspired by @Kemal Karadag.

I noticed that every solution posted here is relying on the focus,

While I wanted my placeholder to be the exact clone of a standard HTML placeholder in Google Chrome.

Instead of hiding/showing the placeholder when the box is focused,

I hide/show the placeholder depending on the text length of the box:

If the box is empty, the placeholder is shown, and if you type in the box, the placeholder disappears.

As it is inherited from a standard TextBox, you can find it in your Toolbox!

using System;
using System.Drawing;
using System.Windows.Forms;

public class PlaceHolderTextBox : TextBox
{
    private bool isPlaceHolder = true;
    private string placeHolderText;

    public string PlaceHolderText
    {
        get { return placeHolderText; }
        set
        {
            placeHolderText = value;
            SetPlaceholder();
        }
    }

    public PlaceHolderTextBox()
    {
        TextChanged += OnTextChanged;
    }

    private void SetPlaceholder()
    {
        if (!isPlaceHolder)
        {
            this.Text = placeHolderText;
            this.ForeColor = Color.Gray;
            isPlaceHolder = true;
        }
    }

    private void RemovePlaceHolder()
    {
        if (isPlaceHolder)
        {
            this.Text = this.Text[0].ToString(); // Remove placeHolder text, but keep the character we just entered
            this.Select(1, 0); // Place the caret after the character we just entered
            this.ForeColor = System.Drawing.SystemColors.WindowText;
            isPlaceHolder = false;
        }
    }

    private void OnTextChanged(object sender, EventArgs e)
    {
        if (this.Text.Length == 0)
        {
            SetPlaceholder();
        }
        else
        {
            RemovePlaceHolder();
        }
    }
}

Permission is only granted to system app

when your add permission in manifest then in eclipse go to project and clic

  1. click on project
  2. click on clean project that's all

k on clean project

How do I retrieve query parameters in Spring Boot?

To accept both @PathVariable and @RequestParam in the same /user endpoint:

@GetMapping(path = {"/user", "/user/{data}"})
public void user(@PathVariable(required=false,name="data") String data,
                 @RequestParam(required=false) Map<String,String> qparams) {
    qparams.forEach((a,b) -> {
        System.out.println(String.format("%s -> %s",a,b));
    }
  
    if (data != null) {
        System.out.println(data);
    }
}

Testing with curl:

  • curl 'http://localhost:8080/user/books'
  • curl 'http://localhost:8080/user?book=ofdreams&name=nietzsche'

How do you clear the focus in javascript?

You can call window.focus();

but moving or losing the focus is bound to interfere with anyone using the tab key to get around the page.

you could listen for keycode 13, and forego the effect if the tab key is pressed.

Rails update_attributes without save?

I believe what you are looking for is assign_attributes.

It's basically the same as update_attributes but it doesn't save the record:

class User < ActiveRecord::Base
  attr_accessible :name
  attr_accessible :name, :is_admin, :as => :admin
end

user = User.new
user.assign_attributes({ :name => 'Josh', :is_admin => true }) # Raises an ActiveModel::MassAssignmentSecurity::Error
user.assign_attributes({ :name => 'Bob'})
user.name        # => "Bob"
user.is_admin?   # => false
user.new_record? # => true

Git - How to use .netrc file on Windows to save user and password

Is it possible to use a .netrc file on Windows?

Yes: You must:

  • define environment variable %HOME% (pre-Git 2.0, no longer needed with Git 2.0+)
  • put a _netrc file in %HOME%

If you are using Windows 7/10, in a CMD session, type:

setx HOME %USERPROFILE%

and the %HOME% will be set to 'C:\Users\"username"'.
Go that that folder (cd %HOME%) and make a file called '_netrc'

Note: Again, for Windows, you need a '_netrc' file, not a '.netrc' file.

Its content is quite standard (Replace the <examples> with your values):

machine <hostname1>
login <login1>
password <password1>
machine <hostname2>
login <login2>
password <password2>

Luke mentions in the comments:

Using the latest version of msysgit on Windows 7, I did not need to set the HOME environment variable. The _netrc file alone did the trick.

This is indeed what I mentioned in "Trying to “install” github, .ssh dir not there":
git-cmd.bat included in msysgit does set the %HOME% environment variable:

@if not exist "%HOME%" @set HOME=%HOMEDRIVE%%HOMEPATH%
@if not exist "%HOME%" @set HOME=%USERPROFILE%

??? believes in the comments that "it seems that it won't work for http protocol"

However, I answered that netrc is used by curl, and works for HTTP protocol, as shown in this example (look for 'netrc' in the page): . Also used with HTTP protocol here: "_netrc/.netrc alternative to cURL".


A common trap with with netrc support on Windows is that git will bypass using it if an origin https url specifies a user name.

For example, if your .git/config file contains:

[remote "origin"]
     fetch = +refs/heads/*:refs/remotes/origin/*
     url = https://[email protected]/p/my-project/

Git will not resolve your credentials via _netrc, to fix this remove your username, like so:

[remote "origin"]
     fetch = +refs/heads/*:refs/remotes/origin/*
     url = https://code.google.com/p/my-project/

Alternative solution: With git version 1.7.9+ (January 2012): This answer from Mark Longair details the credential cache mechanism which also allows you to not store your password in plain text as shown below.


With Git 1.8.3 (April 2013):

You now can use an encrypted .netrc (with gpg).
On Windows: %HOME%/_netrc (_, not '.')

A new read-only credential helper (in contrib/) to interact with the .netrc/.authinfo files has been added.

That script would allow you to use gpg-encrypted netrc files, avoiding the issue of having your credentials stored in a plain text file.

Files with the .gpg extension will be decrypted by GPG before parsing.
Multiple -f arguments are OK. They are processed in order, and the first matching entry found is returned via the credential helper protocol.

When no -f option is given, .authinfo.gpg, .netrc.gpg, .authinfo, and .netrc files in your home directory are used in this order.

To enable this credential helper:

git config credential.helper '$shortname -f AUTHFILE1 -f AUTHFILE2'

(Note that Git will prepend "git-credential-" to the helper name and look for it in the path.)

# and if you want lots of debugging info:
git config credential.helper '$shortname -f AUTHFILE -d'

#or to see the files opened and data found:
git config credential.helper '$shortname -f AUTHFILE -v'

See a full example at "Is there a way to skip password typing when using https:// github"


With Git 2.18+ (June 2018), you now can customize the GPG program used to decrypt the encrypted .netrc file.

See commit 786ef50, commit f07eeed (12 May 2018) by Luis Marsano (``).
(Merged by Junio C Hamano -- gitster -- in commit 017b7c5, 30 May 2018)

git-credential-netrc: accept gpg option

git-credential-netrc was hardcoded to decrypt with 'gpg' regardless of the gpg.program option.
This is a problem on distributions like Debian that call modern GnuPG something else, like 'gpg2'

socket connect() vs bind()

The one liner : bind() to own address, connect() to remote address.

Quoting from the man page of bind()

bind() assigns the address specified by addr to the socket referred to by the file descriptor sockfd. addrlen specifies the size, in bytes, of the address structure pointed to by addr. Traditionally, this operation is called "assigning a name to a socket".

and, from the same for connect()

The connect() system call connects the socket referred to by the file descriptor sockfd to the address specified by addr.

To clarify,

  • bind() associates the socket with its local address [that's why server side binds, so that clients can use that address to connect to server.]
  • connect() is used to connect to a remote [server] address, that's why is client side, connect [read as: connect to server] is used.

JQuery select2 set default value from an option in list?

One more way - just add a selected = "selected" attribute to the select markup and call select2 on it. It must take your selected value. No need for extra JavaScript. Like this :

Markup

<select class="select2">
   <option id="foo">Some Text</option>
   <option id="bar" selected="selected">Other Text</option>
</select>

JavaScript

$('select').select2(); //oh yes just this!

See fiddle : http://jsfiddle.net/6hZFU/

Edit: (Thanks, Jay Haase!)

If this doesn't work, try setting the val property of select2 to null, to clear the value, like this:

$('select').select2("val", null); //a lil' bit more :)

After this, it is simple enough to set val to "Whatever You Want".

Converting Float to Dollars and Cents

In python 3, you can use:

import locale
locale.setlocale( locale.LC_ALL, 'English_United States.1252' )
locale.currency( 1234.50, grouping = True )

Output

'$1,234.50'

Javascript variable access in HTML

<html>
<head>
<script>
    function putText() {
        var simpleText = "hello_world";
        var finalSplitText = simpleText.split("_");
        var splitText = finalSplitText[0];
        document.getElementById("destination").innerHTML = "I need the value of " + splitText + " variable here";
    }
</script>
</head>
<body onLoad = putText()>
    <a id="destination" href = test.html>I need the value of "splitText" variable here</a>
</body>
</html>

JavaScript file upload size validation

I use one main Javascript function that I had found at Mozilla Developer Network site https://developer.mozilla.org/en-US/docs/Using_files_from_web_applications, along with another function with AJAX and changed according to my needs. It receives a document element id regarding the place in my html code where I want to write the file size.

<Javascript>

function updateSize(elementId) {
    var nBytes = 0,
    oFiles = document.getElementById(elementId).files,
    nFiles = oFiles.length;

    for (var nFileId = 0; nFileId < nFiles; nFileId++) {
        nBytes += oFiles[nFileId].size;
    }
    var sOutput = nBytes + " bytes";
    // optional code for multiples approximation
    for (var aMultiples = ["K", "M", "G", "T", "P", "E", "Z", "Y"], nMultiple = 0, nApprox = nBytes / 1024; nApprox > 1; nApprox /= 1024, nMultiple++) {
        sOutput = " (" + nApprox.toFixed(3) + aMultiples[nMultiple] + ")";
    }

    return sOutput;
}
</Javascript>

<HTML>
<input type="file" id="inputFileUpload" onchange="uploadFuncWithAJAX(this.value);" size="25">
</HTML>

<Javascript with XMLHttpRequest>
document.getElementById('spanFileSizeText').innerHTML=updateSize("inputFileUpload");
</XMLHttpRequest>

Cheers

Accessing clicked element in angularjs

While AngularJS allows you to get a hand on a click event (and thus a target of it) with the following syntax (note the $event argument to the setMaster function; documentation here: http://docs.angularjs.org/api/ng.directive:ngClick):

function AdminController($scope) {    
  $scope.setMaster = function(obj, $event){
    console.log($event.target);
  }
}

this is not very angular-way of solving this problem. With AngularJS the focus is on the model manipulation. One would mutate a model and let AngularJS figure out rendering.

The AngularJS-way of solving this problem (without using jQuery and without the need to pass the $event argument) would be:

<div ng-controller="AdminController">
    <ul class="list-holder">
        <li ng-repeat="section in sections" ng-class="{active : isSelected(section)}">
            <a ng-click="setMaster(section)">{{section.name}}</a>
        </li>
    </ul>
    <hr>
    {{selected | json}}
</div>

where methods in the controller would look like this:

$scope.setMaster = function(section) {
    $scope.selected = section;
}

$scope.isSelected = function(section) {
    return $scope.selected === section;
}

Here is the complete jsFiddle: http://jsfiddle.net/pkozlowski_opensource/WXJ3p/15/

ReadFile in Base64 Nodejs

I think that the following example demonstrates what you need:http://www.hacksparrow.com/base64-encoding-decoding-in-node-js.html

The essence of the article is this code part:

var fs = require('fs');

// function to encode file data to base64 encoded string
function base64_encode(file) {
    // read binary data
    var bitmap = fs.readFileSync(file);
    // convert binary data to base64 encoded string
    return new Buffer(bitmap).toString('base64');
}

// function to create file from base64 encoded string
function base64_decode(base64str, file) {
    // create buffer object from base64 encoded string, it is important to tell the constructor that the string is base64 encoded
    var bitmap = new Buffer(base64str, 'base64');
    // write buffer to file
    fs.writeFileSync(file, bitmap);
    console.log('******** File created from base64 encoded string ********');
}

// convert image to base64 encoded string
var base64str = base64_encode('kitten.jpg');
console.log(base64str);
// convert base64 string back to image 
base64_decode(base64str, 'copy.jpg');

Get value of multiselect box using jQuery or pure JS

This got me the value and text of the selected options for the jQuery multiselect.js plugin:

$("#selectBox").multiSelect({
    afterSelect: function(){
        var selections = [];
        $("#selectBox option:selected").each(function(){
            var optionValue = $(this).val();
            var optionText = $(this).text();
            console.log("optionText",optionText);                
            // collect all values
            selections.push(optionValue);
        });

        // use array "selections" here.. 
    }
});   

very usefull if you need it for your "onChange" event ;)

Why is division in Ruby returning an integer instead of decimal value?

Change the 5 to 5.0. You're getting integer division.

print highest value in dict with key

just :

 mydict = {'A':4,'B':10,'C':0,'D':87}
 max(mydict.items(), key=lambda x: x[1])

Print to the same line and not a new line?

From python 3.x you can do:

print('bla bla', end='')

(which can also be used in Python 2.6 or 2.7 by putting from __future__ import print_function at the top of your script/module)

Python console progressbar example:

import time

# status generator
def range_with_status(total):
    """ iterate from 0 to total and show progress in console """
    n=0
    while n<total:
        done = '#'*(n+1)
        todo = '-'*(total-n-1)
        s = '<{0}>'.format(done+todo)
        if not todo:
            s+='\n'        
        if n>0:
            s = '\r'+s
        print(s, end='')
        yield n
        n+=1

# example for use of status generator
for i in range_with_status(10):
    time.sleep(0.1)

A network-related or instance-specific error occurred while establishing a connection to SQL Server

Sql Server fire this error when your application don't have enough rights to access the database. there are several reason about this error . To fix this error you should follow the following instruction.

  1. Try to connect sql server from your server using management studio . if you use windows authentication to connect sql server then set your application pool identity to server administrator .

  2. if you use sql server authentication then check you connection string in web.config of your web application and set user id and password of sql server which allows you to log in .

  3. if your database in other server(access remote database) then first of enable remote access of sql server form sql server property from sql server management studio and enable TCP/IP form sql server configuration manager .

  4. after doing all these stuff and you still can't access the database then check firewall of server form where you are trying to access the database and add one rule in firewall to enable port of sql server(by default sql server use 1433 , to check port of sql server you need to check sql server configuration manager network protocol TCP/IP port).

  5. if your sql server is running on named instance then you need to write port number with sql serer name for example 117.312.21.21/nameofsqlserver,1433.

  6. If you are using cloud hosting like amazon aws or microsoft azure then server or instance will running behind cloud firewall so you need to enable 1433 port in cloud firewall if you have default instance or specific port for sql server for named instance.

  7. If you are using amazon RDS or SQL azure then you need to enable port from security group of that instance.

  8. If you are accessing sql server through sql server authentication mode them make sure you enabled "SQL Server and Windows Authentication Mode" sql server instance property. enter image description here

    1. Restart your sql server instance after making any changes in property as some changes will require restart.

if you further face any difficulty then you need to provide more information about your web site and sql server .

Downloading a file from spring controllers

With Spring 3.0 you can use the HttpEntity return object. If you use this, then your controller does not need a HttpServletResponse object, and therefore it is easier to test. Except this, this answer is relative equals to the one of Infeligo.

If the return value of your pdf framework is an byte array (read the second part of my answer for other return values) :

@RequestMapping(value = "/files/{fileName}", method = RequestMethod.GET)
public HttpEntity<byte[]> createPdf(
                 @PathVariable("fileName") String fileName) throws IOException {

    byte[] documentBody = this.pdfFramework.createPdf(filename);

    HttpHeaders header = new HttpHeaders();
    header.setContentType(MediaType.APPLICATION_PDF);
    header.set(HttpHeaders.CONTENT_DISPOSITION,
                   "attachment; filename=" + fileName.replace(" ", "_"));
    header.setContentLength(documentBody.length);

    return new HttpEntity<byte[]>(documentBody, header);
}

If the return type of your PDF Framework (documentBbody) is not already a byte array (and also no ByteArrayInputStream) then it would been wise NOT to make it a byte array first. Instead it is better to use:

example with FileSystemResource:

@RequestMapping(value = "/files/{fileName}", method = RequestMethod.GET)
public HttpEntity<byte[]> createPdf(
                 @PathVariable("fileName") String fileName) throws IOException {

    File document = this.pdfFramework.createPdf(filename);

    HttpHeaders header = new HttpHeaders();
    header.setContentType(MediaType.APPLICATION_PDF);
    header.set(HttpHeaders.CONTENT_DISPOSITION,
                   "attachment; filename=" + fileName.replace(" ", "_"));
    header.setContentLength(document.length());

    return new HttpEntity<byte[]>(new FileSystemResource(document),
                                  header);
}

How to initialize a variable of date type in java?

To initialize to current date, you could do something like:

Date firstDate = new Date();

To get it from String, you could use SimpleDateFormat like:

String dateInString = "10-Jan-2016";
SimpleDateFormat formatter = new SimpleDateFormat("dd-MMM-yyyy");
try {
    Date date = formatter.parse(dateInString);
    System.out.println(date);
    System.out.println(formatter.format(date));
} catch (ParseException e) {
    //handle exception if date is not in "dd-MMM-yyyy" format
}

How to run test methods in specific order in JUnit4?

I ended up here thinking that my tests weren't run in order, but the truth is that the mess was in my async jobs. When working with concurrency you need to perform concurrency checks between your tests as well. In my case, jobs and tests share a semaphore, so next tests hang until the running job releases the lock.

I know this is not fully related to this question, but maybe could help targeting the correct issue

How to check if multiple array keys exists

One more possible solution:

if (!array_diff(['story', 'message'], array_keys($array))) {
    // OK: all the keys are in $array
} else {
   // FAIL: some keys are not
}

How to select a dropdown value in Selenium WebDriver using Java

As discussed above, we need to implement Select Class in Selenium and further we can use various available methods like :- enter image description here

pandas loc vs. iloc vs. at vs. iat?

loc: only work on index
iloc: work on position
at: get scalar values. It's a very fast loc
iat: Get scalar values. It's a very fast iloc

Also,

at and iat are meant to access a scalar, that is, a single element in the dataframe, while loc and iloc are ments to access several elements at the same time, potentially to perform vectorized operations.

http://pyciencia.blogspot.com/2015/05/obtener-y-filtrar-datos-de-un-dataframe.html

node.js require() cache - possible to invalidate?

You can always safely delete an entry in require.cache without a problem, even when there are circular dependencies. Because when you delete, you just delete a reference to the cached module object, not the module object itself, the module object will not be GCed because in case of circular dependencies, there is still a object referencing this module object.

Suppose you have:

script a.js:

var b=require('./b.js').b;
exports.a='a from a.js';
exports.b=b;

and script b.js:

var a=require('./a.js').a;
exports.b='b from b.js';
exports.a=a;

when you do:

var a=require('./a.js')
var b=require('./b.js')

you will get:

> a
{ a: 'a from a.js', b: 'b from b.js' }
> b
{ b: 'b from b.js', a: undefined }

now if you edit your b.js:

var a=require('./a.js').a;
exports.b='b from b.js. changed value';
exports.a=a;

and do:

delete require.cache[require.resolve('./b.js')]
b=require('./b.js')

you will get:

> a
{ a: 'a from a.js', b: 'b from b.js' }
> b
{ b: 'b from b.js. changed value',
  a: 'a from a.js' }

===

The above is valid if directly running node.js. However, if using tools that have their own module caching system, such as jest, the correct statement would be:

jest.resetModules();

how to make window.open pop up Modal?

I was able to make parent window disable. However making the pop-up always keep raised didn't work. Below code works even for frame tags. Just add id and class property to frame tag and it works well there too.

In parent window use:

<head>    
<style>
.disableWin{
     pointer-events: none;
}
</style>
<script type="text/javascript">
    function openPopUp(url) {
      disableParentWin(); 
      var win = window.open(url);
      win.focus();
      checkPopUpClosed(win);
    }
    /*Function to detect pop up is closed and take action to enable parent window*/
   function checkPopUpClosed(win) {
         var timer = setInterval(function() {
              if(win.closed) {
                  clearInterval(timer);                  
                  enableParentWin();
              }
          }, 1000);
     }
     /*Function to enable parent window*/ 
     function enableParentWin() {
          window.document.getElementById('mainDiv').class="";
     }
     /*Function to enable parent window*/ 
     function disableParentWin() {
          window.document.getElementById('mainDiv').class="disableWin";
     }

</script>
</head>

<body>
<div id="mainDiv class="">
</div>
</body>    

MySQL Nested Select Query?

You just need to write the first query as a subquery (derived table), inside parentheses, pick an alias for it (t below) and alias the columns as well.

The DISTINCT can also be safely removed as the internal GROUP BY makes it redundant:

SELECT DATE(`date`) AS `date` , COUNT(`player_name`) AS `player_count`
FROM (
    SELECT MIN(`date`) AS `date`, `player_name`
    FROM `player_playtime`
    GROUP BY `player_name`
) AS t
GROUP BY DATE( `date`) DESC LIMIT 60 ;

Since the COUNT is now obvious that is only counting rows of the derived table, you can replace it with COUNT(*) and further simplify the query:

SELECT t.date , COUNT(*) AS player_count
FROM (
    SELECT DATE(MIN(`date`)) AS date
    FROM player_playtime
    GROUP BY player_name
) AS t
GROUP BY t.date DESC LIMIT 60 ;

Connection string with relative path to the database file

Relative to what, your application ? If so then you can simply get the applications current Path with :

System.Environment.CurrentDirectory 

And append it to the connection string

Postgresql Windows, is there a default password?

Try this:

Open PgAdmin -> Files -> Open pgpass.conf

You would get the path of pgpass.conf at the bottom of the window. Go to that location and open this file, you can find your password there.

Reference

If the above does not work, you may consider trying this:

 1. edit pg_hba.conf to allow trust authorization temporarily
 2. Reload the config file (pg_ctl reload)
 3. Connect and issue ALTER ROLE / PASSWORD to set the new password
 4. edit pg_hba.conf again and restore the previous settings
 5. Reload the config file again

Difference between variable declaration syntaxes in Javascript (including global variables)?

Yes, there are a couple of differences, though in practical terms they're not usually big ones.

There's a fourth way, and as of ES2015 (ES6) there's two more. I've added the fourth way at the end, but inserted the ES2015 ways after #1 (you'll see why), so we have:

var a = 0;     // 1
let a = 0;     // 1.1 (new with ES2015)
const a = 0;   // 1.2 (new with ES2015)
a = 0;         // 2
window.a = 0;  // 3
this.a = 0;    // 4

Those statements explained

#1 var a = 0;

This creates a global variable which is also a property of the global object, which we access as window on browsers (or via this a global scope, in non-strict code). Unlike some other properties, the property cannot be removed via delete.

In specification terms, it creates an identifier binding on the object Environment Record for the global environment. That makes it a property of the global object because the global object is where identifier bindings for the global environment's object Environment Record are held. This is why the property is non-deletable: It's not just a simple property, it's an identifier binding.

The binding (variable) is defined before the first line of code runs (see "When var happens" below).

Note that on IE8 and earlier, the property created on window is not enumerable (doesn't show up in for..in statements). In IE9, Chrome, Firefox, and Opera, it's enumerable.


#1.1 let a = 0;

This creates a global variable which is not a property of the global object. This is a new thing as of ES2015.

In specification terms, it creates an identifier binding on the declarative Environment Record for the global environment rather than the object Environment Record. The global environment is unique in having a split Environment Record, one for all the old stuff that goes on the global object (the object Environment Record) and another for all the new stuff (let, const, and the functions created by class) that don't go on the global object.

The binding is created before any step-by-step code in its enclosing block is executed (in this case, before any global code runs), but it's not accessible in any way until the step-by-step execution reaches the let statement. Once execution reaches the let statement, the variable is accessible. (See "When let and const happen" below.)


#1.2 const a = 0;

Creates a global constant, which is not a property of the global object.

const is exactly like let except that you must provide an initializer (the = value part), and you cannot change the value of the constant once it's created. Under the covers, it's exactly like let but with a flag on the identifier binding saying its value cannot be changed. Using const does three things for you:

  1. Makes it a parse-time error if you try to assign to the constant.
  2. Documents its unchanging nature for other programmers.
  3. Lets the JavaScript engine optimize on the basis that it won't change.

#2 a = 0;

This creates a property on the global object implicitly. As it's a normal property, you can delete it. I'd recommend not doing this, it can be unclear to anyone reading your code later. If you use ES5's strict mode, doing this (assigning to a non-existent variable) is an error. It's one of several reasons to use strict mode.

And interestingly, again on IE8 and earlier, the property created not enumerable (doesn't show up in for..in statements). That's odd, particularly given #3 below.


#3 window.a = 0;

This creates a property on the global object explicitly, using the window global that refers to the global object (on browsers; some non-browser environments have an equivalent global variable, such as global on NodeJS). As it's a normal property, you can delete it.

This property is enumerable, on IE8 and earlier, and on every other browser I've tried.


#4 this.a = 0;

Exactly like #3, except we're referencing the global object through this instead of the global window. This won't work in strict mode, though, because in strict mode global code, this doesn't have a reference to the global object (it has the value undefined instead).


Deleting properties

What do I mean by "deleting" or "removing" a? Exactly that: Removing the property (entirely) via the delete keyword:

window.a = 0;
display("'a' in window? " + ('a' in window)); // displays "true"
delete window.a;
display("'a' in window? " + ('a' in window)); // displays "false"

delete completely removes a property from an object. You can't do that with properties added to window indirectly via var, the delete is either silently ignored or throws an exception (depending on the JavaScript implementation and whether you're in strict mode).

Warning: IE8 again (and presumably earlier, and IE9-IE11 in the broken "compatibility" mode): It won't let you delete properties of the window object, even when you should be allowed to. Worse, it throws an exception when you try (try this experiment in IE8 and in other browsers). So when deleting from the window object, you have to be defensive:

try {
    delete window.prop;
}
catch (e) {
    window.prop = undefined;
}

That tries to delete the property, and if an exception is thrown it does the next best thing and sets the property to undefined.

This only applies to the window object, and only (as far as I know) to IE8 and earlier (or IE9-IE11 in the broken "compatibility" mode). Other browsers are fine with deleting window properties, subject to the rules above.


When var happens

The variables defined via the var statement are created before any step-by-step code in the execution context is run, and so the property exists well before the var statement.

This can be confusing, so let's take a look:

display("foo in window? " + ('foo' in window)); // displays "true"
display("window.foo = " + window.foo);          // displays "undefined"
display("bar in window? " + ('bar' in window)); // displays "false"
display("window.bar = " + window.bar);          // displays "undefined"
var foo = "f";
bar = "b";
display("foo in window? " + ('foo' in window)); // displays "true"
display("window.foo = " + window.foo);          // displays "f"
display("bar in window? " + ('bar' in window)); // displays "true"
display("window.bar = " + window.bar);          // displays "b"

Live example:

_x000D_
_x000D_
display("foo in window? " + ('foo' in window)); // displays "true"_x000D_
display("window.foo = " + window.foo);          // displays "undefined"_x000D_
display("bar in window? " + ('bar' in window)); // displays "false"_x000D_
display("window.bar = " + window.bar);          // displays "undefined"_x000D_
var foo = "f";_x000D_
bar = "b";_x000D_
display("foo in window? " + ('foo' in window)); // displays "true"_x000D_
display("window.foo = " + window.foo);          // displays "f"_x000D_
display("bar in window? " + ('bar' in window)); // displays "true"_x000D_
display("window.bar = " + window.bar);          // displays "b"_x000D_
_x000D_
function display(msg) {_x000D_
  var p = document.createElement('p');_x000D_
  p.innerHTML = msg;_x000D_
  document.body.appendChild(p);_x000D_
}
_x000D_
_x000D_
_x000D_

As you can see, the symbol foo is defined before the first line, but the symbol bar isn't. Where the var foo = "f"; statement is, there are really two things: defining the symbol, which happens before the first line of code is run; and doing an assignment to that symbol, which happens where the line is in the step-by-step flow. This is known as "var hoisting" because the var foo part is moved ("hoisted") to the top of the scope, but the foo = "f" part is left in its original location. (See Poor misunderstood var on my anemic little blog.)


When let and const happen

let and const are different from var in a couple of ways. The way that's relevant to the question is that although the binding they define is created before any step-by-step code runs, it's not accessible until the let or const statement is reached.

So while this runs:

display(a);    // undefined
var a = 0;
display(a);    // 0

This throws an error:

display(a);    // ReferenceError: a is not defined
let a = 0;
display(a);

The other two ways that let and const differ from var, which aren't really relevant to the question, are:

  1. var always applies to the entire execution context (throughout global code, or throughout function code in the function where it appears), but let and const apply only within the block where they appear. That is, var has function (or global) scope, but let and const have block scope.

  2. Repeating var a in the same context is harmless, but if you have let a (or const a), having another let a or a const a or a var a is a syntax error.

Here's an example demonstrating that let and const take effect immediately in their block before any code within that block runs, but aren't accessible until the let or const statement:

var a = 0;
console.log(a);
if (true)
{
  console.log(a); // ReferenceError: a is not defined
  let a = 1;
  console.log(a);
}

Note that the second console.log fails, instead of accessing the a from outside the block.


Off-topic: Avoid cluttering the global object (window)

The window object gets very, very cluttered with properties. Whenever possible, strongly recommend not adding to the mess. Instead, wrap up your symbols in a little package and export at most one symbol to the window object. (I frequently don't export any symbols to the window object.) You can use a function to contain all of your code in order to contain your symbols, and that function can be anonymous if you like:

(function() {
    var a = 0; // `a` is NOT a property of `window` now

    function foo() {
        alert(a);   // Alerts "0", because `foo` can access `a`
    }
})();

In that example, we define a function and have it executed right away (the () at the end).

A function used in this way is frequently called a scoping function. Functions defined within the scoping function can access variables defined in the scoping function because they're closures over that data (see: Closures are not complicated on my anemic little blog).

Guzzlehttp - How get the body of a response from Guzzle 6?

For get response in JSON format :

  1.$response = (string) $res->getBody();
      $response =json_decode($response); // Using this you can access any key like below
     
     $key_value = $response->key_name; //access key  

  2. $response = json_decode($res->getBody(),true);
     
     $key_value =   $response['key_name'];//access key

Mockito matcher and array of primitives

I agree with Mutanos and Alecio. Further, one can check as many identical method calls as possible (verifying the subsequent calls in the production code, the order of the verify's does not matter). Here is the code:

import static org.mockito.AdditionalMatchers.*;

    verify(mockObject).myMethod(aryEq(new byte[] { 0 }));
    verify(mockObject).myMethod(aryEq(new byte[] { 1, 2 }));

Passing parameter using onclick or a click binding with KnockoutJS

A generic answer on how to handle click events with KnockoutJS...

Not a straight up answer to the question as asked, but probably an answer to the question most Googlers landing here have: use the click binding from KnockoutJS instead of onclick. Like this:

_x000D_
_x000D_
function Item(parent, txt) {_x000D_
  var self = this;_x000D_
  _x000D_
  self.doStuff = function(data, event) {_x000D_
    console.log(data, event);_x000D_
    parent.log(parent.log() + "\n  data = " + ko.toJSON(data));_x000D_
  };_x000D_
  _x000D_
  self.doOtherStuff = function(customParam, data, event) {_x000D_
    console.log(data, event);_x000D_
    parent.log(parent.log() + "\n  data = " + ko.toJSON(data) + ", customParam = " + customParam);_x000D_
  };_x000D_
  _x000D_
  self.txt = ko.observable(txt);_x000D_
}_x000D_
_x000D_
function RootVm(items) {_x000D_
  var self = this;_x000D_
  _x000D_
  self.doParentStuff = function(data, event) {_x000D_
    console.log(data, event);_x000D_
    self.log(self.log() + "\n  data = " + ko.toJSON(data));_x000D_
  };_x000D_
  _x000D_
  self.items = ko.observableArray([_x000D_
    new Item(self, "John Doe"),_x000D_
    new Item(self, "Marcus Aurelius")_x000D_
  ]);_x000D_
  self.log = ko.observable("Started logging...");_x000D_
}_x000D_
_x000D_
ko.applyBindings(new RootVm());
_x000D_
.parent { background: rgba(150, 150, 200, 0.5); padding: 2px; margin: 5px; }_x000D_
button { margin: 2px 0; font-family: consolas; font-size: 11px; }_x000D_
pre { background: #eee; border: 1px solid #ccc; padding: 5px; }
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.0/knockout-min.js"></script>_x000D_
_x000D_
<div data-bind="foreach: items">_x000D_
  <div class="parent">_x000D_
    <span data-bind="text: txt"></span><br>_x000D_
    <button data-bind="click: doStuff">click: doStuff</button><br>_x000D_
    <button data-bind="click: $parent.doParentStuff">click: $parent.doParentStuff</button><br>_x000D_
    <button data-bind="click: $root.doParentStuff">click: $root.doParentStuff</button><br>_x000D_
    <button data-bind="click: function(data, event) { $parent.log($parent.log() + '\n  data = ' + ko.toJSON(data)); }">click: function(data, event) { $parent.log($parent.log() + '\n  data = ' + ko.toJSON(data)); }</button><br>_x000D_
    <button data-bind="click: doOtherStuff.bind($data, 'test 123')">click: doOtherStuff.bind($data, 'test 123')</button><br>_x000D_
    <button data-bind="click: function(data, event) { doOtherStuff('test 123', $data, event); }">click: function(data, event) { doOtherStuff($data, 'test 123', event); }</button><br>_x000D_
  </div>_x000D_
</div>_x000D_
_x000D_
Click log:_x000D_
<pre data-bind="text: log"></pre>
_x000D_
_x000D_
_x000D_


**A note about the actual question...*

The actual question has one interesting bit:

// Uh oh! Modifying the DOM....
place.innerHTML = "somthing"

Don't do that! Don't modify the DOM like that when using an MVVM framework like KnockoutJS, especially not the piece of the DOM that is your own parent. If you would do this the button would disappear (if you replace your parent's innerHTML you yourself will be gone forever ever!).

Instead, modify the View Model in your handler instead, and have the View respond. For example:

_x000D_
_x000D_
function RootVm() {_x000D_
  var self = this;_x000D_
  self.buttonWasClickedOnce = ko.observable(false);_x000D_
  self.toggle = function(data, event) {_x000D_
    self.buttonWasClickedOnce(!self.buttonWasClickedOnce());_x000D_
  };_x000D_
}_x000D_
_x000D_
ko.applyBindings(new RootVm());
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.0/knockout-min.js"></script>_x000D_
_x000D_
<div>_x000D_
  <div  data-bind="visible: !buttonWasClickedOnce()">_x000D_
    <button data-bind="click: toggle">Toggle!</button>_x000D_
  </div>_x000D_
  <div data-bind="visible: buttonWasClickedOnce">_x000D_
    Can be made visible with toggle..._x000D_
    <button data-bind="click: toggle">Untoggle!</button>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Base64 length calculation?

Here is a function to calculate the original size of an encoded Base 64 file as a String in KB:

private Double calcBase64SizeInKBytes(String base64String) {
    Double result = -1.0;
    if(StringUtils.isNotEmpty(base64String)) {
        Integer padding = 0;
        if(base64String.endsWith("==")) {
            padding = 2;
        }
        else {
            if (base64String.endsWith("=")) padding = 1;
        }
        result = (Math.ceil(base64String.length() / 4) * 3 ) - padding;
    }
    return result / 1000;
}

SQL Server: What is the difference between CROSS JOIN and FULL OUTER JOIN?

They are the same concepts, apart from the NULL value returned.

See below:

declare @table1 table( col1 int, col2 int );
insert into @table1 select 1, 11 union all select 2, 22;

declare @table2 table ( col1 int, col2 int );
insert into @table2 select 10, 101 union all select 2, 202;

select
    t1.*,
    t2.*
from @table1 t1
full outer join @table2 t2 on t1.col1 = t2.col1
order by t1.col1, t2.col1;

/* full outer join
col1        col2        col1        col2
----------- ----------- ----------- -----------
NULL        NULL        10          101
1           11          NULL        NULL
2           22          2           202
*/

select
    t1.*,
    t2.*
from @table1 t1
cross join @table2 t2
order by t1.col1, t2.col1;

/* cross join
col1        col2        col1        col2
----------- ----------- ----------- -----------
1           11          2           202
1           11          10          101
2           22          2           202
2           22          10          101
*/

Redirect to an external URL from controller action in Spring MVC

Another way to do it is just to use the sendRedirect method:

@RequestMapping(
    value = "/",
    method = RequestMethod.GET)
public void redirectToTwitter(HttpServletResponse httpServletResponse) throws IOException {
    httpServletResponse.sendRedirect("https://twitter.com");
}

How do I get the logfile from an Android device?

Thanks to user1354692 I could made it more easy, with only one line! the one he has commented:

try {
    File file = new File(Environment.getExternalStorageDirectory(), String.valueOf(System.currentTimeMillis()));
    Runtime.getRuntime().exec("logcat -d -v time -f " + file.getAbsolutePath());}catch (IOException e){}

SQL Server Script to create a new user

You can use:

CREATE LOGIN <login name> WITH PASSWORD = '<password>' ; GO 

To create the login (See here for more details).

Then you may need to use:

CREATE USER user_name 

To create the user associated with the login for the specific database you want to grant them access too.

(See here for details)

You can also use:

GRANT permission  [ ,...n ] ON SCHEMA :: schema_name

To set up the permissions for the schema's that you assigned the users to.

(See here for details)

Two other commands you might find useful are ALTER USER and ALTER LOGIN.

CSS float right not working correctly

You have not used float:left command for your text.

Find a file by name in Visual Studio Code

It is CMD + P (or CTRL + P) by default. However the keyboard bindings may differ according to your preferences.

To know your bindings go to the "Keyboard Shortcuts" settings and search for "Go to File"

How to pass macro definition from "make" command line arguments (-D) to C source code?

$ cat x.mak
all:
    echo $(OPTION)
$ make -f x.mak 'OPTION=-DPASSTOC=42'
echo -DPASSTOC=42
-DPASSTOC=42

How to align checkboxes and their labels consistently cross-browsers

Use simply vertical-align: sub, as pokrishka already suggested.

Fiddle

HTML Code:

<div class="checkboxes">
    <label for="check1">Test</label>
    <input id="check1" type="checkbox"></input>
</div>

CSS Code:

.checkboxes input {
    vertical-align: sub;
}

Call int() function on every list element?

Another way,

for i, v in enumerate(numbers): numbers[i] = int(v)

READ_EXTERNAL_STORAGE permission for Android

In addition of all answers. You can also specify the minsdk to apply with this annotation

@TargetApi(_apiLevel_)

I used this in order to accept this request even my minsdk is 18. What it does is that the method only runs when device targets "_apilevel_" and upper. Here's my method:

    @TargetApi(23)
void solicitarPermisos(){

    if (ContextCompat.checkSelfPermission(this,permiso)
            != PackageManager.PERMISSION_GRANTED) {

        // Should we show an explanation?
        if (shouldShowRequestPermissionRationale(
                Manifest.permission.READ_EXTERNAL_STORAGE)) {
            // Explain to the user why we need to read the contacts
        }

        requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
                1);

        // MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE is an
        // app-defined int constant that should be quite unique

        return;
    }

}

Laravel 4: Redirect to a given url

Yes, it's

use Illuminate\Support\Facades\Redirect;

return Redirect::to('http://heera.it');

Check the documentation.

Update: Redirect::away('url') (For external link, Laravel Version 4.19):

public function away($path, $status = 302, $headers = array())
{
    return $this->createRedirect($path, $status, $headers);
}

C# Pass Lambda Expression as Method Parameter

You should use a delegate type and specify that as your command parameter. You could use one of the built in delegate types - Action and Func.

In your case, it looks like your delegate takes two parameters, and returns a result, so you could use Func:

List<IJob> GetJobs(Func<FullTimeJob, Student, FullTimeJob> projection)

You could then call your GetJobs method passing in a delegate instance. This could be a method which matches that signature, an anonymous delegate, or a lambda expression.

P.S. You should use PascalCase for method names - GetJobs, not getJobs.

Need a row count after SELECT statement: what's the optimal SQL approach?

Approach 2 will always return a count that matches your result set.

I suggest you link the sub-query to your outer query though, to guarantee that the condition on your count matches the condition on the dataset.

SELECT 
  mt.my_row,
 (SELECT COUNT(mt2.my_row) FROM my_table mt2 WHERE mt2.foo = mt.foo) as cnt
FROM my_table mt
WHERE mt.foo = 'bar';

Get Maven artifact version at runtime

I know it's a very late answer but I'd like to share what I did as per this link:

I added the below code to the pom.xml:

        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
            <executions>
                <execution>
                    <id>build-info</id>
                    <goals>
                        <goal>build-info</goal>
                    </goals>
                </execution>
            </executions>
        </plugin>

And this Advice Controller in order to get the version as model attribute:

import java.io.IOException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.info.BuildProperties;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ModelAttribute;

@ControllerAdvice
public class CommonControllerAdvice
{
       @Autowired
       BuildProperties buildProperties;
    
       @ModelAttribute("version")
       public String getVersion() throws IOException
       {
          String version = buildProperties.getVersion();
          return version;
       }
    }

Most efficient way to concatenate strings in JavaScript?

Three years past since this question was answered but I will provide my answer anyway :)

Actually, accepted answer is not fully correct. Jakub's test uses hardcoded string which allows JS engine to optimize code execution (Google's V8 is really good in this stuff!). But as soon as you use completely random strings (here is JSPerf) then string concatenation will be on a second place.

Django download a file

I use this method:

{% if quote.myfile %}
    <div class="">
        <a role="button" 
            href="{{ quote.myfile.url }}"
            download="{{ quote.myfile.url }}"
            class="btn btn-light text-dark ml-0">
            Download attachment
        </a>
    </div>
{% endif %}

How to print the ld(linker) search path

You can do this by executing the following command:

ld --verbose | grep SEARCH_DIR | tr -s ' ;' \\012

gcc passes a few extra -L paths to the linker, which you can list with the following command:

gcc -print-search-dirs | sed '/^lib/b 1;d;:1;s,/[^/.][^/]*/\.\./,/,;t 1;s,:[^=]*=,:;,;s,;,;  ,g' | tr \; \\012

The answers suggesting to use ld.so.conf and ldconfig are not correct because they refer to the paths searched by the runtime dynamic linker (i.e. whenever a program is executed), which is not the same as the path searched by ld (i.e. whenever a program is linked).

Java verify void method calls n times with Mockito

The necessary method is Mockito#verify:

public static <T> T verify(T mock,
                           VerificationMode mode)

mock is your mocked object and mode is the VerificationMode that describes how the mock should be verified. Possible modes are:

verify(mock, times(5)).someMethod("was called five times");
verify(mock, never()).someMethod("was never called");
verify(mock, atLeastOnce()).someMethod("was called at least once");
verify(mock, atLeast(2)).someMethod("was called at least twice");
verify(mock, atMost(3)).someMethod("was called at most 3 times");
verify(mock, atLeast(0)).someMethod("was called any number of times"); // useful with captors
verify(mock, only()).someMethod("no other method has been called on the mock");

You'll need these static imports from the Mockito class in order to use the verify method and these verification modes:

import static org.mockito.Mockito.atLeast;
import static org.mockito.Mockito.atLeastOnce;
import static org.mockito.Mockito.atMost;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.only;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;

So in your case the correct syntax will be:

Mockito.verify(mock, times(4)).send()

This verifies that the method send was called 4 times on the mocked object. It will fail if it was called less or more than 4 times.


If you just want to check, if the method has been called once, then you don't need to pass a VerificationMode. A simple

verify(mock).someMethod("was called once");

would be enough. It internally uses verify(mock, times(1)).someMethod("was called once");.


It is possible to have multiple verification calls on the same mock to achieve a "between" verification. Mockito doesn't support something like this verify(mock, between(4,6)).someMethod("was called between 4 and 6 times");, but we can write

verify(mock, atLeast(4)).someMethod("was called at least four times ...");
verify(mock, atMost(6)).someMethod("... and not more than six times");

instead, to get the same behaviour. The bounds are included, so the test case is green when the method was called 4, 5 or 6 times.

Read lines from a file into a Bash array

The readarray command (also spelled mapfile) was introduced in bash 4.0.

readarray -t a < /path/to/filename

Print a list in reverse order with range()?

Very often asked question is whether range(9, -1, -1) better than reversed(range(10)) in Python 3? People who have worked in other languages with iterators immediately tend to think that reversed() must cache all values and then return in reverse order. Thing is that Python's reversed() operator doesn't work if the object is just an iterator. The object must have one of below two for reversed() to work:

  1. Either support len() and integer indexes via []
  2. Or have __reversed__() method implemented.

If you try to use reversed() on object that has none of above then you will get:

>>> [reversed((x for x in range(10)))]
TypeError: 'generator' object is not reversible

So in short, Python's reversed() is only meant on array like objects and so it should have same performance as forward iteration.

But what about range()? Isn't that a generator? In Python 3 it is generator but wrapped in a class that implements both of above. So range(100000) doesn't take up lot of memory but it still supports efficient indexing and reversing.

So in summary, you can use reversed(range(10)) without any hit on performance.

What is the difference between encode/decode?

mybytestring.encode(somecodec) is meaningful for these values of somecodec:

  • base64
  • bz2
  • zlib
  • hex
  • quopri
  • rot13
  • string_escape
  • uu

I am not sure what decoding an already decoded unicode text is good for. Trying that with any encoding seems to always try to encode with the system's default encoding first.

Python regex for integer?

You are apparently using Django.

You are probably better off just using models.IntegerField() instead of models.TextField(). Not only will it do the check for you, but it will give you the error message translated in several langs, and it will cast the value from it's type in the database to the type in your Python code transparently.

How do I vertical center text next to an image in html/css?

One basic way that comes to mind would be to put the item into a table and have two cells, one with the text, the other with the image, and use style="valign:center" with the tags.

Where do I download JDBC drivers for DB2 that are compatible with JDK 1.5?

I know its late but i recently ran into this situation. After wasting entire day I finally found the solution. I am suprised that I got this info on oracle's website whereas this seems nowhere to be found on IBM's website.

If you want to use JDBC drivers for DB2 that are compatible with JDK 1.5 or 1.4 , you need to use the jar db2jcc.jar, which is available in SQLLIB/java/ folder of your db2 installation.

How to check if a date is in a given range?

It's not necessary to convert to timestamp to do the comparison, given that the strings are validated as dates in 'YYYY-MM-DD' canonical format.

This test will work:

( ( $date_from_user >= $start_date ) && ( $date_from_user <= $end_date ) )

given:

$start_date     = '2009-06-17';
$end_date       = '2009-09-05';
$date_from_user = '2009-08-28';

NOTE: Comparing strings like this does allow for "non-valid" dates e.g. (December 32nd ) '2009-13-32' and for weirdly formatted strings '2009/3/3', such that a string comparison will NOT be equivalent to a date or timestamp comparison. This works ONLY if the date values in the strings are in a CONSISTENT and CANONICAL format.

EDIT to add a note here, elaborating on the obvious.

By CONSISTENT, I mean for example that the strings being compared must be in identical format: the month must always be two characters, the day must always be two characters, and the separator character must always be a dash. We can't reliably compare "strings" that aren't four character year, two character month, two character day. If we had a mix of one character and two character months in the strings, for example, we'd get unexpected result when we compared, '2009-9-30' to '2009-10-11'. We humanly see "9" as being less than "10", but a string comparison will see '2009-9' as greater than '2009-1'. We don't necessarily need to have a dash separator characters; we could just as reliably compare strings in 'YYYYMMDD' format; if there is a separator character, it has to always be there and always be the same.

By CANONICAL, I mean that a format that will result in strings that will be sorted in date order. That is, the string will have a representation of "year" first, then "month", then "day". We can't reliably compare strings in 'MM-DD-YYYY' format, because that's not canonical. A string comparison would compare the MM (month) before it compared YYYY (year) since the string comparison works from left to right.) A big benefit of the 'YYYY-MM-DD' string format is that it is canonical; dates represented in this format can reliably be compared as strings.

[ADDENDUM]

If you do go for the php timestamp conversion, be aware of the limitations.

On some platforms, php does not support timestamp values earlier than 1970-01-01 and/or later than 2038-01-19. (That's the nature of the unix timestamp 32-bit integer.) Later versions pf php (5.3?) are supposed to address that.

The timezone can also be an issue, if you aren't careful to use the same timezone when converting from string to timestamp and from timestamp back to string.

HTH

How do I recognize "#VALUE!" in Excel spreadsheets?

in EXCEL 2013 i had to use IF function 2 times: 1st to identify error with ISERROR and 2nd to identify the specific type of error by ERROR.TYPE=3 in order to address this type of error. This way you can differentiate between error you want and other types.

Is it possible to animate scrollTop with jQuery?

$(".scroll-top").on("click", function(e){
   e.preventDefault();
   $("html, body").animate({scrollTop:"0"},600);
});

Run JavaScript code on window close or page refresh?

Trying this in React, if the function does not gets executed try wrapping it in an IIFE like this:


  window.onbeforeunload = (function () {
    alert('GrrrR!!!')
    return null;
  })()

How do I escape double quotes in attributes in an XML String in T-SQL?

Wouldn't that be &quot; in xml? i.e.

"hi &quot;mom&quot; lol" 

**edit: ** tested; works fine:

declare @xml xml

 set @xml = '<transaction><item value="hi &quot;mom&quot; lol" 
    ItemId="106"  ItemType="2"  instanceId="215923801"  dataSetId="1" /></transaction>'

select @xml.value('(//item/@value)[1]','varchar(50)')

How to resize datagridview control when form resizes

In your form constructor you could create an event handler like this:

this.SizeChanged(frm_sizeChanged);

Then create an event handler that resizes the grid appropriately, example:

private void frm_sizeChanged(object sender, EventArgs e)
{
     dataGrid.Size = new Size(100, 200);
}

Replacing those numbers with whatever you'd like.

How do I find the distance between two points?

dist = sqrt( (x2 - x1)**2 + (y2 - y1)**2 )

As others have pointed out, you can also use the equivalent built-in math.hypot():

dist = math.hypot(x2 - x1, y2 - y1)

How do I exit a foreach loop in C#?

Use break.


Unrelated to your question, I see in your code the line:

Violated = !(name.firstname == null) ? false : true;

In this line, you take a boolean value (name.firstname == null). Then, you apply the ! operator to it. Then, if the value is true, you set Violated to false; otherwise to true. So basically, Violated is set to the same value as the original expression (name.firstname == null). Why not use that, as in:

Violated = (name.firstname == null);

How to search JSON tree with jQuery

I found ifaour's example of jQuery.each() to be helpful, but would add that jQuery.each() can be broken (that is, stopped) by returning false at the point where you've found what you're searching for:

$.each(json.people.person, function(i, v) {
        if (v.name == "Peter") {
            // found it...
            alert(v.age);
            return false; // stops the loop
        }
});

How do you run a .exe with parameters using vba's shell()?

Here are some examples of how to use Shell in VBA.
Open stackoverflow in Chrome.

Call Shell("C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" & _
 " -url" & " " & "www.stackoverflow.com",vbMaximizedFocus)

Open some text file.

Call Shell ("notepad C:\Users\user\Desktop\temp\TEST.txt")

Open some application.

Call Shell("C:\Temp\TestApplication.exe",vbNormalFocus)

Hope this helps!

MySQL: Set user variable from result of query

First lets take a look at how can we define a variable in mysql

To define a varible in mysql it should start with '@' like @{variable_name} and this '{variable_name}', we can replace it with our variable name.

Now, how to assign a value in a variable in mysql. For this we have many ways to do that

  1. Using keyword 'SET'.

Example :-

mysql >  SET @a = 1;
  1. Without using keyword 'SET' and using ':='.

Example:-

mysql > @a:=1;
  1. By using 'SELECT' statement.

Example:-

mysql > select 1 into @a;

Here @a is user defined variable and 1 is going to be assigned in @a.

Now how to get or select the value of @{variable_name}.

we can use select statement like

Example :-

mysql > select @a;

it will show the output and show the value of @a.

Now how to assign a value from a table in a variable.

For this we can use two statement like :-

1.

@a := (select emp_name from employee where emp_id = 1);
select emp_name into @a from employee where emp_id = 1;

Always be careful emp_name must return single value otherwise it will throw you a error in this type statements.

refer this:- http://www.easysolutionweb.com/sql-pl-sql/how-to-assign-a-value-in-a-variable-in-mysql

Unable to open debugger port in IntelliJ IDEA

I solved the issue by this way.

  1. I tried to kill all the java.exe processes but it was useless.
  2. Then I tried deleting the Tomcat server
  3. I re-deployed the project and restarted the project and it worked.

See these links for more information:

Delete Tomcat Delete Tomcat

Add a new Tomcat Add a new Tomcat

How to get the current date and time of your timezone in Java?

Date in 24 hrs format

Output:14/02/2020 19:56:49 PM

 Date date = new Date();
 DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss aa");
 dateFormat.setTimeZone(TimeZone.getTimeZone("Europe/London"));
 System.out.println("date is: "+dateFormat.format(date));

Date in 12 hrs format

Output:14/02/2020 07:57:11 PM

 Date date = new Date();`enter code here`
 DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss aa");
 dateFormat.setTimeZone(TimeZone.getTimeZone("Europe/London"));
 System.out.println("date is: "+dateFormat.format(date));

How to find the socket connection state in C?

Very simple, as pictured in the recv.

To check that you will want to read 1 byte from the socket with MSG_PEEK and MSG_DONT_WAIT. This will not dequeue data (PEEK) and the operation is nonblocking (DONT_WAIT)

while (recv(client->socket,NULL,1, MSG_PEEK | MSG_DONTWAIT) != 0) {
    sleep(rand() % 2); // Sleep for a bit to avoid spam
    fflush(stdin);
    printf("I am alive: %d\n", socket);
}

// When the client has disconnected, this line will execute
printf("Client %d went away :(\n", client->socket);

Found the example here.

Letter Count on a string

def count_letter(word, char):
    count = 0
    for char in word:
        if char == word:
            count += 1
    return count        #Your return is inside your for loop
r = count_word("banana", "a")
print r

3

Make div fill remaining space along the main axis in flexbox

Basically I was trying to get my code to have a middle section on a 'row' to auto-adjust to the content on both sides (in my case, a dotted line separator). Like @Michael_B suggested, the key is using display:flex on the row container and at least making sure your middle container on the row has a flex-grow value of at least 1 higher than the outer containers (if outer containers don't have any flex-grow properties applied, middle container only needs 1 for flex-grow).

Here's a pic of what I was trying to do and sample code for how I solved it.

enter image description here

_x000D_
_x000D_
.row {
  background: lightgray;
  height: 30px;
  width: 100%;
  display: flex;
  align-items:flex-end;
  margin-top:5px;
}
.left {
  background:lightblue;
}
.separator{
  flex-grow:1;
  border-bottom:dotted 2px black;
}
.right {
  background:coral;
}
_x000D_
<div class="row">
  <div class="left">Left</div>
  <div class="separator"></div>
  <div class="right">Right With Text</div>
</div>
<div class="row">
  <div class="left">Left With More Text</div>
  <div class="separator"></div>
  <div class="right">Right</div>
</div>
<div class="row">
  <div class="left">Left With Text</div>
  <div class="separator"></div>
  <div class="right">Right With More Text</div>
</div>
_x000D_
_x000D_
_x000D_

align 3 images in same row with equal spaces?

I assumed the first DIV is #content :

<div id="content">
   <img src="@Url.Content("~/images/image1.bmp")" alt="" />
   <img src="@Url.Content("~/images/image2.bmp")" alt="" />
   <img src="@Url.Content("~/images/image3.bmp")" alt="" />
</div>

And CSS :

#content{
         width: 700px;
         display: block;
         height: auto;
     }
     #content > img{
        float: left; width: 200px;
        height: 200px;
        margin: 5px 8px;
     }

Change border-bottom color using jquery?

$("selector").css("border-bottom-color", "#fff");
  1. construct your jQuery object which provides callable methods first. In this case, say you got an #mydiv, then $("#mydiv")
  2. call the .css() method provided by jQuery to modify specified object's css property values.

Is it possible to use vh minus pixels in a CSS calc()?

It does work indeed. Issue was with my less compiler. It was compiled in to:

.container {
  min-height: calc(-51vh);
}

Fixed with the following code in less file:

.container {
  min-height: calc(~"100vh - 150px");
}

Thanks to this link: Less Aggressive Compilation with CSS3 calc

Hide axis values but keep axis tick labels in matplotlib

Without a subplots, you can universally remove the ticks like this:

plt.xticks([])
plt.yticks([])

Java : How to determine the correct charset encoding of a stream

I have used this library, similar to jchardet for detecting encoding in Java: http://code.google.com/p/juniversalchardet/

SVG Positioning

Everything in the g element is positioned relative to the current transform matrix.

To move the content, just put the transformation in the g element:

<g transform="translate(20,2.5) rotate(10)">
    <rect x="0" y="0" width="60" height="10"/>
</g>

Links: Example from the SVG 1.1 spec

How to generate access token using refresh token through google drive API?

Just posting my answer in case it helps anyone as I spent an hour to figure it out :)

First of all two very helpful link related to google api and fetching data from any of google services:

https://developers.google.com/analytics/devguides/config/mgmt/v3/quickstart/web-php

https://developers.google.com/identity/protocols/OAuth2WebServer

Furthermore, when using the following method:

$client->setAccessToken($token)

The $token needs to be the full object returned by the google when making authorization request, not the only access_token which you get inside the object so if you get the object lets say:

{"access_token":"xyz","token_type":"Bearer","expires_in":3600,"refresh_token":"mno","created":1532363626}

then you need to give:

$client->setAccessToken('{"access_token":"xyz","token_type":"Bearer","expires_in":3600,"refresh_token":"mno","created":1532363626}')

Not

$client->setAccessToken('xyz')

And then even if your access_token is expired, google will refresh it itself by using the refresh_token in the access_token object.

Working with $scope.$emit and $scope.$on

According to the angularjs event docs the receiving end should be containing arguments with a structure like

@params

-- {Object} event being the event object containing info on the event

-- {Object} args that are passed by the callee (Note that this can only be one so better to send in a dictionary object always)

$scope.$on('fooEvent', function (event, args) { console.log(args) }); From your code

Also if you are trying to get a shared piece of information to be available accross different controllers there is an another way to achieve that and that is angular services.Since the services are singletons information can be stored and fetched across controllers.Simply create getter and setter functions in that service, expose these functions, make global variables in the service and use them to store the info

Decode HTML entities in Python string?

This probably isnt relevant here. But to eliminate these html entites from an entire document, you can do something like this: (Assume document = page and please forgive the sloppy code, but if you have ideas as to how to make it better, Im all ears - Im new to this).

import re
import HTMLParser

regexp = "&.+?;" 
list_of_html = re.findall(regexp, page) #finds all html entites in page
for e in list_of_html:
    h = HTMLParser.HTMLParser()
    unescaped = h.unescape(e) #finds the unescaped value of the html entity
    page = page.replace(e, unescaped) #replaces html entity with unescaped value

How to convert a color integer to a hex String in Android?

Here is what i did

 int color=//your color
 Integer.toHexString(color).toUpperCase();//upercase with alpha
 Integer.toHexString(color).toUpperCase().substring(2);// uppercase without alpha

Thanks guys you answers did the thing

Finding repeated words on a string and counting the repetitions

public class StringsCount{

    public static void main(String args[]) {

        String value = "This is testing Program testing Program";

        String item[] = value.split(" ");

        HashMap<String, Integer> map = new HashMap<>();

        for (String t : item) {
            if (map.containsKey(t)) {
                map.put(t, map.get(t) + 1);

            } else {
                map.put(t, 1);
            }
        }
        Set<String> keys = map.keySet();
        for (String key : keys) {
            System.out.println(key);
            System.out.println(map.get(key));
        }

    }
}

How to ignore SSL certificate errors in Apache HttpClient 4.0

You need to create a SSLContext with your own TrustManager and create HTTPS scheme using this context. Here is the code,

SSLContext sslContext = SSLContext.getInstance("SSL");

// set up a TrustManager that trusts everything
sslContext.init(null, new TrustManager[] { new X509TrustManager() {
            public X509Certificate[] getAcceptedIssuers() {
                    System.out.println("getAcceptedIssuers =============");
                    return null;
            }

            public void checkClientTrusted(X509Certificate[] certs,
                            String authType) {
                    System.out.println("checkClientTrusted =============");
            }

            public void checkServerTrusted(X509Certificate[] certs,
                            String authType) {
                    System.out.println("checkServerTrusted =============");
            }
} }, new SecureRandom());

SSLSocketFactory sf = new SSLSocketFactory(sslContext);
Scheme httpsScheme = new Scheme("https", 443, sf);
SchemeRegistry schemeRegistry = new SchemeRegistry();
schemeRegistry.register(httpsScheme);

// apache HttpClient version >4.2 should use BasicClientConnectionManager
ClientConnectionManager cm = new SingleClientConnManager(schemeRegistry);
HttpClient httpClient = new DefaultHttpClient(cm);

How can a Java program get its own process ID?

The following method tries to extract the PID from java.lang.management.ManagementFactory:

private static String getProcessId(final String fallback) {
    // Note: may fail in some JVM implementations
    // therefore fallback has to be provided

    // something like '<pid>@<hostname>', at least in SUN / Oracle JVMs
    final String jvmName = ManagementFactory.getRuntimeMXBean().getName();
    final int index = jvmName.indexOf('@');

    if (index < 1) {
        // part before '@' empty (index = 0) / '@' not found (index = -1)
        return fallback;
    }

    try {
        return Long.toString(Long.parseLong(jvmName.substring(0, index)));
    } catch (NumberFormatException e) {
        // ignore
    }
    return fallback;
}

Just call getProcessId("<PID>"), for instance.

A simple algorithm for polygon intersection

You have not given us your representation of a polygon. So I am choosing (more like suggesting) one for you :)

Represent each polygon as one big convex polygon, and a list of smaller convex polygons which need to be 'subtracted' from that big convex polygon.

Now given two polygons in that representation, you can compute the intersection as:

Compute intersection of the big convex polygons to form the big polygon of the intersection. Then 'subtract' the intersections of all the smaller ones of both to get a list of subracted polygons.

You get a new polygon following the same representation.

Since convex polygon intersection is easy, this intersection finding should be easy too.

This seems like it should work, but I haven't given it more deeper thought as regards to correctness/time/space complexity.

Moment.js with Vuejs

For moment.js at Vue 3

npm install moment --save

Then in any component

import moment from 'moment'

...

export default {
  created: function () {
    this.moment = moment;
  },

...

<div class="comment-line">
   {{moment(new Date()).format('DD.MM.YYYY [&nbsp;] HH:mm')}}
</div>

sqlite copy data from one table to another

INSERT INTO Destination SELECT * FROM Source;

See SQL As Understood By SQLite: INSERT for a formal definition.

ERROR 2003 (HY000): Can't connect to MySQL server on '127.0.0.1' (111)

If you are using ubuntu, you have to use the following steps to avoid this error(if there is no replication enabled):

  1. run the command vim /etc/mysql/my.cnf
  2. comment bind-address = 127.0.0.1 using the # symbol
  3. restart your mysql server once.

Update

In Step 1, if you cannot find bind-address in the my.cnf file, look for it in /etc/mysql/mysql.conf.d/mysqld.cnf file.

Update in case of MySQL replication enabled

Try to connect MySQL server on IP for which MySQL server is bind in 'my.cnfinstead oflocalhost or 127.0.0.1`.

How to escape single quotes in MySQL

' is the escape character. So your string should be:

This is Ashok''s Pen

If you are using some front-end code, you need to do a string replace before sending the data to the stored procedure.

For example, in C# you can do

value = value.Replace("'", "''");

and then pass value to the stored procedure.

jQuery - How to dynamically add a validation rule

You need to call .validate() before you can add rules this way, like this:

$("#myForm").validate(); //sets up the validator
$("input[id*=Hours]").rules("add", "required");

The .validate() documentation is a good guide, here's the blurb about .rules("add", option):

Adds the specified rules and returns all rules for the first matched element. Requires that the parent form is validated, that is, $("form").validate() is called first.

AngularJS ng-class if-else expression

Use nested inline if-then statements (Ternary Operators)

<div ng-class=" ... ? 'class-1' : ( ... ? 'class-2' : 'class-3')">

for example :

<div ng-class="apt.name.length >= 15 ? 'col-md-12' : (apt.name.length >= 10 ? 'col-md-6' : 'col-md-4')">
    ...
</div>

And make sure it's readable by your colleagues :)

Changing tab bar item image and text color iOS

From here.

Each tab bar item has a title, selected image, unselected image, and a badge value.

Use the Image Tint (selectedImageTintColor) field to specify the bar item’s tint color when that tab is selected. By default, that color is blue.

Python No JSON object could be decoded

It seems that you have invalid JSON. In that case, that's totally dependent on the data the server sends you which you have not shown. I would suggest running the response through a JSON validator.

How do I use LINQ Contains(string[]) instead of Contains(string)

You should write it the other way around, checking your priviliged user id list contains the id on that row of table:

string[] search = new string[] { "2", "3" };
var result = from x in xx where search.Contains(x.uid.ToString()) select x;

LINQ behaves quite bright here and converts it to a good SQL statement:

sp_executesql N'SELECT [t0].[uid]
FROM [dbo].[xx] AS [t0]
WHERE (CONVERT(NVarChar,[t0].[uid]))
IN (@p0, @p1)',N'@p0 nvarchar(1),
@p1 nvarchar(1)',@p0=N'2',@p1=N'3'

which basicly embeds the contents of the 'search' array into the sql query, and does the filtering with 'IN' keyword in SQL.

Generate random integers between 0 and 9

In case of continuous numbers randint or randrange are probably the best choices but if you have several distinct values in a sequence (i.e. a list) you could also use choice:

>>> import random
>>> values = list(range(10))
>>> random.choice(values)
5

choice also works for one item from a not-continuous sample:

>>> values = [1, 2, 3, 5, 7, 10]
>>> random.choice(values)
7

If you need it "cryptographically strong" there's also a secrets.choice in python 3.6 and newer:

>>> import secrets
>>> values = list(range(10))
>>> secrets.choice(values)
2

Pass parameter to EventHandler

Timer.Elapsed expects method of specific signature (with arguments object and EventArgs). If you want to use your PlayMusicEvent method with additional argument evaluated during event registration, you can use lambda expression as an adapter:

myTimer.Elapsed += new ElapsedEventHandler((sender, e) => PlayMusicEvent(sender, e, musicNote));

Edit: you can also use shorter version:

myTimer.Elapsed += (sender, e) => PlayMusicEvent(sender, e, musicNote);

Easiest way to compare arrays in C#

I did this in visual studios and it worked perfectly; comparing arrays index by index with short this code.

private void compareButton_Click(object sender, EventArgs e)
        {
            int[] answer = { 1, 3, 4, 6, 8, 9, 5, 4, 0, 6 };
            int[] exam = { 1, 2, 3, 6, 8, 9, 5, 4, 0, 7 };

            int correctAnswers = 0;
            int wrongAnswers = 0;

            for (int index = 0; index < answer.Length; index++)
            {
                if (answer[index] == exam[index])
                {
                    correctAnswers += 1;
                }
                else
                {
                    wrongAnswers += 1;
                }
            }

            outputLabel.Text = ("The matching numbers are " + correctAnswers +
                "\n" + "The non matching numbers are " + wrongAnswers);
        }

the output will be; The matching numbers are 7 The non matching numbers are 3

Java: int[] array vs int array[]

No, there is no difference. But I prefer using int[] array as it is more readable.

input[type='text'] CSS selector does not apply to default-type text inputs?

Because, it is not supposed to do that.

input[type=text] { } is an attribute selector, and will only select those element, with the matching attribute.

Programmatically scroll to a specific position in an Android ListView

I have set OnGroupExpandListener and override onGroupExpand() as:

and use setSelectionFromTop() method which Sets the selected item and positions the selection y pixels from the top edge of the ListView. (If in touch mode, the item will not be selected but it will still be positioned appropriately.) (android docs)

    yourlist.setOnGroupExpandListener (new ExpandableListView.OnGroupExpandListener()
    {

        @Override
        public void onGroupExpand(int groupPosition) {

            expList.setSelectionFromTop(groupPosition, 0);
            //your other code
        }
    });

Javascript : get <img> src and set as variable?

As long as the script is after the img, then:

var youtubeimgsrc = document.getElementById("youtubeimg").src;

See getElementById in the DOM specification.

If the script is before the img, then of course the img doesn't exist yet, and that doesn't work. This is one reason why many people recommend putting scripts at the end of the body element.


Side note: It doesn't matter in your case because you've used an absolute URL, but if you used a relative URL in the attribute, like this:

<img id="foo" src="/images/example.png">

...the src reflected property will be the resolved URL — that is, the absolute URL that that turns into. So if that were on the page http://www.example.com, document.getElementById("foo").src would give you "http://www.example.com/images/example.png".

If you wanted the src attribute's content as is, without being resolved, you'd use getAttribute instead: document.getElementById("foo").getAttribute("src"). That would give you "/images/example.png" with my example above.

If you have an absolute URL, like the one in your question, it doesn't matter.

How does setTimeout work in Node.JS?

The only way to ensure code is executed is to place your setTimeout logic in a different process.

Use the child process module to spawn a new node.js program that does your logic and pass data to that process through some kind of a stream (maybe tcp).

This way even if some long blocking code is running in your main process your child process has already started itself and placed a setTimeout in a new process and a new thread and will thus run when you expect it to.

Further complication are at a hardware level where you have more threads running then processes and thus context switching will cause (very minor) delays from your expected timing. This should be neglible and if it matters you need to seriously consider what your trying to do, why you need such accuracy and what kind of real time alternative hardware is available to do the job instead.

In general using child processes and running multiple node applications as separate processes together with a load balancer or shared data storage (like redis) is important for scaling your code.

When to use React setState callback

this.setState({
    name:'value' 
},() => {
    console.log(this.state.name);
});

Align printf output in Java

You can try the below example. Do use '-' before the width to ensure left indentation. By default they will be right indented; which may not suit your purpose.

System.out.printf("%2d. %-20s $%.2f%n",  i + 1, BOOK_TYPE[i], COST[i]);

Format String Syntax: http://docs.oracle.com/javase/7/docs/api/java/util/Formatter.html#syntax

Formatting Numeric Print Output: https://docs.oracle.com/javase/tutorial/java/data/numberformat.html

PS: This could go as a comment to DwB's answer, but i still don't have permissions to comment and so answering it.

Maximum length for MySQL type text

Acording to http://dev.mysql.com/doc/refman/5.0/en/storage-requirements.html, the limit is L + 2 bytes, where L < 2^16, or 64k.

You shouldn't need to concern yourself with limiting it, it's automatically broken down into chunks that get added as the string grows, so it won't always blindly use 64k.

Any reason to prefer getClass() over instanceof when generating .equals()?

Correct me if I am wrong, but getClass() will be useful when you want to make sure your instance is NOT a subclass of the class you are comparing with. If you use instanceof in that situation you can NOT know that because:

class A { }

class B extends A { }

Object oA = new A();
Object oB = new B();

oA instanceof A => true
oA instanceof B => false
oB instanceof A => true // <================ HERE
oB instanceof B => true

oA.getClass().equals(A.class) => true
oA.getClass().equals(B.class) => false
oB.getClass().equals(A.class) => false // <===============HERE
oB.getClass().equals(B.class) => true

How to set up googleTest as a shared library on Linux

Let me answer this specifically for ubuntu users. First start by installing the gtest development package.

sudo apt-get install libgtest-dev

Note that this package only install source files. You have to compile the code yourself to create the necessary library files. These source files should be located at /usr/src/gtest. Browse to this folder and use cmake to compile the library:

sudo apt-get install cmake # install cmake
cd /usr/src/gtest
sudo mkdir build
cd build
sudo cmake ..
sudo make
sudo make install

Now to compile your programs that uses gtest, you have to link it with:

-lgtest -lgtest_main -lpthread

This worked perfectly for me on Ubuntu 14.04LTS.

Changing the interval of SetInterval while it's running

You can use a variable and change the variable instead.

````setInterval([the function], [the variable])```

How to create temp table using Create statement in SQL Server?

Same thing, Just start the table name with # or ##:

CREATE TABLE #TemporaryTable          -- Local temporary table - starts with single #
(
    Col1 int,
    Col2 varchar(10)
    ....
);

CREATE TABLE ##GlobalTemporaryTable   -- Global temporary table - note it starts with ##.
(
    Col1 int,
    Col2 varchar(10)
    ....
);

Temporary table names start with # or ## - The first is a local temporary table and the last is a global temporary table.

Here is one of many articles describing the differences between them.

How does collections.defaultdict work?

The defaultdict tool is a container in the collections class of Python. It's similar to the usual dictionary (dict) container, but it has one difference: The value fields' data type is specified upon initialization.

For example:

from collections import defaultdict

d = defaultdict(list)

d['python'].append("awesome")

d['something-else'].append("not relevant")

d['python'].append("language")

for i in d.items():

    print i

This prints:

('python', ['awesome', 'language'])
('something-else', ['not relevant'])

What are functional interfaces used for in Java 8?

Beside other answers, I think the main reason to "why using Functional Interface other than directly with lambda expressions" can be related to nature of Java language which is Object Oriented.

The main attributes of Lambda expressions are: 1. They can be passed around 2. and they can executed in future in specific time (several times). Now to support this feature in languages, some other languages deal simply with this matter.

For instance in Java Script, a function (Anonymous function, or Function literals) can be addressed as a object. So, you can create them simply and also they can be assigned to a variable and so forth. For example:

var myFunction = function (...) {
    ...;
}
alert(myFunction(...));

or via ES6, you can use an arrow function.

const myFunction = ... => ...

Up to now, Java language designers have not accepted to handle mentioned features via these manner (functional programming techniques). They believe that Java language is Object Oriented and therefore they should solve this problem via Object Oriented techniques. They don't want to miss simplicity and consistency of Java language.

Therefore, they use interfaces, as when an object of an interface with just one method (I mean functional interface) is need you can replace it with a lambda expression. Such as:

ActionListener listener = event -> ...;

CSV parsing in Java - working example..?

There is a serious problem with using

String[] strArr=line.split(",");

in order to parse CSV files, and that is because there can be commas within the data values, and in that case you must quote them, and ignore commas between quotes.

There is a very very simple way to parse this:

/**
* returns a row of values as a list
* returns null if you are past the end of the input stream
*/
public static List<String> parseLine(Reader r) throws Exception {
    int ch = r.read();
    while (ch == '\r') {
        //ignore linefeed chars wherever, particularly just before end of file
        ch = r.read();
    }
    if (ch<0) {
        return null;
    }
    Vector<String> store = new Vector<String>();
    StringBuffer curVal = new StringBuffer();
    boolean inquotes = false;
    boolean started = false;
    while (ch>=0) {
        if (inquotes) {
            started=true;
            if (ch == '\"') {
                inquotes = false;
            }
            else {
                curVal.append((char)ch);
            }
        }
        else {
            if (ch == '\"') {
                inquotes = true;
                if (started) {
                    // if this is the second quote in a value, add a quote
                    // this is for the double quote in the middle of a value
                    curVal.append('\"');
                }
            }
            else if (ch == ',') {
                store.add(curVal.toString());
                curVal = new StringBuffer();
                started = false;
            }
            else if (ch == '\r') {
                //ignore LF characters
            }
            else if (ch == '\n') {
                //end of a line, break out
                break;
            }
            else {
                curVal.append((char)ch);
            }
        }
        ch = r.read();
    }
    store.add(curVal.toString());
    return store;
}

There are many advantages to this approach. Note that each character is touched EXACTLY once. There is no reading ahead, pushing back in the buffer, etc. No searching ahead to the end of the line, and then copying the line before parsing. This parser works purely from the stream, and creates each string value once. It works on header lines, and data lines, you just deal with the returned list appropriate to that. You give it a reader, so the underlying stream has been converted to characters using any encoding you choose. The stream can come from any source: a file, a HTTP post, an HTTP get, and you parse the stream directly. This is a static method, so there is no object to create and configure, and when this returns, there is no memory being held.

You can find a full discussion of this code, and why this approach is preferred in my blog post on the subject: The Only Class You Need for CSV Files.

Find in Files: Search all code in Team Foundation Server

Another solution is to use "ctrl+shift+F". You can change the search location to a local directory rather than a solution or project. This will just take the place of the desktop search and you'll still need to get the latest code, but it will allow you to remain within Visual Studio to do your searching.

Android Studio - Auto complete and other features not working

I encounter with this problem while adding a kotlin library into my project on mac. Changing macbook language to english solved this problem. I also had some weird problems with auto-generated databinding codes, those are also solved.

How to check if a list is empty in Python?

Empty lists evaluate to False in boolean contexts (such as if some_list:).

Is there a common Java utility to break a list into batches?

Check out Lists.partition(java.util.List, int) from Google Guava:

Returns consecutive sublists of a list, each of the same size (the final list may be smaller). For example, partitioning a list containing [a, b, c, d, e] with a partition size of 3 yields [[a, b, c], [d, e]] -- an outer list containing two inner lists of three and two elements, all in the original order.

Insecure content in iframe on secure page

Based on generality of this question, I think, that you'll need to setup your own HTTPS proxy on some server online. Do the following steps:

  • Prepare your proxy server - install IIS, Apache
  • Get valid SSL certificate to avoid security errors (free from startssl.com for example)
  • Write a wrapper, which will download insecure content (how to below)
  • From your site/app get https://yourproxy.com/?page=http://insecurepage.com

If you simply download remote site content via file_get_contents or similiar, you can still have insecure links to content. You'll have to find them with regex and also replace. Images are hard to solve, but Ï found workaround here: http://foundationphp.com/tutorials/image_proxy.php


Note: While this solution may have worked in some browsers when it was written in 2014, it no longer works. Navigating or redirecting to an HTTP URL in an iframe embedded in an HTTPS page is not permitted by modern browsers, even if the frame started out with an HTTPS URL.

The best solution I created is to simply use google as the ssl proxy...

https://www.google.com/search?q=%http://yourhttpsite.com&btnI=Im+Feeling+Lucky

Tested and works in firefox.

Other Methods:

  • Use a Third party such as embed.ly (but it it really only good for well known http APIs).

  • Create your own redirect script on an https page you control (a simple javascript redirect on a relative linked page should do the trick. Something like: (you can use any langauge/method)

    https://example.com That has a iframe linking to...

    https://example.com/utilities/redirect.html Which has a simple js redirect script like...

    document.location.href ="http://thenonsslsite.com";

  • Alternatively, you could add an RSS feed or write some reader/parser to read the http site and display it within your https site.

  • You could/should also recommend to the http site owner that they create an ssl connection. If for no other reason than it increases seo.

Unless you can get the http site owner to create an ssl certificate, the most secure and permanent solution would be to create an RSS feed grabing the content you need (presumably you are not actually 'doing' anything on the http site -that is to say not logging in to any system).

The real issue is that having http elements inside a https site represents a security issue. There are no completely kosher ways around this security risk so the above are just current work arounds.

Note, that you can disable this security measure in most browsers (yourself, not for others). Also note that these 'hacks' may become obsolete over time.

How to fix error Base table or view not found: 1146 Table laravel relationship table?

Laravel tries to guess the name of the table, you have to specify it directly so that it does not give you that error..

Try this:

class NameModel extends Model {
    public $table = 'name_exact_of_the_table';

I hope that helps!

CSS3 selector :first-of-type with class name?

Not sure how to explain this but I ran into something similar today. Not being able to set .user:first-of-type{} while .user:last-of-type{} worked fine. This was fixed after I wrapped them inside a div without any class or styling:

https://codepen.io/adrianTNT/pen/WgEpbE

<style>
.user{
  display:block;
  background-color:#FFCC00;
}

.user:first-of-type{
  background-color:#FF0000;
}
</style>

<p>Not working while this P additional tag exists</p>

<p class="user">A</p>
<p class="user">B</p>
<p class="user">C</p>

<p>Working while inside a div:</p>

<div>
<p class="user">A</p>
<p class="user">B</p>
<p class="user">C</p>
</div>

Can an Android NFC phone act as an NFC tag?

For NFC tech, it is easy. For Google, it will not support it as Google wallet.

Detect whether Office is 32bit or 64bit via the registry

In my tests many of the approaches described here fail, I think because they rely on entries in the Windows registry that turn out to be not reliably present, depending on Office version, how it was installed etc. So a different approach is to not use the registry at all (Ok, so strictly that makes it not an answer to the question as posed), but instead write a script that:

  1. Instantiates Excel
  2. Adds a workbook to that Excel instance
  3. Adds a VBA module to that workbook
  4. Injects a small VBA function that returns the bitness of Office
  5. Calls that function
  6. Cleans up

Here's that approach implemented in VBScript:

Function OfficeBitness()

    Dim VBACode, Excel, Wb, Module, Result

    VBACode = "Function Is64bit() As Boolean" & vbCrLf & _
              "#If Win64 Then" & vbCrLf & _
              "    Is64bit = True" & vbCrLf & _
              "#End If" & vbCrLf & _
              "End Function"

    On Error Resume Next
    Set Excel = CreateObject("Excel.Application")
    Excel.Visible = False
    Set Wb = Excel.Workbooks.Add
    Set Module = Wb.VBProject.VBComponents.Add(1)
    Module.CodeModule.AddFromString VBACode
    Result = Excel.Run("Is64bit")
    Set Module = Nothing
    Wb.Saved = True
    Wb.Close False
    Excel.Quit
    Set Excel = Nothing
    On Error GoTo 0
    If IsEmpty(Result) Then
        OfficeBitness = 0 'Alternatively raise an error here?
    ElseIf Result = True Then
        OfficeBitness = 64
    Else
        OfficeBitness = 32
    End If

End Function

PS. This approach runs more slowly than others here (about 2 seconds on my PC) but it might turn out to be more reliable across different installations and Office versions.

After some months, I've realised there may be a simpler approach, though still one that instantiates an Excel instance. The VBScript is:

Function OfficeBitness()
    Dim Excel
    Set Excel = CreateObject("Excel.Application")
    Excel.Visible = False
    If InStr(Excel.OperatingSystem,"64") > 0 Then
        OfficeBitness = 64
    Else
        OfficeBitness = 32
    End if
    Excel.Quit
    Set Excel = Nothing
End Function

This relies on the fact that Application.OperatingSystem, when called from 32-bit Excel on 64-bit Windows returns Windows (32-bit) NT 10.00 or at least it does on my PC. But that's not mentioned in the docs.

How can I find the maximum value and its index in array in MATLAB?

For a matrix you can use this:

[M,I] = max(A(:))

I is the index of A(:) containing the largest element.

Now, use the ind2sub function to extract the row and column indices of A corresponding to the largest element.

[I_row, I_col] = ind2sub(size(A),I)

source: https://www.mathworks.com/help/matlab/ref/max.html

What is (functional) reactive programming?

FRP is a combination of Functional programming(programming paradigm built upon the idea of everything is a function) and reactive programming paradigm (built upon the idea that everything is a stream(observer and observable philosophy)). It is supposed to be the best of the worlds.

Check out Andre Staltz post on reactive programming to start with.

The type is defined in an assembly that is not referenced, how to find the cause?

The type 'Domain.tblUser' is defined in an assembly that is not referenced. You must add a reference to assembly 'Domain, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null'.

**Solved:**
 Add reference of my domain library layer to my web app libary layer

Note: Make sure your references are correct according to you DI container

Alternative for <blink>

A small javascript snippet to mimic the blink , no need of css even

<span id="lastDateBlinker">
    Last Date for Participation : 30th July 2014
</span>

<script type="text/javascript">
    function blinkLastDateSpan() {
        if ($("#lastDateBlinker").css("visibility").toUpperCase() == "HIDDEN") {
            $("#lastDateBlinker").css("visibility", "visible");
            setTimeout(blinkLastDateSpan, 200);
        } else {
            $("#lastDateBlinker").css("visibility", "hidden");
            setTimeout(blinkLastDateSpan, 200);
        }
    }
    blinkLastDateSpan();
</script>

Any way to make a WPF textblock selectable?

Use a TextBox with these settings instead to make it read only and to look like a TextBlock control.

<TextBox Background="Transparent"
         BorderThickness="0"
         Text="{Binding Text, Mode=OneWay}"
         IsReadOnly="True"
         TextWrapping="Wrap" />

Does reading an entire file leave the file handle open?

Well, if you have to read file line by line to work with each line, you can use

with open('Path/to/file', 'r') as f:
    s = f.readline()
    while s:
        # do whatever you want to
        s = f.readline()

Or even better way:

with open('Path/to/file') as f:
    for line in f:
        # do whatever you want to

MS-access reports - The search key was not found in any record - on save

In Access 2007 this error occurs when importing an Excel file where there are two fields with the same column header.

Fastest way to copy a file in Node.js

   const fs = require("fs");
   fs.copyFileSync("filepath1", "filepath2"); //fs.copyFileSync("file1.txt", "file2.txt");

This is what I personally use to copy a file and replace another file using Node.js :)

Fill SVG path element with a background-image

You can do it by making the background into a pattern:

<defs>
  <pattern id="img1" patternUnits="userSpaceOnUse" width="100" height="100">
    <image href="wall.jpg" x="0" y="0" width="100" height="100" />
  </pattern>
</defs>

Adjust the width and height according to your image, then reference it from the path like this:

<path d="M5,50
         l0,100 l100,0 l0,-100 l-100,0
         M215,100
         a50,50 0 1 1 -100,0 50,50 0 1 1 100,0
         M265,50
         l50,100 l-100,0 l50,-100
         z"
  fill="url(#img1)" />

Working example

Eclipse error: "Editor does not contain a main type"

Did you import the packages for the file reading stuff.

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.InputStreamReader;

also here

cfiltering(numberOfUsers, numberOfMovies);

Are you trying to create an object or calling a method?

also another thing:

user_movie_matrix[userNo][movieNo]=rating;

you are assigning a value to a member of an instance as if it was a static variable also remove the Th in

private int user_movie_matrix[][];Th

Hope this helps.

Open window in JavaScript with HTML inserted

I would not recomend you to use document.write as others suggest, because if you will open such window twice your HTML will be duplicated 2 times (or more).

Use innerHTML instead

var win = window.open("", "Title", "toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=yes,resizable=yes,width=780,height=200,top="+(screen.height-400)+",left="+(screen.width-840));
win.document.body.innerHTML = "HTML";

Parse JSON String into List<string>

I use this JSON Helper class in my projects. I found it on the net a year ago but lost the source URL. So I am pasting it directly from my project:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Runtime.Serialization.Json;
using System.IO;
using System.Text;
/// <summary>
/// JSON Serialization and Deserialization Assistant Class
/// </summary>
public class JsonHelper
{
    /// <summary>
    /// JSON Serialization
    /// </summary>
    public static string JsonSerializer<T> (T t)
    {
        DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T));
        MemoryStream ms = new MemoryStream();
        ser.WriteObject(ms, t);
        string jsonString = Encoding.UTF8.GetString(ms.ToArray());
        ms.Close();
        return jsonString;
    }
    /// <summary>
    /// JSON Deserialization
    /// </summary>
    public static T JsonDeserialize<T> (string jsonString)
    {
        DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T));
        MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(jsonString));
        T obj = (T)ser.ReadObject(ms);
        return obj;
    }
}

You can use it like this: Create the classes as Craig W. suggested.

And then deserialize like this

RootObject root = JSONHelper.JsonDeserialize<RootObject>(json);

Add objects to an array of objects in Powershell

To append to an array, just use the += operator.

$Target += $TargetObject

Also, you need to declare $Target = @() before your loop because otherwise, it will empty the array every loop.

How do I remove files saying "old mode 100755 new mode 100644" from unstaged changes in Git?

This happens when you pull and all files were executable in the remote repository. Making them executable again will set everything back to normal again.

chmod +x <yourfile> //For one file
chmod +x folder/* // For files in a folder

You might need to do:

chmod -x <file> // Removes execute bit

instead, for files that was not set as executable and that was changed because of the above operation. There is a better way to do this but this is just a very quick and dirty fix.

Python Pandas : group by in group by and average?

I would simply do this, which literally follows what your desired logic was:

df.groupby(['org']).mean().groupby(['cluster']).mean()

How to start and stop android service from a adb shell?

I can start service through

am startservice com.xxx/.service.XXXService

but i don't know how to stop it yet.

How do I make CMake output into a 'bin' dir?

As to me I am using cmake 3.5, the below(set variable) does not work:

set(
      ARCHIVE_OUTPUT_DIRECTORY "/home/xy/cmake_practice/lib/"
      LIBRARY_OUTPUT_DIRECTORY "/home/xy/cmake_practice/lib/"
      RUNTIME_OUTPUT_DIRECTORY "/home/xy/cmake_practice/bin/"
)

but this works(set set_target_properties):

set_target_properties(demo5
    PROPERTIES
    ARCHIVE_OUTPUT_DIRECTORY "/home/xy/cmake_practice/lib/"
    LIBRARY_OUTPUT_DIRECTORY "/home/xy/cmake_practice/lib/"
    RUNTIME_OUTPUT_DIRECTORY "/home/xy/cmake_practice/bin/"
)

How can I escape white space in a bash loop list?

I needed the same concept to compress sequentially several directories or files from a certain folder. I have solved using awk to parsel the list from ls and to avoid the problem of blank space in the name.

source="/xxx/xxx"
dest="/yyy/yyy"

n_max=`ls . | wc -l`

echo "Loop over items..."
i=1
while [ $i -le $n_max ];do
item=`ls . | awk 'NR=='$i'' `
echo "File selected for compression: $item"
tar -cvzf $dest/"$item".tar.gz "$item"
i=$(( i + 1 ))
done
echo "Done!!!"

what do you think?

How can I get an object's absolute position on the page in Javascript?

var cumulativeOffset = function(element) {
    var top = 0, left = 0;
    do {
        top += element.offsetTop  || 0;
        left += element.offsetLeft || 0;
        element = element.offsetParent;
    } while(element);

    return {
        top: top,
        left: left
    };
};

(Method shamelessly stolen from PrototypeJS; code style, variable names and return value changed to protect the innocent)

How to do SQL Like % in Linq?

If you are using VB.NET, then the answer would be "*". Here is what your where clause would look like...

Where OH.Hierarchy Like '*/12/*'

Note: "*" Matches zero or more characters. Here is the msdn article for the Like operator.

How do I prevent an Android device from going to sleep programmatically?

what @eldarerathis said is correct in all aspects, the wake lock is the right way of keeping the device from going to sleep.

I don't know waht you app needs to do but it is really important that you think on how architect your app so that you don't force the phone to stay awake for more that you need, or the battery life will suffer enormously.

I would point you to this really good example on how to use AlarmManager to fire events and wake up the phone and (your app) to perform what you need to do and then go to sleep again: Alarm Manager (source: commonsware.com)

java.lang.NoClassDefFoundError:failed resolution of :Lorg/apache/http/ProtocolVersion

According to this SO answer, it occurs due to an AWS SDK bug that appears to be solved in version 2.6.30 of the SDK, so updating the version to a newer, can help you fixing the problem.

How do I create sql query for searching partial matches?

This may work as well.

SELECT * 
FROM myTable
WHERE CHARINDEX('mall', name) > 0
  OR CHARINDEX('mall', description) > 0

Class extending more than one class Java?

Hello please note like real work.

Children can not have two mother

So in java, subclass can not have two parent class.

HTML5 Video not working in IE 11

What is the resolution of the video? I had a similar problem with IE11 in Win7. The Microsoft H.264 decoder supports only 1920x1088 pixels in Windows 7. See my story: http://lars.st0ne.at/blog/html5+video+in+IE11+-+size+does+matter

Combining multiple commits before pushing in Git

You probably want to use Interactive Rebasing, which is described in detail in that link.

You can find other good resources if you search for "git rebase interactive".

The action or event has been blocked by Disabled Mode

Another issue is that your database may be in a "non-trusted" location. Go to the trust center settings and add your database location to the trusted locations list.

How to do a logical OR operation for integer comparison in shell scripting?

This should work:

#!/bin/bash

if [ "$#" -eq 0 ] || [ "$#" -gt 1 ] ; then
    echo "hello"
fi

I'm not sure if this is different in other shells but if you wish to use <, >, you need to put them inside double parenthesis like so:

if (("$#" > 1))
 ...

Display unescaped HTML in Vue.js

Starting with Vue2, the triple braces were deprecated, you are to use v-html.

<div v-html="task.html_content"> </div>

It is unclear from the documentation link as to what we are supposed to place inside v-html, your variables goes inside v-html.

Also, v-html works only with <div> or <span> but not with <template>.

If you want to see this live in an app, click here.

How to get distinct values for non-key column fields in Laravel?

I found this method working quite well (for me) to produce a flat array of unique values:

$uniqueNames = User::select('name')->distinct()->pluck('name')->toArray();

If you ran ->toSql() on this query builder, you will see it generates a query like this:

select distinct `name` from `users`

The ->pluck() is handled by illuminate\collection lib (not via sql query).

How to establish a connection pool in JDBC?

MiniConnectionPoolManager is a one-java-file implementation, if you're looking for an embeddable solution and are not too concerned about performances (though I haven't tested it in that regard).

It is multi-licensed EPL, LGPL and MPL.

Its documentation also gives alternatives worth checking (on top of DBCP and C3P0):

Practical uses of different data structures

Few more Practical Application of data structures

Red-Black Trees (Used when there is frequent Insertion/Deletion and few searches) - K-mean Clustering using red black tree, Databases, Simple-minded database, searching words inside dictionaries, searching on web

AVL Trees (More Search and less of Insertion/Deletion) - Data Analysis and Data Mining and the applications which involves more searches

Min Heap - Clustering Algorithms

Android: upgrading DB version and adding new table

Handling database versions is very important part of application development. I assume that you already have class AppDbHelper extending SQLiteOpenHelper. When you extend it you will need to implement onCreate and onUpgrade method.

  1. When onCreate and onUpgrade methods called

    • onCreate called when app newly installed.
    • onUpgrade called when app updated.
  2. Organizing Database versions I manage versions in a class methods. Create implementation of interface Migration. E.g. For first version create MigrationV1 class, second version create MigrationV1ToV2 (these are my naming convention)


    public interface Migration {
        void run(SQLiteDatabase db);//create tables, alter tables
    }

Example migration:

public class MigrationV1ToV2 implements Migration{
      public void run(SQLiteDatabase db){
        //create new tables
        //alter existing tables(add column, add/remove constraint)
        //etc.
     }
   }
  1. Using Migration classes

onCreate: Since onCreate will be called when application freshly installed, we also need to execute all migrations(database version updates). So onCreate will looks like this:

public void onCreate(SQLiteDatabase db){
        Migration mV1=new MigrationV1();
       //put your first database schema in this class
        mV1.run(db);
        Migration mV1ToV2=new MigrationV1ToV2();
        mV1ToV2.run(db);
        //other migration if any
  }

onUpgrade: This method will be called when application is already installed and it is updated to new application version. If application contains any database changes then put all database changes in new Migration class and increment database version.

For example, lets say user has installed application which has database version 1, and now database version is updated to 2(all schema updates kept in MigrationV1ToV2). Now when application upgraded, we need to upgrade database by applying database schema changes in MigrationV1ToV2 like this:

public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    if (oldVersion < 2) {
        //means old version is 1
        Migration migration = new MigrationV1ToV2();
        migration.run(db);
    }
    if (oldVersion < 3) {
        //means old version is 2
    }
}

Note: All upgrades (mentioned in onUpgrade) in to database schema should be executed in onCreate

Simple file write function in C++

You need to declare the prototype of your writeFile function, before actually using it:

int writeFile( void );

int main( void )
{
   ...

Inconsistent accessibility: property type is less accessible

Your class Delivery has no access modifier, which means it defaults to internal. If you then try to expose a property of that type as public, it won't work. Your type (class) needs to have the same, or higher access as your property.

More about access modifiers: http://msdn.microsoft.com/en-us/library/ms173121.aspx

Reflection: How to Invoke Method with parameters

I m invoking the weighted average through reflection. And had used method with more than one parameter.

Class cls = Class.forName(propFile.getProperty(formulaTyp));// reading class name from file

Object weightedobj = cls.newInstance(); // invoke empty constructor

Class<?>[] paramTypes = { String.class, BigDecimal[].class, BigDecimal[].class }; // 3 parameter having first is method name and other two are values and their weight
Method printDogMethod = weightedobj.getClass().getMethod("applyFormula", paramTypes); // created the object 
return BigDecimal.valueOf((Double) printDogMethod.invoke(weightedobj, formulaTyp, decimalnumber, weight)); calling the method

Python Save to file

file = open('Failed.py', 'w')
file.write('whatever')
file.close()

Here is a more pythonic version, which automatically closes the file, even if there was an exception in the wrapped block:

with open('Failed.py', 'w') as file:
    file.write('whatever')

How to create XML file with specific structure in Java

You can use the JDOM library in Java. Define your tags as Element objects, document your elements with Document Class, and build your xml file with SAXBuilder. Try this example:

//Root Element
Element root=new Element("CONFIGURATION");
Document doc=new Document();
//Element 1
Element child1=new Element("BROWSER");
//Element 1 Content
child1.addContent("chrome");
//Element 2
Element child2=new Element("BASE");
//Element 2 Content
child2.addContent("http:fut");
//Element 3
Element child3=new Element("EMPLOYEE");
//Element 3 --> In this case this element has another element with Content
child3.addContent(new Element("EMP_NAME").addContent("Anhorn, Irene"));

//Add it in the root Element
root.addContent(child1);
root.addContent(child2);
root.addContent(child3);
//Define root element like root
doc.setRootElement(root);
//Create the XML
XMLOutputter outter=new XMLOutputter();
outter.setFormat(Format.getPrettyFormat());
outter.output(doc, new FileWriter(new File("myxml.xml")));

How to uncommit my last commit in Git

git reset --soft HEAD^ Will keep the modified changes in your working tree.

git reset --hard HEAD^ WILL THROW AWAY THE CHANGES YOU MADE !!!

Check whether user has a Chrome extension installed

If you're trying to detect any extension from any website, This post helped: https://ide.hey.network/post/5c3b6c7aa7af38479accc0c7

Basically, the solution would be to simply try to get a specific file (manifest.json or an image) from the extension by specifying its path. Here's what I used. Definitely working:

const imgExists = function(_f, _cb) {
    const __i = new Image();
    __i.onload = function() {
        if (typeof _cb === 'function') {
            _cb(true);
        }
    }
    __i.onerror = function() {
        if (typeof _cb === 'function') {
            _cb(false);
        }
    }
    __i.src = _f;
    __i = null;
});

try {
    imgExists("chrome-extension://${CHROME_XT_ID}/xt_content/assets/logo.png", function(_test) {
        console.log(_test ? 'chrome extension installed !' : 'chrome extension not installed..');
        ifrm.xt_chrome = _test;
        // use that information
    });
} catch (e) {
    console.log('ERROR', e)
}

How often should Oracle database statistics be run?

Whenever the data changes "significantly".

If a table goes from 1 row to 200 rows, that's a significant change. When a table goes from 100,000 rows to 150,000 rows, that's not a terribly significant change. When a table goes from 1000 rows all with identical values in commonly-queried column X to 1000 rows with nearly unique values in column X, that's a significant change.

Statistics store information about item counts and relative frequencies -- things that will let it "guess" at how many rows will match a given criteria. When it guesses wrong, the optimizer can pick a very suboptimal query plan.

XOR operation with two strings in java

Note: this only works for low characters i.e. below 0x8000, This works for all ASCII characters.

I would do an XOR each charAt() to create a new String. Like

String s, key;

StringBuilder sb = new StringBuilder();
for(int i = 0; i < s.length(); i++)
    sb.append((char)(s.charAt(i) ^ key.charAt(i % key.length())));
String result = sb.toString();

In response to @user467257's comment

If your input/output is utf-8 and you xor "a" and "æ", you are left with an invalid utf-8 string consisting of one character (decimal 135, a continuation character).

It is the char values which are being xor'ed, but the byte values and this produces a character whichc an be UTF-8 encoded.

public static void main(String... args) throws UnsupportedEncodingException {
    char ch1 = 'a';
    char ch2 = 'æ';
    char ch3 = (char) (ch1 ^ ch2);
    System.out.println((int) ch3 + " UTF-8 encoded is " + Arrays.toString(String.valueOf(ch3).getBytes("UTF-8")));
}

prints

135 UTF-8 encoded is [-62, -121]

What is the simplest way to convert array to vector?

One simple way can be the use of assign() function that is pre-defined in vector class.

e.g.

array[5]={1,2,3,4,5};

vector<int> v;
v.assign(array, array+5); // 5 is size of array.

Convert np.array of type float64 to type uint8 scaling values

Considering that you are using OpenCV, the best way to convert between data types is to use normalize function.

img_n = cv2.normalize(src=img, dst=None, alpha=0, beta=255, norm_type=cv2.NORM_MINMAX, dtype=cv2.CV_8U)

However, if you don't want to use OpenCV, you can do this in numpy

def convert(img, target_type_min, target_type_max, target_type):
    imin = img.min()
    imax = img.max()

    a = (target_type_max - target_type_min) / (imax - imin)
    b = target_type_max - a * imax
    new_img = (a * img + b).astype(target_type)
    return new_img

And then use it like this

imgu8 = convert(img16u, 0, 255, np.uint8)

This is based on the answer that I found on crossvalidated board in comments under this solution https://stats.stackexchange.com/a/70808/277040

referenced before assignment error in python

My Scenario

def example():
    cl = [0, 1]
    def inner():
        #cl = [1, 2] # access this way will throw `reference before assignment`
        cl[0] = 1 
        cl[1] = 2   # these won't

    inner()

Run a PHP file in a cron job using CPanel

It is actually very simple,

php -q /home/username/public_html/cron/cron.php

How to have Android Service communicate with Activity

The asker has probably long since moved past this, but in case someone else searches for this...

There's another way to handle this, which I think might be the simplest.

Add a BroadcastReceiver to your activity. Register it to receive some custom intent in onResume and unregister it in onPause. Then send out that intent from your service when you want to send out your status updates or what have you.

Make sure you wouldn't be unhappy if some other app listened for your Intent (could anyone do anything malicious?), but beyond that, you should be alright.

Code sample was requested:

In my service, I have this:

// Do stuff that alters the content of my local SQLite Database
sendBroadcast(new Intent(RefreshTask.REFRESH_DATA_INTENT));

(RefreshTask.REFRESH_DATA_INTENT is just a constant string.)

In my listening activity, I define my BroadcastReceiver:

private class DataUpdateReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        if (intent.getAction().equals(RefreshTask.REFRESH_DATA_INTENT)) {
          // Do stuff - maybe update my view based on the changed DB contents
        }
    }
}

I declare my receiver at the top of the class:

private DataUpdateReceiver dataUpdateReceiver;

I override onResume to add this:

if (dataUpdateReceiver == null) dataUpdateReceiver = new DataUpdateReceiver();
IntentFilter intentFilter = new IntentFilter(RefreshTask.REFRESH_DATA_INTENT);
registerReceiver(dataUpdateReceiver, intentFilter);

And I override onPause to add:

if (dataUpdateReceiver != null) unregisterReceiver(dataUpdateReceiver);

Now my activity is listening for my service to say "Hey, go update yourself." I could pass data in the Intent instead of updating database tables and then going back to find the changes within my activity, but since I want the changes to persist anyway, it makes sense to pass the data via DB.

LaTeX: remove blank page after a \part or \chapter

I think you can simply add the oneside option the book class?

i.e.

\documentclass[oneside]{book}

Although I didn't test it :)

Getting the class of the element that fired an event using JQuery

Try:

$(document).ready(function() {
    $("a").click(function(event) {
       alert(event.target.id+" and "+$(event.target).attr('class'));
    });
});

How to normalize a histogram in MATLAB?

hist can not only plot an histogram but also return you the count of elements in each bin, so you can get that count, normalize it by dividing each bin by the total and plotting the result using bar. Example:

Y = rand(10,1);
C = hist(Y);
C = C ./ sum(C);
bar(C)

or if you want a one-liner:

bar(hist(Y) ./ sum(hist(Y)))

Documentation:

Edit: This solution answers the question How to have the sum of all bins equal to 1. This approximation is valid only if your bin size is small relative to the variance of your data. The sum used here correspond to a simple quadrature formula, more complex ones can be used like trapz as proposed by R. M.

Microsoft Excel mangles Diacritics in .csv files?

I can only get CSV to parse properly in Excel 2007 as tab-separated little-endian UTF-16 starting with the proper byte order mark.

How can I use a Python script in the command line without cd-ing to its directory? Is it the PYTHONPATH?

You're confusing PATH and PYTHONPATH. You need to do this:

export PATH=$PATH:/home/randy/lib/python 

PYTHONPATH is used by the python interpreter to determine which modules to load.

PATH is used by the shell to determine which executables to run.

What exactly is a Maven Snapshot and why do we need it?

Snapshot Dependencies Snapshot dependencies are dependencies (JAR files) which are under development. Instead of constantly updating the version numbers to get the latest version, you can depend on a snapshot version of the project. Snapshot versions are always downloaded into your local repository for every build, even if a matching snapshot version is already located in your local repository. Always downloading the snapshot dependencies assures that you always have the latest version in your local repository, for every build.

your pom contains a lot of -SNAPSHOT dependencies and those -SNAPSHOT dependencies are a moving target enter image description here

enter image description here

https://dzone.com/articles/maven-release-plugin-in-the-enterprise https://javarevisited.blogspot.com/2019/03/top-5-course-to-learn-apache-maven-for.html https://www.mojohaus.org/versions-maven-plugin/examples/lock-snapshots.html http://tutorials.jenkov.com/maven/maven-tutorial.html

What is the default database path for MongoDB?

For a Windows machine start the mongod process by specifying the dbpath:

mongod --dbpath \mongodb\data

Reference: Manage mongod Processes

Pylint, PyChecker or PyFlakes?

Well, I am a bit curious, so I just tested the three myself right after asking the question ;-)

Ok, this is not a very serious review, but here is what I can say:

I tried the tools with the default settings (it's important because you can pretty much choose your check rules) on the following script:

#!/usr/local/bin/python
# by Daniel Rosengren modified by e-satis

import sys, time
stdout = sys.stdout

BAILOUT = 16
MAX_ITERATIONS = 1000

class Iterator(object) :

    def __init__(self):

        print 'Rendering...'
        for y in xrange(-39, 39):
            stdout.write('\n')
            for x in xrange(-39, 39):
                if self.mandelbrot(x/40.0, y/40.0) :
                    stdout.write(' ')
                else:
                    stdout.write('*')


    def mandelbrot(self, x, y):
        cr = y - 0.5
        ci = x
        zi = 0.0
        zr = 0.0

        for i in xrange(MAX_ITERATIONS) :
            temp = zr * zi
            zr2 = zr * zr
            zi2 = zi * zi
            zr = zr2 - zi2 + cr
            zi = temp + temp + ci

            if zi2 + zr2 > BAILOUT:
                return i

        return 0

t = time.time()
Iterator()
print '\nPython Elapsed %.02f' % (time.time() - t)

As a result:

  • PyChecker is troublesome because it compiles the module to analyze it. If you don't want your code to run (e.g, it performs a SQL query), that's bad.
  • PyFlakes is supposed to be light. Indeed, it decided that the code was perfect. I am looking for something quite severe so I don't think I'll go for it.
  • PyLint has been very talkative and rated the code 3/10 (OMG, I'm a dirty coder !).

Strong points of PyLint:

  • Very descriptive and accurate report.
  • Detect some code smells. Here it told me to drop my class to write something with functions because the OO approach was useless in this specific case. Something I knew, but never expected a computer to tell me :-p
  • The fully corrected code run faster (no class, no reference binding...).
  • Made by a French team. OK, it's not a plus for everybody, but I like it ;-)

Cons of Pylint:

  • Some rules are really strict. I know that you can change it and that the default is to match PEP8, but is it such a crime to write 'for x in seq'? Apparently yes because you can't write a variable name with less than 3 letters. I will change that.
  • Very very talkative. Be ready to use your eyes.

Corrected script (with lazy doc strings and variable names):

#!/usr/local/bin/python
# by Daniel Rosengren, modified by e-satis
"""
Module doctring
"""


import time
from sys import stdout

BAILOUT = 16
MAX_ITERATIONS = 1000

def mandelbrot(dim_1, dim_2):
    """
    function doc string
    """
    cr1 = dim_1 - 0.5
    ci1 = dim_2
    zi1 = 0.0
    zr1 = 0.0

    for i in xrange(MAX_ITERATIONS) :
        temp = zr1 * zi1
        zr2 = zr1 * zr1
        zi2 = zi1 * zi1
        zr1 = zr2 - zi2 + cr1
        zi1 = temp + temp + ci1

        if zi2 + zr2 > BAILOUT:
            return i

    return 0

def execute() :
    """
    func doc string
    """
    print 'Rendering...'
    for dim_1 in xrange(-39, 39):
        stdout.write('\n')
        for dim_2 in xrange(-39, 39):
            if mandelbrot(dim_1/40.0, dim_2/40.0) :
                stdout.write(' ')
            else:
                stdout.write('*')


START_TIME = time.time()
execute()
print '\nPython Elapsed %.02f' % (time.time() - START_TIME)

Thanks to Rudiger Wolf, I discovered pep8 that does exactly what its name suggests: matching PEP8. It has found several syntax no-nos that Pylint did not. But Pylint found stuff that was not specifically linked to PEP8 but interesting. Both tools are interesting and complementary.

Eventually I will use both since there are really easy to install (via packages or setuptools) and the output text is so easy to chain.

To give you a little idea of their output:

pep8:

./python_mandelbrot.py:4:11: E401 multiple imports on one line
./python_mandelbrot.py:10:1: E302 expected 2 blank lines, found 1
./python_mandelbrot.py:10:23: E203 whitespace before ':'
./python_mandelbrot.py:15:80: E501 line too long (108 characters)
./python_mandelbrot.py:23:1: W291 trailing whitespace
./python_mandelbrot.py:41:5: E301 expected 1 blank line, found 3

Pylint:

************* Module python_mandelbrot
C: 15: Line too long (108/80)
C: 61: Line too long (85/80)
C:  1: Missing docstring
C:  5: Invalid name "stdout" (should match (([A-Z_][A-Z0-9_]*)|(__.*__))$)
C: 10:Iterator: Missing docstring
C: 15:Iterator.__init__: Invalid name "y" (should match [a-z_][a-z0-9_]{2,30}$)
C: 17:Iterator.__init__: Invalid name "x" (should match [a-z_][a-z0-9_]{2,30}$)

[...] and a very long report with useful stats like :

Duplication
-----------

+-------------------------+------+---------+-----------+
|                         |now   |previous |difference |
+=========================+======+=========+===========+
|nb duplicated lines      |0     |0        |=          |
+-------------------------+------+---------+-----------+
|percent duplicated lines |0.000 |0.000    |=          |
+-------------------------+------+---------+-----------+

ValueError: could not convert string to float: id

This error is pretty verbose:

ValueError: could not convert string to float: id

Somewhere in your text file, a line has the word id in it, which can't really be converted to a number.

Your test code works because the word id isn't present in line 2.


If you want to catch that line, try this code. I cleaned your code up a tad:

#!/usr/bin/python

import os, sys
from scipy import stats
import numpy as np

for index, line in enumerate(open('data2.txt', 'r').readlines()):
    w = line.split(' ')
    l1 = w[1:8]
    l2 = w[8:15]

    try:
        list1 = map(float, l1)
        list2 = map(float, l2)
    except ValueError:
        print 'Line {i} is corrupt!'.format(i = index)'
        break

    result = stats.ttest_ind(list1, list2)
    print result[1]

Query to get only numbers from a string

Just a little modification to @Epsicron 's answer

SELECT SUBSTRING(string, PATINDEX('%[0-9]%', string), PATINDEX('%[0-9][^0-9]%', string + 't') - PATINDEX('%[0-9]%', 
                    string) + 1) AS Number
FROM (values ('003Preliminary Examination Plan'),
    ('Coordination005'),
    ('Balance1000sheet')) as a(string)

no need for a temporary variable

Python Pandas Counting the Occurrences of a Specific value

An elegant way to count the occurrence of '?' or any symbol in any column, is to use built-in function isin of a dataframe object.

Suppose that we have loaded the 'Automobile' dataset into df object. We do not know which columns contain missing value ('?' symbol), so let do:

df.isin(['?']).sum(axis=0)

DataFrame.isin(values) official document says:

it returns boolean DataFrame showing whether each element in the DataFrame is contained in values

Note that isin accepts an iterable as input, thus we need to pass a list containing the target symbol to this function. df.isin(['?']) will return a boolean dataframe as follows.

    symboling   normalized-losses   make    fuel-type   aspiration-ratio ...
0   False       True                False   False       False
1   False       True                False   False       False
2   False       True                False   False       False
3   False       False               False   False       False
4   False       False               False   False       False
5   False       True                False   False       False
...

To count the number of occurrence of the target symbol in each column, let's take sum over all the rows of the above dataframe by indicating axis=0. The final (truncated) result shows what we expect:

symboling             0
normalized-losses    41
...
bore                  4
stroke                4
compression-ratio     0
horsepower            2
peak-rpm              2
city-mpg              0
highway-mpg           0
price                 4

How to read data from java properties file using Spring Boot

We can read properties file in spring boot using 3 way

1. Read value from application.properties Using @Value

map key as

public class EmailService {

 @Value("${email.username}")
 private String username;

}

2. Read value from application.properties Using @ConfigurationProperties

In this we will map prefix of key using ConfigurationProperties and key name is same as field of class

  @Component
   @ConfigurationProperties("email")
    public class EmailConfig {

        private String   username;
    }

3. Read application.properties Using using Environment object

public class EmailController {

@Autowired
private Environment env;

@GetMapping("/sendmail")
public void sendMail(){     
    System.out.println("reading value from application properties file  using Environment ");
    System.out.println("username ="+ env.getProperty("email.username"));
    System.out.println("pwd ="+ env.getProperty("email.pwd"));
}

Reference : how to read value from application.properties in spring boot

Serializing an object to JSON

Download https://github.com/douglascrockford/JSON-js/blob/master/json2.js, include it and do

var json_data = JSON.stringify(obj);

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".

Binding Button click to a method

Click is an event. In your code behind, you need to have a corresponding event handler to whatever you have in the XAML. In this case, you would need to have the following:

private void Command(object sender, RoutedEventArgs e)
{

}

Commands are different. If you need to wire up a command, you'd use the Commmand property of the button and you would either use some pre-built Commands or wire up your own via the CommandManager class (I think).

Sort an array of objects in React and render them

You will need to sort your object before mapping over them. And it can be done easily with a sort() function with a custom comparator definition like

var obj = [...this.state.data];
obj.sort((a,b) => a.timeM - b.timeM);
obj.map((item, i) => (<div key={i}> {item.matchID}  
                      {item.timeM} {item.description}</div>))

How to print (using cout) a number in binary form?

Using the std::bitset answers and convenience templates:

#include <iostream>
#include <bitset>
#include <climits>

template<typename T>
struct BinaryForm {
    BinaryForm(const T& v) : _bs(v) {}
    const std::bitset<sizeof(T)*CHAR_BIT> _bs;
};

template<typename T>
inline std::ostream& operator<<(std::ostream& os, const BinaryForm<T> bf) {
    return os << bf._bs;
}

Using it like this:

auto c = 'A';
std::cout << "c: " << c << " binary: " << BinaryForm{c} << std::endl;
unsigned x = 1234;
std::cout << "x: " << x << " binary: " << BinaryForm{x} << std::endl;
int64_t z { -1024 };
std::cout << "z: " <<  << " binary: " << BinaryForm{z} << std::endl;

Generates output:

c: A binary: 01000001
x: 1234 binary: 00000000000000000000010011010010
z: -1024 binary: 1111111111111111111111111111111111111111111111111111110000000000

Javascript negative number

function negative(n) {
  return n < 0;
}

Your regex should work fine for string numbers, but this is probably faster. (edited from comment in similar answer above, conversion with +n is not needed.)

How do I escape a single quote in SQL Server?

Also another thing to be careful of is whether or not it is really stored as a classic ASCII ' (ASCII 27) or Unicode 2019 (which looks similar, but not the same).

This isn't a big deal on inserts, but it can mean the world on selects and updates.
If it's the unicode value then escaping the ' in a WHERE clause (e.g where blah = 'Workers''s Comp') will return like the value you are searching for isn't there if the ' in "Worker's Comp" is actually the unicode value.

If your client application supports free-key, as well as copy and paste based input, it could be Unicode in some rows, and ASCII in others!

A simple way to confirm this is by doing some kind of open ended query that will bring back the value you are searching for, and then copy and paste that into notepad++ or some other unicode supporting editor.

The differing appearance between the ascii value and the unicode one should be obvious to the eyes, but if you lean towards the anal, it will show up as 27 (ascii) or 92 (unicode) in a hex editor.

How to sort an array of ints using a custom comparator?

How about using streams (Java 8)?

int[] ia = {99, 11, 7, 21, 4, 2};
ia = Arrays.stream(ia).
    boxed().
    sorted((a, b) -> b.compareTo(a)). // sort descending
    mapToInt(i -> i).
    toArray();

Or in-place:

int[] ia = {99, 11, 7, 21, 4, 2};
System.arraycopy(
        Arrays.stream(ia).
            boxed().
            sorted((a, b) -> b.compareTo(a)). // sort descending
            mapToInt(i -> i).
            toArray(),
        0,
        ia,
        0,
        ia.length
    );

bootstrap popover not showing on top of all elements

  $('[data-toggle="popover"]').popover({
        placement: 'top',
        boundary: 'viewport',
        trigger: 'hover',
        html: true,
        content: function () {
            let content = $(this).attr("data-popover-content");
            return $(content).html();
        }
    });,



`placement`: 'top',
`boundary`: 'viewport'
both needed

How to specify the JDK version in android studio?

For new Android Studio versions, go to C:\Program Files\Android\Android Studio\jre\bin(or to location of Android Studio installed files) and open command window at this location and type in following command in command prompt:-

java -version

Using $_POST to get select option value from HTML

You can access values in the $_POST array by their key. $_POST is an associative array, so to access taskOption you would use $_POST['taskOption'];.

Make sure to check if it exists in the $_POST array before proceeding though.

<form method="post" action="process.php">
  <select name="taskOption">
    <option value="first">First</option>
    <option value="second">Second</option>
    <option value="third">Third</option>
  </select>
  <input type="submit" value="Submit the form"/>
</form>

process.php

<?php
   $option = isset($_POST['taskOption']) ? $_POST['taskOption'] : false;
   if ($option) {
      echo htmlentities($_POST['taskOption'], ENT_QUOTES, "UTF-8");
   } else {
     echo "task option is required";
     exit; 
   }

Correct way to add external jars (lib/*.jar) to an IntelliJ IDEA project

You add them as libraries to your module.

I usually have a /lib directory in my source. I put all the JARs I need there, add /lib as a library, and make it part of my module dependencies.

2018 update: I'm using IntelliJ 2017/2018 now.

I'm fully committed to Maven and Nexus for dependency management.

This is the way the world has gone. Every open source Java project that I know of uses Maven or Gradle. You should, too.

E11000 duplicate key error index in mongodb mongoose

Check indexes of that collection in MongoDB compass and remove those indexes which are not related to it or for try remove all indexes(Not from code but in db).

How to extract duration time from ffmpeg output?

From my experience many tools offer the desired data in some kind of a table/ordered structure and also offer parameters to gather specific parts of that data. This applies to e.g. smartctl, nvidia-smi and ffmpeg/ffprobe, too. Simply speaking - often there's no need to pipe data around or to open subshells for such a task.

As a consequence I'd use the right tool for the job - in that case ffprobe would return the raw duration value in seconds, afterwards one could create the desired time format on his own:

$ ffmpeg --version
ffmpeg version 2.2.3 ...

The command may vary dependent on the version you are using.

#!/usr/bin/env bash
input_file="/path/to/media/file"

# Get raw duration value
ffprobe -v quiet -print_format compact=print_section=0:nokey=1:escape=csv -show_entries format=duration "$input_file"

An explanation:

"-v quiet": Don't output anything else but the desired raw data value

"-print_format": Use a certain format to print out the data

"compact=": Use a compact output format

"print_section=0": Do not print the section name

":nokey=1": do not print the key of the key:value pair

":escape=csv": escape the value

"-show_entries format=duration": Get entries of a field named duration inside a section named format

Reference: ffprobe man pages