Programs & Examples On #Append

To append is to join or add on to the end of something.

How can I implement prepend and append with regular JavaScript?

This is not best way to do it but if anyone wants to insert an element before everything, here is a way.

var newElement = document.createElement("div");
var element = document.getElementById("targetelement");
element.innerHTML = '<div style="display:none !important;"></div>' + element.innerHTML;
var referanceElement = element.children[0];
element.insertBefore(newElement,referanceElement);
element.removeChild(referanceElement);

jQuery append text inside of an existing paragraph tag

Try this...

$('p').append('<span id="add_here">new-dynamic-text</span>');

OR if there is an existing span, do this.

$('p').children('span').text('new-dynamic-text');

DEMO

How merge two objects array in angularjs?

$scope.actions.data.concat is not a function 

same problem with me but i solve the problem by

 $scope.actions.data = [].concat($scope.actions.data , data)

Writing to a new file if it doesn't exist, and appending to a file if it does

Notice that if the file's parent folder doesn't exist you'll get the same error:

IOError: [Errno 2] No such file or directory:

Below is another solution which handles this case:
(*) I used sys.stdout and print instead of f.write just to show another use case

# Make sure the file's folder exist - Create folder if doesn't exist
folder_path = 'path/to/'+folder_name+'/'
if not os.path.exists(folder_path):
     os.makedirs(folder_path)

print_to_log_file(folder_path, "Some File" ,"Some Content")

Where the internal print_to_log_file just take care of the file level:

# If you're not familiar with sys.stdout - just ignore it below (just a use case example)
def print_to_log_file(folder_path ,file_name ,content_to_write):

   #1) Save a reference to the original standard output       
    original_stdout = sys.stdout   
    
    #2) Choose the mode
    write_append_mode = 'a' #Append mode
    file_path = folder_path + file_name
    if (if not os.path.exists(file_path) ):
       write_append_mode = 'w' # Write mode
     
    #3) Perform action on file
    with open(file_path, write_append_mode) as f:
        sys.stdout = f  # Change the standard output to the file we created.
        print(file_path, content_to_write)
        sys.stdout = original_stdout  # Reset the standard output to its original value

Consider the following states:

'w'  --> Write to existing file
'w+' --> Write to file, Create it if doesn't exist
'a'  --> Append to file
'a+' --> Append to file, Create it if doesn't exist

In your case I would use a different approach and just use 'a' and 'a+'.

How can I add an element after another element?

try

.insertAfter()

here

$(content).insertAfter('#bla');

Append to string variable

var str1 = 'abc';
var str2 = str1+' def'; // str2 is now 'abc def'

How do I append one string to another in Python?

str1 = "Hello"
str2 = "World"
newstr = " ".join((str1, str2))

That joins str1 and str2 with a space as separators. You can also do "".join(str1, str2, ...). str.join() takes an iterable, so you'd have to put the strings in a list or a tuple.

That's about as efficient as it gets for a builtin method.

How to append one file to another in Linux from the shell?

You can also do this without cat, though honestly cat is more readable:

>> file1 < file2

The >> appends STDIN to file1 and the < dumps file2 to STDIN.

Append text to input field

If you are planning to use appending more then once, you might want to write a function:

//Append text to input element
function jQ_append(id_of_input, text){
    var input_id = '#'+id_of_input;
    $(input_id).val($(input_id).val() + text);
}

After you can just call it:

jQ_append('my_input_id', 'add this text');

C++ - How to append a char to char*?

Remove those char * ret declarations inside if blocks which hide outer ret. Therefor you have memory leak and on the other hand un-allocated memory for ret.

To compare a c-style string you should use strcmp(array,"") not array!="". Your final code should looks like below:

char* appendCharToCharArray(char* array, char a)
{
    size_t len = strlen(array);

    char* ret = new char[len+2];

    strcpy(ret, array);    
    ret[len] = a;
    ret[len+1] = '\0';

    return ret;
}

Note that, you must handle the allocated memory of returned ret somewhere by delete[] it.

 

Why you don't use std::string? it has .append method to append a character at the end of a string:

std::string str;

str.append('x');
// or
str += x;

What is the difference between Python's list methods append and extend?

This is the equivalent of append and extend using the + operator:

>>> x = [1,2,3]
>>> x
[1, 2, 3]
>>> x = x + [4,5,6] # Extend
>>> x
[1, 2, 3, 4, 5, 6]
>>> x = x + [[7,8]] # Append
>>> x
[1, 2, 3, 4, 5, 6, [7, 8]]

Create pandas Dataframe by appending one row at a time

If all data in your Dataframe has the same dtype you might use a numpy array. You can write rows directly into the predefined array and convert it to a dataframe at the end. Seems to be even faster than converting a list of dicts.

import pandas as pd
import numpy as np
from string import ascii_uppercase

startTime = time.perf_counter()
numcols, numrows = 5, 10000
npdf = np.ones((numrows, numcols))
for row in range(numrows):
    npdf[row, 0:] = np.random.randint(0, 100, (1, numcols))
df5 = pd.DataFrame(npdf, columns=list(ascii_uppercase[:numcols]))      
print('Elapsed time: {:6.3f} seconds for {:d} rows'.format(time.perf_counter() - startTime, numOfRows))
print(df5.shape)

   

Appending a list or series to a pandas DataFrame as a row?

Here's a simple and dumb solution:

>>> import pandas as pd
>>> df = pd.DataFrame()
>>> df = df.append({'foo':1, 'bar':2}, ignore_index=True)

jQuery append() and remove() element

You can call a reset function before appending. Something like this:

    function resetNewReviewBoardForm() {
    $("#Description").val('');
    $("#PersonName").text('');
    $("#members").empty(); //this one what worked in my case
    $("#EmailNotification").val('False');
}

Creating a LinkedList class from scratch

Please read this article: How To Implement a LinkedList Class From Scratch In Java

package com.crunchify.tutorials;

/**
 * @author Crunchify.com
 */

public class CrunchifyLinkedListTest {

    public static void main(String[] args) {
        CrunchifyLinkedList lList = new CrunchifyLinkedList();

        // add elements to LinkedList
        lList.add("1");
        lList.add("2");
        lList.add("3");
        lList.add("4");
        lList.add("5");

        /*
         * Please note that primitive values can not be added into LinkedList
         * directly. They must be converted to their corresponding wrapper
         * class.
         */

        System.out.println("lList - print linkedlist: " + lList);
        System.out.println("lList.size() - print linkedlist size: " + lList.size());
        System.out.println("lList.get(3) - get 3rd element: " + lList.get(3));
        System.out.println("lList.remove(2) - remove 2nd element: " + lList.remove(2));
        System.out.println("lList.get(3) - get 3rd element: " + lList.get(3));
        System.out.println("lList.size() - print linkedlist size: " + lList.size());
        System.out.println("lList - print linkedlist: " + lList);
    }
}

class CrunchifyLinkedList {
    // reference to the head node.
    private Node head;
    private int listCount;

    // LinkedList constructor
    public CrunchifyLinkedList() {
        // this is an empty list, so the reference to the head node
        // is set to a new node with no data
        head = new Node(null);
        listCount = 0;
    }

    public void add(Object data)
    // appends the specified element to the end of this list.
    {
        Node crunchifyTemp = new Node(data);
        Node crunchifyCurrent = head;
        // starting at the head node, crawl to the end of the list
        while (crunchifyCurrent.getNext() != null) {
            crunchifyCurrent = crunchifyCurrent.getNext();
        }
        // the last node's "next" reference set to our new node
        crunchifyCurrent.setNext(crunchifyTemp);
        listCount++;// increment the number of elements variable
    }

    public void add(Object data, int index)
    // inserts the specified element at the specified position in this list
    {
        Node crunchifyTemp = new Node(data);
        Node crunchifyCurrent = head;
        // crawl to the requested index or the last element in the list,
        // whichever comes first
        for (int i = 1; i < index && crunchifyCurrent.getNext() != null; i++) {
            crunchifyCurrent = crunchifyCurrent.getNext();
        }
        // set the new node's next-node reference to this node's next-node
        // reference
        crunchifyTemp.setNext(crunchifyCurrent.getNext());
        // now set this node's next-node reference to the new node
        crunchifyCurrent.setNext(crunchifyTemp);
        listCount++;// increment the number of elements variable
    }

    public Object get(int index)
    // returns the element at the specified position in this list.
    {
        // index must be 1 or higher
        if (index <= 0)
            return null;

        Node crunchifyCurrent = head.getNext();
        for (int i = 1; i < index; i++) {
            if (crunchifyCurrent.getNext() == null)
                return null;

            crunchifyCurrent = crunchifyCurrent.getNext();
        }
        return crunchifyCurrent.getData();
    }

    public boolean remove(int index)
    // removes the element at the specified position in this list.
    {
        // if the index is out of range, exit
        if (index < 1 || index > size())
            return false;

        Node crunchifyCurrent = head;
        for (int i = 1; i < index; i++) {
            if (crunchifyCurrent.getNext() == null)
                return false;

            crunchifyCurrent = crunchifyCurrent.getNext();
        }
        crunchifyCurrent.setNext(crunchifyCurrent.getNext().getNext());
        listCount--; // decrement the number of elements variable
        return true;
    }

    public int size()
    // returns the number of elements in this list.
    {
        return listCount;
    }

    public String toString() {
        Node crunchifyCurrent = head.getNext();
        String output = "";
        while (crunchifyCurrent != null) {
            output += "[" + crunchifyCurrent.getData().toString() + "]";
            crunchifyCurrent = crunchifyCurrent.getNext();
        }
        return output;
    }

    private class Node {
        // reference to the next node in the chain,
        // or null if there isn't one.
        Node next;
        // data carried by this node.
        // could be of any type you need.
        Object data;

        // Node constructor
        public Node(Object dataValue) {
            next = null;
            data = dataValue;
        }

        // another Node constructor if we want to
        // specify the node to point to.
        public Node(Object dataValue, Node nextValue) {
            next = nextValue;
            data = dataValue;
        }

        // these methods should be self-explanatory
        public Object getData() {
            return data;
        }

        public void setData(Object dataValue) {
            data = dataValue;
        }

        public Node getNext() {
            return next;
        }

        public void setNext(Node nextValue) {
            next = nextValue;
        }
    }
}

Output

lList - print linkedlist: [1][2][3][4][5]
lList.size() - print linkedlist size: 5
lList.get(3) - get 3rd element: 3
lList.remove(2) - remove 2nd element: true
lList.get(3) - get 3rd element: 4
lList.size() - print linkedlist size: 4
lList - print linkedlist: [1][3][4][5]

List append() in for loop

The list.append function does not return any value(but None), it just adds the value to the list you are using to call that method.

In the first loop round you will assign None (because the no-return of append) to a, then in the second round it will try to call a.append, as a is None it will raise the Exception you are seeing

You just need to change it to:

a=[]
for i in range(5):    
    a.append(i)
print(a)
# [0, 1, 2, 3, 4]

list.append is what is called a mutating or destructive method, i.e. it will destroy or mutate the previous object into a new one(or a new state).

If you would like to create a new list based in one list without destroying or mutating it you can do something like this:

a=['a', 'b', 'c']
result = a + ['d']

print result
# ['a', 'b', 'c', 'd']

print a
# ['a', 'b', 'c']

As a corollary only, you can mimic the append method by doing the following:

a=['a', 'b', 'c']
a = a + ['d']

print a
# ['a', 'b', 'c', 'd']

jQuery - Appending a div to body, the body is the object?

Using jQuery appendTo try this:

var holdyDiv = $('<div></div>').attr('id', 'holdy');
holdyDiv.appendTo('body');

How to append binary data to a buffer in node.js

This is to help anyone who comes here looking for a solution that wants a pure approach. I would recommend understanding this problem because it can happen in lots of different places not just with a JS Buffer object. By understanding why the problem exists and how to solve it you will improve your ability to solve other problems in the future since this one is so fundamental.

For those of us that have to deal with these problems in other languages it is quite natural to devise a solution, but there are people who may not realize how to abstract away the complexities and implement a generally efficient dynamic buffer. The code below may have potential to be optimized further.

I have left the read method unimplemented to keep the example small in size.

The realloc function in C (or any language dealing with intrinsic allocations) does not guarantee that the allocation will be expanded in size with out moving the existing data - although sometimes it is possible. Therefore most applications when needing to store a unknown amount of data will use a method like below and not constantly reallocate, unless the reallocation is very infrequent. This is essentially how most file systems handle writing data to a file. The file system simply allocates another node and keeps all the nodes linked together, and when you read from it the complexity is abstracted away so that the file/buffer appears to be a single contiguous buffer.

For those of you who wish to understand the difficulty in just simply providing a high performance dynamic buffer you only need to view the code below, and also do some research on memory heap algorithms and how the memory heap works for programs.

Most languages will provide a fixed size buffer for performance reasons, and then provide another version that is dynamic in size. Some language systems opt for a third-party system where they keep the core functionality minimal (core distribution) and encourage developers to create libraries to solve additional or higher level problems. This is why you may question why a language does not provide some functionality. This small core functionality allows costs to be reduced in maintaining and enhancing the language, however you end up having to write your own implementations or depending on a third-party.

var Buffer_A1 = function (chunk_size) {
    this.buffer_list = [];
    this.total_size = 0;
    this.cur_size = 0;
    this.cur_buffer = [];
    this.chunk_size = chunk_size || 4096;

    this.buffer_list.push(new Buffer(this.chunk_size));
};

Buffer_A1.prototype.writeByteArrayLimited = function (data, offset, length) {
    var can_write = length > (this.chunk_size - this.cur_size) ? (this.chunk_size - this.cur_size) : length;

    var lastbuf = this.buffer_list.length - 1;

    for (var x = 0; x < can_write; ++x) {
        this.buffer_list[lastbuf][this.cur_size + x] = data[x + offset];
    }

    this.cur_size += can_write;
    this.total_size += can_write;

    if (this.cur_size == this.chunk_size) {
        this.buffer_list.push(new Buffer(this.chunk_size));
        this.cur_size = 0;
    }

    return can_write;
};

/*
    The `data` parameter can be anything that is array like. It just must
    support indexing and a length and produce an acceptable value to be
    used with Buffer.
*/
Buffer_A1.prototype.writeByteArray = function (data, offset, length) {
    offset = offset == undefined ? 0 : offset;
    length = length == undefined ? data.length : length;

    var rem = length;
    while (rem > 0) {
        rem -= this.writeByteArrayLimited(data, length - rem, rem);
    }
};

Buffer_A1.prototype.readByteArray = function (data, offset, length) {
    /*
        If you really wanted to implement some read functionality
        then you would have to deal with unaligned reads which could
        span two buffers.
    */
};

Buffer_A1.prototype.getSingleBuffer = function () {
    var obuf = new Buffer(this.total_size);
    var cur_off = 0;
    var x;

    for (x = 0; x < this.buffer_list.length - 1; ++x) {
        this.buffer_list[x].copy(obuf, cur_off);
        cur_off += this.buffer_list[x].length;
    }

    this.buffer_list[x].copy(obuf, cur_off, 0, this.cur_size);

    return obuf;
};

JavaScript CSS how to add and remove multiple CSS classes to an element

  addClass(element, className1, className2){
    element.classList.add(className1, className2);
  }
  removeClass(element, className1, className2) {
    element.classList.remove(className1, className2);
  }

removeClass(myElement, 'myClass1', 'myClass2');
addClass(myElement, 'myClass1', 'myClass2');

Adding dictionaries together, Python

If you're interested in creating a new dict without using intermediary storage: (this is faster, and in my opinion, cleaner than using dict.items())

dic2 = dict(dic0, **dic1)

Or if you're happy to use one of the existing dicts:

dic0.update(dic1)

Append a tuple to a list - what's the difference between two ways?

It has nothing to do with append. tuple(3, 4) all by itself raises that error.

The reason is that, as the error message says, tuple expects an iterable argument. You can make a tuple of the contents of a single object by passing that single object to tuple. You can't make a tuple of two things by passing them as separate arguments.

Just do (3, 4) to make a tuple, as in your first example. There's no reason not to use that simple syntax for writing a tuple.

append new row to old csv file python

I prefer this solution using the csv module from the standard library and the with statement to avoid leaving the file open.

The key point is using 'a' for appending when you open the file.

import csv   
fields=['first','second','third']
with open(r'name', 'a') as f:
    writer = csv.writer(f)
    writer.writerow(fields)

If you are using Python 2.7 you may experience superfluous new lines in Windows. You can try to avoid them using 'ab' instead of 'a' this will, however, cause you TypeError: a bytes-like object is required, not 'str' in python and CSV in Python 3.6. Adding the newline='', as Natacha suggests, will cause you a backward incompatibility between Python 2 and 3.

How to insert an element after another element in JavaScript without using a library?

Lets handle all the scenarios

 function insertAfter(newNode, referenceNode) {
        if(referenceNode && referenceNode.nextSibling && referenceNode.nextSibling.nodeName == '#text')
            referenceNode = referenceNode.nextSibling;

        if(!referenceNode)
            document.body.appendChild(newNode);
        else if(!referenceNode.nextSibling)
            document.body.appendChild(newNode);
        else            
            referenceNode.parentNode.insertBefore(newNode, referenceNode.nextSibling);            
    }

java: use StringBuilder to insert at the beginning

Difference Between String, StringBuilder And StringBuffer Classes
String
String is immutable ( once created can not be changed )object. The object created as a
String is stored in the Constant String Pool.
Every immutable object in Java is thread-safe, which implies String is also thread-safe. String
can not be used by two threads simultaneously.
String once assigned can not be changed.
StringBuffer
StringBuffer is mutable means one can change the value of the object. The object created
through StringBuffer is stored in the heap. StringBuffer has the same methods as the
StringBuilder , but each method in StringBuffer is synchronized that is StringBuffer is thread
safe .
Due to this, it does not allow two threads to simultaneously access the same method. Each
method can be accessed by one thread at a time.
But being thread-safe has disadvantages too as the performance of the StringBuffer hits due
to thread-safe property. Thus StringBuilder is faster than the StringBuffer when calling the
same methods of each class.
String Buffer can be converted to the string by using
toString() method.

    StringBuffer demo1 = new StringBuffer("Hello") ;

// The above object stored in heap and its value can be changed.
/
// Above statement is right as it modifies the value which is allowed in the StringBuffer
StringBuilder
StringBuilder is the same as the StringBuffer, that is it stores the object in heap and it can also
be modified. The main difference between the StringBuffer and StringBuilder is
that StringBuilder is also not thread-safe.
StringBuilder is fast as it is not thread-safe.
/
// The above object is stored in the heap and its value can be modified
/
// Above statement is right as it modifies the value which is allowed in the StringBuilder

Unsuccessful append to an empty NumPy array

numpy.append is pretty different from list.append in python. I know that's thrown off a few programers new to numpy. numpy.append is more like concatenate, it makes a new array and fills it with the values from the old array and the new value(s) to be appended. For example:

import numpy

old = numpy.array([1, 2, 3, 4])
new = numpy.append(old, 5)
print old
# [1, 2, 3, 4]
print new
# [1, 2, 3, 4, 5]
new = numpy.append(new, [6, 7])
print new
# [1, 2, 3, 4, 5, 6, 7]

I think you might be able to achieve your goal by doing something like:

result = numpy.zeros((10,))
result[0:2] = [1, 2]

# Or
result = numpy.zeros((10, 2))
result[0, :] = [1, 2]

Update:

If you need to create a numpy array using loop, and you don't know ahead of time what the final size of the array will be, you can do something like:

import numpy as np

a = np.array([0., 1.])
b = np.array([2., 3.])

temp = []
while True:
    rnd = random.randint(0, 100)
    if rnd > 50:
        temp.append(a)
    else:
        temp.append(b)
    if rnd == 0:
         break

 result = np.array(temp)

In my example result will be an (N, 2) array, where N is the number of times the loop ran, but obviously you can adjust it to your needs.

new update

The error you're seeing has nothing to do with types, it has to do with the shape of the numpy arrays you're trying to concatenate. If you do np.append(a, b) the shapes of a and b need to match. If you append an (2, n) and (n,) you'll get a (3, n) array. Your code is trying to append a (1, 0) to a (2,). Those shapes don't match so you get an error.

How to remove an appended element with Jquery and why bind or live is causing elements to repeat

I would do something like:

$(documento).on('click', '#answer', function() {
  feedback('hey there');
});

How to append rows to an R data frame

Suppose you simply don't know the size of the data.frame in advance. It can well be a few rows, or a few millions. You need to have some sort of container, that grows dynamically. Taking in consideration my experience and all related answers in SO I come with 4 distinct solutions:

  1. rbindlist to the data.frame

  2. Use data.table's fast set operation and couple it with manually doubling the table when needed.

  3. Use RSQLite and append to the table held in memory.

  4. data.frame's own ability to grow and use custom environment (which has reference semantics) to store the data.frame so it will not be copied on return.

Here is a test of all the methods for both small and large number of appended rows. Each method has 3 functions associated with it:

  • create(first_element) that returns the appropriate backing object with first_element put in.

  • append(object, element) that appends the element to the end of the table (represented by object).

  • access(object) gets the data.frame with all the inserted elements.

rbindlist to the data.frame

That is quite easy and straight-forward:

create.1<-function(elems)
{
  return(as.data.table(elems))
}

append.1<-function(dt, elems)
{ 
  return(rbindlist(list(dt,  elems),use.names = TRUE))
}

access.1<-function(dt)
{
  return(dt)
}

data.table::set + manually doubling the table when needed.

I will store the true length of the table in a rowcount attribute.

create.2<-function(elems)
{
  return(as.data.table(elems))
}

