Programs & Examples On #Lostfocus

A phenomena of losing access from a control.

How can I know when an EditText loses focus?

Implement onFocusChange of setOnFocusChangeListener and there's a boolean parameter for hasFocus. When this is false, you've lost focus to another control.

 EditText txtEdit = (EditText) findViewById(R.id.edittxt);

 txtEdit.setOnFocusChangeListener(new OnFocusChangeListener() {          
        @Override
        public void onFocusChange(View v, boolean hasFocus) {
            if (!hasFocus) {
               // code to execute when EditText loses focus
            }
        }
    });

Insert line break in wrapped cell via code

Yes there are two way to add a line feed:

  1. Use the existing function from VBA vbCrLf in the string you want to add a line feed, as such:

    Dim text As String

    text = "Hello" & vbCrLf & "World!"

    Worksheets(1).Cells(1, 1) = text

  2. Use the Chr() function and pass the ASCII characters 13 and 10 in order to add a line feed, as shown bellow:

    Dim text As String

    text = "Hello" & Chr(13) & Chr(10) & "World!"

    Worksheets(1).Cells(1, 1) = text

In both cases, you will have the same output in cell (1,1) or A1.

MS SQL 2008 - get all table names and their row counts in a DB

to get all tables in a database:

select * from INFORMATION_SCHEMA.TABLES

to get all columns in a database:

select * from INFORMATION_SCHEMA.columns

to get all views in a db:

select * from INFORMATION_SCHEMA.TABLES where table_type = 'view'

Where to change default pdf page width and font size in jspdf.debug.js?

Besides using one of the default formats you can specify any size you want in the unit you specify.

For example:

// Document of 210mm wide and 297mm high
new jsPDF('p', 'mm', [297, 210]);
// Document of 297mm wide and 210mm high
new jsPDF('l', 'mm', [297, 210]);
// Document of 5 inch width and 3 inch high
new jsPDF('l', 'in', [3, 5]);

The 3rd parameter of the constructor can take an array of the dimensions. However they do not correspond to width and height, instead they are long side and short side (or flipped around).

Your 1st parameter (landscape or portrait) determines what becomes the width and the height.

In the sourcecode on GitHub you can see the supported units (relative proportions to pt), and you can also see the default page formats (with their sizes in pt).

canvas.toDataURL() SecurityError

Unless google serves this image with the correct Access-Control-Allow-Origin header, then you wont be able to use their image in canvas. This is due to not having CORS approval. You can read more about this here, but it essentially means:

Although you can use images without CORS approval in your canvas, doing so taints the canvas. Once a canvas has been tainted, you can no longer pull data back out of the canvas. For example, you can no longer use the canvas toBlob(), toDataURL(), or getImageData() methods; doing so will throw a security error.

This protects users from having private data exposed by using images to pull information from remote web sites without permission.

I suggest just passing the URL to your server-side language and using curl to download the image. Be careful to sanitise this though!

EDIT:

As this answer is still the accepted answer, you should check out @shadyshrif's answer, which is to use:

var img = new Image();
img.setAttribute('crossOrigin', 'anonymous');
img.src = url;

This will only work if you have the correct permissions, but will at least allow you to do what you want.

Numpy converting array from float to strings

This is probably slower than what you want, but you can do:

>>> tostring = vectorize(lambda x: str(x))
>>> numpy.where(tostring(phis).astype('float64') != phis)
(array([], dtype=int64),)

It looks like it rounds off the values when it converts to str from float64, but this way you can customize the conversion however you like.

Converting user input string to regular expression

var flags = inputstring.replace(/.*\/([gimy]*)$/, '$1');
var pattern = inputstring.replace(new RegExp('^/(.*?)/'+flags+'$'), '$1');
var regex = new RegExp(pattern, flags);

or

var match = inputstring.match(new RegExp('^/(.*?)/([gimy]*)$'));
// sanity check here
var regex = new RegExp(match[1], match[2]);

Mean Squared Error in Numpy?

Even more numpy

np.square(np.subtract(A, B)).mean()

Where does forever store console.log output?

Forever, by default, will put logs into a random file in ~/.forever/ folder.

You should run forever list to see the running processes and their corresponding log file.

Sample output

>>> forever list
info:    Forever processes running
data:        uid  command       script forever pid  logfile                         uptime
data:    [0] 6n71 /usr/bin/node app.js 2233    2239 /home/vagrant/.forever/6n71.log 0:0:0:1.590

However, it's probably best to specify with -l as mentioned by bryanmac.

How do I loop through or enumerate a JavaScript object?

Multiple way to iterate object in javascript

Using for...in loop

_x000D_
_x000D_
 var p = {_x000D_
    "p1": "value1",_x000D_
    "p2": "value2",_x000D_
    "p3": "value3"_x000D_
};_x000D_
for (let key in p){_x000D_
   if(p.hasOwnProperty(key)){_x000D_
     console.log(`${key} : ${p[key]}`)_x000D_
   }_x000D_
}
_x000D_
_x000D_
_x000D_

Using for...of loop

_x000D_
_x000D_
 var p = {_x000D_
    "p1": "value1",_x000D_
    "p2": "value2",_x000D_
    "p3": "value3"_x000D_
};_x000D_
for (let key of Object.keys(p)){_x000D_
     console.log(`key: ${key} & value: ${p[key]}`)_x000D_
}
_x000D_
_x000D_
_x000D_

Using forEach() with Object.keys, Object.values, Object.entries

_x000D_
_x000D_
var p = {_x000D_
    "p1": "value1",_x000D_
    "p2": "value2",_x000D_
    "p3": "value3"_x000D_
};_x000D_
Object.keys(p).forEach(key=>{_x000D_
   console.log(`${key} : ${p[key]}`);_x000D_
});_x000D_
Object.values(p).forEach(value=>{_x000D_
   console.log(value);_x000D_
});_x000D_
Object.entries(p).forEach(([key,value])=>{_x000D_
    console.log(`${key}:${value}`)_x000D_
})
_x000D_
_x000D_
_x000D_

How to update and order by using ms sql

I have to offer this as a better approach - you don't always have the luxury of an identity field:

UPDATE m
SET [status]=10
FROM (
  Select TOP (10) *
  FROM messages
  WHERE [status]=0
  ORDER BY [priority] DESC
) m

You can also make the sub-query as complicated as you want - joining multiple tables, etc...

Why is this better? It does not rely on the presence of an identity field (or any other unique column) in the messages table. It can be used to update the top N rows from any table, even if that table has no unique key at all.

What's the difference between deadlock and livelock?

Maybe these two examples illustrate you the difference between a deadlock and a livelock:


Java-Example for a deadlock:

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class DeadlockSample {

    private static final Lock lock1 = new ReentrantLock(true);
    private static final Lock lock2 = new ReentrantLock(true);

    public static void main(String[] args) {
        Thread threadA = new Thread(DeadlockSample::doA,"Thread A");
        Thread threadB = new Thread(DeadlockSample::doB,"Thread B");
        threadA.start();
        threadB.start();
    }

    public static void doA() {
        System.out.println(Thread.currentThread().getName() + " : waits for lock 1");
        lock1.lock();
        System.out.println(Thread.currentThread().getName() + " : holds lock 1");

        try {
            System.out.println(Thread.currentThread().getName() + " : waits for lock 2");
            lock2.lock();
            System.out.println(Thread.currentThread().getName() + " : holds lock 2");

            try {
                System.out.println(Thread.currentThread().getName() + " : critical section of doA()");
            } finally {
                lock2.unlock();
                System.out.println(Thread.currentThread().getName() + " : does not hold lock 2 any longer");
            }
        } finally {
            lock1.unlock();
            System.out.println(Thread.currentThread().getName() + " : does not hold lock 1 any longer");
        }
    }

    public static void doB() {
        System.out.println(Thread.currentThread().getName() + " : waits for lock 2");
        lock2.lock();
        System.out.println(Thread.currentThread().getName() + " : holds lock 2");

        try {
            System.out.println(Thread.currentThread().getName() + " : waits for lock 1");
            lock1.lock();
            System.out.println(Thread.currentThread().getName() + " : holds lock 1");

            try {
                System.out.println(Thread.currentThread().getName() + " : critical section of doB()");
            } finally {
                lock1.unlock();
                System.out.println(Thread.currentThread().getName() + " : does not hold lock 1 any longer");
            }
        } finally {
            lock2.unlock();
            System.out.println(Thread.currentThread().getName() + " : does not hold lock 2 any longer");
        }
    }
}

Sample output:

Thread A : waits for lock 1
Thread B : waits for lock 2
Thread A : holds lock 1
Thread B : holds lock 2
Thread B : waits for lock 1
Thread A : waits for lock 2

Java-Example for a livelock:


import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class LivelockSample {

    private static final Lock lock1 = new ReentrantLock(true);
    private static final Lock lock2 = new ReentrantLock(true);

    public static void main(String[] args) {
        Thread threadA = new Thread(LivelockSample::doA, "Thread A");
        Thread threadB = new Thread(LivelockSample::doB, "Thread B");
        threadA.start();
        threadB.start();
    }

    public static void doA() {
        try {
            while (!lock1.tryLock()) {
                System.out.println(Thread.currentThread().getName() + " : waits for lock 1");
                Thread.sleep(100);
            }
            System.out.println(Thread.currentThread().getName() + " : holds lock 1");

            try {
                while (!lock2.tryLock()) {
                    System.out.println(Thread.currentThread().getName() + " : waits for lock 2");
                    Thread.sleep(100);
                }
                System.out.println(Thread.currentThread().getName() + " : holds lock 2");

                try {
                    System.out.println(Thread.currentThread().getName() + " : critical section of doA()");
                } finally {
                    lock2.unlock();
                    System.out.println(Thread.currentThread().getName() + " : does not hold lock 2 any longer");
                }
            } finally {
                lock1.unlock();
                System.out.println(Thread.currentThread().getName() + " : does not hold lock 1 any longer");
            }
        } catch (InterruptedException e) {
            // can be ignored here for this sample
        }
    }

    public static void doB() {
        try {
            while (!lock2.tryLock()) {
                System.out.println(Thread.currentThread().getName() + " : waits for lock 2");
                Thread.sleep(100);
            }
            System.out.println(Thread.currentThread().getName() + " : holds lock 2");

            try {
                while (!lock1.tryLock()) {
                    System.out.println(Thread.currentThread().getName() + " : waits for lock 1");
                    Thread.sleep(100);
                }
                System.out.println(Thread.currentThread().getName() + " : holds lock 1");

                try {
                    System.out.println(Thread.currentThread().getName() + " : critical section of doB()");
                } finally {
                    lock1.unlock();
                    System.out.println(Thread.currentThread().getName() + " : does not hold lock 1 any longer");
                }
            } finally {
                lock2.unlock();
                System.out.println(Thread.currentThread().getName() + " : does not hold lock 2 any longer");
            }
        } catch (InterruptedException e) {
            // can be ignored here for this sample
        }
    }
}

Sample output:

Thread B : holds lock 2
Thread A : holds lock 1
Thread A : waits for lock 2
Thread B : waits for lock 1
Thread B : waits for lock 1
Thread A : waits for lock 2
Thread A : waits for lock 2
Thread B : waits for lock 1
Thread B : waits for lock 1
Thread A : waits for lock 2
Thread A : waits for lock 2
Thread B : waits for lock 1
...

Both examples force the threads to aquire the locks in different orders. While the deadlock waits for the other lock, the livelock does not really wait - it desperately tries to acquire the lock without the chance of getting it. Every try consumes CPU cycles.

How to change Java version used by TOMCAT?

You can change the JDK or JRE location using the following steps:

  1. open the terminal or cmd.
  2. go to the [tomcat-home]\bin directory.
    ex: c:\tomcat8\bin
  3. write the following command: Tomcat8W //ES//Tomcat8
  4. will open dialog, select the java tab(top pane).
  5. change the Java virtual Machine value.
  6. click OK.

note: in Apache TomEE same steps, but step (3) the command must be: TomEE //ES

Set textbox to readonly and background color to grey in jquery

there are 2 solutions:

visit this jsfiddle

in your css you can add this:
     .input-disabled{background-color:#EBEBE4;border:1px solid #ABADB3;padding:2px 1px;}

in your js do something like this:
     $('#test').attr('readonly', true);
     $('#test').addClass('input-disabled');

Hope this help.

Another way is using hidden input field as mentioned by some of the comments. However bear in mind that, in the backend code, you need to make sure you validate this newly hidden input at correct scenario. Hence I'm not recommend this way as it will create more bugs if its not handle properly.

Installation of SQL Server Business Intelligence Development Studio

If you have installed SQL 2005 express edition and want to install BIDS (Business Intelligence Development Studio) then go to here Microsoft SQL Server 2005 Express Edition Toolkit

This has an option to install BIDS on my machine, and is the only way l could get hold of BIDS for SQL Server 2005 express edition.

Also this package l think has also allowed me to install both BIDS 2005 & 2008 express edition on the same machine.

How does java do modulus calculations with negative numbers?

In Java latest versions you get -13%64 = -13. The answer will always have sign of numerator.

Circle-Rectangle collision detection (intersection)

To visualise, take your keyboard's numpad. If the key '5' represents your rectangle, then all the keys 1-9 represent the 9 quadrants of space divided by the lines that make up your rectangle (with 5 being the inside.)

1) If the circle's center is in quadrant 5 (i.e. inside the rectangle) then the two shapes intersect.

With that out of the way, there are two possible cases: a) The circle intersects with two or more neighboring edges of the rectangle. b) The circle intersects with one edge of the rectangle.

The first case is simple. If the circle intersects with two neighboring edges of the rectangle, it must contain the corner connecting those two edges. (That, or its center lies in quadrant 5, which we have already covered. Also note that the case where the circle intersects with only two opposing edges of the rectangle is covered as well.)

2) If any of the corners A, B, C, D of the rectangle lie inside the circle, then the two shapes intersect.

The second case is trickier. We should make note of that it may only happen when the circle's center lies in one of the quadrants 2, 4, 6 or 8. (In fact, if the center is on any of the quadrants 1, 3, 7, 8, the corresponding corner will be the closest point to it.)

Now we have the case that the circle's center is in one of the 'edge' quadrants, and it only intersects with the corresponding edge. Then, the point on the edge that is closest to the circle's center, must lie inside the circle.

3) For each line AB, BC, CD, DA, construct perpendicular lines p(AB,P), p(BC,P), p(CD,P), p(DA,P) through the circle's center P. For each perpendicular line, if the intersection with the original edge lies inside the circle, then the two shapes intersect.

There is a shortcut for this last step. If the circle's center is in quadrant 8 and the edge AB is the top edge, the point of intersection will have the y-coordinate of A and B, and the x-coordinate of center P.

You can construct the four line intersections and check if they lie on their corresponding edges, or find out which quadrant P is in and check the corresponding intersection. Both should simplify to the same boolean equation. Be wary of that the step 2 above did not rule out P being in one of the 'corner' quadrants; it just looked for an intersection.

