Programs & Examples On #Iteration

Iterations are the successive repetitions in loops such as for, foreach or while. Questions with this tag are often concerned about how to best handle a collection of data.

Java HashMap: How to get a key and value by index?

You can do:

for(String key: hashMap.keySet()){
    for(String value: hashMap.get(key)) {
        // use the value here
    }
}

This will iterate over every key, and then every value of the list associated with each key.

How to iterate over a JavaScript object?

For object iteration we usually use a for..in loop. This structure will loop through all enumerable properties, including ones who are inherited via prototypal inheritance. For example:

_x000D_
_x000D_
let obj = {_x000D_
  prop1: '1',_x000D_
  prop2: '2'_x000D_
}_x000D_
_x000D_
for(let el in obj) {_x000D_
  console.log(el);_x000D_
  console.log(obj[el]);_x000D_
}
_x000D_
_x000D_
_x000D_

However, for..in will loop over all enumerable elements and this will not able us to split the iteration in chunks. To achieve this we can use the built in Object.keys() function to retrieve all the keys of an object in an array. We then can split up the iteration into multiple for loops and access the properties using the keys array. For example:

_x000D_
_x000D_
let obj = {_x000D_
  prop1: '1',_x000D_
  prop2: '2',_x000D_
  prop3: '3',_x000D_
  prop4: '4',_x000D_
};_x000D_
_x000D_
const keys = Object.keys(obj);_x000D_
console.log(keys);_x000D_
_x000D_
_x000D_
for (let i = 0; i < 2; i++) {_x000D_
  console.log(obj[keys[i]]);_x000D_
}_x000D_
_x000D_
_x000D_
for (let i = 2; i < 4; i++) {_x000D_
  console.log(obj[keys[i]]);_x000D_
}
_x000D_
_x000D_
_x000D_

How to iterate through range of Dates in Java?

This will help you start 30 days back and loop through until today's date. you can easily change range of dates and direction.

private void iterateThroughDates() throws Exception {
    Calendar start = Calendar.getInstance();
    start.add(Calendar.DATE, -30);
    Calendar end = Calendar.getInstance();
    for (Calendar date = start; date.before(end); date.add(Calendar.DATE, 1))
        {
        System.out.println(date.getTime());
        }
}

How does "FOR" work in cmd batch file?

It works for me, try it.

for /f "tokens=* delims=;" %g in ('echo %PATH%') do echo %g%

Is there a better way to iterate over two lists, getting one element from each list for each iteration?

Iterating through elements of two lists simultaneously is known as zipping, and python provides a built in function for it, which is documented here.

>>> x = [1, 2, 3]
>>> y = [4, 5, 6]
>>> zipped = zip(x, y)
>>> zipped
[(1, 4), (2, 5), (3, 6)]
>>> x2, y2 = zip(*zipped)
>>> x == list(x2) and y == list(y2)
True

[Example is taken from pydocs]

In your case, it will be simply:

for (lat, lon) in zip(latitudes, longitudes):
    ... process lat and lon

Iterate over object attributes in python

As mentioned in some of the answers/comments already, Python objects already store a dictionary of their attributes (methods aren't included). This can be accessed as __dict__, but the better way is to use vars (the output is the same, though). Note that modifying this dictionary will modify the attributes on the instance! This can be useful, but also means you should be careful with how you use this dictionary. Here's a quick example:

class A():
    def __init__(self, x=3, y=2, z=5):
        self.x = x
        self._y = y
        self.__z__ = z

    def f(self):
        pass

a = A()
print(vars(a))
# {'x': 3, '_y': 2, '__z__': 5}
# all of the attributes of `a` but no methods!

# note how the dictionary is always up-to-date
a.x = 10
print(vars(a))
# {'x': 10, '_y': 2, '__z__': 5}

# modifying the dictionary modifies the instance attribute
vars(a)["_y"] = 20
print(vars(a))
# {'x': 10, '_y': 20, '__z__': 5}

Using dir(a) is an odd, if not outright bad, approach to this problem. It's good if you really needed to iterate over all attributes and methods of the class (including the special methods like __init__). However, this doesn't seem to be what you want, and even the accepted answer goes about this poorly by applying some brittle filtering to try to remove methods and leave just the attributes; you can see how this would fail for the class A defined above.

(using __dict__ has been done in a couple of answers, but they all define unnecessary methods instead of using it directly. Only a comment suggests to use vars).

How to loop backwards in python?

To reverse a string without using reversed or [::-1], try something like:

def reverse(text):
    # Container for reversed string
    txet=""

    # store the length of the string to be reversed
    # account for indexes starting at 0
    length = len(text)-1

    # loop through the string in reverse and append each character
    # deprecate the length index
    while length>=0:
        txet += "%s"%text[length]
        length-=1
    return txet

How to produce a range with step n in bash? (generate a sequence of numbers with increments)

$ seq 4
1
2
3
4

$ seq 2 5
2
3
4
5

$ seq 4 2 12
4
6
8
10
12

$ seq -w 4 2 12
04
06
08
10
12

$ seq -s, 4 2 12
4,6,8,10,12

How to loop through array in jQuery?


(Update: My other answer here lays out the non-jQuery options much more thoroughly. The third option below, jQuery.each, isn't in it though.)


Four options:

Generic loop:

var i;
for (i = 0; i < substr.length; ++i) {
    // do something with `substr[i]`
}

or in ES2015+:

for (let i = 0; i < substr.length; ++i) {
    // do something with `substr[i]`
}

Advantages: Straight-forward, no dependency on jQuery, easy to understand, no issues with preserving the meaning of this within the body of the loop, no unnecessary overhead of function calls (e.g., in theory faster, though in fact you'd have to have so many elements that the odds are you'd have other problems; details).

ES5's forEach:

As of ECMAScript5, arrays have a forEach function on them which makes it easy to loop through the array:

substr.forEach(function(item) {
    // do something with `item`
});

Link to docs

(Note: There are lots of other functions, not just forEach; see the answer referenced above for details.)

Advantages: Declarative, can use a prebuilt function for the iterator if you have one handy, if your loop body is complex the scoping of a function call is sometimes useful, no need for an i variable in your containing scope.

Disadvantages: If you're using this in the containing code and you want to use this within your forEach callback, you have to either A) Stick it in a variable so you can use it within the function, B) Pass it as a second argument to forEach so forEach sets it as this during the callback, or C) Use an ES2015+ arrow function, which closes over this. If you don't do one of those things, in the callback this will be undefined (in strict mode) or the global object (window) in loose mode. There used to be a second disadvantage that forEach wasn't universally supported, but here in 2018, the only browser you're going to run into that doesn't have forEach is IE8 (and it can't be properly polyfilled there, either).

ES2015+'s for-of:

for (const s of substr) { // Or `let` if you want to modify it in the loop body
    // do something with `s`
}

See the answer linked at the top of this answer for details on how that works.

Advantages: Simple, straightforward, offers a contained-scope variable (or constant, in the above) for the entry from the array.

Disadvantages: Not supported in any version of IE.

jQuery.each:

jQuery.each(substr, function(index, item) {
    // do something with `item` (or `this` is also `item` if you like)
});

(Link to docs)

Advantages: All of the same advantages as forEach, plus you know it's there since you're using jQuery.

Disadvantages: If you're using this in the containing code, you have to stick it in a variable so you can use it within the function, since this means something else within the function.

You can avoid the this thing though, by either using $.proxy:

jQuery.each(substr, $.proxy(function(index, item) {
    // do something with `item` (`this` is the same as it was outside)
}, this));

...or Function#bind:

jQuery.each(substr, function(index, item) {
    // do something with `item` (`this` is the same as it was outside)
}.bind(this));

...or in ES2015 ("ES6"), an arrow function:

jQuery.each(substr, (index, item) => {
    // do something with `item` (`this` is the same as it was outside)
});

What NOT to do:

Don't use for..in for this (or if you do, do it with proper safeguards). You'll see people saying to (in fact, briefly there was an answer here saying that), but for..in does not do what many people think it does (it does something even more useful!). Specifically, for..in loops through the enumerable property names of an object (not the indexes of an array). Since arrays are objects, and their only enumerable properties by default are the indexes, it mostly seems to sort of work in a bland deployment. But it's not a safe assumption that you can just use it for that. Here's an exploration: http://jsbin.com/exohi/3

I should soften the "don't" above. If you're dealing with sparse arrays (e.g., the array has 15 elements in total but their indexes are strewn across the range 0 to 150,000 for some reason, and so the length is 150,001), and if you use appropriate safeguards like hasOwnProperty and checking the property name is really numeric (see link above), for..in can be a perfectly reasonable way to avoid lots of unnecessary loops, since only the populated indexes will be enumerated.

Python loop that also accesses previous and next values

Here's a version using generators with no boundary errors:

def trios(iterable):
    it = iter(iterable)
    try:
        prev, current = next(it), next(it)
    except StopIteration:
        return
    for next in it:
        yield prev, current, next
        prev, current = current, next

def find_prev_next(objects, foo):
    prev, next = 0, 0
    for temp_prev, current, temp_next in trios(objects):
        if current == foo:
            prev, next = temp_prev, temp_next
    return prev, next

print(find_prev_next(range(10), 1))
print(find_prev_next(range(10), 0))
print(find_prev_next(range(10), 10))
print(find_prev_next(range(0), 10))
print(find_prev_next(range(1), 10))
print(find_prev_next(range(2), 10))

Please notice that the boundary behavior is that we never look for "foo" in the first or last element, unlike your code. Again, the boundary semantics are strange...and are hard to fathom from your code :)

Python list iterator behavior and next(iterator)

I find the existing answers a little confusing, because they only indirectly indicate the essential mystifying thing in the code example: both* the "print i" and the "next(a)" are causing their results to be printed.

Since they're printing alternating elements of the original sequence, and it's unexpected that the "next(a)" statement is printing, it appears as if the "print i" statement is printing all the values.

In that light, it becomes more clear that assigning the result of "next(a)" to a variable inhibits the printing of its' result, so that just the alternate values that the "i" loop variable are printed. Similarly, making the "print" statement emit something more distinctive disambiguates it, as well.

(One of the existing answers refutes the others because that answer is having the example code evaluated as a block, so that the interpreter is not reporting the intermediate values for "next(a)".)

The beguiling thing in answering questions, in general, is being explicit about what is obvious once you know the answer. It can be elusive. Likewise critiquing answers once you understand them. It's interesting...

How does PHP 'foreach' actually work?

Some points to note when working with foreach():

a) foreach works on the prospected copy of the original array. It means foreach() will have SHARED data storage until or unless a prospected copy is not created foreach Notes/User comments.

b) What triggers a prospected copy? A prospected copy is created based on the policy of copy-on-write, that is, whenever an array passed to foreach() is changed, a clone of the original array is created.

c) The original array and foreach() iterator will have DISTINCT SENTINEL VARIABLES, that is, one for the original array and other for foreach; see the test code below. SPL , Iterators, and Array Iterator.

Stack Overflow question How to make sure the value is reset in a 'foreach' loop in PHP? addresses the cases (3,4,5) of your question.

The following example shows that each() and reset() DOES NOT affect SENTINEL variables (for example, the current index variable) of the foreach() iterator.

$array = array(1, 2, 3, 4, 5);

list($key2, $val2) = each($array);
echo "each() Original (outside): $key2 => $val2<br/>";

foreach($array as $key => $val){
    echo "foreach: $key => $val<br/>";

    list($key2,$val2) = each($array);
    echo "each() Original(inside): $key2 => $val2<br/>";

    echo "--------Iteration--------<br/>";
    if ($key == 3){
        echo "Resetting original array pointer<br/>";
        reset($array);
    }
}

list($key2, $val2) = each($array);
echo "each() Original (outside): $key2 => $val2<br/>";

Output:

each() Original (outside): 0 => 1
foreach: 0 => 1
each() Original(inside): 1 => 2
--------Iteration--------
foreach: 1 => 2
each() Original(inside): 2 => 3
--------Iteration--------
foreach: 2 => 3
each() Original(inside): 3 => 4
--------Iteration--------
foreach: 3 => 4
each() Original(inside): 4 => 5
--------Iteration--------
Resetting original array pointer
foreach: 4 => 5
each() Original(inside): 0=>1
--------Iteration--------
each() Original (outside): 1 => 2

Remove elements from collection while iterating

Let me give a few examples with some alternatives to avoid a ConcurrentModificationException.

Suppose we have the following collection of books

List<Book> books = new ArrayList<Book>();
books.add(new Book(new ISBN("0-201-63361-2")));
books.add(new Book(new ISBN("0-201-63361-3")));
books.add(new Book(new ISBN("0-201-63361-4")));

Collect and Remove

The first technique consists in collecting all the objects that we want to delete (e.g. using an enhanced for loop) and after we finish iterating, we remove all found objects.

ISBN isbn = new ISBN("0-201-63361-2");
List<Book> found = new ArrayList<Book>();
for(Book book : books){
    if(book.getIsbn().equals(isbn)){
        found.add(book);
    }
}
books.removeAll(found);

This is supposing that the operation you want to do is "delete".

If you want to "add" this approach would also work, but I would assume you would iterate over a different collection to determine what elements you want to add to a second collection and then issue an addAll method at the end.

Using ListIterator

If you are working with lists, another technique consists in using a ListIterator which has support for removal and addition of items during the iteration itself.

ListIterator<Book> iter = books.listIterator();
while(iter.hasNext()){
    if(iter.next().getIsbn().equals(isbn)){
        iter.remove();
    }
}

Again, I used the "remove" method in the example above which is what your question seemed to imply, but you may also use its add method to add new elements during iteration.

Using JDK >= 8

For those working with Java 8 or superior versions, there are a couple of other techniques you could use to take advantage of it.

You could use the new removeIf method in the Collection base class:

ISBN other = new ISBN("0-201-63361-2");
books.removeIf(b -> b.getIsbn().equals(other));

Or use the new stream API:

ISBN other = new ISBN("0-201-63361-2");
List<Book> filtered = books.stream()
                           .filter(b -> b.getIsbn().equals(other))
                           .collect(Collectors.toList());

In this last case, to filter elements out of a collection, you reassign the original reference to the filtered collection (i.e. books = filtered) or used the filtered collection to removeAll the found elements from the original collection (i.e. books.removeAll(filtered)).

Use Sublist or Subset

There are other alternatives as well. If the list is sorted, and you want to remove consecutive elements you can create a sublist and then clear it:

books.subList(0,5).clear();

Since the sublist is backed by the original list this would be an efficient way of removing this subcollection of elements.

Something similar could be achieved with sorted sets using NavigableSet.subSet method, or any of the slicing methods offered there.

Considerations:

What method you use might depend on what you are intending to do

  • The collect and removeAl technique works with any Collection (Collection, List, Set, etc).
  • The ListIterator technique obviously only works with lists, provided that their given ListIterator implementation offers support for add and remove operations.
  • The Iterator approach would work with any type of collection, but it only supports remove operations.
  • With the ListIterator/Iterator approach the obvious advantage is not having to copy anything since we remove as we iterate. So, this is very efficient.
  • The JDK 8 streams example don't actually removed anything, but looked for the desired elements, and then we replaced the original collection reference with the new one, and let the old one be garbage collected. So, we iterate only once over the collection and that would be efficient.
  • In the collect and removeAll approach the disadvantage is that we have to iterate twice. First we iterate in the foor-loop looking for an object that matches our removal criteria, and once we have found it, we ask to remove it from the original collection, which would imply a second iteration work to look for this item in order to remove it.
  • I think it is worth mentioning that the remove method of the Iterator interface is marked as "optional" in Javadocs, which means that there could be Iterator implementations that throw UnsupportedOperationException if we invoke the remove method. As such, I'd say this approach is less safe than others if we cannot guarantee the iterator support for removal of elements.

Ways to iterate over a list in Java

I don't know what you consider pathological, but let me provide some alternatives you could have not seen before:

List<E> sl= list ;
while( ! sl.empty() ) {
    E element= sl.get(0) ;
    .....
    sl= sl.subList(1,sl.size());
}

Or its recursive version:

void visit(List<E> list) {
    if( list.isEmpty() ) return;
    E element= list.get(0) ;
    ....
    visit(list.subList(1,list.size()));
}