append.2<-function(dt, elems)
{
  n<-attr(dt, 'rowcount')
  if (is.null(n))
    n<-nrow(dt)
  if (n==nrow(dt))
  {
    tmp<-elems[1]
    tmp[[1]]<-rep(NA,n)
    dt<-rbindlist(list(dt, tmp), fill=TRUE, use.names=TRUE)
    setattr(dt,'rowcount', n)
  }
  pos<-as.integer(match(names(elems), colnames(dt)))
  for (j in seq_along(pos))
  {
    set(dt, i=as.integer(n+1), pos[[j]], elems[[j]])
  }
  setattr(dt,'rowcount',n+1)
  return(dt)
}

access.2<-function(elems)
{
  n<-attr(elems, 'rowcount')
  return(as.data.table(elems[1:n,]))
}

SQL should be optimized for fast record insertion, so I initially had high hopes for RSQLite solution

This is basically copy&paste of Karsten W. answer on similar thread.

create.3<-function(elems)
{
  con <- RSQLite::dbConnect(RSQLite::SQLite(), ":memory:")
  RSQLite::dbWriteTable(con, 't', as.data.frame(elems))
  return(con)
}

append.3<-function(con, elems)
{ 
  RSQLite::dbWriteTable(con, 't', as.data.frame(elems), append=TRUE)
  return(con)
}

access.3<-function(con)
{
  return(RSQLite::dbReadTable(con, "t", row.names=NULL))
}

data.frame's own row-appending + custom environment.

create.4<-function(elems)
{
  env<-new.env()
  env$dt<-as.data.frame(elems)
  return(env)
}

append.4<-function(env, elems)
{ 
  env$dt[nrow(env$dt)+1,]<-elems
  return(env)
}

access.4<-function(env)
{
  return(env$dt)
}

The test suite:

For convenience I will use one test function to cover them all with indirect calling. (I checked: using do.call instead of calling the functions directly doesn't makes the code run measurable longer).

test<-function(id, n=1000)
{
  n<-n-1
  el<-list(a=1,b=2,c=3,d=4)
  o<-do.call(paste0('create.',id),list(el))
  s<-paste0('append.',id)
  for (i in 1:n)
  {
    o<-do.call(s,list(o,el))
  }
  return(do.call(paste0('access.', id), list(o)))
}

Let's see the performance for n=10 insertions.

I also added a 'placebo' functions (with suffix 0) that don't perform anything - just to measure the overhead of the test setup.

r<-microbenchmark(test(0,n=10), test(1,n=10),test(2,n=10),test(3,n=10), test(4,n=10))
autoplot(r)

Timings for adding n=10 rows

Timings for n=100 rows Timings for n=1000 rows

For 1E5 rows (measurements done on Intel(R) Core(TM) i7-4710HQ CPU @ 2.50GHz):

nr  function      time
4   data.frame    228.251 
3   sqlite        133.716
2   data.table      3.059
1   rbindlist     169.998 
0   placebo         0.202

It looks like the SQLite-based sulution, although regains some speed on large data, is nowhere near data.table + manual exponential growth. The difference is almost two orders of magnitude!

Summary

If you know that you will append rather small number of rows (n<=100), go ahead and use the simplest possible solution: just assign the rows to the data.frame using bracket notation and ignore the fact that the data.frame is not pre-populated.

For everything else use data.table::set and grow the data.table exponentially (e.g. using my code).

How do you append to a file?

Here's my script, which basically counts the number of lines, then appends, then counts them again so you have evidence it worked.

shortPath  = "../file_to_be_appended"
short = open(shortPath, 'r')

## this counts how many line are originally in the file:
long_path = "../file_to_be_appended_to" 
long = open(long_path, 'r')
for i,l in enumerate(long): 
    pass
print "%s has %i lines initially" %(long_path,i)
long.close()

long = open(long_path, 'a') ## now open long file to append
l = True ## will be a line
c = 0 ## count the number of lines you write
while l: 
    try: 
        l = short.next() ## when you run out of lines, this breaks and the except statement is run
        c += 1
        long.write(l)

    except: 
        l = None
        long.close()
        print "Done!, wrote %s lines" %c 

## finally, count how many lines are left. 
long = open(long_path, 'r')
for i,l in enumerate(long): 
    pass
print "%s has %i lines after appending new lines" %(long_path, i)
long.close()

Append an object to a list in R in amortized constant time, O(1)?

try this function lappend

lappend <- function (lst, ...){
  lst <- c(lst, list(...))
  return(lst)
}

and other suggestions from this page Add named vector to a list

Bye.

Appending a line break to an output file in a shell script

this also works, and prolly is more readable than the echo version:

printf "`date` User `whoami` started the script.\r\n" >> output.log

How to add an element at the end of an array?

To clarify the terminology right: arrays are fixed length structures (and the length of an existing cannot be altered) the expression add at the end is meaningless (by itself).

What you can do is create a new array one element larger and fill in the new element in the last slot:

public static int[] append(int[] array, int value) {
     int[] result = Arrays.copyOf(array, array.length + 1);
     result[result.length - 1] = value;
     return result;
}

This quickly gets inefficient, as each time append is called a new array is created and the old array contents is copied over.

One way to drastically reduce the overhead is to create a larger array and keep track of up to which index it is actually filled. Adding an element becomes as simple a filling the next index and incrementing the index. If the array fills up completely, a new array is created with more free space.

And guess what ArrayList does: exactly that. So when a dynamically sized array is needed, ArrayList is a good choice. Don't reinvent the wheel.

Can someone explain how to append an element to an array in C programming?

You can have a counter (freePosition), which will track the next free place in an array of size n.

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

To avoid confusion, paraphrasing both question and answer. I am assuming that user who posted this question wanted to save dictionary type object in JSON file format but when the user used json.dump, this method dumped all its content in one line. Instead, he wanted to record each dictionary entry on a new line. To achieve this use:

with g as outfile:
  json.dump(hostDict, outfile,indent=2)

Using indent = 2 helped me to dump each dictionary entry on a new line. Thank you @agf. Rewriting this answer to avoid confusion.

Python append() vs. + operator on lists, why do these give different results?

append is appending an element to a list. if you want to extend the list with the new list you need to use extend.

>>> c = [1, 2, 3]
>>> c.extend(c)
>>> c
[1, 2, 3, 1, 2, 3]

How to append something to an array?

There are a couple of ways to append an array in JavaScript:

1) The push() method adds one or more elements to the end of an array and returns the new length of the array.

var a = [1, 2, 3];
a.push(4, 5);
console.log(a);

Output:

[1, 2, 3, 4, 5]

2) The unshift() method adds one or more elements to the beginning of an array and returns the new length of the array:

var a = [1, 2, 3];
a.unshift(4, 5);
console.log(a); 

Output:

[4, 5, 1, 2, 3]

3) The concat() method is used to merge two or more arrays. This method does not change the existing arrays, but instead returns a new array.

var arr1 = ["a", "b", "c"];
var arr2 = ["d", "e", "f"];
var arr3 = arr1.concat(arr2);
console.log(arr3);

Output:

[ "a", "b", "c", "d", "e", "f" ]

4) You can use the array's .length property to add an element to the end of the array:

var ar = ['one', 'two', 'three'];
ar[ar.length] = 'four';
console.log( ar ); 

Output:

 ["one", "two", "three", "four"]

5) The splice() method changes the content of an array by removing existing elements and/or adding new elements:

var myFish = ["angel", "clown", "mandarin", "surgeon"];
myFish.splice(4, 0, "nemo");
//array.splice(start, deleteCount, item1, item2, ...)
console.log(myFish);

Output:

["angel", "clown", "mandarin", "surgeon","nemo"]

6) You can also add a new element to an array simply by specifying a new index and assigning a value:

var ar = ['one', 'two', 'three'];
ar[3] = 'four'; // add new element to ar
console.log(ar);

Output:

["one", "two","three","four"]

The preferred way of creating a new element with jQuery

I would recommend the first option, where you actually build elements using jQuery. the second approach simply sets the innerHTML property of the element to a string, which happens to be HTML, and is more error prone and less flexible.

Scala: what is the best way to append an element to an Array?

val array2 = array :+ 4
//Array(1, 2, 3, 4)

Works also "reversed":

val array2 = 4 +: array
Array(4, 1, 2, 3)

There is also an "in-place" version:

var array = Array( 1, 2, 3 )
array +:= 4
//Array(4, 1, 2, 3)
array :+= 0
//Array(4, 1, 2, 3, 0)

jQuery append() vs appendChild()

appendChild is a pure javascript method where as append is a jQuery method.

Concatenate two slices in Go

Appending to and copying slices

The variadic function append appends zero or more values x to s of type S, which must be a slice type, and returns the resulting slice, also of type S. The values x are passed to a parameter of type ...T where T is the element type of S and the respective parameter passing rules apply. As a special case, append also accepts a first argument assignable to type []byte with a second argument of string type followed by .... This form appends the bytes of the string.

append(s S, x ...T) S  // T is the element type of S

s0 := []int{0, 0}
s1 := append(s0, 2)        // append a single element     s1 == []int{0, 0, 2}
s2 := append(s1, 3, 5, 7)  // append multiple elements    s2 == []int{0, 0, 2, 3, 5, 7}
s3 := append(s2, s0...)    // append a slice              s3 == []int{0, 0, 2, 3, 5, 7, 0, 0}

Passing arguments to ... parameters

If f is variadic with final parameter type ...T, then within the function the argument is equivalent to a parameter of type []T. At each call of f, the argument passed to the final parameter is a new slice of type []T whose successive elements are the actual arguments, which all must be assignable to the type T. The length of the slice is therefore the number of arguments bound to the final parameter and may differ for each call site.

The answer to your question is example s3 := append(s2, s0...) in the Go Programming Language Specification. For example,

s := append([]int{1, 2}, []int{3, 4}...)

Append to the end of a file in C

Following the documentation of fopen:

``a'' Open for writing. The file is created if it does not exist. The stream is positioned at the end of the file. Subsequent writes to the file will always end up at the then cur- rent end of file, irrespective of any intervening fseek(3) or similar.

So if you pFile2=fopen("myfile2.txt", "a"); the stream is positioned at the end to append automatically. just do:

FILE *pFile;
FILE *pFile2;
char buffer[256];

pFile=fopen("myfile.txt", "r");
pFile2=fopen("myfile2.txt", "a");
if(pFile==NULL) {
    perror("Error opening file.");
}
else {
    while(fgets(buffer, sizeof(buffer), pFile)) {
        fprintf(pFile2, "%s", buffer);
    }
}
fclose(pFile);
fclose(pFile2);

How can I store HashMap<String, ArrayList<String>> inside a list?

First you need to define the List as :

List<Map<String, ArrayList<String>>> list = new ArrayList<>();

To add the Map to the List , use add(E e) method :

list.add(map);

Add / Change parameter of URL and redirect to the new URL

Here's a way of accomplishing this. It takes the param name and param value, and an optional 'clear'. If you supply clear=true, it will remove all other params and just leave the newly added one - in other cases, it will either replace the original with the new, or add it if it's not present in the querystring.

This is modified from the original top answer as that one broke if it replaced anything but the last value. This will work for any value, and preserve the existing order.

function setGetParameter(paramName, paramValue, clear)
{
clear = typeof clear !== 'undefined' ? clear : false;
var url = window.location.href;
var queryString = location.search.substring(1); 
var newQueryString = "";
if (clear)
{
    newQueryString = paramName + "=" + paramValue;
}
else if (url.indexOf(paramName + "=") >= 0)
{
    var decode = function (s) { return decodeURIComponent(s.replace(/\+/g, " ")); };
    var keyValues = queryString.split('&'); 
    for(var i in keyValues) { 
        var key = keyValues[i].split('=');
        if (key.length > 1) {
            if(newQueryString.length > 0) {newQueryString += "&";}
            if(decode(key[0]) == paramName)
            {
                newQueryString += key[0] + "=" + encodeURIComponent(paramValue);;
            }
            else
            {
                newQueryString += key[0] + "=" + key[1];
            }
        }
    } 
}
else
{
    if (url.indexOf("?") < 0)
        newQueryString = "?" + paramName + "=" + paramValue;
    else
        newQueryString = queryString + "&" + paramName + "=" + paramValue;
}
window.location.href = window.location.href.split('?')[0] + "?" + newQueryString;
}

Python RuntimeWarning: overflow encountered in long scalars

An easy way to overcome this problem is to use 64 bit type

list = numpy.array(list, dtype=numpy.float64)

Append a single character to a string or char array in java?

new StringBuilder().append(str.charAt(0))
                   .append(str.charAt(10))
                   .append(str.charAt(20))
                   .append(str.charAt(30))
                   .toString();

This way you can get the new string with whatever characters you want.

jQuery using append with effects

Why don't you simply hide, append, then show, like this:

<div id="parent1" style="  width: 300px; height: 300px; background-color: yellow;">
    <div id="child" style=" width: 100px; height: 100px; background-color: red;"></div>
</div>


<div id="parent2" style="  width: 300px; height: 300px; background-color: green;">
</div>

<input id="mybutton" type="button" value="move">

<script>
    $("#mybutton").click(function(){
        $('#child').hide(1000, function(){
            $('#parent2').append($('#child'));
            $('#child').show(1000);
        });

    });
</script>

How to append new data onto a new line

I had the same issue. And I was able to solve it by using a formatter.

file_name = "abc.txt"
new_string = "I am a new string."
opened_file = open(file_name, 'a')
opened_file.write("%r\n" %new_string)
opened_file.close()

I hope this helps.

Append date to filename in linux

There's two problems here.

1. Get the date as a string

This is pretty easy. Just use the date command with the + option. We can use backticks to capture the value in a variable.

$ DATE=`date +%d-%m-%y` 

You can change the date format by using different % options as detailed on the date man page.

2. Split a file into name and extension.

This is a bit trickier. If we think they'll be only one . in the filename we can use cut with . as the delimiter.