Edit: As it turns out, I have overlooked the simple fact that #2 is a subcase of #3 above. After all, corners too are points on the edges. See @ShreevatsaR's answer below for a great explanation. And in the meanwhile, forget #2 above unless you want a quick but redundant check.

convert month from name to number

I know this might seem a simple solution, but why not just use something like this

<select name="month">
  <option value="01">January</option>
  <option value="02">February</option>
  <option selected value="03">March</option>
</select>

The user sees February, but 02 is posted to the database

JS search in object values

I have created this easy to use library that does exactly what you are looking for: ss-search

import { search } from "ss-search"

const data = [
  {
       "foo" : "bar",
       "bar" : "sit"
  },
  {
       "foo" : "lorem",
       "bar" : "ipsum"
  },
  {
       "foo" : "dolor",
       "bar" : "amet"
  }
]
const searchKeys = ["foor", "bar"] 
const searchText = "dolor"

const results = search(data, keys, searchText)
// results: [{ "foo": "dolor", "bar": "amet" }]

Java check to see if a variable has been initialized

Assuming you're interested in whether the variable has been explicitly assigned a value or not, the answer is "not really". There's absolutely no difference between a field (instance variable or class variable) which hasn't been explicitly assigned at all yet, and one which has been assigned its default value - 0, false, null etc.

Now if you know that once assigned, the value will never reassigned a value of null, you can use:

if (box != null) {
    box.removeFromCanvas();
}

(and that also avoids a possible NullPointerException) but you need to be aware that "a field with a value of null" isn't the same as "a field which hasn't been explicitly assigned a value". Null is a perfectly valid variable value (for non-primitive variables, of course). Indeed, you may even want to change the above code to:

if (box != null) {
    box.removeFromCanvas();
    // Forget about the box - we don't want to try to remove it again
    box = null;
}

The difference is also visible for local variables, which can't be read before they've been "definitely assigned" - but one of the values which they can be definitely assigned is null (for reference type variables):

// Won't compile
String x;
System.out.println(x);

// Will compile, prints null
String y = null;
System.out.println(y);

View contents of database file in Android Studio

This might not be the answer you're looking for, but I don't have a better way for downloading DB from phone. What I will suggest is make sure you're using this mini-DDMS. It will be super hidden though if you don't click the very small camoflage box at the very bottom left of program. (tried to hover over it otherwise you might miss it.)

Also the drop down that says no filters (top right). It literally has a ton of different ways you can monitor different process/apps by PPID, name, and a lot more. I've always used this to monitor phone, but keep in mind I'm not doing the type of dev work that needs to be 120% positive the database isn't doing something out of the ordinary.

Hope it helps

enter image description here

Show datalist labels but submit the actual value

The solution I use is the following:

<input list="answers" id="answer">
<datalist id="answers">
  <option data-value="42" value="The answer">
</datalist>

Then access the value to be sent to the server using JavaScript like this:

var shownVal = document.getElementById("answer").value;
var value2send = document.querySelector("#answers option[value='"+shownVal+"']").dataset.value;


Hope it helps.

Project has no default.properties file! Edit the project properties to set one

Project has no default.properties file! Edit the project properties to set one

best option is create new workspace import the project ,fix the project its work

Python map object is not subscriptable

In Python 3, map returns an iterable object of type map, and not a subscriptible list, which would allow you to write map[i]. To force a list result, write

payIntList = list(map(int,payList))

However, in many cases, you can write out your code way nicer by not using indices. For example, with list comprehensions:

payIntList = [pi + 1000 for pi in payList]
for pi in payIntList:
    print(pi)

How to set default Checked in checkbox ReactJS?

In my case I felt that "defaultChecked" was not working properly with states/conditions. So I used "checked" with "onChange" for toggling the state.

Eg.

checked={this.state.enabled} onChange={this.setState({enabled : !this.state.enabled})}

Converting Go struct to JSON

You need to export the User.name field so that the json package can see it. Rename the name field to Name.

package main

import (
    "fmt"
    "encoding/json"
)

type User struct {
    Name string
}

func main() {
    user := &User{Name: "Frank"}
    b, err := json.Marshal(user)
    if err != nil {
        fmt.Println(err)
        return
    }
    fmt.Println(string(b))
}

Output:

{"Name":"Frank"}

clear javascript console in Google Chrome

On MacOS:

  1. Chrome - CMD+K
  2. Safari - CMD+K
  3. Firefox - No shortcut

On Linux:

  1. Chrome - CTRL+L
  2. Firefox - No shortcut

On Windows:

  1. Chrome - CTRL+L
  2. IE - CTRL+L
  3. Edge - CTRL+L
  4. Firefox - No shortcut

To make it work in Firefox, userscripts can be used. Download GreaseMonkey extension for FF.

document.addEventListener("keydown",function(event){
    if(event.metaKey && event.which==75) //CMD+K
    {
        console.clear();
    }
});

In the script, update the metadata with the value, //@include *://*/*, to make it run on every pages. It will work only when the focus is on the page. It's just a workaround.

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

tl;dr

Use java.time.Instant class to parse text in standard ISO 8601 format, representing a moment in UTC.

Instant.parse( "2010-10-02T12:23:23Z" )

ISO 8601

That format is defined by the ISO 8601 standard for date-time string formats.

Both:

…use ISO 8601 formats by default for parsing and generating strings.

You should generally avoid using the old java.util.Date/.Calendar & java.text.SimpleDateFormat classes as they are notoriously troublesome, confusing, and flawed. If required for interoperating, you can convert to and fro.

java.time

Built into Java 8 and later is the new java.time framework. Inspired by Joda-Time, defined by JSR 310, and extended by the ThreeTen-Extra project.

Instant instant = Instant.parse( "2010-10-02T12:23:23Z" );  // `Instant` is always in UTC.

Convert to the old class.

java.util.Date date = java.util.Date.from( instant );  // Pass an `Instant` to the `from` method.

Time Zone

If needed, you can assign a time zone.

ZoneId zoneId = ZoneId.of( "America/Montreal" ); // Define a time zone rather than rely implicitly on JVM’s current default time zone.
ZonedDateTime zdt = ZonedDateTime.ofInstant( instant , zoneId );  // Assign a time zone adjustment from UTC.

Convert.

java.util.Date date = java.util.Date.from( zdt.toInstant() );  // Extract an `Instant` from the `ZonedDateTime` to pass to the `from` method.

Joda-Time

UPDATE: The Joda-Time project is now in maintenance mode. The team advises migration to the java.time classes.

Here is some example code in Joda-Time 2.8.

org.joda.time.DateTime dateTime_Utc = new DateTime( "2010-10-02T12:23:23Z" , DateTimeZone.UTC );  // Specifying a time zone to apply, rather than implicitly assigning the JVM’s current default.

Convert to old class. Note that the assigned time zone is lost in conversion, as j.u.Date cannot be assigned a time zone.

java.util.Date date = dateTime_Utc.toDate(); // The `toDate` method converts to old class.

Time Zone

If needed, you can assign a time zone.

DateTimeZone zone = DateTimeZone.forID( "America/Montreal" );
DateTime dateTime_Montreal = dateTime_Utc.withZone ( zone );

Table of date-time types in Java, both modern and legacy.


About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.

Where to obtain the java.time classes?

Table of which java.time library to use with which version of Java or Android.

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

Vue js error: Component template should contain exactly one root element

For a more complete answer: http://www.compulsivecoders.com/tech/vuejs-component-template-should-contain-exactly-one-root-element/

But basically:

  • Currently, a VueJS template can contain only one root element (because of rendering issue)
  • In cases you really need to have two root elements because HTML structure does not allow you to create a wrapping parent element, you can use vue-fragment.

To install it:

npm install vue-fragment

To use it:

import Fragment from 'vue-fragment';
Vue.use(Fragment.Plugin);

// or

import { Plugin } from 'vue-fragment';
Vue.use(Plugin);

Then, in your component:

<template>
  <fragment>
    <tr class="hola">
      ...
    </tr>
    <tr class="hello">
      ...
    </tr>
  </fragment>
</template>

Callback functions in C++

The accepted answer is comprehensive but related to the question i just want to put an simple example here. I had a code that i'd written it a long time ago. i wanted to traverse a tree with in-order way (left-node then root-node then right-node) and whenever i reach to one Node i wanted to be able to call a arbitrary function so that it could do everything.

void inorder_traversal(Node *p, void *out, void (*callback)(Node *in, void *out))
{
    if (p == NULL)
        return;
    inorder_traversal(p->left, out, callback);
    callback(p, out); // call callback function like this.
    inorder_traversal(p->right, out, callback);
}


// Function like bellow can be used in callback of inorder_traversal.
void foo(Node *t, void *out = NULL)
{
    // You can just leave the out variable and working with specific node of tree. like bellow.
    // cout << t->item;
    // Or
    // You can assign value to out variable like below
    // Mention that the type of out is void * so that you must firstly cast it to your proper out.
    *((int *)out) += 1;
}
// This function use inorder_travesal function to count the number of nodes existing in the tree.
void number_nodes(Node *t)
{
    int sum = 0;
    inorder_traversal(t, &sum, foo);
    cout << sum;
}

 int main()
{

    Node *root = NULL;
    // What These functions perform is inserting an integer into a Tree data-structure.
    root = insert_tree(root, 6);
    root = insert_tree(root, 3);
    root = insert_tree(root, 8);
    root = insert_tree(root, 7);
    root = insert_tree(root, 9);
    root = insert_tree(root, 10);
    number_nodes(root);
}

How Do I Uninstall Yarn

I couldn't uninstall yarn on windows and I tried every single answer here, but every time I ran yarn -v, the command worked. But then I realized that there is another thing that can affect this.

If you on windows (not sure if this also happens in mac) and using nvm, one problem that can happen is that you have installed nvm without uninstalling npm, and the working yarn command is from your old yarn version from the old npm.

So what you need to do is follow this step from the nvm docs

You should also delete the existing npm install location (e.g. "C:\Users<user>\AppData\Roaming\npm"), so that the nvm install location will be correctly used instead. Backup the global npmrc config (e.g. C:\Users&lt;user>\AppData\Roaming\npm\etc\npmrc), if you have some important settings there, or copy the settings to the user config C:\Users&lt;user>.npmrc.

And to confirm that you problem is with the old npm, you will probably see the yarn.cmd file inside the C:\Users\<user>\AppData\Roaming\npm folder.

How to iterate through a list of objects in C++

Since C++ 11, you could do the following:

for(const auto& student : data)
{
  std::cout << student.name << std::endl;
}

Spring Boot application.properties value not populating

Using Environment class we can get application. Properties values

@Autowired,

private Environment env;

and access using

String password =env.getProperty(your property key);

Save image from url with curl PHP

This is easiest implement.

function downloadFile($url, $path)
{
    $newfname = $path;
    $file = fopen($url, 'rb');
    if ($file) {
        $newf = fopen($newfname, 'wb');
        if ($newf) {
            while (!feof($file)) {
                fwrite($newf, fread($file, 1024 * 8), 1024 * 8);
            }
        }
    }
    if ($file) {
        fclose($file);
    }
    if ($newf) {
        fclose($newf);
    }
}

How can I get double quotes into a string literal?

Thankfully, with C++11 there is also the more pleasing approach of using raw string literals.

printf("She said \"time flies like an arrow, but fruit flies like a banana\".");

Becomes:

printf(R"(She said "time flies like an arrow, but fruit flies like a banana".)");

With respect to the addition of brackets after the opening quote, and before the closing quote, note that they can be almost any combination of up to 16 characters, helping avoid the situation where the combination is present in the string itself. Specifically:

any member of the basic source character set except: space, the left parenthesis (, the right parenthesis ), the backslash , and the control characters representing horizontal tab, vertical tab, form feed, and newline" (N3936 §2.14.5 [lex.string] grammar) and "at most 16 characters" (§2.14.5/2)

How much clearer it makes this short strings might be debatable, but when used on longer formatted strings like HTML or JSON, it's unquestionably far clearer.

How to open a new tab using Selenium WebDriver

driver.findElement(By.cssSelector("body")).sendKeys(Keys.CONTROL +"t");

ArrayList<String> tabs = new ArrayList<String> (driver.getWindowHandles());

driver.switchTo().window(tabs.get(0));

Example on ToggleButton

You should follow the Google guide;

ToggleButton toggle = (ToggleButton) findViewById(R.id.togglebutton);
toggle.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        if (isChecked) {
            // The toggle is enabled
        } else {
            // The toggle is disabled
        }
    }
});

You can check the documentation here

Automatically capture output of last command into a variable using Bash?

I find remembering to pipe the output of my commands into a specific file to be a bit annoying, my solution is a function in my .bash_profile that catches the output in a file and returns the result when you need it.

The advantage with this one is that you don't have to rerun the whole command (when using find or other long-running commands that can be critical)

Simple enough, paste this in your .bash_profile:

Script

# catch stdin, pipe it to stdout and save to a file
catch () { cat - | tee /tmp/catch.out}
# print whatever output was saved to a file
res () { cat /tmp/catch.out }

Usage

$ find . -name 'filename' | catch
/path/to/filename

$ res
/path/to/filename

At this point, I tend to just add | catch to the end of all of my commands, because there's no cost to doing it and it saves me having to rerun commands that take a long time to finish.

Also, if you want to open the file output in a text editor you can do this:

# vim or whatever your favorite text editor is
$ vim <(res)

How to send a correct authorization header for basic authentication

PHP - curl:

$username = 'myusername';
$password = 'mypassword';
...
curl_setopt($ch, CURLOPT_USERPWD, $username . ":" . $password);
...

PHP - POST in WordPress:

$username = 'myusername';
$password = 'mypassword';
...
wp_remote_post('https://...some...api...endpoint...', array(
  'headers' => array(
    'Authorization' => 'Basic ' . base64_encode("$username:$password")
  )
));
...

Disabled UIButton not faded or grey

If you use a text button, you can put into viewDidLoad the instance method

- (void)setTitleColor:(UIColor *)color forState:(UIControlState)state

example:

[self.syncImagesButton setTitleColor:[UIColor grayColor] forState:UIControlStateDisabled];

Javascript add leading zeroes to date

try this for a basic function, no libraries required

Date.prototype.CustomformatDate = function() {
 var tmp = new Date(this.valueOf());
 var mm = tmp.getMonth() + 1;
 if (mm < 10) mm = "0" + mm;
 var dd = tmp.getDate();
 if (dd < 10) dd = "0" + dd;
 return mm + "/" + dd + "/" + tmp.getFullYear();
};

Creating a UICollectionView programmatically

Apple Docs:

- (id)initWithFrame:(CGRect)frame 
      collectionViewLayout:(UICollectionViewLayout *)layoutParameters

Use this method when initializing a collection view object programmatically. If you specify nil for the layout parameter, you must assign a layout object to the collectionViewLayout property before displaying the collection view onscreen. If you do not, the collection view will be unable to present any items onscreen.