Also, a recursive version of the classical for(int i=0... :

void visit(List<E> list,int pos) {
    if( pos >= list.size() ) return;
    E element= list.get(pos) ;
    ....
    visit(list,pos+1);
}

I mention them because you are "somewhat new to Java" and this could be interesting.

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

The place where each can cause you problems is that it's a true, non-scoped iterator. By way of example:

while ( my ($key,$val) = each %a_hash ) {
    print "$key => $val\n";
    last if $val; #exits loop when $val is true
}

# but "each" hasn't reset!!
while ( my ($key,$val) = each %a_hash ) {
    # continues where the last loop left off
    print "$key => $val\n";
}

If you need to be sure that each gets all the keys and values, you need to make sure you use keys or values first (as that resets the iterator). See the documentation for each.

Getting next element while cycling through a list

You can use a pairwise cyclic iterator:

from itertools import izip, cycle, tee

def pairwise(seq):
    a, b = tee(seq)
    next(b)
    return izip(a, b)

for elem, next_elem in pairwise(cycle(li)):
    ...

Time complexity of Euclid's Algorithm

At every step, there are two cases

b >= a / 2, then a, b = b, a % b will make b at most half of its previous value

b < a / 2, then a, b = b, a % b will make a at most half of its previous value, since b is less than a / 2

So at every step, the algorithm will reduce at least one number to at least half less.

In at most O(log a)+O(log b) step, this will be reduced to the simple cases. Which yield an O(log n) algorithm, where n is the upper limit of a and b.

I have found it here

How to iterate through an ArrayList of Objects of ArrayList of Objects?

We can do a nested loop to visit all the elements of elements in your list:

 for (Gun g: gunList) {
   System.out.print(g.toString() + "\n   "); 
   for(Bullet b : g.getBullet() {
      System.out.print(g);    
   }
   System.out.println(); 
 }

python: iterate a specific range in a list

A more memory efficient way to iterate over a slice of a list would be to use islice() from the itertools module:

from itertools import islice

listOfStuff = (['a','b'], ['c','d'], ['e','f'], ['g','h'])

for item in islice(listOfStuff, 1, 3):
    print item

# ['c', 'd']
# ['e', 'f']

However, this can be relatively inefficient in terms of performance if the start value of the range is a large value sinceislicewould have to iterate over the first start value-1 items before returning items.

How to loop through an array containing objects and access their properties

This would work. Looping thorough array(yourArray) . Then loop through direct properties of each object (eachObj) .

yourArray.forEach( function (eachObj){
    for (var key in eachObj) {
        if (eachObj.hasOwnProperty(key)){
           console.log(key,eachObj[key]);
        }
    }
});

How can I loop through a C++ map of maps?

Do something like this:

typedef std::map<std::string, std::string> InnerMap;
typedef std::map<std::string, InnerMap> OuterMap;

Outermap mm;

...//set the initial values

for (OuterMap::iterator i = mm.begin(); i != mm.end(); ++i) {
    InnerMap &im = i->second;
    for (InnerMap::iterator ii = im.begin(); ii != im.end(); ++ii) {
        std::cout << "map[" 
                  << i->first 
                  << "][" 
                  << ii->first 
                  << "] =" 
                  << ii->second 
                  << '\n';
    }
}   

Python: Adding element to list while iterating

You can do this.

bonus_rows = []
for a in myarr:
  if somecond(a):
      bonus_rows.append(newObj())
myarr.extend( bonus_rows )

How to iterate through a list of dictionaries in Jinja template?

**get id from dic value. I got the result.try the below code**
get_abstracts = s.get_abstracts(session_id)
    sessions = get_abstracts['sessions']
    abs = {}
    for a in get_abstracts['abstracts']:
        a_session_id = a['session_id']
        abs.setdefault(a_session_id,[]).append(a)
    authors = {}
    # print('authors')
    # print(get_abstracts['authors'])
    for au in get_abstracts['authors']: 
        # print(au)
        au_abs_id = au['abs_id']
        authors.setdefault(au_abs_id,[]).append(au)
 **In jinja template**
{% for s in sessions %}
          <h4><u>Session : {{ s.session_title}} - Hall : {{ s.session_hall}}</u></h4> 
            {% for a in abs[s.session_id] %}
            <hr>
                      <p><b>Chief Author :</b>  Dr. {{ a.full_name }}</p>  
               
                {% for au in authors[a.abs_id] %}
                      <p><b> {{ au.role }} :</b> Dr.{{ au.full_name }}</p>
                {% endfor %}
            {% endfor %}
        {% endfor %}

Iterating through a variable length array

for(int i = 0; i < array.length; i++)
{
    System.out.println(array[i]);
}

or

for(String value : array)
{
    System.out.println(value);
}

The second version is a "for-each" loop and it works with arrays and Collections. Most loops can be done with the for-each loop because you probably don't care about the actual index. If you do care about the actual index us the first version.

Just for completeness you can do the while loop this way:

int index = 0;

while(index < myArray.length)
{
  final String value;

  value = myArray[index];
  System.out.println(value);
  index++;
}

But you should use a for loop instead of a while loop when you know the size (and even with a variable length array you know the size... it is just different each time).

In Ruby, how do I skip a loop in a .each loop, similar to 'continue'

next - it's like return, but for blocks! (So you can use this in any proc/lambda too.)

That means you can also say next n to "return" n from the block. For instance:

puts [1, 2, 3].map do |e|
  next 42 if e == 2
  e
end.inject(&:+)

This will yield 46.

Note that return always returns from the closest def, and never a block; if there's no surrounding def, returning is an error.

Using return from within a block intentionally can be confusing. For instance:

def my_fun
  [1, 2, 3].map do |e|
    return "Hello." if e == 2
    e
  end
end

my_fun will result in "Hello.", not [1, "Hello.", 2], because the return keyword pertains to the outer def, not the inner block.

Java: Most efficient method to iterate over all elements in a org.w3c.dom.Document?

I also stumbled over this problem recently. Here is my solution. I wanted to avoid recursion, so I used a while loop.

Because of the adds and removes in arbitrary places on the list, I went with the LinkedList implementation.

/* traverses tree starting with given node */
  private static List<Node> traverse(Node n)
  {
    return traverse(Arrays.asList(n));
  }

  /* traverses tree starting with given nodes */
  private static List<Node> traverse(List<Node> nodes)
  {
    List<Node> open = new LinkedList<Node>(nodes);
    List<Node> visited = new LinkedList<Node>();

    ListIterator<Node> it = open.listIterator();
    while (it.hasNext() || it.hasPrevious())
    {
      Node unvisited;
      if (it.hasNext())
        unvisited = it.next();
      else
        unvisited = it.previous();

      it.remove();

      List<Node> children = getChildren(unvisited);
      for (Node child : children)
        it.add(child);

      visited.add(unvisited);
    }

    return visited;
  }

  private static List<Node> getChildren(Node n)
  {
    List<Node> children = asList(n.getChildNodes());
    Iterator<Node> it = children.iterator();
    while (it.hasNext())
      if (it.next().getNodeType() != Node.ELEMENT_NODE)
        it.remove();
    return children;
  }

  private static List<Node> asList(NodeList nodes)
  {
    List<Node> list = new ArrayList<Node>(nodes.getLength());
    for (int i = 0, l = nodes.getLength(); i < l; i++)
      list.add(nodes.item(i));
    return list;
  }

How to iterate std::set?

Just use the * before it:

set<unsigned long>::iterator it;
for (it = myset.begin(); it != myset.end(); ++it) {
    cout << *it;
}

This dereferences it and allows you to access the element the iterator is currently on.

Remove Elements from a HashSet while Iterating

The reason you get a ConcurrentModificationException is because an entry is removed via Set.remove() as opposed to Iterator.remove(). If an entry is removed via Set.remove() while an iteration is being done, you will get a ConcurrentModificationException. On the other hand, removal of entries via Iterator.remove() while iteration is supported in this case.

The new for loop is nice, but unfortunately it does not work in this case, because you can't use the Iterator reference.

If you need to remove an entry while iteration, you need to use the long form that uses the Iterator directly.

for (Iterator<Integer> it = set.iterator(); it.hasNext();) {
    Integer element = it.next();
    if (element % 2 == 0) {
        it.remove();
    }
}

Efficient iteration with index in Scala

It has been mentioned that Scala does have syntax for for loops:

for (i <- 0 until xs.length) ...

or simply

for (i <- xs.indices) ...

However, you also asked for efficiency. It turns out that the Scala for syntax is actually syntactic sugar for higher order methods such as map, foreach, etc. As such, in some cases these loops can be inefficient, e.g. How to optimize for-comprehensions and loops in Scala?

(The good news is that the Scala team is working on improving this. Here's the issue in the bug tracker: https://issues.scala-lang.org/browse/SI-4633)

For utmost efficiency, one can use a while loop or, if you insist on removing uses of var, tail recursion:

import scala.annotation.tailrec

@tailrec def printArray(i: Int, xs: Array[String]) {
  if (i < xs.length) {
    println("String #" + i + " is " + xs(i))
    printArray(i+1, xs)
  }
}
printArray(0, Array("first", "second", "third"))

Note that the optional @tailrec annotation is useful for ensuring that the method is actually tail recursive. The Scala compiler translates tail-recursive calls into the byte code equivalent of while loops.

How to loop over grouped Pandas dataframe?

df.groupby('l_customer_id_i').agg(lambda x: ','.join(x)) does already return a dataframe, so you cannot loop over the groups anymore.

In general:

  • df.groupby(...) returns a GroupBy object (a DataFrameGroupBy or SeriesGroupBy), and with this, you can iterate through the groups (as explained in the docs here). You can do something like:

    grouped = df.groupby('A')
    
    for name, group in grouped:
        ...
    
  • When you apply a function on the groupby, in your example df.groupby(...).agg(...) (but this can also be transform, apply, mean, ...), you combine the result of applying the function to the different groups together in one dataframe (the apply and combine step of the 'split-apply-combine' paradigm of groupby). So the result of this will always be again a DataFrame (or a Series depending on the applied function).

"Continue" (to next iteration) on VBScript

We can use a separate function for performing a continue statement work. suppose you have following problem:

for i=1 to 10

if(condition) then   'for loop body'
contionue
End If

Next

Here we will use a function call for for loop body:

for i=1 to 10
Call loopbody()
next

function loopbody()

if(condition) then   'for loop body'
Exit Function
End If

End Function

loop will continue for function exit statement....

How to iterate over a string in C?

The last index of a C-String is always the integer value 0, hence the phrase "null terminated string". Since integer 0 is the same as the Boolean value false in C, you can use that to make a simple while clause for your for loop. When it hits the last index, it will find a zero and equate that to false, ending the for loop.

for(int i = 0; string[i]; i++) { printf("Char at position %d is %c\n", i, string[i]); }

std::queue iteration

Why not just make a copy of the queue that you want to iterate over, and remove items one at a time, printing them as you go? If you want to do more with the elements as you iterate, then a queue is the wrong data structure.

How do I loop through a list by twos?

You can use for in range with a step size of 2:

Python 2

for i in xrange(0,10,2):
  print(i)

Python 3

for i in range(0,10,2):
  print(i)

Note: Use xrange in Python 2 instead of range because it is more efficient as it generates an iterable object, and not the whole list.

What is the easiest/best/most correct way to iterate through the characters of a string in Java?

In Java 8 we can solve it as:

String str = "xyz";
str.chars().forEachOrdered(i -> System.out.print((char)i));
str.codePoints().forEachOrdered(i -> System.out.print((char)i));

The method chars() returns an IntStream as mentioned in doc:

Returns a stream of int zero-extending the char values from this sequence. Any char which maps to a surrogate code point is passed through uninterpreted. If the sequence is mutated while the stream is being read, the result is undefined.

The method codePoints() also returns an IntStream as per doc:

Returns a stream of code point values from this sequence. Any surrogate pairs encountered in the sequence are combined as if by Character.toCodePoint and the result is passed to the stream. Any other code units, including ordinary BMP characters, unpaired surrogates, and undefined code units, are zero-extended to int values which are then passed to the stream.

How is char and code point different? As mentioned in this article:

Unicode 3.1 added supplementary characters, bringing the total number of characters to more than the 2^16 = 65536 characters that can be distinguished by a single 16-bit char. Therefore, a char value no longer has a one-to-one mapping to the fundamental semantic unit in Unicode. JDK 5 was updated to support the larger set of character values. Instead of changing the definition of the char type, some of the new supplementary characters are represented by a surrogate pair of two char values. To reduce naming confusion, a code point will be used to refer to the number that represents a particular Unicode character, including supplementary ones.

Finally why forEachOrdered and not forEach ?

The behaviour of forEach is explicitly nondeterministic where as the forEachOrdered performs an action for each element of this stream, in the encounter order of the stream if the stream has a defined encounter order. So forEach does not guarantee that the order would be kept. Also check this question for more.

For difference between a character, a code point, a glyph and a grapheme check this question.

Is recursion ever faster than looping?

This depends on the language being used. You wrote 'language-agnostic', so I'll give some examples.

In Java, C, and Python, recursion is fairly expensive compared to iteration (in general) because it requires the allocation of a new stack frame. In some C compilers, one can use a compiler flag to eliminate this overhead, which transforms certain types of recursion (actually, certain types of tail calls) into jumps instead of function calls.

In functional programming language implementations, sometimes, iteration can be very expensive and recursion can be very cheap. In many, recursion is transformed into a simple jump, but changing the loop variable (which is mutable) sometimes requires some relatively heavy operations, especially on implementations which support multiple threads of execution. Mutation is expensive in some of these environments because of the interaction between the mutator and the garbage collector, if both might be running at the same time.

I know that in some Scheme implementations, recursion will generally be faster than looping.

In short, the answer depends on the code and the implementation. Use whatever style you prefer. If you're using a functional language, recursion might be faster. If you're using an imperative language, iteration is probably faster. In some environments, both methods will result in the same assembly being generated (put that in your pipe and smoke it).

Addendum: In some environments, the best alternative is neither recursion nor iteration but instead higher order functions. These include "map", "filter", and "reduce" (which is also called "fold"). Not only are these the preferred style, not only are they often cleaner, but in some environments these functions are the first (or only) to get a boost from automatic parallelization — so they can be significantly faster than either iteration or recursion. Data Parallel Haskell is an example of such an environment.

List comprehensions are another alternative, but these are usually just syntactic sugar for iteration, recursion, or higher order functions.

Iterating through a Collection, avoiding ConcurrentModificationException when removing objects in a loop

In such cases a common trick is (was?) to go backwards:

for(int i = l.size() - 1; i >= 0; i --) {
  if (l.get(i) == 5) {
    l.remove(i);
  }
}

That said, I'm more than happy that you have better ways in Java 8, e.g. removeIf or filter on streams.

Loop through a date range with JavaScript

Here's a way to do it by making use of the way adding one day causes the date to roll over to the next month if necessary, and without messing around with milliseconds. Daylight savings aren't an issue either.

var now = new Date();
var daysOfYear = [];
for (var d = new Date(2012, 0, 1); d <= now; d.setDate(d.getDate() + 1)) {
    daysOfYear.push(new Date(d));
}

Note that if you want to store the date, you'll need to make a new one (as above with new Date(d)), or else you'll end up with every stored date being the final value of d in the loop.

How do I iterate over an NSArray?

Add each method in your NSArray category, you gonna need it a lot

Code taken from ObjectiveSugar

- (void)each:(void (^)(id object))block {
    [self enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
        block(obj);
    }];
}

How do I access properties of a javascript object if I don't know the names?

var obj = {
 a: [1, 3, 4],
 b: 2,
 c: ['hi', 'there']
 }
for(let r in obj){  //for in loop iterates all properties in an object
 console.log(r) ;  //print all properties in sequence
 console.log(obj[r]);//print all properties values
}

How do I iterate through children elements of a div using jQuery?

If you need to loop through child elements recursively:

function recursiveEach($element){
    $element.children().each(function () {
        var $currentElement = $(this);
        // Show element
        console.info($currentElement);
        // Show events handlers of current element
        console.info($currentElement.data('events'));
        // Loop her children
        recursiveEach($currentElement);
    });
}

// Parent div
recursiveEach($("#div"));   

NOTE: In this example I show the events handlers registered with an object.

What is the perfect counterpart in Python for "while not EOF"

The Python idiom for opening a file and reading it line-by-line is:

with open('filename') as f:
    for line in f:
        do_something(line)

The file will be automatically closed at the end of the above code (the with construct takes care of that).

Finally, it is worth noting that line will preserve the trailing newline. This can be easily removed using:

line = line.rstrip()

How to loop through key/value object in Javascript?

Something like this:

setUsers = function (data) {
    for (k in data) {
        user[k] = data[k];
    }
}

How to skip to next iteration in jQuery.each() util?

Javascript sort of has the idea of 'truthiness' and 'falsiness'. If a variable has a value then, generally 9as you will see) it has 'truthiness' - null, or no value tends to 'falsiness'. The snippets below might help:

var temp1; 
if ( temp1 )...  // false

var temp2 = true;
if ( temp2 )...  // true

var temp3 = "";
if ( temp3 ).... // false

var temp4 = "hello world";
if ( temp4 )...  // true

Hopefully that helps?

Also, its worth checking out these videos from Douglas Crockford

update: thanks @cphpython for spotting the broken links - I've updated to point at working versions now

The Javascript language

Javascript - The Good Parts

How to iterate over a column vector in Matlab?

with many functions in matlab, you don't need to iterate at all.

for example, to multiply by it's position in the list:

m = [1:numel(list)]';
elm = list.*m;

vectorized algorithms in matlab are in general much faster.

recursion versus iteration

Question :

And if recursion is usually slower what is the technical reason for ever using it over for loop iteration?

Answer :

Because in some algorithms are hard to solve it iteratively. Try to solve depth-first search in both recursively and iteratively. You will get the idea that it is plain hard to solve DFS with iteration.

Another good thing to try out : Try to write Merge sort iteratively. It will take you quite some time.

Question :

Is it correct to say that everywhere recursion is used a for loop could be used?

Answer :

Yes. This thread has a very good answer for this.

Question :

And if it is always possible to convert an recursion into a for loop is there a rule of thumb way to do it?

Answer :

Trust me. Try to write your own version to solve depth-first search iteratively. You will notice that some problems are easier to solve it recursively.

Hint : Recursion is good when you are solving a problem that can be solved by divide and conquer technique.

Java - get index of key in HashMap?

Use LinkedHashMap instead of HashMap It will always return keys in same order (as insertion) when calling keySet()

For more detail, see Class LinkedHashMap

How to remove items from a list while iterating?

TLDR:

I wrote a library that allows you to do this:

from fluidIter import FluidIterable
fSomeList = FluidIterable(someList)  
for tup in fSomeList:
    if determine(tup):
        # remove 'tup' without "breaking" the iteration
        fSomeList.remove(tup)
        # tup has also been removed from 'someList'
        # as well as 'fSomeList'

It's best to use another method if possible that doesn't require modifying your iterable while iterating over it, but for some algorithms it might not be that straight forward. And so if you are sure that you really do want the code pattern described in the original question, it is possible.

Should work on all mutable sequences not just lists.


Full answer:

Edit: The last code example in this answer gives a use case for why you might sometimes want to modify a list in place rather than use a list comprehension. The first part of the answers serves as tutorial of how an array can be modified in place.

The solution follows on from this answer (for a related question) from senderle. Which explains how the the array index is updated while iterating through a list that has been modified. The solution below is designed to correctly track the array index even if the list is modified.

Download fluidIter.py from here https://github.com/alanbacon/FluidIterator, it is just a single file so no need to install git. There is no installer so you will need to make sure that the file is in the python path your self. The code has been written for python 3 and is untested on python 2.

from fluidIter import FluidIterable
l = [0,1,2,3,4,5,6,7,8]  
fluidL = FluidIterable(l)                       
for i in fluidL:
    print('initial state of list on this iteration: ' + str(fluidL)) 
    print('current iteration value: ' + str(i))
    print('popped value: ' + str(fluidL.pop(2)))
    print(' ')

print('Final List Value: ' + str(l))

This will produce the following output:

initial state of list on this iteration: [0, 1, 2, 3, 4, 5, 6, 7, 8]
current iteration value: 0
popped value: 2

initial state of list on this iteration: [0, 1, 3, 4, 5, 6, 7, 8]
current iteration value: 1
popped value: 3

initial state of list on this iteration: [0, 1, 4, 5, 6, 7, 8]
current iteration value: 4
popped value: 4

initial state of list on this iteration: [0, 1, 5, 6, 7, 8]
current iteration value: 5
popped value: 5

initial state of list on this iteration: [0, 1, 6, 7, 8]
current iteration value: 6
popped value: 6

initial state of list on this iteration: [0, 1, 7, 8]
current iteration value: 7
popped value: 7

initial state of list on this iteration: [0, 1, 8]
current iteration value: 8
popped value: 8

Final List Value: [0, 1]

Above we have used the pop method on the fluid list object. Other common iterable methods are also implemented such as del fluidL[i], .remove, .insert, .append, .extend. The list can also be modified using slices (sort and reverse methods are not implemented).

The only condition is that you must only modify the list in place, if at any point fluidL or l were reassigned to a different list object the code would not work. The original fluidL object would still be used by the for loop but would become out of scope for us to modify.

i.e.

fluidL[2] = 'a'   # is OK
fluidL = [0, 1, 'a', 3, 4, 5, 6, 7, 8]  # is not OK

If we want to access the current index value of the list we cannot use enumerate, as this only counts how many times the for loop has run. Instead we will use the iterator object directly.

fluidArr = FluidIterable([0,1,2,3])
# get iterator first so can query the current index
fluidArrIter = fluidArr.__iter__()
for i, v in enumerate(fluidArrIter):
    print('enum: ', i)
    print('current val: ', v)
    print('current ind: ', fluidArrIter.currentIndex)
    print(fluidArr)
    fluidArr.insert(0,'a')
    print(' ')

print('Final List Value: ' + str(fluidArr))

This will output the following:

enum:  0
current val:  0
current ind:  0
[0, 1, 2, 3]

enum:  1
current val:  1
current ind:  2
['a', 0, 1, 2, 3]

enum:  2
current val:  2
current ind:  4
['a', 'a', 0, 1, 2, 3]

enum:  3
current val:  3
current ind:  6
['a', 'a', 'a', 0, 1, 2, 3]

Final List Value: ['a', 'a', 'a', 'a', 0, 1, 2, 3]

The FluidIterable class just provides a wrapper for the original list object. The original object can be accessed as a property of the fluid object like so:

originalList = fluidArr.fixedIterable

More examples / tests can be found in the if __name__ is "__main__": section at the bottom of fluidIter.py. These are worth looking at because they explain what happens in various situations. Such as: Replacing a large sections of the list using a slice. Or using (and modifying) the same iterable in nested for loops.

As I stated to start with: this is a complicated solution that will hurt the readability of your code and make it more difficult to debug. Therefore other solutions such as the list comprehensions mentioned in David Raznick's answer should be considered first. That being said, I have found times where this class has been useful to me and has been easier to use than keeping track of the indices of elements that need deleting.


Edit: As mentioned in the comments, this answer does not really present a problem for which this approach provides a solution. I will try to address that here:

List comprehensions provide a way to generate a new list but these approaches tend to look at each element in isolation rather than the current state of the list as a whole.

i.e.

newList = [i for i in oldList if testFunc(i)]

But what if the result of the testFunc depends on the elements that have been added to newList already? Or the elements still in oldList that might be added next? There might still be a way to use a list comprehension but it will begin to lose it's elegance, and for me it feels easier to modify a list in place.

The code below is one example of an algorithm that suffers from the above problem. The algorithm will reduce a list so that no element is a multiple of any other element.

randInts = [70, 20, 61, 80, 54, 18, 7, 18, 55, 9]
fRandInts = FluidIterable(randInts)
fRandIntsIter = fRandInts.__iter__()
# for each value in the list (outer loop)
# test against every other value in the list (inner loop)
for i in fRandIntsIter:
    print(' ')
    print('outer val: ', i)
    innerIntsIter = fRandInts.__iter__()
    for j in innerIntsIter:
        innerIndex = innerIntsIter.currentIndex
        # skip the element that the outloop is currently on
        # because we don't want to test a value against itself
        if not innerIndex == fRandIntsIter.currentIndex:
            # if the test element, j, is a multiple 
            # of the reference element, i, then remove 'j'
            if j%i == 0:
                print('remove val: ', j)
                # remove element in place, without breaking the
                # iteration of either loop
                del fRandInts[innerIndex]
            # end if multiple, then remove
        # end if not the same value as outer loop
    # end inner loop
# end outerloop

print('')
print('final list: ', randInts)

The output and the final reduced list are shown below

outer val:  70

outer val:  20
remove val:  80

outer val:  61

outer val:  54

outer val:  18
remove val:  54
remove val:  18

outer val:  7
remove val:  70

outer val:  55

outer val:  9
remove val:  18

final list:  [20, 61, 7, 55, 9]

Iterating through a range of dates in Python

import datetime
from dateutil.rrule import DAILY,rrule

date=datetime.datetime(2019,1,10)

date1=datetime.datetime(2019,2,2)

for i in rrule(DAILY , dtstart=date,until=date1):
     print(i.strftime('%Y%b%d'),sep='\n')

OUTPUT:

2019Jan10
2019Jan11
2019Jan12
2019Jan13
2019Jan14
2019Jan15
2019Jan16
2019Jan17
2019Jan18
2019Jan19
2019Jan20
2019Jan21
2019Jan22
2019Jan23
2019Jan24
2019Jan25
2019Jan26
2019Jan27
2019Jan28
2019Jan29
2019Jan30
2019Jan31
2019Feb01
2019Feb02

Iterate through Nested JavaScript Objects

You can get through every object in the list and get which value you want. Just pass an object as first parameter in the function call and object property which you want as second parameter. Change object with your object.

_x000D_
_x000D_
const treeData = [{_x000D_
        "jssType": "fieldset",_x000D_
        "jssSelectLabel": "Fieldset (with legend)",_x000D_
        "jssSelectGroup": "jssItem",_x000D_
        "jsName": "fieldset-715",_x000D_
        "jssLabel": "Legend",_x000D_
        "jssIcon": "typcn typcn-folder",_x000D_
        "expanded": true,_x000D_
        "children": [{_x000D_
                "jssType": "list-ol",_x000D_
                "jssSelectLabel": "List - ol",_x000D_
                "jssSelectGroup": "jssItem",_x000D_
                "jsName": "list-ol-147",_x000D_
                "jssLabel": "",_x000D_
                "jssIcon": "dashicons dashicons-editor-ol",_x000D_
                "noChildren": false,_x000D_
                "expanded": true,_x000D_
                "children": [{_x000D_
                        "jssType": "list-li",_x000D_
                        "jssSelectLabel": "List Item - li",_x000D_
                        "jssSelectGroup": "jssItem",_x000D_
                        "jsName": "list-li-752",_x000D_
                        "jssLabel": "",_x000D_
                        "jssIcon": "dashicons dashicons-editor-ul",_x000D_
                        "noChildren": false,_x000D_
                        "expanded": true,_x000D_
                        "children": [{_x000D_
                            "jssType": "text",_x000D_
                            "jssSelectLabel": "Text (short text)",_x000D_
                            "jssSelectGroup": "jsTag",_x000D_
                            "jsName": "text-422",_x000D_
                            "jssLabel": "Your Name (required)",_x000D_
                            "jsRequired": true,_x000D_
                            "jsTagOptions": [{_x000D_
                                    "jsOption": "",_x000D_
                                    "optionLabel": "Default value",_x000D_
                                    "optionType": "input"_x000D_
                                },_x000D_
                                {_x000D_
                                    "jsOption": "placeholder",_x000D_
                                    "isChecked": false,_x000D_
                                    "optionLabel": "Use this text as the placeholder of the field",_x000D_
                                    "optionType": "checkbox"_x000D_
                                },_x000D_
                                {_x000D_
                                    "jsOption": "akismet_author_email",_x000D_
                                    "isChecked": false,_x000D_
                                    "optionLabel": "Akismet - this field requires author's email address",_x000D_
                                    "optionType": "checkbox"_x000D_
                                }_x000D_
                            ],_x000D_
                            "jsValues": "",_x000D_
                            "jsPlaceholder": false,_x000D_
                            "jsAkismetAuthor": false,_x000D_
                            "jsIdAttribute": "",_x000D_
                            "jsClassAttribute": "",_x000D_
                            "jssIcon": "typcn typcn-sort-alphabetically",_x000D_
                            "noChildren": true_x000D_
                        }]_x000D_
                    },_x000D_
                    {_x000D_
                        "jssType": "list-li",_x000D_
                        "jssSelectLabel": "List Item - li",_x000D_
                        "jssSelectGroup": "jssItem",_x000D_
                        "jsName": "list-li-538",_x000D_
                        "jssLabel": "",_x000D_
                        "jssIcon": "dashicons dashicons-editor-ul",_x000D_
                        "noChildren": false,_x000D_
                        "expanded": true,_x000D_
                        "children": [{_x000D_
                            "jssType": "email",_x000D_
                            "jssSelectLabel": "Email",_x000D_
                            "jssSelectGroup": "jsTag",_x000D_
                            "jsName": "email-842",_x000D_
                            "jssLabel": "Email Address (required)",_x000D_
                            "jsRequired": true,_x000D_
                            "jsTagOptions": [{_x000D_
                                    "jsOption": "",_x000D_
                                    "optionLabel": "Default value",_x000D_
                                    "optionType": "input"_x000D_
                                },_x000D_
                                {_x000D_
                                    "jsOption": "placeholder",_x000D_
                                    "isChecked": false,_x000D_
                                    "optionLabel": "Use this text as the placeholder of the field",_x000D_
                                    "optionType": "checkbox"_x000D_
                                },_x000D_
                                {_x000D_
                                    "jsOption": "akismet_author_email",_x000D_
                                    "isChecked": false,_x000D_
                                    "optionLabel": "Akismet - this field requires author's email address",_x000D_
                                    "optionType": "checkbox"_x000D_
                                }_x000D_
                            ],_x000D_
                            "jsValues": "",_x000D_
                            "jsPlaceholder": false,_x000D_
                            "jsAkismetAuthorEmail": false,_x000D_
                            "jsIdAttribute": "",_x000D_
                            "jsClassAttribute": "",_x000D_
                            "jssIcon": "typcn typcn-mail",_x000D_
                            "noChildren": true_x000D_
                        }]_x000D_
                    },_x000D_
                    {_x000D_
                        "jssType": "list-li",_x000D_
                        "jssSelectLabel": "List Item - li",_x000D_
                        "jssSelectGroup": "jssItem",_x000D_
                        "jsName": "list-li-855",_x000D_
                        "jssLabel": "",_x000D_
                        "jssIcon": "dashicons dashicons-editor-ul",_x000D_
                        "noChildren": false,_x000D_
                        "expanded": true,_x000D_
                        "children": [{_x000D_
                            "jssType": "textarea",_x000D_
                            "jssSelectLabel": "Textarea (long text)",_x000D_
                            "jssSelectGroup": "jsTag",_x000D_
                            "jsName": "textarea-217",_x000D_
                            "jssLabel": "Your Message",_x000D_
                            "jsRequired": false,_x000D_
                            "jsTagOptions": [{_x000D_
                                    "jsOption": "",_x000D_
                                    "optionLabel": "Default value",_x000D_
                                    "optionType": "input"_x000D_
                                },_x000D_
                                {_x000D_
                                    "jsOption": "placeholder",_x000D_
                                    "isChecked": false,_x000D_
                                    "optionLabel": "Use this text as the placeholder of the field",_x000D_
                                    "optionType": "checkbox"_x000D_
                                }_x000D_
                            ],_x000D_
                            "jsValues": "",_x000D_
                            "jsPlaceholder": false,_x000D_
                            "jsIdAttribute": "",_x000D_
                            "jsClassAttribute": "",_x000D_
                            "jssIcon": "typcn typcn-document-text",_x000D_
                            "noChildren": true_x000D_
                        }]_x000D_
                    }_x000D_
                ]_x000D_
            },_x000D_
            {_x000D_
                "jssType": "paragraph",_x000D_
                "jssSelectLabel": "Paragraph - p",_x000D_
                "jssSelectGroup": "jssItem",_x000D_
                "jsName": "paragraph-993",_x000D_
                "jssContent": "* Required",_x000D_
                "jssIcon": "dashicons dashicons-editor-paragraph",_x000D_
                "noChildren": true_x000D_
            }_x000D_
        ]_x000D_
        _x000D_
    },_x000D_
    {_x000D_
        "jssType": "submit",_x000D_
        "jssSelectLabel": "Submit",_x000D_
        "jssSelectGroup": "jsTag",_x000D_
        "jsName": "submit-704",_x000D_
        "jssLabel": "Send",_x000D_
        "jsValues": "",_x000D_
        "jsRequired": false,_x000D_
        "jsIdAttribute": "",_x000D_
        "jsClassAttribute": "",_x000D_
        "jssIcon": "typcn typcn-mail",_x000D_
        "noChildren": true_x000D_
    },_x000D_
    _x000D_
];_x000D_
_x000D_
_x000D_
_x000D_
_x000D_
 function findObjectByLabel(obj, label) {_x000D_
       for(var elements in obj){_x000D_
           if (elements === label){_x000D_
                console.log(obj[elements]);_x000D_
           }_x000D_
            if(typeof obj[elements] === 'object'){_x000D_
            findObjectByLabel(obj[elements], 'jssType');_x000D_
           }_x000D_
          _x000D_
       }_x000D_
};_x000D_
_x000D_
 findObjectByLabel(treeData, 'jssType');
_x000D_
_x000D_
_x000D_

Is there a way to iterate over a dictionary?

Yes, NSDictionary supports fast enumeration. With Objective-C 2.0, you can do this:

// To print out all key-value pairs in the NSDictionary myDict
for(id key in myDict)
    NSLog(@"key=%@ value=%@", key, [myDict objectForKey:key]);

The alternate method (which you have to use if you're targeting Mac OS X pre-10.5, but you can still use on 10.5 and iPhone) is to use an NSEnumerator:

NSEnumerator *enumerator = [myDict keyEnumerator];
id key;
// extra parens to suppress warning about using = instead of ==
while((key = [enumerator nextObject]))
    NSLog(@"key=%@ value=%@", key, [myDict objectForKey:key]);

Fastest way to iterate over all the chars in a String

This is just micro-optimisation that you shouldn't worry about.

char[] chars = str.toCharArray();

returns you a copy of str character arrays (in JDK, it returns a copy of characters by calling System.arrayCopy).

Other than that, str.charAt() only checks if the index is indeed in bounds and returns a character within the array index.

The first one doesn't create additional memory in JVM.

Is generator.next() visible in Python 3?

Try:

next(g)

Check out this neat table that shows the differences in syntax between 2 and 3 when it comes to this.

Iterate through a HashMap

Extracted from the reference How to Iterate Over a Map in Java:

There are several ways of iterating over a Map in Java. Let's go over the most common methods and review their advantages and disadvantages. Since all maps in Java implement the Map interface, the following techniques will work for any map implementation (HashMap, TreeMap, LinkedHashMap, Hashtable, etc.)

Method #1: Iterating over entries using a For-Each loop.

This is the most common method and is preferable in most cases. It should be used if you need both map keys and values in the loop.

Map<Integer, Integer> map = new HashMap<Integer, Integer>();
for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
    System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());
}