$ NAME=`echo $FILE | cut -d. -f1
$ EXT=`echo $FILE | cut -d. -f2`

However, this won't work with multiple . in the file name. If we're using bash - which you probably are - we can use some bash magic that allows us to match patterns when we do variable expansion:

$ NAME=${FILE%.*}
$ EXT=${FILE#*.} 

Putting them together we get:

$ FILE=somefile.txt             
$ NAME=${FILE%.*}
$ EXT=${FILE#*.} 
$ DATE=`date +%d-%m-%y`         
$ NEWFILE=${NAME}_${DATE}.${EXT}
$ echo $NEWFILE                 
somefile_25-11-09.txt                         

And if we're less worried about readability we do all the work on one line (with a different date format):

$ FILE=somefile.txt  
$ FILE=${FILE%.*}_`date +%d%b%y`.${FILE#*.}
$ echo $FILE                                 
somefile_25Nov09.txt

The process cannot access the file because it is being used by another process (File is created but contains nothing)

Try This

string path = @"c:\mytext.txt";

if (File.Exists(path))
{
    File.Delete(path);
}

{ // Consider File Operation 1
    FileStream fs = new FileStream(path, FileMode.OpenOrCreate);
    StreamWriter str = new StreamWriter(fs);
    str.BaseStream.Seek(0, SeekOrigin.End);
    str.Write("mytext.txt.........................");
    str.WriteLine(DateTime.Now.ToLongTimeString() + " " + 
                  DateTime.Now.ToLongDateString());
    string addtext = "this line is added" + Environment.NewLine;
    str.Flush();
    str.Close();
    fs.Close();
    // Close the Stream then Individually you can access the file.
}

File.AppendAllText(path, addtext);  // File Operation 2

string readtext = File.ReadAllText(path); // File Operation 3

Console.WriteLine(readtext);

In every File Operation, The File will be Opened and must be Closed prior Opened. Like wise in the Operation 1 you must Close the File Stream for the Further Operations.

Appending a list to a list of lists in R

The purrr package has a lot of handy functions for working on lists. The flatten command can clean up unwanted nesting.

resultsa <- list(1,2,3,4,5)
resultsb <- list(6,7,8,9,10)
resultsc <- list(11,12,13,14,15)

nested_outlist <- list(resultsa, resultsb, resultsc)
outlist <- purrr::flatten(nested_outlist)

Creating a div element in jQuery

document.createElement('div');

How can I append a string to an existing field in MySQL?

Update image field to add full URL, ignoring null fields:

UPDATE test SET image = CONCAT('https://my-site.com/images/',image) WHERE image IS NOT NULL;

Append integer to beginning of list in Python

None of these worked for me. I converted the first element to be part of a series (a single element series), and converted the second element also to be a series, and used append function.

l = ((pd.Series(<first element>)).append(pd.Series(<list of other elements>))).tolist()

.append(), prepend(), .after() and .before()

There is a basic difference between .append() and .after() and .prepend() and .before().

.append() adds the parameter element inside the selector element's tag at the very end whereas the .after() adds the parameter element after the element's tag.

The vice-versa is for .prepend() and .before().

Fiddle

How to insert table values from one database to another database?

You can try

Insert into your_table_in_db1 select * from your_table_in_db2@db2SID 

db2SID is the sid of other DB. It will be present in tnsnames.ora file

ValueError: all the input arrays must have same number of dimensions

The reason why you get your error is because a "1 by n" matrix is different from an array of length n.

I recommend using hstack() and vstack() instead. Like this:

import numpy as np
a = np.arange(32).reshape(4,8) # 4 rows 8 columns matrix.
b = a[:,-1:]                    # last column of that matrix.

result = np.hstack((a,b))       # stack them horizontally like this:
#array([[ 0,  1,  2,  3,  4,  5,  6,  7,  7],
#       [ 8,  9, 10, 11, 12, 13, 14, 15, 15],
#       [16, 17, 18, 19, 20, 21, 22, 23, 23],
#       [24, 25, 26, 27, 28, 29, 30, 31, 31]])

Notice the repeated "7, 15, 23, 31" column. Also, notice that I used a[:,-1:] instead of a[:,-1]. My version generates a column:

array([[7],
       [15],
       [23],
       [31]])

Instead of a row array([7,15,23,31])


Edit: append() is much slower. Read this answer.

How to redirect and append both stdout and stderr to a file with Bash?

There are two ways to do this, depending on your Bash version.

The classic and portable (Bash pre-4) way is:

cmd >> outfile 2>&1

A nonportable way, starting with Bash 4 is

cmd &>> outfile

(analog to &> outfile)

For good coding style, you should

  • decide if portability is a concern (then use classic way)
  • decide if portability even to Bash pre-4 is a concern (then use classic way)
  • no matter which syntax you use, not change it within the same script (confusion!)

If your script already starts with #!/bin/sh (no matter if intended or not), then the Bash 4 solution, and in general any Bash-specific code, is not the way to go.

Also remember that Bash 4 &>> is just shorter syntax — it does not introduce any new functionality or anything like that.

The syntax is (beside other redirection syntax) described here: http://bash-hackers.org/wiki/doku.php/syntax/redirection#appending_redirected_output_and_error_output

Append value to empty vector in R?

FWIW: analogous to python's append():

b <- 1
b <- c(b, 2)

Appending items to a list of lists in python

import csv
cols = [' V1', ' I1'] # define your columns here, check the spaces!
data = [[] for col in cols] # this creates a list of **different** lists, not a list of pointers to the same list like you did in [[]]*len(positions) 
with open('data.csv', 'r') as f:
    for rec in csv.DictReader(f):
        for l, col in zip(data, cols):
            l.append(float(rec[col]))
print data

# [[3.0, 3.0], [0.01, 0.01]]

How to append elements at the end of ArrayList in Java?

I know this is an old question, but I wanted to make an answer of my own. here is another way to do this if you "really" want to add to the end of the list instead of using list.add(str) you can do it this way, but I don't recommend.

 String[] items = new String[]{"Hello", "World"};
        ArrayList<String> list = new ArrayList<>();
        Collections.addAll(list, items);
        int endOfList = list.size();
        list.add(endOfList, "This goes end of list");
        System.out.println(Collections.singletonList(list));

this is the 'Compact' way of adding the item to the end of list. here is a safer way to do this, with null checking and more.

String[] items = new String[]{"Hello", "World"};
        ArrayList<String> list = new ArrayList<>();
        Collections.addAll(list, items);
        addEndOfList(list, "Safer way");
        System.out.println(Collections.singletonList(list));

 private static void addEndOfList(List<String> list, String item){
            try{
                list.add(getEndOfList(list), item);
            } catch (IndexOutOfBoundsException e){
                System.out.println(e.toString());
            }
        }

   private static int getEndOfList(List<String> list){
        if(list != null) {
            return list.size();
        }
        return -1;
    }

Heres another way to add items to the end of list, happy coding :)

Append values to a set in Python

You can also use the | operator to concatenate two sets (union in set theory):

>>> my_set = {1}
>>> my_set = my_set | {2}
>>> my_set
{1, 2}

Or a shorter form using |=:

>>> my_set = {1}
>>> my_set |= {2}
>>> my_set
{1, 2}

Note: In versions prior to Python 2.7, use set([...]) instead of {...}.

Append file contents to the bottom of existing file in Bash

This should work:

 cat "$API" >> "$CONFIG"

You need to use the >> operator to append to a file. Redirecting with > causes the file to be overwritten. (truncated).

How do I append text to a file?

Follow up to accepted answer.

You need something other than CTRL-D to designate the end if using this in a script. Try this instead:

cat << EOF >> filename
This is text entered via the keyboard or via a script.
EOF

This will append text to the stated file (not including "EOF").

It utilizes a here document (or heredoc).

However if you need sudo to append to the stated file, you will run into trouble utilizing a heredoc due to I/O redirection if you're typing directly on the command line.

This variation will work when you are typing directly on the command line:

sudo sh -c 'cat << EOF >> filename
This is text entered via the keyboard.
EOF'

Or you can use tee instead to avoid the command line sudo issue seen when using the heredoc with cat:

tee -a filename << EOF
This is text entered via the keyboard or via a script.
EOF

What is the syntax to insert one list into another list in python?

Do you mean append?

>>> x = [1,2,3]
>>> y = [4,5,6]
>>> x.append(y)
>>> x
[1, 2, 3, [4, 5, 6]]

Or merge?

>>> x = [1,2,3]
>>> y = [4,5,6]
>>> x + y
[1, 2, 3, 4, 5, 6]
>>> x.extend(y)
>>> x
[1, 2, 3, 4, 5, 6] 

PostgreSQL: insert from another table

You could use coalesce:

insert into destination select coalesce(field1,'somedata'),... from source;

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

RewriteEngine on
RewriteRule ^(.*)\.html$ $1.php%{QUERY_STRING} [L]

Put these two lines at the top of your .htaccess file. It will show .html in the URL for your .php pages.

RewriteEngine on
RewriteRule ^(.*)\.php$ $1.html%{QUERY_STRING} [L]

Use this for showing .php in URL for your .html pages.

Reordering arrays

Here is an immutable version for those who are interested:

function immutableMove(arr, from, to) {
  return arr.reduce((prev, current, idx, self) => {
    if (from === to) {
      prev.push(current);
    }
    if (idx === from) {
      return prev;
    }
    if (from < to) {
      prev.push(current);
    }
    if (idx === to) {
      prev.push(self[from]);
    }
    if (from > to) {
      prev.push(current);
    }
    return prev;
  }, []);
}

Make UINavigationBar transparent

After doing what everyone else said above, i.e.:

navigationController?.navigationBar.setBackgroundImage(UIImage(), forBarMetrics: .default)
navigationController?.navigationBar.shadowImage = UIImage()
navigationController!.navigationBar.isTranslucent = true

... my navigation bar was still white. So I added this line:

navigationController?.navigationBar.backgroundColor = .clear

... et voila! That seemed to do the trick.

How to make a Java Generic method static?

the only thing you can do is to change your signature to

public static <E> E[] appendToArray(E[] array, E item)

Important details:

Generic expressions preceding the return value always introduce (declare) a new generic type variable.

Additionally, type variables between types (ArrayUtils) and static methods (appendToArray) never interfere with each other.

So, what does this mean: In my answer <E> would hide the E from ArrayUtils<E> if the method wouldn't be static. AND <E> has nothing to do with the E from ArrayUtils<E>.

To reflect this fact better, a more correct answer would be:

public static <I> I[] appendToArray(I[] array, I item)

C multi-line macro: do/while(0) vs scope block

Andrey Tarasevich provides the following explanation:

  1. On Google Groups
  2. On bytes.com

[Minor changes to formatting made. Parenthetical annotations added in square brackets []].

The whole idea of using 'do/while' version is to make a macro which will expand into a regular statement, not into a compound statement. This is done in order to make the use of function-style macros uniform with the use of ordinary functions in all contexts.

Consider the following code sketch:

if (<condition>)
  foo(a);
else
  bar(a);

where foo and bar are ordinary functions. Now imagine that you'd like to replace function foo with a macro of the above nature [named CALL_FUNCS]:

if (<condition>)
  CALL_FUNCS(a);
else
  bar(a);

Now, if your macro is defined in accordance with the second approach (just { and }) the code will no longer compile, because the 'true' branch of if is now represented by a compound statement. And when you put a ; after this compound statement, you finished the whole if statement, thus orphaning the else branch (hence the compilation error).

One way to correct this problem is to remember not to put ; after macro "invocations":

if (<condition>)
  CALL_FUNCS(a)
else
  bar(a);

This will compile and work as expected, but this is not uniform. The more elegant solution is to make sure that macro expand into a regular statement, not into a compound one. One way to achieve that is to define the macro as follows:

#define CALL_FUNCS(x) \
do { \
  func1(x); \
  func2(x); \
  func3(x); \
} while (0)

Now this code:

if (<condition>)
  CALL_FUNCS(a);
else
  bar(a);

will compile without any problems.

However, note the small but important difference between my definition of CALL_FUNCS and the first version in your message. I didn't put a ; after } while (0). Putting a ; at the end of that definition would immediately defeat the entire point of using 'do/while' and make that macro pretty much equivalent to the compound-statement version.

I don't know why the author of the code you quoted in your original message put this ; after while (0). In this form both variants are equivalent. The whole idea behind using 'do/while' version is not to include this final ; into the macro (for the reasons that I explained above).

What is a .NET developer?

I'd say the minimum would be to

  • know one of the .Net Languages (C#, VB.NET, etc.)
  • know the basic working of the .Net runtime
  • know and understand the core parts of the .Net class libraries
  • have an understanding about what additional classes and functions are available as part of the .Net class libraries

Reference to non-static member function must be called

The problem is that buttonClickedEvent is a member function and you need a pointer to member in order to invoke it.

Try this:

void (MyClass::*func)(int);
func = &MyClass::buttonClickedEvent;

And then when you invoke it, you need an object of type MyClass to do so, for example this:

(this->*func)(<argument>);

http://www.codeguru.com/cpp/cpp/article.php/c17401/C-Tutorial-PointertoMember-Function.htm

Interesting 'takes exactly 1 argument (2 given)' Python error

Yes, when you invoke e.extractAll(foo), Python munges that into extractAll(e, foo).

From http://docs.python.org/tutorial/classes.html

the special thing about methods is that the object is passed as the first argument of the function. In our example, the call x.f() is exactly equivalent to MyClass.f(x). In general, calling a method with a list of n arguments is equivalent to calling the corresponding function with an argument list that is created by inserting the method’s object before the first argument.

Emphasis added.

Access 2010 VBA query a table and iterate through results

Ahh. Because I missed the point of you initial post, here is an example which also ITERATES. The first example did not. In this case, I retreive an ADODB recordset, then load the data into a collection, which is returned by the function to client code:

EDIT: Not sure what I screwed up in pasting the code, but the formatting is a little screwball. Sorry!

Public Function StatesCollection() As Collection
Dim cn As ADODB.Connection
Dim cmd As ADODB.Command
Dim rs As ADODB.Recordset
Dim colReturn As New Collection

Set colReturn = New Collection

Dim SQL As String
SQL = _
    "SELECT tblState.State, tblState.StateName " & _
    "FROM tblState"

Set cn = New ADODB.Connection
Set cmd = New ADODB.Command

With cn
    .Provider = DataConnection.MyADOProvider
    .ConnectionString = DataConnection.MyADOConnectionString
    .Open
End With

With cmd
    .CommandText = SQL
    .ActiveConnection = cn
End With

Set rs = cmd.Execute

With rs
    If Not .EOF Then
    Do Until .EOF
        colReturn.Add Nz(!State, "")
        .MoveNext
    Loop
    End If
    .Close
End With
cn.Close

Set rs = Nothing
Set cn = Nothing

Set StatesCollection = colReturn

End Function

Creating temporary files in bash

mktemp is probably the most versatile, especially if you plan to work with the file for a while.

You can also use a process substitution operator <() if you only need the file temporarily as input to another command, e.g.:

$ diff <(echo hello world) <(echo foo bar)

How can I see if a Perl hash already has a certain key?

I guess that this code should answer your question:

use strict;
use warnings;

my @keys = qw/one two three two/;
my %hash;
for my $key (@keys)
{
    $hash{$key}++;
}

for my $key (keys %hash)
{
   print "$key: ", $hash{$key}, "\n";
}

Output:

three: 1
one: 1
two: 2

The iteration can be simplified to:

$hash{$_}++ for (@keys);

(See $_ in perlvar.) And you can even write something like this:

$hash{$_}++ or print "Found new value: $_.\n" for (@keys);

Which reports each key the first time it’s found.

How can I change column types in Spark SQL's DataFrame?

Using Spark Sql 2.4.0 you can do that:

spark.sql("SELECT STRING(NULLIF(column,'')) as column_string")

How do I set the background color of Excel cells using VBA?

You can use either:

ActiveCell.Interior.ColorIndex = 28

or

ActiveCell.Interior.Color = RGB(255,0,0)

Disabling Log4J Output in Java

 log4j.rootLogger=OFF

Block Comments in a Shell Script

A variation on the here-doc trick in the accepted answer by sunny256 is to use the Perl keywords for comments. If your comments are actually some sort of documentation, you can then start using the Perl syntax inside the commented block, which allows you to print it out nicely formatted, convert it to a man-page, etc.

As far as the shell is concerned, you only need to replace 'END' with '=cut'.

echo "before comment"
: <<'=cut'
=pod

=head1 NAME
   podtest.sh - Example shell script with embedded POD documentation

etc.

=cut
echo "after comment"

(Found on "Embedding documentation in shell script")

Android Studio build fails with "Task '' not found in root project 'MyProject'."

Yet another solution to the same problem:

This happened to me every time I imported an eclipse project into studio using the wizard (studio version 1.3.2).

What I found, quite by chance, was that quitting out of Android studio and then restarting studio again made the problem go away.

Frustrating, but hope this helps someone...

How do I decode a string with escaped unicode?

Using JSON.decode for this comes with significant drawbacks that you must be aware of:

  • You must wrap the string in double quotes
  • Many characters are not supported and must be escaped themselves. For example, passing any of the following to JSON.decode (after wrapping them in double quotes) will error even though these are all valid: \\n, \n, \\0, a"a
  • It does not support hexadecimal escapes: \\x45
  • It does not support Unicode code point sequences: \\u{045}

There are other caveats as well. Essentially, using JSON.decode for this purpose is a hack and doesn't work the way you might always expect. You should stick with using the JSON library to handle JSON, not for string operations.


I recently ran into this issue myself and wanted a robust decoder, so I ended up writing one myself. It's complete and thoroughly tested and is available here: https://github.com/iansan5653/unraw. It mimics the JavaScript standard as closely as possible.

Explanation:

The source is about 250 lines so I won't include it all here, but essentially it uses the following Regex to find all escape sequences and then parses them using parseInt(string, 16) to decode the base-16 numbers and then String.fromCodePoint(number) to get the corresponding character:

/\\(?:(\\)|x([\s\S]{0,2})|u(\{[^}]*\}?)|u([\s\S]{4})\\u([^{][\s\S]{0,3})|u([\s\S]{0,4})|([0-3]?[0-7]{1,2})|([\s\S])|$)/g

Commented (NOTE: This regex matches all escape sequences, including invalid ones. If the string would throw an error in JS, it throws an error in my library [ie, '\x!!' will error]):

/
\\ # All escape sequences start with a backslash
(?: # Starts a group of 'or' statements
(\\) # If a second backslash is encountered, stop there (it's an escaped slash)
| # or
x([\s\S]{0,2}) # Match valid hexadecimal sequences
| # or
u(\{[^}]*\}?) # Match valid code point sequences
| # or
u([\s\S]{4})\\u([^{][\s\S]{0,3}) # Match surrogate code points which get parsed together
| # or
u([\s\S]{0,4}) # Match non-surrogate Unicode sequences
| # or
([0-3]?[0-7]{1,2}) # Match deprecated octal sequences
| # or
([\s\S]) # Match anything else ('.' doesn't match newlines)
| # or
$ # Match the end of the string
) # End the group of 'or' statements
/g # Match as many instances as there are

Example

Using that library:

import unraw from "unraw";

let step1 = unraw('http\\u00253A\\u00252F\\u00252Fexample.com');
// yields "http%3A%2F%2Fexample.com"
// Then you can use decodeURIComponent to further decode it:
let step2 = decodeURIComponent(step1);
// yields http://example.com

Deactivate or remove the scrollbar on HTML

If you really need it...

html { overflow-y: hidden; }

How to add a default include path for GCC in Linux?

Create an alias for gcc with your favorite includes.

alias mygcc='gcc -I /whatever/'

Why does DEBUG=False setting make my django Static Files Access fail?

Support for string view arguments to url() is deprecated and will be removed in Django 1.10

My solution is just small correction to Conrado solution above.

from django.conf import settings
import os
from django.views.static import serve as staticserve

if settings.DEBUG404:
    urlpatterns += patterns('',
        (r'^static/(?P<path>.*)$', staticserve,
            {'document_root': os.path.join(os.path.dirname(__file__), 'static')} ),
        )

How to trigger ngClick programmatically

This following solution works for me :

angular.element(document.querySelector('#myselector')).click();

instead of :

angular.element('#myselector').triggerHandler('click');

Install sbt on ubuntu

The simplest way of installing SBT on ubuntu is the deb package provided by Typesafe.

Run the following shell commands:

  1. wget http://apt.typesafe.com/repo-deb-build-0002.deb
  2. sudo dpkg -i repo-deb-build-0002.deb
  3. sudo apt-get update
  4. sudo apt-get install sbt

And you're done !

C# Inserting Data from a form into an access Database

and doesnt give any clues

Yes it does, unfortunately your code is ignoring all of those clues. Take a look at your exception handler:

catch (OleDbException  ex)
{
    MessageBox.Show(ex.Source);
    conn.Close();
}

All you're examining is the source of the exception. Which, in this case, is "Microsoft Access Database Engine". You're not examining the error message itself, or the stack trace, or any inner exception, or anything useful about the exception.

Don't ignore the exception, it contains information about what went wrong and why.

There are various logging tools out there (NLog, log4net, etc.) which can help you log useful information about an exception. Failing that, you should at least capture the exception message, stack trace, and any inner exception(s). Currently you're ignoring the error, which is why you're not able to solve the error.

In your debugger, place a breakpoint inside the catch block and examine the details of the exception. You'll find it contains a lot of information.

Label python data points on plot

How about print (x, y) at once.

from matplotlib import pyplot as plt

fig = plt.figure()
ax = fig.add_subplot(111)

A = -0.75, -0.25, 0, 0.25, 0.5, 0.75, 1.0
B = 0.73, 0.97, 1.0, 0.97, 0.88, 0.73, 0.54

plt.plot(A,B)
for xy in zip(A, B):                                       # <--
    ax.annotate('(%s, %s)' % xy, xy=xy, textcoords='data') # <--

plt.grid()
plt.show()

enter image description here

Remove gutter space for a specific div only

Update 2018

For Bootstrap 3, it's much easier. Bootstrap 3 now uses padding instead of margins to create the "gutter".

.row.no-gutter {
  margin-left: 0;
  margin-right: 0;
}

.row.no-gutter [class*='col-']:not(:first-child),
.row.no-gutter [class*='col-']:not(:last-child) {
  padding-right: 0;
  padding-left: 0;
}

Then just add no-gutter to any rows where spacing is to be removed:

  <div class="row no-gutter">
    <div class="col-lg-1"><div>1</div></div>
    <div class="col-lg-1"><div>1</div></div>
    <div class="col-lg-1"><div>1</div></div>
  </div>

Demo: http://bootply.com/107708

Bootstrap 4 (no extra CSS needed)

Bootstrap 4 includes a no-gutters class that can be applied to the entire row:

http://www.codeply.com/go/pVsGQZVVtG

<div class="row no-gutters">
    <div class="col">..</div>
    <div class="col">..</div>
    <div class="col">..</div>
</div>

There are also new spacing utils that enable control of padding/margins. So this can be used to change the padding (gutter) for a single column (ie: <div class="col-3 pl-0"></div>) sets padding-left:0; on the column, or use px-0 to remove both the left and right padding (x-axis).

ServletException, HttpServletResponse and HttpServletRequest cannot be resolved to a type

As a reason of this problem, some code is broken or undefined.You may see an error in a java class such as "The type javax.servlet.http.HttpSession cannot be resolved. It is indirectly referenced from required .class files". you shuold download " javax.servlet.jar" as mentioned before. Then configure your project build path, add the javax.servlet.jar as an external jar.I hope it fixes the problem.At least it worked for me.

HTTP Error 503. The service is unavailable. App pool stops on accessing website

In my case error message displaed in Windows Event Viewer -> Windows Logs -> Application was "The Module DLL C:\Windows\system32\inetsrv\rewrite.dll failed to load. The data is the error." Uninstalling rewrite module via installer solved the problem. I wasn't using any rewrite rules so I uninstalled rewrite module. Reinstalling the module may help the problem as well.

Using StringWriter for XML Serialization

First of all, beware of finding old examples. You've found one that uses XmlTextWriter, which is deprecated as of .NET 2.0. XmlWriter.Create should be used instead.

Here's an example of serializing an object into an XML column:

public void SerializeToXmlColumn(object obj)
{
    using (var outputStream = new MemoryStream())
    {
        using (var writer = XmlWriter.Create(outputStream))
        {
            var serializer = new XmlSerializer(obj.GetType());
            serializer.Serialize(writer, obj);
        }

        outputStream.Position = 0;
        using (var conn = new SqlConnection(Settings.Default.ConnectionString))
        {
            conn.Open();

            const string INSERT_COMMAND = @"INSERT INTO XmlStore (Data) VALUES (@Data)";
            using (var cmd = new SqlCommand(INSERT_COMMAND, conn))
            {
                using (var reader = XmlReader.Create(outputStream))
                {
                    var xml = new SqlXml(reader);

                    cmd.Parameters.Clear();
                    cmd.Parameters.AddWithValue("@Data", xml);
                    cmd.ExecuteNonQuery();
                }
            }
        }
    }
}

Proper way to wait for one function to finish before continuing?

One way to deal with asynchronous work like this is to use a callback function, eg:

function firstFunction(_callback){
    // do some asynchronous work
    // and when the asynchronous stuff is complete
    _callback();    
}

function secondFunction(){
    // call first function and pass in a callback function which
    // first function runs when it has completed
    firstFunction(function() {
        console.log('huzzah, I\'m done!');
    });    
}

As per @Janaka Pushpakumara's suggestion, you can now use arrow functions to achieve the same thing. For example:

firstFunction(() => console.log('huzzah, I\'m done!'))


Update: I answered this quite some time ago, and really want to update it. While callbacks are absolutely fine, in my experience they tend to result in code that is more difficult to read and maintain. There are situations where I still use them though, such as to pass in progress events and the like as parameters. This update is just to emphasise alternatives.

Also the original question doesn't specificallty mention async, so in case anyone is confused, if your function is synchronous, it will block when called. For example:

doSomething()
// the function below will wait until doSomething completes if it is synchronous
doSomethingElse()

If though as implied the function is asynchronous, the way I tend to deal with all my asynchronous work today is with async/await. For example:

const secondFunction = async () => {
  const result = await firstFunction()
  // do something else here after firstFunction completes
}

IMO, async/await makes your code much more readable than using promises directly (most of the time). If you need to handle catching errors then use it with try/catch. Read about it more here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function .

Javascript: How to remove the last character from a div or a string?

var string = "Hello";
var str = string.substring(0, string.length-1);
alert(str);

http://jsfiddle.net/d72ML/

jQuery.getJSON - Access-Control-Allow-Origin Issue

It's simple, use $.getJSON() function and in your URL just include

callback=?

as a parameter. That will convert the call to JSONP which is necessary to make cross-domain calls. More info: http://api.jquery.com/jQuery.getJSON/

Convert Month Number to Month Name Function in SQL

Starting with SQL Server 2012, you can use FORMAT and DATEFROMPARTS to solve this problem. (If you want month names from other cultures, change: en-US)

select FORMAT(DATEFROMPARTS(1900, @month_num, 1), 'MMMM', 'en-US')

If you want a three-letter month:

select FORMAT(DATEFROMPARTS(1900, @month_num, 1), 'MMM', 'en-US')

If you really want to, you can create a function for this:

CREATE FUNCTION fn_month_num_to_name
(
    @month_num tinyint
)
RETURNS varchar(20)
AS
BEGIN
    RETURN FORMAT(DATEFROMPARTS(1900, @month_num, 1), 'MMMM', 'en-US')
END

null check in jsf expression language

Use empty (it checks both nullness and emptiness) and group the nested ternary expression by parentheses (EL is in certain implementations/versions namely somewhat problematic with nested ternary expressions). Thus, so:

styleClass="#{empty obj.validationErrorMap ? ' ' :  
 (obj.validationErrorMap.contains('key') ? 'highlight_field' : 'highlight_row')}"

If still in vain (I would then check JBoss EL configs), use the "normal" EL approach:

styleClass="#{empty obj.validationErrorMap ? ' ' :  
 (obj.validationErrorMap['key'] ne null ? 'highlight_field' : 'highlight_row')}"

Update: as per the comments, the Map turns out to actually be a List (please work on your naming conventions). To check if a List contains an item the "normal" EL way, use JSTL fn:contains (although not explicitly documented, it works for List as well).

styleClass="#{empty obj.validationErrorMap ? ' ' :  
 (fn:contains(obj.validationErrorMap, 'key') ? 'highlight_field' : 'highlight_row')}"

Concatenating Column Values into a Comma-Separated List

Please try this with the following code:

DECLARE @listStr VARCHAR(MAX)
SELECT @listStr = COALESCE(@listStr+',' , '') + CarName
FROM Cars
SELECT @listStr

jackson deserialization json to java-objects

 JsonNode node = mapper.readValue("[{\"id\":\"value11\",\"name\": \"value12\",\"qty\":\"value13\"},"

 System.out.println("id : "+node.findValues("id").get(0).asText());

this also done the trick.

How to set menu to Toolbar in Android

Also you need this, to implement some action to every options of menu.

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case R.id.menu_help:
            Toast.makeText(this, "This is teh option help", Toast.LENGTH_LONG).show();
            break;
        default:
            break;
    }
    return true;
}

ASP.NET MVC passing an ID in an ActionLink to the controller

Doesn't look like you are using the correct overload of ActionLink. Try this:-

<%=Html.ActionLink("Modify Villa", "Modify", new {id = "1"})%>

This assumes your view is under the /Views/Villa folder. If not then I suspect you need:-

<%=Html.ActionLink("Modify Villa", "Modify", "Villa", new {id = "1"}, null)%>

How to delete an instantiated object Python?

object.__del__(self) is called when the instance is about to be destroyed.

>>> class Test:
...     def __del__(self):
...         print "deleted"
... 
>>> test = Test()
>>> del test
deleted

Object is not deleted unless all of its references are removed(As quoted by ethan)

Also, From Python official doc reference:

del x doesn’t directly call x.del() — the former decrements the reference count for x by one, and the latter is only called when x‘s reference count reaches zero

What does appending "?v=1" to CSS and JavaScript URLs in link and script tags do?

These are usually to make sure that the browser gets a new version when the site gets updated with a new version, e.g. as part of our build process we'd have something like this:

/Resources/Combined.css?v=x.x.x.buildnumber

Since this changes with every new code push, the client's forced to grab a new version, just because of the querystring. Look at this page (at the time of this answer) for example:

<link ... href="http://sstatic.net/stackoverflow/all.css?v=c298c7f8233d">

I think instead of a revision number the SO team went with a file hash, which is an even better approach, even with a new release, the browsers only forced to grab a new version when the file actually changes.

Both of these approaches allow you to set the cache header to something ridiculously long, say 20 years...yet when it changes, you don't have to worry about that cache header, the browser sees a different querystring and treats it as a different, new file.

jQuery AJAX file upload PHP

and this is the php file to receive the uplaoded files

<?
$data = array();
    //check with your logic
    if (isset($_FILES)) {
        $error = false;
        $files = array();

        $uploaddir = $target_dir;
        foreach ($_FILES as $file) {
            if (move_uploaded_file($file['tmp_name'], $uploaddir . basename( $file['name']))) {
                $files[] = $uploaddir . $file['name'];
            } else {
                $error = true;
            }
        }
        $data = ($error) ? array('error' => 'There was an error uploading your files') : array('files' => $files);
    } else {
        $data = array('success' => 'NO FILES ARE SENT','formData' => $_REQUEST);
    }

    echo json_encode($data);
?>

Django auto_now and auto_now_add

class Feedback(models.Model):
   feedback = models.CharField(max_length=100)
   created = models.DateTimeField(auto_now_add=True)
   updated = models.DateTimeField(auto_now=True)

Here, we have created and updated columns that will have a timestamp when created, and when someone modified feedback.

auto_now_add will set time when an instance is created whereas auto_now will set time when someone modified his feedback.

Bundler: Command not found

Make sure you do rbenv rehash when installing different rubies

Get program execution time in the shell

For a line-by-line delta measurement, try gnomon.

A command line utility, a bit like moreutils's ts, to prepend timestamp information to the standard output of another command. Useful for long-running processes where you'd like a historical record of what's taking so long.

You can also use the --high and/or --medium options to specify a length threshold in seconds, over which gnomon will highlight the timestamp in red or yellow. And you can do a few other things, too.

example

Is it possible to set a custom font for entire of application?

I would also like to improve weston's answer for API 21 Android 5.0.

I had the same issue on my Samsung s5, when using DEFAULT font. (with the others fonts it's working fine)

I managed to make it working by setting the typeface ("sans" for example) in XML files, for each Textview or Button

<TextView
android:layout_width="match_parent"
android:layout_height="39dp"
android:textColor="@color/abs__background_holo_light"
android:textSize="12sp"
android:gravity="bottom|center"
android:typeface="sans" />

and in MyApplication Class :

public class MyApplication extends Application {
    @Override
    public void onCreate() {
    TypefaceUtil.overrideFont(getApplicationContext(), "SANS_SERIF",
    "fonts/my_font.ttf");
    }
}

Hope it helps.

How do I use a pipe to redirect the output of one command to the input of another?

This should work:

for /F "tokens=*" %i in ('temperature') do prismcom.exe usb %i

If running in a batch file, you need to use %%i instead of just %i (in both places).

Error: Module not specified (IntelliJ IDEA)

This happened to me when I started to work with a colleque's project.

He was using jdk 12.0.2 .

If you are suspicious jdk difference might be the case (Your IDE complains about SDK, JDK etc.):

  1. Download the appropriate jdk
  2. Move new jdk to the folder of your choice. (I use C:\Program Files\Java)
  3. On Intellij, click to the dropdown on top middle bar. Click Edit Configurations. Change jdk.
  4. File -> Invalidate Caches and Restart.

CSS: Force float to do a whole new line

Use display:inline-block

You may also find vertical-align: top or vertical-align:middle useful.

In Java, should I escape a single quotation mark (') in String (double quoted)?

You don't need to escape the ' character in a String (wrapped in "), and you don't have to escape a " character in a char (wrapped in ').

Create PDF with Java

I prefer outputting my data into XML (using Castor, XStream or JAXB), then transforming it using a XSLT stylesheet into XSL-FO and render that with Apache FOP into PDF. Worked so far for 10-page reports and 400-page manuals. I found this more flexible and stylable than generating PDFs in code using iText.

Count frequency of words in a list and sort by frequency

You can use reduce() - A functional way.

words = "apple banana apple strawberry banana lemon"
reduce( lambda d, c: d.update([(c, d.get(c,0)+1)]) or d, words.split(), {})

returns:

{'strawberry': 1, 'lemon': 1, 'apple': 2, 'banana': 2}

import module from string variable

Apart from using the importlib one can also use exec method to import a module from a string variable.

Here I am showing an example of importing the combinations method from itertools package using the exec method:

MODULES = [
    ['itertools','combinations'],
]

for ITEM in MODULES:
    import_str = "from {0} import {1}".format(ITEM[0],', '.join(str(i) for i in ITEM[1:]))
    exec(import_str)

ar = list(combinations([1, 2, 3, 4], 2))
for elements in ar:
    print(elements)

Output:

(1, 2)
(1, 3)
(1, 4)
(2, 3)
(2, 4)
(3, 4)

How to close activity and go back to previous activity in android

Finish closes the whole application, this is is something i hate in Android development not finish that is fine but that they do not keep up wit ok syntax they have

startActivity(intent)

Why not

closeActivity(intent) ?

HTML table with horizontal scrolling (first column fixed)

How about:

_x000D_
_x000D_
table {_x000D_
  table-layout: fixed; _x000D_
  width: 100%;_x000D_
  *margin-left: -100px; /*ie7*/_x000D_
}_x000D_
td, th {_x000D_
  vertical-align: top;_x000D_
  border-top: 1px solid #ccc;_x000D_
  padding: 10px;_x000D_
  width: 100px;_x000D_
}_x000D_
.fix {_x000D_
  position: absolute;_x000D_
  *position: relative; /*ie7*/_x000D_
  margin-left: -100px;_x000D_
  width: 100px;_x000D_
}_x000D_
.outer {_x000D_
  position: relative;_x000D_
}_x000D_
.inner {_x000D_
  overflow-x: scroll;_x000D_
  overflow-y: visible;_x000D_
  width: 400px; _x000D_
  margin-left: 100px;_x000D_
}
_x000D_
<div class="outer">_x000D_
  <div class="inner">_x000D_
    <table>_x000D_
      <tr>_x000D_
        <th class=fix></th>_x000D_
        <th>Col 1</th>_x000D_
        <th>Col 2</th>_x000D_
        <th>Col 3</th>_x000D_
        <th>Col 4</th>_x000D_
        <th class="fix">Col 5</th>_x000D_
      </tr>_x000D_
      <tr>_x000D_
        <th class=fix>Header A</th>_x000D_
        <td>col 1 - A</td>_x000D_
        <td>col 2 - A (WITH LONGER CONTENT)</td>_x000D_
        <td>col 3 - A</td>_x000D_
        <td>col 4 - A</td>_x000D_
        <td class=fix>col 5 - A</td>_x000D_
      </tr>_x000D_
      <tr>_x000D_
        <th class=fix>Header B</th>_x000D_
        <td>col 1 - B</td>_x000D_
        <td>col 2 - B</td>_x000D_
        <td>col 3 - B</td>_x000D_
        <td>col 4 - B</td>_x000D_
        <td class=fix>col 5 - B</td>_x000D_
      </tr>_x000D_
      <tr>_x000D_
        <th class=fix>Header C</th>_x000D_
        <td>col 1 - C</td>_x000D_
        <td>col 2 - C</td>_x000D_
        <td>col 3 - C</td>_x000D_
        <td>col 4 - C</td>_x000D_
        <td class=fix>col 5 - C</td>_x000D_
      </tr>_x000D_
    </table>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

You can test it out in this jsbin: http://jsbin.com/uxecel/4/edit

get dataframe row count based on conditions

In Pandas, I like to use the shape attribute to get number of rows.

df[df.A > 0].shape[0]

gives the number of rows matching the condition A > 0, as desired.

How to create multiple class objects with a loop in python?

I hope this is what you are looking for.

class Try:
    def do_somthing(self):
        print 'Hello'

if __name__ == '__main__':
    obj_list = []
    for obj in range(10):
        obj = Try()
        obj_list.append(obj)

    obj_list[0].do_somthing()

Output:

Hello

member names cannot be the same as their enclosing type C#

just remove this because constructor don't have a return type like void it will be like this :

private Flow()
    {
        X = x;
        Y = y;
    }  

Iterate over elements of List and Map using JSTL <c:forEach> tag

Mark, this is already answered in your previous topic. But OK, here it is again:

Suppose ${list} points to a List<Object>, then the following

<c:forEach items="${list}" var="item">
    ${item}<br>
</c:forEach>

does basically the same as as following in "normal Java":

for (Object item : list) {
    System.out.println(item);
}

If you have a List<Map<K, V>> instead, then the following

<c:forEach items="${list}" var="map">
    <c:forEach items="${map}" var="entry">
        ${entry.key}<br>
        ${entry.value}<br>
    </c:forEach>
</c:forEach>

does basically the same as as following in "normal Java":

for (Map<K, V> map : list) {
    for (Entry<K, V> entry : map.entrySet()) {
        System.out.println(entry.getKey());
        System.out.println(entry.getValue());
    }
}

The key and value are here not special methods or so. They are actually getter methods of Map.Entry object (click at the blue Map.Entry link to see the API doc). In EL (Expression Language) you can use the . dot operator to access getter methods using "property name" (the getter method name without the get prefix), all just according the Javabean specification.

That said, you really need to cleanup the "answers" in your previous topic as they adds noise to the question. Also read the comments I posted in your "answers".

PHP class: Global variable as property in class

Simply use the global keyword.

e.g.:

class myClass() {
    private function foo() {
        global $MyNumber;
        ...

$MyNumber will then become accessible (and indeed modifyable) within that method.

However, the use of globals is often frowned upon (they can give off a bad code smell), so you might want to consider using a singleton class to store anything of this nature. (Then again, without knowing more about what you're trying to achieve this might be a very bad idea - a define could well be more useful.)

How do I change select2 box height

Here's my take on Carpetsmoker's answer (which I liked due to it being dynamic), cleaned up and updated for select2 v4:

$('#selectField').on('select2:open', function (e) {
  var container = $(this).select('select2-container');
  var position = container.offset().top;
  var availableHeight = $(window).height() - position - container.outerHeight();
  var bottomPadding = 50; // Set as needed
  $('ul.select2-results__options').css('max-height', (availableHeight - bottomPadding) + 'px');
});

How to change Visual Studio 2012,2013 or 2015 License Key?

For those of you using Visual Studio 2017 Professional, the registry key is:

HKCR\Licenses\5C505A59-E312-4B89-9508-E162F8150517

I also recommend you first export the registry key, before you delete it, so you'll have a backup if you accidentally delete the wrong key.

Append text using StreamWriter

using(StreamWriter writer = new StreamWriter("debug.txt", true))
{
  writer.WriteLine("whatever you text is");
}

The second "true" parameter tells it to append.

http://msdn.microsoft.com/en-us/library/36b035cb.aspx

Where do I find the line number in the Xcode editor?

  1. Go to Xcode preferences by clicking on "Xcode" in the left hand side upper corner.

  2. Select "Text Editing".

  3. Select "Show: Line numbers" and click on check box for enable it.

  4. Close it.

Then you will see the line number in Xcode.

No Creators, like default construct, exist): cannot deserialize from Object value (no delegate- or property-based Creator

I know this is an old post, but for anyone using Retrofit, this can be useful useful.

If you are using Retrofit + Jackson + Kotlin + Data classes, you need:

  1. add implement group: 'com.fasterxml.jackson.module', name: 'jackson-module-kotlin', version: '2.7.1-2' to your dependencies, so that Jackson can de-serialize into Data classes
  2. When building retrofit, pass the Kotlin Jackson Mapper, so that Retrofit uses the correct mapper, ex:
    val jsonMapper = com.fasterxml.jackson.module.kotlin.jacksonObjectMapper()

    val retrofit = Retrofit.Builder()
          ...
          .addConverterFactory(JacksonConverterFactory.create(jsonMapper))
          .build()

Note: If Retrofit is not being used, @Jayson Minard has a more general approach answer.

Slick.js: Get current and total slides (ie. 3/5)

Modifications are done to the new Slick version 1.7.1.

Here is a updated script example: jsfiddle

Force LF eol in git repo and working copy

To force LF line endings for all text files, you can create .gitattributes file in top-level of your repository with the following lines (change as desired):

# Ensure all C and PHP files use LF.
*.c         eol=lf
*.php       eol=lf

which ensures that all files that Git considers to be text files have normalized (LF) line endings in the repository (normally core.eol configuration controls which one do you have by default).

Based on the new attribute settings, any text files containing CRLFs should be normalized by Git. If this won't happen automatically, you can refresh a repository manually after changing line endings, so you can re-scan and commit the working directory by the following steps (given clean working directory):

$ echo "* text=auto" >> .gitattributes
$ rm .git/index     # Remove the index to force Git to
$ git reset         # re-scan the working directory
$ git status        # Show files that will be normalized
$ git add -u
$ git add .gitattributes
$ git commit -m "Introduce end-of-line normalization"

or as per GitHub docs:

git add . -u
git commit -m "Saving files before refreshing line endings"
git rm --cached -r . # Remove every file from Git's index.
git reset --hard # Rewrite the Git index to pick up all the new line endings.
git add . # Add all your changed files back, and prepare them for a commit.
git commit -m "Normalize all the line endings" # Commit the changes to your repository.

See also: @Charles Bailey post.

In addition, if you would like to exclude any files to not being treated as a text, unset their text attribute, e.g.

manual.pdf      -text

Or mark it explicitly as binary:

# Denote all files that are truly binary and should not be modified.
*.png binary
*.jpg binary

To see some more advanced git normalization file, check .gitattributes at Drupal core:

# Drupal git normalization
# @see https://www.kernel.org/pub/software/scm/git/docs/gitattributes.html
# @see https://www.drupal.org/node/1542048

# Normally these settings would be done with macro attributes for improved
# readability and easier maintenance. However macros can only be defined at the
# repository root directory. Drupal avoids making any assumptions about where it
# is installed.

# Define text file attributes.
# - Treat them as text.
# - Ensure no CRLF line-endings, neither on checkout nor on checkin.
# - Detect whitespace errors.
#   - Exposed by default in `git diff --color` on the CLI.
#   - Validate with `git diff --check`.
#   - Deny applying with `git apply --whitespace=error-all`.
#   - Fix automatically with `git apply --whitespace=fix`.

*.config  text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2
*.css     text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2
*.dist    text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2
*.engine  text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2 diff=php
*.html    text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2 diff=html
*.inc     text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2 diff=php
*.install text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2 diff=php
*.js      text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2
*.json    text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2
*.lock    text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2
*.map     text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2
*.md      text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2
*.module  text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2 diff=php
*.php     text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2 diff=php
*.po      text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2
*.profile text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2 diff=php
*.script  text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2
*.sh      text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2 diff=php
*.sql     text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2
*.svg     text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2
*.theme   text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2 diff=php
*.twig    text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2
*.txt     text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2
*.xml     text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2
*.yml     text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2

# Define binary file attributes.
# - Do not treat them as text.
# - Include binary diff in patches instead of "binary files differ."
*.eot     -text diff
*.exe     -text diff
*.gif     -text diff
*.gz      -text diff
*.ico     -text diff
*.jpeg    -text diff
*.jpg     -text diff
*.otf     -text diff
*.phar    -text diff
*.png     -text diff
*.svgz    -text diff
*.ttf     -text diff
*.woff    -text diff
*.woff2   -text diff

See also:

No provider for TemplateRef! (NgIf ->TemplateRef)

You missed the * in front of NgIf (like we all have, dozens of times):

<div *ngIf="answer.accepted">&#10004;</div>

Without the *, Angular sees that the ngIf directive is being applied to the div element, but since there is no * or <template> tag, it is unable to locate a template, hence the error.


If you get this error with Angular v5:

Error: StaticInjectorError[TemplateRef]:
  StaticInjectorError[TemplateRef]:
    NullInjectorError: No provider for TemplateRef!

You may have <template>...</template> in one or more of your component templates. Change/update the tag to <ng-template>...</ng-template>.

How to hide a div element depending on Model value? MVC

The below code should apply different CSS classes based on your Model's CanEdit Property value .

<div class="@(Model.CanEdit?"visible-item":"hidden-item")">Some links</div>

But if it is something important like Edit/Delete links, you shouldn't be simply hiding,because people can update the css class/HTML markup in their browser and get access to your important link. Instead you should be simply not Rendering the important stuff to the browser.

@if(Model.CanEdit)
{
  <div>Edit/Delete link goes here</div>
}

MySQL my.ini location

it is there at C:\Program Files\MySQL\MySQL Server 5.5 there are various .ini files with small, medium & large names. generally medium is used or it depends on your requirement.

What does jQuery.fn mean?

In jQuery, the fn property is just an alias to the prototype property.

The jQuery identifier (or $) is just a constructor function, and all instances created with it, inherit from the constructor's prototype.

A simple constructor function:

function Test() {
  this.a = 'a';
}
Test.prototype.b = 'b';

var test = new Test(); 
test.a; // "a", own property
test.b; // "b", inherited property

A simple structure that resembles the architecture of jQuery:

(function() {
  var foo = function(arg) { // core constructor
    // ensure to use the `new` operator
    if (!(this instanceof foo))
      return new foo(arg);
    // store an argument for this example
    this.myArg = arg;
    //..
  };

  // create `fn` alias to `prototype` property
  foo.fn = foo.prototype = {
    init: function () {/*...*/}
    //...
  };

  // expose the library
  window.foo = foo;
})();

// Extension:

foo.fn.myPlugin = function () {
  alert(this.myArg);
  return this; // return `this` for chainability
};

foo("bar").myPlugin(); // alerts "bar"

Combine Points with lines with ggplot2

The following example using the iris dataset works fine:

dat = melt(subset(iris, select = c("Sepal.Length","Sepal.Width", "Species")),
      id.vars = "Species")
ggplot(aes(x = 1:nrow(iris), y = value, color = variable), data = dat) +  
      geom_point() + geom_line()

enter image description here

Sorting a DropDownList? - C#, ASP.NET

If your data is coming to you as a System.Data.DataTable, call the DataTable's .Select() method, passing in "" for the filterExpression and "COLUMN1 ASC" (or whatever column you want to sort by) for the sort. This will return an array of DataRow objects, sorted as specified, that you can then iterate through and dump into the DropDownList.

How do I change the android actionbar title and icon

You just need to add these 3 lines of code. Replace the icon with your own icon. If you want to generate icons use this

getSupportActionBar().setHomeAsUpIndicator(R.drawable.icon_back_arrow);
getActionBar().setHomeButtonEnabled(true);
getActionBar().setDisplayHomeAsUpEnabled(true);

How to Refresh a Component in Angular

constructor(private router:Router, private route:ActivatedRoute ) { 
}

onReload(){
 this.router.navigate(['/servers'],{relativeTo:this.route})
}

Best way to do multi-row insert in Oracle?

This works in Oracle:

insert into pager (PAG_ID,PAG_PARENT,PAG_NAME,PAG_ACTIVE)
          select 8000,0,'Multi 8000',1 from dual
union all select 8001,0,'Multi 8001',1 from dual

The thing to remember here is to use the from dual statement.

python request with authentication (access_token)

I'll add a bit hint: it seems what you pass as the key value of a header depends on your authorization type, in my case that was PRIVATE-TOKEN

header = {'PRIVATE-TOKEN': 'my_token'}
response = requests.get(myUrl, headers=header)

Execute PHP scripts within Node.js web server

You can try to implement direct link node -> fastcgi -> php. In the previous answer, nginx serves php requests using http->fastcgi serialisation->unix socket->php and node requests as http->nginx reverse proxy->node http server.

It seems that node-fastcgi paser is useable at the moment, but only as a node fastcgi backend. You need to adopt it to use as a fastcgi client to php fastcgi server.

iOS - Build fails with CocoaPods cannot find header files

One simple workaround is: 1. Delete Pods folder and Podfile.lock file. But don't delete Podfile 2. Run following command in your project root folder:

pod install

Escape sequence \f - form feed - what exactly is it?

It comes from the era of Line Printers and green-striped fan-fold paper.

Trust me, you ain't gonna need it...

Find specific string in a text file with VBS script

Try to change like this ..

firstStr = "<?xml version" 'my file always starts like this

Do until objInputFile.AtEndOfStream  

    strToAdd = "<tr><td><a href=" & chr(34) & "../../Logs/DD/Beginning_of_DD_TC" & CStr(index) & ".html" & chr(34) & ">Beginning_of_DD_TC" & CStr(index) & "</a></td></tr>"  

   substrToFind = "<tr><td><a href=" & chr(34) & "../Test case " & trim(cstr((index)))

   tmpStr = objInputFile.ReadLine

   If InStr(tmpStr, substrToFind) <= 0 Then
       If Instr(tmpStr, firstStr) > 0 Then
          text = tmpStr 'to avoid the first empty line
       Else
          text = text & vbCrLf & tmpStr
       End If
   Else
      text = text & vbCrLf & strToAdd & vbCrLf & tmpStr

   End If
   index = index + 1
Loop

Connection Java-MySql : Public Key Retrieval is not allowed

This also can be happened due to wrong user name or password. As solutions I've added allowPublicKeyRetrieval=true&useSSL=false part but still I got error then I checked the password and it was wrong.

Programmatic equivalent of default(Type)

Why do you say generics are out of the picture?

    public static object GetDefault(Type t)
    {
        Func<object> f = GetDefault<object>;
        return f.Method.GetGenericMethodDefinition().MakeGenericMethod(t).Invoke(null, null);
    }

    private static T GetDefault<T>()
    {
        return default(T);
    }

Background blur with CSS

In recent versions of major browsers you can use backdrop-filter property.

HTML

<div>backdrop blur</div>

CSS

div {
    -webkit-backdrop-filter: blur(10px);
    backdrop-filter: blur(10px);
}

or if you need different background color for browsers without support:

div {
    background-color: rgba(255, 255, 255, 0.9);
}

@supports (-webkit-backdrop-filter: none) or (backdrop-filter: none) {
    div {
        -webkit-backdrop-filter: blur(10px);
        backdrop-filter: blur(10px);
        background-color: rgba(255, 255, 255, 0.5);  
    }
}

Demo: JSFiddle

Docs: Mozilla Developer: backdrop-filter

Is it for me?: CanIUse

Recyclerview inside ScrollView not scrolling smoothly

XML code:

<android.support.v4.widget.NestedScrollView
            android:layout_width="match_parent"
            android:layout_height="match_parent">

            <android.support.v7.widget.RecyclerView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:clipToPadding="false" />

        </android.support.v4.widget.NestedScrollView>

in java code :

  recycleView = (RecyclerView) findViewById(R.id.recycleView);
     recycleView.setNestedScrollingEnabled(false);

How to Compare a long value is equal to Long value

First your code is not compiled. Line Long b = 1113;

is wrong. You have to say

Long b = 1113L;

Second when I fixed this compilation problem the code printed "not equals".

Byte Array and Int conversion in Java

here is my implementation

public static byte[] intToByteArray(int a) {
    return BigInteger.valueOf(a).toByteArray();
}

public static int byteArrayToInt(byte[] b) {
    return new BigInteger(b).intValue();
}

Bootstrap Dropdown with Hover

Try this using hover function with fadein fadeout animations

$('ul.nav li.dropdown').hover(function() {
  $(this).find('.dropdown-menu').stop(true, true).delay(200).fadeIn(500);
}, function() {
  $(this).find('.dropdown-menu').stop(true, true).delay(200).fadeOut(500);
});

How can I inspect element in chrome when right click is disabled?

Use Ctrl+Shift+C (or Cmd+Shift+C on Mac) to open the DevTools in Inspect Element mode, or toggle Inspect Element mode if the DevTools are already open.

How to change color of SVG image using CSS (jQuery SVG image replacement)?

Here's a version for knockout.js based on the accepted answer:

Important: It does actually require jQuery too for the replacing, but I thought it may be useful to some.

ko.bindingHandlers.svgConvert =
    {
        'init': function ()
        {
            return { 'controlsDescendantBindings': true };
        },

        'update': function (element, valueAccessor, allBindings, viewModel, bindingContext)
        {
            var $img = $(element);
            var imgID = $img.attr('id');
            var imgClass = $img.attr('class');
            var imgURL = $img.attr('src');

            $.get(imgURL, function (data)
            {
                // Get the SVG tag, ignore the rest
                var $svg = $(data).find('svg');

                // Add replaced image's ID to the new SVG
                if (typeof imgID !== 'undefined')
                {
                    $svg = $svg.attr('id', imgID);
                }
                // Add replaced image's classes to the new SVG
                if (typeof imgClass !== 'undefined')
                {
                    $svg = $svg.attr('class', imgClass + ' replaced-svg');
                }

                // Remove any invalid XML tags as per http://validator.w3.org
                $svg = $svg.removeAttr('xmlns:a');

                // Replace image with new SVG
                $img.replaceWith($svg);

            }, 'xml');

        }
    };

Then just apply data-bind="svgConvert: true" to your img tag.

This solution completely replaces the img tag with a SVG and any additional bindings would not be respected.

How can I render HTML from another file in a React component?

You can use dangerouslySetInnerHTML to do this:

import React from 'react';
function iframe() {
    return {
        __html: '<iframe src="./Folder/File.html" width="540" height="450"></iframe>'
    }
}


export default function Exercises() {
    return (
        <div>
            <div dangerouslySetInnerHTML={iframe()} />
        </div>)
}

HTML files must be in the public folder

Seeing the console's output in Visual Studio 2010?

You could create 2 small methods, one that can be called at the beginning of the program, the other at the end. You could also use Console.Read(), so that the program doesn't close after the last write line.

This way you can determine when your functionality gets executed and also when the program exists.

startProgram()
{
     Console.WriteLine("-------Program starts--------");
     Console.Read();
}


endProgram()
{
    Console.WriteLine("-------Program Ends--------");
    Console.Read();
}

Trying to fire the onload event on script tag

You should set the src attribute after the onload event, f.ex:

el.onload = function() { //...
el.src = script;

You should also append the script to the DOM before attaching the onload event:

$body.append(el);
el.onload = function() { //...
el.src = script;

Remember that you need to check readystate for IE support. If you are using jQuery, you can also try the getScript() method: http://api.jquery.com/jQuery.getScript/

How to configure "Shorten command line" method for whole project in IntelliJ

Thanks to Rajesh Goel in Android Studio:

Run > Edit Configurations...

enter image description here

Select a test (better to select a parent test class) and set a Shorten command line: option to classpath file. Then OK (or Apply, OK).

enter image description here

Python: pandas merge multiple dataframes

@everestial007 's solution worked for me. This is how I improved it for my use case, which is to have the columns of each different df with a different suffix so I can more easily differentiate between the dfs in the final merged dataframe.

from functools import reduce
import pandas as pd
dfs = [df1, df2, df3, df4]
suffixes = [f"_{i}" for i in range(len(dfs))]
# add suffixes to each df
dfs = [dfs[i].add_suffix(suffixes[i]) for i in range(len(dfs))]
# remove suffix from the merging column
dfs = [dfs[i].rename(columns={f"date{suffixes[i]}":"date"}) for i in range(len(dfs))]
# merge
dfs = reduce(lambda left,right: pd.merge(left,right,how='outer', on='date'), dfs)

Generating random numbers with Swift

let MAX : UInt32 = 9
let MIN : UInt32 = 1 
func randomNumber()
{
   var random_number = Int(arc4random_uniform(MAX) + MIN)
   print ("random = ", random_number);    
}

How to reload page the page with pagination in Angular 2?

This should technically be achievable using window.location.reload():

HTML:

<button (click)="refresh()">Refresh</button>

TS:

refresh(): void {
    window.location.reload();
}

Update:

Here is a basic StackBlitz example showing the refresh in action. Notice the URL on "/hello" path is retained when window.location.reload() is executed.

Bash: Strip trailing linebreak from output

One way:

wc -l < log.txt | xargs echo -n

Calculate the mean by group

There are many ways to do this in R. Specifically, by, aggregate, split, and plyr, cast, tapply, data.table, dplyr, and so forth.

Broadly speaking, these problems are of the form split-apply-combine. Hadley Wickham has written a beautiful article that will give you deeper insight into the whole category of problems, and it is well worth reading. His plyr package implements the strategy for general data structures, and dplyr is a newer implementation performance tuned for data frames. They allow for solving problems of the same form but of even greater complexity than this one. They are well worth learning as a general tool for solving data manipulation problems.

Performance is an issue on very large datasets, and for that it is hard to beat solutions based on data.table. If you only deal with medium-sized datasets or smaller, however, taking the time to learn data.table is likely not worth the effort. dplyr can also be fast, so it is a good choice if you want to speed things up, but don't quite need the scalability of data.table.

Many of the other solutions below do not require any additional packages. Some of them are even fairly fast on medium-large datasets. Their primary disadvantage is either one of metaphor or of flexibility. By metaphor I mean that it is a tool designed for something else being coerced to solve this particular type of problem in a 'clever' way. By flexibility I mean they lack the ability to solve as wide a range of similar problems or to easily produce tidy output.


Examples

base functions

tapply:

tapply(df$speed, df$dive, mean)
#     dive1     dive2 
# 0.5419921 0.5103974

aggregate:

aggregate takes in data.frames, outputs data.frames, and uses a formula interface.

aggregate( speed ~ dive, df, mean )
#    dive     speed
# 1 dive1 0.5790946
# 2 dive2 0.4864489

by:

In its most user-friendly form, it takes in vectors and applies a function to them. However, its output is not in a very manipulable form.:

res.by <- by(df$speed, df$dive, mean)
res.by
# df$dive: dive1
# [1] 0.5790946
# ---------------------------------------
# df$dive: dive2
# [1] 0.4864489

To get around this, for simple uses of by the as.data.frame method in the taRifx library works:

library(taRifx)
as.data.frame(res.by)
#    IDX1     value
# 1 dive1 0.6736807
# 2 dive2 0.4051447

split:

As the name suggests, it performs only the "split" part of the split-apply-combine strategy. To make the rest work, I'll write a small function that uses sapply for apply-combine. sapply automatically simplifies the result as much as possible. In our case, that means a vector rather than a data.frame, since we've got only 1 dimension of results.

splitmean <- function(df) {
  s <- split( df, df$dive)
  sapply( s, function(x) mean(x$speed) )
}
splitmean(df)
#     dive1     dive2 
# 0.5790946 0.4864489 

External packages

data.table:

library(data.table)
setDT(df)[ , .(mean_speed = mean(speed)), by = dive]
#    dive mean_speed
# 1: dive1  0.5419921
# 2: dive2  0.5103974

dplyr:

library(dplyr)
group_by(df, dive) %>% summarize(m = mean(speed))

plyr (the pre-cursor of dplyr)

Here's what the official page has to say about plyr:

It’s already possible to do this with base R functions (like split and the apply family of functions), but plyr makes it all a bit easier with:

  • totally consistent names, arguments and outputs
  • convenient parallelisation through the foreach package
  • input from and output to data.frames, matrices and lists
  • progress bars to keep track of long running operations
  • built-in error recovery, and informative error messages
  • labels that are maintained across all transformations

In other words, if you learn one tool for split-apply-combine manipulation it should be plyr.

library(plyr)
res.plyr <- ddply( df, .(dive), function(x) mean(x$speed) )
res.plyr
#    dive        V1
# 1 dive1 0.5790946
# 2 dive2 0.4864489

reshape2:

The reshape2 library is not designed with split-apply-combine as its primary focus. Instead, it uses a two-part melt/cast strategy to perform a wide variety of data reshaping tasks. However, since it allows an aggregation function it can be used for this problem. It would not be my first choice for split-apply-combine operations, but its reshaping capabilities are powerful and thus you should learn this package as well.

library(reshape2)
dcast( melt(df), variable ~ dive, mean)
# Using dive as id variables
#   variable     dive1     dive2
# 1    speed 0.5790946 0.4864489

Benchmarks

10 rows, 2 groups

library(microbenchmark)
m1 <- microbenchmark(
  by( df$speed, df$dive, mean),
  aggregate( speed ~ dive, df, mean ),
  splitmean(df),
  ddply( df, .(dive), function(x) mean(x$speed) ),
  dcast( melt(df), variable ~ dive, mean),
  dt[, mean(speed), by = dive],
  summarize( group_by(df, dive), m = mean(speed) ),
  summarize( group_by(dt, dive), m = mean(speed) )
)

> print(m1, signif = 3)
Unit: microseconds
                                           expr  min   lq   mean median   uq  max neval      cld
                    by(df$speed, df$dive, mean)  302  325  343.9    342  362  396   100  b      
              aggregate(speed ~ dive, df, mean)  904  966 1012.1   1020 1060 1130   100     e   
                                  splitmean(df)  191  206  249.9    220  232 1670   100 a       
  ddply(df, .(dive), function(x) mean(x$speed)) 1220 1310 1358.1   1340 1380 2740   100      f  
         dcast(melt(df), variable ~ dive, mean) 2150 2330 2440.7   2430 2490 4010   100        h
                   dt[, mean(speed), by = dive]  599  629  667.1    659  704  771   100   c     
 summarize(group_by(df, dive), m = mean(speed))  663  710  774.6    744  782 2140   100    d    
 summarize(group_by(dt, dive), m = mean(speed)) 1860 1960 2051.0   2020 2090 3430   100       g 

autoplot(m1)

benchmark 10 rows

As usual, data.table has a little more overhead so comes in about average for small datasets. These are microseconds, though, so the differences are trivial. Any of the approaches works fine here, and you should choose based on:

  • What you're already familiar with or want to be familiar with (plyr is always worth learning for its flexibility; data.table is worth learning if you plan to analyze huge datasets; by and aggregate and split are all base R functions and thus universally available)
  • What output it returns (numeric, data.frame, or data.table -- the latter of which inherits from data.frame)

10 million rows, 10 groups

But what if we have a big dataset? Let's try 10^7 rows split over ten groups.

df <- data.frame(dive=factor(sample(letters[1:10],10^7,replace=TRUE)),speed=runif(10^7))
dt <- data.table(df)
setkey(dt,dive)

m2 <- microbenchmark(
  by( df$speed, df$dive, mean),
  aggregate( speed ~ dive, df, mean ),
  splitmean(df),
  ddply( df, .(dive), function(x) mean(x$speed) ),
  dcast( melt(df), variable ~ dive, mean),
  dt[,mean(speed),by=dive],
  times=2
)

> print(m2, signif = 3)
Unit: milliseconds
                                           expr   min    lq    mean median    uq   max neval      cld
                    by(df$speed, df$dive, mean)   720   770   799.1    791   816   958   100    d    
              aggregate(speed ~ dive, df, mean) 10900 11000 11027.0  11000 11100 11300   100        h
                                  splitmean(df)   974  1040  1074.1   1060  1100  1280   100     e   
  ddply(df, .(dive), function(x) mean(x$speed))  1050  1080  1110.4   1100  1130  1260   100      f  
         dcast(melt(df), variable ~ dive, mean)  2360  2450  2492.8   2490  2520  2620   100       g 
                   dt[, mean(speed), by = dive]   119   120   126.2    120   122   212   100 a       
 summarize(group_by(df, dive), m = mean(speed))   517   521   531.0    522   532   620   100   c     
 summarize(group_by(dt, dive), m = mean(speed))   154   155   174.0    156   189   321   100  b      

autoplot(m2)

benchmark 1e7 rows, 10 groups

Then data.table or dplyr using operating on data.tables is clearly the way to go. Certain approaches (aggregate and dcast) are beginning to look very slow.

10 million rows, 1,000 groups

If you have more groups, the difference becomes more pronounced. With 1,000 groups and the same 10^7 rows:

df <- data.frame(dive=factor(sample(seq(1000),10^7,replace=TRUE)),speed=runif(10^7))
dt <- data.table(df)
setkey(dt,dive)

# then run the same microbenchmark as above
print(m3, signif = 3)
Unit: milliseconds
                                           expr   min    lq    mean median    uq   max neval    cld
                    by(df$speed, df$dive, mean)   776   791   816.2    810   828   925   100  b    
              aggregate(speed ~ dive, df, mean) 11200 11400 11460.2  11400 11500 12000   100      f
                                  splitmean(df)  5940  6450  7562.4   7470  8370 11200   100     e 
  ddply(df, .(dive), function(x) mean(x$speed))  1220  1250  1279.1   1280  1300  1440   100   c   
         dcast(melt(df), variable ~ dive, mean)  2110  2190  2267.8   2250  2290  2750   100    d  
                   dt[, mean(speed), by = dive]   110   111   113.5    111   113   143   100 a     
 summarize(group_by(df, dive), m = mean(speed))   625   630   637.1    633   644   701   100  b    
 summarize(group_by(dt, dive), m = mean(speed))   129   130   137.3    131   142   213   100 a     

autoplot(m3)

enter image description here

So data.table continues scaling well, and dplyr operating on a data.table also works well, with dplyr on data.frame close to an order of magnitude slower. The split/sapply strategy seems to scale poorly in the number of groups (meaning the split() is likely slow and the sapply is fast). by continues to be relatively efficient--at 5 seconds, it's definitely noticeable to the user but for a dataset this large still not unreasonable. Still, if you're routinely working with datasets of this size, data.table is clearly the way to go - 100% data.table for the best performance or dplyr with dplyr using data.table as a viable alternative.

How to serve all existing static files directly with NGINX, but proxy the rest to a backend server.

If you use mod_rewrite to hide the extension of your scripts, or if you just like pretty URLs that end in /, then you might want to approach this from the other direction. Tell nginx to let anything with a non-static extension to go through to apache. For example:

location ~* ^.+\.(jpg|jpeg|gif|png|ico|css|zip|tgz|gz|rar|bz2|pdf|txt|tar|wav|bmp|rtf|js|flv|swf|html|htm)$
{
    root   /path/to/static-content;
}

location ~* ^!.+\.(jpg|jpeg|gif|png|ico|css|zip|tgz|gz|rar|bz2|pdf|txt|tar|wav|bmp|rtf|js|flv|swf|html|htm)$ {
    if (!-f $request_filename) {
        return 404;
    }
    proxy_set_header X-Real-IP  $remote_addr;
    proxy_set_header Host $host;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_pass http://127.0.0.1:8080;
}

I found the first part of this snippet over at: http://code.google.com/p/scalr/wiki/NginxStatic

javascript /jQuery - For Loop

.each() should work for you. http://api.jquery.com/jQuery.each/ or http://api.jquery.com/each/ or you could use .map.

var newArray = $(array).map(function(i) {
    return $('#event' + i, response).html();
});

Edit: I removed the adding of the prepended 0 since it is suggested to not use that.

If you must have it use

var newArray = $(array).map(function(i) {
    var number = '' + i;
    if (number.length == 1) {
        number = '0' + number;
    }   
    return $('#event' + number, response).html();
});

Landscape printing from HTML

You might be able to use the CSS 2 @page rule which allows you to set the 'size' property to landscape.

How to trigger SIGUSR1 and SIGUSR2?

They are signals that application developers use. The kernel shouldn't ever send these to a process. You can send them using kill(2) or using the utility kill(1).

If you intend to use signals for synchronization you might want to check real-time signals (there's more of them, they are queued, their delivery order is guaranteed etc).

MS Excel showing the formula in a cell instead of the resulting value

Make sure that...

  • There's an = sign before the formula
  • There's no white space before the = sign
  • There are no quotes around the formula (must be =A1, instead of "=A1")
  • You're not in formula view (hit Ctrl + ` to switch between modes)
  • The cell format is set to General instead of Text
  • If simply changing the format doesn't work, hit F2, Enter
  • Undoing actions (CTRL+Z) back until the value shows again and then simply redoing all those actions with CTRL-Y also worked for some users