This method is the designated initializer.

This method is used to initialize the UICollectionView. here you provide frame and a UICollectionViewLayout object.

UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc]init];

At the end, add UICollectionView as a subview to your view.

Now collection view is added pro grammatically. You can go on learning.
Happy learning!! Hope it helps you.

Android Firebase, simply get one child object's data

just fetch specific node data and its working perfect for me

mFirebaseInstance.getReference("yourNodeName").getRef().addValueEventListener(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {


        for (DataSnapshot postSnapshot : dataSnapshot.getChildren()) {
            Log.e(TAG, "======="+postSnapshot.child("email").getValue());
            Log.e(TAG, "======="+postSnapshot.child("name").getValue());
        }
    }

    @Override
    public void onCancelled(DatabaseError error) {
        // Failed to read value
        Log.e(TAG, "Failed to read app title value.", error.toException());
    }
});

How to use OUTPUT parameter in Stored Procedure

There are a several things you need to address to get it working

  1. The name is wrong its not @ouput its @code
  2. You need to set the parameter direction to Output.
  3. Don't use AddWithValue since its not supposed to have a value just you Add.
  4. Use ExecuteNonQuery if you're not returning rows

Try

SqlParameter output = new SqlParameter("@code", SqlDbType.Int);
output.Direction = ParameterDirection.Output;
cmd.Parameters.Add(output);
cmd.ExecuteNonQuery();
MessageBox.Show(output.Value.ToString());

Apache Proxy: No protocol handler was valid

In my case, I needed proxy_ajp module.

a2enmod proxy proxy_http proxy_ajp 

How do shift operators work in Java?

Signed left shift Logically Simple if 1<<11 it will tends to 2048 and 2<<11 will give 4096

In java programming int a = 2 << 11;

// it will result in 4096

2<<11 = 2*(2^11) = 4096

Generate Row Serial Numbers in SQL Query

I'm not certain, based on your question if you want numbered rows that will remember their numbers even if the underlying data changes (and gives a different ordering), but if you just want numbered rows - that reset on a change in customer ID, then try using the Partition by clause of row_number()

row_number() over(partition by CustomerID order by CustomerID)

Way to read first few lines for pandas dataframe

I think you can use the nrows parameter. From the docs:

nrows : int, default None

    Number of rows of file to read. Useful for reading pieces of large files

which seems to work. Using one of the standard large test files (988504479 bytes, 5344499 lines):

In [1]: import pandas as pd

In [2]: time z = pd.read_csv("P00000001-ALL.csv", nrows=20)
CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
Wall time: 0.00 s

In [3]: len(z)
Out[3]: 20

In [4]: time z = pd.read_csv("P00000001-ALL.csv")
CPU times: user 27.63 s, sys: 1.92 s, total: 29.55 s
Wall time: 30.23 s

Count number of records returned by group by

How about:

SELECT count(column_1)
FROM
    (SELECT * FROM temptable
    GROUP BY column_1, column_2, column_3, column_4) AS Records

Node - how to run app.js?

Assuming I have node and npm properly installed on the machine, I would

  • Download the code
  • Navigate to inside the project folder on terminal, where I would hopefully see a package.json file
  • Do an npm install for installing all the project dependencies
  • Do an npm install -g nodemon for installing all the project dependencies
  • Then npm start OR node app.js OR nodemon app.js to get the app running on local host

Hope this helps someone

use nodemon app.js ( nodemon is a utility that will monitor for any changes in your source and automatically restart your server)

How to solve SQL Server Error 1222 i.e Unlock a SQL Server table

In the SQL Server Management Studio, to find out details of the active transaction, execute following command

DBCC opentran()

You will get the detail of the active transaction, then from the SPID of the active transaction, get the detail about the SPID using following commands

exec sp_who2 <SPID>
exec sp_lock <SPID>

For example, if SPID is 69 then execute the command as

exec sp_who2 69
exec sp_lock 69

Now , you can kill that process using the following command

KILL 69

I hope this helps :)

Descending order by date filter in AngularJs

According to documentation you can use the reverse argument.

filter:orderBy(array, expression[, reverse]);

Change your filter to:

orderBy: 'created_at':true

Run two async tasks in parallel and collect results in .NET 4.5

While your Sleep method is async, Thread.Sleep is not. The whole idea of async is to reuse a single thread, not to start multiple threads. Because you've blocked using a synchronous call to Thread.Sleep, it's not going to work.

I'm assuming that Thread.Sleep is a simplification of what you actually want to do. Can your actual implementation be coded as async methods?

If you do need to run multiple synchronous blocking calls, look elsewhere I think!

CSS image resize percentage of itself?

Actually most of the answers here doesn't really scale the image to the width of itself.

We need to have a width and height of auto on the img element itself so we can start with it's original size.

After that a container element can scale the image for us.

Simple HTML example:

<div style="position: relative;">
    <figure>
       <img src="[email protected]" />
    </figure>
</div>

And here are the CSS rules. I use an absolute container in this case:

figure {
    position: absolute;
    left: 0;
    top: 0;
    -webkit-transform: scale(0.5); 
    -moz-transform: scale(0.5);
    -ms-transform: scale(0.5); 
    -o-transform: scale(0.5);
    transform: scale(0.5);
    transform-origin: left;
} 

figure img {
    width: auto;
    height: auto;
}

You could tweak the image positioning with rules like transform: translate(0%, -50%);.

Infinite Recursion with Jackson JSON and Hibernate JPA issue

If you use @JsonManagedReference, @JsonBackReference or @JsonIgnore annotation it ignore some fields and solve Infinite Recursion with Jackson JSON.

But if you use @JsonIdentityInfo which also avoid the Infinite Recursion and you can get all the fields values, so I suggest that you use @JsonIdentityInfo annotation.

@JsonIdentityInfo(generator= ObjectIdGenerators.UUIDGenerator.class, property="@id")

Refer this article https://www.toptal.com/javascript/bidirectional-relationship-in-json to get good understanding about @JsonIdentityInfo annotation.

How to install pip3 on Windows?

For python3.5.3, pip3 is also installed when you install python. When you install it you may not select the add to path. Then you can find where the pip3 located and add it to path manually.

Update query PHP MySQL

<?php
require 'db_config.php';


  $id  = $_POST["id"];
  $post = $_POST;

  $sql = "UPDATE items SET title = '".$post['title']."'

    ,description = '".$post['description']."' 

    WHERE id = '".$id."'";

  $result = $mysqli->query($sql);


  $sql = "SELECT * FROM items WHERE id = '".$id."'"; 

  $result = $mysqli->query($sql);

  $data = $result->fetch_assoc();


echo json_encode($data);
?>

Difference between del, remove, and pop on lists

Here is a detailed answer.

del can be used for any class object whereas pop and remove and bounded to specific classes.

For del

Here are some examples

>>> a = 5
>>> b = "this is string"
>>> c = 1.432
>>> d = myClass()

>>> del c
>>> del a, b, d   # we can use comma separated objects

We can override __del__ method in user-created classes.

Specific uses with list

>>> a = [1, 4, 2, 4, 12, 3, 0]
>>> del a[4]
>>> a
[1, 4, 2, 4, 3, 0]

>>> del a[1: 3]   # we can also use slicing for deleting range of indices
>>> a
[1, 4, 3, 0]

For pop

pop takes the index as a parameter and removes the element at that index

Unlike del, pop when called on list object returns the value at that index

>>> a = [1, 5, 3, 4, 7, 8]
>>> a.pop(3)  # Will return the value at index 3
4
>>> a
[1, 5, 3, 7, 8]

For remove

remove takes the parameter value and remove that value from the list.

If multiple values are present will remove the first occurrence

Note: Will throw ValueError if that value is not present

>>> a = [1, 5, 3, 4, 2, 7, 5]
>>> a.remove(5)  # removes first occurence of 5
>>> a
[1, 3, 4, 2, 7, 5]
>>> a.remove(5)
>>> a
[1, 3, 4, 2, 7]

Hope this answer is helpful.

Uploading Images to Server android

use below code it helps you....

        BitmapFactory.Options options = new BitmapFactory.Options();

        options.inSampleSize = 4;
        options.inPurgeable = true;
        Bitmap bm = BitmapFactory.decodeFile("your path of image",options);

        ByteArrayOutputStream baos = new ByteArrayOutputStream();

        bm.compress(Bitmap.CompressFormat.JPEG,40,baos); 


        // bitmap object

        byteImage_photo = baos.toByteArray();

                    //generate base64 string of image

                   String encodedImage =Base64.encodeToString(byteImage_photo,Base64.DEFAULT);

  //send this encoded string to server

Matplotlib scatterplot; colour as a function of a third variable

Sometimes you may need to plot color precisely based on the x-value case. For example, you may have a dataframe with 3 types of variables and some data points. And you want to do following,

  • Plot points corresponding to Physical variable 'A' in RED.
  • Plot points corresponding to Physical variable 'B' in BLUE.
  • Plot points corresponding to Physical variable 'C' in GREEN.

In this case, you may have to write to short function to map the x-values to corresponding color names as a list and then pass on that list to the plt.scatter command.

x=['A','B','B','C','A','B']
y=[15,30,25,18,22,13]

# Function to map the colors as a list from the input list of x variables
def pltcolor(lst):
    cols=[]
    for l in lst:
        if l=='A':
            cols.append('red')
        elif l=='B':
            cols.append('blue')
        else:
            cols.append('green')
    return cols
# Create the colors list using the function above
cols=pltcolor(x)

plt.scatter(x=x,y=y,s=500,c=cols) #Pass on the list created by the function here
plt.grid(True)
plt.show()

Coloring scatter plot as a function of x variable

How to break line in JavaScript?

Here you are ;-)

<script type="text/javascript">
    alert("Hello there.\nI am on a second line ;-)")
</script>

Creating your own header file in C

foo.h

#ifndef FOO_H_   /* Include guard */
#define FOO_H_

int foo(int x);  /* An example function declaration */

#endif // FOO_H_

foo.c

#include "foo.h"  /* Include the header (not strictly necessary here) */

int foo(int x)    /* Function definition */
{
    return x + 5;
}

main.c

#include <stdio.h>
#include "foo.h"  /* Include the header here, to obtain the function declaration */

int main(void)
{
    int y = foo(3);  /* Use the function here */
    printf("%d\n", y);
    return 0;
}

To compile using GCC

gcc -o my_app main.c foo.c

How can I de-install a Perl module installed via `cpan`?

There are scripts on CPAN which attempt to uninstall modules:

ExtUtils::Packlist shows sample module removing code, modrm.

Error starting ApplicationContext. To display the auto-configuration report re-run your application with 'debug' enabled

It seems to me that your Hibernate libraries are not found (NoClassDefFoundError: org/hibernate/boot/archive/scan/spi/ScanEnvironment as you can see above).

Try checking to see if Hibernate core is put in as dependency:

<dependency>
  <groupId>org.hibernate</groupId>
  <artifactId>hibernate-core</artifactId>
  <version>5.0.11.Final</version>
  <scope>compile</scope>
</dependency>

Returning http 200 OK with error within response body

HTTP Is the Protocol handling the transmission of data over the internet.

If that transmission breaks for whatever reason the HTTP error codes tell you why it can't be sent to you.

The data being transmitted is not handled by HTTP Error codes. Only the method of transmission.

HTTP can't say 'Ok, this answer is gobbledigook, but here it is'. it just says 200 OK.

i.e : I've completed my job of getting it to you, the rest is up to you.

I know this has been answered already but I put it in words I can understand. sorry for any repetition.

Why should I use core.autocrlf=true in Git?

For me.

Edit .gitattributes file.

add

*.dll binary

Then everything goes well.

How to convert an array of key-value tuples into an object

In my case, all other solutions didn't work, but this one did:

obj = {...arr}

my arr is in a form: [name: "the name", email: "[email protected]"]

div with dynamic min-height based on browser window height

Just look for my solution on jsfiddle, it is based on csslayout

_x000D_
_x000D_
html,_x000D_
body {_x000D_
  margin: 0;_x000D_
  padding: 0;_x000D_
  height: 100%; /* needed for container min-height */_x000D_
}_x000D_
div#container {_x000D_
  position: relative; /* needed for footer positioning*/_x000D_
  height: auto !important; /* real browsers */_x000D_
  min-height: 100%; /* real browsers */_x000D_
}_x000D_
div#header {_x000D_
  padding: 1em;_x000D_
  background: #efe;_x000D_
}_x000D_
div#content {_x000D_
  /* padding:1em 1em 5em; *//* bottom padding for footer */_x000D_
}_x000D_
div#footer {_x000D_
  position: absolute;_x000D_
  width: 100%;_x000D_
  bottom: 0; /* stick to bottom */_x000D_
  background: #ddd;_x000D_
}
_x000D_
<div id="container">_x000D_
_x000D_
  <div id="header">header</div>_x000D_
_x000D_
  <div id="content">_x000D_
    content<br/>content<br/>content<br/>content<br/>content<br/>content<br/>content<br/>content<br/>content<br/>content<br/>content<br/>content<br/>content<br/>content<br/>content<br/>content<br/>content<br/>content<br/>_x000D_
  </div>_x000D_
_x000D_
  <div id="footer">_x000D_
    footer_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Passing variable number of arguments around

There's no way of calling (eg) printf without knowing how many arguments you're passing to it, unless you want to get into naughty and non-portable tricks.

The generally used solution is to always provide an alternate form of vararg functions, so printf has vprintf which takes a va_list in place of the .... The ... versions are just wrappers around the va_list versions.

How to display a "busy" indicator with jQuery?

I had to use

HTML:
   <img id="loading" src="~/Images/spinner.gif" alt="Updating ..." style="display: none;" />

In script file:
  // invoked when sending ajax request
  $(document).ajaxSend(function () {
      $("#loading").show();
  });

  // invoked when sending ajax completed
  $(document).ajaxComplete(function () {
      $("#loading").hide();
  });

Node.js: printing to console without a trailing newline?

I got the following error when using strict mode:

Node error: "Octal literals are not allowed in strict mode."

The following solution works (source):

process.stdout.write("received: " + bytesReceived + "\x1B[0G");

X11/Xlib.h not found in Ubuntu

Why not try find /usr/include/X11 -name Xlib.h

If there is a hit, you have Xlib.h

If not install it using sudo apt-get install libx11-dev

and you are good to go :)

vba error handling in loop

There is another way of controlling error handling that works well for loops. Create a string variable called here and use the variable to determine how a single error handler handles the error.

The code template is:

On error goto errhandler

Dim here as String

here = "in loop"
For i = 1 to 20 
    some code
Next i

afterloop:
here = "after loop"
more code

exitproc:    
exit sub

errhandler:
If here = "in loop" Then 
    resume afterloop
elseif here = "after loop" Then
    msgbox "An error has occurred" & err.desc
    resume exitproc
End if

Terminal Commands: For loop with echo

The default shell on OS X is bash. You could write this:

for i in {1..100}; do echo http://www.example.com/${i}.jpg; done

Here is a link to the reference manual of bash concerning loop constructs.

forcing web-site to show in landscape mode only

I had to play with the widths of my main containers:

html {
  @media only screen and (orientation: portrait) and (max-width: 555px) {
    transform: rotate(90deg);
    width: calc(155%);
    .content {
      width: calc(155%);
    }
  }
}

Is there any way to have a fieldset width only be as wide as the controls in them?

Going further of Mihai solution, cross-browser left aligned:

<TABLE>
  <TR>
    <TD>
      <FORM>
        <FIELDSET>
          ...
        </FIELDSET>
      </FORM>
    </TD>
  </TR>
</TABLE>

Cross-browser right aligned:

<TABLE>
  <TR>
    <TD WIDTH=100%></TD>
    <TD>
      <FORM>
        <FIELDSET>
          ...
        </FIELDSET>
      </FORM>
    </TD>
  </TR>
</TABLE>

How to set editor theme in IntelliJ Idea

For IntelliJ in Mac

View -> Quick Switch theme (^`)-> color schema

What do I use for a max-heap implementation in Python?

This is a simple MaxHeap implementation based on heapq. Though it only works with numeric values.

import heapq
from typing import List


class MaxHeap:
    def __init__(self):
        self.data = []

    def top(self):
        return -self.data[0]

    def push(self, val):
        heapq.heappush(self.data, -val)

    def pop(self):
        return -heapq.heappop(self.data)

Usage:

max_heap = MaxHeap()
max_heap.push(3)
max_heap.push(5)
max_heap.push(1)
print(max_heap.top())  # 5

JSON array get length

The below snippet works fine for me(I used the size())

String itemId;
            for (int i = 0; i < itemList.size(); i++) {
            JSONObject itemObj = (JSONObject)itemList.get(i);
            itemId=(String) itemObj.get("ItemId");
            System.out.println(itemId);
            }

If it is wrong to use use size() kindly advise

How to get text and a variable in a messagebox

As has been suggested, using the string.format method is nice and simple and very readable.

In vb.net the " + " is used for addition and the " & " is used for string concatenation.

In your example:

MsgBox("Variable = " + variable)

becomes:

MsgBox("Variable = " & variable)

I may have been a bit quick answering this as it appears these operators can both be used for concatenation, but recommended use is the "&", source http://msdn.microsoft.com/en-us/library/te2585xw(v=VS.100).aspx

maybe call

variable.ToString()

update:

Use string interpolation (vs2015 onwards I believe):

MsgBox($"Variable = {variable}")

How to send an HTTPS GET Request in C#

Add ?var1=data1&var2=data2 to the end of url to submit values to the page via GET:

using System.Net;
using System.IO;

string url = "https://www.example.com/scriptname.php?var1=hello";

HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream resStream = response.GetResponseStream();

How to decode encrypted wordpress admin password?

just edit wp_user table with your phpmyadmin, and choose MD5 on Function field then input your new password, save it (go button). enter image description here

How do I rename all folders and files to lowercase on Linux?

In OS X, mv -f shows "same file" error, so I rename twice:

for i in `find . -name "*" -type f |grep -e "[A-Z]"`; do j=`echo $i | tr '[A-Z]' '[a-z]' | sed s/\-1$//`; mv $i $i-1; mv $i-1 $j; done

how to drop database in sqlite?

If you use SQLiteOpenHelper you can do this

        String myPath = DB_PATH + DB_NAME;
        SQLiteDatabase.deleteDatabase(new File(myPath));

How to apply a CSS filter to a background image

I didn't write this, but I noticed there was a polyfill for the partially supported backdrop-filter using the CSS SASS compiler, so if you have a compilation pipeline it can be achieved nicely (it also uses TypeScript):

https://codepen.io/mixal_bl4/pen/EwPMWo

CSS how to make an element fade in and then fade out?

Try this:

@keyframes animationName {
  0%   { opacity:0; }
  50%  { opacity:1; }
  100% { opacity:0; }
}
@-o-keyframes animationName{
  0%   { opacity:0; }
  50%  { opacity:1; }
  100% { opacity:0; }
}
@-moz-keyframes animationName{
  0%   { opacity:0; }
  50%  { opacity:1; }
  100% { opacity:0; }
}
@-webkit-keyframes animationName{
  0%   { opacity:0; }
  50%  { opacity:1; }
  100% { opacity:0; }
}   
.elementToFadeInAndOut {
   -webkit-animation: animationName 5s infinite;
   -moz-animation: animationName 5s infinite;
   -o-animation: animationName 5s infinite;
    animation: animationName 5s infinite;
}

VBA error 1004 - select method of range class failed

assylias and Head of Catering have already given your the reason why the error is occurring.

Now regarding what you are doing, from what I understand, you don't need to use Select at all

I guess you are doing this from VBA PowerPoint? If yes, then your code be rewritten as

Dim sourceXL As Object, sourceBook As Object
Dim sourceSheet As Object, sourceSheetSum As Object
Dim lRow As Long
Dim measName As Variant, partName As Variant
Dim filepath As String

filepath = CStr(FileDialog)

'~~> Establish an EXCEL application object
On Error Resume Next
Set sourceXL = GetObject(, "Excel.Application")

'~~> If not found then create new instance
If Err.Number <> 0 Then
    Set sourceXL = CreateObject("Excel.Application")
End If
Err.Clear
On Error GoTo 0

Set sourceBook = sourceXL.Workbooks.Open(filepath)
Set sourceSheet = sourceBook.Sheets("Measurements")
Set sourceSheetSum = sourceBook.Sheets("Analysis Summary")

lRow = sourceSheetSum.Range("C" & sourceSheetSum.Rows.Count).End(xlUp).Row
measName = sourceSheetSum.Range("C3:C" & lRow)

lRow = sourceSheetSum.Range("D" & sourceSheetSum.Rows.Count).End(xlUp).Row
partName = sourceSheetSum.Range("D3:D" & lRow)

How to put two divs on the same line with CSS in simple_form in rails?

Your css is fine, but I think it's not applying on divs. Just write simple class name and then try. You can check it at Jsfiddle.

.left {
  float: left;
  width: 125px;
  text-align: right;
  margin: 2px 10px;
  display: inline;
}

.right {
  float: left;
  text-align: left;
  margin: 2px 10px;
  display: inline;
}

SQL Server - INNER JOIN WITH DISTINCT

I think you actually provided a good start for the correct answer right in your question (you just need the correct syntax). I had this exact same problem, and putting DISTINCT in a sub-query was indeed less costly than what other answers here have proposed.

select a.FirstName, a.LastName, v.District
from AddTbl a 
inner join (select distinct LastName, District 
    from ValTbl) v
   on a.LastName = v.LastName
order by Firstname   

Define a fixed-size list in Java

You need either of the following depending on the type of the container of T elements you pass to the builder (Collection<T> or T[]):

  • In case of an existing Collection<T> YOUR_COLLECTION:
Collections.unmodifiableList(new ArrayList<>(YOUR_COLLECTION));
  • In case of an existing T[] YOUR_ARRAY:
Arrays.asList(YOUR_ARRAY);

Simple as that

How can I get a list of users from active directory?

Include the System.DirectoryServices.dll, then use the code below:

DirectoryEntry directoryEntry = new DirectoryEntry("WinNT://" + Environment.MachineName);
string userNames="Users: ";

foreach (DirectoryEntry child in directoryEntry.Children)
{
    if (child.SchemaClassName == "User")
    {
        userNames += child.Name + Environment.NewLine   ;         
    }

}
MessageBox.Show(userNames);

Extracting the last n characters from a string in R

An alternative to substr is to split the string into a list of single characters and process that:

N <- 2
sapply(strsplit(x, ""), function(x, n) paste(tail(x, n), collapse = ""), N)

Concatenate two char* strings in a C program

The way it works is to:

  1. Malloc memory large enough to hold copies of str1 and str2
  2. Then it copies str1 into str3
  3. Then it appends str2 onto the end of str3
  4. When you're using str3 you'd normally free it free (str3);

Here's an example for you play with. It's very simple and has no hard-coded lengths. You can try it here: http://ideone.com/d3g1xs

See this post for information about size of char

#include <stdio.h>
#include <memory.h>

int main(int argc, char** argv) {

      char* str1;
      char* str2;
      str1 = "sssss";
      str2 = "kkkk";
      char * str3 = (char *) malloc(1 + strlen(str1)+ strlen(str2) );
      strcpy(str3, str1);
      strcat(str3, str2);
      printf("%s", str3);

      return 0;
 }

What are named pipes?

Named pipes in a unix/linux context can be used to make two different shells to communicate since a shell just can't share anything with another.

Furthermore, one script instantiated twice in the same shell can't share anything through the two instances. I found a use for named pipes when coding a daemon that contains the start() and stop() function, and I wanted to use the same script to perform the two actions.

Without named pipes (or any kind of semaphore) starting the script in the background is not a problem. The thing is when it finishes you just can't access the instance in background.

So when you want to send him the stop command you just can't: running the same script without named pipes and calling the stop() function won't do anything since you are actually running another instance.

The solution was to implement two pipes, one READ and the other WRITE when you start the daemon. Then make him, among its other tasks, listen to the READ pipe. Then the Stop() function contains a command that will write a message in the pipe, that will be handled by the background running script that will perform an exit 0. This way our second instance of the same script has only on task to do: tell the first instance to stop.

This way one and only one script can start and stop itself.

Of course you have different ways to do it by triggering the stop via a touch for example. But this one is nice and interesting to code.

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

If you want to make it fully automatic, one click, or to load automatically into Excel from say a web page, but can't generate proper Excel files, then I would suggest looking at SYLK format as an alternative. OK it is not as simple as CSV but it is text based and very easy to implement and it supports UTF-8 with no issues.

I wrote a PHP class that receives the data and outputs a SYLK file which will open directly in Excel by just clicking the file (or will auto-launch Excel if you write the file to a web page with the correct mime type. You can even add formatting (like bold, format numbers in particular ways etc) and change column sizes, or auto size columns to the text in the columns and all in all the code is probably not more than about 100 lines.

It is dead easy to reverse engineer SYLK by creating a simple spreadsheet and saving as SYLK and then reading it with a text editor. The first block are headers and standard number formats that you will recognise (which you just regurgitate in every file you create), then the data is simply an X/Y coordinate and a value.

Is object empty?

if (Object.getOwnPropertyNames(obj1).length > 0)
{
 alert('obj1 is empty!');
}

Should I call Close() or Dispose() for stream objects?

On many classes which support both Close() and Dispose() methods, the two calls would be equivalent. On some classes, however, it is possible to re-open an object which has been closed. Some such classes may keep some resources alive after a Close, in order to permit reopening; others may not keep any resources alive on Close(), but might set a flag on Dispose() to explicitly forbid re-opening.

The contract for IDisposable.Dispose explicitly requires that calling it on an object which will never be used again will be at worst harmless, so I would recommend calling either IDisposable.Dispose or a method called Dispose() on every IDisposable object, whether or not one also calls Close().

How to remove the border highlight on an input text element

The only solutiion that worked with me

The border is actually a shadow. So to hide it I had to do this:

input[type="text"]:focus{
     box-shadow: 0 0 0 rgb(255, 255, 255);
}

 input[type="checkbox"]:focus{
      box-shadow: 0 0 0 rgb(255, 255, 255);
 }

How do I create a new branch?

In the Repository Browser of TortoiseSVN, find the branch that you want to create the new branch from. Right-click, Copy To.... and enter the new branch path. Now you can "switch" your local WC to that branch.

import an array in python

Have a look at SciPy cookbook. It should give you an idea of some basic methods to import /export data.

If you save/load the files from your own Python programs, you may also want to consider the Pickle module, or cPickle.

<select> HTML element with height

You can also "center" the text with:

vertical-align: middle;

Downloading a file from spring controllers

I was able to stream line this by using the built in support in Spring with it's ResourceHttpMessageConverter. This will set the content-length and content-type if it can determine the mime-type

@RequestMapping(value = "/files/{file_name}", method = RequestMethod.GET)
@ResponseBody
public FileSystemResource getFile(@PathVariable("file_name") String fileName) {
    return new FileSystemResource(myService.getFileFor(fileName)); 
}

Get list from pandas dataframe column or row?

If your column will only have one value something like pd.series.tolist() will produce an error. To guarantee that it will work for all cases, use the code below:

(
    df
        .filter(['column_name'])
        .values
        .reshape(1, -1)
        .ravel()
        .tolist()
)

Pandas: ValueError: cannot convert float NaN to integer

For identifying NaN values use boolean indexing:

print(df[df['x'].isnull()])

Then for removing all non-numeric values use to_numeric with parameter errors='coerce' - to replace non-numeric values to NaNs:

df['x'] = pd.to_numeric(df['x'], errors='coerce')

And for remove all rows with NaNs in column x use dropna:

df = df.dropna(subset=['x'])

Last convert values to ints:

df['x'] = df['x'].astype(int)

What does the term "Tuple" Mean in Relational Databases?

tuple = 1 record; n-tuple = ordered list of 'n' records; Elmasri Navathe book (page 198 3rd edition).

record = either ordered or unordered.

C++ Boost: undefined reference to boost::system::generic_category()

try

g++ -c main.cpp && g++ main.o /usr/lib/x86_64-linux-gnu/libboost_system.so && ./a.out 

/usr/lib/x86_64-linux-gnu/ is the location of the boost library

use find /usr/ -name '*boost*.so' to find the boost library location

Cannot get Kerberos service ticket: KrbException: Server not found in Kerberos database (7)

Consider adding

[appdefaults]
validate=false

to your /etc/krb5.conf. This can work around mismatching DNS.

Getting Cannot read property 'offsetWidth' of undefined with bootstrap carousel script

if you're using the compiled bootstrap, one of the ways of fixing it is by editing the bootstrap.min.js before the line

$next[0].offsetWidth 

force reflow Change to

if (typeof $next == 'object' && $next.length) $next[0].offsetWidth // force reflow

Make ABC Ordered List Items Have Bold Style

You could do something like this also:

<ol type="A" style="font-weight: bold;">

<li style="padding-bottom: 8px;">****</li>

It is simple code for the beginners.

This code is been tested in "Mozilla, chrome and edge..

How to get AM/PM from a datetime in PHP

Like this:

$date = '08/04/2010 22:15:00';
echo date('h:i A', strtotime($date));

Result:

10:15 PM

More Info:

How to stop tracking and ignore changes to a file in Git?

I am assuming that you are trying to remove a single file from git tacking. for that I would recommend below command.

git update-index --assume-unchanged

Ex - git update-index --assume-unchanged .gitignore .idea/compiler.xml

Accessing value inside nested dictionaries

You can use the get() on each dict. Make sure that you have added the None check for each access.

Detecting when a div's height changes using jQuery

You can use this, but it only supports Firefox and Chrome.

_x000D_
_x000D_
$(element).bind('DOMSubtreeModified', function () {_x000D_
  var $this = this;_x000D_
  var updateHeight = function () {_x000D_
    var Height = $($this).height();_x000D_
    console.log(Height);_x000D_
  };_x000D_
  setTimeout(updateHeight, 2000);_x000D_
});
_x000D_
_x000D_
_x000D_

remote rejected master -> master (pre-receive hook declined)

You might also want to check for Heroku telling you there's a typo in your CSS file.

Read through the long boring messages in the terminal closely after you push. There may be something like this: Invalid CSS after. It means Heroku has found a typo and you need to fix it in the CSS file.

You can do a find for rake aborted! and directly after that it should say why the push failed.

Java Multiple Inheritance

To reduce the complexity and simplify the language, multiple inheritance is not supported in java.

Consider a scenario where A, B and C are three classes. The C class inherits A and B classes. If A and B classes have same method and you call it from child class object, there will be ambiguity to call method of A or B class.

Since compile time errors are better than runtime errors, java renders compile time error if you inherit 2 classes. So whether you have same method or different, there will be compile time error now.

class A {  
    void msg() {
        System.out.println("From A");
    }  
}

class B {  
    void msg() {
        System.out.println("From B");
    }  
}

class C extends A,B { // suppose if this was possible
    public static void main(String[] args) {  
        C obj = new C();  
        obj.msg(); // which msg() method would be invoked?  
    }
} 

Import CSV to mysql table

To load data from text file or csv file the command is

load data local infile 'file-name.csv'
into table table-name
fields terminated by '' enclosed by '' lines terminated by '\n' (column-name);

In above command, in my case there is only one column to be loaded so there is no "terminated by" and "enclosed by" so I kept it empty else programmer can enter the separating character . for e.g . ,(comma) or " or ; or any thing.

**for people who are using mysql version 5 and above **

Before loading the file into mysql must ensure that below tow line are added in side etc/mysql/my.cnf

to edit my.cnf command is

sudo vi /etc/mysql/my.cnf

[mysqld]  
local-infile

[mysql]  
local-infile  

Using a BOOL property

Apple simply recommends declaring an isX getter for stylistic purposes. It doesn't matter whether you customize the getter name or not, as long as you use the dot notation or message notation with the correct name. If you're going to use the dot notation it makes no difference, you still access it by the property name:

@property (nonatomic, assign) BOOL working;

[self setWorking:YES];         // Or self.working = YES;
BOOL working = [self working]; // Or = self.working;

Or

@property (nonatomic, assign, getter=isWorking) BOOL working;

[self setWorking:YES];           // Or self.working = YES;, same as above
BOOL working = [self isWorking]; // Or = self.working;, also same as above

Virtualbox shared folder permissions

sudo adduser xxxxxxx vboxsf

where xxxxxx is your user account name. Log out and log back in to Ubuntu.

How do I change the root directory of an Apache server?

I was working with LAMP and to change the document root folder, I have edited the default file which is there in the /etc/apache2/sites-available folder.

If you want to do the same, just edit as follows:

DocumentRoot /home/username/new_root_folder
    <Directory />
        Options FollowSymLinks
        AllowOverride None
    </Directory>
    <Directory /home/username/new_root_folder>
        Options Indexes FollowSymLinks MultiViews
        AllowOverride None
        Order allow,deny
        allow from all
    </Directory>

After this, if you type "localhost" in the browser, it will load the /home/username/new_root_folder content.

Javascript Confirm popup Yes, No button instead of OK and Cancel

the very specific answer to the point is confirm dialogue Js Function:

confirm('Do you really want to do so');

It show dialogue box with ok cancel buttons,to replace these button with yes no is not so simple task,for that you need to write jQuery function.

Why is MySQL InnoDB insert so slow?

What's your innodb buffer-pool size? Make sure you've set it to 75% of your RAM. Usually inserts are better when in primary key order for InnoDB. But with a big pool-size, you should see good speeds.

How to resolve Nodejs: Error: ENOENT: no such file or directory

If there is no layout folder.Just use like this to your routing:

app.get('/', (req, res) => {
    res.render('something', { layout: false });
})

Here change something with your folder name and Hope it will fix your error.

psql: server closed the connection unexepectedly

this is an old post but...

just surprised that nobody talk about pg_hba file as it can be a good reason to get this error code.

Check here for those who forgot to configure it: http://www.postgresql.org/docs/current/static/auth-pg-hba-conf.html

MVC3 DropDownListFor - a simple example?

     @Html.DropDownListFor(m => m.SelectedValue,Your List,"ID","Values")

Here Value is that object of model where you want to save your Selected Value

What's the difference between ASCII and Unicode?

ASCII has 128 code positions, allocated to graphic characters and control characters (control codes).

Unicode has 1,114,112 code positions. About 100,000 of them have currently been allocated to characters, and many code points have been made permanently noncharacters (i.e. not used to encode any character ever), and most code points are not yet assigned.

The only things that ASCII and Unicode have in common are: 1) They are character codes. 2) The 128 first code positions of Unicode have been defined to have the same meanings as in ASCII, except that the code positions of ASCII control characters are just defined as denoting control characters, with names corresponding to their ASCII names, but their meanings are not defined in Unicode.