Note that the For-Each loop was introduced in Java 5, so this method is working only in newer versions of the language. Also a For-Each loop will throw NullPointerException if you try to iterate over a map that is null, so before iterating you should always check for null references.

Method #2: Iterating over keys or values using a For-Each loop.

If you need only keys or values from the map, you can iterate over keySet or values instead of entrySet.

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

// Iterating over keys only
for (Integer key : map.keySet()) {
    System.out.println("Key = " + key);
}

// Iterating over values only
for (Integer value : map.values()) {
    System.out.println("Value = " + value);
}

This method gives a slight performance advantage over entrySet iteration (about 10% faster) and is more clean.

Method #3: Iterating using Iterator.

Using Generics:

Map<Integer, Integer> map = new HashMap<Integer, Integer>();
Iterator<Map.Entry<Integer, Integer>> entries = map.entrySet().iterator();
while (entries.hasNext()) {
    Map.Entry<Integer, Integer> entry = entries.next();
    System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());
}

Without Generics:

Map map = new HashMap();
Iterator entries = map.entrySet().iterator();
while (entries.hasNext()) {
    Map.Entry entry = (Map.Entry) entries.next();
    Integer key = (Integer)entry.getKey();
    Integer value = (Integer)entry.getValue();
    System.out.println("Key = " + key + ", Value = " + value);
}

You can also use same technique to iterate over keySet or values.

This method might look redundant, but it has its own advantages. First of all, it is the only way to iterate over a map in older versions of Java. The other important feature is that it is the only method that allows you to remove entries from the map during iteration by calling iterator.remove(). If you try to do this during For-Each iteration you will get "unpredictable results" according to Javadoc.

From a performance point of view this method is equal to a For-Each iteration.

Method #4: Iterating over keys and searching for values (inefficient).

Map<Integer, Integer> map = new HashMap<Integer, Integer>();
for (Integer key : map.keySet()) {
    Integer value = map.get(key);
    System.out.println("Key = " + key + ", Value = " + value);
}

This might look like a cleaner alternative for method #1, but in practice it is pretty slow and inefficient as getting values by a key might be time-consuming (this method in different Map implementations is 20%-200% slower than method #1). If you have FindBugs installed, it will detect this and warn you about inefficient iteration. This method should be avoided.

Conclusion:

If you need only keys or values from the map, use method #2. If you are stuck with older version of Java (less than 5) or planning to remove entries during iteration, you have to use method #3. Otherwise use method #1.

Python using enumerate inside list comprehension

Try this:

[(i, j) for i, j in enumerate(mylist)]

You need to put i,j inside a tuple for the list comprehension to work. Alternatively, given that enumerate() already returns a tuple, you can return it directly without unpacking it first:

[pair for pair in enumerate(mylist)]

Either way, the result that gets returned is as expected:

> [(0, 'a'), (1, 'b'), (2, 'c'), (3, 'd')]

Difference between agile and iterative and incremental development

  • Iterative - you don't finish a feature in one go. You are in a code >> get feedback >> code >> ... cycle. You keep iterating till done.
  • Incremental - you build as much as you need right now. You don't over-engineer or add flexibility unless the need is proven. When the need arises, you build on top of whatever already exists. (Note: differs from iterative in that you're adding new things.. vs refining something).
  • Agile - you are agile if you value the same things as listed in the agile manifesto. It also means that there is no standard template or checklist or procedure to "do agile". It doesn't overspecify.. it just states that you can use whatever practices you need to "be agile". Scrum, XP, Kanban are some of the more prescriptive 'agile' methodologies because they share the same set of values. Continuous and early feedback, frequent releases/demos, evolve design, etc.. hence they can be iterative and incremental.

Way to go from recursion to iteration

Usually, I replace a recursive algorithm by an iterative algorithm by pushing the parameters that would normally be passed to the recursive function onto a stack. In fact, you are replacing the program stack by one of your own.

var stack = [];
stack.push(firstObject);

// while not empty
while (stack.length) {

    // Pop off end of stack.
    obj = stack.pop();

    // Do stuff.
    // Push other objects on the stack as needed.
    ...

}

Note: if you have more than one recursive call inside and you want to preserve the order of the calls, you have to add them in the reverse order to the stack:

foo(first);
foo(second);

has to be replaced by

stack.push(second);
stack.push(first);

Edit: The article Stacks and Recursion Elimination (or Article Backup link) goes into more details on this subject.

"for" vs "each" in Ruby

See "The Evils of the For Loop" for a good explanation (there's one small difference considering variable scoping).

Using each is considered more idiomatic use of Ruby.

C# Iterating through an enum? (Indexing a System.Array)

How about a dictionary list?

Dictionary<string, int> list = new Dictionary<string, int>();
foreach( var item in Enum.GetNames(typeof(MyEnum)) )
{
    list.Add(item, (int)Enum.Parse(typeof(MyEnum), item));
}

and of course you can change the dictionary value type to whatever your enum values are.

Start index for iterating Python list

Why are people using list slicing (slow because it copies to a new list), importing a library function, or trying to rotate an array for this?

Use a normal for-loop with range(start, stop, step) (where start and step are optional arguments).

For example, looping through an array starting at index 1:

for i in range(1, len(arr)):
    print(arr[i])

Iterating on a file doesn't work the second time

As the file object reads the file, it uses a pointer to keep track of where it is. If you read part of the file, then go back to it later it will pick up where you left off. If you read the whole file, and go back to the same file object, it will be like reading an empty file because the pointer is at the end of the file and there is nothing left to read. You can use file.tell() to see where in the file the pointer is and file.seek to set the pointer. For example:

>>> file = open('myfile.txt')
>>> file.tell()
0
>>> file.readline()
'one\n'
>>> file.tell()
4L
>>> file.readline()
'2\n'
>>> file.tell()
6L
>>> file.seek(4)
>>> file.readline()
'2\n'

Also, you should know that file.readlines() reads the whole file and stores it as a list. That's useful to know because you can replace:

for line in file.readlines():
    #do stuff
file.seek(0)
for line in file.readlines():
    #do more stuff

with:

lines = file.readlines()
for each_line in lines:
    #do stuff
for each_line in lines:
    #do more stuff

You can also iterate over a file, one line at a time, without holding the whole file in memory (this can be very useful for very large files) by doing:

for line in file:
    #do stuff

Iterating each character in a string using Python

If you need access to the index as you iterate through the string, use enumerate():

>>> for i, c in enumerate('test'):
...     print i, c
... 
0 t
1 e
2 s
3 t

Why is using "for...in" for array iteration a bad idea?

There are three reasons why you shouldn't use for..in to iterate over array elements:

  • for..in will loop over all own and inherited properties of the array object which aren't DontEnum; that means if someone adds properties to the specific array object (there are valid reasons for this - I've done so myself) or changed Array.prototype (which is considered bad practice in code which is supposed to work well with other scripts), these properties will be iterated over as well; inherited properties can be excluded by checking hasOwnProperty(), but that won't help you with properties set in the array object itself

  • for..in isn't guaranteed to preserve element ordering

  • it's slow because you have to walk all properties of the array object and its whole prototype chain and will still only get the property's name, ie to get the value, an additional lookup will be required

Best way to iterate through a Perl array

The best way to decide questions like this to benchmark them:

use strict;
use warnings;
use Benchmark qw(:all);

our @input_array = (0..1000);

my $a = sub {
    my @array = @{[ @input_array ]};
    my $index = 0;
    foreach my $element (@array) {
       die unless $index == $element;
       $index++;
    }
};

my $b = sub {
    my @array = @{[ @input_array ]};
    my $index = 0;
    while (defined(my $element = shift @array)) {
       die unless $index == $element;
       $index++;
    }
};

my $c = sub {
    my @array = @{[ @input_array ]};
    my $index = 0;
    while (scalar(@array) !=0) {
       my $element = shift(@array);
       die unless $index == $element;
       $index++;
    }
};

my $d = sub {
    my @array = @{[ @input_array ]};
    foreach my $index (0.. $#array) {
       my $element = $array[$index];
       die unless $index == $element;
    }
};

my $e = sub {
    my @array = @{[ @input_array ]};
    for (my $index = 0; $index <= $#array; $index++) {
       my $element = $array[$index];
       die unless $index == $element;
    }
};

my $f = sub {
    my @array = @{[ @input_array ]};
    while (my ($index, $element) = each @array) {
       die unless $index == $element;
    }
};

my $count;
timethese($count, {
   '1' => $a,
   '2' => $b,
   '3' => $c,
   '4' => $d,
   '5' => $e,
   '6' => $f,
});

And running this on perl 5, version 24, subversion 1 (v5.24.1) built for x86_64-linux-gnu-thread-multi

I get:

Benchmark: running 1, 2, 3, 4, 5, 6 for at least 3 CPU seconds...
         1:  3 wallclock secs ( 3.16 usr +  0.00 sys =  3.16 CPU) @ 12560.13/s (n=39690)
         2:  3 wallclock secs ( 3.18 usr +  0.00 sys =  3.18 CPU) @ 7828.30/s (n=24894)
         3:  3 wallclock secs ( 3.23 usr +  0.00 sys =  3.23 CPU) @ 6763.47/s (n=21846)
         4:  4 wallclock secs ( 3.15 usr +  0.00 sys =  3.15 CPU) @ 9596.83/s (n=30230)
         5:  4 wallclock secs ( 3.20 usr +  0.00 sys =  3.20 CPU) @ 6826.88/s (n=21846)
         6:  3 wallclock secs ( 3.12 usr +  0.00 sys =  3.12 CPU) @ 5653.53/s (n=17639)

So the 'foreach (@Array)' is about twice as fast as the others. All the others are very similar.

@ikegami also points out that there are quite a few differences in these implimentations other than speed.

Is there a way in Pandas to use previous row value in dataframe.apply when previous value is also calculated in the apply?

It's an old question but the solution below (without a for loop) might be helpful:

def new_fun(df):
    prev_value = df.iloc[0]["C"]
    def func2(row):
        # non local variable ==> will use pre_value from the new_fun function
        nonlocal prev_value
        new_value =  prev_value * row['A'] + row['B']
        prev_value = row['C']
        return new_value
    # This line might throw a SettingWithCopyWarning warning
    df.iloc[1:]["C"] = df.iloc[1:].apply(func2, axis=1)
    return df

df = new_fun(df)

How do I iterate through each element in an n-dimensional matrix in MATLAB?

You could make a recursive function do the work

  • Let L = size(M)
  • Let idx = zeros(L,1)
  • Take length(L) as the maximum depth
  • Loop for idx(depth) = 1:L(depth)
  • If your depth is length(L), do the element operation, else call the function again with depth+1

Not as fast as vectorized methods if you want to check all the points, but if you don't need to evaluate most of them it can be quite a time saver.

What exactly are iterator, iterable, and iteration?

Here's another view using collections.abc. This view may be useful the second time around or later.

From collections.abc we can see the following hierarchy:

builtins.object
    Iterable
        Iterator
            Generator

i.e. Generator is derived from Iterator is derived from Iterable is derived from the base object.

Hence,

  • Every iterator is an iterable, but not every iterable is an iterator. For example, [1, 2, 3] and range(10) are iterables, but not iterators. x = iter([1, 2, 3]) is an iterator and an iterable.
  • A similar relationship exists between Iterator and Generator.
  • Calling iter() on an iterator or a generator returns itself. Thus, if it is an iterator, then iter(it) is it is True.
  • Under the hood, a list comprehension like [2 * x for x in nums] or a for loop like for x in nums:, acts as though iter() is called on the iterable (nums) and then iterates over nums using that iterator. Hence, all of the following are functionally equivalent (with, say, nums=[1, 2, 3]):
    • for x in nums:
    • for x in iter(nums):
    • for x in iter(iter(nums)):
    • for x in iter(iter(iter(iter(iter(nums))))):

How do I efficiently iterate over each entry in a Java Map?

package com.test;

import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

public class Test {

    public static void main(String[] args) {
        Map<String, String> map = new HashMap<String, String>();
        map.put("ram", "ayodhya");
        map.put("krishan", "mathura");
        map.put("shiv", "kailash");

        System.out.println("********* Keys *********");
        Set<String> keys = map.keySet();
        for (String key : keys) {
            System.out.println(key);
        }

        System.out.println("********* Values *********");
        Collection<String> values = map.values();
        for (String value : values) {
            System.out.println(value);
        }

        System.out.println("***** Keys and Values (Using for each loop) *****");
        for (Map.Entry<String, String> entry : map.entrySet()) {
            System.out.println("Key: " + entry.getKey() + "\t Value: "
                    + entry.getValue());
        }

        System.out.println("***** Keys and Values (Using while loop) *****");
        Iterator<Entry<String, String>> entries = map.entrySet().iterator();
        while (entries.hasNext()) {
            Map.Entry<String, String> entry = (Map.Entry<String, String>) entries
                    .next();
            System.out.println("Key: " + entry.getKey() + "\t Value: "
                    + entry.getValue());
        }

        System.out
                .println("** Keys and Values (Using java 8 using lambdas )***");
        map.forEach((k, v) -> System.out
                .println("Key: " + k + "\t value: " + v));
    }
}

Iterating a JavaScript object's properties using jQuery

You can use each for objects too and not just for arrays:

var obj = {
    foo: "bar",
    baz: "quux"
};
jQuery.each(obj, function(name, value) {
    alert(name + ": " + value);
});

What is the difference between Sprint and Iteration in Scrum and length of each Sprint?

According to my experience

  1. Sprint is a kind of Iteration and one can have many Iterations within a single Sprint (e.g. one shall startover or iterate a task if it's failed and still having extra estimated time) or across many Sprints (such as performing ongoing tasks).
  2. Normally, the duration for a Sprint can be one or two weeks, It depends on the time required and the priority of tasks (which could be defined by Product Owner or Scrum Master or the team) from the Product Backlog.

ref: https://en.wikipedia.org/wiki/Scrum_(software_development)

Loading a properties file from Java package

When loading the Properties from a Class in the package com.al.common.email.templates you can use

Properties prop = new Properties();
InputStream in = getClass().getResourceAsStream("foo.properties");
prop.load(in);
in.close();

(Add all the necessary exception handling).

If your class is not in that package, you need to aquire the InputStream slightly differently:

InputStream in = 
 getClass().getResourceAsStream("/com/al/common/email/templates/foo.properties");

Relative paths (those without a leading '/') in getResource()/getResourceAsStream() mean that the resource will be searched relative to the directory which represents the package the class is in.

Using java.lang.String.class.getResource("foo.txt") would search for the (inexistent) file /java/lang/String/foo.txt on the classpath.

Using an absolute path (one that starts with '/') means that the current package is ignored.

How to rotate portrait/landscape Android emulator?

See the Android documentation on controlling the emulator; it's Ctrl + F11 / Ctrl + F12.

On ThinkPad running Ubuntu, you may try CTRL + Left Arrow Key or Right Arrow Key

Select all columns except one in MySQL?

I liked the answer from @Mahomedalid besides this fact informed in comment from @Bill Karwin. The possible problem raised by @Jan Koritak is true I faced that but I have found a trick for that and just want to share it here for anyone facing the issue.

we can replace the REPLACE function with where clause in the sub-query of Prepared statement like this:

Using my table and column name

SET @SQL = CONCAT('SELECT ', (SELECT GROUP_CONCAT(COLUMN_NAME) FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'users' AND COLUMN_NAME NOT IN ('id')), ' FROM users');
PREPARE stmt1 FROM @SQL;
EXECUTE stmt1;

So, this is going to exclude only the field id but not company_id

PHP executable not found. Install PHP 7 and add it to your PATH or set the php.executablePath setting

Try this !!!. This will solve your problem for sure!

Method 1 -

Step 1 - Go to 'Environmental Variables'.

Step 2 - Find PATH variable and add the path to your PHP folder.

Step 3 - For 'XAMPP' users put 'C:\xampp\php' and 'WAMP' users put 'C:\wamp64\bin\php\php7.1.9' ) and save.

Method 2-

In VS Code

File -> Preferences -> Settings.

enter image description here

Open 'settings.json' file and put the below codes.

If you are using WAMP put this code and Save.

  "php.validate.executablePath": "C:\\wamp64\\bin\\php\\php7.1.9\\php.exe",
  "php.executablePath": "C:\\wamp64\\bin\\php\\php7.1.9\\php.exe"

If you are using XAMPP put this code and Save.

  "php.validate.executablePath": "C:\\xampp\\php\\php.exe",
  "php.executablePath": "C:\\xampp\\php\\php.exe"

Note - Replace php7.1.9 with your PHP version.

How to use a client certificate to authenticate and authorize in a Web API

Looking at the source code I also think there must be some issue with the private key.

What it is doing is actually to check if the certificate that is passed is of type X509Certificate2 and if it has the private key.

If it doesn't find the private key it tries to find the certificate in the CurrentUser store and then in the LocalMachine store. If it finds the certificate it checks if the private key is present.

(see source code from class SecureChannnel, method EnsurePrivateKey)

So depending on which file you imported (.cer - without private key or .pfx - with private key) and on which store it might not find the right one and Request.ClientCertificate won't be populated.

You can activate Network Tracing to try to debug this. It will give you output like this:

  • Trying to find a matching certificate in the certificate store
  • Cannot find the certificate in either the LocalMachine store or the CurrentUser store.

Mongoose, update values in array of objects

Below is an example of how to update the value in the array of objects more dynamically.

Person.findOneAndUpdate({_id: id}, 
{ 
  "$set": {[`items.$[outer].${propertyName}`]: value} 
},
{ 
  "arrayFilters": [{ "outer.id": itemId }]
},
function(err, response) {
  ...
})

Note that by doing it that way, you would be able to update even deeper levels of the nested array by adding additional arrayFilters and positional operator like so:

"$set": {[`items.$[outer].innerItems.$[inner].${propertyName}`]: value} 

"arrayFilters":[{ "outer.id": itemId },{ "inner.id": innerItemId }]

More usage can be found in the official docs.

How to parse/read a YAML file into a Python object?

If your YAML file looks like this:

# tree format
treeroot:
    branch1:
        name: Node 1
        branch1-1:
            name: Node 1-1
    branch2:
        name: Node 2
        branch2-1:
            name: Node 2-1

And you've installed PyYAML like this:

pip install PyYAML

And the Python code looks like this:

import yaml
with open('tree.yaml') as f:
    # use safe_load instead load
    dataMap = yaml.safe_load(f)

The variable dataMap now contains a dictionary with the tree data. If you print dataMap using PrettyPrint, you will get something like:

{
    'treeroot': {
        'branch1': {
            'branch1-1': {
                'name': 'Node 1-1'
            },
            'name': 'Node 1'
        },
        'branch2': {
            'branch2-1': {
                'name': 'Node 2-1'
            },
            'name': 'Node 2'
        }
    }
}

So, now we have seen how to get data into our Python program. Saving data is just as easy:

with open('newtree.yaml', "w") as f:
    yaml.dump(dataMap, f)

You have a dictionary, and now you have to convert it to a Python object:

class Struct:
    def __init__(self, **entries): 
        self.__dict__.update(entries)

Then you can use:

>>> args = your YAML dictionary
>>> s = Struct(**args)
>>> s
<__main__.Struct instance at 0x01D6A738>
>>> s...

and follow "Convert Python dict to object".

For more information you can look at pyyaml.org and this.

What is @ModelAttribute in Spring MVC?

The ModelAttribute annotation is used as part of a Spring MVC Web application and can be used in two scenarios.

First of all, it can be used to inject data into a pre-JSP load model. This is especially useful in ensuring that a JSP is required to display all the data itself. An injection is obtained by connecting one method to the model.

Second, it can be used to read data from an existing model and assign it to the parameters of the coach's method.

refrence https://dzone.com/articles/using-spring-mvc%E2%80%99s

Job for httpd.service failed because the control process exited with error code. See "systemctl status httpd.service" and "journalctl -xe" for details

<VirtualHost *:80>
    ServerName www.YOURDOMAIN.COM
    ServerAlias YOURDOMAIN.COM
    DocumentRoot /var/www/YOURDOMAIN.COM/public_html
    ErrorLog /var/www/YOURDOMAIN.COM/error.log
    CustomLog /var/www/YOURDOMAIN.COM/requests.log combined

    DocumentRoot /var/www/YOURDOMAIN.COM/public_html
    <Directory />
        Options FollowSymLinks
        AllowOverride None
    </Directory>
    <Directory /var/www/YOURDOMAIN.COM/public_html>
        Options Indexes FollowSymLinks MultiViews
        AllowOverride All
        Order allow,deny
        allow from all
    </Directory>

</VirtualHost>

How to publish a Web Service from Visual Studio into IIS?

If using Visual Studio 2010 you can right-click on the project for the service, and select properties. Then select the Web tab. Under the Servers section you can configure the URL. There is also a button to create the virtual directory.

download csv file from web api in angular js

I think the best way to download any file generated by REST call is to use window.location example :

_x000D_
_x000D_
    $http({_x000D_
        url: url,_x000D_
        method: 'GET'_x000D_
    })_x000D_
    .then(function scb(response) {_x000D_
        var dataResponse = response.data;_x000D_
        //if response.data for example is : localhost/export/data.csv_x000D_
        _x000D_
        //the following will download the file without changing the current page location_x000D_
        window.location = 'http://'+ response.data_x000D_
    }, function(response) {_x000D_
      showWarningNotification($filter('translate')("global.errorGetDataServer"));_x000D_
    });
_x000D_
_x000D_
_x000D_

Change User Agent in UIWebView

By pooling the answer by Louis St-Amour and the NSUserDefaults+UnRegisterDefaults category from this question/answer, you can use the following methods to start and stop user-agent spoofing at any time while your app is running:

#define kUserAgentKey @"UserAgent"

- (void)startSpoofingUserAgent:(NSString *)userAgent {
    [[NSUserDefaults standardUserDefaults] registerDefaults:@{ kUserAgentKey : userAgent }];
}

- (void)stopSpoofingUserAgent {
    [[NSUserDefaults standardUserDefaults] unregisterDefaultForKey:kUserAgentKey];
}

How can I hide or encrypt JavaScript code?

The only safe way to protect your code is not giving it away. With client deployment, there is no avoiding the client having access to the code.

So the short answer is: You can't do it

The longer answer is considering flash or Silverlight. Although I believe silverlight will gladly give away it's secrets with reflector running on the client.

I'm not sure if something simular exists with the flash platform.

UnicodeDecodeError: 'ascii' codec can't decode byte 0xe2 in position 13: ordinal not in range(128)

To find ANY and ALL unicode error related... Using the following command:

grep -r -P '[^\x00-\x7f]' /etc/apache2 /etc/letsencrypt /etc/nginx

Found mine in

/etc/letsencrypt/options-ssl-nginx.conf:        # The following CSP directives don't use default-src as 

Using shed, I found the offending sequence. It turned out to be an editor mistake.

00008099:     C2  194 302 11000010
00008100:     A0  160 240 10100000
00008101:  d  64  100 144 01100100
00008102:  e  65  101 145 01100101
00008103:  f  66  102 146 01100110
00008104:  a  61  097 141 01100001
00008105:  u  75  117 165 01110101
00008106:  l  6C  108 154 01101100
00008107:  t  74  116 164 01110100
00008108:  -  2D  045 055 00101101
00008109:  s  73  115 163 01110011
00008110:  r  72  114 162 01110010
00008111:  c  63  099 143 01100011
00008112:     C2  194 302 11000010
00008113:     A0  160 240 10100000

Difference between JPanel, JFrame, JComponent, and JApplet

JFrame and JApplet are top level containers. If you wish to create a desktop application, you will use JFrame and if you plan to host your application in browser you will use JApplet.

JComponent is an abstract class for all Swing components and you can use it as the base class for your new component. JPanel is a simple usable component you can use for almost anything.

Since this is for a fun project, the simplest way for you is to work with JPanel and then host it inside JFrame or JApplet. Netbeans has a visual designer for Swing with simple examples.

React navigation goBack() and update parent state

You can pass a callback function as parameter when you call navigate like this:

  const DEMO_TOKEN = await AsyncStorage.getItem('id_token');
  if (DEMO_TOKEN === null) {
    this.props.navigation.navigate('Login', {
      onGoBack: () => this.refresh(),
    });
    return -3;
  } else {
    this.doSomething();
  }

And define your callback function:

refresh() {
  this.doSomething();
}

Then in the login/registration view, before goBack, you can do this:

await AsyncStorage.setItem('id_token', myId);
this.props.navigation.state.params.onGoBack();
this.props.navigation.goBack();

Update for React Navigation v5:

await AsyncStorage.setItem('id_token', myId);
this.props.route.params.onGoBack();
this.props.navigation.goBack();

TypeError: window.initMap is not a function

This may seem obvious but just in case: If someone placed the JS code inside $(document).ready like this:

     $(document).ready(function() {
       ... Google Maps JS code ...
      }

Then that's the problem because using async defer when loading the Google Maps API library, it will load asynchronously, and when it finishes loading, will look for the callback function, which needs to be available by then.

So, you just need to put the code outside $(document).ready, and:

<script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap"
    async defer></script>

at the very bottom, so your page loads FAST :-)

html select option separator

 <option  data-divider="true" disabled>______________</option>

you can do this one also. it is easy and make divider select drop down list.

Getting value GET OR POST variable using JavaScript?

When i had the issue i saved the value into a hidden input:

in html body:

    <body>
    <?php 
    if (isset($_POST['Id'])){
      $fid= $_POST['Id']; 
    }
    ?>

... then put the hidden input on the page and write the value $fid with php echo

    <input type=hidden id ="fid" name=fid value="<?php echo $fid ?>">