Get specific line from text file using just shell script

Assuming line is a variable which holds your required line number, if you can use head and tail, then it is quite simple:

head -n $line file | tail -1

If not, this should work:

x=0
want=5
cat lines | while read line; do
  x=$(( x+1 ))
  if [ $x -eq "$want" ]; then
    echo $line
    break
  fi
done

Global variables in c#.net

Use a public static class and access it from anywhere.

public static class MyGlobals {
    public const string Prefix = "ID_"; // cannot change
    public static int Total = 5; // can change because not const
}

used like so, from master page or anywhere:

string strStuff = MyGlobals.Prefix + "something";
textBox1.Text = "total of " + MyGlobals.Total.ToString();

You don't need to make an instance of the class; in fact you can't because it's static. new Just use it directly. All members inside a static class must also be static. The string Prefix isn't marked static because const is implicitly static by nature.

The static class can be anywhere in your project. It doesn't have to be part of Global.asax or any particular page because it's "global" (or at least as close as we can get to that concept in object-oriented terms.)

You can make as many static classes as you like and name them whatever you want.


Sometimes programmers like to group their constants by using nested static classes. For example,

public static class Globals {
    public static class DbProcedures {
        public const string Sp_Get_Addresses = "dbo.[Get_Addresses]";
        public const string Sp_Get_Names = "dbo.[Get_First_Names]";
    }
    public static class Commands {
        public const string Go = "go";
        public const string SubmitPage = "submit_now";
    }
}