Sometimes, however, Unicode is characterized (even in the Unicode standard!) as “wide ASCII”. This is a slogan that mainly tries to convey the idea that Unicode is meant to be a universal character code the same way as ASCII once was (though the character repertoire of ASCII was hopelessly insufficient for universal use), as opposite to using different codes in different systems and applications and for different languages.

Unicode as such defines only the “logical size” of characters: Each character has a code number in a specific range. These code numbers can be presented using different transfer encodings, and internally, in memory, Unicode characters are usually represented using one or two 16-bit quantities per character, depending on character range, sometimes using one 32-bit quantity per character.

AngularJS sorting by property

I will add my upgraded version of filter which able to supports next syntax:

ng-repeat="(id, item) in $ctrl.modelData | orderObjectBy:'itemProperty.someOrder':'asc'

app.filter('orderObjectBy', function(){

         function byString(o, s) {
            s = s.replace(/\[(\w+)\]/g, '.$1'); // convert indexes to properties
            s = s.replace(/^\./, '');           // strip a leading dot
            var a = s.split('.');
            for (var i = 0, n = a.length; i < n; ++i) {
                var k = a[i];
                if (k in o) {
                    o = o[k];
                } else {
                    return;
                }
            }
            return o;
        }

        return function(input, attribute, direction) {
            if (!angular.isObject(input)) return input;

            var array = [];
            for(var objectKey in input) {
                if (input.hasOwnProperty(objectKey)) {
                    array.push(input[objectKey]);
                }
            }

            array.sort(function(a, b){
                a = parseInt(byString(a, attribute));
                b = parseInt(byString(b, attribute));
                return direction == 'asc' ? a - b : b - a;
            });
            return array;
        }
    })

Thanks to Armin and Jason for their answers in this thread, and Alnitak in this thread.

"pip install json" fails on Ubuntu

While it's true that json is a built-in module, I also found that on an Ubuntu system with python-minimal installed, you DO have python but you can't do import json. And then I understand that you would try to install the module using pip!

If you have python-minimal you'll get a version of python with less modules than when you'd typically compile python yourself, and one of the modules you'll be missing is the json module. The solution is to install an additional package, called libpython2.7-stdlib, to install all 'default' python libraries.

sudo apt install libpython2.7-stdlib

And then you can do import json in python and it would work!

What is the difference between old style and new style classes in Python?

Declaration-wise:

New-style classes inherit from object, or from another new-style class.

class NewStyleClass(object):
    pass

class AnotherNewStyleClass(NewStyleClass):
    pass

Old-style classes don't.

class OldStyleClass():
    pass

Python 3 Note:

Python 3 doesn't support old style classes, so either form noted above results in a new-style class.

smtp configuration for php mail

PHP's mail() function does not have support for SMTP. You're going to need to use something like the PEAR Mail package.

Here is a sample SMTP mail script:

<?php
require_once("Mail.php");

$from = "Your Name <[email protected]>";
$to = "Their Name <[email protected]>";
$subject = "Subject";
$body = "Lorem ipsum dolor sit amet, consectetur adipiscing elit...";

$host = "mailserver.blahblah.com";
$username = "smtp_username";
$password = "smtp_password";

$headers = array('From' => $from, 'To' => $to, 'Subject' => $subject);

$smtp = Mail::factory('smtp', array ('host' => $host,
                                     'auth' => true,
                                     'username' => $username,
                                     'password' => $password));

$mail = $smtp->send($to, $headers, $body);

if ( PEAR::isError($mail) ) {
    echo("<p>Error sending mail:<br/>" . $mail->getMessage() . "</p>");
} else {
    echo("<p>Message sent.</p>");
}
?>

How to JUnit test that two List<E> contain the same elements in the same order?

assertTrue()/assertFalse() : to use only to assert boolean result returned

assertTrue(Iterables.elementsEqual(argumentComponents, returnedComponents));