then in $(document).ready( function () {

    var postId=document.getElementById("fid").value;

so i got my hidden url parameter in php an js.

how to git commit a whole folder?

OR, even better just the ol' "drag and drop" the folder, onto your repository opened in git browser.

  1. Open your repository in the web portal , you will see the listing of all your files. If you have just recently created the repo, and initiated with a README, you will only see the README listing.

  2. Open your folder which you want to upload. drag and drop on the listing in browser. See the image here.

How to scroll to top of long ScrollView layout?

Try

mainScrollView.fullScroll(ScrollView.FOCUS_UP);

it should work.

Compiler error "archive for required library could not be read" - Spring Tool Suite

In my case I had to manually delete all the files in .m2\repository folder and then open command prompt and run mvn -install command in my project directory.

rails generate model

For me what happened was that I generated the app with rails new rails new chapter_2 but the RVM --default had rails 4.0.2 gem, but my chapter_2 project use a new gemset with rails 3.2.16.

So when I ran

rails generate scaffold User name:string email:string

the console showed

Usage:
   rails new APP_PATH [options]

So I fixed the RVM and the gemset with the rails 3.2.16 gem , and then generated the app again then I executed

 rails generate scaffold User name:string email:string

and it worked

VBA for clear value in specific range of cell and protected cell from being wash away formula

Not sure its faster with VBA - the fastest way to do it in the normal Excel programm would be:

  1. Ctrl-G
  2. A1:X50 Enter
  3. Delete

Unless you have to do this very often, entering and then triggering the VBAcode is more effort.

And in case you only want to delete formulas or values, you can insert Ctrl-G, Alt-S to select Goto Special and here select Formulas or Values.

NoClassDefFoundError while trying to run my jar with java.exe -jar...what's wrong?

The -jar option is mutually exclusive of -classpath. See an old description here

-jar

Execute a program encapsulated in a JAR file. The first argument is the name of a JAR file instead of a startup class name. In order for this option to work, the manifest of the JAR file must contain a line of the form Main-Class: classname. Here, classname identifies the class having the public static void main(String[] args) method that serves as your application's starting point.

See the Jar tool reference page and the Jar trail of the Java Tutorial for information about working with Jar files and Jar-file manifests.

When you use this option, the JAR file is the source of all user classes, and other user class path settings are ignored.

A quick and dirty hack is to append your classpath to the bootstrap classpath:

-Xbootclasspath/a:path

Specify a colon-separated path of directires, JAR archives, and ZIP archives to append to the default bootstrap class path.

However, as @Dan rightly says, the correct solution is to ensure your JARs Manifest contains the classpath for all JARs it will need.

Converting File to MultiPartFile

If you can't import MockMultipartFile using

import org.springframework.mock.web.MockMultipartFile;

you need to add the below dependency into pom.xml:

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

java comparator, how to sort by integer?

If you have access to the Java 8 Comparable API, Comparable.comparingToInt() may be of use. (See Java 8 Comparable Documentation).

For example, a Comparator<Dog> to sort Dog instances descending by age could be created with the following:

Comparable.comparingToInt(Dog::getDogAge).reversed();

The function take a lambda mapping T to Integer, and creates an ascending comparator. The chained function .reversed() turns the ascending comparator into a descending comparator.

Note: while this may not be useful for most versions of Android out there, I came across this question while searching for similar information for a non-Android Java application. I thought it might be useful to others in the same spot to see what I ended up settling on.

How do I create a MessageBox in C#?

Code summary:

using System.Windows.Forms;

...

MessageBox.Show( "hello world" );

Also (as per this other stack post): In Visual Studio expand the project in Solution Tree, right click on References, Add Reference, Select System.Windows.Forms on Framework tab. This will get the MessageBox working in conjunction with the using System.Windows.Forms reference from above.

How to dismiss ViewController in Swift?

If you are presenting a ViewController modally, and want to go back to the root ViewController, take care to dismiss this modally presented ViewController before you go back to the root ViewController otherwise this ViewController will not be removed from Memory and cause Memory leaks.

Get the string representation of a DOM node

Use element.outerHTML to get full representation of element, including outer tags and attributes.

Converting a date in MySQL from string field

STR_TO_DATE allows you to do this, and it has a format argument.

Safely limiting Ansible playbooks to a single machine?

There's IMHO a more convenient way. You can indeed interactively prompt the user for the machine(s) he wants to apply the playbook to thanks to vars_prompt:

---

- hosts: "{{ setupHosts }}"
  vars_prompt:
    - name: "setupHosts"
      prompt: "Which hosts would you like to setup?"
      private: no
  tasks:
    […]

Why I get 411 Length required error?

var requestedURL = "https://accounts.google.com/o/oauth2/token?code=" + code + "&client_id=" + client_id + "&client_secret=" + client_secret + "&redirect_uri=" + redirect_uri + "&grant_type=authorization_code";
HttpWebRequest authRequest = (HttpWebRequest)WebRequest.Create(requestedURL);
authRequest.ContentType = "application/x-www-form-urlencoded";
authRequest.Method = "POST";
//Set content length to 0
authRequest.ContentLength = 0;
WebResponse authResponseTwitter = authRequest.GetResponse();

The ContentLength property contains the value to send as the Content-length HTTP header with the request.

Any value other than -1 in the ContentLength property indicates that the request uploads data and that only methods that upload data are allowed to be set in the Method property.

After the ContentLength property is set to a value, that number of bytes must be written to the request stream that is returned by calling the GetRequestStream method or both the BeginGetRequestStream and the EndGetRequestStream methods.

for more details click here

Trigger function when date is selected with jQuery UI datepicker

If you are also interested in the case where the user closes the date selection dialog without selecting a date (in my case choosing no date also has meaning) you can bind to the onClose event:

$('#datePickerElement').datepicker({
         onClose: function (dateText, inst) {
            //you will get here once the user is done "choosing" - in the dateText you will have 
            //the new date or "" if no date has been selected             
      });

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

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

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

How to escape special characters of a string with single backslashes

Utilize the output of built-in repr to deal with \r\n\t and process the output of re.escape is what you want:

re.escape(repr(a)[1:-1]).replace('\\\\', '\\')

json: cannot unmarshal object into Go value of type

Determining of root cause is not an issue since Go 1.8; field name now is shown in the error message:

json: cannot unmarshal object into Go struct field Comment.author of type string

Find current directory and file's directory

If you are trying to find the current directory of the file you are currently in:

OS agnostic way:

dirname, filename = os.path.split(os.path.abspath(__file__))

How to get row count in an Excel file using POI library?

Since Sheet.getPhysicalNumberOfRows() does not count empty rows and Sheet.getLastRowNum() returns 0 both if there is one row or no rows, I use a combination of the two methods to accurately calculate the total number of rows.

int rowTotal = sheet.getLastRowNum();

if ((rowTotal > 0) || (sheet.getPhysicalNumberOfRows() > 0)) {
    rowTotal++;
}

Note: This will treat a spreadsheet with one empty row as having none but for most purposes this is probably okay.

Change Active Menu Item on Page Scroll?

It's done by binding to the scroll event of the container (usually window).

Quick example:

// Cache selectors
var topMenu = $("#top-menu"),
    topMenuHeight = topMenu.outerHeight()+15,
    // All list items
    menuItems = topMenu.find("a"),
    // Anchors corresponding to menu items
    scrollItems = menuItems.map(function(){
      var item = $($(this).attr("href"));
      if (item.length) { return item; }
    });

// Bind to scroll
$(window).scroll(function(){
   // Get container scroll position
   var fromTop = $(this).scrollTop()+topMenuHeight;

   // Get id of current scroll item
   var cur = scrollItems.map(function(){
     if ($(this).offset().top < fromTop)
       return this;
   });
   // Get the id of the current element
   cur = cur[cur.length-1];
   var id = cur && cur.length ? cur[0].id : "";
   // Set/remove active class
   menuItems
     .parent().removeClass("active")
     .end().filter("[href='#"+id+"']").parent().addClass("active");
});?

See the above in action at jsFiddle including scroll animation.

How can I "reset" an Arduino board?

After scratching my head about this problem, here is a very simple solution that works anytime:

  • Unplug your USB cable
  • Go in Device Manager
  • Click on Ports (COM & LPT)
  • Right click on Arduino....(COMx)
  • Properties
  • Port Settings
  • Put Flow Control to HARDWARE
  • Create an empty sketch (Optional)
  • Connect the USB cable
  • Upload (Ctrl + U)

// Empty sketch to fix the upload problem
// Created by Eric Phenix
// Nov 2014

void setup()
{
}

// The loop routine runs over and over again forever:
void loop()
{
    delay(1000);
}

Et voila!

Remove commas from the string using JavaScript

To remove the commas, you'll need to use replace on the string. To convert to a float so you can do the maths, you'll need parseFloat:

var total = parseFloat('100,000.00'.replace(/,/g, '')) +
            parseFloat('500,000.00'.replace(/,/g, ''));

Streaming Audio from A URL in Android using MediaPlayer?

I've had the same error as you have and it turned out that there was nothing wrong with the code. The problem was that the webserver was sending the wrong Content-Type header.

Try wireshark or something similar to see what content-type the webserver is sending.

How do I remove time part from JavaScript date?

The previous answers are fine, just adding my preferred way of handling this:

var timePortion = myDate.getTime() % (3600 * 1000 * 24);
var dateOnly = new Date(myDate - timePortion);

If you start with a string, you first need to parse it like so:

var myDate = new Date(dateString);

And if you come across timezone related problems as I have, this should fix it:

var timePortion = (myDate.getTime() - myDate.getTimezoneOffset() * 60 * 1000) % (3600 * 1000 * 24);

Get lengths of a list in a jinja2 template

I've experienced a problem with length of None, which leads to Internal Server Error: TypeError: object of type 'NoneType' has no len()

My workaround is just displaying 0 if object is None and calculate length of other types, like list in my case:

{{'0' if linked_contacts == None else linked_contacts|length}}

A connection was successfully established with the server, but then an error occurred during the pre-login handshake

You might want to check a few things:

  1. You production server allows remote connections. (possible that someone turned this off, especially if you have a DBA)

  2. Check your connection string. Sometimes if you are using an ip address or server name this will cause this error. Try both.

PHP sessions default timeout

It depends on the server configuration or the relevant directives session.gc_maxlifetime in php.ini.

Typically the default is 24 minutes (1440 seconds), but your webhost may have altered the default to something else.

MySQL Cannot drop index needed in a foreign key constraint

A foreign key always requires an index. Without an index enforcing the constraint would require a full table scan on the referenced table for every inserted or updated key in the referencing table. And that would have an unacceptable performance impact. This has the following 2 consequences:

  • When creating a foreign key, the database checks if an index exists. If not an index will be created. By default, it will have the same name as the constraint.
  • When there is only one index that can be used for the foreign key, it can't be dropped. If you really wan't to drop it, you either have to drop the foreign key constraint or to create another index for it first.

How can I extract a number from a string in JavaScript?

You can extract numbers from a string using a regex expression:

let string = "xxfdx25y93.34xxd73";
let res = string.replace(/\D/g, "");
console.log(res); 

output: 25933473

CSS border less than 1px

It's impossible to draw a line on screen that's thinner than one pixel. Try using a more subtle color for the border instead.

How to get disk capacity and free space of remote computer

Much simpler solution:

Get-PSDrive C | Select-Object Used,Free

and for remote computers (needs Powershell Remoting)

Invoke-Command -ComputerName SRV2 {Get-PSDrive C} | Select-Object PSComputerName,Used,Free

Difference between a SOAP message and a WSDL?

A SOAP document is sent per request. Say we were a book store, and had a remote server we queried to learn the current price of a particular book. Say we needed to pass the Book's title, number of pages and ISBN number to the server.

Whenever we wanted to know the price, we'd send a unique SOAP message. It'd look something like this;

<SOAP-ENV:Envelope
  xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"
  SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
  <SOAP-ENV:Body>
    <m:GetBookPrice xmlns:m="http://namespaces.my-example-book-info.com">
      <ISBN>978-0451524935</ISBN>
      <Title>1984</Title>
      <NumPages>328</NumPages>
    </m:GetBookPrice>
  </SOAP-ENV:Body>
</SOAP-ENV:Envelope> 

And we expect to get a SOAP response message back like;

<SOAP-ENV:Envelope
  xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"
  SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
  <SOAP-ENV:Body>
    <m:GetBookPriceResponse xmlns:m="http://namespaces.my-example-book-info.com">
      <CurrentPrice>8.99</CurrentPrice>
      <Currency>USD</Currency>
    </m:GetBookPriceResponse>
  </SOAP-ENV:Body>
</SOAP-ENV:Envelope>

The WSDL then describes how to handle/process this message when a server receives it. In our case, it describes what types the Title, NumPages & ISBN would be, whether we should expect a response from the GetBookPrice message and what that response should look like.

The types would look like this;

<wsdl:types>

  <!-- all type declarations are in a chunk of xsd -->
  <xsd:schema targetNamespace="http://namespaces.my-example-book-info.com"
    xmlns:xsd="http://www.w3.org/1999/XMLSchema">

    <xsd:element name="GetBookPrice">
      <xsd:complexType>
        <xsd:sequence>
          <xsd:element name="ISBN" type="string"/>
          <xsd:element name="Title" type="string"/>
          <xsd:element name="NumPages" type="integer"/>
        </xsd:sequence>
      </xsd:complexType>
    </xsd:element>

    <xsd:element name="GetBookPriceResponse">
      <xsd:complexType>
        <xsd:sequence>
          <xsd:element name="CurrentPrice" type="decimal" />
          <xsd:element name="Currency" type="string" />
        </xsd:sequence>
      </xsd:complexType>
    </xsd:element>

  </xsd:schema>
</wsdl:types>

But the WSDL also contains more information, about which functions link together to make operations, and what operations are avaliable in the service, and whereabouts on a network you can access the service/operations.

See also W3 Annotated WSDL Examples

How to parse my json string in C#(4.0)using Newtonsoft.Json package?

This is a simple example of JSON parsing by taking example of google map API. This will return City name of given zip code.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Newtonsoft.Json;
using System.Net;

namespace WebApplication1
{
    public partial class WebForm1 : System.Web.UI.Page
    {
        WebClient client = new WebClient();
        string jsonstring;
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            jsonstring = client.DownloadString("http://maps.googleapis.com/maps/api/geocode/json?address="+txtzip.Text.Trim());
            dynamic dynObj = JsonConvert.DeserializeObject(jsonstring);

            Response.Write(dynObj.results[0].address_components[1].long_name);
        }
    }
}

WordPress Get the Page ID outside the loop

You can also create a generic function to get the ID of the post, whether its outside or inside the loop (handles both the cases):

<?php

/**
 * @uses WP_Query
 * @uses get_queried_object()
 * @see get_the_ID()
 * @return int
 */
function get_the_post_id() {
  if (in_the_loop()) {
       $post_id = get_the_ID();
  } else {
       global $wp_query;
       $post_id = $wp_query->get_queried_object_id();
         }
  return $post_id;
} ?>

And simply do:

$page_id = get_the_post_id();

jQuery callback for multiple ajax calls

async   : false,

By default, all requests are sent asynchronously (i.e. this is set to true by default). If you need synchronous requests, set this option to false. Cross-domain requests and dataType: "jsonp" requests do not support synchronous operation. Note that synchronous requests may temporarily lock the browser, disabling any actions while the request is active. As of jQuery 1.8, the use of async: false with jqXHR ($.Deferred) is deprecated; you must use the success/error/complete callback options instead of the corresponding methods of the jqXHR object such as jqXHR.done() or the deprecated jqXHR.success().

What is the equivalent of Java's final in C#?

What everyone here is missing is Java's guarantee of definite assignment for final member variables.

For a class C with final member variable V, every possible execution path through every constructor of C must assign V exactly once - failing to assign V or assigning V two or more times will result in an error.

C#'s readonly keyword has no such guarantee - the compiler is more than happy to leave readonly members unassigned or allow you to assign them multiple times within a constructor.

So, final and readonly (at least with respect to member variables) are definitely not equivalent - final is much more strict.

How to configure robots.txt to allow everything?

I understand that this is fairly old question and has some pretty good answers. But, here is my two cents for the sake of completeness.

As per the official documentation, there are four ways, you can allow complete access for robots to access your site.

Clean:

Specify a global matcher with a disallow segment as mentioned by @unor. So your /robots.txt looks like this.

User-agent: *
Disallow:

The hack:

Create a /robots.txt file with no content in it. Which will default to allow all for all type of Bots.

I don't care way:

Do not create a /robots.txt altogether. Which should yield the exact same results as the above two.

The ugly:

From the robots documentation for meta tags, You can use the following meta tag on all your pages on your site to let the Bots know that these pages are not supposed to be indexed.

<META NAME="ROBOTS" CONTENT="NOINDEX">

In order for this to be applied to your entire site, You will have to add this meta tag for all of your pages. And this tag should strictly be placed under your HEAD tag of the page. More about this meta tag here.

Convert a float64 to an int in Go

Simply casting to an int truncates the float, which if your system internally represent 2.0 as 1.9999999999, you will not get what you expect. The various printf conversions deal with this and properly round the number when converting. So to get a more accurate value, the conversion is even more complicated than you might first expect:

package main

import (
    "fmt"
    "strconv"
)

func main() {
    floats := []float64{1.9999, 2.0001, 2.0}
    for _, f := range floats {
        t := int(f)
        s := fmt.Sprintf("%.0f", f)
        if i, err := strconv.Atoi(s); err == nil {
            fmt.Println(f, t, i)
        } else {
            fmt.Println(f, t, err)
        }
    }
}

Code on Go Playground

HTML / CSS Popup div on text click

DEMO

In the content area you can provide whatever you want to display in it.

_x000D_
_x000D_
.black_overlay {_x000D_
  display: none;_x000D_
  position: absolute;_x000D_
  top: 0%;_x000D_
  left: 0%;_x000D_
  width: 100%;_x000D_
  height: 100%;_x000D_
  background-color: black;_x000D_
  z-index: 1001;_x000D_
  -moz-opacity: 0.8;_x000D_
  opacity: .80;_x000D_
  filter: alpha(opacity=80);_x000D_
}_x000D_
.white_content {_x000D_
  display: none;_x000D_
  position: absolute;_x000D_
  top: 25%;_x000D_
  left: 25%;_x000D_
  width: 50%;_x000D_
  height: 50%;_x000D_
  padding: 16px;_x000D_
  border: 16px solid orange;_x000D_
  background-color: white;_x000D_
  z-index: 1002;_x000D_
  overflow: auto;_x000D_
}
_x000D_
<html>_x000D_
_x000D_
<head>_x000D_
  <title>LIGHTBOX EXAMPLE</title>_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
  <p>This is the main content. To display a lightbox click <a href="javascript:void(0)" onclick="document.getElementById('light').style.display='block';document.getElementById('fade').style.display='block'">here</a>_x000D_
  </p>_x000D_
  <div id="light" class="white_content">This is the lightbox content. <a href="javascript:void(0)" onclick="document.getElementById('light').style.display='none';document.getElementById('fade').style.display='none'">Close</a>_x000D_
  </div>_x000D_
  <div id="fade" class="black_overlay"></div>_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
_x000D_
_x000D_

How enable auto-format code for Intellij IDEA?

This can also be achieved by Ctrl+WindowsBtn+Alt+L. This will be important to some people,because in some Virtual Machines, Ctrl+Alt+L can log you out.

How to get a variable from a file to another file in Node.js

You need module.exports:

Exports

An object which is shared between all instances of the current module and made accessible through require(). exports is the same as the module.exports object. See src/node.js for more information. exports isn't actually a global but rather local to each module.

For example, if you would like to expose variableName with value "variableValue" on sourceFile.js then you can either set the entire exports as such:

module.exports = { variableName: "variableValue" };

Or you can set the individual value with:

module.exports.variableName = "variableValue";

To consume that value in another file, you need to require(...) it first (with relative pathing):

const sourceFile = require('./sourceFile');
console.log(sourceFile.variableName);

Alternatively, you can deconstruct it.

const { variableName } = require('./sourceFile');
//            current directory --^
// ../     would be one directory down
// ../../  is two directories down

If all you want out of the file is variableName then

./sourceFile.js:

const variableName = 'variableValue'
module.exports = variableName

./consumer.js:

const variableName = require('./sourceFile')

Edit (2020):

Since Node.js version 8.9.0, you can also use ECMAScript Modules with varying levels of support. The documentation.

  • For Node v13.9.0 and beyond, experimental modules are enabled by default
  • For versions of Node less than version 13.9.0, use --experimental-modules

Node.js will treat the following as ES modules when passed to node as the initial input, or when referenced by import statements within ES module code:

  • Files ending in .mjs.
  • Files ending in .js when the nearest parent package.json file contains a top-level field "type" with a value of "module".
  • Strings passed in as an argument to --eval or --print, or piped to node via STDIN, with the flag --input-type=module.

Once you have it setup, you can use import and export.

Using the example above, there are two approaches you can take

./sourceFile.js:

// This is a named export of variableName
export const variableName = 'variableValue'
// Alternatively, you could have exported it as a default. 
// For sake of explanation, I'm wrapping the variable in an object
// but it is not necessary. 
// You can actually omit declaring what variableName is here. 
// { variableName } is equivalent to { variableName: variableName } in this case. 
export default { variableName: variableName } 

./consumer.js:

// There are three ways of importing. 
// If you need access to a non-default export, then 
// you use { nameOfExportedVariable } 
import { variableName } from './sourceFile'
console.log(variableName) // 'variableValue'

// Otherwise, you simply provide a local variable name 
// for what was exported as default.
import sourceFile from './sourceFile'
console.log(sourceFile.variableName) // 'variableValue'

./sourceFileWithoutDefault.js:

// The third way of importing is for situations where there
// isn't a default export but you want to warehouse everything
// under a single variable. Say you have:
export const a = 'A'
export const b = 'B'

./consumer2.js

// Then you can import all exports under a single variable
// with the usage of * as:
import * as sourceFileWithoutDefault from './sourceFileWithoutDefault'

console.log(sourceFileWithoutDefault.a) // 'A'
console.log(sourceFileWithoutDefault.b) // 'B'

// You can use this approach even if there is a default export:
import * as sourceFile from './sourceFile'

// Default exports are under the variable default:
console.log(sourceFile.default) // { variableName: 'variableValue' }

// As well as named exports:
console.log(sourceFile.variableName) // 'variableValue

How to resize an image to fit in the browser window?

I had a similar requirement, and had to do it it basic CSS and JavaScript. No JQuery available.

This is what I got working.

<html>
      <head>
            <style>
                   img {
                          max-width: 95% !important;
                          max-height: 95% !important;
                       }
            </style>
            <script>
                   function FitImagesToScreen() {
                      var images = document.getElementsByTagName('img');
                      if(images.length > 0){
                         for(var i=0; i < images.length; i++){
                             if(images[i].width >= (window.innerWidth - 10)){
                                 images[i].style.width = 'auto';
                               }
                            }
                         }
                   }
             </script>
      </head>
      <body onload='FitImagesToScreen()'>
      ----    
      </body>
</html>

Note : I haven't used 100% for image width as there was always a bit of padding to be considered.

How to give a pandas/matplotlib bar graph custom colors

You can specify the color option as a list directly to the plot function.

from matplotlib import pyplot as plt
from itertools import cycle, islice
import pandas, numpy as np  # I find np.random.randint to be better

# Make the data
x = [{i:np.random.randint(1,5)} for i in range(10)]
df = pandas.DataFrame(x)

# Make a list by cycling through the colors you care about
# to match the length of your data.
my_colors = list(islice(cycle(['b', 'r', 'g', 'y', 'k']), None, len(df)))

# Specify this list of colors as the `color` option to `plot`.
df.plot(kind='bar', stacked=True, color=my_colors)

To define your own custom list, you can do a few of the following, or just look up the Matplotlib techniques for defining a color item by its RGB values, etc. You can get as complicated as you want with this.

my_colors = ['g', 'b']*5 # <-- this concatenates the list to itself 5 times.
my_colors = [(0.5,0.4,0.5), (0.75, 0.75, 0.25)]*5 # <-- make two custom RGBs and repeat/alternate them over all the bar elements.
my_colors = [(x/10.0, x/20.0, 0.75) for x in range(len(df))] # <-- Quick gradient example along the Red/Green dimensions.

The last example yields the follow simple gradient of colors for me:

enter image description here

I didn't play with it long enough to figure out how to force the legend to pick up the defined colors, but I'm sure you can do it.

In general, though, a big piece of advice is to just use the functions from Matplotlib directly. Calling them from Pandas is OK, but I find you get better options and performance calling them straight from Matplotlib.

Post to another page within a PHP script

Although not ideal, if the cURL option doesn't do it for you, may be try using shell_exec();

Get first row of dataframe in Python Pandas based on criteria

you can take care of the first 3 items with slicing and head:

  1. df[df.A>=4].head(1)
  2. df[(df.A>=4)&(df.B>=3)].head(1)
  3. df[(df.A>=4)&((df.B>=3) * (df.C>=2))].head(1)

The condition in case nothing comes back you can handle with a try or an if...

try:
    output = df[df.A>=6].head(1)
    assert len(output) == 1
except: 
    output = df.sort_values('A',ascending=False).head(1)

Convert NSArray to NSString in Objective-C

Swift 3.0 solution:

let string = array.joined(separator: " ")

Check file extension in upload form in PHP

Checking the file extension is not considered best practice. The preferred method of accomplishing this task is by checking the files MIME type.

From PHP:

<?php
    $finfo = finfo_open(FILEINFO_MIME_TYPE); // Return MIME type
    foreach (glob("*") as $filename) {
        echo finfo_file($finfo, $filename) . "\n";
    }
    finfo_close($finfo);
?>

The above example will output something similar to which you should be checking.

text/html
image/gif
application/vnd.ms-excel

Although MIME types can also be tricked (edit the first few bytes of a file and modify the magic numbers), it's harder than editing a filename. So you can never be 100% sure what that file type actually is, and care should be taken about handling files uploaded/emailed by your users.

Shorthand for if-else statement

Try like

var hasName = 'N';
if (name == "true") {
    hasName = 'Y';
}

Or even try with ternary operator like

var hasName = (name == "true") ? "Y" : "N" ;

Even simply you can try like

var hasName = (name) ? "Y" : "N" ;

Since name has either Yes or No but iam not sure with it.

In C++, what is a virtual base class?

You're being a little confusing. I dont' know if you're mixing up some concepts.

You don't have a virtual base class in your OP. You just have a base class.

You did virtual inheritance. This is usually used in multiple inheritance so that multiple derived classes use the members of the base class without reproducing them.

A base class with a pure virtual function is not be instantiated. this requires the syntax that Paul gets at. It is typically used so that derived classes must define those functions.

I don't want to explain any more about this because I don't totally get what you're asking.

Is there a way to follow redirects with command line cURL?

I had a similar problem. I am posting my solution here because I believe it might help one of the commenters.

For me, the obstacle was that the page required a login and then gave me a new URL through javascript. Here is what I had to do:

curl -c cookiejar -g -O -J -L -F "j_username=username" -F "j_password=password" <URL>

Note that j_username and j_password is the name of the fields for my website's login form. You will have to open the source of the webpage to see what the 'name' of the username field and the 'name' of the password field is in your case. After that I go an html file with java script in which the new URL was embedded. After parsing this out just resubmit with the new URL:

curl -c cookiejar -g -O -J -L -F "j_username=username" -F "j_password=password" <NEWURL>

regex match any single character (one character only)

Match any single character

  • Use the dot . character as a wildcard to match any single character.

Example regex: a.c

abc   // match
a c   // match
azc   // match
ac    // no match
abbc  // no match

Match any specific character in a set

  • Use square brackets [] to match any characters in a set.
  • Use \w to match any single alphanumeric character: 0-9, a-z, A-Z, and _ (underscore).
  • Use \d to match any single digit.
  • Use \s to match any single whitespace character.

Example 1 regex: a[bcd]c

abc   // match
acc   // match
adc   // match
ac    // no match
abbc  // no match

Example 2 regex: a[0-7]c

a0c   // match
a3c   // match
a7c   // match
a8c   // no match
ac    // no match
a55c  // no match

Match any character except ...

Use the hat in square brackets [^] to match any single character except for any of the characters that come after the hat ^.

Example regex: a[^abc]c

aac   // no match
abc   // no match
acc   // no match
a c   // match
azc   // match
ac    // no match
azzc  // no match

(Don't confuse the ^ here in [^] with its other usage as the start of line character: ^ = line start, $ = line end.)

Match any character optionally

Use the optional character ? after any character to specify zero or one occurrence of that character. Thus, you would use .? to match any single character optionally.

Example regex: a.?c

abc   // match
a c   // match
azc   // match
ac    // match
abbc  // no match

See also

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

If all you want is to rerun your last command and get the output, a simple bash variable would work:

LAST=`!!`

So then you can run your command on the output with:

yourCommand $LAST

This will spawn a new process and rerun your command, then give you the output. It sounds like what you would really like would be a bash history file for command output. This means you will need to capture the output that bash sends to your terminal. You could write something to watch the /dev or /proc necessary, but that's messy. You could also just create a "special pipe" between your term and bash with a tee command in the middle which redirects to your output file.

But both of those are kind of hacky solutions. I think the best thing would be terminator which is a more modern terminal with output logging. Just check your log file for the results of the last command. A bash variable similar to the above would make this even simpler.

Returning string from C function

Easier still: return a pointer to a string that's been malloc'd with strdup.

#include <ncurses.h>

char * getStr(int length)
{   
    char word[length];

    for (int i = 0; i < length; i++)
    {
        word[i] = getch();
    }

    word[i] = '\0';
    return strdup(&word[0]);
}

int main()
{
    char wordd[10];
    initscr();
    *wordd = getStr(10);
    printw("The string is:\n");
    printw("%s\n",*wordd);
    getch();
    endwin();
    return 0;
}

JavaScript: Global variables after Ajax requests

What you expect is the synchronous (blocking) type request.

var it_works = false;

jQuery.ajax({
  type: "POST",
  url: 'some_file.php',
  success: function (data) {
    it_works = true;
  }, 
  async: false // <- this turns it into synchronous
});?

// Execution is BLOCKED until request finishes.

// it_works is available
alert(it_works);

Requests are asynchronous (non-blocking) by default which means that the browser won't wait for them to be completed in order to continue its work. That's why your alert got wrong result.

Now, with jQuery.ajax you can optionally set the request to be synchronous, which means that the script will only continue to run after the request is finished.


The RECOMMENDED way, however, is to refactor your code so that the data would be passed to a callback function as soon as the request is finished. This is preferred because blocking execution means blocking the UI which is unacceptable. Do it this way:

$.post("some_file.php", '', function(data) {
    iDependOnMyParameter(data);
});

function iDependOnMyParameter(param) {
    // You should do your work here that depends on the result of the request!
    alert(param)
}

// All code here should be INDEPENDENT of the result of your AJAX request
// ...

Asynchronous programming is slightly more complicated because the consequence of making a request is encapsulated in a function instead of following the request statement. But the realtime behavior that the user experiences can be significantly better because they will not see a sluggish server or sluggish network cause the browser to act as though it had crashed. Synchronous programming is disrespectful and should not be employed in applications which are used by people.

Douglas Crockford (YUI Blog)

JS strings "+" vs concat method

  • We can't concatenate a string variable to an integer variable using concat() function because this function only applies to a string, not on a integer. but we can concatenate a string to a number(integer) using + operator.
  • As we know, functions are pretty slower than operators. functions needs to pass values to the predefined functions and need to gather the results of the functions. which is slower than doing operations using operators because operators performs operations in-line but, functions used to jump to appropriate memory locations... So, As mentioned in previous answers the other difference is obviously the speed of operation.

_x000D_
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
<body>_x000D_
_x000D_
<p>The concat() method joins two or more strings</p>_x000D_
_x000D_
_x000D_
<p id="demo"></p>_x000D_
<p id="demo1"></p>_x000D_
_x000D_
<script>_x000D_
var text1 = 4;_x000D_
var text2 = "World!";_x000D_
document.getElementById("demo").innerHTML = text1 + text2;_x000D_
//Below Line can't produce result_x000D_
document.getElementById("demo1").innerHTML = text1.concat(text2);_x000D_
</script>_x000D_
<p><strong>The Concat() method can't concatenate a string with a integer </strong></p>_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

Creating a UICollectionView programmatically

swift 4 code


//
//  ViewController.swift
//  coolectionView
//




import UIKit

class ViewController: UIViewController , UICollectionViewDataSource, UICollectionViewDelegate,UICollectionViewDelegateFlowLayout{
    @IBOutlet weak var collectionView: UICollectionView!

    var items = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "30", "31", "32", "33", "34", "35", "36", "37", "38", "39", "40", "41", "42", "43", "44", "45", "46", "47", "48"]

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return self.items.count
    }
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize
    {
        if indexPath.row % 3 != 0
        {
        return CGSize(width:collectionView.frame.width/2 - 7.5 , height: 100)
        }
        else
        {
            return CGSize(width:collectionView.frame.width - 10 , height: 100 )
        }
    }


    // make a cell for each cell index path
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

        // get a reference to our storyboard cell
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "CollectionViewCell1234", for: indexPath as IndexPath) as! CollectionViewCell1234

        // Use the outlet in our custom class to get a reference to the UILabel in the cell
        cell.lbl1.text = self.items[indexPath.item]
        cell.backgroundColor = UIColor.cyan // make cell more visible in our example project
        cell.layer.borderColor = UIColor.black.cgColor
        cell.layer.borderWidth = 1
        cell.layer.cornerRadius = 8

        return cell
    }
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        // handle tap events
        print("You selected cell #\(indexPath.item)!")
    }



}

Pandas How to filter a Series

A fast way of doing this is to reconstruct using numpy to slice the underlying arrays. See timings below.

mask = s.values != 1
pd.Series(s.values[mask], s.index[mask])

0
383    3.000000
737    9.000000
833    8.166667
dtype: float64

naive timing

enter image description here

Phone mask with jQuery and Masked Input Plugin

Here is a jQuery phone number mask. No plugin required. Format can be adjusted to your needs.

Updated JSFiddle.

HTML

<form id="example-form" name="my-form">
    <input id="phone-number" name="phone-number" type="text" placeholder="(XXX) XXX-XXXX">
</form>

JavaScript

$('#phone-number', '#example-form')

.keydown(function (e) {
    var key = e.which || e.charCode || e.keyCode || 0;
    $phone = $(this);

    // Don't let them remove the starting '('
    if ($phone.val().length === 1 && (key === 8 || key === 46)) {
        $phone.val('('); 
        return false;
    } 
    // Reset if they highlight and type over first char.
    else if ($phone.val().charAt(0) !== '(') {
        $phone.val('('+$phone.val()); 
    }

    // Auto-format- do not expose the mask as the user begins to type
    if (key !== 8 && key !== 9) {
        if ($phone.val().length === 4) {
            $phone.val($phone.val() + ')');
        }
        if ($phone.val().length === 5) {
            $phone.val($phone.val() + ' ');
        }           
        if ($phone.val().length === 9) {
            $phone.val($phone.val() + '-');
        }
    }

    // Allow numeric (and tab, backspace, delete) keys only
    return (key == 8 || 
            key == 9 ||
            key == 46 ||
            (key >= 48 && key <= 57) ||
            (key >= 96 && key <= 105)); 
})

.bind('focus click', function () {
    $phone = $(this);

    if ($phone.val().length === 0) {
        $phone.val('(');
    }
    else {
        var val = $phone.val();
        $phone.val('').val(val); // Ensure cursor remains at the end
    }
})

.blur(function () {
    $phone = $(this);

    if ($phone.val() === '(') {
        $phone.val('');
    }
});

How to style dt and dd so they are on the same line?

Assuming you know the width of the margin:

dt { float: left; width: 100px; }
dd { margin-left: 100px; }

How to render a DateTime in a specific format in ASP.NET MVC 3?

you can do like this @item.Date.Value.Tostring("dd-MMM-yy");

How can I display two div in one line via css inline property

You don't need to use display:inline to achieve this:

.inline { 
    border: 1px solid red;
    margin:10px;
    float:left;/*Add float left*/
    margin :10px;
}

You can use float-left.

Using float:left is best way to place multiple div elements in one line. Why? Because inline-block does have some problem when is viewed in IE older versions.

fiddle

How to round up a number to nearest 10?

There are many anwers in this question, probably all will give you the answer you are looking for. But as @TallGreenTree mentions, there is a function for this.

But the problem of the answer of @TallGreenTree is that it doesn't round up, it rounds to the nearest 10. To solve this, add +5 to your number in order to round up. If you want to round down, do -5.

So in code:

round($num + 5, -1);

You can't use the round mode for rounding up, because that only rounds up fractions and not whole numbers.

If you want to round up to the nearest 100, you shoud use +50.

Remove IE10's "clear field" X button on certain inputs?

I think it's worth noting that all the style and CSS based solutions don't work when a page is running in compatibility mode. The compatibility mode renderer ignores the ::-ms-clear element, even though the browser shows the x.

If your page needs to run in compatibility mode, you may be stuck with the X showing.

In my case, I am working with some third party data bound controls, and our solution was to handle the "onchange" event and clear the backing store if the field is cleared with the x button.

How to check model string property for null in a razor view

Try this first, you may be passing a Null Model:

@if (Model != null && !String.IsNullOrEmpty(Model.ImageName))
{
    <label for="Image">Change picture</label>
}
else
{ 
    <label for="Image">Add picture</label>
}

Otherise, you can make it even neater with some ternary fun! - but that will still error if your model is Null.

<label for="Image">@(String.IsNullOrEmpty(Model.ImageName) ? "Add" : "Change") picture</label>

vba pass a group of cells as range to function

As written, your function accepts only two ranges as arguments.

To allow for a variable number of ranges to be used in the function, you need to declare a ParamArray variant array in your argument list. Then, you can process each of the ranges in the array in turn.

For example,

Function myAdd(Arg1 As Range, ParamArray Args2() As Variant) As Double
    Dim elem As Variant
    Dim i As Long
    For Each elem In Arg1
        myAdd = myAdd + elem.Value
    Next elem
    For i = LBound(Args2) To UBound(Args2)
        For Each elem In Args2(i)
            myAdd = myAdd + elem.Value
        Next elem
    Next i
End Function

This function could then be used in the worksheet to add multiple ranges.

myAdd usage

For your function, there is the question of which of the ranges (or cells) that can passed to the function are 'Sessions' and which are 'Customers'.

The easiest case to deal with would be if you decided that the first range is Sessions and any subsequent ranges are Customers.

Function calculateIt(Sessions As Range, ParamArray Customers() As Variant) As Double
    'This function accepts a single Sessions range and one or more Customers
    'ranges
    Dim i As Long
    Dim sessElem As Variant
    Dim custElem As Variant
    For Each sessElem In Sessions
        'do something with sessElem.Value, the value of each
        'cell in the single range Sessions
        Debug.Print "sessElem: " & sessElem.Value
    Next sessElem
    'loop through each of the one or more ranges in Customers()
    For i = LBound(Customers) To UBound(Customers)
        'loop through the cells in the range Customers(i)
        For Each custElem In Customers(i)
            'do something with custElem.Value, the value of
            'each cell in the range Customers(i)
            Debug.Print "custElem: " & custElem.Value
         Next custElem
    Next i