and access them like so:

MyDbCommand proc = new MyDbCommand( Globals.DbProcedures.Sp_Get_Addresses );
proc.Execute();
//or
string strCommand = Globals.Commands.Go;

How to convert password into md5 in jquery?

<script src="http://crypto-js.googlecode.com/svn/tags/3.0.2/build/rollups/md5.js"></script>
<script>
    var passhash = CryptoJS.MD5(password).toString();

    $.post(
      'includes/login.php', 
      { user: username, pass: passhash },
      onLogin, 
      'json' );
</script>

Nested ng-repeat

If you have a big nested JSON object and using it across several screens, you might face performance issues in page loading. I always go for small individual JSON objects and query the related objects as lazy load only where they are required.

you can achieve it using ng-init

<td class="lectureClass" ng-repeat="s in sessions" ng-init='presenters=getPresenters(s.id)'>
      {{s.name}}
      <div class="presenterClass" ng-repeat="p in presenters">
          {{p.name}}
      </div>
</td> 

The code on the controller side should look like below

$scope.getPresenters = function(id) {
    return SessionPresenters.get({id: id});
};

While the API factory is as follows:

angular.module('tryme3App').factory('SessionPresenters', function ($resource, DateUtils) {

        return $resource('api/session.Presenters/:id', {}, {
            'query': { method: 'GET', isArray: true},
            'get': {
                method: 'GET', isArray: true
            },
            'update': { method:'PUT' }
        });
    });

Google OAuth 2 authorization - Error: redirect_uri_mismatch