You want to use Assert.assertTrue() or Assert.assertFalse() as the method under test returns a boolean value.
As the method returns a specific thing such as a List that should contain some expected elements, asserting with assertTrue() in this way : Assert.assertTrue(myActualList.containsAll(myExpectedList) is an anti pattern.
It makes the assertion easy to write but as the test fails, it also makes it hard to debug because the test runner will only say to you something like :

expected true but actual is false

Assert.assertEquals(Object, Object) in JUnit4 or Assertions.assertIterableEquals(Iterable, Iterable) in JUnit 5 : to use only as both equals() and toString() are overrided for the classes (and deeply) of the compared objects

It matters because the equality test in the assertion relies on equals() and the test failure message relies on toString() of the compared objects.
As String overrides both equals() and toString(), it is perfectly valid to assert the List<String> with assertEquals(Object,Object). And about this matter : you have to override equals() in a class because it makes sense in terms of object equality, not only to make assertions easier in a test with JUnit.
To make assertions easier you have other ways (that you can see in the next points of the answer).

Is Guava a way to perform/build unit test assertions ?

Is Google Guava Iterables.elementsEqual() the best way, provided I have the library in my build path, to compare those two lists?

No it is not. Guava is not an library to write unit test assertions.
You don't need it to write most (all I think) of unit tests.

What's the canonical way to compare lists for unit tests?

As a good practice I favor assertion/matcher libraries.

I cannot encourage JUnit to perform specific assertions because this provides really too few and limited features : it performs only an assertion with a deep equals.
Sometimes you want to allow any order in the elements, sometimes you want to allow that any elements of the expected match with the actual, and so for...

So using a unit test assertion/matcher library such as Hamcrest or AssertJ is the correct way.
The actual answer provides a Hamcrest solution. Here is a AssertJ solution.

org.assertj.core.api.ListAssert.containsExactly() is what you need : it verifies that the actual group contains exactly the given values and nothing else, in order as stated :

Verifies that the actual group contains exactly the given values and nothing else, in order.

Your test could look like :

import org.assertj.core.api.Assertions;
import org.junit.jupiter.api.Test;

@Test
void ofComponent_AssertJ() throws Exception {
   MyObject myObject = MyObject.ofComponents("One", "Two", "Three");
   Assertions.assertThat(myObject.getComponents())
             .containsExactly("One", "Two", "Three");
}

A AssertJ good point is that declaring a List as expected is needless : it makes the assertion straighter and the code more readable :

Assertions.assertThat(myObject.getComponents())
         .containsExactly("One", "Two", "Three");

And if the test fails :

// Fail : Three was not expected 
Assertions.assertThat(myObject.getComponents())
          .containsExactly("One", "Two");

you get a very clear message such as :

java.lang.AssertionError:

Expecting:

<["One", "Two", "Three"]>

to contain exactly (and in same order):

<["One", "Two"]>

but some elements were not expected:

<["Three"]>

Assertion/matcher libraries are a must because these will really further

Suppose that MyObject doesn't store Strings but Foos instances such as :

public class MyFooObject {

    private List<Foo> values;
    @SafeVarargs
    public static MyFooObject ofComponents(Foo... values) {
        // ...
    }

    public List<Foo> getComponents(){
        return new ArrayList<>(values);
    }
}

That is a very common need. With AssertJ the assertion is still simple to write. Better you can assert that the list content are equal even if the class of the elements doesn't override equals()/hashCode() while JUnit ways require that :

import org.assertj.core.api.Assertions;
import static org.assertj.core.groups.Tuple.tuple;
import org.junit.jupiter.api.Test;

@Test
void ofComponent() throws Exception {
    MyFooObject myObject = MyFooObject.ofComponents(new Foo(1, "One"), new Foo(2, "Two"), new Foo(3, "Three"));

    Assertions.assertThat(myObject.getComponents())
              .extracting(Foo::getId, Foo::getName)
              .containsExactly(tuple(1, "One"),
                               tuple(2, "Two"),
                               tuple(3, "Three"));
}

Bootstrap 4 dropdown with search

As of 10. July 2017, the issue of Bootstrap 4 support with bootstrap-select is still open. In the open issue, there are some ad-hoc solutions which you could try with your project.

Or you could use a library like Select2 and add a theme to match Bootstrap 4. Here is an example: Select 2 with Bootstrap 4 (disclaimer: I'm not the author of this blog post and I haven't verified if this still works with the all versions of Bootstrap 4).

Why do I get a C malloc assertion failure?

We got this error because we forgot to multiply by sizeof(int). Note the argument to malloc(..) is a number of bytes, not number of machine words or whatever.

Maven: How to run a .java file from command line passing arguments

In addition to running it with mvn exec:java, you can also run it with mvn exec:exec

mvn exec:exec -Dexec.executable="java" -Dexec.args="-classpath %classpath your.package.MainClass"

Get current scroll position of ScrollView in React Native

This is how ended up getting the current scroll position live from the view. All I am doing is using the on scroll event listener and the scrollEventThrottle. I am then passing it as an event to handle scroll function I made and updating my props.

 export default class Anim extends React.Component {
          constructor(props) {
             super(props);
             this.state = {
               yPos: 0,
             };
           }

        handleScroll(event){
            this.setState({
              yPos : event.nativeEvent.contentOffset.y,
            })
        }

        render() {
            return (
          <ScrollView onScroll={this.handleScroll.bind(this)} scrollEventThrottle={16} />
    )
    }
    }

How to generate a range of numbers between two numbers?

recursive CTE in exponential size (even for default of 100 recursion, this can build up to 2^100 numbers):

DECLARE @startnum INT=1000
DECLARE @endnum INT=1050
DECLARE @size INT=@endnum-@startnum+1
;
WITH numrange (num) AS (
    SELECT 1 AS num
    UNION ALL
    SELECT num*2 FROM numrange WHERE num*2<=@size
    UNION ALL
    SELECT num*2+1 FROM numrange WHERE num*2+1<=@size
)
SELECT num+@startnum-1 FROM numrange order by num

Why can't I check if a 'DateTime' is 'Nothing'?

DateTime is a value type, which means it always has some value.

It's like an integer - it can be 0, or 1, or less than zero, but it can never be "nothing".

If you want a DateTime that can take the value Nothing, use a Nullable DateTime.

TSQL select into Temp table from dynamic sql

DECLARE @count_ser_temp int;
DECLARE @TableName AS VARCHAR(100)
SELECT @TableName = 'TableTemporal'

EXECUTE ('CREATE VIEW vTemp AS
    SELECT *
    FROM ' + @TableTemporal)
SELECT TOP 1 * INTO #servicios_temp  FROM vTemp

DROP VIEW vTemp

-- Contar la cantidad de registros de la tabla temporal
SELECT @count_ser_temp = COUNT(*) FROM #servicios_temp;

-- Recorro los registros de la tabla temporal 
WHILE @count_ser_temp > 0
 BEGIN
 END
END

Convert python long/int to fixed size byte array

long/int to the byte array looks like exact purpose of struct.pack. For long integers that exceed 4(8) bytes, you can come up with something like the next:

>>> limit = 256*256*256*256 - 1
>>> i = 1234567890987654321
>>> parts = []
>>> while i:
        parts.append(i & limit)
        i >>= 32

>>> struct.pack('>' + 'L'*len(parts), *parts )
'\xb1l\x1c\xb1\x11"\x10\xf4'

>>> struct.unpack('>LL', '\xb1l\x1c\xb1\x11"\x10\xf4')
(2976652465L, 287445236)
>>> (287445236L << 32) + 2976652465L
1234567890987654321L

JS: Uncaught TypeError: object is not a function (onclick)

Please change only the name of the function; no other change is required

<script>
    function totalbandwidthresult() {
        alert("fdf");
        var fps = Number(document.calculator.fps.value);
        var bitrate = Number(document.calculator.bitrate.value);
        var numberofcameras = Number(document.calculator.numberofcameras.value);
        var encoding = document.calculator.encoding.value;
        if (encoding = "mjpeg") {
            storage = bitrate * fps;
        } else {
            storage = bitrate;
        }

        totalbandwidth = (numberofcameras * storage) / 1000;
        alert(totalbandwidth);
        document.calculator.totalbandwidthresult.value = totalbandwidth;
    }
</script>

<form name="calculator" class="formtable">
    <div class="formrow">
        <label for="rcname">RC Name</label>
        <input type="text" name="rcname">
    </div>
    <div class="formrow">
        <label for="fps">FPS</label>
        <input type="text" name="fps">
    </div>
    <div class="formrow">
        <label for="bitrate">Bitrate</label>
        <input type="text" name="bitrate">
    </div>
    <div class="formrow">
        <label for="numberofcameras">Number of Cameras</label>
        <input type="text" name="numberofcameras">
    </div>
    <div class="formrow">
        <label for="encoding">Encoding</label>
        <select name="encoding" id="encodingoptions">
            <option value="h264">H.264</option>
            <option value="mjpeg">MJPEG</option>
            <option value="mpeg4">MPEG4</option>
        </select>
    </div>Total Storage:
    <input type="text" name="totalstorage">Total Bandwidth:
    <input type="text" name="totalbandwidth">
    <input type="button" value="totalbandwidthresult" onclick="totalbandwidthresult();">
</form>

The SQL OVER() clause - when and why is it useful?

So in simple words: Over clause can be used to select non aggregated values along with Aggregated ones.

Partition BY, ORDER BY inside, and ROWS or RANGE are part of OVER() by clause.

partition by is used to partition data and then perform these window, aggregated functions, and if we don't have partition by the then entire result set is considered as a single partition.

OVER clause can be used with Ranking Functions(Rank, Row_Number, Dense_Rank..), Aggregate Functions like (AVG, Max, Min, SUM...etc) and Analytics Functions like (First_Value, Last_Value, and few others).

Let's See basic syntax of OVER clause

OVER (   
       [ <PARTITION BY clause> ]  
       [ <ORDER BY clause> ]   
       [ <ROW or RANGE clause> ]  
      )  

PARTITION BY: It is used to partition data and perform operations on groups with the same data.

ORDER BY: It is used to define the logical order of data in Partitions. When we don't specify Partition, entire resultset is considered as a single partition

: This can be used to specify what rows are supposed to be considered in a partition when performing the operation.

Let's take an example:

Here is my dataset:

Id          Name                                               Gender     Salary
----------- -------------------------------------------------- ---------- -----------
1           Mark                                               Male       5000
2           John                                               Male       4500
3           Pavan                                              Male       5000
4           Pam                                                Female     5500
5           Sara                                               Female     4000
6           Aradhya                                            Female     3500
7           Tom                                                Male       5500
8           Mary                                               Female     5000
9           Ben                                                Male       6500
10          Jodi                                               Female     7000
11          Tom                                                Male       5500
12          Ron                                                Male       5000

So let me execute different scenarios and see how data is impacted and I'll come from difficult syntax to simple one

Select *,SUM(salary) Over(order by salary RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) as sum_sal from employees

Id          Name                                               Gender     Salary      sum_sal
----------- -------------------------------------------------- ---------- ----------- -----------
6           Aradhya                                            Female     3500        3500
5           Sara                                               Female     4000        7500
2           John                                               Male       4500        12000
3           Pavan                                              Male       5000        32000
1           Mark                                               Male       5000        32000
8           Mary                                               Female     5000        32000
12          Ron                                                Male       5000        32000
11          Tom                                                Male       5500        48500
7           Tom                                                Male       5500        48500
4           Pam                                                Female     5500        48500
9           Ben                                                Male       6500        55000
10          Jodi                                               Female     7000        62000

Just observe the sum_sal part. Here I am using order by Salary and using "RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW". In this case, we are not using partition so entire data will be treated as one partition and we are ordering on salary. And the important thing here is UNBOUNDED PRECEDING AND CURRENT ROW. This means when we are calculating the sum, from starting row to the current row for each row. But if we see rows with salary 5000 and name="Pavan", ideally it should be 17000 and for salary=5000 and name=Mark, it should be 22000. But as we are using RANGE and in this case, if it finds any similar elements then it considers them as the same logical group and performs an operation on them and assigns value to each item in that group. That is the reason why we have the same value for salary=5000. The engine went up to salary=5000 and Name=Ron and calculated sum and then assigned it to all salary=5000.

Select *,SUM(salary) Over(order by salary ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) as sum_sal from employees


   Id          Name                                               Gender     Salary      sum_sal
----------- -------------------------------------------------- ---------- ----------- -----------
6           Aradhya                                            Female     3500        3500
5           Sara                                               Female     4000        7500
2           John                                               Male       4500        12000
3           Pavan                                              Male       5000        17000
1           Mark                                               Male       5000        22000
8           Mary                                               Female     5000        27000
12          Ron                                                Male       5000        32000
11          Tom                                                Male       5500        37500
7           Tom                                                Male       5500        43000
4           Pam                                                Female     5500        48500
9           Ben                                                Male       6500        55000
10          Jodi                                               Female     7000        62000

So with ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW The difference is for same value items instead of grouping them together, It calculates SUM from starting row to current row and it doesn't treat items with same value differently like RANGE

Select *,SUM(salary) Over(order by salary) as sum_sal from employees

Id          Name                                               Gender     Salary      sum_sal
----------- -------------------------------------------------- ---------- ----------- -----------
6           Aradhya                                            Female     3500        3500
5           Sara                                               Female     4000        7500
2           John                                               Male       4500        12000
3           Pavan                                              Male       5000        32000
1           Mark                                               Male       5000        32000
8           Mary                                               Female     5000        32000
12          Ron                                                Male       5000        32000
11          Tom                                                Male       5500        48500
7           Tom                                                Male       5500        48500
4           Pam                                                Female     5500        48500
9           Ben                                                Male       6500        55000
10          Jodi                                               Female     7000        62000

These results are the same as

Select *, SUM(salary) Over(order by salary RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) as sum_sal from employees

That is because Over(order by salary) is just a short cut of Over(order by salary RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) So wherever we simply specify Order by without ROWS or RANGE it is taking RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW as default.

Note: This is applicable only to Functions that actually accept RANGE/ROW. For example, ROW_NUMBER and few others don't accept RANGE/ROW and in that case, this doesn't come into the picture.

Till now we saw that Over clause with an order by is taking Range/ROWS and syntax looks something like this RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW And it is actually calculating up to the current row from the first row. But what If it wants to calculate values for the entire partition of data and have it for each column (that is from 1st row to last row). Here is the query for that

Select *,sum(salary) Over(order by salary ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) as sum_sal from employees

Id          Name                                               Gender     Salary      sum_sal
----------- -------------------------------------------------- ---------- ----------- -----------
1           Mark                                               Male       5000        62000
2           John                                               Male       4500        62000
3           Pavan                                              Male       5000        62000
4           Pam                                                Female     5500        62000
5           Sara                                               Female     4000        62000
6           Aradhya                                            Female     3500        62000
7           Tom                                                Male       5500        62000
8           Mary                                               Female     5000        62000
9           Ben                                                Male       6500        62000
10          Jodi                                               Female     7000        62000
11          Tom                                                Male       5500        62000
12          Ron                                                Male       5000        62000

Instead of CURRENT ROW, I am specifying UNBOUNDED FOLLOWING which instructs the engine to calculate till the last record of partition for each row.

Now coming to your point on what is OVER() with empty braces?

It is just a short cut for Over(order by salary ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING)

Here we are indirectly specifying to treat all my resultset as a single partition and then perform calculations from the first record to the last record of each partition.

Select *,Sum(salary) Over() as sum_sal from employees

Id          Name                                               Gender     Salary      sum_sal
----------- -------------------------------------------------- ---------- ----------- -----------
1           Mark                                               Male       5000        62000
2           John                                               Male       4500        62000
3           Pavan                                              Male       5000        62000
4           Pam                                                Female     5500        62000
5           Sara                                               Female     4000        62000
6           Aradhya                                            Female     3500        62000
7           Tom                                                Male       5500        62000
8           Mary                                               Female     5000        62000
9           Ben                                                Male       6500        62000
10          Jodi                                               Female     7000        62000
11          Tom                                                Male       5500        62000
12          Ron                                                Male       5000        62000

I did create a video on this and if you are interested you can visit it. https://www.youtube.com/watch?v=CvVenuVUqto&t=1177s

Thanks, Pavan Kumar Aryasomayajulu HTTP://xyzcoder.github.io

How to globally replace a forward slash in a JavaScript string?

The following would do but only will replace one occurence:

"string".replace('/', 'ForwardSlash');

For a global replacement, or if you prefer regular expressions, you just have to escape the slash:

"string".replace(/\//g, 'ForwardSlash');

How do I read all classes from a Java package in the classpath?

Java 1.6.0_24:

public static File[] getPackageContent(String packageName) throws IOException{
    ArrayList<File> list = new ArrayList<File>();
    Enumeration<URL> urls = Thread.currentThread().getContextClassLoader()
                            .getResources(packageName);
    while (urls.hasMoreElements()) {
        URL url = urls.nextElement();
        File dir = new File(url.getFile());
        for (File f : dir.listFiles()) {
            list.add(f);
        }
    }
    return list.toArray(new File[]{});
}

This solution was tested within the EJB environment.

Merging Cells in Excel using C#

Code Snippet

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private Excel.Application excelApp = null;
    private void button1_Click(object sender, EventArgs e)
    {
        excelApp.get_Range("A1:A360,B1:E1", Type.Missing).Merge(Type.Missing);
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        excelApp = Marshal.GetActiveObject("Excel.Application") as Excel.Application ;
    }
}

Thanks

How to condense if/else into one line in Python?

Only for using as a value:

x = 3 if a==2 else 0

or

return 3 if a==2 else 0

Change the Bootstrap Modal effect

I copied model code from w3school bootstrap model and added following css. This code provides beautiful animation. You can try it.

.modal.fade .modal-dialog {
     -webkit-transform: scale(0.1);
     -moz-transform: scale(0.1);
     -ms-transform: scale(0.1);
     transform: scale(0.1);
     top: 300px;
     opacity: 0;
     -webkit-transition: all 0.3s;
     -moz-transition: all 0.3s;
     transition: all 0.3s;
}

.modal.fade.in .modal-dialog {
    -webkit-transform: scale(1);
    -moz-transform: scale(1);
    -ms-transform: scale(1);
    transform: scale(1);
    -webkit-transform: translate3d(0, -300px, 0);
    transform: translate3d(0, -300px, 0);
    opacity: 1;
}

AJAX in Chrome sending OPTIONS instead of GET/POST/PUT/DELETE?

I've encountered a very similar issue. I spent almost half a day to understand why everything works correctly in Firefox and fails in Chrome. In my case it was because of duplicated (or maybe mistyped) fields in my request header.

When is assembly faster than C?

Longpoke, there is just one limitation: time. When you don't have the resources to optimize every single change to code and spend your time allocating registers, optimize few spills away and what not, the compiler will win every single time. You do your modification to the code, recompile and measure. Repeat if necessary.

Also, you can do a lot in the high-level side. Also, inspecting the resulting assembly may give the IMPRESSION that the code is crap, but in practice it will run faster than what you think would be quicker. Example:

int y = data[i]; // do some stuff here.. call_function(y, ...);

The compiler will read the data, push it to stack (spill) and later read from stack and pass as argument. Sounds shite? It might actually be very effective latency compensation and result in faster runtime.

// optimized version call_function(data[i], ...); // not so optimized after all..

The idea with the optimized version was, that we have reduced register pressure and avoid spilling. But in truth, the "shitty" version was faster!

Looking at the assembly code, just looking at the instructions and concluding: more instructions, slower, would be a misjudgment.

The thing here to pay attention is: many assembly experts think they know a lot, but know very little. The rules change from architecture to next, too. There is no silver-bullet x86 code, for example, which is always the fastest. These days is better to go by rules-of-thumb:

  • memory is slow
  • cache is fast
  • try to use cached better
  • how often you going to miss? do you have latency compensation strategy?
  • you can execute 10-100 ALU/FPU/SSE instructions for one single cache miss
  • application architecture is important..
  • .. but it does't help when the problem isn't in the architecture

Also, trusting too much into compiler magically transforming poorly-thought-out C/C++ code into "theoretically optimum" code is wishful thinking. You have to know the compiler and tool chain you use if you care about "performance" at this low-level.

Compilers in C/C++ are generally not very good at re-ordering sub-expressions because the functions have side effects, for starters. Functional languages don't suffer from this caveat but don't fit the current ecosystem that well. There are compiler options to allow relaxed precision rules which allow order of operations to be changed by the compiler/linker/code generator.

This topic is a bit of a dead-end; for most it's not relevant, and the rest, they know what they are doing already anyway.

It all boils down to this: "to understand what you are doing", it's a bit different from knowing what you are doing.

Configuring Hibernate logging using Log4j XML config file?

Here's what I use:

<logger name="org.hibernate">
    <level value="warn"/>
</logger>

<logger name="org.hibernate.SQL">
    <level value="warn"/>
</logger>

<logger name="org.hibernate.type">
    <level value="warn"/>
</logger>

<root>
    <priority value="info"/>
    <appender-ref ref="C1"/>
</root> 

Obviously, I don't like to see Hibernate messages ;) -- set the level to "debug" to get the output.

How do I execute cmd commands through a batch file?

I think the correct syntax is:

cmd /k "cd c:\<folder name>"

Attach Authorization header for all axios requests

The best solution to me is to create a client service that you'll instantiate with your token an use it to wrap axios.

import axios from 'axios';

const client = (token = null) => {
    const defaultOptions = {
        headers: {
            Authorization: token ? `Token ${token}` : '',
        },
    };

    return {
        get: (url, options = {}) => axios.get(url, { ...defaultOptions, ...options }),
        post: (url, data, options = {}) => axios.post(url, data, { ...defaultOptions, ...options }),
        put: (url, data, options = {}) => axios.put(url, data, { ...defaultOptions, ...options }),
        delete: (url, options = {}) => axios.delete(url, { ...defaultOptions, ...options }),
    };
};

const request = client('MY SECRET TOKEN');

request.get(PAGES_URL);

In this client, you can also retrieve the token from the localStorage / cookie, as you want.

Best way to do a PHP switch with multiple values per case?

For the sake of completeness, I'll point out that the broken "Version 2" logic can be replaced with a switch statement that works, and also make use of arrays for both speed and clarity, like so:

// used for $current_home = 'current';
$home_group = array(
    'home'  => True,
);

// used for $current_users = 'current';
$user_group = array(
    'users.online'      => True,
    'users.location'    => True,
    'users.featured'    => True,
    'users.new'         => True,
    'users.browse'      => True,
    'users.search'      => True,
    'users.staff'       => True,
);

// used for $current_forum = 'current';
$forum_group = array(
    'forum'     => True,
);

switch (true) {
    case isset($home_group[$p]):
        $current_home = 'current';
        break;
    case isset($user_group[$p]):
        $current_users = 'current';
        break;
    case isset($forum_group[$p]):
        $current_forum = 'current';
        break;
    default:
        user_error("\$p is invalid", E_USER_ERROR);
}    

Read environment variables in Node.js

If you want to use a string key generated in your Node.js program, say, var v = 'HOME', you can use process.env[v].

Otherwise, process.env.VARNAME has to be hardcoded in your program.

Simplest two-way encryption using PHP

IMPORTANT this answer is valid only for PHP 5, in PHP 7 use built-in cryptographic functions.

Here is simple but secure enough implementation:

  • AES-256 encryption in CBC mode
  • PBKDF2 to create encryption key out of plain-text password
  • HMAC to authenticate the encrypted message.

Code and examples are here: https://stackoverflow.com/a/19445173/1387163

Swift how to sort array of custom objects by property value

First, declare your Array as a typed array so that you can call methods when you iterate:

var images : [imageFile] = []

Then you can simply do:

Swift 2

images.sorted({ $0.fileID > $1.fileID })

Swift 3+

images.sorted(by: { $0.fileID > $1.fileID })

The example above gives desc sort order

SQL Server "cannot perform an aggregate function on an expression containing an aggregate or a subquery", but Sybase can

One option is to put the subquery in a LEFT JOIN:

select sum ( t.graduates ) - t1.summedGraduates 
from table as t
    left join 
     ( 
        select sum ( graduates ) summedGraduates, id
        from table  
        where group_code not in ('total', 'others' )
        group by id 
    ) t1 on t.id = t1.id
where t.group_code = 'total'
group by t1.summedGraduates 

Perhaps a better option would be to use SUM with CASE:

select sum(case when group_code = 'total' then graduates end) -
    sum(case when group_code not in ('total','others') then graduates end)
from yourtable

SQL Fiddle Demo with both

iPhone 6 and 6 Plus Media Queries

iPhone X

/* Portrait and Landscape */
@media only screen 
  and (min-device-width: 375px) 
  and (max-device-width: 812px) 
  and (-webkit-min-device-pixel-ratio: 3)
  /* uncomment for only portrait: */
  /* and (orientation: portrait) */
  /* uncomment for only landscape: */
  /* and (orientation: landscape) */ { 

}

iPhone 6+, 7+ and 8+

/* Portrait and Landscape */
@media only screen 
  and (min-device-width: 414px) 
  and (max-device-width: 736px) 
  and (-webkit-min-device-pixel-ratio: 3)
  /* uncomment for only portrait: */
  /* and (orientation: portrait) */
  /* uncomment for only landscape: */
  /* and (orientation: landscape) */ { 

}

iPhone 6, 6S, 7 and 8

/* Portrait and Landscape */
@media only screen 
  and (min-device-width: 375px) 
  and (max-device-width: 667px) 
  and (-webkit-min-device-pixel-ratio: 2)
  /* uncomment for only portrait: */
  /* and (orientation: portrait) */
  /* uncomment for only landscape: */
  /* and (orientation: landscape) */ { 

}

Source: Media Queries for Standard Devices

sorting a List of Map<String, String>

Not really an answer to your question but I had a requirement to sort a List of maps by its values' properties, this will work in your case too:

List<Map<String, Object>> sortedListOfMaps = someListOfMaps.sorted(Comparator.comparing(map -> ((String) map.get("someKey")))).collect(Collectors.toList()))

Advantages of std::for_each over for loop

The nice thing with C++11 (previously called C++0x), is that this tiresome debate will be settled.

I mean, no one in their right mind, who wants to iterate over a whole collection, will still use this

for(auto it = collection.begin(); it != collection.end() ; ++it)
{
   foo(*it);
}

Or this

for_each(collection.begin(), collection.end(), [](Element& e)
{
   foo(e);
});

when the range-based for loop syntax is available:

for(Element& e : collection)
{
   foo(e);
}

This kind of syntax has been available in Java and C# for some time now, and actually there are way more foreach loops than classical for loops in every recent Java or C# code I saw.

Program "make" not found in PATH

You may try altering toolchain in case if for some reason you can't use gcc. Open Properties for your project (by right clicking on your project name in the Project Explorer), then C/C++ Build > Tool Chain Editor. You can change the current builder there from GNU Make Builder to CDT Internal Builder or whatever compatible you have.

Find object by its property in array of objects with AngularJS way

How about plain JavaScript? More about Array.prototype.filter().

_x000D_
_x000D_
var myArray = [{'id': '73', 'name': 'john'}, {'id': '45', 'name': 'Jass'}]_x000D_
_x000D_
var item73 = myArray.filter(function(item) {_x000D_
  return item.id === '73';_x000D_
})[0];_x000D_
_x000D_
// even nicer with ES6 arrow functions:_x000D_
// var item73 = myArray.filter(i => i.id === '73')[0];_x000D_
_x000D_
console.log(item73); // {"id": "73", "name": "john"}
_x000D_
_x000D_
_x000D_

how to solve Error cannot add duplicate collection entry of type add with unique key attribute 'value' in iis 7

Remove element should clear out such errors. The reason behind this is the inherited settings. Your application will inherit some settings from its parent's config file and machine's (server) config files.
You can either remove such duplicates with the remove tag before adding them or make these tags non-inheritable in the upper level config files.

PHP array: count or sizeof?

According to the website, sizeof() is an alias of count(), so they should be running the same code. Perhaps sizeof() has a little bit of overhead because it needs to resolve it to count()? It should be very minimal though.

When to use which design pattern?

Usually the process is the other way around. Do not go looking for situations where to use design patterns, look for code that can be optimized. When you have code that you think is not structured correctly. try to find a design pattern that will solve the problem.

Design patterns are meant to help you solve structural problems, do not go design your application just to be able to use design patterns.

What do two question marks together mean in C#?

The ?? operator is called the null-coalescing operator. It returns the left-hand operand if the operand is not null; otherwise it returns the right hand operand.

int? variable1 = null;
int variable2  = variable1 ?? 100;

Set variable2 to the value of variable1, if variable1 is NOT null; otherwise, if variable1 == null, set variable2 to 100.

A weighted version of random.choice

If you don't mind using numpy, you can use numpy.random.choice.

For example:

import numpy

items  = [["item1", 0.2], ["item2", 0.3], ["item3", 0.45], ["item4", 0.05]
elems = [i[0] for i in items]
probs = [i[1] for i in items]

trials = 1000
results = [0] * len(items)
for i in range(trials):
    res = numpy.random.choice(items, p=probs)  #This is where the item is selected!
    results[items.index(res)] += 1
results = [r / float(trials) for r in results]
print "item\texpected\tactual"
for i in range(len(probs)):
    print "%s\t%0.4f\t%0.4f" % (items[i], probs[i], results[i])

If you know how many selections you need to make in advance, you can do it without a loop like this:

numpy.random.choice(items, trials, p=probs)

How do you make div elements display inline?

I just tend to make them fixed widths so that they add up to the total width of the page - probably only works if you are using a fixed width page. Also "float".

How to round up a number to nearest 10?

to nearest 10 , should be as below

$number = ceil($input * 0.1)/0.1 ;

Python: Writing to and Reading from serial port

ser.read(64) should be ser.read(size=64); ser.read uses keyword arguments, not positional.

Also, you're reading from the port twice; what you probably want to do is this:

i=0
for modem in PortList:
    for port in modem:
        try:
            ser = serial.Serial(port, 9600, timeout=1)
            ser.close()
            ser.open()
            ser.write("ati")
            time.sleep(3)
            read_val = ser.read(size=64)
            print read_val
            if read_val is not '':
                print port
        except serial.SerialException:
            continue
        i+=1

Ruby on Rails: Clear a cached page

I was able to resolve this problem by cleaning my assets cache:

$ rake assets:clean

How to get current time and date in Android

tl;dr

Instant.now()  // Current moment in UTC.

…or…

ZonedDateTime.now( ZoneId.of( "America/Montreal" ) )  // In a particular time zone

Details

The other Answers, while correct, are outdated. The old date-time classes have proven to be poorly designed, confusing, and troublesome.

java.time

Those old classes have been supplanted by the java.time framework.

These new classes are inspired by the highly successful Joda-Time project, defined by JSR 310, and extended by the ThreeTen-Extra project.

See the Oracle Tutorial.

Instant

An Instant is a moment on the timeline in UTC with resolution up to nanoseconds.

 Instant instant = Instant.now(); // Current moment in UTC.

Time Zone

Apply a time zone (ZoneId) to get a ZonedDateTime. If you omit the time zone your JVM’s current default time zone is implicitly applied. Better to specify explicitly the desired/expected time zone.

Use proper time zone names in the format of continent/region such as America/Montreal, Europe/Brussels, or Asia/Kolkata. Never use the 3-4 letter abbreviations such as EST or IST as they are neither standardized nor unique.

ZoneId zoneId = ZoneId.of( "America/Montreal" ); // Or "Asia/Kolkata", "Europe/Paris", and so on.
ZonedDateTime zdt = ZonedDateTime.ofInstant( instant , zoneId );

Table of date-time types in Java, both modern and legacy

Generating Strings

You can easily generate a String as a textual representation of the date-time value. You can go with a standard format, your own custom format, or an automatically localized format.

ISO 8601

You can call the toString methods to get text formatted using the common and sensible ISO 8601 standard.

String output = instant.toString();

2016-03-23T03:09:01.613Z

Note that for ZonedDateTime, the toString method extends the ISO 8601 standard by appending the name of the time zone in square brackets. Extremely useful and important information, but not standard.

2016-03-22T20:09:01.613-08:00[America/Los_Angeles]

Custom format

Or specify your own particular formatting pattern with the DateTimeFormatter class.

DateTimeFormatter formatter = DateTimeFormatter.ofPattern( "dd/MM/yyyy hh:mm a" );

Specify a Locale for a human language (English, French, etc.) to use in translating the name of day/month and also in defining cultural norms such as the order of year and month and date. Note that Locale has nothing to do with time zone.

formatter = formatter.withLocale( Locale.US ); // Or Locale.CANADA_FRENCH or such.
String output = zdt.format( formatter );

Localizing

Better yet, let java.time do the work of localizing automatically.

DateTimeFormatter formatter = DateTimeFormatter.ofLocalizedDateTime( FormatStyle.MEDIUM );
String output = zdt.format( formatter.withLocale( Locale.US ) );  // Or Locale.CANADA_FRENCH and so on.

About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.

Where to obtain the java.time classes?

Table listing which implementation of the *java.time* technology to use on which versions of Java and Android.

Get first line of a shell command's output

Yes, that is one way to get the first line of output from a command.

If the command outputs anything to standard error that you would like to capture in the same manner, you need to redirect the standard error of the command to the standard output stream:

utility 2>&1 | head -n 1

There are many other ways to capture the first line too, including sed 1q (quit after first line), sed -n 1p (only print first line, but read everything), awk 'FNR == 1' (only print first line, but again, read everything) etc.

Single TextView with multiple colored text

Awesome answers! I was able to use Spannable to build rainbow colored text (so this could be repeated for any array of colors). Here's my method, if it helps anyone:

private Spannable buildRainbowText(String pack_name) {
        int[] colors = new int[]{Color.RED, 0xFFFF9933, Color.YELLOW, Color.GREEN, Color.BLUE, Color.RED, 0xFFFF9933, Color.YELLOW, Color.GREEN, Color.BLUE, Color.RED, 0xFFFF9933, Color.YELLOW, Color.GREEN, Color.BLUE, Color.RED, 0xFFFF9933, Color.YELLOW, Color.GREEN, Color.BLUE};
        Spannable word = new SpannableString(pack_name);
        for(int i = 0; i < word.length(); i++) {
            word.setSpan(new ForegroundColorSpan(colors[i]), i, i+1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        }
        return word;
    }

And then I just setText(buildRainboxText(pack_name)); Note that all of the words I pass in are under 15 characters and this just repeats 5 colors 3 times - you'd want to adjust the colors/length of the array for your usage!

Trigger function when date is selected with jQuery UI datepicker

Working demo : http://jsfiddle.net/YbLnj/

Documentation: http://jqueryui.com/demos/datepicker/

code

$("#dt").datepicker({
    onSelect: function(dateText, inst) {
        var date = $(this).val();
        var time = $('#time').val();
        alert('on select triggered');
        $("#start").val(date + time.toString(' HH:mm').toString());

    }
});

Passing multiple variables in @RequestBody to a Spring MVC controller using Ajax

Good. I suggest creating a Value Object (Vo) that contains the fields you need. The code is simpler, we do not change the functioning of Jackson and it is even easier to understand. Regards!

How can I override Bootstrap CSS styles?

It should not effect the load time much since you are overriding parts of the base stylesheet.

Here are some best practices I personally follow:

  1. Always load custom CSS after the base CSS file (not responsive).
  2. Avoid using !important if possible. That can override some important styles from the base CSS files.
  3. Always load bootstrap-responsive.css after custom.css if you don't want to lose media queries. - MUST FOLLOW
  4. Prefer modifying required properties (not all).

How to convert int to QString?

And if you want to put it into string within some text context, forget about + operator. Simply do:

// Qt 5 + C++11
auto i = 13;    
auto printable = QStringLiteral("My magic number is %1. That's all!").arg(i);

// Qt 5
int i = 13;    
QString printable = QStringLiteral("My magic number is %1. That's all!").arg(i);

// Qt 4
int i = 13;    
QString printable = QString::fromLatin1("My magic number is %1. That's all!").arg(i);

How to read a line from a text file in c/c++?

im not really that good at C , but i believe this code should get you complete single line till the end...

 #include<stdio.h>

 int main()   
{      
  char line[1024];    
  FILE *f=fopen("filename.txt","r");    
  fscanf(*f,"%[^\n]",line);    
  printf("%s",line);    
 }    

"[notice] child pid XXXX exit signal Segmentation fault (11)" in apache error.log

A segementation fault is an internal error in php (or, less likely, apache). Oftentimes, the segmentation fault is caused by one of the newer and lesser-tested php modules such as imagemagick or subversion.

Try disabling all non-essential modules (in php.ini), and then re-enabling them one-by-one until the error occurs. You may also want to update php and apache.

If that doesn't help, you should report a php bug.

Sending emails with Javascript

If this is just going to open up the user's client to send the email, why not let them compose it there as well. You lose the ability to track what they are sending, but if that's not important, then just collect the addresses and subject and pop up the client to let the user fill in the body.

What is the difference between == and equals() in Java?

The difference between == and equals confused me for sometime until I decided to have a closer look at it. Many of them say that for comparing string you should use equals and not ==. Hope in this answer I will be able to say the difference.

The best way to answer this question will be by asking a few questions to yourself. so let's start:

What is the output for the below program:

String mango = "mango";
String mango2 = "mango";
System.out.println(mango != mango2);
System.out.println(mango == mango2);

if you say,

false
true

I will say you are right but why did you say that? and If you say the output is,

true
false

I will say you are wrong but I will still ask you, why you think that is right?

Ok, Let's try to answer this one:

What is the output for the below program:

String mango = "mango";
String mango3 = new String("mango");
System.out.println(mango != mango3);
System.out.println(mango == mango3);

Now If you say,

false
true

I will say you are wrong but why is it wrong now? the correct output for this program is

true
false

Please compare the above program and try to think about it.

Ok. Now this might help (please read this : print the address of object - not possible but still we can use it.)

String mango = "mango";
String mango2 = "mango";
String mango3 = new String("mango");
System.out.println(mango != mango2);
System.out.println(mango == mango2);
System.out.println(mango3 != mango2);
System.out.println(mango3 == mango2);
// mango2 = "mang";
System.out.println(mango+" "+ mango2);
System.out.println(mango != mango2);
System.out.println(mango == mango2);

System.out.println(System.identityHashCode(mango));
System.out.println(System.identityHashCode(mango2));
System.out.println(System.identityHashCode(mango3));

can you just try to think about the output of the last three lines in the code above: for me ideone printed this out (you can check the code here):

false
true
true
false
mango mango
false
true
17225372
17225372
5433634

Oh! Now you see the identityHashCode(mango) is equal to identityHashCode(mango2) But it is not equal to identityHashCode(mango3)

Even though all the string variables - mango, mango2 and mango3 - have the same value, which is "mango", identityHashCode() is still not the same for all.

Now try to uncomment this line // mango2 = "mang"; and run it again this time you will see all three identityHashCode() are different. Hmm that is a helpful hint

we know that if hashcode(x)=N and hashcode(y)=N => x is equal to y

I am not sure how java works internally but I assume this is what happened when I said:

mango = "mango";

java created a string "mango" which was pointed(referenced) by the variable mango something like this

mango ----> "mango"

Now in the next line when I said:

mango2 = "mango";

It actually reused the same string "mango" which looks something like this

mango ----> "mango" <---- mango2

Both mango and mango2 pointing to the same reference Now when I said

mango3 = new String("mango")

It actually created a completely new reference(string) for "mango". which looks something like this,

mango -----> "mango" <------ mango2

mango3 ------> "mango"

and that's why when I put out the values for mango == mango2, it put out true. and when I put out the value for mango3 == mango2, it put out false (even when the values were the same).

and when you uncommented the line // mango2 = "mang"; It actually created a string "mang" which turned our graph like this:

mango ---->"mango"
mango2 ----> "mang"
mango3 -----> "mango"

This is why the identityHashCode is not the same for all.

Hope this helps you guys. Actually, I wanted to generate a test case where == fails and equals() pass. Please feel free to comment and let me know If I am wrong.

loading json data from local file into React JS

My JSON file name: terrifcalculatordata.json

[
    {
      "id": 1,
      "name": "Vigo",
      "picture": "./static/images/vigo.png",
      "charges": "PKR 100 per excess km"
    },
    {
      "id": 2,
      "name": "Mercedes",
      "picture": "./static/images/Marcedes.jpg",
      "charges": "PKR 200 per excess km"
    },
    {
        "id": 3,
        "name": "Lexus",
        "picture": "./static/images/Lexus.jpg",
        "charges": "PKR 150 per excess km"
      }
]

First , import on top:

import calculatorData from "../static/data/terrifcalculatordata.json";

then after return:

  <div>
  {
    calculatorData.map((calculatedata, index) => {
        return (
            <div key={index}>
                <img
                    src={calculatedata.picture}
                    class="d-block"
                    height="170"
                />
                <p>
                    {calculatedata.charges}
                </p>
            </div>
                  

Error: Configuration with name 'default' not found in Android Studio

To diagnose this error quickly drop to a terminal or use the terminal built into Android Studio (accessible on in bottom status bar). Change to the main directory for your PROJECT (where settings.gradle is located).

1.) Check to make sure your settings.gradle includes the subproject. Something like this. This ensures your multi-project build knows about your library sub-project.

include ':apps:App1', ':apps:App2', ':library:Lib1'

Where the text between the colons are sub-directories.

2.) Run the following gradle command just see if Gradle can give you a list of tasks for the library. Use the same qualifier in the settings.gradle definition. This will uncover issues with the Library build script in isolation.

./gradlew :library:Lib1:tasks --info

3.) Make sure the output from the last step listed an "assembleDefault" task. If it didn't make sure the Library is including the Android Library plugin in build.gradle. Like this at the very top.

apply plugin: 'com.android.library'

I know the original poster's question was answered but I believe the answer has evolved over the past year and I think there are multiple reasons for the error. I think this resolution flow should assist those who run into the various issues.

How can I parse a string with a comma thousand separator to a number?

Yes remove the commas:

parseFloat(yournumber.replace(/,/g, ''));

How do I group Windows Form radio buttons?

Radio button without panel

public class RadioButton2 : RadioButton
{
   public string GroupName { get; set; }
}

private void RadioButton2_Clicked(object sender, EventArgs e)
{
    RadioButton2 rb = (sender as RadioButton2);

    if (!rb.Checked)
    {
       foreach (var c in Controls)
       {
           if (c is RadioButton2 && (c as RadioButton2).GroupName == rb.GroupName)
           {
              (c as RadioButton2).Checked = false;
           }
       }

       rb.Checked = true;
    }
}

private void Form1_Load(object sender, EventArgs e)
{
    //a group
    RadioButton2 rb1 = new RadioButton2();
    rb1.Text = "radio1";
    rb1.AutoSize = true;
    rb1.AutoCheck = false;
    rb1.Top = 50;
    rb1.Left = 50;
    rb1.GroupName = "a";
    rb1.Click += RadioButton2_Clicked;
    Controls.Add(rb1);

    RadioButton2 rb2 = new RadioButton2();
    rb2.Text = "radio2";
    rb2.AutoSize = true;
    rb2.AutoCheck = false;
    rb2.Top = 50;
    rb2.Left = 100;
    rb2.GroupName = "a";
    rb2.Click += RadioButton2_Clicked;
    Controls.Add(rb2);

    //b group
    RadioButton2 rb3 = new RadioButton2();
    rb3.Text = "radio3";
    rb3.AutoSize = true;
    rb3.AutoCheck = false;
    rb3.Top = 80;
    rb3.Left = 50;
    rb3.GroupName = "b";
    rb3.Click += RadioButton2_Clicked;
    Controls.Add(rb3);

    RadioButton2 rb4 = new RadioButton2();
    rb4.Text = "radio4";
    rb4.AutoSize = true;
    rb4.AutoCheck = false;
    rb4.Top = 80;
    rb4.Left = 100;
    rb4.GroupName = "b";
    rb4.Click += RadioButton2_Clicked;
    Controls.Add(rb4);
}

How do you store Java objects in HttpSession?

You are not adding the object to the session, instead you are adding it to the request.
What you need is:

HttpSession session = request.getSession();
session.setAttribute("MySessionVariable", param);

In Servlets you have 4 scopes where you can store data.

  1. Application
  2. Session
  3. Request
  4. Page

Make sure you understand these. For more look here

HttpClient does not exist in .net 4.0: what can I do?

read this...

Portable HttpClient for .NET Framework and Windows Phone

see paragraph Using HttpClient on .NET Framework 4.0 or Windows Phone 7.5 http://blogs.msdn.com/b/bclteam/archive/2013/02/18/portable-httpclient-for-net-framework-and-windows-phone.aspx

Hash and salt passwords in C#

I read all answers and I think those enough, specially @Michael articles with slow hashing and @CodesInChaos good comments, but I decided to share my code snippet for hashing/validating that may be useful and it does not require [Microsoft.AspNet.Cryptography.KeyDerivation].

    private static bool SlowEquals(byte[] a, byte[] b)
            {
                uint diff = (uint)a.Length ^ (uint)b.Length;
                for (int i = 0; i < a.Length && i < b.Length; i++)
                    diff |= (uint)(a[i] ^ b[i]);
                return diff == 0;
            }

    private static byte[] PBKDF2(string password, byte[] salt, int iterations, int outputBytes)
            {
                Rfc2898DeriveBytes pbkdf2 = new Rfc2898DeriveBytes(password, salt);
                pbkdf2.IterationCount = iterations;
                return pbkdf2.GetBytes(outputBytes);
            }

    private static string CreateHash(string value, int salt_bytes, int hash_bytes, int pbkdf2_iterations)
            {
                // Generate a random salt
                RNGCryptoServiceProvider csprng = new RNGCryptoServiceProvider();
                byte[] salt = new byte[salt_bytes];
                csprng.GetBytes(salt);

                // Hash the value and encode the parameters
                byte[] hash = PBKDF2(value, salt, pbkdf2_iterations, hash_bytes);

                //You need to return the salt value too for the validation process
                return Convert.ToBase64String(hash) + ":" + 
                       Convert.ToBase64String(hash);
            }

    private static bool ValidateHash(string pureVal, string saltVal, string hashVal, int pbkdf2_iterations)
            {
                try
                {
                    byte[] salt = Convert.FromBase64String(saltVal);
                    byte[] hash = Convert.FromBase64String(hashVal);

                    byte[] testHash = PBKDF2(pureVal, salt, pbkdf2_iterations, hash.Length);
                    return SlowEquals(hash, testHash);
                }
                catch (Exception ex)
                {
                    return false;
                }
            }

Please pay attention SlowEquals function that is so important, Finally, I hope this help and Please don't hesitate to advise me about better approaches.

Why does Node.js' fs.readFile() return a buffer instead of string?

Async:

fs.readFile('test.txt', 'utf8', callback);

Sync:

var content = fs.readFileSync('test.txt', 'utf8');

Getting Chrome to accept self-signed localhost certificate

This worked for me. See: http://www.robpeck.com/2010/10/google-chrome-mac-os-x-and-self-signed-ssl-certificates/#.Vcy8_ZNVhBc

In the address bar, click the little lock with the X. This will bring up a small information screen. Click the button that says "Certificate Information."

Click and drag the image to your desktop. It looks like a little certificate.

Double-click it. This will bring up the Keychain Access utility. Enter your password to unlock it.

Be sure you add the certificate to the System keychain, not the login keychain. Click "Always Trust," even though this doesn't seem to do anything.

After it has been added, double-click it. You may have to authenticate again.

Expand the "Trust" section.

"When using this certificate," set to "Always Trust"

Using C# to read/write Excel files (.xls/.xlsx)

I use NPOI for all my Excel needs.

http://npoi.codeplex.com/

Comes with a solution of examples for many common Excel tasks.

How do I share a global variable between c files?

If you want to use global variable i of file1.c in file2.c, then below are the points to remember:

  1. main function shouldn't be there in file2.c
  2. now global variable i can be shared with file2.c by two ways:
    a) by declaring with extern keyword in file2.c i.e extern int i;
    b) by defining the variable i in a header file and including that header file in file2.c.

Javascript: How to check if a string is empty?

I check length.

if (str.length == 0) {
}

How do I get a file's directory using the File object?

File directory = new File("Enter any 
                directory name or file name");
boolean isDirectory = directory.isDirectory();
if (isDirectory) {
  // It returns true if directory is a directory.
  System.out.println("the name you have entered 
         is a directory  : "  +    directory);  
  //It returns the absolutepath of a directory.
  System.out.println("the path is "  + 
              directory.getAbsolutePath());
} else {
  // It returns false if directory is a file.
  System.out.println("the name you have
   entered is a file  : " +   directory);
  //It returns the absolute path of a file.
  System.out.println("the path is "  +  
            file.getParent());
}

"Specified argument was out of the range of valid values"

It seems that you are trying to get 5 items out of a collection with 5 items. Looking at your code, it seems you're starting at the second value in your collection at position 1. Collections are zero-based, so you should start with the item at index 0. Try this:

TextBox box1 = (TextBox)Gridview1.Rows[i].Cells[0].FindControl("txt_type");
TextBox box2 = (TextBox)Gridview1.Rows[i].Cells[1].FindControl("txt_total");
TextBox box3 = (TextBox)Gridview1.Rows[i].Cells[2].FindControl("txt_max");
TextBox box4 = (TextBox)Gridview1.Rows[i].Cells[3].FindControl("txt_min");
TextBox box5 = (TextBox)Gridview1.Rows[i].Cells[4].FindControl("txt_rate");

When is TCP option SO_LINGER (0) required?

I like Maxim's observation that DOS attacks can exhaust server resources. It also happens without an actually malicious adversary.

Some servers have to deal with the 'unintentional DOS attack' which occurs when the client app has a bug with connection leak, where they keep creating a new connection for every new command they send to your server. And then perhaps eventually closing their connections if they hit GC pressure, or perhaps the connections eventually time out.

Another scenario is when 'all clients have the same TCP address' scenario. Then client connections are distinguishable only by port numbers (if they connect to a single server). And if clients start rapidly cycling opening/closing connections for any reason they can exhaust the (client addr+port, server IP+port) tuple-space.

So I think servers may be best advised to switch to the Linger-Zero strategy when they see a high number of sockets in the TIME_WAIT state - although it doesn't fix the client behavior, it might reduce the impact.