End Function

If you want to include any number of Sessions ranges and any number of Customers range, then you will have to include an argument that will tell the function so that it can separate the Sessions ranges from the Customers range.

This argument could be set up as the first, numeric, argument to the function that would identify how many of the following arguments are Sessions ranges, with the remaining arguments implicitly being Customers ranges. The function's signature would then be:

Function calculateIt(numOfSessionRanges, ParamAray Args() As Variant)

Or it could be a "guard" argument that separates the Sessions ranges from the Customers ranges. Then, your code would have to test each argument to see if it was the guard. The function would look like:

Function calculateIt(ParamArray Args() As Variant)

Perhaps with a call something like:

calculateIt(sessRange1,sessRange2,...,"|",custRange1,custRange2,...)

The program logic might then be along the lines of:

Function calculateIt(ParamArray Args() As Variant) As Double
   ...
   'loop through Args
   IsSessionArg = True
   For i = lbound(Args) to UBound(Args)
       'only need to check for the type of the argument
       If TypeName(Args(i)) = "String" Then
          IsSessionArg = False
       ElseIf IsSessionArg Then
          'process Args(i) as Session range
       Else
          'process Args(i) as Customer range
       End if
   Next i
   calculateIt = <somevalue>
End Function

Git removing upstream from local repository

$ git remote remove <name>

ie.

$ git remote remove upstream

that should do the trick

How can I slice an ArrayList out of an ArrayList in Java?

This is how I solved it. I forgot that sublist was a direct reference to the elements in the original list, so it makes sense why it wouldn't work.

ArrayList<Integer> inputA = new ArrayList<Integer>(input.subList(0, input.size()/2));

What does "The code generator has deoptimised the styling of [some file] as it exceeds the max of "100KB"" mean?

Either one of the below three options gets rid of the message (but for different reasons and with different side-effects I suppose):

  1. exclude the node_modules directory or explicitly include the directory where your app resides (which presumably does not contain files in excess of 100KB)
  2. set the Babel option compact to true (actually any value other than "auto")
  3. set the Babel option compact to false (see above)

#1 in the above list can be achieved by either excluding the node_modules directory or be explicitly including the directory where your app resides.

E.g. in webpack.config.js:

let path = require('path');
....
module: {
     loaders: [
          ...
          loader: 'babel',
          exclude: path.resolve(__dirname, 'node_modules/')

... or by using include: path.resolve(__dirname, 'app/') (again in webpack.config.js).

#2 and #3 in the above list can be accomplished by the method suggested in this answer or (my preference) by editing the .babelrc file. E.g.:

$ cat .babelrc 
{
    "presets": ["es2015", "react"],
    "compact" : true
}

Tested with the following setup:

$ npm ls --depth 0 | grep babel
+-- [email protected]
+-- [email protected]
+-- [email protected]
+-- [email protected]

Parse XLSX with Node and create json

You can also use

var XLSX = require('xlsx');
var workbook = XLSX.readFile('Master.xlsx');
var sheet_name_list = workbook.SheetNames;
console.log(XLSX.utils.sheet_to_json(workbook.Sheets[sheet_name_list[0]]))

Running script upon login mac

  1. Create your shell script as login.sh in your $HOME folder.

  2. Paste the following one-line script into Script Editor:

    do shell script "$HOME/login.sh"

  3. Then save it as an application.

  4. Finally add the application to your login items.

If you want to make the script output visual, you can swap step 2 for this:

tell application "Terminal"
  activate
  do script "$HOME/login.sh"
end tell

If multiple commands are needed something like this can be used:

tell application "Terminal"
  activate
  do script "cd $HOME"
  do script "./login.sh" in window 1
end tell

How can I convert string date to NSDate?

If you're going to need to parse the string into a date often, you may want to move the functionality into an extension. I created a sharedCode.swift file and put my extensions there:

extension String
{   
    func toDateTime() -> NSDate
    {
        //Create Date Formatter
        let dateFormatter = NSDateFormatter()

        //Specify Format of String to Parse
        dateFormatter.dateFormat = "yyyy-MM-dd hh:mm:ss.SSSSxxx"

        //Parse into NSDate
        let dateFromString : NSDate = dateFormatter.dateFromString(self)!

        //Return Parsed Date
        return dateFromString
    }
}

Then if you want to convert your string into a NSDate you can just write something like:

var myDate = myDateString.toDateTime()

How to add a list item to an existing unordered list?

How about using "after" instead of "append".

$("#content ul li:last").after('<li><a href="/user/messages"><span class="tab">Message Center</span></a></li>');

".after()" can insert content, specified by the parameter, after each element in the set of matched elements.

What is /var/www/html?

In the most shared hosts you can't set it.

On a VPS or dedicated server, you can set it, but everything has its price.

On shared hosts, in general you receive a Linux account, something such as /home/(your username)/, and the equivalent of /var/www/html turns to /home/(your username)/public_html/ (or something similar, such as /home/(your username)/www)

If you're accessing your account via FTP, you automatically has accessing the your */home/(your username)/ folder, just find the www or public_html and put your site in it.

If you're using absolute path in the code, bad news, you need to refactor it to use relative paths in the code, at least in a shared host.

How do I format a String in an email so Outlook will print the line breaks?

I had been struggling with all of the above solutions and nothing helped here, because I used a String variable (plain text from a JTextPane) in combination with "text/html" formatting in my e-mail library.

So, the solution to this problem is to use "text/plain", instead of "text/html" and no need to replace return characters at all:

MimeBodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setContent(message, "text/plain");

JQUERY ajax passing value from MVC View to Controller

View Data
==============


 @model IEnumerable<DemoApp.Models.BankInfo>
<p>
    <b>Search Results</b>
</p>
@if (!Model.Any())
{
    <tr>
        <td colspan="4" style="text-align:center">
            No Bank(s) found
        </td>
    </tr>
}
else
{
    <table class="table">
        <tr>
            <th>
                @Html.DisplayNameFor(model => model.Name)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.Address)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.Postcode)
            </th>
            <th></th>
        </tr>

        @foreach (var item in Model)
        {
            <tr>
                <td>
                    @Html.DisplayFor(modelItem => item.Name)
                </td>
                <td>
                    @Html.DisplayFor(modelItem => item.Address)
                </td>
                <td>
                    @Html.DisplayFor(modelItem => item.Postcode)
                </td>
                <td>
                    <input type="button" class="btn btn-default bankdetails" value="Select" data-id="@item.Id" />
                </td>
            </tr>
        }
    </table>
}


<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script type="text/javascript">
    $(function () {
        $("#btnSearch").off("click.search").on("click.search", function () {
            if ($("#SearchBy").val() != '') {
                $.ajax({
                    url: '/home/searchByName',
                    data: { 'name': $("#SearchBy").val() },
                    dataType: 'html',
                    success: function (data) {
                        $('#dvBanks').html(data);
                    }
                });
            }
            else {
                alert('Please enter Bank Name');
            }
        });
}
});


public ActionResult SearchByName(string name)
        {
            var banks = GetBanksInfo();
            var filteredBanks = banks.Where(x => x.Name.ToLower().Contains(name.ToLower())).ToList();
            return PartialView("_banks", filteredBanks);
        }

        /// <summary>
        /// Get List of Banks Basically it should get from Database 
        /// </summary>
        /// <returns></returns>
        private List<BankInfo> GetBanksInfo()
        {
            return new List<BankInfo>
            {
                new BankInfo {Id = 1, Name = "Bank of America", Address = "1438 Potomoc Avenue, Pittsburge", Postcode = "PA 15220"  },
                new BankInfo {Id = 2, Name = "Bank of America", Address = "643 River Hwy, Mooresville", Postcode = "NC 28117"  },
                new BankInfo {Id = 3, Name = "Bank of Barroda", Address = "643 Hyderabad", Postcode = "500061"  },
                new BankInfo {Id = 4, Name = "State Bank of India", Address = "AsRao Nagar", Postcode = "500061"  },
                new BankInfo {Id = 5, Name = "ICICI", Address = "AsRao Nagar", Postcode = "500061"  }
            };
        }

Combining two expressions (Expression<Func<T, bool>>)

Nothing new here but married this answer with this answer and slightly refactored it so that even I understand what's going on:

public static class ExpressionExtensions
{
    public static Expression<Func<T, bool>> AndAlso<T>(this Expression<Func<T, bool>> expr1, Expression<Func<T, bool>> expr2)
    {
        ParameterExpression parameter1 = expr1.Parameters[0];
        var visitor = new ReplaceParameterVisitor(expr2.Parameters[0], parameter1);
        var body2WithParam1 = visitor.Visit(expr2.Body);
        return Expression.Lambda<Func<T, bool>>(Expression.AndAlso(expr1.Body, body2WithParam1), parameter1);
    }

    private class ReplaceParameterVisitor : ExpressionVisitor
    {
        private ParameterExpression _oldParameter;
        private ParameterExpression _newParameter;

        public ReplaceParameterVisitor(ParameterExpression oldParameter, ParameterExpression newParameter)
        {
            _oldParameter = oldParameter;
            _newParameter = newParameter;
        }

        protected override Expression VisitParameter(ParameterExpression node)
        {
            if (ReferenceEquals(node, _oldParameter))
                return _newParameter;

            return base.VisitParameter(node);
        }
    }
}

How can I let a user download multiple files when a button is clicked?

I fond that executing click() event on a element inside a for loop for multiple files download works only for limited number of files (10 files in my case). The only reason that would explain this behavior that made sense to me, was speed/intervals of downloads executed by click() events.

I figure out that, if I slow down execution of click() event, then I will be able to downloads all files.

This is solution that worked for me.

var urls = [
  'http://example.com/file1',
  'http://example.com/file2',
  'http://example.com/file3'
]

var interval = setInterval(download, 300, urls);

function download(urls) {
  var url = urls.pop();

  var a = document.createElement("a");
  a.setAttribute('href', url);
  a.setAttribute('download', '');
  a.setAttribute('target', '_blank');
  a.click();

  if (urls.length == 0) {
    clearInterval(interval);
  }
}

I execute download event click() every 300ms. When there is no more files to download urls.length == 0 then, I execute clearInterval on interval function to stop downloads.

SQL count rows in a table

Yes, SELECT COUNT(*) FROM TableName

How to use boolean 'and' in Python

You can also test them as a couple.

if (i,ii)==(5,10):
    print "i is 5 and ii is 10"

drop down list value in asp.net

You can add an empty value such as:

ddlmonths.Items.Insert(0, new ListItem("Select Month", ""))

And just add a validation to prevent chosing empty option such as asp:RequiredFieldValidator.

Create list of single item repeated N times

As others have pointed out, using the * operator for a mutable object duplicates references, so if you change one you change them all. If you want to create independent instances of a mutable object, your xrange syntax is the most Pythonic way to do this. If you are bothered by having a named variable that is never used, you can use the anonymous underscore variable.

[e for _ in xrange(n)]

Python idiom to return first item or None

You could use Extract Method. In other words extract that code into a method which you'd then call.

I wouldn't try to compress it much more, the one liners seem harder to read than the verbose version. And if you use Extract Method, it's a one liner ;)

Do I need to convert .CER to .CRT for Apache SSL certificates? If so, how?

If your cer file has binary format you must convert it by

openssl x509 -inform DER -in YOUR_CERTIFICATE.cer -out YOUR_CERTIFICATE.crt

How do I set a textbox's value using an anchor with jQuery?

Just to note that prefixing the tagName in a selector is slower than just using the id. In your case jQuery will get all the inputs rather than just using the getElementById. Just use $('#textbox')

Get list of all tables in Oracle?

A new feature available in SQLcl( which is a free command line interface for Oracle Database) is

Tables alias.

Here are few examples showing the usage and additional aspects of the feature. First, connect to a sql command line (sql.exe in windows) session. It is recommended to enter this sqlcl specific command before running any other commands or queries which display data.

SQL> set sqlformat ansiconsole     -- resizes the columns to the width of the 
                                   -- data to save space 

SQL> tables

TABLES
-----------
REGIONS
LOCATIONS
DEPARTMENTS
JOBS
EMPLOYEES
JOB_HISTORY
..

To know what the tables alias is referring to, you may simply use alias list <alias>

SQL> alias list tables
tables - tables <schema> - show tables from schema
--------------------------------------------------

 select table_name "TABLES" from user_tables

You don't have to define this alias as it comes by default under SQLcl. If you want to list tables from a specific schema, using a new user-defined alias and passing schema name as a bind argument with only a set of columns being displayed, you may do so using

SQL> alias tables_schema = select owner, table_name, last_analyzed from all_tables where owner = :ownr;

Thereafter you may simply pass schema name as an argument

SQL> tables_schema HR

OWNER   TABLE_NAME               LAST_ANALYZED
HR      DUMMY1                   18-10-18
HR      YOURTAB2                 16-11-18
HR      YOURTABLE                01-12-18
HR      ID_TABLE                 05-12-18
HR      REGIONS                  26-05-18
HR      LOCATIONS                26-05-18
HR      DEPARTMENTS              26-05-18
HR      JOBS                     26-05-18
HR      EMPLOYEES                12-10-18
..
..

A more sophisticated pre-defined alias is known as Tables2, which displays several other columns.

SQL> tables2

Tables
======
TABLE_NAME                 NUM_ROWS   BLOCKS   UNFORMATTED_SIZE COMPRESSION     INDEX_COUNT   CONSTRAINT_COUNT   PART_COUNT LAST_ANALYZED
AN_IP_TABLE                       0        0                  0 Disabled                  0                  0            0 > Month
PARTTABLE                         0        0                  0                           1                  0            1 > Month
TST2                              0        0                  0 Disabled                  0                  0            0 > Month
TST3                              0        0                  0 Disabled                  0                  0            0 > Month
MANAGE_EMPLYEE                    0        0                  0 Disabled                  0                  0            0 > Month
PRODUCT                           0        0                  0 Disabled                  0                  0            0 > Month
ALL_TAB_X78EHRYFK                 0        0                  0 Disabled                  0                  0            0 > Month
TBW                               0        0                  0 Disabled                  0                  0            0 > Month
DEPT                              0        0                  0 Disabled                  0                  0            0 > Month

To know what query it runs in the background, enter

alias list tables2

This will show you a slightly more complex query along with predefined column definitions commonly used in SQL*Plus.

Jeff Smith explains more about aliases here

Java URL encoding of query string parameters

I found an easy solution to your question. I also wanted to use an encoded URL but nothing helped me. enter image description here

http://example.com/query?q=random%20word%20%A3500%20bank%20%24

to use String example = "random word £500 bank $"; you can you below code.

String example = "random word £500 bank $";
String URL = "http://example.com/query?q=" + example.replaceAll(" ","%20");

Print a file, skipping the first X lines, in Bash

This shell script works fine for me:

#!/bin/bash
awk -v initial_line=$1 -v end_line=$2 '{
    if (NR >= initial_line && NR <= end_line) 
    print $0
}' $3

Used with this sample file (file.txt):

one
two
three
four
five
six

The command (it will extract from second to fourth line in the file):

edu@debian5:~$./script.sh 2 4 file.txt

Output of this command:

two
three
four

Of course, you can improve it, for example by testing that all argument values are the expected :-)

How to set height property for SPAN

Use

.title{
  display: inline-block;
  height: 25px;
}

The only trick is browser support. Check if your list of supported browsers handles inline-block here.

VB.net Need Text Box to Only Accept Numbers

On each entry in textbox (event - Handles RestrictedTextBox.TextChanged), you can do a try to caste entered text into integer, if failure occurs, you just reset the value of the text in RestrictedTextBox to last valid entry (which gets constantly updating under the temp1 variable).

Here's how to go about it. In the sub that loads with the form (me.load or mybase.load), initialize temp1 to the default value of RestrictedTextBox.Text

Dim temp1 As Integer 'initialize temp1 default value, you should do this after the default value for RestrictedTextBox.Text was loaded.
If (RestrictedTextBox.Text = Nothing) Then 
    temp1 = Nothing
Else
    Try 
        temp1 = CInt(RestrictedTextBox.Text)
    Catch ex As Exception
        temp1 = Nothing
    End Try
End If   

At any other point in form:

Private Sub textBox_TextChanged(sender As System.Object, e As System.EventArgs) Handles RestrictedTextBox.TextChanged
    Try
        temp1 = CInt(RestrictedTextBox.Text) 'If user inputs integer, this will succeed and temp will be updated
    Catch ex As Exception
        RestrictedTextBox.Text = temp1.ToString 'If user inputs non integer, textbox will be reverted to state the state it was in before the string entry
    End Try
End Sub

The nice thing about this is that you can use this to restrict a textbox to any type you want: double, uint etc....

JCheckbox - ActionListener and ItemListener?

Both ItemListener as well as ActionListener, in case of JCheckBox have the same behaviour. However, major difference is ItemListener can be triggered by calling the setSelected(true) on the checkbox. As a coding practice do not register both ItemListener as well as ActionListener with the JCheckBox, in order to avoid inconsistency.

Remove padding from columns in Bootstrap 3

If you download bootstrap with the SASS files you will be able to edit the config file where there are a setting for the margin of the columns and then save it, in that way the SASS calculates the new width of the columns

How do I rotate the Android emulator display?

Ctrl + F12 did not work for me, nor did Home, PageUp etc.

So here's what finally came up with:

  • Enable NUMLOCK;
  • Open your emulator and press the 7 followed by 9 on the NUMPAD on the right side of your keyboard;
  • Now your emulator will be rotated in the opposite direction;

Inner join of DataTables in C#

If you are allowed to use LINQ, take a look at the following example. It creates two DataTables with integer columns, fills them with some records, join them using LINQ query and outputs them to Console.

    DataTable dt1 = new DataTable();
    dt1.Columns.Add("CustID", typeof(int));
    dt1.Columns.Add("ColX", typeof(int));
    dt1.Columns.Add("ColY", typeof(int));

    DataTable dt2 = new DataTable();
    dt2.Columns.Add("CustID", typeof(int));
    dt2.Columns.Add("ColZ", typeof(int));

    for (int i = 1; i <= 5; i++)
    {
        DataRow row = dt1.NewRow();
        row["CustID"] = i;
        row["ColX"] = 10 + i;
        row["ColY"] = 20 + i;
        dt1.Rows.Add(row);

        row = dt2.NewRow();
        row["CustID"] = i;
        row["ColZ"] = 30 + i;
        dt2.Rows.Add(row);
    }

    var results = from table1 in dt1.AsEnumerable()
                 join table2 in dt2.AsEnumerable() on (int)table1["CustID"] equals (int)table2["CustID"]
                 select new
                 {
                     CustID = (int)table1["CustID"],
                     ColX = (int)table1["ColX"],
                     ColY = (int)table1["ColY"],
                     ColZ = (int)table2["ColZ"]
                 };
    foreach (var item in results)
    {
        Console.WriteLine(String.Format("ID = {0}, ColX = {1}, ColY = {2}, ColZ = {3}", item.CustID, item.ColX, item.ColY, item.ColZ));
    }
    Console.ReadLine();

// Output:
// ID = 1, ColX = 11, ColY = 21, ColZ = 31
// ID = 2, ColX = 12, ColY = 22, ColZ = 32
// ID = 3, ColX = 13, ColY = 23, ColZ = 33
// ID = 4, ColX = 14, ColY = 24, ColZ = 34
// ID = 5, ColX = 15, ColY = 25, ColZ = 35

Core dump file is not generated

The answers given here cover pretty well most scenarios for which core dump is not created. However, in my instance, none of these applied. I'm posting this answer as an addition to the other answers.

If your core file is not being created for whatever reason, I recommend looking at the /var/log/messages. There might be a hint in there to why the core file is not created. In my case there was a line stating the root cause:

Executable '/path/to/executable' doesn't belong to any package

To work around this issue edit /etc/abrt/abrt-action-save-package-data.conf and change ProcessUnpackaged from 'no' to 'yes'.

ProcessUnpackaged = yes

This setting specifies whether to create core for binaries not installed with package manager.

Select subset of columns in data.table R

To subset by column index (to avoid typing their names) you can do

dt[, .SD, .SDcols = -c(1:3, 5L)]

result seems ok

            V4          V6         V7         V8         V9       V10
 1: 0.51500037 0.919066234 0.49447244 0.19564261 0.51945102 0.7238604
 2: 0.36477648 0.828889808 0.04564637 0.20265215 0.32255945 0.4483778
 3: 0.10853112 0.601278633 0.58363636 0.47807015 0.58061000 0.2584015
 4: 0.57569100 0.228642846 0.25734995 0.79528506 0.52067802 0.6644448
 5: 0.07873759 0.840349039 0.77798153 0.48699653 0.98281006 0.4480908
 6: 0.31347303 0.670762371 0.04591664 0.03428055 0.35916057 0.1297684
 7: 0.45374290 0.957848949 0.99383496 0.43939774 0.33470618 0.9429592
 8: 0.99403107 0.009750809 0.78816609 0.34713435 0.57937680 0.9227709
 9: 0.62776909 0.400467655 0.49433474 0.81536420 0.01637135 0.4942351
10: 0.10318372 0.177712847 0.27678497 0.59554454 0.29532020 0.7117959

Using FolderBrowserDialog in WPF application

If I'm not mistaken you're looking for the FolderBrowserDialog (hence the naming):

var dialog = new System.Windows.Forms.FolderBrowserDialog();
System.Windows.Forms.DialogResult result = dialog.ShowDialog();

Also see this SO thread: Open directory dialog

How to use dashes in HTML-5 data-* attributes in ASP.NET MVC

In mvc 4 Could be rendered with Underscore(" _ ")

Razor:

@Html.ActionLink("Vote", "#", new { id = item.FileId, }, new { @class = "votes", data_fid = item.FileId, data_jid = item.JudgeID, })

Rendered Html

<a class="votes" data-fid="18587" data-jid="9" href="/Home/%23/18587">Vote</a>

How do I combine two dataframes?

I believe you can use the append method

bigdata = data1.append(data2, ignore_index=True)

to keep their indexes just dont use the ignore_index keyword ...

How should I use Outlook to send code snippets?

Here's what works for me, and is quickest and causes the least amount of pain / annoyance:

1) Paste you code snippet into sublime; make sure your syntax is looking good.

2) Right click and choose 'Copy as RTF'

3) Paste into your email

4) Done

Get query from java.sql.PreparedStatement

You can add log4jdbc to your project. This adds logging of sql commands as they execute + a lot of other information.

http://code.google.com/p/log4jdbc/wiki/FAQ

Why isn't textarea an input[type="textarea"]?

I realize this is an older post, but thought this might be helpful to anyone wondering the same question:

While the previous answers are no doubt valid, there is a more simple reason for the distinction between textarea and input.

As mentioned previously, HTML is used to describe and give as much semantic structure to web content as possible, including input forms. A textarea may be used for input, however a textarea can also be marked as read only via the readonly attribute. The existence of such an attribute would not make any sense for an input type, and thus the distinction.

How to change background Opacity when bootstrap modal is open

You can download a custom compiled bootstrap 3, just customize the @modal-backdrop-opacity from:

https://getbootstrap.com/docs/3.4/customize/