Checklist:

  • http or https?
  • & or &amp;?
  • trailing slash(/) or open ?
  • (CMD/CTRL)+F, search for the exact match in the credential page. If not found then search for the missing one.
  • Wait until google refreshes it. May happen in each half an hour if you are changing frequently or it may stay in the pool. For my case it was almost half an hour to take effect.

How to change Android usb connect mode to charge only?

Nothing worked until I went this way: Settings>Developer options>Default USB configuration now you can choose your default USB connection purpose.

How can I get a list of locally installed Python modules?

Solution

Do not use with pip > 10.0!

My 50 cents for getting a pip freeze-like list from a Python script:

import pip
installed_packages = pip.get_installed_distributions()
installed_packages_list = sorted(["%s==%s" % (i.key, i.version)
     for i in installed_packages])
print(installed_packages_list)

As a (too long) one liner:

sorted(["%s==%s" % (i.key, i.version) for i in pip.get_installed_distributions()])

Giving:

['behave==1.2.4', 'enum34==1.0', 'flask==0.10.1', 'itsdangerous==0.24', 
 'jinja2==2.7.2', 'jsonschema==2.3.0', 'markupsafe==0.23', 'nose==1.3.3', 
 'parse-type==0.3.4', 'parse==1.6.4', 'prettytable==0.7.2', 'requests==2.3.0',
 'six==1.6.1', 'vioozer-metadata==0.1', 'vioozer-users-server==0.1', 
 'werkzeug==0.9.4']

Scope

This solution applies to the system scope or to a virtual environment scope, and covers packages installed by setuptools, pip and (god forbid) easy_install.

My use case

I added the result of this call to my flask server, so when I call it with http://example.com/exampleServer/environment I get the list of packages installed on the server's virtualenv. It makes debugging a whole lot easier.

Caveats

I have noticed a strange behaviour of this technique - when the Python interpreter is invoked in the same directory as a setup.py file, it does not list the package installed by setup.py.

Steps to reproduce:

Create a virtual environment
$ cd /tmp
$ virtualenv test_env
New python executable in test_env/bin/python
Installing setuptools, pip...done.
$ source test_env/bin/activate
(test_env) $ 
Clone a git repo with setup.py
(test_env) $ git clone https://github.com/behave/behave.git
Cloning into 'behave'...
remote: Reusing existing pack: 4350, done.
remote: Total 4350 (delta 0), reused 0 (delta 0)
Receiving objects: 100% (4350/4350), 1.85 MiB | 418.00 KiB/s, done.
Resolving deltas: 100% (2388/2388), done.
Checking connectivity... done.

We have behave's setup.py in /tmp/behave:

(test_env) $ ls /tmp/behave/setup.py
/tmp/behave/setup.py
Install the python package from the git repo
(test_env) $ cd /tmp/behave && pip install . 
running install
...
Installed /private/tmp/test_env/lib/python2.7/site-packages/enum34-1.0-py2.7.egg
Finished processing dependencies for behave==1.2.5a1

If we run the aforementioned solution from /tmp

>>> import pip
>>> sorted(["%s==%s" % (i.key, i.version) for i in pip.get_installed_distributions()])
['behave==1.2.5a1', 'enum34==1.0', 'parse-type==0.3.4', 'parse==1.6.4', 'six==1.6.1']
>>> import os
>>> os.getcwd()
'/private/tmp'

If we run the aforementioned solution from /tmp/behave

>>> import pip
>>> sorted(["%s==%s" % (i.key, i.version) for i in pip.get_installed_distributions()])
['enum34==1.0', 'parse-type==0.3.4', 'parse==1.6.4', 'six==1.6.1']
>>> import os
>>> os.getcwd()
'/private/tmp/behave'

behave==1.2.5a1 is missing from the second example, because the working directory contains behave's setup.py file.

I could not find any reference to this issue in the documentation. Perhaps I shall open a bug for it.

ReferenceError: Invalid left-hand side in assignment

Common reasons for the error:

  • use of assignment (=) instead of equality (==/===)
  • assigning to result of function foo() = 42 instead of passing arguments (foo(42))
  • simply missing member names (i.e. assuming some default selection) : getFoo() = 42 instead of getFoo().theAnswer = 42 or array indexing getArray() = 42 instead of getArray()[0]= 42

