Programs & Examples On #Php socket

PHP comes with a very capable socket programming API. These socket functions include almost everything you would need for socket-based client-server communication over TCP/IP, and can be easily deployed to build simple network applications.

How can I convert NSDictionary to NSData and vice versa?

Use NSJSONSerialization:

NSDictionary *dict;
NSData *dataFromDict = [NSJSONSerialization dataWithJSONObject:dict

NSDictionary *dictFromData = [NSJSONSerialization JSONObjectWithData:dataFromDict

The latest returns id, so its a good idea to check the returned object type after you cast (here i casted to NSDictionary).

VB.NET - How to move to next item a For Each Loop?

For Each I As Item In Items
    If I = x Then Continue For

    ' Do something

How can I open a link in a new window?

What's wrong with <a href="myurl.html" target="_blank">My Link</a>? No Javascript needed...

android button selector

Create custom_selector.xml in drawable folder

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="">
   <item android:drawable="@drawable/unselected" android:state_pressed="true" />
   <item android:drawable="@drawable/selected" />

Create selected.xml shape in drawable folder

<shape xmlns:android="" android:shape="rectangle" android:padding="90dp">
   <solid android:color="@color/selected"/>
   <padding />
   <stroke android:color="#000" android:width="1dp"/>
   <corners android:bottomRightRadius="15dp" android:bottomLeftRadius="15dp" android:topLeftRadius="15dp" android:topRightRadius="15dp"/>

Create unselected.xml shape in drawable folder

<shape xmlns:android="" android:shape="rectangle" android:padding="90dp">
   <solid android:color="@color/unselected"/>
   <padding />
   <stroke android:color="#000" android:width="1dp"/>
   <corners android:bottomRightRadius="15dp" android:bottomLeftRadius="15dp" android:topLeftRadius="15dp" android:topRightRadius="15dp"/>

Add following colors for selected/unselected state in color.xml of values folder

<color name="selected">#a8cf45</color>
<color name="unselected">#ff8cae3b</color>

you can check complete solution from here

Trying to SSH into an Amazon Ec2 instance - permission error

In windows you can go to the properties of the pem file, and go to the security tab, then to advance button.

remove inheritance and all the permissions. then grant yourself the full control. after all SSL will not give you the same error again.

HashMap allows duplicates?

Each key in a HashMap must be unique.

When "adding a duplicate key" the old value (for the same key, as keys must be unique) is simply replaced; see HashMap.put:

Associates the specified value with the specified key in this map. If the map previously contained a mapping for the key, the old value is replaced.

Returns the previous value associated with key, or null if there was no mapping for key.

As far as nulls: a single null key is allowed (as keys must be unique) but the HashMap can have any number of null values, and a null key need not have a null value. Per the documentation:

[.. HashMap] permits null values and [a] null key.

However, the documentation says nothing about null/null needing to be a specific key/value pair or null/"a" being invalid.

Hidden property of a button in HTML

<script src=""></script>

function showButtons () { $('#b1, #b2, #b3').show(); }

<style type="text/css">
#b1, #b2, #b3 {
display: none;


<a href="#" onclick="showButtons();">Show me the money!</a>

<input type="submit" id="b1" value="B1" />
<input type="submit" id="b2" value="B2"/>
<input type="submit" id="b3" value="B3" />


echo key and value of an array without and with loop

Echo key and value of an array without and with loop

$array = array(



    [1] => name
    [value] => name
    [0] => kk6NFKK
    [key] => kk6NFKK

How to sort an ArrayList in Java

Use a Comparator like this:

List<Fruit> fruits= new ArrayList<Fruit>();

Fruit fruit;
for(int i = 0; i < 100; i++)
  fruit = new Fruit();

// Sorting
Collections.sort(fruits, new Comparator<Fruit>() {
        public int compare(Fruit fruit2, Fruit fruit1)

            return  fruit1.fruitName.compareTo(fruit2.fruitName);

Now your fruits list is sorted based on fruitName.

How do I determine whether an array contains a particular value in Java?

In Java 8 use Streams.

List<String> myList =
Arrays.asList("a1", "a2", "b1", "c2", "c1");

.filter(s -> s.startsWith("c"))

Returning a stream from File.OpenRead()

Try changing your code to this:

private void Test()
    System.IO.MemoryStream data = new System.IO.MemoryStream(TestStream());

    byte[] buf = new byte[data.Length];
    data.Read(buf, 0, buf.Length);                       

How can I remove duplicate rows?

To Fetch Duplicate Rows:

name, email, COUNT(*)
name, email

To Delete the Duplicate Rows:

DELETE users 
(SELECT MIN(rowid)
FROM users
GROUP BY name, email);      

How to get the date from the DatePicker widget in Android?

U can also use te Calendar.GregorianCalendar java class

    GregorianCalendar calendarBeg=new GregorianCalendar(datePicker.getYear(),
    Date begin=calendarBeg.getTime();

Python 2,3 Convert Integer to "bytes" Cleanly

from int to byte:

bytes_string = int_v.to_bytes( lenth, endian )

where the lenth is 1/2/3/4...., and endian could be 'big' or 'little'

form bytes to int:

data_list = list( bytes );

What is difference between 'git reset --hard HEAD~1' and 'git reset --soft HEAD~1'?

Git reset has 5 main modes: soft, mixed, merged, hard, keep. The difference between them is to change or not change head, stage (index), working directory.

Git reset --hard will change head, index and working directory.
Git reset --soft will change head only. No change to index, working directory.

So in other words if you want to undo your commit, --soft should be good enough. But after that you still have the changes from bad commit in your index and working directory. You can modify the files, fix them, add them to index and commit again.

With the --hard, you completely get a clean slate in your project. As if there hasn't been any change from the last commit. If you are sure this is what you want then move forward. But once you do this, you'll lose your last commit completely. (Note: there are still ways to recover the lost commit).

How do you detect Credit card type based on number?

Try this.For swift.

func checkCardValidation(number : String) -> Bool
    let reversedInts = number.characters.reversed().map { Int(String($0)) }
        return reversedInts.enumerated().reduce(0, {(sum, val) in
            let odd = val.offset % 2 == 1
            return sum + (odd ? (val.element! == 9 ? 9 : (val.element! * 2) % 9) : val.element!)
        }) % 10 == 0


if (self.checkCardValidation(number: "yourNumber") == true) {
     print("Card Number valid")
     print("Card Number not valid")

How do you access a website running on localhost from iPhone browser

For those of you that are using the correct IP address and you STILL aren't able to connect to the local server, one other thing to check is that you or your coworker didn't configure the device to use a proxy server.

I had one device that wouldn't connect, and it turned out that the device was configured to use Charles Proxy, which of course wasn't running.

How to get coordinates of an svg element?

I was trying to select an area of svg with a rectangle and get all the elements from it. For this, element.getBoundingClientRect() worked perfectly for me. It returns current coordinates of svg elements regardless of whether svg is scaled or transformed.

Typescript empty object for a typed variable


Here are two worthy caveats from the comments.

Either you want user to be of type User | {} or Partial<User>, or you need to redefine the User type to allow an empty object. Right now, the compiler is correctly telling you that user is not a User. – jcalz

I don't think this should be considered a proper answer because it creates an inconsistent instance of the type, undermining the whole purpose of TypeScript. In this example, the property Username is left undefined, while the type annotation is saying it can't be undefined. – Ian Liu Rodrigues


One of the design goals of TypeScript is to "strike a balance between correctness and productivity." If it will be productive for you to do this, use Type Assertions to create empty objects for typed variables.

type User = {
    Username: string;
    Email: string;

const user01 = {} as User;
const user02 = <User>{};

user01.Email = "[email protected]";

Here is a working example for you.

Here are type assertions working with suggestion.

What is the difference between the | and || or operators?

The singe pipe "|" is the "bitwise" or and should only be used when you know what you're doing. The double pipe "||" is a logical or, and can be used in logical statements, like "x == 0 || x == 1".

Here's an example of what the bitwise or does: if a=0101 and b=0011, then a|b=0111. If you're dealing with a logic system that treats any non-zero as true, then the bitwise or will act in the same way as the logical or, but it's counterpart (bitwise and, "&") will NOT. Also the bitwise or does not perform short circuit evaluation.

What is the OR operator in an IF statement

Or is ||

And is &&

Update for changed question:

You need to specify what you are comparing against in each logical section of the if statement.

if (title == "User greeting" || title == "User name") 
    // do stuff

CSS Transition doesn't work with top, bottom, left, right

Something that is not relevant for the OP, but maybe for someone else in the future:

For pixels (px), if the value is "0", the unit can be omitted: right: 0 and right: 0px both work.

However I noticed that in Firefox and Chrome this is not the case for the seconds unit (s). While transition: right 1s ease 0s works, transition: right 1s ease 0 (missing unit s for last value transition-delay) does not (it does work in Edge however).

In the following example, you'll see that right works for both 0px and 0, but transition only works for 0s and it doesn't work with 0.

#box {_x000D_
    border: 1px solid black;_x000D_
    height: 240px;_x000D_
    width: 260px;_x000D_
    margin: 50px;_x000D_
    position: relative;_x000D_
.jump {_x000D_
    position: absolute;_x000D_
    width: 200px;_x000D_
    height: 50px;_x000D_
    color: white;_x000D_
    padding: 5px;_x000D_
#jump1 {_x000D_
    background-color: maroon;_x000D_
    top: 0px;_x000D_
    right: 0px;_x000D_
    transition: right 1s ease 0s;_x000D_
#jump2 {_x000D_
    background-color: green;_x000D_
    top: 60px;_x000D_
    right: 0;_x000D_
    transition: right 1s ease 0s;_x000D_
#jump3 {_x000D_
    background-color: blue;_x000D_
    top: 120px;_x000D_
    right: 0px;_x000D_
    transition: right 1s ease 0;_x000D_
#jump4 {_x000D_
    background-color: gray;_x000D_
    top: 180px;_x000D_
    right: 0;_x000D_
    transition: right 1s ease 0;_x000D_
#box:hover .jump {_x000D_
    right: 50px;_x000D_
<div id="box">_x000D_
  <div class="jump" id="jump1">right: 0px<br>transition: right 1s ease 0s</div>_x000D_
  <div class="jump" id="jump2">right: 0<br>transition: right 1s ease 0s</div>_x000D_
  <div class="jump" id="jump3">right: 0px<br>transition: right 1s ease 0</div>_x000D_
  <div class="jump" id="jump4">right: 0<br>transition: right 1s ease 0</div>_x000D_

Set Windows process (or user) memory limit

No way to do this that I know of, although I'm very curious to read if anyone has a good answer. I have been thinking about adding something like this to one of the apps my company builds, but have found no good way to do it.

The one thing I can think of (although not directly on point) is that I believe you can limit the total memory usage for a COM+ application in Windows. It would require the app to be written to run in COM+, of course, but it's the closest way I know of.

The working set stuff is good (Job Objects also control working sets), but that's not total memory usage, only real memory usage (paged in) at any one time. It may work for what you want, but afaik it doesn't limit total allocated memory.

Saving data to a file in C#

Here's an article from MSDN on a guide for how to write text to a file:

I'd start there, then post additional, more specific questions as you continue your development.

How to make a back-to-top button using CSS and HTML only?

Hope this helps somebody!

<style> html { scroll-behavior: smooth;} </style>
<a id="top"></>
<!--content here-->
<a href="#top">Back to top..</a>

If input value is blank, assign a value of "empty" with Javascript

I'm guessing this is what you want...

When the form is submitted, check if the value is empty and if so, send a value = empty.

If so, you could do the following with jQuery.

    var input = $('#test').val();
    if(input == ''){


    <input id="test" type="text" />

Click your cursor in the box and then hit enter to see the form submit the value.

Markdown open a new window link

You can edit the generated markup and add

target = "_blank"

What was the strangest coding standard rule that you were forced to follow?

no single character variable names - even for a simple iterator like i. Had to use ii or something. I thought this was stupid.

Another one - perhaps the craziest of all, but maybe not a coding standard...

no STL allowed. and this was in 2007/2008. I left there soon after I found out about that nonsense. Apparently some idiots thought that there was no "standard" (As in 15 years ago...) I guess they missed the memo about stl being in the C++ standard...

Use of the stupid COM HRESULTs as return types for just about ALL methods - even if they are not COM. It was ludicrous. So now instead of returning some enumerated type or a useful value that indicates a result, etc, we had to look up what S_OK or E_FAIL or whatever meant in the context of each of the methods. Again, I left there shortly after that.

How to place a JButton at a desired location in a JFrame using Java

Use child.setLocation(0, 0) on the button, and parent.setLayout(null). Instead of using setBounds(...) on the JFrame to size it, consider using just setSize(...) and letting the OS position the frame.

JPanel pnlButton = new JPanel();
JButton btnAddFlight = new JButton("Add Flight");

public Control() {

    //JFrame layout

    //JPanel layout

    //Adding to JFrame

    // postioning

HTML table with fixed headers and a fixed column?

I see this, although an old question, is a pretty good place to plug my own script:

It just works with no configuration and is really easy to setup.

How to list only top level directories in Python?

A very much simpler and elegant way is to use this:

 import os
 dir_list = os.walk('.').next()[1]
 print dir_list

Run this script in the same folder for which you want folder names.It will give you exactly the immediate folders name only(that too without the full path of the folders).

HTML list-style-type dash

ul {
  list-style-type: none;

ul > li:before {
  content: "–"; /* en dash */
  position: absolute;
  margin-left: -1.1em; 

demo fiddle

Equivalent of shell 'cd' command to change the working directory?

I would use os.chdir like this:


By the way, if you need to figure out your current path, use os.getcwd().

More here

How to filter files when using scp to copy dir recursively?

With ssh key based authentication enabled, the following script would work.

for x in `ssh user@remotehost 'find /usr/some -type f -name *.class'`; do y=$(echo $x|sed 's/.[^/]*$//'|sed "s/^\/usr//"); mkdir -p /usr/project/backup$y; scp $(echo 'user@remotehost:'$x) /usr/project/backup$y/; done

Encrypt and decrypt a password in Java

Jasypt can do it for you easy and simple

For homebrew mysql installs, where's my.cnf?

I believe the answer is no. Installing one in ~/.my.cnf or /usr/local/etc seems to be the preferred solution.

Undefined symbols for architecture arm64

If your Architectures and Valid Architectures are all right, you may check whether you have added $(inherited) , which will add linker flags generated in pods, to Other Linker Flags as below: enter image description here

Set android shape color programmatically

hope this will help someone with the same issue

GradientDrawable gd = (GradientDrawable) YourImageView.getBackground();
//To shange the solid color

//To change the stroke color
int width_px = (int)TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, youStrokeWidth, getResources().getDisplayMetrics());
gd.setStroke(width_px, yourColor);

indexOf method in an object array?

Using the ES6 findIndex method, without lodash or any other libraries, you can write:

function deepIndexOf(arr, obj) {
  return arr.findIndex(function (cur) {
    return Object.keys(obj).every(function (key) {
      return obj[key] === cur[key];

This will compare the immediate properties of the object, but not recurse into the properties.

If your implementation doesn't provide findIndex yet (most don't), you can add a light polyfill that supports this search:

function deepIndexOf(arr, obj) {
  function findIndex = Array.prototype.findIndex || function (pred) {
    for (let i = 0; i < this.length; ++i) {
      if (, this[i], i)) {
        return i;

    return -1;

  return, function (cur) {
    return Object.keys(obj).every(function (key) {
      return obj[key] === cur[key];

(from my answer on this dupe)

How to print variable addresses in C?

To print the address of a variable, you need to use the %p format. %d is for signed integers. For example:


void main(void)
  int a;

  printf("Address is %p:",&a);

Check if table exists in SQL Server

If anyone is trying to do this same thing in linq to sql (or especially linqpad) turn on option to include system tables and views and do this code:

let oSchema = sys.Schemas.FirstOrDefault(s=>s.Name==a.schema )
where oSchema !=null
let o=oSchema!=null?sys.Objects.FirstOrDefault (o => o.Name==a.item && o.Schema_id==oSchema.Schema_id):null
where o!=null

given that you have an object with the name in a property called item, and the schema in a property called schema where the source variable name is a

How do I 'git diff' on a certain directory?

You should make a habit of looking at the documentation for stuff like this. It's very useful and will improve your skills very quickly. Here's the relevant bit when you do git help diff

   git diff [options] [--no-index] [--] <path> <path>

The two <path>s are what you need to change to the directories in question.

Format date with Moment.js

The 2nd argument to moment() is a parsing format rather than an display format.

For that, you want the .format() method:


Also note that case does matter. For Month, Day of Month, and Year, the format should be uppercase.

How do I install Python libraries in wheel format?

Have you checked this ?

  1. First you have to install the module

    $ pip install requests

  2. Then, before using it you must import it from your program.

    from requests import requests

    Note that your modules must be in the same directory.

  3. Then you can use it.

    For this part you have to check for the documentation.

Maintain image aspect ratio when changing height

To keep images from stretching in either axis inside a flex parent I have found a couple of solutions.

You can try using object-fit on the image which, e.g.

object-fit: contain;

Or you can add flex-specfic rules which may work better in some cases.

align-self: center;
flex: 0 0 auto;

minimize app to system tray

I'd go with

private void Form1_Resize(object sender, EventArgs e)
     if (FormWindowState.Minimized == this.WindowState)
          notifyIcon1.Visible = true;
     else if (FormWindowState.Normal == this.WindowState)
          notifyIcon1.Visible = false;

private void notifyIcon1_MouseDoubleClick(object sender, MouseEventArgs e)
     this.WindowState = FormWindowState.Normal;

Is there a TRY CATCH command in Bash

bash does not abort the running execution in case something detects an error state (unless you set the -e flag). Programming languages which offer try/catch do this in order to inhibit a "bailing out" because of this special situation (hence typically called "exception").

In the bash, instead, only the command in question will exit with an exit code greater than 0, indicating that error state. You can check for that of course, but since there is no automatic bailing out of anything, a try/catch does not make sense. It is just lacking that context.

You can, however, simulate a bailing out by using sub shells which can terminate at a point you decide:

  echo "Do one thing"
  echo "Do another thing"
  if some_condition
    exit 3  # <-- this is our simulated bailing out
  echo "Do yet another thing"
  echo "And do a last thing"
)   # <-- here we arrive after the simulated bailing out, and $? will be 3 (exit code)
if [ $? = 3 ]
  echo "Bail out detected"

Instead of that some_condition with an if you also can just try a command, and in case it fails (has an exit code greater than 0), bail out:

  echo "Do one thing"
  echo "Do another thing"
  some_command || exit 3
  echo "Do yet another thing"
  echo "And do a last thing"

Unfortunately, using this technique you are restricted to 255 different exit codes (1..255) and no decent exception objects can be used.

If you need more information to pass along with your simulated exception, you can use the stdout of the subshells, but that is a bit complicated and maybe another question ;-)

Using the above mentioned -e flag to the shell you can even strip that explicit exit statement:

  set -e
  echo "Do one thing"
  echo "Do another thing"
  echo "Do yet another thing"
  echo "And do a last thing"

Delete duplicate elements from an array

As elements are yet ordered, you don't have to build a map, there's a fast solution :

var newarr = [arr[0]];
for (var i=1; i<arr.length; i++) {
   if (arr[i]!=arr[i-1]) newarr.push(arr[i]);

If your array weren't sorted, you would use a map :

var newarr = (function(arr){
  var m = {}, newarr = []
  for (var i=0; i<arr.length; i++) {
    var v = arr[i];
    if (!m[v]) {
  return newarr;

Note that this is, by far, much faster than the accepted answer.

how to output every line in a file python

Did you try

for line in open("masters", "r").readlines(): print line



only reads "a line", on the other hand


reads whole lines and gives you a list of all lines.

OnItemClickListener using ArrayAdapter for ListView

i'm using arrayadpter ,using this follwed code i'm able to get items

String value = (String)adapter.getItemAtPosition(position);

listView.setOnItemClickListener(new OnItemClickListener() {

        public void onItemClick(AdapterView<?> parent, View view,
                int position, long id) {
             String string=adapter.getItem(position);
             Log.d("**********", string);


How to pass the button value into my onclick event function?

You can get value by using id for that element in onclick function

function dosomething(){
     var buttonValue = document.getElementById('buttonId').value;

In Bootstrap open Enlarge image in modal

You can try this code if you are using bootstrap 3:


<a href="#" id="pop">
    <img id="imageresource" src="" style="width: 400px; height: 264px;">
    Click to Enlarge

<!-- Creates the bootstrap modal where the image will appear -->
<div class="modal fade" id="imagemodal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">&times;</span><span class="sr-only">Close</span></button>
        <h4 class="modal-title" id="myModalLabel">Image preview</h4>
      <div class="modal-body">
        <img src="" id="imagepreview" style="width: 400px; height: 264px;" >
      <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>


$("#pop").on("click", function() {
   $('#imagepreview').attr('src', $('#imageresource').attr('src')); // here asign the image to the modal when the user click the enlarge link
   $('#imagemodal').modal('show'); // imagemodal is the id attribute assigned to the bootstrap modal, then i use the show function

This is the working fiddle. Hope this helps :)

JSON Naming Convention (snake_case, camelCase or PascalCase)

As others have stated there is no standard so you should choose one yourself. Here are a couple of things to consider when doing so:

  1. If you are using JavaScript to consume JSON then using the same naming convention for properties in both will provide visual consistency and possibly some opportunities for cleaner code re-use.

  2. A small reason to avoid kebab-case is that the hyphens may clash visually with - characters that appear in values.

      "bank-balance": -10

Read a javascript cookie by name

You can use the following function:

function getCookiesMap(cookiesString) {
  return cookiesString.split(";")
    .map(function(cookieString) {
        return cookieString.trim().split("=");
    .reduce(function(acc, curr) {
        acc[curr[0]] = curr[1];
        return acc;
    }, {});

When, called with document.cookie as parameter, it will return an object, with the cookies keys as keys and the cookies values.

var cookies = getCookiesMap(document.cookie);
var cookieValue = cookies["MYBIGCOOKIE"];

What equivalents are there to TortoiseSVN, on Mac OSX?

I use svnX (, it is free and usable, but not as user friendly as tortoise. It shows you the review before commit with diff for every file... but sometimes I still had to go to command line to fix some things

How to bind RadioButtons to an enum?

This work for Checkbox too.

public class EnumToBoolConverter:IValueConverter
    private int val;
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        int intParam = (int)parameter;
        val = (int)value;

        return ((intParam & val) != 0);

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        val ^= (int)parameter;
        return Enum.Parse(targetType, val.ToString());

Binding a single enum to multiple checkboxes.

Find and Replace text in the entire table using a MySQL query

If you are positive that none of the fields to be updated are serialized, the solutions above will work well.

However, if any of the fields that need updating contain serialized data, an SQL Query or a simple search/replace on a dump file, will break serialization (unless the replaced string has exactly the same number of characters as the searched string).

To be sure, a "serialized" field looks like this:


The number of characters in the relevant data is encoded as part of the data.
Serialization is a way to convert "objects" into a format easily stored in a database, or to easily transport object data between different languages.
Here is an explanation of different methods used to serialize object data, and why you might want to do so, and here is a WordPress-centric post: Serialized Data, What Does That Mean And Why is it so Important? in plain language.

It would be amazing if MySQL had some built in tool to handle serialized data automatically, but it does not, and since there are different serialization formats, it would not even make sense for it to do so.

Some of the answers above seemed specific to WordPress databases, which serializes much of its data. WordPress offers a command line tool, wp search-replace, that does handle serialization.
A basic command would be:

    wp search-replace 'an-old-string' 'a-new-string' --dry-run

However, WordPress emphasizes that the guid should never be changed, so it recommends skipping that column.
It also suggests that often times you'll want to skip the wp_users table.
Here's what that would look like:

wp search-replace '' '' --skip-columns=guid --skip-tables=wp_users --dry-run

Note: I added the --dry-run flag so a copy-paste won't automatically ruin anyone's database. After you're sure the script does what you want, run it again without that flag.

If you are using WordPress, there are also many free and commercial plugins available that offer a gui interface to do the same, packaged with many additional features.

Interconnect/it php script
Interconnect/it offers a php script to handle serialized data: Safe Search and Replace tool. It was created for use on WordPress sites, but it looks like it can be used on any database serialized by PHP.
Many companies, including WordPress itself, recommends this tool. Instructions here, about 3/4 down the page. Invalid hostname for server: local

Please try to set SPARK_LOCAL_IP environment variable to the ip address(can be localhost i.e. your own ip address) you want to connect. E.g.

$ export SPARK_LOCAL_IP=

This way you will not be required to alter existing linux settings. Worked for me, hope helps you too.

Random row selection in Pandas dataframe

Something like this?

import random

def some(x, n):
    return x.ix[random.sample(x.index, n)]

Note: As of Pandas v0.20.0, ix has been deprecated in favour of loc for label based indexing.

How to check list A contains any value from list B?

You can check if a list is inside of another list with this

var list1 = new List<int> { 1, 2, 3, 4, 6 };
var list2 = new List<int> { 2, 3 };
bool a = list1.Any(c => list2.Contains(c));

Array.Add vs +=

When using the $array.Add()-method, you're trying to add the element into the existing array. An array is a collection of fixed size, so you will receive an error because it can't be extended.

$array += $element creates a new array with the same elements as old one + the new item, and this new larger array replaces the old one in the $array-variable

You can use the += operator to add an element to an array. When you use it, Windows PowerShell actually creates a new array with the values of the original array and the added value. For example, to add an element with a value of 200 to the array in the $a variable, type:

    $a += 200

Source: about_Arrays

+= is an expensive operation, so when you need to add many items you should try to add them in as few operations as possible, ex:

$arr = 1..3    #Array
$arr += (4..5) #Combine with another array in a single write-operation


If that's not possible, consider using a more efficient collection like List or ArrayList (see the other answer).

Pass object to javascript function

The "braces" are making an object literal, i.e. they create an object. It is one argument.


function someFunc(arg) {

someFunc({foo: "This", bar: "works!"});

the object can be created beforehand as well:

var someObject = {
    foo: "This", 
    bar: "works!"


I recommend to read the MDN JavaScript Guide - Working with Objects.

WAMP won't turn green. And the VCRUNTIME140.dll error

Since you already had a running version of WAMP and it stopped working, you probably had VCRUNTIME140.dll already installed. In that case:

  1. Open Programs and Features
  2. Right-click on the respective Microsoft Visual C++ 20xx Redistributable installers and choose "Change"
  3. Choose "Repair". Do this for both x86 and x64

This did the trick for me.

IIS - can't access page by ip address instead of localhost

Maybe it helps someone too:)

I'm not allowed to post images, so here goes extra link to my blog. Sorry.

IIS webpage by using IP address

In IIS Management : Choose Site, then Bindings.


  • Type : http
  • HostName : Empty
  • Port : 80
  • IP Address : Choose from drop-down menu the IP you need (usually there is only one IP)

Changing the JFrame title

I strongly recommend you learn how to use layout managers to get the layout you want to see. null layouts are fragile, and cause no end of trouble.

Try this source & check the comments.

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTabbedPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;

public class VolumeCalculator extends JFrame implements ActionListener {
    private JTabbedPane jtabbedPane;
    private JPanel options;
    JTextField poolLengthText, poolWidthText, poolDepthText, poolVolumeText, hotTub,
            hotTubLengthText, hotTubWidthText, hotTubDepthText, hotTubVolumeText, temp, results,
    JTextArea labelTubStatus;

    public VolumeCalculator(){
        setSize(400, 250);
        setSize(400, 250);
        setTitle("Volume Calculator");
        setSize(300, 200);
        JPanel topPanel = new JPanel();
        topPanel.setLayout(new BorderLayout());


        jtabbedPane = new JTabbedPane();

        jtabbedPane.addTab("Options", options);

        topPanel.add(jtabbedPane, BorderLayout.CENTER);

    public void createOptions(){
        options = new JPanel();
        JLabel labelOptions = new JLabel("Change Company Name:");
        labelOptions.setBounds(120, 10, 150, 20);
        JTextField newTitle = new JTextField("Some Title");
        //newTitle.setBounds(80, 40, 225, 20);    
        myTitle = new JTextField(20);
        // myTitle WAS NEVER ADDED to the GUI!
        //myTitle.setBounds(80, 40, 225, 20);
        JButton newName = new JButton("Set New Name");
        //newName.setBounds(60, 80, 150, 20);
        JButton Exit = new JButton("Exit");
        //Exit.setBounds(250, 80, 80, 20);

    public void actionPerformed(ActionEvent event){
        JButton button = (JButton) event.getSource();
        String buttonLabel = button.getText();
        if ("Exit".equalsIgnoreCase(buttonLabel)){
        if ("Set New Name".equalsIgnoreCase(buttonLabel)){

    private void Exit_pressed(){

    private void New_Name(){
        System.out.println("'" + myTitle.getText() + "'");

    private void Options(){

    public static void main(String[] args){
        JFrame frame = new VolumeCalculator();
        frame.setSize(380, 350);

What's the longest possible worldwide phone number I should consider in SQL varchar(length) for phone

It's a bit worse, I use a calling card for international calls, so its local number in the US + account# (6 digits) + pin (4 digits) + "pause" + what you described above.

I suspect there might be other cases

.NET HashTable Vs Dictionary - Can the Dictionary be as fast?

Dictionary is faster than hashtable as dictionary is a generic strong type. Hashtable is slower as it takes object as data type which leads to boxing and unboxing.

IE 8: background-size fix

As pointed by @RSK IE8 doesn't support background-size. To figure out a way to deal with this, I used some IE specific hacks as showed here:

//IE8.0 Hack!
@media \0screen {
    .brand {
        background-image: url("./images/logo1.png");
        margin-top: 8px;

    .navbar .brand {
        margin-left: -2px;
        padding-bottom: 2px;

//IE7.0 Hack!
*+html .brand {
    background-image: url("./images/logo1.png");
    margin-top: 8px;

*+html .navbar .brand {
    margin-left: -2px;
    padding-bottom: 2px;

Using this I was able to change my logo image to a ugly resided picture. But the final result is fine. I suggest u try something like this.

Getting the IP Address of a Remote Socket Endpoint

You can then call the IPEndPoint..::.Address method to retrieve the remote IPAddress, and the IPEndPoint..::.Port method to retrieve the remote port number.

More from the link (fixed up alot heh):

Socket s;

IPEndPoint remoteIpEndPoint = s.RemoteEndPoint as IPEndPoint;
IPEndPoint localIpEndPoint = s.LocalEndPoint as IPEndPoint;

if (remoteIpEndPoint != null)
    // Using the RemoteEndPoint property.
    Console.WriteLine("I am connected to " + remoteIpEndPoint.Address + "on port number " + remoteIpEndPoint.Port);

if (localIpEndPoint != null)
    // Using the LocalEndPoint property.
    Console.WriteLine("My local IpAddress is :" + localIpEndPoint.Address + "I am connected on port number " + localIpEndPoint.Port);

Find object in list that has attribute equal to some value (that meets any condition)

For below code, xGen is an anonomous generator expression, yFilt is a filter object. Note that for xGen the additional None parameter is returned rather than throwing StopIteration when the list is exhausted.

arr =((10,0), (11,1), (12,2), (13,2), (14,3))

value = 2
xGen = (x for x in arr if x[1] == value)
yFilt = filter(lambda x: x[1] == value, arr)

for i in range(1,4):
    print('xGen: pass=',i,' result=',next(xGen,None))
    print('yFilt: pass=',i,' result=',next(yFilt))


<class 'generator'>
<class 'filter'>
xGen: pass= 1  result= (12, 2)
yFilt: pass= 1  result= (12, 2)
xGen: pass= 2  result= (13, 2)
yFilt: pass= 2  result= (13, 2)
xGen: pass= 3  result= None
Traceback (most recent call last):
  File "", line 12, in <module>
    print('yFilt: pass=',i,' result=',next(yFilt))

Open link in new tab or window

set the target attribute of your <a> element to "_tab"

EDIT: It works, however W3Schools says there is no such target attribute:

EDIT2: From what I've figured out from the comments. setting target to _blank will take you to a new tab or window (depending on your browser settings). Typing anything except one of the ones below will create a new tab group (I'm not sure how these work):

_blank  Opens the linked document in a new window or tab
_self   Opens the linked document in the same frame as it was clicked (this is default)
_parent Opens the linked document in the parent frame
_top    Opens the linked document in the full body of the window
framename   Opens the linked document in a named frame

Insert new column into table in sqlite?

ALTER TABLE {tableName} ADD COLUMN COLNew {type};
UPDATE {tableName} SET COLNew = {base on {type} pass value here};

This update is required to handle the null value, inputting a default value as you require. As in your case, you need to call the SELECT query and you will get the order of columns, as paxdiablo already said:

SELECT name, colnew, qty, rate FROM{tablename}

and in my opinion, your column name to get the value from the cursor:

private static final String ColNew="ColNew";
String val=cursor.getString(cursor.getColumnIndex(ColNew));

so if the index changes your application will not face any problems.

This is the safe way in the sense that otherwise, if you are using CREATE temptable or RENAME table or CREATE, there would be a high chance of data loss if not handled carefully, for example in the case where your transactions occur while the battery is running out.

Passing Javascript variable to <a href >

If you use internationalization (i18n), and after switch to another language, something like ?locale=fror ?fr might be added at the end of the url. But when you go to another page on click event, translation switch wont be stable.

For this kind of cases a DOM click event handler function must be produced to handle all the a.href attributes by storing the switch state as a variable and add it to all a tags’ tail.

Loop in Jade (currently known as "Pug") template engine

Pug (renamed from 'Jade') is a templating engine for full stack web app development. It provides a neat and clean syntax for writing HTML and maintains strict whitespace indentation (like Python). It has been implemented with JavaScript APIs. The language mainly supports two iteration constructs: each and while. 'for' can be used instead 'each'. Kindly consult the language reference here:

Here is one of my snippets: each/for iteration in pug_screenshot

Bootstrap Dropdown menu is not working

I tried all the above answers and the only version who works for me is the jquery 1.11.1. I tried with all the other versions 1.3.2, 1.4.4, 1.8.2, 3.3.1 and navbar dropdown doesn't work.

<script src="jquery/jquery-1.11.1.min.js"></script>

How to put spacing between floating divs?

You can do the following:

Assuming your container div has a class "yellow".

.yellow div {
    // Apply margin to every child in this container
    margin: 10px;

.yellow div:first-child, .yellow div:nth-child(3n+1) {
    // Remove the margin on the left side on the very first and then every fourth element (for example)
    margin-left: 0;

.yellow div:last-child {
    // Remove the right side margin on the last element
    margin-right: 0;

The number 3n+1 equals every fourth element outputted and will clearly only work if you know how many will be displayed in a row, but it should illustrate the example. More details regarding nth-child here.

Note: For :first-child to work in IE8 and earlier, a <!DOCTYPE> must be declared.

Note2: The :nth-child() selector is supported in all major browsers, except IE8 and earlier.

Using IF..ELSE in UPDATE (SQL server 2005 and/or ACCESS 2007)

Yes you can use CASE

UPDATE table 
SET columnB = CASE fieldA 
        WHEN columnA=1 THEN 'x' 
        WHEN columnA=2 THEN 'y' 
        ELSE 'z' 
WHERE columnC = 1

Is there a null-coalescing (Elvis) operator or safe navigation operator in javascript?

This is more commonly known as a null-coalescing operator. Javascript does not have one.

How to get column by number in Pandas?

One is a column (aka Series), while the other is a DataFrame:

In [1]: df = pd.DataFrame([[1,2], [3,4]], columns=['a', 'b'])

In [2]: df
   a  b
0  1  2
1  3  4

The column 'b' (aka Series):

In [3]: df['b']
0    2
1    4
Name: b, dtype: int64

The subdataframe with columns (position) in [1]:

In [4]: df[[1]]
0  2
1  4

Note: it's preferable (and less ambiguous) to specify whether you're talking about the column name e.g. ['b'] or the integer location, since sometimes you can have columns named as integers:

In [5]: df.iloc[:, [1]]
0  2
1  4

In [6]: df.loc[:, ['b']]
0  2
1  4

In [7]: df.loc[:, 'b']
0    2
1    4
Name: b, dtype: int64

How to get a List<string> collection of values from app.config in WPF?

In App.config:

<add key="YOURKEY" value="a,b,c"/>

In C#:

string[] InFormOfStringArray = ConfigurationManager.AppSettings["YOURKEY"].Split(',').Select(s => s.Trim()).ToArray();
List<string> list = new List<string>(InFormOfStringArray);

Using Oracle to_date function for date string with milliseconds

TO_DATE supports conversion to DATE datatype, which doesn't support milliseconds. If you want millisecond support in Oracle, you should look at TIMESTAMP datatype and TO_TIMESTAMP function.

Hope that helps.

How to prevent a browser from storing passwords

< input type="password" style='pointer-event: none' onInput= (e) => handleInput(e) />
function handleInput(e) {
  e.stopPropagation();'readonly', true);
  setTimeout(() => {;'readonly');

PHP: convert spaces in string into %20?

The plus sign is the historic encoding for a space character in URL parameters, as documented in the help for the urlencode() function.

That same page contains the answer you need - use rawurlencode() instead to get RFC 3986 compatible encoding.

How do I copy a folder from remote to local using scp?

Better to first compress catalog on remote server:

tar czfP backup.tar.gz /path/to/catalog

Secondly, download from remote:

scp [email protected]:/path/to/backup.tar.gz .

At the end, extract the files:

tar -xzvf backup.tar.gz

jquery drop down menu closing by clicking outside

You can tell any click that bubbles all the way up the DOM to hide the dropdown, and any click that makes it to the parent of the dropdown to stop bubbling.

/* Anything that gets to the document
   will hide the dropdown */

/* Clicks within the dropdown won't make
   it past the dropdown itself */


How to get all Errors from ASP.Net MVC modelState?

var x = new Dictionary<string,string>();
for (var b = 0; b < ViewData.ModelState.Values.Count(); b++)
    if (ViewData.ModelState.Values.ElementAt(b).Errors.Count() > 0)
        x.Add(ViewData.ModelState.Keys.ElementAt(b), String.Join(",", ViewData
            .ModelState.Values.ElementAt(b).Errors.Select(c => c.ErrorMessage)));

C# "as" cast vs classic cast

using as will return null if not a valid cast which allows you to do other things besides wrapping the cast in a try/catch. I hate classic cast. I always use as cast if i'm not sure. Plus, exceptions are expensive. Null checks are not.

How to find the duration of difference between two dates in java?

This is a program I wrote, which gets the number of days between 2 dates(no time here).

import java.util.Scanner;
public class HelloWorld {
 public static void main(String args[]) {
  Scanner s = new Scanner(;
  System.out.print("Enter starting date separated by dots: ");
  String inp1 = s.nextLine();
  System.out.print("Enter ending date separated by dots: ");
  String inp2 = s.nextLine();
  int[] nodim = {
  String[] inpArr1 = split(inp1);
  String[] inpArr2 = split(inp2);
  int d1 = Integer.parseInt(inpArr1[0]);
  int m1 = Integer.parseInt(inpArr1[1]);
  int y1 = Integer.parseInt(inpArr1[2]);
  int d2 = Integer.parseInt(inpArr2[0]);
  int m2 = Integer.parseInt(inpArr2[1]);
  int y2 = Integer.parseInt(inpArr2[2]);
  if (y1 % 4 == 0) nodim[2] = 29;
  int diff = m1 == m2 && y1 == y2 ? d2 - (d1 - 1) : (nodim[m1] - (d1 - 1));
  int mm1 = m1 + 1, mm2 = m2 - 1, yy1 = y1, yy2 = y2;
  for (; yy1 <= yy2; yy1++, mm1 = 1) {
   mm2 = yy1 == yy2 ? (m2 - 1) : 12;
   if (yy1 % 4 == 0) nodim[2] = 29;
   else nodim[2] = 28;
   if (mm2 == 0) {
    mm2 = 12;
    yy2 = yy2 - 1;
   for (; mm1 <= mm2 && yy1 <= yy2; mm1++) diff = diff + nodim[mm1];
  System.out.print("No. of days from " + inp1 + " to " + inp2 + " is " + diff);
 public static String[] split(String s) {
  String[] retval = {
  s = s + ".";
  s = s + " ";
  for (int i = 0; i <= 2; i++) {
   retval[i] = s.substring(0, s.indexOf("."));
   s = s.substring((s.indexOf(".") + 1), s.length());
  return retval;

How do I add 24 hours to a unix timestamp in php?

A Unix timestamp is simply the number of seconds since January the first 1970, so to add 24 hours to a Unix timestamp we just add the number of seconds in 24 hours. (24 * 60 *60)

time() + 24*60*60;

Method List in Visual Studio Code

Yes, there is the workbench.action.gotoSymbol command. On Windows and Linux it's set to CTRL+Shift+O by default.

If this command isn't available for the file types you are working with then you should take a look at the VSCode extensions. Not all languages support this feature.

How can I find a specific file from a Linux terminal?

In general, the best way to find any file in any arbitrary location is to start a terminal window and type in the classic Unix command "find":

find / -name index.html -print

Since the file you're looking for is the root file in the root directory of your web server, it's probably easier to find your web server's document root. For example, look under:


Or type:

find /var/www -name index.html -print

How to display tables on mobile using Bootstrap?

Bootstrap 3 introduces responsive tables:

<div class="table-responsive">
  <table class="table">

Bootstrap 4 is similar, but with more control via some new classes:

...responsive across all viewports ... with .table-responsive. Or, pick a maximum breakpoint with which to have a responsive table up to by using .table-responsive{-sm|-md|-lg|-xl}.

Credit to Jason Bradley for providing an example:

Responsive Tables

jQuery if Element has an ID?

Number of .parent a elements that have an id attribute:

$('.parent a[id]').length

How to create a drop shadow only on one side of an element?

Just use the spread parameter to make the shadow smaller:

.shadow {_x000D_
  -webkit-box-shadow: 0 6px 4px -4px black;_x000D_
  -moz-box-shadow: 0 6px 4px -4px black;_x000D_
  box-shadow: 0 6px 4px -4px black;_x000D_
<div class="shadow">Some content</div>

Live demo:

To not see any shadow on the sides, the (absolute value of the) spread radius (4th parameter) needs to be the same as the blur radius (3rd parameter).

How do you write multiline strings in Go?

For me this is what I use if adding \n is not a problem.

fmt.Sprintf("Hello World\nHow are you doing today\nHope all is well with your go\nAnd code")

Else you can use the raw string

multiline := `Hello Brothers and sisters of the Code
              The grail needs us.

Import error No module named skimage

OSX python3

Just run this code in your terminal:

sudo pip3 install scikit-image

If you faced any other issues please check this link for more.

How To Convert A Number To an ASCII Character?

I was googling about how to convert an int to char, that got me here. But my question was to convert for example int of 6 to char of '6'. For those who came here like me, this is how to do it:

int num = 6;

Indentation shortcuts in Visual Studio

Tab to tab right, shift-tab to tab left.

How to copy only a single worksheet to another workbook using vba

The much longer example below combines some of the useful snippets above:

  • You can specify any number of sheets you want to copy across
  • You can copy entire sheets, i.e. like dragging the tab across, or you can copy over the contents of cells as values-only but preserving formatting.

It could still do with a lot of work to make it better (better error-handling, general cleaning up), but it hopefully provides a good start.

Note that not all formatting is carried across because the new sheet uses its own theme's fonts and colours. I can't work out how to copy those across when pasting as values only.

 Option Explicit

Sub copyDataToNewFile()
    Application.ScreenUpdating = False

    ' Allow different ways of copying data:
    ' sheet = copy the entire sheet
    ' valuesWithFormatting = create a new sheet with the same name as the
    '                        original, copy values from the cells only, then
    '                        apply original formatting. Formatting is only as
    '                        good as the Paste Special > Formats command - theme
    '                        colours and fonts are not preserved.
    Dim copyMethod As String
    copyMethod = "valuesWithFormatting"

    Dim newFilename As String           ' Name (+optionally path) of new file
    Dim themeTempFilePath As String     ' To temporarily save the source file's theme

    Dim sourceWorkbook As Workbook      ' This file
    Set sourceWorkbook = ThisWorkbook

    Dim newWorkbook As Workbook         ' New file

    Dim sht As Worksheet                ' To iterate through sheets later on.
    Dim sheetFriendlyName As String     ' To store friendly sheet name
    Dim sheetCount As Long              ' To avoid having to count multiple times

    ' Sheets to copy over, using internal code names as more reliable.
    Dim colSheetObjectsToCopy As New Collection
    colSheetObjectsToCopy.Add Sheet1
    colSheetObjectsToCopy.Add Sheet2

    ' Get filename of new file from user.
        newFilename = InputBox("Please Specify the name of your new workbook." & vbCr & vbCr & "Either enter a full path or just a filename, in which case the file will be saved in the same location (" & sourceWorkbook.Path & "). Don't use the name of a workbook that is already open, otherwise this script will break.", "New Copy")
        If newFilename = "" Then MsgBox "You must enter something.", vbExclamation, "Filename needed"
    Loop Until newFilename > ""

    ' If they didn't supply a path, assume same location as the source workbook.
    ' Not perfect - simply assumes a path has been supplied if a path separator
    ' exists somewhere. Could still be a badly-formed path. And, no check is done
    ' to see if the path actually exists.
    If InStr(1, newFilename, Application.PathSeparator, vbTextCompare) = 0 Then
        newFilename = sourceWorkbook.Path & Application.PathSeparator & newFilename
    End If

    ' Create a new workbook and save as the user requested.
    ' NB This fails if the filename is the same as a workbook that's
    ' already open - it should check for this.
    Set newWorkbook = Application.Workbooks.Add(xlWBATWorksheet)
    newWorkbook.SaveAs Filename:=newFilename, _

    ' Theme fonts and colours don't get copied over with most paste-special operations.
    ' This saves the theme of the source workbook and then loads it into the new workbook.
    ' BUG: Doesn't work!
    'themeTempFilePath = Environ("temp") & Application.PathSeparator & sourceWorkbook.Name & " - Theme.xml"
    'sourceWorkbook.Theme.ThemeFontScheme.Save themeTempFilePath
    'sourceWorkbook.Theme.ThemeColorScheme.Save themeTempFilePath
    'newWorkbook.Theme.ThemeFontScheme.Load themeTempFilePath
    'newWorkbook.Theme.ThemeColorScheme.Load themeTempFilePath
    'On Error Resume Next
    'Kill themeTempFilePath  ' kill = delete in VBA-speak
    'On Error GoTo 0

    ' getWorksheetNameFromObject returns null if the worksheet object doens't
    ' exist
    For Each sht In colSheetObjectsToCopy
        sheetFriendlyName = getWorksheetNameFromObject(sourceWorkbook, sht)
        Application.StatusBar = "VBL Copying " & sheetFriendlyName
        If Not IsNull(sheetFriendlyName) Then
            Select Case copyMethod
                Case "sheet"
                    sourceWorkbook.Sheets(sheetFriendlyName).Copy _
                Case "valuesWithFormatting"
                    newWorkbook.Sheets.Add After:=newWorkbook.Sheets(newWorkbook.Sheets.count), _
                    sheetCount = newWorkbook.Sheets.count
                    newWorkbook.Sheets(sheetCount).Name = sheetFriendlyName
                    ' Copy all cells in current source sheet to the clipboard. Could copy straight
                    ' to the new workbook by specifying the Destination parameter but in this case
                    ' we want to do a paste special as values only and the Copy method doens't allow that.
                    sourceWorkbook.Sheets(sheetFriendlyName).Cells.Copy ' Destination:=newWorkbook.Sheets(newWorkbook.Sheets.Count).[A1]
                    newWorkbook.Sheets(sheetCount).[A1].PasteSpecial Paste:=xlValues
                    newWorkbook.Sheets(sheetCount).[A1].PasteSpecial Paste:=xlFormats
                    newWorkbook.Sheets(sheetCount).Tab.Color = sourceWorkbook.Sheets(sheetFriendlyName).Tab.Color
                    Application.CutCopyMode = False
            End Select
        End If
    Next sht

    Application.StatusBar = False
    Application.ScreenUpdating = True

How do I run a terminal inside of Vim?

The way that I get around this is:

  • pause Vim with Ctrl + Z,
  • play in the terminal,
  • then return to exactly where you left with Vim by just typing the command fg.

Which data type for latitude and longitude?

You can use the data type point - combines (x,y) which can be your lat / long. Occupies 16 bytes: 2 float8 numbers internally.

Or make it two columns of type float (= float8 or double precision). 8 bytes each.
Or real (= float4) if additional precision is not needed. 4 bytes each.
Or even numeric if you need absolute precision. 2 bytes for each group of 4 digits, plus 3 - 8 bytes overhead.

Read the fine manual about numeric types and geometric types.

The geometry and geography data types are provided by the additional module PostGIS and occupy one column in your table. Each occupies 32 bytes for a point. There is some additional overhead like an SRID in there. These types store (long/lat), not (lat/long).

Start reading the PostGIS manual here.

Ignore outliers in ggplot2 boxplot

If you want to force the whiskers to extend to the max and min values, you can tweak the coef argument. Default value for coef is 1.5 (i.e. default length of the whiskers is 1.5 times the IQR).

# Load package and create a dummy data frame with outliers 
#(using example from Ramnath's answer above)
df = data.frame(y = c(-100, rnorm(100), 100))

# create boxplot that includes outliers
p0 = ggplot(df, aes(y = y)) + geom_boxplot(aes(x = factor(1)))

# create boxplot where whiskers extend to max and min values
p1 = ggplot(df, aes(y = y)) + geom_boxplot(aes(x = factor(1)), coef = 500)

image of p0

image of p1

Remap values in pandas column with a dict

You can use .replace. For example:

>>> df = pd.DataFrame({'col2': {0: 'a', 1: 2, 2: np.nan}, 'col1': {0: 'w', 1: 1, 2: 2}})
>>> di = {1: "A", 2: "B"}
>>> df
  col1 col2
0    w    a
1    1    2
2    2  NaN
>>> df.replace({"col1": di})
  col1 col2
0    w    a
1    A    2
2    B  NaN

or directly on the Series, i.e. df["col1"].replace(di, inplace=True).

How do you prevent install of "devDependencies" NPM modules for Node.js (package.json)?

The new option is:

npm install --only=prod

If you want to install only devDependencies:

npm install --only=dev

How to set background color in jquery

$(this).css('background-color', 'red');

find all unchecked checkbox in jquery

$("input:checkbox:not(:checked)") Will get you the unchecked boxes.

Python + Regex: AttributeError: 'NoneType' object has no attribute 'groups'

You are getting AttributeError because you're calling groups on None, which hasn't any methods. returning None means the regex couldn't find anything matching the pattern from supplied string.

when using regex, it is nice to check whether a match has been made:

Result =, htmlString)

if Result:
    print Result.groups()

How do I style radio buttons with images - laughing smiley for good, sad smiley for bad?

another alternative is to use a form replacement script/library. They usually hide the original element and replace them with a div or span, which you can style in whatever way you like.

Examples are: (based on mootools)

Remove a folder from git tracking

From the git documentation:

Another useful thing you may want to do is to keep the file in your working tree but remove it from your staging area. In other words, you may want to keep the file on your hard drive but not have Git track it anymore. This is particularly useful if you forgot to add something to your .gitignore file and accidentally staged it, like a large log file or a bunch of .a compiled files. To do this, use the --cached option:

$ git rm --cached readme.txt

So maybe don't include the "-r"?

How to quit android application programmatically

@Sivi 's answer closes the app. But on return, if you have some child activities, another unfinished activity might be opened. I added noHistory:true to my activities so the app on return starts from MainActivity.


How to prevent XSS with HTML/PHP?

The best way to protect your input it's use htmlentities function. Example:

htmlentities($target, ENT_QUOTES, 'UTF-8');

You can get more information here.

Show current assembly instruction in GDB

There is a simple solution that consists in using stepi, which in turns moves forward by 1 asm instruction and shows the surrounding asm code.

How to find Oracle Service Name

Found here, no DBA : Checking oracle sid and database name

select * from global_name;

Repository access denied. access via a deployment key is read-only

Two step process to be able to push pull
Step1: Generate ssh key(public and private) on mac

Step2: Put private key in mac and public key in git website

below detailed steps are for mac users

Step 1: Generating keys

  1. (make sure you have git installed)
  2. open terminal and type ssh-keygen this will prompt you to enter storage location for key, you may type /Users/[machinename]/.ssh/[keyname]
  3. Next it will ask for passphrase, you can either leave it blank by pressing enter or enter some keyword to be entered again at next prompt
  4. This will have created two keys for you, private and public, with name [keyname] and [keyname].pub

Step2:pushing keys to appropriate locations[mac and remote accounts i.e Github, bitbucket, gitlab etc ]

  1. Type ssh-add -K ~/.ssh/[keyname] in terminal to add your private key to the mac
  2. Type pbcopy < ~/.ssh/[keyname].pub to copy public key to clipboard
  3. Open account settings on your respective git website and go to add key, there paste the public key copied above

Done, now you can push pull.

Can I find events bound on an element with jQuery?

I'm adding this for posterity; There's an easier way that doesn't involve writing more JS. Using the amazing firebug addon for firefox,

  1. Right click on the element and select 'Inspect element with Firebug'
  2. In the sidebar panels (shown in the screenshot), navigate to the events tab using the tiny > arrow
  3. The events tab shows the events and corresponding functions for each event
  4. The text next to it shows the function location

enter image description here

Default value to a parameter while passing by reference in C++

There is also rather dirty trick for this:

virtual const ULONG Write(ULONG &&State = 0, bool sequence = true);

In this case you have to call it with std::move:

ULONG val = 0;

It is only some funny workaround, I totally do not recommend it using in real code!

MySQL add days to a date


jQuery’s .bind() vs. .on()

The direct methods and .delegate are superior APIs to .on and there is no intention of deprecating them.

The direct methods are preferable because your code will be less stringly typed. You will get immediate error when you mistype an event name rather than a silent bug. In my opinion, it's also easier to write and read click than on("click"

The .delegate is superior to .on because of the argument's order:

$(elem).delegate( ".selector", {
    click: function() {
    mousemove: function() {
    mouseup: function() {
    mousedown: function() {

You know right away it's delegated because, well, it says delegate. You also instantly see the selector.

With .on it's not immediately clear if it's even delegated and you have to look at the end for the selector:

    click: function() {
    mousemove: function() {
    mouseup: function() {
    mousedown: function() {
}, "selector" );

Now, the naming of .bind is really terrible and is at face value worse than .on. But .delegate cannot do non-delegated events and there are events that don't have a direct method, so in a rare case like this it could be used but only because you want to make a clean separation between delegated and non-delegated events.

How to change the session timeout in PHP?

No. If you don't have access to the php.ini, you can't guarantee that changes would have any effect.

I doubt you need to extend your sessions time though.
It has pretty sensible timeout at the moment and there are no reasons to extend it.

SQL query to group by day

actually this depends on what DBMS you are using but in regular SQL convert(varchar,DateColumn,101) will change the DATETIME format to date (one day)



the magix number 101 is what date format it is converted to

PostgreSQL INSERT ON CONFLICT UPDATE (upsert) use all excluded values

Postgres hasn't implemented an equivalent to INSERT OR REPLACE. From the ON CONFLICT docs (emphasis mine):

It can be either DO NOTHING, or a DO UPDATE clause specifying the exact details of the UPDATE action to be performed in case of a conflict.

Though it doesn't give you shorthand for replacement, ON CONFLICT DO UPDATE applies more generally, since it lets you set new values based on preexisting data. For example:

INSERT INTO users (id, level)
VALUES (1, 0)
SET level = users.level + 1;

Add leading zeroes/0's to existing Excel values to certain length

I am not sure if this is new in Excel 2013, but if you right-click on the column and say "Special" there is actually a pre-defined option for ZIP Code and ZIP Code + 4. Magic.

enter image description here

In C++ check if std::vector<string> contains a certain value

  1. If your container only contains unique values, consider using std::set instead. It allows querying of set membership with logarithmic complexity.

     std::set<std::string> s;
     if (s.find("abc") != s.end()) { ...
  2. If your vector is kept sorted, use std::binary_search, it offers logarithmic complexity as well.

  3. If all else fails, fall back to std::find, which is a simple linear search.

JPA With Hibernate Error: [PersistenceUnit: JPA] Unable to build EntityManagerFactory

You don't need both hibernate.cfg.xml and persistence.xml in this case. Have you tried removing hibernate.cfg.xml and mapping everything in persistence.xml only?

But as the other answer also pointed out, this is not okay like this:

@JoinColumn(name = "categoria") 
private String id;

Didn't you want to use @Column instead?

Error:Cannot fit requested classes in a single dex file.Try supplying a main-dex list. # methods: 72477 > 65536

All I had to do was set the Minimum SDK Version to 21 in File > Project Structure > App > Flavors

C++ error: "Array must be initialized with a brace enclosed initializer"

You can't initialize arrays like this:

int cipher[Array_size][Array_size]=0;

The syntax for 2D arrays is:

int cipher[Array_size][Array_size]={{0}};

Note the curly braces on the right hand side of the initialization statement.

for 1D arrays:

int tomultiply[Array_size]={0};

Removing whitespace between HTML elements when using line breaks

Personally I like the accepted answer stating there is no exact way of doing this, not with out using a trick of some form.

To me, it is an annoying issue with at times can make you waste an hour wondering why a row of check boxes for example are not all aligned correctly.. Hence i had to have a quick google and myself check if there was a css rule that i have not remembered... but seems no :(

As for the next best answer, of using font-size... to me this is a nasty hack that will bite you later on wondering why your text is not showing.

I generally develop a lot with PHP and in the case of where i am generating a grid of check boxes, the PHP generated content removes this problem as it does not insert any spacing/breaks.

Simply, i would suggest either having to deal with the images all being on a single line together or using a server side script to generate the content/images.

Javascript reduce on array of objects

If you have a complex object with a lot of data, like an array of objects, you can take a step by step approach to solve this.

For e.g:

const myArray = [{ id: 1, value: 10}, { id: 2, value: 20}];

First, you should map your array into a new array of your interest, it could be a new array of values in this example.

const values = => obj.value);

This call back function will return a new array containing only values from the original array and store it on values const. Now your values const is an array like this:

values = [10, 20];

And now your are ready to perform your reduce:

const sum = values.reduce((accumulator, currentValue) => { return accumulator + currentValue; } , 0);

As you can see, the reduce method executes the call back function multiple times. For each time, it takes the current value of the item in the array and sum with the accumulator. So to properly sum it you need to set the initial value of your accumulator as the second argument of the reduce method.

Now you have your new const sum with the value of 30.

python: get directory two levels up

You can use this as a generic solution:

import os

def getParentDir(path, level=1):
  return os.path.normpath( os.path.join(path, *([".."] * level)) )

How to generate keyboard events?

user648852's idea at least for me works great for OS X, here is the code to do it:

#!/usr/bin/env python

import time
from Quartz.CoreGraphics import CGEventCreateKeyboardEvent
from Quartz.CoreGraphics import CGEventPost

# Python releases things automatically, using CFRelease will result in a scary error
#from Quartz.CoreGraphics import CFRelease

from Quartz.CoreGraphics import kCGHIDEventTap

# From
# and from

def KeyDown(k):
    keyCode, shiftKey = toKeyCode(k)


    if shiftKey:
        CGEventPost(kCGHIDEventTap, CGEventCreateKeyboardEvent(None, 0x38, True))

    CGEventPost(kCGHIDEventTap, CGEventCreateKeyboardEvent(None, keyCode, True))

    if shiftKey:
        CGEventPost(kCGHIDEventTap, CGEventCreateKeyboardEvent(None, 0x38, False))

def KeyUp(k):
    keyCode, shiftKey = toKeyCode(k)


    CGEventPost(kCGHIDEventTap, CGEventCreateKeyboardEvent(None, keyCode, False))

def KeyPress(k):
    keyCode, shiftKey = toKeyCode(k)


    if shiftKey:
        CGEventPost(kCGHIDEventTap, CGEventCreateKeyboardEvent(None, 0x38, True))

    CGEventPost(kCGHIDEventTap, CGEventCreateKeyboardEvent(None, keyCode, True))

    CGEventPost(kCGHIDEventTap, CGEventCreateKeyboardEvent(None, keyCode, False))

    if shiftKey:
        CGEventPost(kCGHIDEventTap, CGEventCreateKeyboardEvent(None, 0x38, False))

# From

def toKeyCode(c):
    shiftKey = False
    # Letter
    if c.isalpha():
        if not c.islower():
            shiftKey = True
            c = c.lower()

    if c in shiftChars:
        shiftKey = True
        c = shiftChars[c]
    if c in keyCodeMap:
        keyCode = keyCodeMap[c]
        keyCode = ord(c)
    return keyCode, shiftKey

shiftChars = {
    '~': '`',
    '!': '1',
    '@': '2',
    '#': '3',
    '$': '4',
    '%': '5',
    '^': '6',
    '&': '7',
    '*': '8',
    '(': '9',
    ')': '0',
    '_': '-',
    '+': '=',
    '{': '[',
    '}': ']',
    '|': '\\',
    ':': ';',
    '"': '\'',
    '<': ',',
    '>': '.',
    '?': '/'

keyCodeMap = {
    'a'                 : 0x00,
    's'                 : 0x01,
    'd'                 : 0x02,
    'f'                 : 0x03,
    'h'                 : 0x04,
    'g'                 : 0x05,
    'z'                 : 0x06,
    'x'                 : 0x07,
    'c'                 : 0x08,
    'v'                 : 0x09,
    'b'                 : 0x0B,
    'q'                 : 0x0C,
    'w'                 : 0x0D,
    'e'                 : 0x0E,
    'r'                 : 0x0F,
    'y'                 : 0x10,
    't'                 : 0x11,
    '1'                 : 0x12,
    '2'                 : 0x13,
    '3'                 : 0x14,
    '4'                 : 0x15,
    '6'                 : 0x16,
    '5'                 : 0x17,
    '='                 : 0x18,
    '9'                 : 0x19,
    '7'                 : 0x1A,
    '-'                 : 0x1B,
    '8'                 : 0x1C,
    '0'                 : 0x1D,
    ']'                 : 0x1E,
    'o'                 : 0x1F,
    'u'                 : 0x20,
    '['                 : 0x21,
    'i'                 : 0x22,
    'p'                 : 0x23,
    'l'                 : 0x25,
    'j'                 : 0x26,
    '\''                : 0x27,
    'k'                 : 0x28,
    ';'                 : 0x29,
    '\\'                : 0x2A,
    ','                 : 0x2B,
    '/'                 : 0x2C,
    'n'                 : 0x2D,
    'm'                 : 0x2E,
    '.'                 : 0x2F,
    '`'                 : 0x32,
    'k.'                : 0x41,
    'k*'                : 0x43,
    'k+'                : 0x45,
    'kclear'            : 0x47,
    'k/'                : 0x4B,
    'k\n'               : 0x4C,
    'k-'                : 0x4E,
    'k='                : 0x51,
    'k0'                : 0x52,
    'k1'                : 0x53,
    'k2'                : 0x54,
    'k3'                : 0x55,
    'k4'                : 0x56,
    'k5'                : 0x57,
    'k6'                : 0x58,
    'k7'                : 0x59,
    'k8'                : 0x5B,
    'k9'                : 0x5C,

    # keycodes for keys that are independent of keyboard layout
    '\n'                : 0x24,
    '\t'                : 0x30,
    ' '                 : 0x31,
    'del'               : 0x33,
    'delete'            : 0x33,
    'esc'               : 0x35,
    'escape'            : 0x35,
    'cmd'               : 0x37,
    'command'           : 0x37,
    'shift'             : 0x38,
    'caps lock'         : 0x39,
    'option'            : 0x3A,
    'ctrl'              : 0x3B,
    'control'           : 0x3B,
    'right shift'       : 0x3C,
    'rshift'            : 0x3C,
    'right option'      : 0x3D,
    'roption'           : 0x3D,
    'right control'     : 0x3E,
    'rcontrol'          : 0x3E,
    'fun'               : 0x3F,
    'function'          : 0x3F,
    'f17'               : 0x40,
    'volume up'         : 0x48,
    'volume down'       : 0x49,
    'mute'              : 0x4A,
    'f18'               : 0x4F,
    'f19'               : 0x50,
    'f20'               : 0x5A,
    'f5'                : 0x60,
    'f6'                : 0x61,
    'f7'                : 0x62,
    'f3'                : 0x63,
    'f8'                : 0x64,
    'f9'                : 0x65,
    'f11'               : 0x67,
    'f13'               : 0x69,
    'f16'               : 0x6A,
    'f14'               : 0x6B,
    'f10'               : 0x6D,
    'f12'               : 0x6F,
    'f15'               : 0x71,
    'help'              : 0x72,
    'home'              : 0x73,
    'pgup'              : 0x74,
    'page up'           : 0x74,
    'forward delete'    : 0x75,
    'f4'                : 0x76,
    'end'               : 0x77,
    'f2'                : 0x78,
    'page down'         : 0x79,
    'pgdn'              : 0x79,
    'f1'                : 0x7A,
    'left'              : 0x7B,
    'right'             : 0x7C,
    'down'              : 0x7D,
    'up'                : 0x7E

Gradle DSL method not found: 'runProguard'

enter image description hereIf you are using version 0.14.0 or higher of the gradle plugin, you should replace "runProguard" with "minifyEnabled" in your build.gradle files.

runProguard was renamed to minifyEnabled in version 0.14.0. For more info, See Android Build System

How to remove a build from itunes connect?

Dang this is hard. Here is what I did to reject/delete/replace my ios build before it was released. The app was approved how ever I found found a bug I wanted to fix before releasing

  1. I set release to "manual" and saved
  2. I tried to create and app release
  3. got an error message something like "you can only have one release at a time"
  4. where the save button was there was not an option to cancel release
  5. the version of the app is not marked "developer rejected" with a red dot

To replace the bad build I did the following

  1. if you click on the "+ version or platform" to create a new version you will not be be able to create a new iOS version
  2. you need to upload a new build
  3. in your rejected app, select the new build
  4. save
  5. submit for review

Connecting to SQL Server with Visual Studio Express Editions

The only way I was able to get C# Express 2008 to work was to move the database file. So, I opened up SQL Server Management Studio and after dropping the database, I copied the file to my project folder. Then I reattached the database to management studio. Now, when I try to attach to the local copy it works. Apparently, you can not use the same database file more than once.

Tensorflow import error: No module named 'tensorflow'

I had same issues on Windows 64-bit processor but manage to solve them. Check if your Python is for 32- or 64-bit installation. If it is for 32-bit, then you should download the executable installer (for e.g. you can choose latest Python version - for me is 3.7.3) -> Scroll to the bottom in Files section and select “Windows x86-64 executable installer”. Download and install it.

The tensorflow installation steps check here : . I hope this helps somehow ...

How to connect to a secure website using SSL in Java with a pkcs12 file?

This example shows how you can layer SSL on top of an existing socket, obtaining the client cert from a PKCS#12 file. It is appropriate when you need to connect to an upstream server via a proxy, and you want to handle the full protocol by yourself.

Essentially, however, once you have the SSL Context, you can apply it to an HttpsURLConnection, etc, etc.

KeyStore ks = KeyStore.getInstance("PKCS12");
InputStream is = ...;
char[] ksp = storePassword.toCharArray();
ks.load(is, ksp);
KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
char[] kp = keyPassword.toCharArray();
kmf.init(ks, kp);
sslContext = SSLContext.getInstance("SSLv3");
sslContext.init(kmf.getKeyManagers(), null, null);
SSLSocketFactory factory = sslContext.getSocketFactory();
SSLSocket sslsocket = (SSLSocket) factory.createSocket(socket, socket
    .getInetAddress().getHostName(), socket.getPort(), true);

Getting the last argument passed to a shell script

From oldest to newer solutions:

The most portable solution, even older sh (works with spaces and glob characters) (no loop, faster):

eval printf "'%s\n'" "\"\${$#}\""

Since version 2.01 of bash

$ set -- The quick brown fox jumps over the lazy dog

$ printf '%s\n'     "${!#}     ${@:(-1)} ${@: -1} ${@:~0} ${!#}"
dog     dog dog dog dog

For ksh, zsh and bash:

$ printf '%s\n' "${@: -1}    ${@:~0}"     # the space beetwen `:`
                                          # and `-1` is a must.
dog   dog

And for "next to last":

$ printf '%s\n' "${@:~1:1}"

Using printf to workaround any issues with arguments that start with a dash (like -n).

For all shells and for older sh (works with spaces and glob characters) is:

$ set -- The quick brown fox jumps over the lazy dog "the * last argument"

$ eval printf "'%s\n'" "\"\${$#}\""
The last * argument

Or, if you want to set a last var:

$ eval last=\${$#}; printf '%s\n' "$last"
The last * argument

And for "next to last":

$ eval printf "'%s\n'" "\"\${$(($#-1))}\""

Use NSInteger as array index

According to the error message, you declared myLoc as a pointer to an NSInteger (NSInteger *myLoc) rather than an actual NSInteger (NSInteger myLoc). It needs to be the latter.

using jQuery .animate to animate a div from right to left?

I think the reason it doesn't work has something to do with the fact that you have the right position set, but not the left.

If you manually set the left to the current position, it seems to go:

Live example:

var left = $('#coolDiv').offset().left;  // Get the calculated left position

$("#coolDiv").css({left:left})  // Set the left to its calculated position
             .animate({"left":"0px"}, "slow");


Appears as though Firefox behaves as expected because its calculated left position is available as the correct value in pixels, whereas Webkit based browsers, and apparently IE, return a value of auto for the left position.

Because auto is not a starting position for an animation, the animation effectively runs from 0 to 0. Not very interesting to watch. :o)

Setting the left position manually before the animate as above fixes the issue.

If you don't like cluttering the landscape with variables, here's a nice version of the same thing that obviates the need for a variable:

$("#coolDiv").css('left', function(){ return $(this).offset().left; })
             .animate({"left":"0px"}, "slow");    ?

Argparse optional positional arguments?

As an extension to @VinaySajip answer. There are additional nargs worth mentioning.

  1. parser.add_argument('dir', nargs=1, default=os.getcwd())

N (an integer). N arguments from the command line will be gathered together into a list

  1. parser.add_argument('dir', nargs='*', default=os.getcwd())

'*'. All command-line arguments present are gathered into a list. Note that it generally doesn't make much sense to have more than one positional argument with nargs='*', but multiple optional arguments with nargs='*' is possible.

  1. parser.add_argument('dir', nargs='+', default=os.getcwd())

'+'. Just like '*', all command-line args present are gathered into a list. Additionally, an error message will be generated if there wasn’t at least one command-line argument present.

  1. parser.add_argument('dir', nargs=argparse.REMAINDER, default=os.getcwd())

argparse.REMAINDER. All the remaining command-line arguments are gathered into a list. This is commonly useful for command line utilities that dispatch to other command line utilities

If the nargs keyword argument is not provided, the number of arguments consumed is determined by the action. Generally this means a single command-line argument will be consumed and a single item (not a list) will be produced.

Edit (copied from a comment by @Acumenus) nargs='?' The docs say: '?'. One argument will be consumed from the command line if possible and produced as a single item. If no command-line argument is present, the value from default will be produced.

How do I get the path of the assembly the code is in?

I believe this would work for any kind of application:

AppDomain.CurrentDomain.RelativeSearchPath ?? AppDomain.CurrentDomain.BaseDirectory

Matplotlib figure facecolor (background color)

savefig has its own parameter for facecolor. I think an even easier way than the accepted answer is to set them globally just once, instead of putting facecolor=fig.get_facecolor() every time:


Insert into ... values ( SELECT ... FROM ... )

Both the answers I see work fine in Informix specifically, and are basically standard SQL. That is, the notation:

INSERT INTO target_table[(<column-list>)] SELECT ... FROM ...;

works fine with Informix and, I would expect, all the DBMS. (Once upon 5 or more years ago, this is the sort of thing that MySQL did not always support; it now has decent support for this sort of standard SQL syntax and, AFAIK, it would work OK on this notation.) The column list is optional but indicates the target columns in sequence, so the first column of the result of the SELECT will go into the first listed column, etc. In the absence of the column list, the first column of the result of the SELECT goes into the first column of the target table.

What can be different between systems is the notation used to identify tables in different databases - the standard has nothing to say about inter-database (let alone inter-DBMS) operations. With Informix, you can use the following notation to identify a table:


That is, you may specify a database, optionally identifying the server that hosts that database if it is not in the current server, followed by an optional owner, dot, and finally the actual table name. The SQL standard uses the term schema for what Informix calls the owner. Thus, in Informix, any of the following notations could identify a table:


The owner in general does not need to be quoted; however, if you do use quotes, you need to get the owner name spelled correctly - it becomes case-sensitive. That is:


all identify the same table. With Informix, there's a mild complication with MODE ANSI databases, where owner names are generally converted to upper-case (informix is the exception). That is, in a MODE ANSI database (not commonly used), you could write:

CREATE TABLE someone.table ( ... )

and the owner name in the system catalog would be "SOMEONE", rather than 'someone'. If you enclose the owner name in double quotes, it acts like a delimited identifier. With standard SQL, delimited identifiers can be used many places. With Informix, you can use them only around owner names -- in other contexts, Informix treats both single-quoted and double-quoted strings as strings, rather than separating single-quoted strings as strings and double-quoted strings as delimited identifiers. (Of course, just for completeness, there is an environment variable, DELIMIDENT, that can be set - to any value, but Y is safest - to indicate that double quotes always surround delimited identifiers and single quotes always surround strings.)

Note that MS SQL Server manages to use [delimited identifiers] enclosed in square brackets. It looks weird to me, and is certainly not part of the SQL standard.

How do I load an HTTP URL with App Transport Security enabled in iOS 9?

Here's what worked for me:

        <key><!-- / localhost --></key>
    <!-- add more domain here -->

I just wanna add this to help others and save some time:

if you are using: CFStreamCreatePairWithSocketToHost. make sure your host is the same with what you have in your .plist or if you have separate domain for socket just add it there.

CFStreamCreatePairWithSocketToHost(NULL, (__bridge CFStringRef)/*from .plist*/, (unsigned int)port, &readStream, &writeStream);

Hope this is helpful. Cheers. :)

How can I get the current stack trace in Java?

In Java 9 there is a new way:

public static void showTrace() {

  List<StackFrame> frames =
    StackWalker.getInstance( Option.RETAIN_CLASS_REFERENCE )
               .walk( stream  -> stream.collect( Collectors.toList() ) );

  for ( StackFrame stackFrame : frames )
    System.out.println( stackFrame );

a href link for entire div in HTML/CSS

Do it like this:

Parentdivimage should have specified width and height, and its position should be:

position: relative;

Just inside the parentdivimage, next to other divs that parent contains you should put:

<a href=""><span class="clickable"></span></a>

Then in css file:

.clickable {
  height: 100%;
  width: 100%;
  left: 0;
  top: 0;
  position: absolute;     
  z-index: 1;

The span tag will fill out its parent block which is parentdiv, because of height and width set to 100%. Span will be on the top of all of surrounding elements because of setting z-index higher than other elements. Finally span will be clickable, because it's inside of an 'a' tag.

Android - How to get application name? (Not package name)

In Kotlin, use the following codes to get Application Name:

        // Get App Name
        var appName: String = ""
        val applicationInfo = this.getApplicationInfo()
        val stringId = applicationInfo.labelRes
        if (stringId == 0) {
            appName = applicationInfo.nonLocalizedLabel.toString()
        else {
            appName = this.getString(stringId)

How do I set up IntelliJ IDEA for Android applications?

Another way to identify the correct SDK is to install Android Studio, create a new project, go to project structure, SDK Location and find where the SDK was installed.

I found using the default installation process on a mac that the SDK home folder was in the /Users/'yourUser'/Library/Android/sdk folder. Make sure you have enabled your Mac to view the Library folder.

When is it acceptable to call GC.Collect?

I use GC.Collect only when writing crude performance/profiler test rigs; i.e. I have two (or more) blocks of code to test - something like:

GC.Collect(GC.MaxGeneration, GCCollectionMode.Forced);
TestA(); // may allocate lots of transient objects
GC.Collect(GC.MaxGeneration, GCCollectionMode.Forced);
TestB(); // may allocate lots of transient objects
GC.Collect(GC.MaxGeneration, GCCollectionMode.Forced);

So that TestA() and TestB() run with as similar state as possible - i.e. TestB() doesn't get hammered just because TestA left it very close to the tipping point.

A classic example would be a simple console exe (a Main method sort-enough to be posted here for example), that shows the difference between looped string concatenation and StringBuilder.

If I need something precise, then this would be two completely independent tests - but often this is enough if we just want to minimize (or normalize) the GC during the tests to get a rough feel for the behaviour.

During production code? I have yet to use it ;-p

How do I convert from a string to an integer in Visual Basic?

You can use the following to convert string to int:

  • CInt(String) for ints
  • CDec(String) for decimals

For details refer to Type Conversion Functions (Visual Basic).

SyntaxError: expected expression, got '<'

I had same error. And in my case

REASON: There was restriction to that resources on server and server was sending login page instead of javascript pages.

SOLUTION: give access to user for resourses or remove restriction at all.

Downloading and unzipping a .zip file without writing to disk

Below is a code snippet I used to fetch zipped csv file, please have a look:

Python 2:

from StringIO import StringIO
from zipfile import ZipFile
from urllib import urlopen

resp = urlopen("")
zipfile = ZipFile(StringIO(
for line in
    print line

Python 3:

from io import BytesIO
from zipfile import ZipFile
from urllib.request import urlopen
# or: requests.get(url).content

resp = urlopen("")
zipfile = ZipFile(BytesIO(
for line in

Here file is a string. To get the actual string that you want to pass, you can use zipfile.namelist(). For instance,

resp = urlopen('')
zipfile = ZipFile(BytesIO(
# ['bbc.classes', '', 'bbc.mtx', 'bbc.terms']

Moving items around in an ArrayList

To move up, remove and then add.

To remove - ArrayList.remove and assign the returned object to a variable
Then add this object back at the required index -ArrayList.add(int index, E element), E)

DateTime to javascript date

With Moment.js simply use:

var jsDate = moment(netDateTime).toDate();

Where netDateTime is your DateTime variable serialized, something like "/Date(1456956000000+0200)/".

Android: Center an image

This worked for me

        android:orientation="horizontal" >

            android:src="@drawable/logo" />


The request was rejected because no multipart boundary was found in springboot

The "Postman - REST Client" is not suitable for doing post action with setting content-type.You can try to use "Advanced REST client" or others.

Additionally, headers was replace by consumes and produces since Spring 3.1 M2, see And you can directly use produces = MediaType.MULTIPART_FORM_DATA_VALUE.

How to set time delay in javascript

you can use of promise

function sleep(ms) {
  return new Promise(resolve => setTimeout(resolve, ms));


sleep(2000).then(() => { console.log("World!"); });


await sleep(2000);

compareTo() vs. equals()

  • equals: required for checking equality and restricting duplicates. Many classes of Java Library use this in case they wanted to find duplicates. e.g. HashSet.add(ob1) will only add if that doesn't exist. So if you are extending some classes like this then override equals().

  • compareTo: required for ordering of element. Again for stable sorting you require equality, so there is a return 0.

Current time in microseconds in java


Java 9 and later: Up to nanoseconds resolution when capturing the current moment. That’s 9 digits of decimal fraction.   


To limit to microseconds, truncate.

Instant                // Represent a moment in UTC. 
.now()                 // Capture the current moment. Returns a `Instant` object. 
.truncatedTo(          // Lop off the finer part of this moment. 
    ChronoUnit.MICROS  // Granularity to which we are truncating. 
)                      // Returns another `Instant` object rather than changing the original, per the immutable objects pattern. 


In practice, you will see only microseconds captured with .now as contemporary conventional computer hardware clocks are not accurate in nanoseconds.


The other Answers are somewhat outdated as of Java 8.


Java 8 and later comes with the java.time framework. These new classes supplant the flawed troublesome date-time classes shipped with the earliest versions of Java such as java.util.Date/.Calendar and java.text.SimpleDateFormat. The framework is defined by JSR 310, inspired by Joda-Time, extended by the ThreeTen-Extra project.

The classes in java.time resolve to nanoseconds, much finer than the milliseconds used by both the old date-time classes and by Joda-Time. And finer than the microseconds asked in the Question.

enter image description here

Clock Implementation

While the java.time classes support data representing values in nanoseconds, the classes do not yet generate values in nanoseconds. The now() methods use the same old clock implementation as the old date-time classes, System.currentTimeMillis(). We have the new Clock interface in java.time but the implementation for that interface is the same old milliseconds clock.

So you could format the textual representation of the result of ZoneId.of( "America/Montreal" ) ) to see nine digits of a fractional second but only the first three digits will have numbers like this:


New Clock In Java 9

The OpenJDK and Oracle implementations of Java 9 have a new default Clock implementation with finer granularity, up to the full nanosecond capability of the java.time classes.

See the OpenJDK issue, Increase the precision of the implementation of java.time.Clock.systemUTC(). That issue has been successfully implemented.


On a MacBook Pro (Retina, 15-inch, Late 2013) with macOS Sierra, I get the current moment in microseconds (up to six digits of decimal fraction).


Hardware Clock

Remember that even with a new finer Clock implementation, your results may vary by computer. Java depends on the underlying computer hardware’s clock to know the current moment.

  • The resolution of the hardware clocks vary widely. For example, if a particular computer’s hardware clock supports only microseconds granularity, any generated date-time values will have only six digits of fractional second with the last three digits being zeros.
  • The accuracy of the hardware clocks vary widely. Just because a clock generates a value with several digits of decimal fraction of a second, those digits may be inaccurate, just approximations, adrift from actual time as might be read from an atomic clock. In other words, just because you see a bunch of digits to the right of the decimal mark does not mean you can trust the elapsed time between such readings to be true to that minute degree.

Store text file content line by line into array

The simplest solution:

List<String> list = Files.readAllLines(Paths.get("path/of/text"), StandardCharsets.UTF_8);
String[] a = list.toArray(new String[list.size()]); 

Note that java.nio.file.Files is since 1.7

adding 30 minutes to datetime php/mysql

If you are using MySQL you can do it like this:

SELECT '2008-12-31 23:59:59' + INTERVAL 30 MINUTE;

For a pure PHP solution use strtotime

strtotime('+ 30 minute',$yourdate);

Simple UDP example to send and receive data from same socket

I'll try to keep this short, I've done this a few months ago for a game I was trying to build, it does a UDP "Client-Server" connection that acts like TCP, you can send (message) (message + object) using this. I've done some testing with it and it works just fine, feel free to modify it if needed.

How to use PHP with Visual Studio

Maybe we should help you with a big misunderstanding on your side first: PHP is (like ASP.NET or whatever you used to far) a server side language while javascript is client side.

This means that PHP will run on your webserver and create a HTML page dynamically which is then sent to the browser. Javascript in turn is embedded (either directly or as a referenced file) into this HTML page and runs in the browser.

Maybe you can now understand why your approach so far could never work out.

Embed Google Map code in HTML with marker

Learning Google's JavaScript library is a good option. If you don't feel like getting into coding you might find Maps Engine Lite useful.

It is a tool recently published by Google where you can create your personal maps (create markers, draw geometries and adapt the colors and styles).

Here is an useful tutorial I found: Quick Tip: Embedding New Google Maps

What are all the differences between src and data-src attributes?

The first <img /> is invalid - src is a required attribute. data-src is an attribute than can be leveraged by, say, JavaScript, but has no presentational meaning.

Can we have functions inside functions in C++?

No, it's not allowed. Neither C nor C++ support this feature by default, however TonyK points out (in the comments) that there are extensions to the GNU C compiler that enable this behavior in C.

Basic text editor in command prompt?

There is one built into windows 7 in which you can open by clicking the windows and r keys at the same time and then typing

I hope this helped

How to set a variable to be "Today's" date in Python/Pandas

i got the same problem so tried so many things but finally this is the solution.

import time 

print (time.strftime("%d/%m/%Y"))

What is the difference between square brackets and parentheses in a regex?

Your team's advice is almost right, except for the mistake that was made. Once you find out why, you will never forget it. Take a look at this mistake.


What this does:

  • ^ and $ denotes anchored matches, which asserts that the subpattern in between these anchors are the entire match. The string will only match if the subpattern matches the entirety of it, not just a section.
  • () denotes a capturing group.
  • 7|8|9 denotes matching either of 7, 8, or 9. It does this with alternations, which is what the pipe operator | does — alternating between alternations. This backtracks between alternations: If the first alternation is not matched, the engine has to return before the pointer location moved during the match of the alternation, to continue matching the next alternation; Whereas the character class can advance sequentially. See this match on a regex engine with optimizations disabled:
Pattern: (r|f)at
Match string: carat


Pattern: [rf]at
Match string: carat


  • \d{9} matches nine digits. \d is a shorthanded metacharacter, which matches any digits.

Look at what it does:

  • ^ and $ denotes anchored matches as well.
  • [7|8|9] is a character class. Any characters from the list 7, |, 8, |, or 9 can be matched, thus the | was added in incorrectly. This matches without backtracking.
  • [\d] is a character class that inhabits the metacharacter \d. The combination of the use of a character class and a single metacharacter is a bad idea, by the way, since the layer of abstraction can slow down the match, but this is only an implementation detail and only applies to a few of regex implementations. JavaScript is not one, but it does make the subpattern slightly longer.
  • {9} indicates the previous single construct is repeated nine times in total.

The optimal regex is /^[789]\d{9}$/, because /^(7|8|9)\d{9}$/ captures unnecessarily which imposes a performance decrease on most regex implementations ( happens to be one, considering the question uses keyword var in code, this probably is JavaScript). The use of which runs on PCRE for preg matching will optimize away the lack of backtracking, however we're not in PHP either, so using classes [] instead of alternations | gives performance bonus as the match does not backtrack, and therefore both matches and fails faster than using your previous regular expression.

Best/Most Comprehensive API for Stocks/Financial Data

Last I looked -- a couple of years ago -- there wasn't an easy option and the "solution" (which I did not agree with) was screen-scraping a number of websites. It may be easier now but I would still be surprised to see something, well, useful.

The problem here is that the data is immensely valuable (and very expensive), so while defining a method of retrieving it would be easy, getting the trading venues to part with their data would be next to impossible. Some of the MTFs (currently) provide their data for free but I'm not sure how you would get it without paying someone else, like Reuters, for it.

How to properly -filter multiple strings in a PowerShell copy script

-Filter only accepts a single string. -Include accepts multiple values, but qualifies the -Path argument. The trick is to append \* to the end of the path, and then use -Include to select multiple extensions. BTW, quoting strings is unnecessary in cmdlet arguments unless they contain spaces or shell special characters.

Get-ChildItem $originalPath\* -Include *.gif, *.jpg, *.xls*, *.doc*, *.pdf*, *.wav*, .ppt*

Note that this will work regardless of whether $originalPath ends in a backslash, because multiple consecutive backslashes are interpreted as a single path separator. For example, try:

Get-ChildItem C:\\\\\Windows

Windows ignores JAVA_HOME: how to set JDK as default?

I had Java 7 and 8 installed and I want to redirect to java 7 but the java version in my cmd prompt window shows Java 8.
Added Java 7 bin directory path (C:\Program Files\Java\jdk1.7.0_10\bin) to PATH variable at the end, but did not work out and shows Java 8. So I changed the Java 7 path to the starting of the path value and it worked.
Opened a new cmd prompt window and checked my java version and now it shows Java 7

iOS 7 - Failing to instantiate default view controller

First click on the View Controller in the right hand side Utilities bar. Next select the Attributes Inspector and make sure that under the View Controller section the 'Is Initial View Controller' checkbox is checked!

How do I import a .dmp file into Oracle?

I am Using Oracle Database Express Edition 11g Release 2.

Follow the Steps:

Open run SQl Command Line

Step 1: Login as system user

       SQL> connect system/tiger

Step 2 : SQL> CREATE USER UserName IDENTIFIED BY Password;

Step 3 : SQL> grant dba to UserName ;


Step 5:

             DATAFILE 'tbs_perm_03.dat'
             SIZE 8G
             AUTOEXTEND ON;

Open Command Prompt in Windows or Terminal in Ubuntu. Then Type:

Note : if you Use Ubuntu then replace " \" to " /" in path.

Step 6: C:\> imp UserName/password@localhost file=D:\abc\xyz.dmp log=D:\abc\abc_1.log full=y;


I hope you Find Right solution here.


Override console.log(); for production

I use something similar to what posit labs does. Save the console in a closure and you have it all in one portable function.

var GlobalDebug = (function () {
    var savedConsole = console;
    return function(debugOn,suppressAll){
        var suppress = suppressAll || false;
        if (debugOn === false) {
            console = {};
            console.log = function () { };
            if(suppress) {
       = function () { };
                console.warn = function () { };
                console.error = function () { };
            } else {
                console.warn = savedConsole.warn;
                console.error = savedConsole.error;              
        } else {
            console = savedConsole;

Just do globalDebug(false) to toggle log messages off or globalDebug(false,true) to remove all console messages.

How to load a xib file in a UIView

I created a sample project on github to load a UIView from a .xib file inside another .xib file. Or you can do it programmatically.

This is good for little widgets you want to reuse on different UIViewController objects.

  1. New Approach:
  2. Original Approach:

Load a Custom UIView from .xib file

Javascript Date Validation ( DD/MM/YYYY) & Age Checking

You have used regular expression for this format : DD - MM- YYYY

If you need this format DD/MM/YYYY use

var pattern =/^([0-9]{2})\/([0-9]{2})\/([0-9]{4})$/;

How to pass values across the pages in without using Session

You can pass values from one page to another by followings..

Application Variables





string Name = Request.QueryString["Name"];



HttpCookie cookName = new HttpCookie("Name");
cookName.Value = "Pandian"; 


string name = Request.Cookies["Name"].Value;

Application Variables


Application["Name"] = "pandian";


string Name = Application["Name"].ToString();

Refer the full content here : Pass values from one to another

jQuery toggle animation

            height: "150", 
            padding:"20px 0",
        }, 500);
            //otherdiv properties here
        }, 500);
            height: "0", 
            padding:"0px 0",
        }, 500);     
            //otherdiv properties here
        }, 500);

How to render a PDF file in Android

public class MyPdfViewActivity extends Activity {

  protected void onCreate(Bundle savedInstanceState) {
    WebView mWebView=new WebView(MyPdfViewActivity.this);

Getting multiple keys of specified value of a generic Dictionary?

As a twist of the accepted answer ( assuming that the keys will be associated with signle values in the dictionary. Similar to ( but a bit more elegant. The novelty is in that the consuming class can be used as an enumeration alternative (but for strings too) and that the dictionary implements IEnumerable.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;

namespace MyApp.Dictionaries

    class BiDictionary<TFirst, TSecond> : IEnumerable
        IDictionary<TFirst, TSecond> firstToSecond = new Dictionary<TFirst, TSecond>();
        IDictionary<TSecond, TFirst> secondToFirst = new Dictionary<TSecond, TFirst>();

        public void Add(TFirst first, TSecond second)
            firstToSecond.Add(first, second);
            secondToFirst.Add(second, first);

        public TSecond this[TFirst first]
            get { return GetByFirst(first); }

        public TFirst this[TSecond second]
            get { return GetBySecond(second); }

        public TSecond GetByFirst(TFirst first)
            return firstToSecond[first];

        public TFirst GetBySecond(TSecond second)
            return secondToFirst[second];

        public IEnumerator GetEnumerator()
            return GetFirstEnumerator();

        public IEnumerator GetFirstEnumerator()
            return firstToSecond.GetEnumerator();

        public IEnumerator GetSecondEnumerator()
            return secondToFirst.GetEnumerator();

And as a consuming class you could have

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace MyApp.Dictionaries
    class Greek

        public static readonly string Alpha = "Alpha";
        public static readonly string Beta = "Beta";
        public static readonly string Gamma = "Gamma";
        public static readonly string Delta = "Delta";

        private static readonly BiDictionary<int, string> Dictionary = new BiDictionary<int, string>();

        static Greek() {
            Dictionary.Add(1, Alpha);
            Dictionary.Add(2, Beta);
            Dictionary.Add(3, Gamma);
            Dictionary.Add(4, Delta);

        public static string getById(int id){
            return Dictionary.GetByFirst(id);

        public static int getByValue(string value)
            return Dictionary.GetBySecond(value);


are there dictionaries in javascript like python?

There were no real associative arrays in Javascript until 2015 (release of ECMAScript 6). Since then you can use the Map object as Robocat states. Look up the details in MDN. Example:

let map = new Map();
map.set('key', {'value1', 'value2'});
let values = map.get('key');

Without support for ES6 you can try using objects:

var x = new Object();
x["Key"] = "Value";

However with objects it is not possible to use typical array properties or methods like array.length. At least it is possible to access the "object-array" in a for-in-loop.

How do I keep jQuery UI Accordion collapsed by default?

Add the active: false option (documentation)..

$("#accordion").accordion({ header: "h3", collapsible: true, active: false });

Change MySQL root password in phpMyAdmin

you can use this command

 mysql> UPDATE mysql.user SET Password=PASSWORD('Your new Password') WHERE User='root';

check the links

Find your file under the phpMyAdmin installation directory and update the line that looks like

$cfg['Servers'][$i]['password']      = 'password';

... to this:

 $cfg['Servers'][$i]['password']      = 'newpassword';

Spring Boot application in eclipse, the Tomcat connector configured to listen on port XXXX failed to start

The easier way to solve this is changing the port on the file;

enter image description here


JMS Topic vs Queues

TOPIC:: topic is one to many communication... (multipoint or publish/subscribe) EX:-imagine a publisher publishes the movie in the youtub then all its subscribers will gets notification.... QUEVE::queve is one-to-one communication ... Ex:-When publish a request for recharge it will go to only one qreciever ... always remember if request goto all qreceivers then multiple recharge happened so while developing analyze which is fit for a application

How to show x and y axes in a MATLAB graph?

Inspired by @Luisa's answer, I made a function, axes0

x = linspace(-2,2,101);

Example output for axes0

You can follow the link above to download the function and get more details on usage

Import data.sql MySQL Docker Container

You can import database afterwards:

docker exec -i mysql-container mysql -uuser -ppassword name_db < data.sql

Swift - How to convert String to Double

As of Swift 1.1, you can directly pass String to const char * parameter.

import Foundation

let str = "123.4567"
let num = atof(str) // -> 123.4567

atof("123.4567fubar") // -> 123.4567

If you don't like deprecated atof:

strtod("765.4321", nil) // -> 765.4321

One caveat: the behavior of conversion is different from NSString.doubleValue.

atof and strtod accept 0x prefixed hex string:

atof("0xffp-2") // -> 63.75
atof("12.3456e+2") // -> 1,234.56
atof("nan") // -> (not a number)
atof("inf") // -> (+infinity)

If you prefer .doubleValue behavior, we can still use CFString bridging:

let str = "0xff"
atof(str)                      // -> 255.0
strtod(str, nil)               // -> 255.0
CFStringGetDoubleValue(str)    // -> 0.0
(str as NSString).doubleValue  // -> 0.0 Trust anchor for certification path not found

The reason this occur is the JVM/Dalvik haven't not confidence in the CA certificates in the system or in the user certificate stores.

To fix this with Retrofit, If you are used okhttp, with another client it's very similar.
You've to do:

A). Create a cert store contain public Key of CA. To do this you need to launch next script for *nix. You need openssl install in your machine, and download from the jar bcprov-jdk16-1.46.jar. Download this version not other, the version 1.5x is not compatible with android 4.0.4.


if [ -z $1 ]; then
  echo "Usage: cert2Android<CA cert PEM file>"
  exit 1


ALIAS=`openssl x509 -inform PEM -subject_hash -noout -in $CACERT`

if [ -f $TRUSTSTORE ]; then
    rm $TRUSTSTORE || exit 1

echo "Adding certificate to $TRUSTSTORE..."
keytool -import -v -trustcacerts -alias $ALIAS \
      -file $CACERT \
      -keystore $TRUSTSTORE -storetype BKS \
      -providerclass org.bouncycastle.jce.provider.BouncyCastleProvider \
      -providerpath $BCJAR \
      -storepass secret

echo "" 
echo "Added '$CACERT' with alias '$ALIAS' to $TRUSTSTORE..."

B). Copy the file truststore mytruststore.bks in res/raw of your project truststore location

C). Setting SSLContext of the connection:

okHttpClient = new OkHttpClient();
try {
    KeyStore ksTrust = KeyStore.getInstance("BKS");
    InputStream instream = context.getResources().openRawResource(R.raw.mytruststore);
    ksTrust.load(instream, "secret".toCharArray());

    // TrustManager decides which certificate authorities to use.
    TrustManagerFactory tmf = TrustManagerFactory
    SSLContext sslContext = SSLContext.getInstance("TLS");
    sslContext.init(null, tmf.getTrustManagers(), null);

} catch (KeyStoreException | IOException | NoSuchAlgorithmException | CertificateException | KeyManagementException e) {

Converting float to char*

char array[10];
snprintf(array, sizeof(array), "%f", 3.333333);

Save ArrayList to SharedPreferences

You can convert it to JSON String and store the string in the SharedPreferences.

Tomcat manager/html is not available?

After entering the roles and users in tomcat-users still if does not work make sure your tomact server location point to the right server location

javascript createElement(), style problem

Others have given you the answer about appendChild.

Calling document.write() on a page that is not open (e.g. has finished loading) first calls which clears the entire content of the document (including the script calling document.write), so it's rarely a good idea to do that.

How do I create a new line in Javascript?

document.writeln() is what you are looking for or document.write('\n' + 'words') if you are looking for more granularity in when the new line is used

Getting a list of associative array keys

You can use: Object.keys(obj)


var dictionary = {
  "cats": [1, 2, 37, 38, 40, 32, 33, 35, 39, 36],
  "dogs": [4, 5, 6, 3, 2]

// Get the keys
var keys = Object.keys(dictionary);


See reference below for browser support. It is supported in Firefox 4.20, Chrome 5, and Internet Explorer 9. Object.keys() contains a code snippet that you can add if Object.keys() is not supported in your browser.

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

This is my workflow for merging selective files.

# Make a new branch (this will be temporary)
git checkout -b newbranch

# Grab the changes
git merge --no-commit  featurebranch

# Unstage those changes
git reset HEAD
(You can now see the files from the merge are unstaged)

# Now you can chose which files are to be merged.
git add -p

# Remember to "git add" any new files you wish to keep
git commit