Customizing bootstrap 4 requires compiling from source, overriding $modal-backdrop-bg as described in:

https://getbootstrap.com/docs/4.4/getting-started/theming/

In the answers to Bootstrap 4 custom build generator / download there is a NodeJS workflow for compiling Bootstrap 4 from source, alone with some non-official Bootstrap 4 customizers.

How to remove all the null elements inside a generic list in one go?

Easy and without LINQ:

while (parameterList.Remove(null)) {};

Git error: src refspec master does not match any error: failed to push some refs

It doesn't recognize that you have a master branch, but I found a way to get around it. I found out that there's nothing special about a master branch, you can just create another branch and call it master branch and that's what I did.

To create a master branch:

git checkout -b master

And you can work off of that.

Eclipse shows errors but I can't find them

I came across the same issue while working on a selenium project(maven). The Project folder and pom.xml were showing red cross symbol. This was coming as i had the test datasheet open. I could remove the error by just closing the datasheet and the never faced the issue again

How do I get JSON data from RESTful service using Python?

Something like this should work unless I'm missing the point:

import json
import urllib2
json.load(urllib2.urlopen("url"))

Why Response.Redirect causes System.Threading.ThreadAbortException?

There is no simple and elegant solution to the Redirect problem in ASP.Net WebForms. You can choose between the Dirty solution and the Tedious solution

Dirty: Response.Redirect(url) sends a redirect to the browser, and then throws a ThreadAbortedException to terminate the current thread. So no code is executed past the Redirect()-call. Downsides: It is bad practice and have performance implications to kill threads like this. Also, ThreadAbortedExceptions will show up in exception logging.