In this particular case you want to use == (or better === - What exactly is Type Coercion in Javascript?) to check for equality (like if(one === "rock" && two === "rock"), but it the actual reason you are getting the error is trickier.

The reason for the error is Operator precedence. In particular we are looking for && (precedence 6) and = (precedence 3).

Let's put braces in the expression according to priority - && is higher than = so it is executed first similar how one would do 3+4*5+6 as 3+(4*5)+6:

 if(one= ("rock" && two) = "rock"){...

Now we have expression similar to multiple assignments like a = b = 42 which due to right-to-left associativity executed as a = (b = 42). So adding more braces:

 if(one= (  ("rock" && two) = "rock" )  ){...

Finally we arrived to actual problem: ("rock" && two) can't be evaluated to l-value that can be assigned to (in this particular case it will be value of two as truthy).

Note that if you'd use braces to match perceived priority surrounding each "equality" with braces you get no errors. Obviously that also producing different result than you'd expect - changes value of both variables and than do && on two strings "rock" && "rock" resulting in "rock" (which in turn is truthy) all the time due to behavior of logial &&:

if((one = "rock") && (two = "rock"))
{
   // always executed, both one and two are set to "rock"
   ...
}

For even more details on the error and other cases when it can happen - see specification:

Assignment

LeftHandSideExpression = AssignmentExpression
...
Throw a SyntaxError exception if the following conditions are all true:
...
IsStrictReference(lref) is true

Left-Hand-Side Expressions

and The Reference Specification Type explaining IsStrictReference:

... function calls are permitted to return references. This possibility is admitted purely for the sake of host objects. No built-in ECMAScript function defined by this specification returns a reference and there is no provision for a user-defined function to return a reference...

How to "set a breakpoint in malloc_error_break to debug"

I had the same problem with Xcode. I followed steps you gave and it didn't work. I became crazy because in every forum I saw, all clues for this problem are the one you gave. I finally saw I put a space after the malloc_error_break, I suppressed it and now it works. A dumb problem but if the solution doesn't work, be sure you haven't put any space before and after the malloc_error_break.

Hope this message will help..

Is it possible to view RabbitMQ message contents directly from the command line?

If you want multiple messages from a queue, say 10 messages, the command to use is:

rabbitmqadmin get queue=<QueueName> ackmode=ack_requeue_true count=10

If you don't want the messages requeued, just change ackmode to ack_requeue_false.

str.startswith with a list of strings to test for

str.startswith allows you to supply a tuple of strings to test for:

if link.lower().startswith(("js", "catalog", "script", "katalog")):

From the docs:

str.startswith(prefix[, start[, end]])

Return True if string starts with the prefix, otherwise return False. prefix can also be a tuple of prefixes to look for.

Below is a demonstration:

>>> "abcde".startswith(("xyz", "abc"))
True
>>> prefixes = ["xyz", "abc"]
>>> "abcde".startswith(tuple(prefixes)) # You must use a tuple though
True
>>>

Running multiple async tasks and waiting for them all to complete

The best option I've seen is the following extension method:

public static Task ForEachAsync<T>(this IEnumerable<T> sequence, Func<T, Task> action) {
    return Task.WhenAll(sequence.Select(action));
}

Call it like this:

await sequence.ForEachAsync(item => item.SomethingAsync(blah));

Or with an async lambda:

await sequence.ForEachAsync(async item => {
    var more = await GetMoreAsync(item);
    await more.FrobbleAsync();
});

What is the difference between fastcgi and fpm?

What Anthony says is absolutely correct, but I'd like to add that your experience will likely show a lot better performance and efficiency (due not to fpm-vs-fcgi but more to the implementation of your httpd).

For example, I had a quad-core machine running lighttpd + fcgi humming along nicely. I upgraded to a 16-core machine to cope with growth, and two things exploded: RAM usage, and segfaults. I found myself restarting lighttpd every 30 minutes to keep the website up.

I switched to php-fpm and nginx, and RAM usage dropped from >20GB to 2GB. Segfaults disappeared as well. After doing some research, I learned that lighttpd and fcgi don't get along well on multi-core machines under load, and also have memory leak issues in certain instances.

Is this due to php-fpm being better than fcgi? Not entirely, but how you hook into php-fpm seems to be a whole heckuva lot more efficient than how you serve via fcgi.

ReactJS - Get Height of an element

For those who are interested in using react hooks, this might help you get started.

import React, { useState, useEffect, useRef } from 'react'

export default () => {
  const [height, setHeight] = useState(0)
  const ref = useRef(null)

  useEffect(() => {
    setHeight(ref.current.clientHeight)
  })

  return (
    <div ref={ref}>
      {height}
    </div>
  )
}

Chrome Extension - Get DOM content

The terms "background page", "popup", "content script" are still confusing you; I strongly suggest a more in-depth look at the Google Chrome Extensions Documentation.

Regarding your question if content scripts or background pages are the way to go:

Content scripts: Definitely
Content scripts are the only component of an extension that has access to the web-page's DOM.

Background page / Popup: Maybe (probably max. 1 of the two)
You may need to have the content script pass the DOM content to either a background page or the popup for further processing.


Let me repeat that I strongly recommend a more careful study of the available documentation!
That said, here is a sample extension that retrieves the DOM content on StackOverflow pages and sends it to the background page, which in turn prints it in the console:

background.js:

// Regex-pattern to check URLs against. 
// It matches URLs like: http[s]://[...]stackoverflow.com[...]
var urlRegex = /^https?:\/\/(?:[^./?#]+\.)?stackoverflow\.com/;

// A function to use as callback
function doStuffWithDom(domContent) {
    console.log('I received the following DOM content:\n' + domContent);
}

// When the browser-action button is clicked...
chrome.browserAction.onClicked.addListener(function (tab) {
    // ...check the URL of the active tab against our pattern and...
    if (urlRegex.test(tab.url)) {
        // ...if it matches, send a message specifying a callback too
        chrome.tabs.sendMessage(tab.id, {text: 'report_back'}, doStuffWithDom);
    }
});

content.js:

// Listen for messages
chrome.runtime.onMessage.addListener(function (msg, sender, sendResponse) {
    // If the received message has the expected format...
    if (msg.text === 'report_back') {
        // Call the specified callback, passing
        // the web-page's DOM content as argument
        sendResponse(document.all[0].outerHTML);
    }
});

manifest.json:

{
  "manifest_version": 2,
  "name": "Test Extension",
  "version": "0.0",
  ...

  "background": {
    "persistent": false,
    "scripts": ["background.js"]
  },
  "content_scripts": [{
    "matches": ["*://*.stackoverflow.com/*"],
    "js": ["content.js"]
  }],
  "browser_action": {
    "default_title": "Test Extension"
  },

  "permissions": ["activeTab"]
}

Do Git tags only apply to the current branch?

CharlesB's answer and helmbert's answer are both helpful, but it took me a while to understand them. Here's another way of putting it:

  • A tag is a pointer to a commit, and commits exist independently of branches.
    • It is important to understand that tags have no direct relationship with branches - they only ever identify a commit.
      • That commit can be pointed to from any number of branches - i.e., it can be part of the history of any number of branches - including none.
    • Therefore, running git show <tag> to see a tag's details contains no reference to any branches, only the ID of the commit that the tag points to.
      • (Commit IDs (a.k.a. object names or SHA-1 IDs) are 40-character strings composed of hex. digits that are hashes over the contents of a commit; e.g.: 6f6b5997506d48fc6267b0b60c3f0261b6afe7a2)
  • Branches come into play only indirectly:
    • At the time of creating a tag, by implying the commit that the tag will point to:
      • Not specifying a target for a tag defaults to the current branch's most recent commit (a.k.a. HEAD); e.g.:
        • git tag v0.1.0 # tags HEAD of *current* branch
      • Specifying a branch name as the tag target defaults to that branch's most recent commit; e.g.:
        • git tag v0.1.0 develop # tags HEAD of 'develop' branch
      • (As others have noted, you can also specify a commit ID explicitly as the tag's target.)
    • When using git describe to describe the current branch:
      • git describe [--tags] describes the current branch in terms of the commits since the most recent [possibly lightweight] tag in this branch's history.
      • Thus, the tag referenced by git describe may NOT reflect the most recently created tag overall.

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

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

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

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

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

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

Get last 3 characters of string

The easiest way would be using Substring

string str = "AM0122200204";
string substr = str.Substring(str.Length - 3);

Using the overload with one int as I put would get the substring of a string, starting from the index int. In your case being str.Length - 3, since you want to get the last three chars.

UICollectionView - dynamic cell height?

TL;DR: Scan down to image, and then check out working project here.

Updating my answer for a simpler solution that I found..

In my case, I wanted to fix the width, and have variable height cells. I wanted a drop in, reusable solution that handled rotation and didn't require a lot of intervention.

What I arrived at, was override (just) systemLayoutFitting(...) in the collection cell (in this case a base class for me), and first defeat UICollectionView's effort to set the wrong dimension on contentView by adding a constraint for the known dimension, in this case, the width.

class EstimatedWidthCell: UICollectionViewCell {
    override init(frame: CGRect) {
        super.init(frame: frame)
        contentView.translatesAutoresizingMaskIntoConstraints = false
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        contentView.translatesAutoresizingMaskIntoConstraints = false
    }

    override func systemLayoutSizeFitting(
        _ targetSize: CGSize, withHorizontalFittingPriority
        horizontalFittingPriority: UILayoutPriority,
        verticalFittingPriority: UILayoutPriority) -> CGSize {

        width.constant = targetSize.width

and then return the final size for the cell - used for (and this feels like a bug) the dimension of the cell itself, but not contentView - which is otherwise constrained to a conflicting size (hence the constraint above). To calculate the correct cell size, I use a lower priority for the dimension that I wanted to float, and I get back the height required to fit the content within the width to which I want to fix:

        let size = contentView.systemLayoutSizeFitting(
            CGSize(width: targetSize.width, height: 1),
            withHorizontalFittingPriority: .required,
            verticalFittingPriority: verticalFittingPriority)

        print("\(#function) \(#line) \(targetSize) -> \(size)")
        return size
    }

    lazy var width: NSLayoutConstraint = {
        return contentView.widthAnchor
            .constraint(equalToConstant: bounds.size.width)
            .isActive(true)
    }()
}

But where does this width come from? It is configured via the estimatedItemSize on the collection view's flow layout:

lazy var collectionView: UICollectionView = {
    let view = UICollectionView(frame: CGRect(), collectionViewLayout: layout)
    view.backgroundColor = .cyan
    view.translatesAutoresizingMaskIntoConstraints = false
    return view
}()

lazy var layout: UICollectionViewFlowLayout = {
    let layout = UICollectionViewFlowLayout()
    let width = view.bounds.size.width // should adjust for inset
    layout.estimatedItemSize = CGSize(width: width, height: 10)
    layout.scrollDirection = .vertical
    return layout
}()

Finally, to handle rotation, I implement trailCollectionDidChange to invalidate the layout:

override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
    layout.estimatedItemSize = CGSize(width: view.bounds.size.width, height: 10)
    layout.invalidateLayout()
    super.traitCollectionDidChange(previousTraitCollection)
}

The final result looks like this:

enter image description here

And I have published a working sample here.

Insert multiple rows with one query MySQL

In most cases inserting multiple records with one Insert statement is much faster in MySQL than inserting records with for/foreach loop in PHP.

Let's assume $column1 and $column2 are arrays with same size posted by html form.

You can create your query like this:

<?php
    $query = 'INSERT INTO TABLE (`column1`, `column2`) VALUES ';
    $query_parts = array();
    for($x=0; $x<count($column1); $x++){
        $query_parts[] = "('" . $column1[$x] . "', '" . $column2[$x] . "')";
    }
    echo $query .= implode(',', $query_parts);
?>

If data is posted for two records the query will become:

INSERT INTO TABLE (column1, column2) VALUES ('data', 'data'), ('data', 'data')

Configuring Git over SSH to login once

If you have cloned using HTTPS (recommended) then:-

git config --global credential.helper cache

and then

git config --global credential.helper 'cache --timeout=2592000'
  • timeout=2592000 (30 Days in seconds) to enable caching for 30 days (or whatever suites you).

  • Now run a simple git command that requires your username and password.

  • Enter your credentials once and now caching is enabled for 30 Days.

  • Try again with any git command and now you don't need any credentials.

  • For more info :- Caching your GitHub password in Git

Note : You need Git 1.7.10 or newer to use the credential helper. On system restart, we might have to enter the password again.

Update #1:

If you are receiving this error git: 'credential-cache' is not a git command. See 'get --help'

then replace git config --global credential.helper 'cache --timeout=2592000'

with git config --global credential.helper 'store --file ~/.my-credentials'

Update #2:

If you keep getting the prompt of username and password and getting this issue:

Logon failed, use ctrl+c to cancel basic credential prompt.

Reinstalling the latest version of git worked for me.

Angular 2 @ViewChild annotation returns undefined

If you're using Ionic you'll need to use the ionViewDidEnter() lifecycle hook. Ionic runs some additional stuff (mainly animation-related) which typically causes unexpected errors like this, hence the need for something that runs after ngOnInit, ngAfterContentInit, and so on.

CSS Input with width: 100% goes outside parent's bound

Do you want the input fields to be centered? A trick to center elements: specify the width of the element and set the margin to auto, eg:

margin : 0px auto;
width:300px

A link to your updated fiddle:

http://jsfiddle.net/4x2KP/5/

Pagination using MySQL LIMIT, OFFSET

Use .. LIMIT :pageSize OFFSET :pageStart

Where :pageStart is bound to the_page_index (i.e. 0 for the first page) * number_of_items_per_pages (e.g. 4) and :pageSize is bound to number_of_items_per_pages.

To detect for "has more pages", either use SQL_CALC_FOUND_ROWS or use .. LIMIT :pageSize OFFSET :pageStart + 1 and detect a missing last (pageSize+1) record. Needless to say, for pages with an index > 0, there exists a previous page.

If the page index value is embedded in the URL (e.g. in "prev page" and "next page" links) then it can be obtained via the appropriate $_GET item.

Dropping Unique constraint from MySQL table

The constraint could be removed with syntax:

ALTER TABLE

As of MySQL 8.0.19, ALTER TABLE permits more general (and SQL standard) syntax for dropping and altering existing constraints of any type, where the constraint type is determined from the constraint name: ALTER TABLE tbl_name DROP CONSTRAINT symbol;

Example:

CREATE TABLE tab(id INT, CONSTRAINT unq_tab_id UNIQUE(id));

-- checking constraint name if autogenerated
SELECT * FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE TABLE_NAME = 'tab';

-- dropping constraint
ALTER TABLE tab DROP CONSTRAINT unq_tab_id;

db<>fiddle demo

How to return a string from a C++ function?

string str1, str2, str3;

cout << "These are the strings: " << endl;
cout << "str1: \"the dog jumped over the fence\"" << endl;
cout << "str2: \"the\"" << endl;
cout << "str3: \"that\"" << endl << endl;

From this, I see that you have not initialized str1, str2, or str3 to contain the values that you are printing. I might suggest doing so first:

string str1 = "the dog jumped over the fence", 
       str2 = "the",
       str3 = "that";

cout << "These are the strings: " << endl;
cout << "str1: \"" << str1 << "\"" << endl;
cout << "str2: \"" << str2 << "\"" << endl;
cout << "str3: \"" << str3 << "\"" << endl << endl;

What is C# analog of C++ std::pair?

Since .NET 4.0 you have System.Tuple<T1, T2> class:

// pair is implicitly typed local variable (method scope)
var pair = System.Tuple.Create("Current century", 21);

scp from Linux to Windows

I had to use pscp like above Hesham's post once I downloaded and installed putty. I did it to Windows from Linux on Windows so I entered the following:

c:\ssl>pscp username@linuxserver:keenan/ssl/* .

This will copy everything in the keenan/ssl folder to the local folder (.) you performed this command from (c:\ssl). The keenan/ssl will specify the home folder of the username user, for example the full path would be /home/username/keenan/ssl. You can specify a different folder using a forward slash (/), such as

c:\ssl>pscp username@linuxserver:/home/username/keenan/ssl/* .

So you can specify any folder at the root of Linux using :/.

href="file://" doesn't work

The reason your URL is being rewritten to file///K:/AmberCRO%20SOP/2011-07-05/SOP-SOP-3.0.pdf is because you specified http://file://

The http:// at the beginning is the protocol being used, and your browser is stripping out the second colon (:) because it is invalid.

Note

If you link to something like

<a href="file:///K:/yourfile.pdf">yourfile.pdf</a>

The above represents a link to a file called k:/yourfile.pdf on the k: drive on the machine on which you are viewing the URL.

You can do this, for example the below creates a link to C:\temp\test.pdf

<a href="file:///C:/Temp/test.pdf">test.pdf</a>

By specifying file:// you are indicating that this is a local resource. This resource is NOT on the internet.

Most people do not have a K:/ drive.

But, if this is what you are trying to achieve, that's fine, but this is not how a "typical" link on a web page works, and you shouldn't being doing this unless everyone who is going to access your link has access to the (same?) K:/drive (this might be the case with a shared network drive).

You could try

<a href="file:///K:/AmberCRO-SOP/2011-07-05/SOP-SOP-3.0.pdf">test.pdf</a>
<a href="AmberCRO-SOP/2011-07-05/SOP-SOP-3.0.pdf">test.pdf</a>
<a href="2011-07-05/SOP-SOP-3.0.pdf">test.pdf</a>

Note that http://file:///K:/AmberCRO%20SOP/2011-07-05/SOP-SOP-3.0.pdf is a malformed

How to display with n decimal places in Matlab

You can convert a number to a string with n decimal places using the SPRINTF command:

>> x = 1.23;
>> sprintf('%0.6f', x)

ans =

1.230000

>> x = 1.23456789;
>> sprintf('%0.6f', x)

ans =

1.234568

Opening a folder in explorer and selecting a file

Use "/select,c:\file.txt"

Notice there should be a comma after /select instead of space..

What are the differences between LinearLayout, RelativeLayout, and AbsoluteLayout?

Definitions:

  • Frame Layout: This is designed to block out an area on the screen to display a single item.
  • Linear Layout: A layout that arranges its children in a single column or a single row.
  • Relative Layout: This layout is a view group that displays child views in relative positions.
  • Table Layout: A layout that arranges its children into rows and columns.

More Information:

FrameLayout

FrameLayout is designed to block out an area on the screen to display a single item. Generally, FrameLayout should be used to hold a single child view, because it can be difficult to organize child views in a way that's scalable to different screen sizes without the children overlapping each other. You can, however, add multiple children to a FrameLayout and control their position within the FrameLayout by assigning gravity to each child, using the android:layout_gravity attribute.

Child views are drawn in a stack, with the most recently added child on top. The size of the FrameLayout is the size of its largest child (plus padding), visible or not (if the FrameLayout's parent permits).

RelativeLayout

A RelativeLayout is a very powerful utility for designing a user interface because it can eliminate nested view groups and keep your layout hierarchy flat, which improves performance. If you find yourself using several nested LinearLayout groups, you may be able to replace them with a single RelativeLayout.

(Current docs here)

TableLayout

A TableLayout consists of a number of TableRow objects, each defining a row (actually, you can have other children, which will be explained below). TableLayout containers do not display border lines for their rows, columns, or cells. Each row has zero or more cells; each cell can hold one View object. The table has as many columns as the row with the most cells. A table can leave cells empty. Cells can span columns, as they can in HTML.

The width of a column is defined by the row with the widest cell in that column.


Note: Absolute Layout is deprecated.

How to install a package inside virtualenv?

Sharing what has worked for me in both Ubuntu and Windows. This is for python3. To do for python2, replace "3" with "2":

Ubuntu

pip install virtualenv --user
virtualenv -p python3 /tmp/VIRTUAL
source /tmp/VIRTUAL/bin/activate
which python3

To install any package: pip install package

To get out of the virtual environment: deactivate

To activate again: source /tmp/VIRTUAL/bin/activate

Full explanation here.

Windows

(Assuming you have MiniConda installed and are in the Start Menu > Anaconda > Anaconda Terminal)

conda create -n VIRTUAL python=3  
activate VIRTUAL

To install any package: pip install package or conda install package

To get out of the virtual environment: deactivate

To activate again: activate VIRTUAL

Full explanation here.

How do you enable auto-complete functionality in Visual Studio C++ express edition?

All the answers were missing Ctrl-J (which enables and disables autocomplete).

Send email from localhost running XAMMP in PHP using GMAIL mail server

Simplest way is to use PHPMailer and Gmail SMTP. The configuration would be like the below.

require 'PHPMailer/PHPMailerAutoload.php';
$mail = new PHPMailer;

$mail->isSMTP();                            
$mail->Host = 'smtp.gmail.com';            
$mail->SMTPAuth = true;                     
$mail->Username = 'Email Address';          
$mail->Password = 'Email Account Password'; 
$mail->SMTPSecure = 'tls';               
$mail->Port = 587;                  

Example script and full source code can be found from here - How to Send Email from Localhost in PHP

Quicker way to get all unique values of a column in VBA?

Use Excel's AdvancedFilter function to do this.

Using Excels inbuilt C++ is the fastest way with smaller datasets, using the dictionary is faster for larger datasets. For example:

Copy values in Column A and insert the unique values in column B:

Range("A1:A6").AdvancedFilter Action:=xlFilterCopy, CopyToRange:=Range("B1"), Unique:=True

It works with multiple columns too:

Range("A1:B4").AdvancedFilter Action:=xlFilterCopy, CopyToRange:=Range("D1:E1"), Unique:=True

Be careful with multiple columns as it doesn't always work as expected. In those cases I resort to removing duplicates which works by choosing a selection of columns to base uniqueness. Ref: MSDN - Find and remove duplicates

enter image description here

Here I remove duplicate columns based on the third column:

Range("A1:C4").RemoveDuplicates Columns:=3, Header:=xlNo

Here I remove duplicate columns based on the second and third column:

Range("A1:C4").RemoveDuplicates Columns:=Array(2, 3), Header:=xlNo

Importing files from different folder

If you have multiple folders and sub folders, you can always import any class or module from the main directory.

For example: Tree structure of the project

Project 
+-- main.py
+-- .gitignore
|
+-- src
     +----model
     |    +-- user_model.py
     |----controller
          +-- user_controller.py

Now, if you want to import "UserModel" class from user_model.py in main.py file, you can do that using:

from src.model.user_model.py import UserModel

Also, you can import same class in user_controller.py file using same line:

from src.model.user_model.py import UserModel

Overall, you can give reference of main project directory to import classes and files in any python file inside Project directory.

nvarchar(max) vs NText

You should apparently use nvarchar(max):

MSDN

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

As Oriol said, you need the following redistributables before installing WAMP.

From the readme.txt

BEFORE proceeding with the installation of Wampserver, you must ensure that certain elements are installed on your system, otherwise Wampserver will absolutely not run, and in addition, the installation will be faulty and you need to remove Wampserver BEFORE installing the elements that were missing.

Make sure you are "up to date" in the redistributable packages VC9, VC10, VC11, VC13 and VC14 Even if you think you are up to date, install each package as administrator and if message "Already installed", validate Repair.

The following packages (VC9, VC10, VC11) are imperatively required to Wampserver 2.4, 2.5 and 3.0, even if you use only Apache and PHP versions VC11 and VC14 is required for PHP 7 and Apache 2.4.17

https://support.microsoft.com/en-us/help/2977003/the-latest-supported-visual-c-downloads

Email and phone Number Validation in android

For check email and phone number you need to do that

public static boolean isValidMobile(String phone) {
    boolean check = false;
    if (!Pattern.matches("[a-zA-Z]+", phone)) {
        if (phone.length() < 9 || phone.length() > 13) {
            // if(phone.length() != 10) {
            check = false;
            // txtPhone.setError("Not Valid Number");
        } else {
            check = android.util.Patterns.PHONE.matcher(phone).matches();
        }
    } else {
        check = false;
    }
    return check;
}

public static boolean isEmailValid(String email) {
    boolean check;
    Pattern p;
    Matcher m;

    String EMAIL_STRING = "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@"
            + "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";

    p = Pattern.compile(EMAIL_STRING);

    m = p.matcher(email);
    check = m.matches();

    return check;
}



String enter_mob_or_email="";//1234567890 or [email protected]
if (isValidMobile(enter_mob_or_email)) {// Phone number is valid

}else isEmailValid(enter_mob_or_email){//Email is valid

}else{// Not valid email or phone number

}

toBe(true) vs toBeTruthy() vs toBeTrue()

Disclamer: This is just a wild guess

I know everybody loves an easy-to-read list:

  • toBe(<value>) - The returned value is the same as <value>
  • toBeTrue() - Checks if the returned value is true
  • toBeTruthy() - Check if the value, when cast to a boolean, will be a truthy value

    Truthy values are all values that aren't 0, '' (empty string), false, null, NaN, undefined or [] (empty array)*.

    * Notice that when you run !![], it returns true, but when you run [] == false it also returns true. It depends on how it is implemented. In other words: (!![]) === ([] == false)


On your example, toBe(true) and toBeTrue() will yield the same results.

How to Convert JSON object to Custom C# object?

A good way to use JSON in C# is with JSON.NET

Quick Starts & API Documentation from JSON.NET - Official site help you work with it.

An example of how to use it:

public class User
{
    public User(string json)
    {
        JObject jObject = JObject.Parse(json);
        JToken jUser = jObject["user"];
        name = (string) jUser["name"];
        teamname = (string) jUser["teamname"];
        email = (string) jUser["email"];
        players = jUser["players"].ToArray();
    }

    public string name { get; set; }
    public string teamname { get; set; }
    public string email { get; set; }
    public Array players { get; set; }
}

// Use
private void Run()
{
    string json = @"{""user"":{""name"":""asdf"",""teamname"":""b"",""email"":""c"",""players"":[""1"",""2""]}}";
    User user = new User(json);

    Console.WriteLine("Name : " + user.name);
    Console.WriteLine("Teamname : " + user.teamname);
    Console.WriteLine("Email : " + user.email);
    Console.WriteLine("Players:");

    foreach (var player in user.players)
        Console.WriteLine(player);
 }

Is the buildSessionFactory() Configuration method deprecated in Hibernate

Code verified to work in Hibernate 4.3.0. Notice you can remove the XML filename parameter, or else provide your own path there. This is similar to (but typos corrected) other posts here, but this one is correct.

import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;    


Configuration configuration = new Configuration();
configuration.configure("/com/rtw/test/hiber/hibernate.cfg.xml");
ServiceRegistry  serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build();        
    sessionFactory = configuration.buildSessionFactory(serviceRegistry);

Enabling refreshing for specific html elements only

Try this in your script:

$("#YourElement").html(htmlData);

I do this in my table refreshment.

How to print a string in C++

You can't call "printf" with a std::string in parameter. The "%s" is designed for C-style string : char* or char []. In C++ you can do like that :

#include <iostream>
std::cout << YourString << std::endl;

If you absolutely want to use printf, you can use the "c_str()" method that give a char* representation of your string.

printf("%s\n",YourString.c_str())

How to implement "confirmation" dialog in Jquery UI dialog?

Very popular topic and google finds this for "jquery dialog close which event was clicked" query. My solution handles YES,NO,ESC_KEY,X events properly. I want my callback function be called no matter how dialog was disposed.

function dialog_YES_NO(sTitle, txt, fn) {
    $("#dialog-main").dialog({
        title: sTitle,
        resizable: true,
        //height:140,
        modal: true,
        open: function() { $(this).data("retval", false); $(this).text(txt); },
        close: function(evt) {
            var arg1 = $(this).data("retval")==true;
            setTimeout(function() { fn(arg1); }, 30);
        },
        buttons: {
            "Yes": function() { $(this).data("retval", true); $(this).dialog("close"); },
            "No": function()  { $(this).data("retval", false); $(this).dialog("close"); }
        }
    });
}
- - - - 
dialog_YES_NO("Confirm Delete", "Delete xyz item?", function(status) {
   alert("Dialog retval is " + status);
});

It's easy to redirect browser to a new url or perform something else on function retval.

what is the differences between sql server authentication and windows authentication..?

I don't know SQLServer as well as other DBMS' but I imagine the benefit is the same as with DB2 and Oracle. If you use Windows authentication, you only have to maintain one set of users and/or passwords, that of Windows, which is already done for you.

DBMS authentication means having a separate set of users and/or passwords which must be maintained.

In addition, Windows passwords allow them to be configured centrally for the enterprise (Active Directory) whereas SQLServer has to maintain one set for each DBMS instance.

Convert string to number and add one

Parse the Id as it would be string and then add.

e.g.

$('.load_more').live("click",function() { //When user clicks
    var newcurrentpageTemp = parseInt($(this).attr("id")) + 1;//Get the id from the hyperlink
    alert(newcurrentpageTemp);
    dosomething();
});

Adding minutes to date time in PHP

As noted by Brad and Nemoden in their answers above, strtotime() is a great function. Personally, I found the standard DateTime Object to be overly complicated for many use cases. I just wanted to add 5 minutes to the current time, for example.

I wrote a function that returns a date as a string with some optional parameters:
1.) time:String | ex: "+5 minutes" (default = current time)
2.) format:String | ex: "Y-m-d H:i:s" (default = "Y-m-d H:i:s O")

Obviously, this is not a fully featured method. Just a quick and simple function for modifying/formatting the current date.

function get_date($time=null, $format='Y-m-d H:i:s O')
{
    if(empty($time))return date($format);
    return date($format, strtotime($time));
}

// Example #1: Return current date in default format
$date = get_date(); 

// Example #2: Add 5 minutes to the current date
$date = get_date("+5 minutes"); 

// Example #3: Subtract 30 days from the current date & format as 'Y-m-d H:i:s'
$date = get_date("-30 days", "Y-m-d H:i:s"); 

Bootstrap Carousel image doesn't align properly

The solution is to put this CSS code into your custom CSS file:

.carousel-inner > .item > img {
  margin: 0 auto;
}

How to increase font size in a plot in R?

You want something like the cex=1.5 argument to scale fonts 150 percent. But do see help(par) as there are also cex.lab, cex.axis, ...

How can I get browser to prompt to save password?

Using a cookie would probably be the best way to do this.

You could have a checkbox for 'Remember me?' and have the form create a cookie to store the //user's login// info. EDIT: User Session Information

To create a cookie, you'll need to process the login form with PHP.

"Cannot update paths and switch to branch at the same time"

This simple thing worked for me!

If it says it can't do 2 things at same time, separate them.

git branch branch_name origin/branch_name 

git checkout branch_name

Set default format of datetimepicker as dd-MM-yyyy

Ensure that control Format property is properly set to use a custom format:

DateTimePicker1.Format = DateTimePickerFormat.Custom

Then this is how you can set your desired format:

DateTimePicker1.CustomFormat = "dd-MM-yyyy"

What exactly does numpy.exp() do?

It calculates ex for each x in your list where e is Euler's number (approximately 2.718). In other words, np.exp(range(5)) is similar to [math.e**x for x in range(5)].

Converting a String to Object

String extends Object, which means an Object. Object o = a; If you really want to get as Object, you may do like below.

String s = "Hi";

Object a =s;

How to append text to a text file in C++?

You could use an fstream and open it with the std::ios::app flag. Have a look at the code below and it should clear your head.

...
fstream f("filename.ext", f.out | f.app);
f << "any";
f << "text";
f << "written";
f << "wll";
f << "be append";
...

You can find more information about the open modes here and about fstreams here.

add class with JavaScript

There is build in forEach loop for array in ECMAScript 5th Edition.

var buttons = document.getElementsByClassName("navButton");

Array.prototype.forEach.call(buttons,function(button) { 
    button.setAttribute("class", "active");
    button.setAttribute("src", "images/arrows/top_o.png"); 
});

SQL Statement with multiple SETs and WHEREs

Nope, this is how you do it:

UPDATE table SET ID = 111111259 WHERE ID = 2555

UPDATE table SET ID = 111111261 WHERE ID = 2724

UPDATE table SET ID = 111111263 WHERE ID = 2021

UPDATE table SET ID = 111111264 WHERE ID = 2017

submit form on click event using jquery

Why not simply use the submit button to run the code you want. If your function returns false, it will cancel the submission.

$("#testForm").submit(function() {
    /* Do Something */
    return false;
});

Listing files in a directory matching a pattern in Java

Since java 7 you can the java.nio package to achieve the same result:

Path dir = ...;
List<File> files = new ArrayList<>();
try (DirectoryStream<Path> stream = Files.newDirectoryStream(dir, "*.{java,class,jar}")) {
    for (Path entry: stream) {
        files.add(entry.toFile());
    }
    return files;
} catch (IOException x) {
    throw new RuntimeException(String.format("error reading folder %s: %s",
    dir,
    x.getMessage()),
    x);
}

TypeError: Router.use() requires middleware function but got a Object

In my case i wasn't exporting the module. module.exports = router;

What's the best way to calculate the size of a directory in .NET?

I've been fiddling with VS2008 and LINQ up until recently and this compact and short method works great for me (example is in VB.NET; requires LINQ / .NET FW 3.5+ of course):

Dim size As Int64 = (From strFile In My.Computer.FileSystem.GetFiles(strFolder, _
              FileIO.SearchOption.SearchAllSubDirectories) _
              Select New System.IO.FileInfo(strFile).Length).Sum()

Its short, it searches sub-directories and is simple to understand if you know LINQ syntax. You could even specify wildcards to search for specific files using the third parameter of the .GetFiles function.

I'm not a C# expert but you can add the My namespace on C# this way.

I think this way of obtaining a folder size is not only shorter and more modern than the way described on Hao's link, it basically uses the same loop-of-FileInfo method described there in the end.

How to download image using requests

There are 2 main ways:

  1. Using .content (simplest/official) (see Zhenyi Zhang's answer):

    import io  # Note: io.BytesIO is StringIO.StringIO on Python2.
    import requests
    
    r = requests.get('http://lorempixel.com/400/200')
    r.raise_for_status()
    with io.BytesIO(r.content) as f:
        with Image.open(f) as img:
            img.show()
    
  2. Using .raw (see Martijn Pieters's answer):

    import requests
    
    r = requests.get('http://lorempixel.com/400/200', stream=True)
    r.raise_for_status()
    r.raw.decode_content = True  # Required to decompress gzip/deflate compressed responses.
    with PIL.Image.open(r.raw) as img:
        img.show()
    r.close()  # Safety when stream=True ensure the connection is released.
    

Timing both shows no noticeable difference.

How should I store GUID in MySQL tables?

I would suggest using the functions below since the ones mentioned by @bigh_29 transforms my guids into new ones (for reasons I don't understand). Also, these are a little bit faster in the tests I did on my tables. https://gist.github.com/damienb/159151

DELIMITER |

CREATE FUNCTION uuid_from_bin(b BINARY(16))
RETURNS CHAR(36) DETERMINISTIC
BEGIN
  DECLARE hex CHAR(32);
  SET hex = HEX(b);
  RETURN LOWER(CONCAT(LEFT(hex, 8), '-', MID(hex, 9,4), '-', MID(hex, 13,4), '-', MID(hex, 17,4), '-', RIGHT(hex, 12)));
END
|

CREATE FUNCTION uuid_to_bin(s CHAR(36))
RETURNS BINARY(16) DETERMINISTIC
RETURN UNHEX(CONCAT(LEFT(s, 8), MID(s, 10, 4), MID(s, 15, 4), MID(s, 20, 4), RIGHT(s, 12)))
|

DELIMITER ;

What's the source of Error: getaddrinfo EAI_AGAIN?

If you get this error with Firebase Cloud Functions, this is due to the limitations of the free tier (outbound networking only allowed to Google services).

Upgrade to the Flame or Blaze plans for it to work.

enter image description here

What is the difference between String and string in C#?

@JaredPar (a developer on the C# compiler and prolific SO user!) wrote a great blog post on this issue. I think it is worth sharing here. It is a nice perspective on our subject.

string vs. String is not a style debate

[...]

The keyword string has concrete meaning in C#. It is the type System.String which exists in the core runtime assembly. The runtime intrinsically understands this type and provides the capabilities developers expect for strings in .NET. Its presence is so critical to C# that if that type doesn’t exist the compiler will exit before attempting to even parse a line of code. Hence string has a precise, unambiguous meaning in C# code.

The identifier String though has no concrete meaning in C#. It is an identifier that goes through all the name lookup rules as Widget, Student, etc … It could bind to string or it could bind to a type in another assembly entirely whose purposes may be entirely different than string. Worse it could be defined in a way such that code like String s = "hello"; continued to compile.

class TricksterString { 
  void Example() {
    String s = "Hello World"; // Okay but probably not what you expect.
  }
}

class String {
  public static implicit operator String(string s) => null;
}

The actual meaning of String will always depend on name resolution. That means it depends on all the source files in the project and all the types defined in all the referenced assemblies. In short it requires quite a bit of context to know what it means.

True that in the vast majority of cases String and string will bind to the same type. But using String still means developers are leaving their program up to interpretation in places where there is only one correct answer. When String does bind to the wrong type it can leave developers debugging for hours, filing bugs on the compiler team, and generally wasting time that could’ve been saved by using string.

Another way to visualize the difference is with this sample:

string s1 = 42; // Errors 100% of the time  
String s2 = 42; // Might error, might not, depends on the code

Many will argue that while this is information technically accurate using String is still fine because it’s exceedingly rare that a codebase would define a type of this name. Or that when String is defined it’s a sign of a bad codebase.

[...]

You’ll see that String is defined for a number of completely valid purposes: reflection helpers, serialization libraries, lexers, protocols, etc … For any of these libraries String vs. string has real consequences depending on where the code is used.

So remember when you see the String vs. string debate this is about semantics, not style. Choosing string gives crisp meaning to your codebase. Choosing String isn’t wrong but it’s leaving the door open for surprises in the future.

Note: I copy/pasted most of the blog posts for archive reasons. I ignore some parts, so I recommend skipping and reading the blog post if you can.

How to check compiler log in sql developer?

control-shift-L should open the log(s) for you. this will by default be the messages log, but if you create the item that is creating the error the Compiler Log will show up (for me the box shows up in the bottom middle left).

if the messages log is the only log that shows up, simply re-execute the item that was causing the failure and the compiler log will show up

for instance, hit Control-shift-L then execute this

CREATE OR REPLACE FUNCTION TEST123() IS
BEGIN
VAR := 2;
end TEST123;

and you will see the message "Error(1,18): PLS-00103: Encountered the symbol ")" when expecting one of the following: current delete exists prior "

(You can also see this in "View--Log")

One more thing, if you are having a problem with a (function || package || procedure) if you do the coding via the SQL Developer interface (by finding the object in question on the connections tab and editing it the error will be immediately displayed (and even underlined at times)

How to Convert unsigned char* to std::string in C++?

If has access to CryptoPP

Readable Hex String to unsigned char

std::string& hexed = "C23412341324AB";
uint8_t      buffer[64] = {0};
StringSource ssk(hexed, true,
            new HexDecoder(new ArraySink(buffer,sizeof(buffer))));

And back

std::string hexed;
uint8_t val[32]  = {0};
StringSource ss(val, sizeof(val), true,new HexEncoder(new StringSink(hexed));
// val == buffer

How to fill Matrix with zeros in OpenCV?

use cv::mat::setto

img.setTo(cv::Scalar(redVal,greenVal,blueVal))

Android List View Drag and Drop sort

Am adding this answer for the purpose of those who google about this..

There was an episode of DevBytes (ListView Cell Dragging and Rearranging) recently which explains how to do this

You can find it here also the sample code is available here.

What this code basically does is that it creates a dynamic listview by the extension of listview that supports cell dragging and swapping. So that you can use the DynamicListView instead of your basic ListView and that's it you have implemented a ListView with Drag and Drop.

How to print instances of a class using print()?

There are already a lot of answers in this thread but none of them particularly helped me, I had to work it out myself, so I hope this one is a little more informative.

You just have to make sure you have parentheses at the end of your class, e.g:

print(class())

Here's an example of code from a project I was working on:

class Element:
    def __init__(self, name, symbol, number):
        self.name = name
        self.symbol = symbol
        self.number = number
    def __str__(self):
        return "{}: {}\nAtomic Number: {}\n".format(self.name, self.symbol, self.number

class Hydrogen(Element):
    def __init__(self):
        super().__init__(name = "Hydrogen", symbol = "H", number = "1")

To print my Hydrogen class, I used the following:

print(Hydrogen())

Please note, this will not work without the parentheses at the end of Hydrogen. They are necessary.

Hope this helps, let me know if you have anymore questions.

Copy data from one existing row to another existing row in SQL?

Copy a value from one row to any other qualified rows within the same table (or different tables):

UPDATE `your_table` t1, `your_table` t2
SET t1.your_field = t2.your_field
WHERE t1.other_field = some_condition
AND t1.another_field = another_condition
AND t2.source_id = 'explicit_value'

Start off by aliasing the table into 2 unique references so the SQL server can tell them apart

Next, specify the field(s) to copy.

Last, specify the conditions governing the selection of the rows

Depending on the conditions you may copy from a single row to a series, or you may copy a series to a series. You may also specify different tables, and you can even use sub-selects or joins to allow using other tables to control the relationships.

Unable to create a constant value of type Only primitive types or enumeration types are supported in this context

This cannot work because ppCombined is a collection of objects in memory and you cannot join a set of data in the database with another set of data that is in memory. You can try instead to extract the filtered items personProtocol of the ppCombined collection in memory after you have retrieved the other properties from the database:

var persons = db.Favorites
    .Where(f => f.userId == userId)
    .Join(db.Person, f => f.personId, p => p.personId, (f, p) =>
        new // anonymous object
        {
            personId = p.personId,
            addressId = p.addressId,   
            favoriteId = f.favoriteId,
        })
    .AsEnumerable() // database query ends here, the rest is a query in memory
    .Select(x =>
        new PersonDTO
        {
            personId = x.personId,
            addressId = x.addressId,   
            favoriteId = x.favoriteId,
            personProtocol = ppCombined
                .Where(p => p.personId == x.personId)
                .Select(p => new PersonProtocol
                {
                    personProtocolId = p.personProtocolId,
                    activateDt = p.activateDt,
                    personId = p.personId
                })
                .ToList()
        });

How to remove all namespaces from XML with C#?

the obligatory answer using LINQ:

static XElement stripNS(XElement root) {
    return new XElement(
        root.Name.LocalName,
        root.HasElements ? 
            root.Elements().Select(el => stripNS(el)) :
            (object)root.Value
    );
}
static void Main() {
    var xml = XElement.Parse(@"<?xml version=""1.0"" encoding=""utf-16""?>
    <ArrayOfInserts xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema"">
      <insert>
        <offer xmlns=""http://schema.peters.com/doc_353/1/Types"">0174587</offer>
        <type2 xmlns=""http://schema.peters.com/doc_353/1/Types"">014717</type2>
        <supplier xmlns=""http://schema.peters.com/doc_353/1/Types"">019172</supplier>
        <id_frame xmlns=""http://schema.peters.com/doc_353/1/Types"" />
        <type3 xmlns=""http://schema.peters.com/doc_353/1/Types"">
          <type2 />
          <main>false</main>
        </type3>
        <status xmlns=""http://schema.peters.com/doc_353/1/Types"">Some state</status>
      </insert>
    </ArrayOfInserts>");
    Console.WriteLine(stripNS(xml));
}

Why compile Python code?

Something not touched upon is source-to-source-compiling. For example, nuitka translates Python code to C/C++, and compiles it to binary code which directly runs on the CPU, instead of Python bytecode which runs on the slower virtual machine.

This can lead to significant speedups, or it would let you work with Python while your environment depends on C/C++ code.

How to replace plain URLs with links?

Replacing URLs with links (Answer to the General Problem)

The regular expression in the question misses a lot of edge cases. When detecting URLs, it's always better to use a specialized library that handles international domain names, new TLDs like .museum, parentheses and other punctuation within and at the end of the URL, and many other edge cases. See the Jeff Atwood's blog post The Problem With URLs for an explanation of some of the other issues.

The best summary of URL matching libraries is in Dan Dascalescu's Answer +100
(as of Feb 2014)


"Make a regular expression replace more than one match" (Answer to the specific problem)

Add a "g" to the end of the regular expression to enable global matching:

/ig;

But that only fixes the problem in the question where the regular expression was only replacing the first match. Do not use that code.

How to check if ZooKeeper is running or up from command prompt?

I did some test:

When it's running:

$ /usr/lib/zookeeper/bin/zkServer.sh status
JMX enabled by default
Using config: /usr/lib/zookeeper/bin/../conf/zoo.cfg
Mode: follower

When it's stopped:

$ zkServer status                                                                                                                                
JMX enabled by default
Using config: /usr/local/etc/zookeeper/zoo.cfg
Error contacting service. It is probably not running.

I'm not running on the same machine, but you get the idea.

How to get main div container to align to centre?

Do not use the * selector as that will apply to all elements on the page. Suppose you have a structure like this:

...
<body>
    <div id="content">
        <b>This is the main container.</b>
    </div>
</body>
</html>

You can then center the #content div using:

#content {
    width: 400px;
    margin: 0 auto;
    background-color: #66ffff;
}

Don't know what you've seen elsewhere but this is the way to go. The * { margin: 0; padding: 0; } snippet you've seen is for resetting browser's default definitions for all browsers to make your site behave similarly on all browsers, this has nothing to do with centering the main container.

Most browsers apply a default margin and padding to some elements which usually isn't consistent with other browsers' implementations. This is why it is often considered smart to use this kind of 'resetting'. The reset snippet you presented is the most simplest of reset stylesheets, you can read more about the subject here:

C# Error: Parent does not contain a constructor that takes 0 arguments

Since you don't explicitly invoke a parent constructor as part of your child class constructor, there is an implicit call to a parameterless parent constructor inserted. That constructor does not exist, and so you get that error.

To correct the situation, you need to add an explicit call:

public Child(int i) : base(i)
{
    Console.WriteLine("child");
}

Or, you can just add a parameterless parent constructor:

protected Parent() { } 

Pass value to iframe from a window

First, you need to understand that you have two documents: The frame and the container (which contains the frame).

The main obstacle with manipulating the frame from the container is that the frame loads asynchronously. You can't simply access it any time, you must know when it has finished loading. So you need a trick. The usual solution is to use window.parent in the frame to get "up" (into the document which contains the iframe tag).

Now you can call any method in the container document. This method can manipulate the frame (for example call some JavaScript in the frame with the parameters you need). To know when to call the method, you have two options:

  1. Call it from body.onload of the frame.

  2. Put a script element as the last thing into the HTML content of the frame where you call the method of the container (left as an exercise for the reader).

So the frame looks like this:

<script>
function init() { window.parent.setUpFrame(); return true; }
function yourMethod(arg) { ... }
</script>
<body onload="init();">...</body>

And the container like this:

<script>
function setUpFrame() { 
    var frame = window.frames['frame-id'];
    frame.yourMethod('hello');
}
</script>
<body><iframe name="frame-id" src="..."></iframe></body>

javax.net.ssl.SSLException: Read error: ssl=0x9524b800: I/O error during system call, Connection reset by peer

I was experiencing this error on Android 5.1.1 devices sending network requests using okhttp/4.0.0-RC1. Setting header Content-Length: <sizeof response> on the server side resolved the issue.

How to Solve Max Connection Pool Error

Check against any long running queries in your database.

Increasing your pool size will only make your webapp live a little longer (and probably get a lot slower)

You can use sql server profiler and filter on duration / reads to see which querys need optimization.

I also see you're probably keeping a global connection?

blnMainConnectionIsCreatedLocal

Let .net do the pooling for you and open / close your connection with a using statement.

Suggestions:

  1. Always open and close a connection like this, so .net can manage your connections and you won't run out of connections:

        using (SqlConnection conn = new SqlConnection(connectionString))
        {
         conn.Open();
         // do some stuff
        } //conn disposed
    
  2. As I mentioned, check your query with sql server profiler and see if you can optimize it. Having a slow query with many requests in a web app can give these timeouts too.

What is the correct way to write HTML using Javascript?

  1. DOM methods, as outlined by Tom.

  2. innerHTML, as mentioned by iHunger.

DOM methods are highly preferable to strings for setting attributes and content. If you ever find yourself writing innerHTML= '<a href="'+path+'">'+text+'</a>' you're actually creating new cross-site-scripting security holes on the client side, which is a bit sad if you've spent any time securing your server-side.

DOM methods are traditionally described as ‘slow’ compared to innerHTML. But this isn't really the whole story. What is slow is inserting a lot of child nodes:

 for (var i= 0; i<1000; i++)
     div.parentNode.insertBefore(document.createElement('div'), div);

This translates to a load of work for the DOM finding the right place in its nodelist to insert the element, moving the other child nodes up, inserting the new node, updating the pointers, and so on.

Setting an existing attribute's value, or a text node's data, on the other hand, is very fast; you just change a string pointer and that's it. This is going to be much faster than serialising the parent with innerHTML, changing it, and parsing it back in (and won't lose your unserialisable data like event handlers, JS references and form values).

There are techniques to do DOM manipulations without so much slow childNodes walking. In particular, be aware of the possibilities of cloneNode, and using DocumentFragment. But sometimes innerHTML really is quicker. You can still get the best of both worlds by using innerHTML to write your basic structure with placeholders for attribute values and text content, which you then fill in afterwards using DOM. This saves you having to write your own escapehtml() function to get around the escaping/security problems mentioned above.

Scrolling to element using webdriver?

Example:

driver.execute_script("arguments[0].scrollIntoView();", driver.find_element_by_css_selector(.your_css_selector))

This one always works for me for any type of selectors. There is also the Actions class, but for this case, it is not so reliable.

How to remove "disabled" attribute using jQuery?

Use like this,

HTML:

<input type="text" disabled="disabled" class="inputDisabled" value="">

<div id="edit">edit</div>

JS:

 $('#edit').click(function(){ // click to
            $('.inputDisabled').attr('disabled',false); // removing disabled in this class
 });

When should I use a struct rather than a class in C#?

I do not agree with the rules given in the original post. Here are my rules:

1) You use structs for performance when stored in arrays. (see also When are structs the answer?)

2) You need them in code passing structured data to/from C/C++

3) Do not use structs unless you need them:

  • They behave different from "normal objects" (reference types) under assignment and when passing as arguments, which can lead to unexpected behavior; this is particularly dangerous if the person looking at the code does not know they are dealing with a struct.
  • They cannot be inherited.
  • Passing structs as arguments is more expensive than classes.

Parse large JSON file in Nodejs

Just as I was thinking that it would be fun to write a streaming JSON parser, I also thought that maybe I should do a quick search to see if there's one already available.

Turns out there is.

Since I just found it, I've obviously not used it, so I can't comment on its quality, but I'll be interested to hear if it works.

It does work consider the following Javascript and _.isString:

stream.pipe(JSONStream.parse('*'))
  .on('data', (d) => {
    console.log(typeof d);
    console.log("isString: " + _.isString(d))
  });

This will log objects as they come in if the stream is an array of objects. Therefore the only thing being buffered is one object at a time.

How to Initialize char array from a string

This compiles fine on gcc version 4.3.3 (Ubuntu 4.3.3-5ubuntu4).

const char s[] = "cheese";

int main()
{
    return 0;
}

Fatal error: Allowed memory size of 134217728 bytes exhausted (tried to allocate 32 bytes)

128M == 134217728, the number you are seeing.

The memory limit is working fine. When it says it tried to allocate 32 bytes, that the amount requested by the last operation before failing.

Are you building any huge arrays or reading large text files? If so, remember to free any memory you don't need anymore, or break the task down into smaller steps.

Printing an int list in a single line python3

# Print In One Line Python

print('Enter Value')

n = int(input())

print(*range(1, n+1), sep="")

How to write a Python module/package?

Python 3 - UPDATED 18th November 2015

Found the accepted answer useful, yet wished to expand on several points for the benefit of others based on my own experiences.

Module: A module is a file containing Python definitions and statements. The file name is the module name with the suffix .py appended.

Module Example: Assume we have a single python script in the current directory, here I am calling it mymodule.py

The file mymodule.py contains the following code:

def myfunc():
    print("Hello!")

If we run the python3 interpreter from the current directory, we can import and run the function myfunc in the following different ways (you would typically just choose one of the following):

>>> import mymodule
>>> mymodule.myfunc()
Hello!
>>> from mymodule import myfunc
>>> myfunc()
Hello!
>>> from mymodule import *
>>> myfunc()
Hello!

Ok, so that was easy enough.

Now assume you have the need to put this module into its own dedicated folder to provide a module namespace, instead of just running it ad-hoc from the current working directory. This is where it is worth explaining the concept of a package.

Package: Packages are a way of structuring Python’s module namespace by using “dotted module names”. For example, the module name A.B designates a submodule named B in a package named A. Just like the use of modules saves the authors of different modules from having to worry about each other’s global variable names, the use of dotted module names saves the authors of multi-module packages like NumPy or the Python Imaging Library from having to worry about each other’s module names.

Package Example: Let's now assume we have the following folder and files. Here, mymodule.py is identical to before, and __init__.py is an empty file:

.
+-- mypackage
    +-- __init__.py
    +-- mymodule.py

The __init__.py files are required to make Python treat the directories as containing packages. For further information, please see the Modules documentation link provided later on.

Our current working directory is one level above the ordinary folder called mypackage

$ ls
mypackage

If we run the python3 interpreter now, we can import and run the module mymodule.py containing the required function myfunc in the following different ways (you would typically just choose one of the following):

>>> import mypackage
>>> from mypackage import mymodule
>>> mymodule.myfunc()
Hello!
>>> import mypackage.mymodule
>>> mypackage.mymodule.myfunc()
Hello!
>>> from mypackage import mymodule
>>> mymodule.myfunc()
Hello!
>>> from mypackage.mymodule import myfunc
>>> myfunc()
Hello!
>>> from mypackage.mymodule import *
>>> myfunc()
Hello!

Assuming Python 3, there is excellent documentation at: Modules

In terms of naming conventions for packages and modules, the general guidelines are given in PEP-0008 - please see Package and Module Names

Modules should have short, all-lowercase names. Underscores can be used in the module name if it improves readability. Python packages should also have short, all-lowercase names, although the use of underscores is discouraged.

git error: failed to push some refs to remote

I was pushing existing typo 'evelop' branch which I did not have checkout yet, and instead, I wanted to push a branch called 'envelope'. So the branch must be existing/checkout out at local working copy in order to push of course, therefore that error, not to make a typo.

How to get RegistrationID using GCM in android

Here I have written a few steps for How to Get RegID and Notification starting from scratch

  1. Create/Register App on Google Cloud
  2. Setup Cloud SDK with Development
  3. Configure project for GCM
  4. Get Device Registration ID
  5. Send Push Notifications
  6. Receive Push Notifications

You can find a complete tutorial here:

Getting Started with Android Push Notification : Latest Google Cloud Messaging (GCM) - step by step complete tutorial

enter image description here

Code snippet to get Registration ID (Device Token for Push Notification).

Configure project for GCM


Update AndroidManifest file

To enable GCM in our project we need to add a few permissions to our manifest file. Go to AndroidManifest.xml and add this code: Add Permissions

<uses-permission android:name="android.permission.INTERNET”/>
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<uses-permission android:name="android.permission.WAKE_LOCK" />

<uses-permission android:name="android.permission.VIBRATE" />

<uses-permission android:name=“.permission.RECEIVE" />
<uses-permission android:name=“<your_package_name_here>.permission.C2D_MESSAGE" />
<permission android:name=“<your_package_name_here>.permission.C2D_MESSAGE"
        android:protectionLevel="signature" />

Add GCM Broadcast Receiver declaration in your application tag:

<application
        <receiver
            android:name=".GcmBroadcastReceiver"
            android:permission="com.google.android.c2dm.permission.SEND" ]]>
            <intent-filter]]>
                <action android:name="com.google.android.c2dm.intent.RECEIVE" />
                <category android:name="" />
            </intent-filter]]>

        </receiver]]>
     
<application/>

Add GCM Service declaration

<application
     <service android:name=".GcmIntentService" />
<application/>

Get Registration ID (Device Token for Push Notification)

Now Go to your Launch/Splash Activity

Add Constants and Class Variables

private final static int PLAY_SERVICES_RESOLUTION_REQUEST = 9000;
public static final String EXTRA_MESSAGE = "message";
public static final String PROPERTY_REG_ID = "registration_id";
private static final String PROPERTY_APP_VERSION = "appVersion";
private final static String TAG = "LaunchActivity";
protected String SENDER_ID = "Your_sender_id";
private GoogleCloudMessaging gcm =null;
private String regid = null;
private Context context= null;

Update OnCreate and OnResume methods

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_launch);
    context = getApplicationContext();
    if (checkPlayServices()) {
        gcm = GoogleCloudMessaging.getInstance(this);
        regid = getRegistrationId(context);

        if (regid.isEmpty()) {
            registerInBackground();
        } else {
            Log.d(TAG, "No valid Google Play Services APK found.");
        }
    }
}

@Override
protected void onResume() {
    super.onResume();
    checkPlayServices();
}


// # Implement GCM Required methods(Add below methods in LaunchActivity)

private boolean checkPlayServices() {
    int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
    if (resultCode != ConnectionResult.SUCCESS) {
        if (GooglePlayServicesUtil.isUserRecoverableError(resultCode)) {
            GooglePlayServicesUtil.getErrorDialog(resultCode, this,
                PLAY_SERVICES_RESOLUTION_REQUEST).show();
        } else {
            Log.d(TAG, "This device is not supported - Google Play Services.");
            finish();
        }
        return false;
    }
    return true;
}

private String getRegistrationId(Context context) {
    final SharedPreferences prefs = getGCMPreferences(context);
    String registrationId = prefs.getString(PROPERTY_REG_ID, "");
    if (registrationId.isEmpty()) {
        Log.d(TAG, "Registration ID not found.");
        return "";
    }
    int registeredVersion = prefs.getInt(PROPERTY_APP_VERSION, Integer.MIN_VALUE);
    int currentVersion = getAppVersion(context);
    if (registeredVersion != currentVersion) {
        Log.d(TAG, "App version changed.");
        return "";
    }
    return registrationId;
}

private SharedPreferences getGCMPreferences(Context context) {
    return getSharedPreferences(LaunchActivity.class.getSimpleName(),
        Context.MODE_PRIVATE);
}

private static int getAppVersion(Context context) {
    try {
        PackageInfo packageInfo = context.getPackageManager()
            .getPackageInfo(context.getPackageName(), 0);
        return packageInfo.versionCode;
    } catch (NameNotFoundException e) {
        throw new RuntimeException("Could not get package name: " + e);
    }
}


private void registerInBackground() {
    new AsyncTask() {
        @Override
        protected Object doInBackground(Object...params) {
            String msg = "";
            try {
                if (gcm == null) {
                    gcm = GoogleCloudMessaging.getInstance(context);
                }
                regid = gcm.register(SENDER_ID);
                Log.d(TAG, "########################################");
                Log.d(TAG, "Current Device's Registration ID is: " + msg);
            } catch (IOException ex) {
                msg = "Error :" + ex.getMessage();
            }
            return null;
        }
        protected void onPostExecute(Object result) {
            //to do here
        };
    }.execute(null, null, null);
}

Note : please store REGISTRATION_KEY, it is important for sending PN Message to GCM. Also keep in mind: this key will be unique for all devices and GCM will send Push Notifications by REGISTRATION_KEY only.

How to display the string html contents into webbrowser control?

Instead of navigating to blank, you can do

webBrowser1.DocumentText="0";
webBrowser1.Document.OpenNew(true);
webBrowser1.Document.Write(theHTML);
webBrowser1.Refresh();

No need to wait for events or anything else. You can check the MSDN for OpenNew, while I have tested the initial DocumentText assignment in one of my projects and it works.

How do you create a dropdownlist from an enum in ASP.NET MVC?

This is Rune & Prise answers altered to use the Enum int value as the ID.

Sample Enum:

public enum ItemTypes
{
    Movie = 1,
    Game = 2,
    Book = 3
}

Extension method:

    public static SelectList ToSelectList<TEnum>(this TEnum enumObj)
    {
        var values = from TEnum e in Enum.GetValues(typeof(TEnum))
                     select new { Id = (int)Enum.Parse(typeof(TEnum), e.ToString()), Name = e.ToString() };

        return new SelectList(values, "Id", "Name", (int)Enum.Parse(typeof(TEnum), enumObj.ToString()));
    }

Sample of usage:

 <%=  Html.DropDownList("MyEnumList", ItemTypes.Game.ToSelectList()) %>

Remember to Import the namespace containing the Extension method

<%@ Import Namespace="MyNamespace.LocationOfExtensionMethod" %>

Sample of generated HTML:

<select id="MyEnumList" name="MyEnumList">
    <option value="1">Movie</option>
    <option selected="selected" value="2">Game</option>
    <option value="3">Book </option>
</select>

Note that the item that you use to call the ToSelectList on is the selected item.