Tedious: The recommended way is to call Response.Redirect(url, false) and then Context.ApplicationInstance.CompleteRequest() However, code execution will continue and the rest of the event handlers in the page lifecycle will still be executed. (E.g. if you perform the redirect in Page_Load, not only will the rest of the handler be executed, Page_PreRender and so on will also still be called - the rendered page will just not be sent to the browser. You can avoid the extra processing by e.g. setting a flag on the page, and then let subsequent event handlers check this flag before before doing any processing.

(The documentation to CompleteRequest states that it "Causes ASP.NET to bypass all events and filtering in the HTTP pipeline chain of execution". This can easily be misunderstood. It does bypass further HTTP filters and modules, but it doesn't bypass further events in the current page lifecycle.)

The deeper problem is that WebForms lacks a level of abstraction. When you are in a event handler, you are already in the process of building a page to output. Redirecting in an event handler is ugly because you are terminating a partially generated page in order to generate a different page. MVC does not have this problem since the control flow is separate from rendering views, so you can do a clean redirect by simply returning a RedirectAction in the controller, without generating a view.

Console.log(); How to & Debugging javascript

Learn to use a javascript debugger. Venkman (for Firefox) or the Web Inspector (part of Chome & Safari) are excellent tools for debugging what's going on.

You can set breakpoints and interrogate the state of the machine as you're interacting with your script; step through parts of your code to make sure everything is working as planned, etc.

Here is an excellent write up from WebMonkey on JavaScript Debugging for Beginners. It's a great place to start.

How to recover the deleted files using "rm -R" command in linux server?

Short answer: You can't. rm removes files blindly, with no concept of 'trash'.

Some Unix and Linux systems try to limit its destructive ability by aliasing it to rm -i by default, but not all do.

Long answer: Depending on your filesystem, disk activity, and how long ago the deletion occured, you may be able to recover some or all of what you deleted. If you're using an EXT3 or EXT4 formatted drive, you can check out extundelete.

In the future, use rm with caution. Either create a del alias that provides interactivity, or use a file manager.

How to verify static void method has been called with power mockito

Thou the above answer is widely accepted and well documented, I found some of the reason to post my answer here :-

    doNothing().when(InternalUtils.class); //This is the preferred way
                                           //to mock static void methods.
    InternalUtils.sendEmail(anyString(), anyString(), anyString(), anyString());

Here, I dont understand why we are calling InternalUtils.sendEmail ourself. I will explain in my code why we don't need to do that.

mockStatic(Internalutils.class);

So, we have mocked the class which is fine. Now, lets have a look how we need to verify the sendEmail(/..../) method.

@PrepareForTest({InternalService.InternalUtils.class})
@RunWith(PowerMockRunner.class)
public class InternalServiceTest {

    @Mock
    private InternalService.Order order;

    private InternalService internalService;

    @Before
    public void setup() {
        MockitoAnnotations.initMocks(this);
        internalService = new InternalService();
    }

    @Test
    public void processOrder() throws Exception {

        Mockito.when(order.isSuccessful()).thenReturn(true);
        PowerMockito.mockStatic(InternalService.InternalUtils.class);

        internalService.processOrder(order);

        PowerMockito.verifyStatic(times(1));
        InternalService.InternalUtils.sendEmail(anyString(), any(String[].class), anyString(), anyString());
    }

}

These two lines is where the magic is, First line tells the PowerMockito framework that it needs to verify the class it statically mocked. But which method it need to verify ?? Second line tells which method it needs to verify.

PowerMockito.verifyStatic(times(1));
InternalService.InternalUtils.sendEmail(anyString(), any(String[].class), anyString(), anyString());

This is code of my class, sendEmail api twice.

public class InternalService {

    public void processOrder(Order order) {
        if (order.isSuccessful()) {
            InternalUtils.sendEmail("", new String[1], "", "");
            InternalUtils.sendEmail("", new String[1], "", "");
        }
    }

    public static class InternalUtils{

        public static void sendEmail(String from, String[]  to, String msg, String body){

        }

    }

    public class Order{

        public boolean isSuccessful(){
            return true;
        }

    }

}

As it is calling twice you just need to change the verify(times(2))... that's all.

How to disassemble a binary executable in Linux to get the assembly code?

An interesting alternative to objdump is gdb. You don't have to run the binary or have debuginfo.

$ gdb -q ./a.out 
Reading symbols from ./a.out...(no debugging symbols found)...done.
(gdb) info functions 
All defined functions:

Non-debugging symbols:
0x00000000004003a8  _init
0x00000000004003e0  __libc_start_main@plt
0x00000000004003f0  __gmon_start__@plt
0x0000000000400400  _start
0x0000000000400430  deregister_tm_clones
0x0000000000400460  register_tm_clones
0x00000000004004a0  __do_global_dtors_aux
0x00000000004004c0  frame_dummy
0x00000000004004f0  fce
0x00000000004004fb  main
0x0000000000400510  __libc_csu_init
0x0000000000400580  __libc_csu_fini
0x0000000000400584  _fini
(gdb) disassemble main
Dump of assembler code for function main:
   0x00000000004004fb <+0>:     push   %rbp
   0x00000000004004fc <+1>:     mov    %rsp,%rbp
   0x00000000004004ff <+4>:     sub    $0x10,%rsp
   0x0000000000400503 <+8>:     callq  0x4004f0 <fce>
   0x0000000000400508 <+13>:    mov    %eax,-0x4(%rbp)
   0x000000000040050b <+16>:    mov    -0x4(%rbp),%eax
   0x000000000040050e <+19>:    leaveq 
   0x000000000040050f <+20>:    retq   
End of assembler dump.
(gdb) disassemble fce
Dump of assembler code for function fce:
   0x00000000004004f0 <+0>:     push   %rbp
   0x00000000004004f1 <+1>:     mov    %rsp,%rbp
   0x00000000004004f4 <+4>:     mov    $0x2a,%eax
   0x00000000004004f9 <+9>:     pop    %rbp
   0x00000000004004fa <+10>:    retq   
End of assembler dump.
(gdb)

With full debugging info it's even better.

(gdb) disassemble /m main
Dump of assembler code for function main:
9       {
   0x00000000004004fb <+0>:     push   %rbp
   0x00000000004004fc <+1>:     mov    %rsp,%rbp
   0x00000000004004ff <+4>:     sub    $0x10,%rsp

10        int x = fce ();
   0x0000000000400503 <+8>:     callq  0x4004f0 <fce>
   0x0000000000400508 <+13>:    mov    %eax,-0x4(%rbp)

11        return x;
   0x000000000040050b <+16>:    mov    -0x4(%rbp),%eax

12      }
   0x000000000040050e <+19>:    leaveq 
   0x000000000040050f <+20>:    retq   

End of assembler dump.
(gdb)

objdump has a similar option (-S)

Difference between socket and websocket?

WebSocket is just another application level protocol over TCP protocol, just like HTTP.

Some snippets < Spring in Action 4> quoted below, hope it can help you understand WebSocket better.

In its simplest form, a WebSocket is just a communication channel between two applications (not necessarily a browser is involved)...WebSocket communication can be used between any kinds of applications, but the most common use of WebSocket is to facilitate communication between a server application and a browser-based application.

SQL query to find third highest salary in company

WITH CTE AS ( SELECT Salary, RN = ROW_NUMBER() OVER (ORDER BY Salary DESC) FROM Employee ) SELECT salary FROM CTE WHERE RN = 3

How to group dataframe rows into list in pandas groupby

Let us using df.groupby with list and Series constructor

pd.Series({x : y.b.tolist() for x , y in df.groupby('a')})
Out[664]: 
A       [1, 2]
B    [5, 5, 4]
C          [6]
dtype: object

How would you implement an LRU cache in Java?

Here is my tested best performing concurrent LRU cache implementation without any synchronized block:

public class ConcurrentLRUCache<Key, Value> {

private final int maxSize;

private ConcurrentHashMap<Key, Value> map;
private ConcurrentLinkedQueue<Key> queue;

public ConcurrentLRUCache(final int maxSize) {
    this.maxSize = maxSize;
    map = new ConcurrentHashMap<Key, Value>(maxSize);
    queue = new ConcurrentLinkedQueue<Key>();
}

/**
 * @param key - may not be null!
 * @param value - may not be null!
 */
public void put(final Key key, final Value value) {
    if (map.containsKey(key)) {
        queue.remove(key); // remove the key from the FIFO queue
    }

    while (queue.size() >= maxSize) {
        Key oldestKey = queue.poll();
        if (null != oldestKey) {
            map.remove(oldestKey);
        }
    }
    queue.add(key);
    map.put(key, value);
}

/**
 * @param key - may not be null!
 * @return the value associated to the given key or null
 */
public Value get(final Key key) {
    return map.get(key);
}

}

how to remove "," from a string in javascript

If U want to delete more than one characters, say comma and dots you can write

<script type="text/javascript">
  var mystring = "It,is,a,test.string,of.mine" 
  mystring = mystring.replace(/[,.]/g , ''); 
  alert( mystring);
</script>

USB Debugging option greyed out

Unplug your phone from the your computer, then choose PC Software as PC Connection Type. Then go into Developer Options and select USB Debugging

Setting selection to Nothing when programming Excel

You can simply use this code at the end. (Do not use False)

Application.CutCopyMode = True

What are all the common ways to read a file in Ruby?

I usually do this:

open(path_in_string, &:read)

This will give you the whole text as a string object. It works only under Ruby 1.9.

Java split string to array

Try this

String[] array = values.split("\\|",-1); 

Convert Int to String in Swift

Swift 4:

let x:Int = 45
let str:String = String(describing: x)

Developer.Apple.com > String > init(describing:)

The String(describing:) initializer is the preferred way to convert an instance of any type to a string.

Custom String Convertible

enter image description here

How to set radio button checked as default in radiogroup?

There was same problem in my Colleague's code. This sounds as your Radio Group is not properly set with your Radio Buttons. This is the reason you can multi-select the radio buttons. I tried many things, finally i did a trick which is wrong actually, but works fine.

for ( int i = 0 ; i < myCount ; i++ )
{
    if ( i != k )
    {
        System.out.println ( "i = " + i );
        radio1[i].setChecked(false);
    }
}

Here I set one for loop, which checks for the available radio buttons and de-selects every one except the new clicked one. try it.

Unicode via CSS :before

The code points used in icon font tricks are usually Private Use code points, which means that they have no generally defined meaning and should not be used in open information interchange, only by private agreement between interested parties. However, Private Use code points can be represented as any other Unicode value, e.g. in CSS using a notation like \f066, as others have answered. You can even enter the code point as such, if your document is UTF-8 encoded and you know how to type an arbitrary Unicode value by its number in your authoring environment (but of course it would normally be displayed using a symbol for an unknown character).

However, this is not the normal way of using icon fonts. Normally you use a CSS file provided with the font and use constructs like <span class="icon-resize-small">foo</span>. The CSS code will then take care of inserting the symbol at the start of the element, and you don’t need to know the code point number.

Spring Boot @autowired does not work, classes in different package

Another fun way you can screw this up is annotating a setter method's parameter. It appears that for setter methods (unlike constructors), you have to annotate the method as a whole.

This does not work for me: public void setRepository(@Autowired WidgetRepository repo)

but this does: @Autowired public void setRepository(WidgetRepository repo)

(Spring Boot 2.3.2)

How to make a WPF window be on top of all other windows of my app (not system wide)?

This is what helped me:

Window selector = new Window ();
selector.Show();
selector.Activate();
selector.Topmost = true;

Pipenv: Command Not Found

I don't know what happened, but the following did the work (under mac os catalina)

$ brew install pipenv

$ brew update pipenv

after doing this i am able to use

$ pipenv install [package_name]

How to declare an array of objects in C#

With LINQ, you can transform the array of uninitialized elements into the new collection of created objects with one line of code.

var houses = new GameObject[200].Select(h => new GameObject()).ToArray();

Actually, you can use any other source for this, even generated sequence of integers:

var houses = Enumerable.Repeat(0, 200).Select(h => new GameObject()).ToArray();

However, the first case seems to me more readable, although the type of original sequence is not important.

PHP date yesterday

How easy :)

date("F j, Y", strtotime( '-1 days' ) );

Example:

echo date("Y-m-j H:i:s", strtotime( '-1 days' ) ); // 2018-07-18 07:02:43

Output:

2018-07-17 07:02:43

Namenode not getting started

I got the solution just share with you that will work who got the errors:

1. First check the /home/hadoop/etc/hadoop path, hdfs-site.xml and

 check the path of namenode and datanode 

<property>
  <name>dfs.name.dir</name>
    <value>file:///home/hadoop/hadoopdata/hdfs/namenode</value>
</property>

<property>
  <name>dfs.data.dir</name>
    <value>file:///home/hadoop/hadoopdata/hdfs/datanode</value>
</property>

2.Check the permission,group and user of namenode and datanode of the particular path(/home/hadoop/hadoopdata/hdfs/datanode), and check if there are any problems in all of them and if there are any mismatch then correct it. ex .chown -R hadoop:hadoop in_use.lock, change user and group

chmod -R 755 <file_name> for change the permission

How to remove td border with html?

To remove borders between cells, while retaining the border around the table, add the attribute rules=none to the table tag.

There is no way in HTML to achieve the rendering specified in the last figure of the question. There are various tricky workarounds that are based on using some other markup structure.

How do I install PHP cURL on Linux Debian?

I wrote an article on topis how to [manually install curl on debian linu][1]x.

[1]: http://www.jasom.net/how-to-install-curl-command-manually-on-debian-linux. This is its shortcut:

  1. cd /usr/local/src
  2. wget http://curl.haxx.se/download/curl-7.36.0.tar.gz
  3. tar -xvzf curl-7.36.0.tar.gz
  4. rm *.gz
  5. cd curl-7.6.0
  6. ./configure
  7. make
  8. make install

And restart Apache. If you will have an error during point 6, try to run apt-get install build-essential.

Is it good practice to use the xor operator for boolean checks?

I think it'd be okay if you commented it, e.g. // ^ == XOR.

How do I use boolean variables in Perl?

Beautiful explanation given by bobf for Boolean values : True or False? A Quick Reference Guide

Truth tests for different values

                       Result of the expression when $var is:

Expression          | 1      | '0.0'  | a string | 0     | empty str | undef
--------------------+--------+--------+----------+-------+-----------+-------
if( $var )          | true   | true   | true     | false | false     | false
if( defined $var )  | true   | true   | true     | true  | true      | false
if( $var eq '' )    | false  | false  | false    | false | true      | true
if( $var == 0 )     | false  | true   | true     | true  | true      | true

How can I do a line break (line continuation) in Python?

The danger in using a backslash to end a line is that if whitespace is added after the backslash (which, of course, is very hard to see), the backslash is no longer doing what you thought it was.

See Python Idioms and Anti-Idioms (for Python 2 or Python 3) for more.

Difference between String replace() and replaceAll()

Both replace() and replaceAll() replace all occurrences in the String.

Examples

I always find examples helpful to understand the differences.

replace()

Use replace() if you just want to replace some char with another char or some String with another String (actually CharSequence).

Example 1

Replace all occurrences of the character x with o.

String myString = "__x___x___x_x____xx_";

char oldChar = 'x';
char newChar = 'o';

String newString = myString.replace(oldChar, newChar);
// __o___o___o_o____oo_

Example 2

Replace all occurrences of the string fish with sheep.

String myString = "one fish, two fish, three fish";

String target = "fish";
String replacement = "sheep";

String newString = myString.replace(target, replacement);
// one sheep, two sheep, three sheep

replaceAll()

Use replaceAll() if you want to use a regular expression pattern.

Example 3

Replace any number with an x.

String myString = "__1_6____3__6_345____0";

String regex = "\\d";
String replacement = "x";

String newString = myString.replaceAll(regex, replacement); 
// __x_x____x__x_xxx____x

Example 4

Remove all whitespace.

String myString = "   Horse         Cow\n\n   \r Camel \t\t Sheep \n Goat        ";

String regex = "\\s";
String replacement = "";

String newString = myString.replaceAll(regex, replacement); 
// HorseCowCamelSheepGoat

See also

Documentation

Regular Expressions

An invalid form control with name='' is not focusable

I found same problem when using Angular JS. It was caused from using required together with ng-hide. When I clicked on the submit button while this element was hidden then it occurred the error An invalid form control with name='' is not focusable. finally!

For example of using ng-hide together with required:

<input type="text" ng-hide="for some condition" required something >

I solved it by replacing the required with ng-pattern instead.

For example of solution:

<input type="text" ng-hide="for some condition" ng-pattern="some thing" >

Python OpenCV2 (cv2) wrapper to get image size?

I'm afraid there is no "better" way to get this size, however it's not that much pain.

Of course your code should be safe for both binary/mono images as well as multi-channel ones, but the principal dimensions of the image always come first in the numpy array's shape. If you opt for readability, or don't want to bother typing this, you can wrap it up in a function, and give it a name you like, e.g. cv_size:

import numpy as np
import cv2

# ...

def cv_size(img):
    return tuple(img.shape[1::-1])

If you're on a terminal / ipython, you can also express it with a lambda:

>>> cv_size = lambda img: tuple(img.shape[1::-1])
>>> cv_size(img)
(640, 480)

Writing functions with def is not fun while working interactively.

Edit

Originally I thought that using [:2] was OK, but the numpy shape is (height, width[, depth]), and we need (width, height), as e.g. cv2.resize expects, so - we must use [1::-1]. Even less memorable than [:2]. And who remembers reverse slicing anyway?

How to merge two sorted arrays into a sorted array?

A minor improvement, but after the main loop, you could use System.arraycopy to copy the tail of either input array when you get to the end of the other. That won't change the O(n) performance characteristics of your solution, though.

Override standard close (X) button in a Windows Form

The accepted answer works quite well. An alternative method that I have used is to create a FormClosing method for the main Form. This is very similar to the override. My example is for an application that minimizes to the system tray when clicking the close button on the Form.

private void Form1_FormClosing(object sender, FormClosingEventArgs e)
    {
        if (e.CloseReason == CloseReason.ApplicationExitCall)
        {
            return;
        }
        else
        {
            e.Cancel = true;
            WindowState = FormWindowState.Minimized;
        }            
    }

This will allow ALT+F4 or anything in the Application calling Application.Exit(); to act as normal while clicking the (X) will minimize the Application.

How can I have a newline in a string in sh?

On my system (Ubuntu 17.10) your example just works as desired, both when typed from the command line (into sh) and when executed as a sh script:

[bash]§ sh
$ STR="Hello\nWorld"
$ echo $STR
Hello
World
$ exit
[bash]§ echo "STR=\"Hello\nWorld\"
> echo \$STR" > test-str.sh
[bash]§ cat test-str.sh 
STR="Hello\nWorld"
echo $STR
[bash]§ sh test-str.sh 
Hello
World

I guess this answers your question: it just works. (I have not tried to figure out details such as at what moment exactly the substitution of the newline character for \n happens in sh).

However, i noticed that this same script would behave differently when executed with bash and would print out Hello\nWorld instead:

[bash]§ bash test-str.sh
Hello\nWorld

I've managed to get the desired output with bash as follows:

[bash]§ STR="Hello
> World"
[bash]§ echo "$STR"

Note the double quotes around $STR. This behaves identically if saved and run as a bash script.

The following also gives the desired output:

[bash]§ echo "Hello
> World"

Installed Ruby 1.9.3 with RVM but command line doesn't show ruby -v

  • Open Terminal.
  • Go to Edit -> Profile Preferences.
  • Select the Title & command Tab in the window opened.
  • Mark the checkbox Run command as login shell.
  • close the window and restart the Terminal.

Check this Official Linkenter image description here

A non-blocking read on a subprocess.PIPE in Python

I have the original questioner's problem, but did not wish to invoke threads. I mixed Jesse's solution with a direct read() from the pipe, and my own buffer-handler for line reads (however, my sub-process - ping - always wrote full lines < a system page size). I avoid busy-waiting by only reading in a gobject-registered io watch. These days I usually run code within a gobject MainLoop to avoid threads.

def set_up_ping(ip, w):
    # run the sub-process
    # watch the resultant pipe
    p = subprocess.Popen(['/bin/ping', ip], stdout=subprocess.PIPE)
    # make stdout a non-blocking file
    fl = fcntl.fcntl(p.stdout, fcntl.F_GETFL)
    fcntl.fcntl(p.stdout, fcntl.F_SETFL, fl | os.O_NONBLOCK)
    stdout_gid = gobject.io_add_watch(p.stdout, gobject.IO_IN, w)
    return stdout_gid # for shutting down

The watcher is

def watch(f, *other):
    print 'reading',f.read()
    return True

And the main program sets up a ping and then calls gobject mail loop.

def main():
    set_up_ping('192.168.1.8', watch)
    # discard gid as unused here
    gobject.MainLoop().run()

Any other work is attached to callbacks in gobject.

Create a .csv file with values from a Python list

The best option I've found was using the savetxt from the numpy module:

import numpy as np
np.savetxt("file_name.csv", data1, delimiter=",", fmt='%s', header=header)

In case you have multiple lists that need to be stacked

np.savetxt("file_name.csv", np.column_stack((data1, data2)), delimiter=",", fmt='%s', header=header)

auto create database in Entity Framework Core

My answer is very similar to Ricardo's answer, but I feel that my approach is a little more straightforward simply because there is so much going on in his using function that I'm not even sure how exactly it works on a lower level.

So for those who want a simple and clean solution that creates a database for you where you know exactly what is happening under the hood, this is for you:

public Startup(IHostingEnvironment env)
{
    using (var client = new TargetsContext())
    {
        client.Database.EnsureCreated();
    }
}

This pretty much means that within the DbContext that you created (in this case, mine is called TargetsContext), you can use an instance of the DbContext to ensure that the tables defined with in the class are created when Startup.cs is run in your application.

Http Servlet request lose params from POST body after read it once

The only way would be for you to consume the entire input stream yourself in the filter, take what you want from it, and then create a new InputStream for the content you read, and put that InputStream in to a ServletRequestWrapper (or HttpServletRequestWrapper).

The downside is you'll have to parse the payload yourself, the standard doesn't make that capability available to you.

Addenda --

As I said, you need to look at HttpServletRequestWrapper.

In a filter, you continue along by calling FilterChain.doFilter(request, response).

For trivial filters, the request and response are the same as the ones passed in to the filter. That doesn't have to be the case. You can replace those with your own requests and/or responses.

HttpServletRequestWrapper is specifically designed to facilitate this. You pass it the original request, and then you can intercept all of the calls. You create your own subclass of this, and replace the getInputStream method with one of your own. You can't change the input stream of the original request, so instead you have this wrapper and return your own input stream.

The simplest case is to consume the original requests input stream in to a byte buffer, do whatever magic you want on it, then create a new ByteArrayInputStream from that buffer. This is what is returned in your wrapper, which is passed to the FilterChain.doFilter method.

You'll need to subclass ServletInputStream and make another wrapper for your ByteArrayInputStream, but that's not a big deal either.

Notepad++: Multiple words search in a file (may be in different lines)?

You need a new version of notepad++. Looks like old versions don't support |.

Note: egrep "CAT|TOWN" will search for lines containing CATOWN. (CAT)|(TOWN) is the proper or extension (matching 1,3,4). Strangely you wrote and which is btw (CAT.*TOWN)|(TOWN.*CAT)

Is it .yaml or .yml?

.yaml is apparently the official extension, because some applications fail when using .yml. On the other hand I am not familiar with any applications which use YAML code, but fail with a .yaml extension.

I just stumbled across this, as I was used to writing .yml in Ansible and Docker Compose. Out of habit I used .yml when writing Netplan files which failed silently. I finally figured out my mistake. The author of a popular Ansible Galaxy role for Netplan makes the same assumption in his code:

- name: Capturing Existing Configurations
  find:
    paths: /etc/netplan
    patterns: "*.yml,*.yaml"
  register: _netplan_configs

Yet any files with a .yml extension get ignored by Netplan in the same way as files with a .bak extension. As Netplan is very quiet, and gives no feedback whatsoever on success, even with netplan apply --debug, a config such as 01-netcfg.yml will fail silently without any meaningful feedback.

Oracle error : ORA-00905: Missing keyword

If you backup a table in Oracle Database. You try the statement below.

CREATE TABLE name_table_bk
AS
SELECT *
  FROM name_table;

I am using Oracle Database 12c.

Maximum request length exceeded.

If you have a request going to an application in the site, make sure you set maxRequestLength in the root web.config. The maxRequestLength in the applications's web.config appears to be ignored.

Apply function to each column in a data frame observing each columns existing data type

If you want to learn your data summary (df) provides the min, 1st quantile, median and mean, 3rd quantile and max of numerical columns and the frequency of the top levels of the factor columns.

Countdown timer in React

Countdown of user input

Interface Screenshot screenshot

import React, { Component } from 'react';
import './App.css';

class App extends Component {
  constructor() {
    super();
    this.state = {
      hours: 0,
      minutes: 0,
      seconds:0
    }
    this.hoursInput = React.createRef();
    this.minutesInput= React.createRef();
    this.secondsInput = React.createRef();
  }

  inputHandler = (e) => {
    this.setState({[e.target.name]: e.target.value});
  }

  convertToSeconds = ( hours, minutes,seconds) => {
    return seconds + minutes * 60 + hours * 60 * 60;
  }

  startTimer = () => {
    this.timer = setInterval(this.countDown, 1000);
  }

  countDown = () => {
    const  { hours, minutes, seconds } = this.state;
    let c_seconds = this.convertToSeconds(hours, minutes, seconds);

    if(c_seconds) {

      // seconds change
      seconds ? this.setState({seconds: seconds-1}) : this.setState({seconds: 59});

      // minutes change
      if(c_seconds % 60 === 0 && minutes) {
        this.setState({minutes: minutes -1});
      }

      // when only hours entered
      if(!minutes && hours) {
        this.setState({minutes: 59});
      }

      // hours change
      if(c_seconds % 3600 === 0 && hours) {
        this.setState({hours: hours-1});
      }

    } else {
      clearInterval(this.timer);
    }
  }


  stopTimer = () => {
    clearInterval(this.timer);
  }

  resetTimer = () => {
    this.setState({
      hours: 0,
      minutes: 0,
      seconds: 0
    });
    this.hoursInput.current.value = 0;
    this.minutesInput.current.value = 0;
    this.secondsInput.current.value = 0;
  }


  render() {
    const { hours, minutes, seconds } = this.state;

    return (
      <div className="App">
         <h1 className="title"> (( React Countdown )) </h1>
         <div className="inputGroup">
            <h3>Hrs</h3>
            <input ref={this.hoursInput} type="number" placeholder={0}  name="hours"  onChange={this.inputHandler} />
            <h3>Min</h3>
            <input  ref={this.minutesInput} type="number"  placeholder={0}   name="minutes"  onChange={this.inputHandler} />
            <h3>Sec</h3>
            <input   ref={this.secondsInput} type="number"  placeholder={0}  name="seconds"  onChange={this.inputHandler} />
         </div>
         <div>
            <button onClick={this.startTimer} className="start">start</button>
            <button onClick={this.stopTimer}  className="stop">stop</button>
            <button onClick={this.resetTimer}  className="reset">reset</button>
         </div>
         <h1> Timer {hours}: {minutes} : {seconds} </h1>
      </div>

    );
  }
}

export default App;

Use YAML with variables

This is an old post, but I had a similar need and this is the solution I came up with. It is a bit of a hack, but it works and could be refined.

require 'erb'
require 'yaml'

doc = <<-EOF
  theme:
  name: default
  css_path: compiled/themes/<%= data['theme']['name'] %>
  layout_path: themes/<%= data['theme']['name'] %>
  image_path: <%= data['theme']['css_path'] %>/images
  recursive_path: <%= data['theme']['image_path'] %>/plus/one/more
EOF

data = YAML::load("---" + doc)

template = ERB.new(data.to_yaml);
str = template.result(binding)
while /<%=.*%>/.match(str) != nil
  str = ERB.new(str).result(binding)
end

puts str

A big downside is that it builds into the yaml document a variable name (in this case, "data") that may or may not exist. Perhaps a better solution would be to use $ and then substitute it with the variable name in Ruby prior to ERB. Also, just tested using hashes2ostruct which allows data.theme.name type notation which is much easier on the eyes. All that is required is to wrap the YAML::load with this

data = hashes2ostruct(YAML::load("---" + doc))

Then your YAML document can look like this

doc = <<-EOF
  theme:
  name: default
  css_path: compiled/themes/<%= data.theme.name %>
  layout_path: themes/<%= data.theme.name %>
  image_path: <%= data.theme.css_path %>/images
  recursive_path: <%= data.theme.image_path %>/plus/one/more
EOF

How to declare and add items to an array in Python?

{} represents an empty dictionary, not an array/list. For lists or arrays, you need [].

To initialize an empty list do this:

my_list = []

or

my_list = list()

To add elements to the list, use append

my_list.append(12)

To extend the list to include the elements from another list use extend

my_list.extend([1,2,3,4])
my_list
--> [12,1,2,3,4]

To remove an element from a list use remove

my_list.remove(2)

Dictionaries represent a collection of key/value pairs also known as an associative array or a map.

To initialize an empty dictionary use {} or dict()

Dictionaries have keys and values

my_dict = {'key':'value', 'another_key' : 0}

To extend a dictionary with the contents of another dictionary you may use the update method

my_dict.update({'third_key' : 1})

To remove a value from a dictionary

del my_dict['key']

Keyboard shortcut to comment lines in Sublime Text 2

First Open The Sublime Text 2.

And top menu bar on select the Preferences.

And than select the Key Bindings -User.

And than put this code,

[
    { "keys": ["ctrl+shift+c"], "command": "toggle_comment", "args": { "block": false } },

    { "keys": ["ctrl+shift+c"], "command": "toggle_comment", "args": { "block": true } }
]

I use Ctrl+Shift+C, You also different short cut key use.

Check if AJAX response data is empty/blank/null/undefined/0

This worked form me.. PHP Code on page.php

 $query_de="sql statements here";
 $sql_de = sqlsrv_query($conn,$query_de);
      if ($sql_de)
      {
        echo "SQLSuccess";
       }
         exit();

and then AJAX Code has bellow

jQuery.ajax({
                    url  : "page.php",
                    type : "POST",
                    data : {
                            buttonsave   : 1,
                            var1         : val1,
                            var2         : val2,
                              },
                  success:function(data)
                           {
                     if(jQuery.trim(data) === "SQLSuccess")
                                   {
                           alert("Se agrego correctamente");
                          // alert(data);
                                      } else { alert(data);}
                              },
                   error: function(error)
                           {
                    alert("Error AJAX not working: "+ error );
                              } 
               }); 

NOTE: the word 'SQLSuccess' must be received from PHP

How to retrieve raw post data from HttpServletRequest in java

This worked for me: (notice that java 8 is required)

String requestData = request.getReader().lines().collect(Collectors.joining());
UserJsonParser u = gson.fromJson(requestData, UserJsonParser.class);

UserJsonParse is a class that shows gson how to parse the json formant.

class is like that:

public class UserJsonParser {

    private String username;
    private String name;
    private String lastname;
    private String mail;
    private String pass1;
//then put setters and getters
}

the json string that is parsed is like that:

$jsonData: {    "username": "testuser",    "pass1": "clave1234" }

The rest of values (mail, lastname, name) are set to null

Global Git ignore

on windows subsystem for linux I had to navigate to the subsystem root by cd ~/ then touch .gitignore and then update the global gitignore configuration in there.

I hope it helps someone.

How to execute a java .class from the command line

My situation was a little complicated. I had to do three steps since I was using a .dll in the resources directory, for JNI code. My files were

S:\Accessibility\tools\src\main\resources\dlls\HelloWorld.dll
S:\Accessibility\tools\src\test\java\com\accessibility\HelloWorld.class

My code contained the following line

System.load(HelloWorld.class.getResource("/dlls/HelloWorld.dll").getPath());

First, I had to move to the classpath directory

cd /D "S:\Accessibility\tools\src\test\java"

Next, I had to change the classpath to point to the current directory so that my class would be loaded and I had to change the classpath to point to he resources directory so my dll would be loaded.

set classpath=%classpath%;.;..\..\..\src\main\resources; 

Then, I had to run java using the classname.

java com.accessibility.HelloWorld 

How to get RegistrationID using GCM in android

In response to your first question: Yes, you have to run a server app to send the messages, as well as a client app to receive them.

In response to your second question: Yes, every application needs its own API key. This key is for your server app, not the client.

Codeigniter - no input file specified

I found the answer to this question here..... The problem was hosting server... I thank all who tried .... Hope this will help others

Godaddy Installation Tips

Displaying all table names in php from MySQL database

The brackets that are commonly used in the mysql documentation for examples should be ommitted in a 'real' query.

It also doesn't appear that you're echoing the result of the mysql query anywhere. mysql_query returns a mysql resource on success. The php manual page also includes instructions on how to load the mysql result resource into an array for echoing and other manipulation.

How to return a dictionary | Python


def query(id):
    for line in file:
        table = line.split(";")
        if id == int(table[0]):
             yield table
    
    

id = int(input("Enter the ID of the user: "))
for id_, name, city in query(id):
  print("ID: " + id_)
  print("Name: " + name)
  print("City: " + city)
file.close()

Using yield..

Properties file with a list as the value for an individual key

There's probably a another way or better. But this is how I do this in Spring Boot.

My property file contains the following lines. "," is the delimiter in each line.

mml.pots=STDEP:DETY=LI3;,STDEP:DETY=LIMA;
mml.isdn.grunntengingar=STDEP:DETY=LIBAE;,STDEP:DETY=LIBAMA;
mml.isdn.stofntengingar=STDEP:DETY=LIPRAE;,STDEP:DETY=LIPRAM;,STDEP:DETY=LIPRAGS;,STDEP:DETY=LIPRVGS;

My server config

@Configuration
public class ServerConfig {

    @Inject
    private Environment env;

    @Bean
    public MMLProperties mmlProperties() {
        MMLProperties properties = new MMLProperties();
        properties.setMmmlPots(env.getProperty("mml.pots"));
        properties.setMmmlPots(env.getProperty("mml.isdn.grunntengingar"));
        properties.setMmmlPots(env.getProperty("mml.isdn.stofntengingar"));
        return properties;
    }
}

MMLProperties class.

public class MMLProperties {
    private String mmlPots;
    private String mmlIsdnGrunntengingar;
    private String mmlIsdnStofntengingar;

    public MMLProperties() {
        super();
    }

    public void setMmmlPots(String mmlPots) {
        this.mmlPots = mmlPots;
    }

    public void setMmlIsdnGrunntengingar(String mmlIsdnGrunntengingar) {
        this.mmlIsdnGrunntengingar = mmlIsdnGrunntengingar;
    }

    public void setMmlIsdnStofntengingar(String mmlIsdnStofntengingar) {
        this.mmlIsdnStofntengingar = mmlIsdnStofntengingar;
    }

    // These three public getXXX functions then take care of spliting the properties into List
    public List<String> getMmmlCommandForPotsAsList() {
        return getPropertieAsList(mmlPots);
    }

    public List<String> getMmlCommandsForIsdnGrunntengingarAsList() {
        return getPropertieAsList(mmlIsdnGrunntengingar);
    }

    public List<String> getMmlCommandsForIsdnStofntengingarAsList() {
        return getPropertieAsList(mmlIsdnStofntengingar);
    }

    private List<String> getPropertieAsList(String propertie) {
        return ((propertie != null) || (propertie.length() > 0))
        ? Arrays.asList(propertie.split("\\s*,\\s*"))
        : Collections.emptyList();
    }
}

Then in my Runner class I Autowire MMLProperties

@Component
public class Runner implements CommandLineRunner {

    @Autowired
    MMLProperties mmlProperties;

    @Override
    public void run(String... arg0) throws Exception {
        // Now I can call my getXXX function to retrieve the properties as List
        for (String command : mmlProperties.getMmmlCommandForPotsAsList()) {
            System.out.println(command);
        }
    }
}

Hope this helps

How to check if IsNumeric

Other answers have suggested using TryParse, which might fit your needs, but the safest way to provide the functionality of the IsNumeric function is to reference the VB library and use the IsNumeric function.

IsNumeric is more flexible than TryParse. For example, IsNumeric returns true for the string "$100", while the TryParse methods all return false.

To use IsNumeric in C#, add a reference to Microsoft.VisualBasic.dll. The function is a static method of the Microsoft.VisualBasic.Information class, so assuming you have using Microsoft.VisualBasic;, you can do this:

if (Information.IsNumeric(txtMyText.Text.Trim())) //...

Difference between System.DateTime.Now and System.DateTime.Today

DateTime dt = new DateTime();// gives 01/01/0001 12:00:00 AM
DateTime dt = DateTime.Now;// gives today date with current time
DateTime dt = DateTime.Today;// gives today date and 12:00:00 AM time

How to compare two Dates without the time portion?

My proposition:

    Calendar cal = Calendar.getInstance();
    cal.set(1999,10,01);   // nov 1st, 1999
    cal.set(Calendar.AM_PM,Calendar.AM);
    cal.set(Calendar.HOUR,0);
    cal.set(Calendar.MINUTE,0);
    cal.set(Calendar.SECOND,0);
    cal.set(Calendar.MILLISECOND,0);

    // date column in the Thought table is of type sql date
    Thought thought = thoughtDao.getThought(date, language);

    Assert.assertEquals(cal.getTime(), thought.getDate());

MySQL error - #1062 - Duplicate entry ' ' for key 2

you can try adding

$db['db_debug'] = FALSE; 

in "your database file".php after that you can modify your database as you like.

How to make a transparent border using CSS?

use rgba (rgb with alpha transparency):

border: 10px solid rgba(0,0,0,0.5); // 0.5 means 50% of opacity

The alpha transparency variate between 0 (0% opacity = 100% transparent) and 1 (100 opacity = 0% transparent)

Update Multiple Rows in Entity Framework from a list of ids

var idList=new int[]{1, 2, 3, 4};
var friendsToUpdate = await Context.Friends.Where(f => 
    idList.Contains(f.Id).ToListAsync();

foreach(var item in previousEReceipts)
{
  item.msgSentBy = "1234";
}

You can use foreach to update each element that meets your condition.

Here is an example in a more generic way:

var itemsToUpdate = await Context.friends.Where(f => f.Id == <someCondition>).ToListAsync();

foreach(var item in itemsToUpdate)
{
   item.property = updatedValue;
}
Context.SaveChanges()

In general you will most probably use async methods with await for db queries.

How to parse a JSON and turn its values into an Array?

for your example:

{'profiles': [{'name':'john', 'age': 44}, {'name':'Alex','age':11}]}

you will have to do something of this effect:

JSONObject myjson = new JSONObject(the_json);
JSONArray the_json_array = myjson.getJSONArray("profiles");

this returns the array object.

Then iterating will be as follows:

    int size = the_json_array.length();
    ArrayList<JSONObject> arrays = new ArrayList<JSONObject>();
    for (int i = 0; i < size; i++) {
        JSONObject another_json_object = the_json_array.getJSONObject(i);
            //Blah blah blah...
            arrays.add(another_json_object);
    }

//Finally
JSONObject[] jsons = new JSONObject[arrays.size()];
arrays.toArray(jsons);

//The end...

You will have to determine if the data is an array (simply checking that charAt(0) starts with [ character).

Hope this helps.

DropdownList DataSource

You can bind the DropDownList in different ways by using List, Dictionary, Enum, DataSet DataTable.
Main you have to consider three thing while binding the datasource of a dropdown.

  1. DataSource - Name of the dataset or datatable or your datasource
  2. DataValueField - These field will be hidden
  3. DataTextField - These field will be displayed on the dropdwon.

you can use following code to bind a dropdownlist to a datasource as a datatable:

  SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnString"].ConnectionString);

    SqlCommand cmd = new SqlCommand("Select * from tblQuiz", con);

    SqlDataAdapter da = new SqlDataAdapter(cmd);

    DataTable dt=new DataTable();
    da.Fill(dt);

    DropDownList1.DataTextField = "QUIZ_Name";
    DropDownList1.DataValueField = "QUIZ_ID"

    DropDownList1.DataSource = dt;
    DropDownList1.DataBind();

if you want to process on selection of dropdownlist, then you have to change AutoPostBack="true" you can use SelectedIndexChanged event to write your code.

protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
    string strQUIZ_ID=DropDownList1.SelectedValue;
    string strQUIZ_Name=DropDownList1.SelectedItem.Text;
    // Your code..............
}

How can I convert bigint (UNIX timestamp) to datetime in SQL Server?

If anyone getting below error:

Arithmetic overflow error converting expression to data type int

due to unix timestamp is in bigint (instead of int), you can use this:

SELECT DATEADD(S, CONVERT(int,LEFT(1462924862735870900, 10)), '1970-01-01')
FROM TABLE

Replace the hardcoded timestamp for your actual column with unix-timestamp

Source: MSSQL bigint Unix Timestamp to Datetime with milliseconds

What is the syntax for Typescript arrow functions with generics?

The full example explaining the syntax referenced by Robin... brought it home for me:

Generic functions

Something like the following works fine:

function foo<T>(x: T): T { return x; }

However using an arrow generic function will not:

const foo = <T>(x: T) => x; // ERROR : unclosed `T` tag

Workaround: Use extends on the generic parameter to hint the compiler that it's a generic, e.g.:

const foo = <T extends unknown>(x: T) => x;

Best practice to call ConfigureAwait for all server-side code

I have some general thoughts about the implementation of Task:

  1. Task is disposable yet we are not supposed to use using.
  2. ConfigureAwait was introduced in 4.5. Task was introduced in 4.0.
  3. .NET Threads always used to flow the context (see C# via CLR book) but in the default implementation of Task.ContinueWith they do not b/c it was realised context switch is expensive and it is turned off by default.
  4. The problem is a library developer should not care whether its clients need context flow or not hence it should not decide whether flow the context or not.
  5. [Added later] The fact that there is no authoritative answer and proper reference and we keep fighting on this means someone has not done their job right.

I have got a few posts on the subject but my take - in addition to Tugberk's nice answer - is that you should turn all APIs asynchronous and ideally flow the context . Since you are doing async, you can simply use continuations instead of waiting so no deadlock will be cause since no wait is done in the library and you keep the flowing so the context is preserved (such as HttpContext).

Problem is when a library exposes a synchronous API but uses another asynchronous API - hence you need to use Wait()/Result in your code.

What are my options for storing data when using React Native? (iOS and Android)

Quick and dirty: just use Redux + react-redux + redux-persist + AsyncStorage for react-native.

It fits almost perfectly the react native world and works like a charm for both android and ios. Also, there is a solid community around it, and plenty of information.

For a working example, see the F8App from Facebook.

What are the different options for data persistence?

With react native, you probably want to use redux and redux-persist. It can use multiple storage engines. AsyncStorage and redux-persist-filesystem-storage are the options for RN.

There are other options like Firebase or Realm, but I never used those on a RN project.

For each, what are the limits of that persistence (i.e., when is the data no longer available)? For example: when closing the application, restarting the phone, etc.

Using redux + redux-persist you can define what is persisted and what is not. When not persisted, data exists while the app is running. When persisted, the data persists between app executions (close, open, restart phone, etc).

AsyncStorage has a default limit of 6MB on Android. It is possible to configure a larger limit (on Java code) or use redux-persist-filesystem-storage as storage engine for Android.

For each, are there differences (other than general setup) between implementing in iOS vs Android?

Using redux + redux-persist + AsyncStorage the setup is exactly the same on android and iOS.

How do the options compare for accessing data offline? (or how is offline access typically handled?)

Using redux, offiline access is almost automatic thanks to its design parts (action creators and reducers).

All data you fetched and stored are available, you can easily store extra data to indicate the state (fetching, success, error) and the time it was fetched. Normally, requesting a fetch does not invalidate older data and your components just update when new data is received.

The same apply in the other direction. You can store data you are sending to server and that are still pending and handle it accordingly.

Are there any other considerations I should keep in mind?

React promotes a reactive way of creating apps and Redux fits very well on it. You should try it before just using an option you would use in your regular Android or iOS app. Also, you will find much more docs and help for those.

How to disable clicking inside div

The CSS property that can be used is:

pointer-events:none

!IMPORTANT Keep in mind that this property is not supported by Opera Mini and IE 10 and below (inclusive). Another solution is needed for these browsers.

jQuery METHOD If you want to disable it via script and not CSS property, these can help you out: If you're using jQuery versions 1.4.3+:

$('selector').click(false);

If not:

$('selector').click(function(){return false;});

You can re-enable clicks with pointer-events: auto; (Documentation)

Note that pointer-events overrides the cursor property, so if you want the cursor to be something other than the standard cursor, your css should be place after pointer-events.

How can I export the schema of a database in PostgreSQL?

pg_dump -s databasename -t tablename -U user -h host -p port > tablename.sql

this will limit the schema dump to the table "tablename" of "databasename"