Programs & Examples On #Loops

Loops are a type of control flow structure in programming in which a series of statements may be executed repeatedly until some condition is met.

loop through json array jquery

I dont think youre returning json object from server. just a string.

you need the dataType of the return object to be json

Endless loop in C/C++

The problem with asking this question is that you'll get so many subjective answers that simply state "I prefer this...". Instead of making such pointless statements, I'll try to answer this question with facts and references, rather than personal opinions.

Through experience, we can probably start by excluding the do-while alternatives (and the goto), as they are not commonly used. I can't recall ever seeing them in live production code, written by professionals.

The while(1), while(true) and for(;;) are the 3 different versions commonly existing in real code. They are of course completely equivalent and results in the same machine code.


for(;;)

  • This is the original, canonical example of an eternal loop. In the ancient C bible The C Programming Language by Kernighan and Ritchie, we can read that:

    K&R 2nd ed 3.5:

    for (;;) {
    ...
    }
    

    is an "infinite" loop, presumably to be broken by other means, such as a break or return. Whether to use while or for is largely a matter of personal preference.

    For a long while (but not forever), this book was regarded as canon and the very definition of the C language. Since K&R decided to show an example of for(;;), this would have been regarded as the most correct form at least up until the C standardization in 1990.

    However, K&R themselves already stated that it was a matter of preference.

    And today, K&R is a very questionable source to use as a canonical C reference. Not only is it outdated several times over (not addressing C99 nor C11), it also preaches programming practices that are often regarded as bad or blatantly dangerous in modern C programming.

    But despite K&R being a questionable source, this historical aspect seems to be the strongest argument in favour of the for(;;).

  • The argument against the for(;;) loop is that it is somewhat obscure and unreadable. To understand what the code does, you must know the following rule from the standard:

    ISO 9899:2011 6.8.5.3:

    for ( clause-1 ; expression-2 ; expression-3 ) statement
    

    /--/

    Both clause-1 and expression-3 can be omitted. An omitted expression-2 is replaced by a nonzero constant.

    Based on this text from the standard, I think most will agree that it is not only obscure, it is subtle as well, since the 1st and 3rd part of the for loop are treated differently than the 2nd, when omitted.


while(1)

  • This is supposedly a more readable form than for(;;). However, it relies on another obscure, although well-known rule, namely that C treats all non-zero expressions as boolean logical true. Every C programmer is aware of that, so it is not likely a big issue.

  • There is one big, practical problem with this form, namely that compilers tend to give a warning for it: "condition is always true" or similar. That is a good warning, of a kind which you really don't want to disable, because it is useful for finding various bugs. For example a bug such as while(i = 1), when the programmer intended to write while(i == 1).

    Also, external static code analysers are likely to whine about "condition is always true".


while(true)

  • To make while(1) even more readable, some use while(true) instead. The consensus among programmers seem to be that this is the most readable form.

  • However, this form has the same problem as while(1), as described above: "condition is always true" warnings.

  • When it comes to C, this form has another disadvantage, namely that it uses the macro true from stdbool.h. So in order to make this compile, we need to include a header file, which may or may not be inconvenient. In C++ this isn't an issue, since bool exists as a primitive data type and true is a language keyword.

  • Yet another disadvantage of this form is that it uses the C99 bool type, which is only available on modern compilers and not backwards compatible. Again, this is only an issue in C and not in C++.


So which form to use? Neither seems perfect. It is, as K&R already said back in the dark ages, a matter of personal preference.

Personally, I always use for(;;) just to avoid the compiler/analyser warnings frequently generated by the other forms. But perhaps more importantly because of this:

If even a C beginner knows that for(;;) means an eternal loop, then who are you trying to make the code more readable for?

I guess that's what it all really boils down to. If you find yourself trying to make your source code readable for non-programmers, who don't even know the fundamental parts of the programming language, then you are only wasting time. They should not be reading your code.

And since everyone who should be reading your code already knows what for(;;) means, there is no point in making it further readable - it is already as readable as it gets.

How to write a simple Java program that finds the greatest common divisor between two numbers?

Now, I just started programing about a week ago, so nothing fancy, but I had this as a problem and came up with this, which may be easier for people who are just getting into programing to understand. It uses Euclid's method like in previous examples.

public class GCD {
  public static void main(String[] args){
    int x = Math.max(Integer.parseInt(args[0]),Integer.parseInt(args[1]));    
    int y = Math.min(Integer.parseInt(args[0]),Integer.parseInt(args[1]));     
    for (int r = x % y; r != 0; r = x % y){
      x = y;
      y = r;
    }
    System.out.println(y);
  }
}

PHP array printing using a loop

while(@$i++<count($a))
echo $a[$i-1];

3v4l.org

Numpy how to iterate over columns of array?

for c in np.hsplit(array, array.shape[1]):
    some_fun(c)

Should try...catch go inside or outside a loop?

If you want to catch Exception for each iteration, or check at what iteration Exception is thrown and catch every Exceptions in an itertaion, place try...catch inside the loop. This will not break the loop if Exception occurs and you can catch every Exception in each iteration throughout the loop.

If you want to break the loop and examine the Exception whenever thrown, use try...catch out of the loop. This will break the loop and execute statements after catch (if any).

It all depends on your need. I prefer using try...catch inside the loop while deploying as, if Exception occurs, the results aren't ambiguous and loop will not break and execute completely.

What's the best way to loop through a set of elements in JavaScript?

I prefer the for loop as it's more readable. Looping from length to 0 would be more efficient than looping from 0 to length. And using a reversed while loop is more efficient than a foor loop as you said. I don't have the link to the page with comparison results anymore but I remember that the difference varied on different browsers. For some browser the reversed while loop was twice as fast. However it makes no difference if you're looping "small" arrays. In your example case the length of elements will be "small"

How to loop through a dataset in powershell?

Here's a practical example (build a dataset from your current location):

$ds = new-object System.Data.DataSet
$ds.Tables.Add("tblTest")
[void]$ds.Tables["tblTest"].Columns.Add("Name",[string])
[void]$ds.Tables["tblTest"].Columns.Add("Path",[string])

dir | foreach {
    $dr = $ds.Tables["tblTest"].NewRow()
    $dr["Name"] = $_.name
    $dr["Path"] = $_.fullname
    $ds.Tables["tblTest"].Rows.Add($dr)
}


$ds.Tables["tblTest"]

$ds.Tables["tblTest"] is an object that you can manipulate just like any other Powershell object:

$ds.Tables["tblTest"] | foreach {
    write-host 'Name value is : $_.name
    write-host 'Path value is : $_.path
}

How to find the most recent file in a directory using .NET, and without looping?

I do this is a bunch of my apps and I use a statement like this:

  var inputDirectory = new DirectoryInfo("\\Directory_Path_here");
  var myFile = inputDirectory.GetFiles().OrderByDescending(f => f.LastWriteTime).First();

From here you will have the filename for the most recently saved/added/updated file in the Directory of the "inputDirectory" variable. Now you can access it and do what you want with it.

Hope that helps.

Indexes of all occurrences of character in a string

This can be done by iterating myString and shifting fromIndex parameter in indexOf():

  int currentIndex = 0;

  while (
    myString.indexOf(
      mySubstring,
      currentIndex) >= 0) {

    System.out.println(currentIndex);

    currentIndex++;
  }

How to find the foreach index?

PHP arrays have internal pointers, so try this:

foreach($array as $key => $value){
   $index = current($array);
}

Works okay for me (only very preliminarily tested though).

Check if key exists and iterate the JSON array using Python

If all you want is to check if key exists or not

h = {'a': 1}
'b' in h # returns False

If you want to check if there is a value for key

h.get('b') # returns None

Return a default value if actual value is missing

h.get('b', 'Default value')

Is there a "do ... until" in Python?

There is no do-while loop in Python.

This is a similar construct, taken from the link above.

 while True:
     do_something()
     if condition():
        break

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.

How to start and stop/pause setInterval?

(function(){
    var i = 0;
    function stop(){
        clearTimeout(i);
    }

    function start(){
        i = setTimeout( timed, 1000 );
    }

    function timed(){
       document.getElementById("input").value++;
       start();
    }

    window.stop = stop;
    window.start = start;
})()

http://jsfiddle.net/TE3Z2/

How do I break out of nested loops in Java?

Demo for break, continue, and label:

Java keywords break and continue have a default value. It's the "nearest loop", and today, after a few years of using Java, I just got it!

It's seem used rare, but useful.

import org.junit.Test;

/**
 * Created by cui on 17-5-4.
 */

public class BranchLabel {
    @Test
    public void test() {
        System.out.println("testBreak");
        testBreak();

        System.out.println("testBreakLabel");
        testBreakLabel();

        System.out.println("testContinue");
        testContinue();
        System.out.println("testContinueLabel");
        testContinueLabel();
    }

    /**
     testBreak
     a=0,b=0
     a=0,b=1
     a=1,b=0
     a=1,b=1
     a=2,b=0
     a=2,b=1
     a=3,b=0
     a=3,b=1
     a=4,b=0
     a=4,b=1
     */
    public void testBreak() {
        for (int a = 0; a < 5; a++) {
            for (int b = 0; b < 5; b++) {
                if (b == 2) {
                    break;
                }
                System.out.println("a=" + a + ",b=" + b);
            }
        }
    }

    /**
     testContinue
     a=0,b=0
     a=0,b=1
     a=0,b=3
     a=0,b=4
     a=1,b=0
     a=1,b=1
     a=1,b=3
     a=1,b=4
     a=2,b=0
     a=2,b=1
     a=2,b=3
     a=2,b=4
     a=3,b=0
     a=3,b=1
     a=3,b=3
     a=3,b=4
     a=4,b=0
     a=4,b=1
     a=4,b=3
     a=4,b=4
     */
    public void testContinue() {
        for (int a = 0; a < 5; a++) {
            for (int b = 0; b < 5; b++) {
                if (b == 2) {
                    continue;
                }
                System.out.println("a=" + a + ",b=" + b);
            }
        }
    }

    /**
     testBreakLabel
     a=0,b=0,c=0
     a=0,b=0,c=1
     * */
    public void testBreakLabel() {
        anyName:
        for (int a = 0; a < 5; a++) {
            for (int b = 0; b < 5; b++) {
                for (int c = 0; c < 5; c++) {
                    if (c == 2) {
                        break anyName;
                    }
                    System.out.println("a=" + a + ",b=" + b + ",c=" + c);
                }
            }
        }
    }

    /**
     testContinueLabel
     a=0,b=0,c=0
     a=0,b=0,c=1
     a=1,b=0,c=0
     a=1,b=0,c=1
     a=2,b=0,c=0
     a=2,b=0,c=1
     a=3,b=0,c=0
     a=3,b=0,c=1
     a=4,b=0,c=0
     a=4,b=0,c=1
     */
    public void testContinueLabel() {
        anyName:
        for (int a = 0; a < 5; a++) {
            for (int b = 0; b < 5; b++) {
                for (int c = 0; c < 5; c++) {
                    if (c == 2) {
                        continue anyName;
                    }
                    System.out.println("a=" + a + ",b=" + b + ",c=" + c);
                }
            }
        }
    }
}

What's the fastest way to loop through an array in JavaScript?

If you want a faster for loop, define your variables outside the loop and use below syntax

  const iMax = lengthOftheLoop;
  var i = 0;
  for (; i < iMax; i++) {
    console.log("loop"+i);
  }

reference: https://medium.com/kbdev/voyage-to-the-most-efficient-loop-in-nodejs-and-a-bit-js-5961d4524c2e

How do I iterate over a JSON structure?

Another solution to navigate through JSON documents is JSONiq (implemented in the Zorba engine), where you can write something like:

jsoniq version "1.0";

let $doc := [
  {"id":"10", "class": "child-of-9"},
  {"id":"11", "class": "child-of-10"}
]
for $entry in members($doc)             (: binds $entry to each object in turn :)
return $entry.class                     (: gets the value associated with "class" :)

You can run it on http://try.zorba.io/

Do while loop in SQL Server 2008

Only While Loop is officially supported by SQL server. Already there is answer for DO while loop. I am detailing answer on ways to achieve different types of loops in SQL server.

If you know, you need to complete first iteration of loop anyway, then you can try DO..WHILE or REPEAT..UNTIL version of SQL server.

DO..WHILE Loop

DECLARE @X INT=1;

WAY:  --> Here the  DO statement

  PRINT @X;

  SET @X += 1;

IF @X<=10 GOTO WAY;

REPEAT..UNTIL Loop

DECLARE @X INT = 1;

WAY:  -- Here the REPEAT statement

  PRINT @X;

  SET @X += 1;

IFNOT(@X > 10) GOTO WAY;

FOR Loop

DECLARE @cnt INT = 0;

WHILE @cnt < 10
BEGIN
   PRINT 'Inside FOR LOOP';
   SET @cnt = @cnt + 1;
END;

PRINT 'Done FOR LOOP';

Reference

How do I loop through a date range?

you have to be careful here not to miss the dates when in the loop a better solution would be.

this gives you the first date of startdate and use it in the loop before incrementing it and it will process all the dates including the last date of enddate hence <= enddate.

so the above answer is the correct one.

while (startdate <= enddate)
{
    // do something with the startdate
    startdate = startdate.adddays(interval);
}

Iterating through a JSON object

After deserializing the JSON, you have a python object. Use the regular object methods.

In this case you have a list made of dictionaries:

json_object[0].items()

json_object[0]["title"]

etc.

How to loop through an associative array and get the key?

While arguably being less clear this method is faster by roughly a factor of roughly 3.5 (At least on the box I used to test)

$foo = array(
    1 => "Value1",
    2 => "Value2",
    10 => "Value10"
);
while($bar = each($foo)){
    echo $bar[0] . " => " . $bar[1];
}

I would imagine that this is due to the fact the foreach copies the entire array before iterating over it.

Iterating Over Dictionary Key Values Corresponding to List in Python

List comprehension can shorten things...

win_percentages = [m**2.0 / (m**2.0 + n**2.0) * 100 for m, n in [a[i] for i in NL_East]]

powerpoint loop a series of animation

Unfortunately you're probably done with the animation and presentation already. In the hopes this answer can help future questioners, however, this blog post has a walkthrough of steps that can loop a single slide as a sort of sub-presentation.

First, click Slide Show > Set Up Show.

Put a checkmark to Loop continuously until 'Esc'.

Click Ok. Now, Click Slide Show > Custom Shows. Click New.

Select the slide you are looping, click Add. Click Ok and Close.

Click on the slide you are looping. Click Slide Show > Slide Transition. Under Advance slide, put a checkmark to Automatically After. This will allow the slide to loop automatically. Do NOT Apply to all slides.

Right click on the thumbnail of the current slide, select Hide Slide.

Now, you will need to insert a new slide just before the slide you are looping. On the new slide, insert an action button. Set the hyperlink to the custom show you have created. Put a checkmark on "Show and Return"

This has worked for me.

for or while loop to do something n times

but on the other hand it creates a completely useless list of integers just to loop over them. Isn't it a waste of memory, especially as far as big numbers of iterations are concerned?

That is what xrange(n) is for. It avoids creating a list of numbers, and instead just provides an iterator object.

In Python 3, xrange() was renamed to range() - if you want a list, you have to specifically request it via list(range(n)).

How to loop through a HashMap in JSP?

Depending on what you want to accomplish within the loop, iterate over one of these instead:

  • countries.keySet()
  • countries.entrySet()
  • countries.values()

Python loop that also accesses previous and next values

Very C/C++ style solution:

    foo = 5
    objectsList = [3, 6, 5, 9, 10]
    prev = nex = 0
    
    currentIndex = 0
    indexHigher = len(objectsList)-1 #control the higher limit of list
    
    found = False
    prevFound = False
    nexFound = False
    
    #main logic:
    for currentValue in objectsList: #getting each value of list
        if currentValue == foo:
            found = True
            if currentIndex > 0: #check if target value is in the first position   
                prevFound = True
                prev = objectsList[currentIndex-1]
            if currentIndex < indexHigher: #check if target value is in the last position
                nexFound = True
                nex = objectsList[currentIndex+1]
            break #I am considering that target value only exist 1 time in the list
        currentIndex+=1
    
    if found:
        print("Value %s found" % foo)
        if prevFound:
            print("Previous Value: ", prev)
        else:
            print("Previous Value: Target value is in the first position of list.")
        if nexFound:
            print("Next Value: ", nex)
        else:
            print("Next Value: Target value is in the last position of list.")
    else:
        print("Target value does not exist in the list.")

Looping from 1 to infinity in Python

If you're doing that in C, then your judgement there is as cloudy as it would be in Python :-)

For a loop that exits on a simple condition check at the start of each iteration, it's more usual (and clearer, in my opinion) to just do that in the looping construct itself. In other words, something like (if you need i after loop end):

int i = 0;
while (! thereIsAReasonToBreak(i)) {
    // do something
    i++;
}

or (if i can be scoped to just the loop):

for (int i = 0; ! thereIsAReasonToBreak(i); ++i) {
    // do something
}

That would translate to the Python equivalent:

i = 0
while not there_is_a_reason_to_break(i):
    # do something
    i += 1

Only if you need to exit in the middle of the loop somewhere (or if your condition is complex enough that it would render your looping statement far less readable) would you need to worry about breaking.

When your potential exit is a simple one at the start of the loop (as it appears to be here), it's usually better to encode the exit into the loop itself.

How can INSERT INTO a table 300 times within a loop in SQL?

I would prevent loops in general if i can, set approaches are much more efficient:

INSERT INTO tblFoo
  SELECT TOP (300) n = ROW_NUMBER()OVER (ORDER BY [object_id]) 
  FROM sys.all_objects ORDER BY n;

Demo

Generate a set or sequence without loops

Java: Array with loop

int count = 100;
int total = 0;
int[] numbers = new int[count];
for (int i=0; count>i; i++) {
    numbers[i] = i+1;
    total += i+1;
}
// done

Single Line Nested For Loops

First of all, your first code doesn't use a for loop per se, but a list comprehension.

  1. Would be equivalent to

    for j in range(0, width): for i in range(0, height): m[i][j]

  2. Much the same way, it generally nests like for loops, right to left. But list comprehension syntax is more complex.

  3. I'm not sure what this question is asking


  1. Any iterable object that yields iterable objects that yield exactly two objects (what a mouthful - i.e [(1,2),'ab'] would be valid )

  2. The order in which the object yields upon iteration. i goes to the first yield, j the second.

  3. Yes, but not as pretty. I believe it is functionally equivalent to:

    l = list()
    for i,j in object:
        l.append(function(i,j))
    

    or even better use map:

    map(function, object)
    

    But of course function would have to get i, j itself.

  4. Isn't this the same question as 3?

What is the best way to iterate over a dictionary?

I would say foreach is the standard way, though it obviously depends on what you're looking for

foreach(var kvp in my_dictionary) {
  ...
}

Is that what you're looking for?

What is the "right" way to iterate through an array in Ruby?

This will iterate through all the elements:

array = [1, 2, 3, 4, 5, 6]
array.each { |x| puts x }

Prints:

1
2
3
4
5
6

This will iterate through all the elements giving you the value and the index:

array = ["A", "B", "C"]
array.each_with_index {|val, index| puts "#{val} => #{index}" }

Prints:

A => 0
B => 1
C => 2

I'm not quite sure from your question which one you are looking for.

Creating an array from a text file in Bash

You can simply read each line from the file and assign it to an array.

#!/bin/bash
i=0
while read line 
do
        arr[$i]="$line"
        i=$((i+1))
done < file.txt

Iterator Loop vs index loop

The nice thing about iterator is that later on if you wanted to switch your vector to a another STD container. Then the forloop will still work.

python: restarting a loop

Changing the index variable i from within the loop is unlikely to do what you expect. You may need to use a while loop instead, and control the incrementing of the loop variable yourself. Each time around the for loop, i is reassigned with the next value from range(). So something like:

i = 2
while i < n:
    if(something):
        do something
    else:
        do something else
        i = 2 # restart the loop
        continue
    i += 1

In my example, the continue statement jumps back up to the top of the loop, skipping the i += 1 statement for that iteration. Otherwise, i is incremented as you would expect (same as the for loop).

Node.js for() loop returning the same values at each loop

I would suggest doing this in a more functional style :P

function CreateMessageboard(BoardMessages) {
  var htmlMessageboardString = BoardMessages
   .map(function(BoardMessage) {
     return MessageToHTMLString(BoardMessage);
   })
   .join('');
}

Try this

How to do a for loop in windows command line?

You might also consider adding ".

For example for %i in (*.wav) do opusenc "%~ni.wav" "%~ni.opus" is very good idea.

Comparing two vectors in an if statement

Are they identical?

> identical(A,C)
[1] FALSE

Which elements disagree:

> which(A != C)
[1] 2 4

Python Loop: List Index Out of Range

  1. In your for loop, you're iterating through the elements of a list a. But in the body of the loop, you're using those items to index that list, when you actually want indexes.
    Imagine if the list a would contain 5 items, a number 100 would be among them and the for loop would reach it. You will essentially attempt to retrieve the 100th element of the list a, which obviously is not there. This will give you an IndexError.

We can fix this issue by iterating over a range of indexes instead:

for i in range(len(a))

and access the a's items like that: a[i]. This won't give any errors.

  1. In the loop's body, you're indexing not only a[i], but also a[i+1]. This is also a place for a potential error. If your list contains 5 items and you're iterating over it like I've shown in the point 1, you'll get an IndexError. Why? Because range(5) is essentially 0 1 2 3 4, so when the loop reaches 4, you will attempt to get the a[5] item. Since indexing in Python starts with 0 and your list contains 5 items, the last item would have an index 4, so getting the a[5] would mean getting the sixth element which does not exist.

To fix that, you should subtract 1 from len(a) in order to get a range sequence 0 1 2 3. Since you're using an index i+1, you'll still get the last element, but this way you will avoid the error.

  1. There are many different ways to accomplish what you're trying to do here. Some of them are quite elegant and more "pythonic", like list comprehensions:

b = [a[i] + a[i+1] for i in range(len(a) - 1)]

This does the job in only one line.

Is there a way to access an iteration-counter in Java's for-each loop?

Here is an example of how I did this. This gets the index at the for each loop. Hope this helps.

public class CheckForEachLoop {

    public static void main(String[] args) {

        String[] months = new String[] { "JANUARY", "FEBRUARY", "MARCH", "APRIL", "MAY", "JUNE", "JULY", "AUGUST",
                "SEPTEMBER", "OCTOBER", "NOVEMBER", "DECEMBER" };
        for (String s : months) {
            if (s == months[2]) { // location where you can change
              doSomethingWith(s); // however many times s and months
                                  // doSomethingWith(s) will be completed and 
                                  // added together instead of counter
            }

        }
        System.out.println(s); 


    }
}

Equivalent VB keyword for 'break'

In case you're inside a Sub of Function and you want to exit it, you can use :

Exit Sub

or

Exit Function 

Counter inside xsl:for-each loop

position(). E.G.:

<countNo><xsl:value-of select="position()" /></countNo>

What is the difference between range and xrange functions in Python 2.X?

range(x,y) returns a list of each number in between x and y if you use a for loop, then range is slower. In fact, range has a bigger Index range. range(x.y) will print out a list of all the numbers in between x and y

xrange(x,y) returns xrange(x,y) but if you used a for loop, then xrange is faster. xrange has a smaller Index range. xrange will not only print out xrange(x,y) but it will still keep all the numbers that are in it.

[In] range(1,10)
[Out] [1, 2, 3, 4, 5, 6, 7, 8, 9]
[In] xrange(1,10)
[Out] xrange(1,10)

If you use a for loop, then it would work

[In] for i in range(1,10):
        print i
[Out] 1
      2
      3
      4
      5
      6
      7
      8
      9
[In] for i in xrange(1,10):
         print i
[Out] 1
      2
      3
      4
      5
      6
      7
      8
      9

There isn't much difference when using loops, though there is a difference when just printing it!

Loop through a comma-separated shell variable

Here's my pure bash solution that doesn't change IFS, and can take in a custom regex delimiter.

loop_custom_delimited() {
    local list=$1
    local delimiter=$2
    local item
    if [[ $delimiter != ' ' ]]; then
        list=$(echo $list | sed 's/ /'`echo -e "\010"`'/g' | sed -E "s/$delimiter/ /g")
    fi
    for item in $list; do
        item=$(echo $item | sed 's/'`echo -e "\010"`'/ /g')
        echo "$item"
    done
}

Abort trap 6 error in C

You are writing to memory you do not own:

int board[2][50]; //make an array with 3 columns  (wrong)
                  //(actually makes an array with only two 'columns')
...
for (i=0; i<num3+1; i++)
    board[2][i] = 'O';
          ^

Change this line:

int board[2][50]; //array with 2 columns (legal indices [0-1][0-49])
          ^

To:

int board[3][50]; //array with 3 columns (legal indices [0-2][0-49])
          ^

When creating an array, the value used to initialize: [3] indicates array size.
However, when accessing existing array elements, index values are zero based.

For an array created: int board[3][50];
Legal indices are board[0][0]...board[2][49]

EDIT To address bad output comment and initialization comment

add an additional "\n" for formatting output:

Change:

  ...
  for (k=0; k<50;k++) {
     printf("%d",board[j][k]);
  }
 }

       ...

To:

  ...
  for (k=0; k<50;k++) {
     printf("%d",board[j][k]);
  }
  printf("\n");//at the end of every row, print a new line
}
...  

Initialize board variable:

int board[3][50] = {0};//initialize all elements to zero

( array initialization discussion... )

How can I concatenate a string within a loop in JSTL/JSP?

define a String variable using the JSP tags

<%!
String test = new String();
%>

then refer to that variable in your loop as

<c:forEach items="${myParams.items}" var="currentItem" varStatus="stat">
test+= whaterver_value
</c:forEach>

Ways to iterate over a list in Java

Above you'll find all differents ways to iterate over a LIST.

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;

public class test1 {

public static void main(String[] args) {
    //******* Exercise 1 : Write a Java program to create a new array list, add some colors (string) and print out the collection.
    List<String> colors = new ArrayList<String>();
    colors.add("Black");
    colors.add("Red");
    colors.add("Green");
    colors.add("Blue");
    System.out.println(colors);
    
    
    //******* Exercise 2 : Write a Java program to iterate through all elements in a array list. 
    System.out.println("//******* Exercise 2");
    List<Integer> list2 = Arrays.asList(1, 2, 3, 4, 5, 6, 7);
    
    // iteration type 1 : using FOR loop
    System.out.println("// iteration type 1");
    for(Integer nb : list2) {
        System.out.print(nb + ", ");
    }
    System.out.println("\n");
    
    // iteration type 2 : using FOR loop
    System.out.println("// iteration type 2");
    for(int i=0; i < list2.size(); i++) {
        System.out.print(list2.get(i) + ", ");
    }System.out.println("\n");
    
    // iteration type 3  : using Do-While loop
    System.out.println("// iteration type 3");
    int index21 = 0;
    
    do {
        System.out.print(list2.get(index21) + ", ");
        index21++;
    }while(index21<list2.size());
    System.out.println("\n");
    
    
    // iteration type 4  : using While loop
    System.out.println("// iteration type 4");
    int index22 = 0;
    while(index22<list2.size()) {
        System.out.print(list2.get(index22) + ", ");
        index22++;
    }

    System.out.println("\n");
    
    
    // iteration type 5  : using  Iterable forEach loop 
    System.out.println("// iteration type 5");
     list2.forEach(elt -> {
         System.out.print(elt + ", ");
     });

    System.out.println("\n");
    
    
    // iteration type 6  : using  Iterator
    System.out.println("// iteration type 6");
    Iterator<Integer> listIterator = list2.iterator();
    while(listIterator.hasNext()) {
        System.out.print( listIterator.next() + ", ");
    }
    
    System.out.println("\n");
    
    // iteration type 7  : using  Iterator (From the beginning)
    System.out.println("// iteration type 7");
    ListIterator<Integer> listIterator21 = list2.listIterator(list2.size());
    while(listIterator21.hasPrevious()) {
        System.out.print( listIterator21.previous() + ", ");
    }

    System.out.println("\n");   
    
    // iteration type 8  : using  Iterator (From the End)
    System.out.println("// iteration type 8");
    ListIterator<Integer> listIterator22 = list2.listIterator();
    while(listIterator22.hasNext()) {
        System.out.print( listIterator22.next() + ", ");
    }

    System.out.println("\n");   
}

}

VBA EXCEL Multiple Nested FOR Loops that Set two variable for expression

I can't get to your google docs file at the moment but there are some issues with your code that I will try to address while answering

Sub stituterangersNEW()
Dim t As Range
Dim x As Range
Dim dify As Boolean
Dim difx As Boolean
Dim time2 As Date
Dim time1 As Date

    'You said time1 doesn't change, so I left it in a singe cell.
    'If that is not correct, you will have to play with this some more.
    time1 = Range("A6").Value

    'Looping through each of our output cells.
    For Each t In Range("B7:E9") 'Change these to match your real ranges.

        'Looping through each departure date/time.
        '(Only one row in your example. This can be adjusted if needed.)
        For Each x In Range("B2:E2") 'Change these to match your real ranges.
            'Check to see if our dep time corresponds to
            'the matching column in our output
            If t.Column = x.Column Then
                'If it does, then check to see what our time value is
                If x > 0 Then
                    time2 = x.Value
                    'Apply the change to the output cell.
                    t.Value = time1 - time2
                    'Exit out of this loop and move to the next output cell.
                    Exit For
                End If
            End If
            'If the columns don't match, or the x value is not a time
            'then we'll move to the next dep time (x)
        Next x
    Next t

End Sub

EDIT

I changed you worksheet to play with (see above for the new Sub). This probably does not suite your needs directly, but hopefully it will demonstrate the conept behind what I think you want to do. Please keep in mind that this code does not follow all the coding best preactices I would recommend (e.g. validating the time is actually a TIME and not some random other data type).

     A                      B                   C                   D                  E
1    LOAD_NUMBER            1                   2                   3                  4
2    DEPARTURE_TIME_DATE    11/12/2011 19:30    11/12/2011 19:30    11/12/2011 19:30    11/12/2011 20:00                
4    Dry_Refrig 7585.1  0   10099.8 16700
6    1/4/2012 19:30

Using the sub I got this output:

    A           B             C             D             E
7   Friday      1272:00:00    1272:00:00    1272:00:00    1271:30:00
8   Saturday    1272:00:00    1272:00:00    1272:00:00    1271:30:00
9   Thursday    1272:00:00    1272:00:00    1272:00:00    1271:30:00

PHP foreach loop through multidimensional array

If you mean the first and last entry of the array when talking about a.first and a.last, it goes like this:

foreach ($arr_nav as $inner_array) {
    echo reset($inner_array); //apple, orange, pear
    echo end($inner_array); //My Apple, View All Oranges, A Pear
}

arrays in PHP have an internal pointer which you can manipulate with reset, next, end. Retrieving keys/values works with key and current, but using each might be better in many cases..

How to give a delay in loop execution using Qt

C++11 has some portable timer stuff. Check out sleep_for.

Java Loop every minute

ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
executor.schedule(yourRunnable, 1L, TimeUnit.MINUTES);
...
// when done...
executor.shutdown();

How to remove all null elements from a ArrayList or String Array?

As of 2015, this is the best way (Java 8):

tourists.removeIf(Objects::isNull);

Note: This code will throw java.lang.UnsupportedOperationException for fixed-size lists (such as created with Arrays.asList), including immutable lists.

Correct way of looping through C++ arrays

sizeof tells you the size of a thing, not the number of elements in it. A more C++11 way to do what you are doing would be:

#include <array>
#include <string>
#include <iostream>

int main()
{
    std::array<std::string, 3> texts { "Apple", "Banana", "Orange" };
    for (auto& text : texts) {
        std::cout << text << '\n';
    }
    return 0;
}

ideone demo: http://ideone.com/6xmSrn

Incrementing a variable inside a Bash loop

USCOUNTER=$(grep -c "^US " "$FILE")

Iterate through object properties

if(Object.keys(obj).length) {
    Object.keys(obj).forEach(key => {
        console.log("\n" + key + ": " + obj[key]);
    });
}

// *** Explanation line by line ***

// Explaining the bellow line
// It checks if obj has at least one property. Here is how:
// Object.keys(obj) will return an array with all keys in obj.
// Keys are just the regular incremental numbers starting from 0.
// If there is no keys in obj, it will return empty array = []
// Then it will get its length. At this point, it checks: 
// If it has at least one element, it means it's bigger than 0 
// which evaluates to true and the bellow code will be executed.
// Else means it's length = 0 which evaluates to false
// NOTE: you can use Object.hasOwnProperty() instead of Object.keys(obj).length
if(Object.keys(obj).length) {

    // Explaining the bellow line
    // Just like in the previous line, this returns an array with
    // all keys in obj (because if code execution got here, it means 
    // obj has keys.) 
    // Then just invoke built-in javascript forEach() to loop
    // over each key in returned array and calls a call back function 
    // on each array element (key), using ES6 arrow function (=>)
    // Or you can just use a normal function ((key) { blah blah }).
    Object.keys(obj).forEach(key => {

        // The bellow line prints out all keys with their 
        // respective value in obj.
        // key comes from the returned array in Object.keys(obj)
        // obj[key] returns the value of key in obj
        console.log("\n" + key + ": " + obj[key]);
    });
}

For vs. while in C programming?

For the sake of readability

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

When I tried Continue For it Failed, I got a compiler error. While doing this, I discovered 'Resume':

For Each I As Item In Items

    If I = x Then
       'Move to next item
       Resume Next
    End If

    'Do something

Next

Note: I am using VBA here.

Declaring variables inside loops, good practice or bad practice?

For C++ it depends on what you are doing. OK, it is stupid code but imagine

class myTimeEatingClass
{
 public:
 //constructor
      myTimeEatingClass()
      {
          sleep(2000);
          ms_usedTime+=2;
      }
      ~myTimeEatingClass()
      {
          sleep(3000);
          ms_usedTime+=3;
      }
      const unsigned int getTime() const
      {
          return  ms_usedTime;
      }
      static unsigned int ms_usedTime;
};
myTimeEatingClass::ms_CreationTime=0; 
myFunc()
{
    for (int counter = 0; counter <= 10; counter++) {

        myTimeEatingClass timeEater();
        //do something
    }
    cout << "Creating class took "<< timeEater.getTime() <<"seconds at all<<endl;

}
myOtherFunc()
{
    myTimeEatingClass timeEater();
    for (int counter = 0; counter <= 10; counter++) {
        //do something
    }
    cout << "Creating class took "<< timeEater.getTime() <<"seconds at all<<endl;

}

You will wait 55 seconds until you get the output of myFunc. Just because each loop contructor and destructor together need 5 seconds to finish.

You will need 5 seconds until you get the output of myOtherFunc.

Of course, this is a crazy example.

But it illustrates that it might become a performance issue when each loop the same construction is done when the constructor and / or destructor needs some time.

Loop Through Each HTML Table Column and Get the Data using jQuery

try this

    $("#mprDetailDataTable tr:gt(0)").each(function () {
        var this_row = $(this);
        var productId = $.trim(this_row.find('td:eq(0)').html());//td:eq(0) means first td of this row
        var product = $.trim(this_row.find('td:eq(1)').html())
        var Quantity = $.trim(this_row.find('td:eq(2)').html())
    });

Iterating over all the keys of a map

A Type agnostic solution:

for _, key := range reflect.ValueOf(yourMap).MapKeys() {
    value := s.MapIndex(key).Interface()
    fmt.Println("Key:", key, "Value:", value)
}  

How do I break out of a loop in Perl?

Additional data (in case you have more questions):

FOO: {
       for my $i ( @listone ){
          for my $j ( @listtwo ){
                 if ( cond( $i,$j ) ){

                    last FOO;  # --->
                                   # |
                 }                 # |
          }                        # |
       }                           # |
 } # <-------------------------------

Loop backwards using indices in Python?

a = 10
for i in sorted(range(a), reverse=True):
    print i

Repeating a function every few seconds

Use a timer. There are 3 basic kinds, each suited for different purposes.

Use only in a Windows Form application. This timer is processed as part of the message loop, so the the timer can be frozen under high load.

When you need synchronicity, use this one. This means that the tick event will be run on the thread that started the timer, allowing you to perform GUI operations without much hassle.

This is the most high-powered timer, which fires ticks on a background thread. This lets you perform operations in the background without freezing the GUI or the main thread.

For most cases, I recommend System.Timers.Timer.

How to concat string + i?

according to this it looks like you have to set "N" before trying to use it and it looks like it needs to be an int not string? Don't know much bout MatLab but just what i gathered from that site..hope it helps :)

More Pythonic Way to Run a Process X Times

The for loop is definitely more pythonic, as it uses Python's higher level built in functionality to convey what you're doing both more clearly and concisely. The overhead of range vs xrange, and assigning an unused i variable, stem from the absence of a statement like Verilog's repeat statement. The main reason to stick to the for range solution is that other ways are more complex. For instance:

from itertools import repeat

for unused in repeat(None, 10):
    del unused   # redundant and inefficient, the name is clear enough
    print "This is run 10 times"

Using repeat instead of range here is less clear because it's not as well known a function, and more complex because you need to import it. The main style guides if you need a reference are PEP 20 - The Zen of Python and PEP 8 - Style Guide for Python Code.

We also note that the for range version is an explicit example used in both the language reference and tutorial, although in that case the value is used. It does mean the form is bound to be more familiar than the while expansion of a C-style for loop.

How to get out of while loop in java with Scanner method "hasNext" as condition?

Your condition is right (though you should drop the == true). What is happening is that the scanner will keep going until it reaches the end of the input. Try Ctrl+D, or pipe the input from a file (java myclass < input.txt).

Iterating over a 2 dimensional python list

Ref: zip built-in function

zip() in conjunction with the * operator can be used to unzip a list

unzip_lst = zip(*mylist)
for i in unzip_lst:
    for j in i:
        print j

Printing *s as triangles in Java?

well for the triangle , you need to have three loops in place of two , one outer loop to iterate the no of line two parallel loops inside the main loop first loop prints decreasing no of loops second loop prints increasing no of '' well i could give the exact logic as well , but its better if you try first just concentrate how many spaces and how many '' u need in every line relate the no of symbols with loop iterating no of lines and you're done ..... if it bothers more , let me know , i'll explain with logic and code as well

Jquery each - Stop loop and return object

Try this ...

  someArray = new Array();
  someArray[0] = 't5';
  someArray[1] = 'z12';
  someArray[2] = 'b88';
  someArray[3] = 's55';
  someArray[4] = 'e51';
  someArray[5] = 'o322';
  someArray[6] = 'i22';
  someArray[7] = 'k954';  

  var test =  findXX('o322'); 
  console.log(test);



function findXX(word)
{  
  for(var i in someArray){


    if(someArray[i] == word)
    {
      return someArray[i]; //<---  stop the loop!
    }   
  }
}

Loop until a specific user input

As an alternative to @Mark Byers' approach, you can use while True:

guess = 50     # this should be outside the loop, I think
while True:    # infinite loop
    n = raw_input("\n\nTrue, False or Correct?: ")
    if n == "Correct":
        break  # stops the loop
    elif n == "True":
        # etc.

Loop through an array php

Starting simple, with no HTML:

foreach($database as $file) {
    echo $file['filename'] . ' at ' . $file['filepath'];
}

And you can otherwise manipulate the fields in the foreach.

Looping each row in datagridview

Best aproach for me was:

  private void grid_receptie_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
    {
        int X = 1;
        foreach(DataGridViewRow row in grid_receptie.Rows)
        {
            row.Cells["NR_CRT"].Value = X;
            X++;
        }
    }

do-while loop in R

Building on the other answers, I wanted to share an example of using the while loop construct to achieve a do-while behaviour. By using a simple boolean variable in the while condition (initialized to TRUE), and then checking our actual condition later in the if statement. One could also use a break keyword instead of the continue <- FALSE inside the if statement (probably more efficient).

  df <- data.frame(X=c(), R=c())  
  x <- x0
  continue <- TRUE

  while(continue)
  {
    xi <- (11 * x) %% 16
    df <- rbind(df, data.frame(X=x, R=xi))
    x <- xi

    if(xi == x0)
    {
      continue <- FALSE
    }
  }

Skip over a value in the range function in python

for i in range(100):
    if i == 50:
        continue
    dosomething

Looping through rows in a DataView

You can iterate DefaultView as the following code by Indexer:

DataTable dt = new DataTable();
// add some rows to your table
// ...
dt.DefaultView.Sort = "OneColumnName ASC"; // For example
for (int i = 0; i < dt.Rows.Count; i++)
{
    DataRow oRow = dt.DefaultView[i].Row;
    // Do your stuff with oRow
    // ...
}

Object does not support item assignment error

The error seems clear: model objects do not support item assignment. MyModel.objects.latest('id')['foo'] = 'bar' will throw this same error.

It's a little confusing that your model instance is called projectForm...

To reproduce your first block of code in a loop, you need to use setattr

for k,v in session_results.iteritems():
    setattr(projectForm, k, v)

C# loop - break vs. continue

break will exit the loop completely, continue will just skip the current iteration.

For example:

for (int i = 0; i < 10; i++) {
    if (i == 0) {
        break;
    }

    DoSomeThingWith(i);
}

The break will cause the loop to exit on the first iteration - DoSomeThingWith will never be executed. This here:

for (int i = 0; i < 10; i++) {
    if(i == 0) {
        continue;
    }

    DoSomeThingWith(i);
}

Will not execute DoSomeThingWith for i = 0, but the loop will continue and DoSomeThingWith will be executed for i = 1 to i = 9.

How to loop through all elements of a form jQuery

Do one of the two jQuery serializers inside your form submit to get all inputs having a submitted value.

var criteria = $(this).find('input,select').filter(function () {
    return ((!!this.value) && (!!this.name));
}).serializeArray();

var formData = JSON.stringify(criteria);

serializeArray() will produce an array of names and values

0: {name: "OwnLast", value: "Bird"}
1: {name: "OwnFirst", value: "Bob"}
2: {name: "OutBldg[]", value: "PDG"}
3: {name: "OutBldg[]", value: "PDA"}

var criteria = $(this).find('input,select').filter(function () {
    return ((!!this.value) && (!!this.name));
}).serialize();

serialize() creates a text string in standard URL-encoded notation

"OwnLast=Bird&OwnFirst=Bob&OutBldg%5B%5D=PDG&OutBldg%5B%5D=PDA"

"for" vs "each" in Ruby

This is the only difference:

each:

irb> [1,2,3].each { |x| }
  => [1, 2, 3]
irb> x
NameError: undefined local variable or method `x' for main:Object
    from (irb):2
    from :0

for:

irb> for x in [1,2,3]; end
  => [1, 2, 3]
irb> x
  => 3

With the for loop, the iterator variable still lives after the block is done. With the each loop, it doesn't, unless it was already defined as a local variable before the loop started.

Other than that, for is just syntax sugar for the each method.

When @collection is nil both loops throw an exception:

Exception: undefined local variable or method `@collection' for main:Object

How to determine the first and last iteration in a foreach loop?

A more simplified version of the above and presuming you're not using custom indexes...

$len = count($array);
foreach ($array as $index => $item) {
    if ($index == 0) {
        // first
    } else if ($index == $len - 1) {
        // last
    }
}

Version 2 - Because I have come to loathe using the else unless necessary.

$len = count($array);
foreach ($array as $index => $item) {
    if ($index == 0) {
        // first
        // do something
        continue;
    }

    if ($index == $len - 1) {
        // last
        // do something
        continue;
    }
}

Image change every 30 seconds - loop

I agree with using frameworks for things like this, just because its easier. I hacked this up real quick, just fades an image out and then switches, also will not work in older versions of IE. But as you can see the code for the actual fade is much longer than the JQuery implementation posted by KARASZI István.

function changeImage() {
    var img = document.getElementById("img");
    img.src = images[x];
    x++;        
    if(x >= images.length) {
        x = 0;
    } 
    fadeImg(img, 100, true);
    setTimeout("changeImage()", 30000);
}

function fadeImg(el, val, fade) {
    if(fade === true) {
        val--;
    } else {
        val ++;
    }       
    if(val > 0 && val < 100) {
        el.style.opacity = val / 100;
        setTimeout(function(){ fadeImg(el, val, fade); }, 10);
    }
}

var images = [], x = 0;
images[0] = "image1.jpg";
images[1] = "image2.jpg";
images[2] = "image3.jpg";
setTimeout("changeImage()", 30000);

C# Wait until condition is true

Ended up writing this today and seems to be ok. Your usage could be:

await TaskEx.WaitUntil(isExcelInteractive);

code (including the inverse operation)

public static class TaskEx
{
    /// <summary>
    /// Blocks while condition is true or timeout occurs.
    /// </summary>
    /// <param name="condition">The condition that will perpetuate the block.</param>
    /// <param name="frequency">The frequency at which the condition will be check, in milliseconds.</param>
    /// <param name="timeout">Timeout in milliseconds.</param>
    /// <exception cref="TimeoutException"></exception>
    /// <returns></returns>
    public static async Task WaitWhile(Func<bool> condition, int frequency = 25, int timeout = -1)
    {
        var waitTask = Task.Run(async () =>
        {
            while (condition()) await Task.Delay(frequency);
        });

        if(waitTask != await Task.WhenAny(waitTask, Task.Delay(timeout)))
            throw new TimeoutException();
    }

    /// <summary>
    /// Blocks until condition is true or timeout occurs.
    /// </summary>
    /// <param name="condition">The break condition.</param>
    /// <param name="frequency">The frequency at which the condition will be checked.</param>
    /// <param name="timeout">The timeout in milliseconds.</param>
    /// <returns></returns>
    public static async Task WaitUntil(Func<bool> condition, int frequency = 25, int timeout = -1)
    {
        var waitTask = Task.Run(async () =>
        {
            while (!condition()) await Task.Delay(frequency);
        });

        if (waitTask != await Task.WhenAny(waitTask, 
                Task.Delay(timeout))) 
            throw new TimeoutException();
    }
}

Example usage: https://dotnetfiddle.net/Vy8GbV

Looping Over Result Sets in MySQL

Something like this should do the trick (However, read after the snippet for more info)

CREATE PROCEDURE GetFilteredData()
BEGIN
  DECLARE bDone INT;

  DECLARE var1 CHAR(16);    -- or approriate type
  DECLARE Var2 INT;
  DECLARE Var3 VARCHAR(50);

  DECLARE curs CURSOR FOR  SELECT something FROM somewhere WHERE some stuff;
  DECLARE CONTINUE HANDLER FOR NOT FOUND SET bDone = 1;

  DROP TEMPORARY TABLE IF EXISTS tblResults;
  CREATE TEMPORARY TABLE IF NOT EXISTS tblResults  (
    --Fld1 type,
    --Fld2 type,
    --...
  );

  OPEN curs;

  SET bDone = 0;
  REPEAT
    FETCH curs INTO var1,, b;

    IF whatever_filtering_desired
       -- here for whatever_transformation_may_be_desired
       INSERT INTO tblResults VALUES (var1, var2, var3 ...);
    END IF;
  UNTIL bDone END REPEAT;

  CLOSE curs;
  SELECT * FROM tblResults;
END

A few things to consider...

Concerning the snippet above:

  • may want to pass part of the query to the Stored Procedure, maybe particularly the search criteria, to make it more generic.
  • If this method is to be called by multiple sessions etc. may want to pass a Session ID of sort to create a unique temporary table name (actually unnecessary concern since different sessions do not share the same temporary file namespace; see comment by Gruber, below)
  • A few parts such as the variable declarations, the SELECT query etc. need to be properly specified

More generally: trying to avoid needing a cursor.

I purposely named the cursor variable curs[e], because cursors are a mixed blessing. They can help us implement complicated business rules that may be difficult to express in the declarative form of SQL, but it then brings us to use the procedural (imperative) form of SQL, which is a general feature of SQL which is neither very friendly/expressive, programming-wise, and often less efficient performance-wise.

Maybe you can look into expressing the transformation and filtering desired in the context of a "plain" (declarative) SQL query.

Is recursion ever faster than looping?

Tail recursion is as fast as looping. Many functional languages have tail recursion implemented in them.

Modifying list while iterating

Use a while loop that checks for the truthfulness of the array:

while array:
    value = array.pop(0)
    # do some calculation here

And it should do it without any errors or funny behaviour.

C# Iterate through Class properties

Yes, you could make an indexer on your Record class that maps from the property name to the correct property. This would keep all the binding from property name to property in one place eg:

public class Record
{
    public string ItemType { get; set; }

    public string this[string propertyName]
    {
        set
        {
            switch (propertyName)
            {
                case "itemType":
                    ItemType = value;
                    break;
                    // etc
            }   
        }
    }
}

Alternatively, as others have mentioned, use reflection.

Loop through each row of a range in Excel

In Loops, I always prefer to use the Cells class, using the R1C1 reference method, like this:

Cells(rr, col).Formula = ...

This allows me to quickly and easily loop over a Range of cells easily:

Dim r As Long
Dim c As Long

c = GetTargetColumn() ' Or you could just set this manually, like: c = 1

With Sheet1 ' <-- You should always qualify a range with a sheet!

    For r = 1 To 10 ' Or 1 To (Ubound(MyListOfStuff) + 1)

        ' Here we're looping over all the cells in rows 1 to 10, in Column "c"
        .Cells(r, c).Value = MyListOfStuff(r)

        '---- or ----

        '...to easily copy from one place to another (even with an offset of rows and columns)
        .Cells(r, c).Value = Sheet2.Cells(r + 3, 17).Value


    Next r

End With

Python: How to keep repeating a program until a specific input is obtained?

There are two ways to do this. First is like this:

while True:             # Loop continuously
    inp = raw_input()   # Get the input
    if inp == "":       # If it is a blank line...
        break           # ...break the loop

The second is like this:

inp = raw_input()       # Get the input
while inp != "":        # Loop until it is a blank line
    inp = raw_input()   # Get the input again

Note that if you are on Python 3.x, you will need to replace raw_input with input.

How to make for loops in Java increase by increments other than 1

for (let i = 0; i <= value; i+=n) { // increments by n
/*code statement*/
}

this format works for me incrementing index by n

for (let i = 0; i <= value; i+=4) { // increments by 4
/*code statement*/
}

if n = 4 this it will increment by 4

Python: Continuing to next iteration in outer loop

We want to find something and then stop the inner iteration. I use a flag system.

for l in f:
    flag = True
    for e in r:
        if flag==False:continue
        if somecondition:
            do_something()
            flag=False

JavaScript Infinitely Looping slideshow with delays?

The correct approach is to use a single timer. Using setInterval, you can achieve what you want as follows:

window.onload = function start() {
    slide();
}
function slide() {
    var num = 0, style = document.getElementById('container').style;
    window.setInterval(function () {
        // increase by num 1, reset to 0 at 4
        num = (num + 1) % 4;

        // -600 * 1 = -600, -600 * 2 = -1200, etc 
        style.marginLeft = (-600 * num) + "px"; 
    }, 3000); // repeat forever, polling every 3 seconds
}

Why is printing "B" dramatically slower than printing "#"?

Pure speculation is that you're using a terminal that attempts to do word-wrapping rather than character-wrapping, and treats B as a word character but # as a non-word character. So when it reaches the end of a line and searches for a place to break the line, it sees a # almost immediately and happily breaks there; whereas with the B, it has to keep searching for longer, and may have more text to wrap (which may be expensive on some terminals, e.g., outputting backspaces, then outputting spaces to overwrite the letters being wrapped).

But that's pure speculation.

Iterating over ResultSet and adding its value in an ArrayList

If I've understood your problem correctly, there are two possible problems here:

  • resultset is null - I assume that this can't be the case as if it was you'd get an exception in your while loop and nothing would be output.
  • The second problem is that resultset.getString(i++) will get columns 1,2,3 and so on from each subsequent row.

I think that the second point is probably your problem here.

Lets say you only had 1 row returned, as follows:

Col 1, Col 2, Col 3 
A    ,     B,     C

Your code as it stands would only get A - it wouldn't get the rest of the columns.

I suggest you change your code as follows:

ResultSet resultset = ...;
ArrayList<String> arrayList = new ArrayList<String>(); 
while (resultset.next()) {                      
    int i = 1;
    while(i <= numberOfColumns) {
        arrayList.add(resultset.getString(i++));
    }
    System.out.println(resultset.getString("Col 1"));
    System.out.println(resultset.getString("Col 2"));
    System.out.println(resultset.getString("Col 3"));                    
    System.out.println(resultset.getString("Col n"));
}

Edit:

To get the number of columns:

ResultSetMetaData metadata = resultset.getMetaData();
int numberOfColumns = metadata.getColumnCount();

Vba macro to copy row from table if value in table meets condition

you are describing a Problem, which I would try to solve with the VLOOKUP function rather than using VBA.

You should always consider a non-vba solution first.

Here are some application examples of VLOOKUP (or SVERWEIS in German, as i know it):

http://www.youtube.com/watch?v=RCLUM0UMLXo

http://office.microsoft.com/en-us/excel-help/vlookup-HP005209335.aspx


If you have to make it as a macro, you could use VLOOKUP as an application function - a quick solution with slow performance - or you will have to make a simillar function yourself.

If it has to be the latter, then there is need for more details on your specification, regarding performance questions.

You could copy any range to an array, loop through this array and check for your value, then copy this value to any other range. This is how i would solve this as a vba-function.

This would look something like that:

Public Sub CopyFilter()

  Dim wks As Worksheet
  Dim avarTemp() As Variant
  'go through each worksheet
  For Each wks In ThisWorkbook.Worksheets
        avarTemp = wks.UsedRange
        For i = LBound(avarTemp, 1) To UBound(avarTemp, 1)
          'check in the first column in each row
          If avarTemp(i, LBound(avarTemp, 2)) = "XYZ" Then
            'copy cell
             targetWks.Cells(1, 1) = avarTemp(i, LBound(avarTemp, 2))
          End If
        Next i
  Next wks
End Sub

Ok, now i have something nice which could come in handy for myself:

Public Function FILTER(ByRef rng As Range, ByRef lngIndex As Long) As Variant
  Dim avarTemp() As Variant
  Dim avarResult() As Variant
  Dim i As Long
  avarTemp = rng

  ReDim avarResult(0)

  For i = LBound(avarTemp, 1) To UBound(avarTemp, 1)
      If avarTemp(i, 1) = "active" Then
        avarResult(UBound(avarResult)) = avarTemp(i, lngIndex)
        'expand our result array
        ReDim Preserve avarResult(UBound(avarResult) + 1)
      End If
  Next i

  FILTER = avarResult
End Function

You can use it in your Worksheet like this =FILTER(Tabelle1!A:C;2) or with =INDEX(FILTER(Tabelle1!A:C;2);3) to specify the result row. I am sure someone could extend this to include the index functionality into FILTER or knows how to return a range like object - maybe I could too, but not today ;)

How to use goto statement correctly

Java also does not use line numbers, which is a necessity for a GOTO function. Unlike C/C++, Java does not have goto statement, but java supports label. The only place where a label is useful in Java is right before nested loop statements. We can specify label name with break to break out a specific outer loop.

Counting number of words in a file

I think a correct approach would be by means of Regex:

String fileContent = <text from file>;    
String[] words = Pattern.compile("\\s+").split(fileContent);
System.out.println("File has " + words.length + " words");

Hope it helps. The "\s+" meaning is in Pattern javadoc

Single Result from Database by using mySQLi

When just a single result is needed, then no loop should be used. Just fetch the row right away.

  • In case you need to fetch the entire row into associative array:

      $row = $result->fetch_assoc();
    
  • in case you need just a single value

      $row = $result->fetch_row();
      $value = $row[0] ?? false;
    

The last example will return the first column from the first returned row, or false if no row was returned. It can be also shortened to a single line,

$value = $result->fetch_row()[0] ?? false;

Below are complete examples for different use cases

Variables to be used in the query

When variables are to be used in the query, then a prepared statement must be used. For example, given we have a variable $id:

$query = "SELECT ssfullname, ssemail FROM userss WHERE ud=?";
$stmt = $conn->prepare($query);
$stmt->bind_param("s", $id);
$stmt->execute()
$result = $stmt->get_result();
$row = $result->fetch_assoc();

// in case you need just a single value
$query = "SELECT count(*) FROM userss WHERE id=?";
$stmt = $conn->prepare($query);
$stmt->bind_param("s", $id);
$stmt->execute()
$result = $stmt->get_result();
$value = $result->fetch_row()[0] ?? false;

The detailed explanation of the above process can be found in my article. As to why you must follow it is explained in this famous question

No variables in the query

In your case, where no variables to be used in the query, you can use the query() method:

$query = "SELECT ssfullname, ssemail FROM userss ORDER BY ssid";
$result = $conn->query($query);
// in case you need an array
$row = $result->fetch_assoc();
// OR in case you need just a single value
$value = $result->fetch_row()[0] ?? false;

By the way, although using raw API while learning is okay, consider using some database abstraction library or at least a helper function in the future:

// using a helper function
$sql = "SELECT email FROM users WHERE id=?";
$value = prepared_select($conn, $sql, [$id])->fetch_row[0] ?? false;

// using a database helper class
$email = $db->getCol("SELECT email FROM users WHERE id=?", [$id]);

As you can see, although a helper function can reduce the amount of code, a class' method could encapsulate all the repetitive code inside, making you to write only meaningful parts - the query, the input parameters and the desired result format (in the form of the method's name).

Getting "type or namespace name could not be found" but everything seems ok?

Had the same problem after merging some new code into a vs2019 project. Restarted VS, unloaded and reloaded projects, ensured all projects in solution had same ToolsVersion= and TargetFrameworkVersion. None of this helped.

I had a case of project Substrate, failing to find namespace Skin (in project Skin).

Finally I opened up Substrate.csproj and checked all the ProjectReference Include entries. The others were there, but no reference to Skin, even though Skin did show up in the check box of the little project dependencies dialog. So the project dependencies dialog took the check box for Skin (and saved it somewhere) but did not alter Substrate.csproj. I then added the ProjectReference Include manually, ensuring I had the correct path and GUID for the skin project.

<ProjectReference Include="..\Skin\Skin.csproj">
  <Project>{1ad4b5d7-5014-4f5f-983e-2c59ac0e0028}</Project>
  <Name>Skin</Name>
</ProjectReference>

I then saved the Substrate.csproj and the problem was solved. So as others have said this is a problem with VS tooling

how to add a jpg image in Latex

You need to use a graphics library. Put this in your preamble:

\usepackage{graphicx}

You can then add images like this:

\begin{figure}[ht!]
\centering
\includegraphics[width=90mm]{fixed_dome1.jpg}
\caption{A simple caption \label{overflow}}
\end{figure}

This is the basic template I use in my documents. The position and size should be tweaked for your needs. Refer to the guide below for more information on what parameters to use in \figure and \includegraphics. You can then refer to the image in your text using the label you gave in the figure:

And here we see figure \ref{overflow}.

Read this guide here for a more detailed instruction: http://en.wikibooks.org/wiki/LaTeX/Floats,_Figures_and_Captions

How to uninstall mini conda? python

your have to comment that line in ~/.bashrc:

#export PATH=/home/jolth/miniconda3/bin:$PATH

and run:

source ~/.bashrc

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

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

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

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

Get-ChildItem C:\\\\\Windows

What is the difference between encrypting and signing in asymmetric encryption?

In your scenario, you do not encrypt in the meaning of asymmetric encryption; I'd rather call it "encode".

So you encode your data into some binary representation, then you sign with your private key. If you cannot verify the signature via your public key, you know that the signed data is not generated with your private key. ("verification" meaning that the unsigned data is not meaningful)

Can I fade in a background image (CSS: background-image) with jQuery?

jquery:

 $("div").fadeTo(1000 , 1);

css

    div {
     background: url("../images/example.jpg") no-repeat center; 
    opacity:0;
    Height:100%;
    }

html

<div></div>

How to take column-slices of dataframe in pandas

Lets use the titanic dataset from the seaborn package as an example

# Load dataset (pip install seaborn)
>> import seaborn.apionly as sns
>> titanic = sns.load_dataset('titanic')

using the column names

>> titanic.loc[:,['sex','age','fare']]

using the column indices

>> titanic.iloc[:,[2,3,6]]

using ix (Older than Pandas <.20 version)

>> titanic.ix[:,[‘sex’,’age’,’fare’]]

or

>> titanic.ix[:,[2,3,6]]

using the reindex method

>> titanic.reindex(columns=['sex','age','fare'])

How do I add a newline to a windows-forms TextBox?

Have you tried something like:

textbox.text = "text" & system.environment.newline & "some more text"

Add new column with foreign key constraint in one command

If you also need to add default values in case you already have some rows in the table then add DEFAULT val

ALTER TABLE one
ADD two_id int DEFAULT 123,
FOREIGN KEY(two_id) REFERENCES two(id);

Looping through rows in a DataView

The DataView object itself is used to loop through DataView rows.

DataView rows are represented by the DataRowView object. The DataRowView.Row property provides access to the original DataTable row.

C#

foreach (DataRowView rowView in dataView)
{
    DataRow row = rowView.Row;
    // Do something //
}

VB.NET

For Each rowView As DataRowView in dataView
    Dim row As DataRow = rowView.Row
    ' Do something '
Next

Mapping many-to-many association table with extra column(s)

As said before, with JPA, in order to have the chance to have extra columns, you need to use two OneToMany associations, instead of a single ManyToMany relationship. You can also add a column with autogenerated values; this way, it can work as the primary key of the table, if useful.

For instance, the implementation code of the extra class should look like that:

@Entity
@Table(name = "USER_SERVICES")
public class UserService{

    // example of auto-generated ID
    @Id
    @Column(name = "USER_SERVICES_ID", nullable = false)
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private long userServiceID;



    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "USER_ID")
    private User user;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "SERVICE_ID")
    private Service service;



    // example of extra column
    @Column(name="VISIBILITY")    
    private boolean visibility;



    public long getUserServiceID() {
        return userServiceID;
    }


    public User getUser() {
        return user;
    }

    public void setUser(User user) {
        this.user = user;
    }

    public Service getService() {
        return service;
    }

    public void setService(Service service) {
        this.service = service;
    }

    public boolean getVisibility() {
        return visibility;
    }

    public void setVisibility(boolean visibility) {
        this.visibility = visibility;
    }

}

How to install .MSI using PowerShell

#$computerList = "Server Name"
#$regVar = "Name of the package "
#$packageName = "Packe name "
$computerList = $args[0]
$regVar = $args[1]
$packageName = $args[2]
foreach ($computer in $computerList)
{
    Write-Host "Connecting to $computer...."
    Invoke-Command -ComputerName $computer -Authentication Kerberos -ScriptBlock {
    param(
        $computer,
        $regVar,
        $packageName
        )

        Write-Host "Connected to $computer"
        if ([IntPtr]::Size -eq 4)
        {
            $registryLocation = Get-ChildItem "HKLM:\Software\Microsoft\Windows\CurrentVersion\Uninstall\"
            Write-Host "Connected to 32bit Architecture"
        }
        else
        {
            $registryLocation = Get-ChildItem "HKLM:\Software\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\"
            Write-Host "Connected to 64bit Architecture"
        }
        Write-Host "Finding previous version of `enter code here`$regVar...."
        foreach ($registryItem in $registryLocation)
        {
            if((Get-itemproperty $registryItem.PSPath).DisplayName -match $regVar)
            {
                Write-Host "Found $regVar" (Get-itemproperty $registryItem.PSPath).DisplayName
                $UninstallString = (Get-itemproperty $registryItem.PSPath).UninstallString
                    $match = [RegEx]::Match($uninstallString, "{.*?}")
                    $args = "/x $($match.Value) /qb"
                    Write-Host "Uninstalling $regVar...."
                    [diagnostics.process]::start("msiexec", $args).WaitForExit() 
                    Write-Host "Uninstalled $regVar"
            }
        }

        $path = "\\$computer\Msi\$packageName"
        Write-Host "Installaing $path...."
        $args = " /i $path /qb"
        [diagnostics.process]::start("msiexec", $args).WaitForExit()
        Write-Host "Installed $path"
    } -ArgumentList $computer, $regVar, $packageName
Write-Host "Deployment Complete"

}

Principal Component Analysis (PCA) in Python

This is a job for numpy.

And here's a tutorial demonstrating how pincipal component analysis can be done using numpy's built-in modules like mean,cov,double,cumsum,dot,linalg,array,rank.

http://glowingpython.blogspot.sg/2011/07/principal-component-analysis-with-numpy.html

Notice that scipy also has a long explanation here - https://github.com/scikit-learn/scikit-learn/blob/babe4a5d0637ca172d47e1dfdd2f6f3c3ecb28db/scikits/learn/utils/extmath.py#L105

with the scikit-learn library having more code examples - https://github.com/scikit-learn/scikit-learn/blob/babe4a5d0637ca172d47e1dfdd2f6f3c3ecb28db/scikits/learn/utils/extmath.py#L105

How to set a value of a variable inside a template code?

Create a template tag:

The app should contain a templatetags directory, at the same level as models.py, views.py, etc. If this doesn’t already exist, create it - don’t forget the __init__.py file to ensure the directory is treated as a Python package.

Create a file named define_action.py inside of the templatetags directory with the following code:

from django import template
register = template.Library()

@register.simple_tag
def define(val=None):
  return val

Note: Development server won’t automatically restart. After adding the templatetags module, you will need to restart your server before you can use the tags or filters in templates.


Then in your template you can assign values to the context like this:

{% load define_action %}
{% if item %}

   {% define "Edit" as action %}

{% else %}

   {% define "Create" as action %}

{% endif %}


Would you like to {{action}} this item?

Failed to load ApplicationContext for JUnit test of Spring controller

There can be multiple root causes for this exception. For me, my mockMvc wasn't getting auto-configured. I solved this exception by using @WebMvcTest(MyController.class) at the class level. This annotation will disable full auto-configuration and instead apply only configuration relevant to MVC tests.

An alternative to this is, If you are looking to load your full application configuration and use MockMVC, you should consider @SpringBootTest combined with @AutoConfigureMockMvc rather than @WebMvcTest

extra qualification error in C++

This is because you have the following code:

class JSONDeserializer
{
    Value JSONDeserializer::ParseValue(TDR type, const json_string& valueString);
};

This is not valid C++ but Visual Studio seems to accept it. You need to change it to the following code to be able to compile it with a standard compliant compiler (gcc is more compliant to the standard on this point).

class JSONDeserializer
{
    Value ParseValue(TDR type, const json_string& valueString);
};

The error come from the fact that JSONDeserializer::ParseValue is a qualified name (a name with a namespace qualification), and such a name is forbidden as a method name in a class.

Ruby: Merging variables in to a string

You can use sprintf-like formatting to inject values into the string. For that the string must include placeholders. Put your arguments into an array and use on of these ways: (For more info look at the documentation for Kernel::sprintf.)

fmt = 'The %s %s the %s'
res = fmt % [animal, action, other_animal]  # using %-operator
res = sprintf(fmt, animal, action, other_animal)  # call Kernel.sprintf

You can even explicitly specify the argument number and shuffle them around:

'The %3$s %2$s the %1$s' % ['cat', 'eats', 'mouse']

Or specify the argument using hash keys:

'The %{animal} %{action} the %{second_animal}' %
  { :animal => 'cat', :action=> 'eats', :second_animal => 'mouse'}

Note that you must provide a value for all arguments to the % operator. For instance, you cannot avoid defining animal.

Sending JSON to PHP using ajax

To send javascript obj to php using json and ajax:

js:

var dataPost = {
   "var": "foo"
};
var dataString = JSON.stringify(dataPost);

$.ajax({
   url: 'server.php',
   data: {myData: dataString},
   type: 'POST',
   success: function(response) {
      alert(response);
   }
});

to use that object in php:

$obj = json_decode($_POST["myData"]);

echo $obj->var;

Convert object array to hash map, indexed by an attribute value of the Object

There are better ways to do this as explained by other posters. But if I want to stick to pure JS and ol' fashioned way then here it is:

var arr = [
    { key: 'foo', val: 'bar' },
    { key: 'hello', val: 'world' },
    { key: 'hello', val: 'universe' }
];

var map = {};
for (var i = 0; i < arr.length; i++) {
    var key = arr[i].key;
    var value = arr[i].val;

    if (key in map) {
        map[key].push(value);
    } else {
        map[key] = [value];
    }
}

console.log(map);

Unable to set data attribute using jQuery Data() API

It is mentioned in the .data() documentation

The data- attributes are pulled in the first time the data property is accessed and then are no longer accessed or mutated (all data values are then stored internally in jQuery)

This was also covered on Why don't changes to jQuery $.fn.data() update the corresponding html 5 data-* attributes?

The demo on my original answer below doesn't seem to work any more.

Updated answer

Again, from the .data() documentation

The treatment of attributes with embedded dashes was changed in jQuery 1.6 to conform to the W3C HTML5 specification.

So for <div data-role="page"></div> the following is true $('div').data('role') === 'page'

I'm fairly sure that $('div').data('data-role') worked in the past but that doesn't seem to be the case any more. I've created a better showcase which logs to HTML rather than having to open up the Console and added an additional example of the multi-hyphen to camelCase data- attributes conversion.

Updated demo (2015-07-25)

Also see jQuery Data vs Attr?

HTML

<div id="changeMe" data-key="luke" data-another-key="vader"></div>
<a href="#" id="changeData"></a>
<table id="log">
    <tr><th>Setter</th><th>Getter</th><th>Result of calling getter</th><th>Notes</th></tr>
</table>

JavaScript (jQuery 1.6.2+)

var $changeMe = $('#changeMe');
var $log = $('#log');

var logger;
(logger = function(setter, getter, note) {
    note = note || '';
    eval('$changeMe' + setter);
    var result = eval('$changeMe' + getter);
    $log.append('<tr><td><code>' + setter + '</code></td><td><code>' + getter + '</code></td><td>' + result + '</td><td>' + note + '</td></tr>');
})('', ".data('key')", "Initial value");

$('#changeData').click(function() {
    // set data-key to new value
    logger(".data('key', 'leia')", ".data('key')", "expect leia on jQuery node object but DOM stays as luke");
    // try and set data-key via .attr and get via some methods
    logger(".attr('data-key', 'yoda')", ".data('key')", "expect leia (still) on jQuery object but DOM now yoda");
    logger("", ".attr('key')", "expect undefined (no attr <code>key</code>)");
    logger("", ".attr('data-key')", "expect yoda in DOM and on jQuery object");

    // bonus points
    logger('', ".data('data-key')", "expect undefined (cannot get via this method)");
    logger(".data('anotherKey')", ".data('anotherKey')", "jQuery 1.6+ get multi hyphen <code>data-another-key</code>");
    logger(".data('another-key')", ".data('another-key')", "jQuery < 1.6 get multi hyphen <code>data-another-key</code> (also supported in jQuery 1.6+)");

    return false;
});

$('#changeData').click();

Older demo


Original answer

For this HTML:

<div id="foo" data-helptext="bar"></div>
<a href="#" id="changeData">change data value</a>

and this JavaScript (with jQuery 1.6.2)

console.log($('#foo').data('helptext'));

$('#changeData').click(function() {
    $('#foo').data('helptext', 'Testing 123');
//  $('#foo').attr('data-helptext', 'Testing 123');
    console.log($('#foo').data('data-helptext'));
    return false;
});

See demo

Using the Chrome DevTools Console to inspect the DOM, the $('#foo').data('helptext', 'Testing 123'); does not update the value as seen in the Console but $('#foo').attr('data-helptext', 'Testing 123'); does.

Commenting in a Bash script inside a multiline command

$IFS comment hacks

This hack uses parameter expansion on $IFS, which is used to separate words in commands:

$ echo foo${IFS}bar
foo bar

Similarly:

$ echo foo${IFS#comment}bar
foo bar

Using this, you can put a comment on a command line with contination:

$ echo foo${IFS# Comment here} \
> bar
foo bar

but the comment will need to be before the \ continuation.

Note that parameter expansion is performed inside the comment:

$ ls file
ls: cannot access 'file': No such file or directory
$ echo foo${IFS# This command will create file: $(touch file)}bar
foo bar
$ ls file
file

Rare exception

The only rare case this fails is if $IFS previously started with the exact text which is removed via the expansion (ie, after the # character):

$ IFS=x
$ echo foo${IFS#y}bar
foo bar
$ echo foo${IFS#x}bar
foobar

Note the final foobar has no space, illustrating the issue.

Since $IFS contains only whitespace by default, it's extremely unlikely you'll run into this problem.


Credit to @pjh's comment which sparked off this answer.

Javascript/jQuery: Set Values (Selection) in a multiple Select

var groups = ["Test", "Prof","Off"];

    $('#fruits option').filter(function() {
      return groups.indexOf($(this).text()) > -1; //Options text exists in array
    }).prop('selected', true); //Set selected

Copy and Paste a set range in the next empty row

Below is the code that works well but my values overlap in sheet "Final" everytime the condition of <=11 meets in sheet "Calculator"

I would like you to kindly support me to modify the code so that the cursor should move to next blank cell and values keeps on adding up like a list.

Dim i As Integer
Dim ws1 As Worksheet: Set ws1 = ThisWorkbook.Sheets("Calculator")
Dim ws2 As Worksheet: Set ws2 = ThisWorkbook.Sheets("Final")

For i = 2 To ws1.Range("A65536").End(xlUp).Row

    If ws1.Cells(i, 4) <= 11 Then

        ws2.Cells(i, 1).Value = Left(Worksheets("Calculator").Cells(i, 1).Value, Len(Worksheets("Calculator").Cells(i, 1).Value) - 0)
        ws2.Cells(i, 2) = Application.VLookup(Cells(i, 1), Worksheets("Calculator").Columns("A:D"), 4, False)
        ws2.Cells(i, 3) = Application.VLookup(Cells(i, 1), Worksheets("Calculator").Columns("A:E"), 5, False)
        ws2.Cells(i, 4) = Application.VLookup(Cells(i, 1), Worksheets("Calculator").Columns("A:B"), 2, False)
        ws2.Cells(i, 5) = Application.VLookup(Cells(i, 1), Worksheets("Calculator").Columns("A:C"), 3, False)

    End If
Next i

Checkboxes in web pages – how to make them bigger?

I'm writtinga phonegap app, and checkboxes vary in size, look, etc. So I made my own simple checkbox:

First the HTML code:

<span role="checkbox"/>

Then the CSS:

[role=checkbox]{
    background-image: url(../img/checkbox_nc.png);
    height: 15px;
    width: 15px;
    display: inline-block;
    margin: 0 5px 0 5px;
    cursor: pointer;
}

.checked[role=checkbox]{
    background-image: url(../img/checkbox_c.png);
}

To toggle checkbox state, I used JQuery:

CLICKEVENT='touchend';
function createCheckboxes()
{
    $('[role=checkbox]').bind(CLICKEVENT,function()
    {
        $(this).toggleClass('checked');
    });
}

But It can easily be done without it...

Hope it can help!

Setting UILabel text to bold

Use attributed string:

// Define attributes
let labelFont = UIFont(name: "HelveticaNeue-Bold", size: 18)
let attributes :Dictionary = [NSFontAttributeName : labelFont]

// Create attributed string
var attrString = NSAttributedString(string: "Foo", attributes:attributes)
label.attributedText = attrString

You need to define attributes.

Using attributed string you can mix colors, sizes, fonts etc within one text

Matplotlib transparent line plots

Plain and simple:

plt.plot(x, y, 'r-', alpha=0.7)

(I know I add nothing new, but the straightforward answer should be visible).

Rails - passing parameters in link_to

link_to "+ Service", controller_action_path(:account_id => acct.id)

If it is still not working check the path:

$ rake routes

"Too many characters in character literal error"

You cannot treat == or || as chars, since they are not chars, but a sequence of chars.

You could make your switch...case work on strings instead.

Editing the date formatting of x-axis tick labels in matplotlib

From the package matplotlib.dates as shown in this example the date format can be applied to the axis label and ticks for plot.

Below I have given an example for labeling axis ticks for multiplots

import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import pandas as pd

df = pd.read_csv('US_temp.csv')
plt.plot(df['Date'],df_f['MINT'],label='Min Temp.')
plt.plot(df['Date'],df_f['MAXT'],label='Max Temp.')
plt.legend()
####### Use the below functions #######
dtFmt = mdates.DateFormatter('%b') # define the formatting
plt.gca().xaxis.set_major_formatter(dtFmt) # apply the format to the desired axis
plt.show()

As simple as that

Invalid character in identifier

Not sure this is right on but when i copied some code form a paper on using pgmpy and pasted it into the editor under Spyder, i kept getting the "invalid character in identifier" error though it didn't look bad to me. The particular line was grade_cpd = TabularCPD(variable='G',\

For no good reason I replaced the ' with " throughout the code and it worked. Not sure why but it did work

Regular expression for only characters a-z, A-Z

/^[a-zA-Z]+$/ 

Off the top of my head.

Edit:

Or if you don't like the weird looking literal syntax you can do it like this

new RegExp("^[a-zA-Z]+$");

How to post data using HttpClient?

Try to use this:

using (var handler = new HttpClientHandler() { CookieContainer = new CookieContainer() })
{
    using (var client = new HttpClient(handler) { BaseAddress = new Uri("site.com") })
    {
        //add parameters on request
        var body = new List<KeyValuePair<string, string>>
        {
            new KeyValuePair<string, string>("test", "test"),
            new KeyValuePair<string, string>("test1", "test1")
        };

        HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, "site.com");

        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/x-www-form-urlencoded; charset=UTF-8"));
        client.DefaultRequestHeaders.Add("Upgrade-Insecure-Requests", "1");
        client.DefaultRequestHeaders.Add("X-Requested-With", "XMLHttpRequest");
        client.DefaultRequestHeaders.Add("X-MicrosoftAjax", "Delta=true");
        //client.DefaultRequestHeaders.Add("Accept", "*/*");

        client.Timeout = TimeSpan.FromMilliseconds(10000);

        var res = await client.PostAsync("", new FormUrlEncodedContent(body));

        if (res.IsSuccessStatusCode)
        {
            var exec = await res.Content.ReadAsStringAsync();
            Console.WriteLine(exec);
        }                    
    }
}

Angular 4.3 - HttpClient set params

HttpParams is intended to be immutable. The set and append methods don't modify the existing instance. Instead they return new instances, with the changes applied.

let params = new HttpParams().set('aaa', 'A');    // now it has aaa
params = params.set('bbb', 'B');                  // now it has both

This approach works well with method chaining:

const params = new HttpParams()
  .set('one', '1')
  .set('two', '2');

...though that might be awkward if you need to wrap any of them in conditions.

Your loop works because you're grabbing a reference to the returned new instance. The code you posted that doesn't work, doesn't. It just calls set() but doesn't grab the result.

let httpParams = new HttpParams().set('aaa', '111'); // now it has aaa
httpParams.set('bbb', '222');                        // result has both but is discarded

java.lang.ClassNotFoundException: org.eclipse.core.runtime.adaptor.EclipseStarter

Just copying the content of the zip-file to its prefered location from the zip-file will give you this error when you attempt to run the only executable that is visible in the archive. It is named similarly but it is not the real thing.

You should let the archive extract itself to make the installation complete correctly. Doing so gives you an executable named eclipse.exe with which you will not get this error.

New features in java 7

The following list contains links to the the enhancements pages in the Java SE 7.

Swing
IO and New IO
Networking
Security
Concurrency Utilities
Rich Internet Applications (RIA)/Deployment
    Requesting and Customizing Applet Decoration in Dragg able Applets
    Embedding JNLP File in Applet Tag
    Deploying without Codebase
    Handling Applet Initialization Status with Event Handlers
Java 2D
Java XML – JAXP, JAXB, and JAX-WS
Internationalization
java.lang Package
    Multithreaded Custom Class Loaders in Java SE 7
Java Programming Language
    Binary Literals
    Strings in switch Statements
    The try-with-resources Statement
    Catching Multiple Exception Types and Rethrowing Exceptions with Improved Type Checking
    Underscores in Numeric Literals
    Type Inference for Generic Instance Creation
    Improved Compiler Warnings and Errors When Using Non-Reifiable Formal Parameters with Varargs Methods
Java Virtual Machine (JVM)
    Java Virtual Machine Support for Non-Java Languages
    Garbage-First Collector
    Java HotSpot Virtual Machine Performance Enhancements
JDBC

Reference 1 Reference 2

Executing <script> elements inserted with .innerHTML

scriptNode.innerHTML = code didn't work for IE. The only thing to do is replace with scriptNode.text = code and it work fine

Caused by: org.flywaydb.core.api.FlywayException: Validate failed. Migration Checksum mismatch for migration 2

There are 3 ways to solve this issue while development. Any one from below can solve this issue.
1) provide the changes in new migration sql file with incrementing version
2) change the schema name in db url we provide
datasource.flyway.url=jdbc:h2:file:~/cart3
datasource.flyway.url=jdbc:h2:file:~/cart4
3) delete the .mv and .trace files in users home directory
ex: cart3.mv and cart3.trace under c://users/username/

XPath - Difference between node() and text()

Select the text of all items under produce:

//produce/item/text()

Select all the manager nodes in all departments:

//department/*

Drop Down Menu/Text Field in one

I'd like to add a jQuery autocomplete based solution that does the job.

Step 1: Make the list fixed height and scrollable

Get the code from https://jqueryui.com/autocomplete/ "Scrollable" example, setting max height to the list of results so it behaves as a select box.

Step 2: Open the list on focus:

Display jquery ui auto-complete list on focus event

Step 3: Set minimum chars to 0 so it opens no matter how many chars are in the input

Final result:

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>jQuery UI Autocomplete - Scrollable results</title>
  <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
  <link rel="stylesheet" href="/resources/demos/style.css">
  <style>
  .ui-autocomplete {
    max-height: 100px;
    overflow-y: auto;
    /* prevent horizontal scrollbar */
    overflow-x: hidden;
  }
  /* IE 6 doesn't support max-height
   * we use height instead, but this forces the menu to always be this tall
   */
  * html .ui-autocomplete {
    height: 100px;
  }
  </style>
  <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
  <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
  <script>
  $( function() {
    var availableTags = [
      "ActionScript",
      "AppleScript",
      "Asp",
      "BASIC",
      "C",
      "C++",
      "Clojure",
      "COBOL",
      "ColdFusion",
      "Erlang",
      "Fortran",
      "Groovy",
      "Haskell",
      "Java",
      "JavaScript",
      "Lisp",
      "Perl",
      "PHP",
      "Python",
      "Ruby",
      "Scala",
      "Scheme"
    ];
    $( "#tags" ).autocomplete({
//      source: availableTags, // uncomment this and comment the following to have normal autocomplete behavior
      source: function (request, response) {
          response( availableTags);
      },
      minLength: 0
    }).focus(function(){
//        $(this).data("uiAutocomplete").search($(this).val()); // uncomment this and comment the following to have autocomplete behavior when opening
        $(this).data("uiAutocomplete").search('');
    });
  } );
  </script>
</head>
<body>

<div class="ui-widget">
  <label for="tags">Tags: </label>
  <input id="tags">
</div>


</body>
</html>

Check jsfiddle here:

https://jsfiddle.net/bao7fhm3/1/

Mysql database sync between two databases

three different approaches:

  1. Classic client/server approach: don't put any database in the shops; simply have the applications access your server. Of course it's better if you set a VPN, but simply wrapping the connection in SSL or ssh is reasonable. Pro: it's the way databases were originally thought. Con: if you have high latency, complex operations could get slow, you might have to use stored procedures to reduce the number of round trips.

  2. replicated master/master: as @Book Of Zeus suggested. Cons: somewhat more complex to setup (especially if you have several shops), breaking in any shop machine could potentially compromise the whole system. Pros: better responsivity as read operations are totally local and write operations are propagated asynchronously.

  3. offline operations + sync step: do all work locally and from time to time (might be once an hour, daily, weekly, whatever) write a summary with all new/modified records from the last sync operation and send to the server. Pros: can work without network, fast, easy to check (if the summary is readable). Cons: you don't have real-time information.

Regular Expression to match only alphabetic characters

This will match one or more alphabetical characters:

/^[a-z]+$/

You can make it case insensitive using:

/^[a-z]+$/i

or:

/^[a-zA-Z]+$/

How do you convert WSDLs to Java classes using Eclipse?

I wouldn't suggest using the Eclipse tool to generate the WS Client because I had bad experience with it:

I am not really sure if this matters but I had to consume a WS written in .NET. When I used the Eclipse's "New Web Service Client" tool it generated the Java classes using Axis (version 1.x) which as you can check is old (last version from 2006). There is a newer version though that is has some major changes but Eclipse doesn't use it.

Why the old version of Axis matters you'll say? Because when using OpenJDK you can run into some problems like missing cryptography algorithms in OpenJDK that are presented in the Oracle's JDK and some libraries like this one depend on them.

So I just used the wsimport tool and ended my headaches.

How to get Map data using JDBCTemplate.queryForMap

queryForMap is appropriate if you want to get a single row. You are selecting without a where clause, so you probably want to queryForList. The error is probably indicative of the fact that queryForMap wants one row, but you query is retrieving many rows.

Check out the docs. There is a queryForList that takes just sql; the return type is a

List<Map<String,Object>>.

So once you have the results, you can do what you are doing. I would do something like

List results = template.queryForList(sql);

for (Map m : results){
   m.get('userid');
   m.get('username');
} 

I'll let you fill in the details, but I would not iterate over keys in this case. I like to explicit about what I am expecting.

If you have a User object, and you actually want to load User instances, you can use the queryForList that takes sql and a class type

queryForList(String sql, Class<T> elementType)

(wow Spring has changed a lot since I left Javaland.)

Hide Command Window of .BAT file that Executes Another .EXE File

Compile the batch file to an executable using Batch2Exe http://www.f2ko.de/programs.php?lang=en&pid=b2e. Use the "Invisible Window" option.

How do I get the total number of unique pairs of a set in the database?

This is how you can approach these problems in general on your own:

The first of the pair can be picked in N (=100) ways. You don't want to pick this item again, so the second of the pair can be picked in N-1 (=99) ways. In total you can pick 2 items out of N in N(N-1) (= 100*99=9900) different ways.

But hold on, this way you count also different orderings: AB and BA are both counted. Since every pair is counted twice you have to divide N(N-1) by two (the number of ways that you can order a list of two items). The number of subsets of two that you can make with a set of N is then N(N-1)/2 (= 9900/2 = 4950).

Running an executable in Mac Terminal

To run an executable in mac

1). Move to the path of the file:

cd/PATH_OF_THE_FILE

2). Run the following command to set the file's executable bit using the chmod command:

chmod +x ./NAME_OF_THE_FILE

3). Run the following command to execute the file:

./NAME_OF_THE_FILE

Once you have run these commands, going ahead you just have to run command 3, while in the files path.

conversion from infix to prefix

(a–b)/c*(d + e – f / g)

Prefix notation (reverse polish has the operator last, it is unclear which one you meant, but the principle will be exactly the same):

  1. (/ f g)
  2. (+ d e)
  3. (- (+ d e) (/ f g))
  4. (- a b)
  5. (/ (- a b) c)
  6. (* (/ (- a b) c) (- (+ d e) (/ f g)))

Programmatically Hide/Show Android Soft Keyboard

Adding this to your code android:focusableInTouchMode="true" will make sure that your keypad doesn't appear on startup for your edittext box. You want to add this line to your linear layout that contains the EditTextBox. You should be able to play with this to solve both your problems. I have tested this. Simple solution.

ie: In your app_list_view.xml file

<LinearLayout 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent" 
    android:orientation="vertical" 
    android:focusableInTouchMode="true">
    <EditText 
        android:id="@+id/filter_edittext"       
        android:layout_width="fill_parent" 
        android:layout_height="wrap_content" 
        android:hint="Search" 
        android:inputType="text" 
        android:maxLines="1"/>
    <ListView 
        android:id="@id/android:list" 
        android:layout_height="fill_parent"
        android:layout_weight="1.0" 
        android:layout_width="fill_parent" 
        android:focusable="true" 
        android:descendantFocusability="beforeDescendants"/>
</LinearLayout> 

------------------ EDIT: To Make keyboard appear on startup -----------------------

This is to make they Keyboard appear on the username edittextbox on startup. All I've done is added an empty Scrollview to the bottom of the .xml file, this puts the first edittext into focus and pops up the keyboard. I admit this is a hack, but I am assuming you just want this to work. I've tested it, and it works fine.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:orientation="vertical" 
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:paddingLeft="20dip"  
    android:paddingRight="20dip">
    <EditText 
        android:id="@+id/userName" 
        android:singleLine="true" 
        android:layout_width="fill_parent"  
        android:layout_height="wrap_content" 
        android:hint="Username"  
        android:imeOptions="actionDone" 
        android:inputType="text"
        android:maxLines="1"
       />
    <EditText 
        android:id="@+id/password" 
        android:password="true" 
        android:singleLine="true"  
        android:layout_width="fill_parent" 
        android:layout_height="wrap_content" 
        android:hint="Password" />
    <ScrollView
        android:id="@+id/ScrollView01"  
        android:layout_height="fill_parent"   
        android:layout_width="fill_parent"> 
    </ScrollView>
</LinearLayout>

If you are looking for a more eloquent solution, I've found this question which might help you out, it is not as simple as the solution above but probably a better solution. I haven't tested it but it apparently works. I think it is similar to the solution you've tried which didn't work for you though.

Hope this is what you are looking for.

Cheers!

Measure the time it takes to execute a t-sql query

DECLARE @StartTime datetime
DECLARE @EndTime datetime
SELECT @StartTime=GETDATE() 

 -- Write Your Query


SELECT @EndTime=GETDATE()

--This will return execution time of your query
SELECT DATEDIFF(MS,@StartTime,@EndTime) AS [Duration in millisecs]

You can also See this solution

Import Certificate to Trusted Root but not to Personal [Command Line]

If there are multiple certificates in a pfx file (key + corresponding certificate and a CA certificate) then this command worked well for me:

certutil -importpfx c:\somepfx.pfx this works but still a password is needed to be typed in manually for private key. Including -p and "password" cause error too many arguments for certutil on XP

Spring MVC: How to return image in @ResponseBody?

In addition to registering a ByteArrayHttpMessageConverter, you may want to use a ResponseEntity instead of @ResponseBody. The following code works for me :

@RequestMapping("/photo2")
public ResponseEntity<byte[]> testphoto() throws IOException {
    InputStream in = servletContext.getResourceAsStream("/images/no_image.jpg");

    final HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.IMAGE_PNG);

    return new ResponseEntity<byte[]>(IOUtils.toByteArray(in), headers, HttpStatus.CREATED);
}

How to index an element of a list object in R

Indexing a list is done using double bracket, i.e. hypo_list[[1]] (e.g. have a look here: http://www.r-tutor.com/r-introduction/list). BTW: read.table does not return a table but a dataframe (see value section in ?read.table). So you will have a list of dataframes, rather than a list of table objects. The principal mechanism is identical for tables and dataframes though.

Note: In R, the index for the first entry is a 1 (not 0 like in some other languages).

Dataframes

l <- list(anscombe, iris)   # put dfs in list
l[[1]]             # returns anscombe dataframe

anscombe[1:2, 2]   # access first two rows and second column of dataset
[1] 10  8

l[[1]][1:2, 2]     # the same but selecting the dataframe from the list first
[1] 10  8

Table objects

tbl1 <- table(sample(1:5, 50, rep=T))
tbl2 <- table(sample(1:5, 50, rep=T))
l <- list(tbl1, tbl2)  # put tables in a list

tbl1[1:2]              # access first two elements of table 1 

Now with the list

l[[1]]                 # access first table from the list

1  2  3  4  5 
9 11 12  9  9 

l[[1]][1:2]            # access first two elements in first table

1  2 
9 11 

Date to milliseconds and back to date in Swift

Unless you absolutely have to convert the date to an integer, consider using a Double instead to represent the time interval. After all, this is the type that timeIntervalSince1970 returns. All of the answers that convert to integers loose sub-millisecond precision, but this solution is much more accurate (although you will still lose some precision due to floating-point imprecision).

public extension Date {
    
    /// The interval, in milliseconds, between the date value and
    /// 00:00:00 UTC on 1 January 1970.
    /// Equivalent to `self.timeIntervalSince1970 * 1000`.
    var millisecondsSince1970: Double {
        return self.timeIntervalSince1970 * 1000
    }

    /**
     Creates a date value initialized relative to 00:00:00 UTC
     on 1 January 1970 by a given number of **milliseconds**.
     
     equivalent to
     ```
     self.init(timeIntervalSince1970: TimeInterval(milliseconds) / 1000)
     ```
     - Parameter millisecondsSince1970: A time interval in milliseconds.
     */
    init(millisecondsSince1970: Double) {
        self.init(timeIntervalSince1970: TimeInterval(milliseconds) / 1000)
    }

}

How to remove an item from an array in AngularJS scope?

To remove a element from scope use:

// remove an item
    $scope.remove = function(index) {
        $scope.items.splice(index, 1);
    };

From enter link description here

How to quickly clear a JavaScript Object?

You can try this. Function below sets all values of object's properties to undefined. Works as well with nested objects.

var clearObjectValues = (objToClear) => {
    Object.keys(objToClear).forEach((param) => {
        if ( (objToClear[param]).toString() === "[object Object]" ) {
            clearObjectValues(objToClear[param]);
        } else {
            objToClear[param] = undefined;
        }
    })
    return objToClear;
};

Get restaurants near my location

Is this what you are looking for?

https://maps.googleapis.com/maps/api/place/search/xml?location=49.260691,-123.137784&radius=500&sensor=false&key=*PlacesAPIKey*&types=restaurant

types is optional

Add a column to a table, if it does not already exist

When checking for a column in another database, you can simply include the database name:

IF NOT EXISTS (
  SELECT * 
  FROM   DatabaseName.sys.columns 
  WHERE  object_id = OBJECT_ID(N'[DatabaseName].[dbo].[TableName]') 
         AND name = 'ColumnName'
)

Moment.js - tomorrow, today and yesterday

So this is what I ended up doing

var dateText = moment(someDate).from(new Date());
var startOfToday = moment().startOf('day');
var startOfDate = moment(someDate).startOf('day');
var daysDiff = startOfDate.diff(startOfToday, 'days');
var days = {
  '0': 'today',
  '-1': 'yesterday',
  '1': 'tomorrow'
};

if (Math.abs(daysDiff) <= 1) {
  dateText = days[daysDiff];
}

Could not extract response: no suitable HttpMessageConverter found for response type

Since you return to the client just String and its content type == 'text/plain', there is no any chance for default converters to determine how to convert String response to the FFSampleResponseHttp object.

The simple way to fix it:

  • remove expected-response-type from <int-http:outbound-gateway>
  • add to the replyChannel1 <json-to-object-transformer>

Otherwise you should write your own HttpMessageConverter to convert the String to the appropriate object.

To make it work with MappingJackson2HttpMessageConverter (one of default converters) and your expected-response-type, you should send your reply with content type = 'application/json'.

If there is a need, just add <header-enricher> after your <service-activator> and before sending a reply to the <int-http:inbound-gateway>.

So, it's up to you which solution to select, but your current state doesn't work, because of inconsistency with default configuration.

UPDATE

OK. Since you changed your server to return FfSampleResponseHttp object as HTTP response, not String, just add contentType = 'application/json' header before sending the response for the HTTP and MappingJackson2HttpMessageConverter will do the stuff for you - your object will be converted to JSON and with correct contentType header.

From client side you should come back to the expected-response-type="com.mycompany.MyChannel.model.FFSampleResponseHttp" and MappingJackson2HttpMessageConverter should do the stuff for you again.

Of course you should remove <json-to-object-transformer> from you message flow after <int-http:outbound-gateway>.

How to get phpmyadmin username and password

I had a problem with this. I didn't even create any passwords so I was confused. I googled it and I found out that I should just write root as username and than click GO. I hope it helps.

How to keep an iPhone app running on background fully operational

Depends what it does. If your app takes up too much memory, or makes calls to functions/classes it shouldn't, SpringBoard may terminate it. However, it will most likely be rejected by Apple, as it does not follow their 7 background uses.

How to use WPF Background Worker

using System;  
using System.ComponentModel;   
using System.Threading;    
namespace BackGroundWorkerExample  
{   
    class Program  
    {  
        private static BackgroundWorker backgroundWorker;  

        static void Main(string[] args)  
        {  
            backgroundWorker = new BackgroundWorker  
            {  
                WorkerReportsProgress = true,  
                WorkerSupportsCancellation = true  
            };  

            backgroundWorker.DoWork += backgroundWorker_DoWork;  
            //For the display of operation progress to UI.    
            backgroundWorker.ProgressChanged += backgroundWorker_ProgressChanged;  
            //After the completation of operation.    
            backgroundWorker.RunWorkerCompleted += backgroundWorker_RunWorkerCompleted;  
            backgroundWorker.RunWorkerAsync("Press Enter in the next 5 seconds to Cancel operation:");  

            Console.ReadLine();  

            if (backgroundWorker.IsBusy)  
            { 
                backgroundWorker.CancelAsync();  
                Console.ReadLine();  
            }  
        }  

        static void backgroundWorker_DoWork(object sender, DoWorkEventArgs e)  
        {  
            for (int i = 0; i < 200; i++)  
            {  
                if (backgroundWorker.CancellationPending)  
                {  
                    e.Cancel = true;  
                    return;  
                }  

                backgroundWorker.ReportProgress(i);  
                Thread.Sleep(1000);  
                e.Result = 1000;  
            }  
        }  

        static void backgroundWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)  
        {  
            Console.WriteLine("Completed" + e.ProgressPercentage + "%");  
        }  

        static void backgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)  
        {  

            if (e.Cancelled)  
            {  
                Console.WriteLine("Operation Cancelled");  
            }  
            else if (e.Error != null)  
            {  
                Console.WriteLine("Error in Process :" + e.Error);  
            }  
            else  
            {  
                Console.WriteLine("Operation Completed :" + e.Result);  
            }  
        }  
    }  
} 

Also, referr the below link you will understand the concepts of Background:

http://www.c-sharpcorner.com/UploadFile/1c8574/threads-in-wpf/

What is the quickest way to HTTP GET in Python?

Excellent solutions Xuan, Theller.

For it to work with python 3 make the following changes

import sys, urllib.request

def reporthook(a, b, c):
    print ("% 3.1f%% of %d bytes\r" % (min(100, float(a * b) / c * 100), c))
    sys.stdout.flush()
for url in sys.argv[1:]:
    i = url.rfind("/")
    file = url[i+1:]
    print (url, "->", file)
    urllib.request.urlretrieve(url, file, reporthook)
print

Also, the URL you enter should be preceded by a "http://", otherwise it returns a unknown url type error.

pod install -bash: pod: command not found

Try this:

sudo gem install cocoapods -V

and you must update gem to the newest release using this:

sudo gem update --system 

if you want to enjoy the fast responce :)

How do I use raw_input in Python 3

This works in Python 3.x and 2.x:

# Fix Python 2.x.
try: input = raw_input
except NameError: pass
print("Hi " + input("Say something: "))

Is there any difference between DECIMAL and NUMERIC in SQL Server?

They are exactly the same. When you use it be consistent. Use one of them in your database

Google.com and clients1.google.com/generate_204

This documents explains:

http://docs.lib.purdue.edu/cgi/viewcontent.cgi?article=1417&context=ecetr&sei-redir=1

(Search for generate204)

Relevant section:

Among the different objects, a javascript function triggers a generate204 request sent to the video server that is supposed to serve the video. This starts the video prefetch, which has two main goals: first, it forces the client to perform the DNS resolution of the video server name. Second, it forces the client to open a TCP connection toward the video server. Both help to speed-up the video download phase.

In addition, the generate204 request has exactly the same format and options of the real video download request, so that the video server is eventually warned that a client will possibly download that video very soon. Note that the video server replies with a 204 No Content response, as implied by the command, and no video content is downloaded so far.

Is there a typical state machine implementation pattern?

There is a book titled Practical Statecharts in C/C++. However, it is way too heavyweight for what we need.

How to manually install a pypi module without pip/easy_install?

  1. Download the package
  2. unzip it if it is zipped
  3. cd into the directory containing setup.py
  4. If there are any installation instructions contained in documentation contianed herein, read and follow the instructions OTHERWISE
  5. type in python setup.py install

You may need administrator privileges for step 5. What you do here thus depends on your operating system. For example in Ubuntu you would say sudo python setup.py install

EDIT- thanks to kwatford (see first comment)

To bypass the need for administrator privileges during step 5 above you may be able to make use of the --user flag. In this way you can install the package only for the current user.

The docs say:

Files will be installed into subdirectories of site.USER_BASE (written as userbase hereafter). This scheme installs pure Python modules and extension modules in the same location (also known as site.USER_SITE). Here are the values for UNIX, including Mac OS X:

More details can be found here: http://docs.python.org/2.7/install/index.html

Favicon: .ico or .png / correct tags?

I know this is an old question.

Here's another option - attending to different platform requirements - Source

<link rel='shortcut icon' type='image/vnd.microsoft.icon' href='/favicon.ico'> <!-- IE -->
<link rel='apple-touch-icon' type='image/png' href='/icon.57.png'> <!-- iPhone -->
<link rel='apple-touch-icon' type='image/png' sizes='72x72' href='/icon.72.png'> <!-- iPad -->
<link rel='apple-touch-icon' type='image/png' sizes='114x114' href='/icon.114.png'> <!-- iPhone4 -->
<link rel='icon' type='image/png' href='/icon.114.png'> <!-- Opera Speed Dial, at least 144×114 px -->

This is the broadest approach I have found so far.

Ultimately the decision depends on your own needs. Ask yourself, who is your target audience?

UPDATE May 27, 2018: As expected, time goes by and things change. But there's good news too. I found a tool called Real Favicon Generator that generates all the required lines for the icon to work on all modern browsers and platforms. It doesn't handle backwards compatibility though.

Archive the artifacts in Jenkins

Also, does Jenkins delete the artifacts after each build ? (not the archived artifacts, I know I can tell it to delete those)

No, Hudson/Jenkins does not, by itself, clear the workspace after a build. You might have actions in your build process that erase, overwrite, or move build artifacts from where you left them. There is an option in the job configuration, in Advanced Project Options (which must be expanded), called "Clean workspace before build" that will wipe the workspace at the beginning of a new build.

Textarea onchange detection

Keyup should suffice if paired with HTML5 input validation/pattern attribute. So, create a pattern (regex) to validate the input and act upon the .checkValidity() status. Something like below could work. In your case you would want a regex to match length. My solution is in use / demo-able online here.

<input type="text" pattern="[a-zA-Z]+" id="my-input">

var myInput = document.getElementById = "my-input";

myInput.addEventListener("keyup", function(){
  if(!this.checkValidity() || !this.value){
    submitButton.disabled = true;
  } else {
    submitButton.disabled = false;
  }
});

Python3: ImportError: No module named '_ctypes' when using Value from module multiprocessing

I run into this error when I tried to install Python 3.7.3 in Ubuntu 18.04 with next command: $ pyenv install 3.7.3. Installation succeeded after running $ sudo apt-get update && sudo apt-get install libffi-dev (as suggested here). The issue was solved there.

Foreach value from POST from form

Use array-like fields:

<input name="name_for_the_items[]"/>

You can loop through the fields:

foreach($_POST['name_for_the_items'] as $item)
{
  //do something with $item
}

Skip a submodule during a Maven build

there is now (from 1.1.1 version) a 'skip' flag in pit.

So you can do things like :

    <profile>
        <id>pit</id>
        <build>
            <plugins>
                <plugin>
                    <groupId>org.pitest</groupId>
                    <artifactId>pitest-maven</artifactId>
                    <configuration>
                        <skip>true</skip>
                    </configuration>
                </plugin>
            </plugins>
        </build>
    </profile>

in your module, and pit will skip

[INFO] --- pitest-maven:1.1.3:mutationCoverage (default-cli) @ module-selenium --- [INFO] Skipping project

node.js, socket.io with SSL

If your server certificated file is not trusted, (for example, you may generate the keystore by yourself with keytool command in java), you should add the extra option rejectUnauthorized

var socket = io.connect('https://localhost', {rejectUnauthorized: false});

How can I deploy an iPhone application from Xcode to a real iPhone device?

It sounds like the application isn't signed. Download ldid from Cydia and then use it like so: ldid -S /Applications/AccelerometerGraph.app/AccelerometerGraph

Also be sure that the binary is marked as executable: chmod +x /Applications/AccelerometerGraph.app/AccelerometerGraph

Command Line Tools not working - OS X El Capitan, Sierra, High Sierra, Mojave

After update to macOS 10.13.3

After updating do macOS 10.13, I had to install "Command Line Tools (macOS 10.13) for Xcode 9.3" downloaded from https://developer.apple.com/download/more/

Linux configure/make, --prefix?

Do configure --help and see what other options are available.

It is very common to provide different options to override different locations. By standard, --prefix overrides all of them, so you need to override config location after specifying the prefix. This course of actions usually works for every automake-based project.

The worse case scenario is when you need to modify the configure script, or even worse, generated makefiles and config.h headers. But yeah, for Xfce you can try something like this:

./configure --prefix=/home/me/somefolder/mybuild/output/target --sysconfdir=/etc 

I believe that should do it.

Insert new column into table in sqlite?

SQLite has limited ALTER TABLE support that you can use to add a column to the end of a table or to change the name of a table.

If you want to make more complex changes in the structure of a table, you will have to recreate the table. You can save existing data to a temporary table, drop the old table, create the new table, then copy the data back in from the temporary table.

For example, suppose you have a table named "t1" with columns names "a" and "c" and that you want to insert column "b" from this table. The following steps illustrate how this could be done:

BEGIN TRANSACTION;
CREATE TEMPORARY TABLE t1_backup(a,c);
INSERT INTO t1_backup SELECT a,c FROM t1;
DROP TABLE t1;
CREATE TABLE t1(a,b, c);
INSERT INTO t1 SELECT a,c FROM t1_backup;
DROP TABLE t1_backup;
COMMIT;

Now you are ready to insert your new data like so:

UPDATE t1 SET b='blah' WHERE a='key'

Getting the 'external' IP address in Java

http://jstun.javawi.de/ will do it - provided your gateway device does STUN )most do)

Animation CSS3: display + opacity

If you are triggering the change with JS, let's say on click, there is a nice workaround.

You see, the problem happens because the animation is ignored on display:none element but browser applies all the changes at once and the element is never display:block while not animated at the same time.

The trick is to ask the browser to render the frame after changing the visibility but before triggering the animation.

Here is a JQuery example:

    $('.child').css({"display":"block"});
    //now ask the browser what is the value of the display property
    $('.child').css("display"); //this will trigger the browser to apply the change. this costs one frame render
    //now a change to opacity will trigger the animation
    $('.child').css("opacity":100);

How to install beautiful soup 4 with python 2.7 on windows

easy_install BeautifulSoup4

or

easy_install BeautifulSoup 

to install easy_install

http://pypi.python.org/pypi/setuptools#files

String to char array Java

A string to char array is as simple as

String str = "someString"; 
char[] charArray = str.toCharArray();

Can you explain a little more on what you are trying to do?

* Update *

if I am understanding your new comment, you can use a byte array and example is provided.

byte[] bytes = ByteBuffer.allocate(4).putInt(1695609641).array();

for (byte b : bytes) {
   System.out.format("0x%x ", b);
}

With the following output

0x65 0x10 0xf3 0x29

uncaught syntaxerror unexpected token U JSON

Well, to all who actually can't find the error anywhere in your code, neither "undefined as it says in local storage nor null"..simply just comment out your code and write another one that actually removes the item in local storage ..after that ,u can comment or delet the current code and reset again the previous one by simply uncommenting it out (if u dint delet t ...if u did u can write it again:))

LocalStorage.setItem('Previous' , "removeprevious");  


LocalStorage.removeItem('Previous');   
 Console.log(LocalStorage.getItem('Previous'));

Console will show null and that it ..reset your code again if t doesn't work, dude!you got errors.

sorry for my English!

On Selenium WebDriver how to get Text from Span Tag

String kk = wd.findElement(By.xpath(//*[@id='customSelect_3']/div[1]/span));

kk.getText().toString();

System.out.println(+kk.getText().toString());

MySQL SELECT statement for the "length" of the field is greater than 1

Try:

SELECT
    *
FROM
    YourTable
WHERE
    CHAR_LENGTH(Link) > x

Android overlay a view ontop of everything?

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/root_view"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >

<LinearLayout
    android:id = "@+id/Everything"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >
    <!-- other actual layout stuff here EVERYTHING HERE -->

   </LinearLayout>

<LinearLayout
    android:id="@+id/overlay"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="right" >
</LinearLayout>

Now any view you add under LinearLayout with android:id = "@+id/overlay" will appear as overlay with gravity = right on Linear Layout with android:id="@+id/Everything"

How do I execute a string containing Python code in Python?

For statements, use exec(string) (Python 2/3) or exec string (Python 2):

>>> mycode = 'print "hello world"'
>>> exec(mycode)
Hello world

When you need the value of an expression, use eval(string):

>>> x = eval("2+2")
>>> x
4

However, the first step should be to ask yourself if you really need to. Executing code should generally be the position of last resort: It's slow, ugly and dangerous if it can contain user-entered code. You should always look at alternatives first, such as higher order functions, to see if these can better meet your needs.

How can I create Min stl priority_queue?

Use std::greater as the comparison function:

std::priority_queue<int, std::vector<int>, std::greater<int> > my_min_heap;

How to select rows in a DataFrame between two values, in Python Pandas?

Consider also series between:

df = df[df['closing_price'].between(99, 101)]

Core dump file analysis

Steps to debug coredump using GDB:

Some generic help:

gdb start GDB, with no debugging les

gdb program begin debugging program

gdb program core debug coredump core produced by program

gdb --help describe command line options

  1. First of all, find the directory where the corefile is generated.

  2. Then use ls -ltr command in the directory to find the latest generated corefile.

  3. To load the corefile use

    gdb binary path of corefile
    

    This will load the corefile.

  4. Then you can get the information using the bt command.

    For a detailed backtrace use bt full.

  5. To print the variables, use print variable-name or p variable-name

  6. To get any help on GDB, use the help option or use apropos search-topic

  7. Use frame frame-number to go to the desired frame number.

  8. Use up n and down n commands to select frame n frames up and select frame n frames down respectively.

  9. To stop GDB, use quit or q.

Pass in an enum as a method parameter

If you want to pass in the value to use, you have to use the enum type you declared and directly use the supplied value:

public string CreateFile(string id, string name, string description,
              /* --> */  SupportedPermissions supportedPermissions)
{
    file = new File
    {  
        Name = name,
        Id = id,
        Description = description,
        SupportedPermissions = supportedPermissions // <---
    };

    return file.Id;
}

If you instead want to use a fixed value, you don't need any parameter at all. Instead, directly use the enum value. The syntax is similar to a static member of a class:

public string CreateFile(string id, string name, string description) // <---
{
    file = new File
    {  
        Name = name,
        Id = id,
        Description = description,
        SupportedPermissions = SupportedPermissions.basic // <---
    };

    return file.Id;
}

How can I compile and run c# program without using visual studio?

I use a batch script to compile and run C#:

C:\Windows\Microsoft.NET\Framework\v4.0.30319\csc /out:%1 %2

@echo off

if errorlevel 1 (
    pause
    exit
)

start %1 %1

I call it like this:

C:\bin\csc.bat "C:\code\MyProgram.exe" "C:\code\MyProgram.cs"

I also have a shortcut in Notepad++, which you can define by going to Run > Run...:

C:\bin\csc.bat "$(CURRENT_DIRECTORY)\$(NAME_PART).exe" "$(FULL_CURRENT_PATH)"

I assigned this shortcut to my F5 key for maximum laziness.

Get the previous month's first and last day dates in c#

This is a take on Mike W's answer:

internal static DateTime GetPreviousMonth(bool returnLastDayOfMonth)
{
    DateTime firstDayOfThisMonth = DateTime.Today.AddDays( - ( DateTime.Today.Day - 1 ) );
    DateTime lastDayOfLastMonth = firstDayOfThisMonth.AddDays (-1);
    if (returnLastDayOfMonth) return lastDayOfLastMonth;
    return firstDayOfThisMonth.AddMonths(-1);
}

You can call it like so:

dateTimePickerFrom.Value = GetPreviousMonth(false);
dateTimePickerTo.Value = GetPreviousMonth(true);

JavaScript override methods

the method modify() that you called in the last is called in global context if you want to override modify() you first have to inherit A or B.

Maybe you're trying to do this:

In this case C inherits A

function A() {
    this.modify = function() {
        alert("in A");
    }
}

function B() {
    this.modify = function() {
        alert("in B");
    }
}

C = function() {
    this.modify = function() {
        alert("in C");
    };

    C.prototype.modify(); // you can call this method where you need to call modify of the parent class
}

C.prototype = new A();

How to find out if an item is present in a std::vector?

As others have said, use the STL find or find_if functions. But if you are searching in very large vectors and this impacts performance, you may want to sort your vector and then use the binary_search, lower_bound, or upper_bound algorithms.

How do I copy the contents of one stream to another?

I use the following extension methods. They have optimized overloads for when one stream is a MemoryStream.

    public static void CopyTo(this Stream src, Stream dest)
    {
        int size = (src.CanSeek) ? Math.Min((int)(src.Length - src.Position), 0x2000) : 0x2000;
        byte[] buffer = new byte[size];
        int n;
        do
        {
            n = src.Read(buffer, 0, buffer.Length);
            dest.Write(buffer, 0, n);
        } while (n != 0);           
    }

    public static void CopyTo(this MemoryStream src, Stream dest)
    {
        dest.Write(src.GetBuffer(), (int)src.Position, (int)(src.Length - src.Position));
    }

    public static void CopyTo(this Stream src, MemoryStream dest)
    {
        if (src.CanSeek)
        {
            int pos = (int)dest.Position;
            int length = (int)(src.Length - src.Position) + pos;
            dest.SetLength(length); 

            while(pos < length)                
                pos += src.Read(dest.GetBuffer(), pos, length - pos);
        }
        else
            src.CopyTo((Stream)dest);
    }

Remove all special characters except space from a string using JavaScript

Try this:

const strippedString = htmlString.replace(/(<([^>]+)>)/gi, "");
console.log(strippedString);

Java Date cut off time information

I fixed the issue like this(in Eastern eight zone(Beijing time)):

private Date getTruncatedDate(Date d) {
    if (d == null) {
        return null;
    }
    long h = 60 * 60 * 1000L;
    long dateStamp = d.getTime() - (d.getTime() + 8 * h) % (24 * h);
    return new Date(dateStamp);
}

First of all, you should be clear what is time stamp. Time stamp is the total milliseconds from Jan 01 00:00:00 1970 of GMT(same as UTC), or Thu Jan 01 08:00:00 CST 1970 to now.

Remember: Time stamp is independent of time zone.

So you get same result with the following statement in differnt time zones:

System.out.println(new Date().getTime());

And

System.out.println(new Date(0));

prints diferent time info in different time zones: If you set your pc time zone as UTC, you get

Thu Jan 01 00:00:00 UTC 1970

But if you set the time zone as (UTC +8:00) Beijing, Chongqing, HongKong, Urumq, you get:

Thu Jan 01 08:00:00 CST 1970

Java gets the time stamp, then displays date and time info according on the time zone.

For the introduction of how Java displays date and time info in different time zones, how to trancate the time info is easy. You should get the time stamp , and take the time zone into account when cut off the time info. Then you can create a new Date object with the cut time stamp(we can call it date stamp), java will compensate the time zone when displays date info.

As in Eastern eight zone(Beijing time), the Beijing time is earlier 8 hours than GMT, so you should subtract more 8 hours when you do the modulo operation. That's to say, you should get the GMT time first, then Java will add 8 hours when display time based on your pc's time zone setting.


The time zone issue is obscure, and also puzzles me for a long time. Now I make it clear. Hope helps.


2018-01-04 The method below also works.

private Date getTruncatedDate2(Date d) {
    Calendar cal = Calendar.getInstance(); // locale-specific
    cal.setTime(d);
    cal.set(Calendar.HOUR_OF_DAY, 0);
    cal.set(Calendar.MINUTE, 0);
    cal.set(Calendar.SECOND, 0);
    cal.set(Calendar.MILLISECOND, 0);


return cal.getTime();

}

BOOLEAN or TINYINT confusion

MySQL does not have internal boolean data type. It uses the smallest integer data type - TINYINT.

The BOOLEAN and BOOL are equivalents of TINYINT(1), because they are synonyms.

Try to create this table -

CREATE TABLE table1 (
  column1 BOOLEAN DEFAULT NULL
);

Then run SHOW CREATE TABLE, you will get this output -

CREATE TABLE `table1` (
  `column1` tinyint(1) DEFAULT NULL
)

How to solve '...is a 'type', which is not valid in the given context'? (C#)

CERAS is a class name which cannot be assigned. As the class implements IDisposable a typical usage would be:

using (CERas.CERAS ceras = new CERas.CERAS())
{
    // call some method on ceras
}

git discard all changes and pull from upstream

while on branch master: git reset --hard origin/master

then do some clean up with git gc (more about this in the man pages)

Update: You will also probably need to do a git fetch origin (or git fetch origin master if you only want that branch); it should not matter if you do this before or after the reset. (Thanks @eric-walker)

NotificationCenter issue on Swift 3

Swift 3 & 4

Swift 3, and now Swift 4, have replaced many "stringly-typed" APIs with struct "wrapper types", as is the case with NotificationCenter. Notifications are now identified by a struct Notfication.Name rather than by String. For more details see the now legacy Migrating to Swift 3 guide

Swift 2.2 usage:

// Define identifier
let notificationIdentifier: String = "NotificationIdentifier"

// Register to receive notification
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(YourClassName.methodOfReceivedNotification(_:)), name: notificationIdentifier, object: nil)

// Post a notification
NSNotificationCenter.defaultCenter().postNotificationName(notificationIdentifier, object: nil)

Swift 3 & 4 usage:

// Define identifier
let notificationName = Notification.Name("NotificationIdentifier")

// Register to receive notification
NotificationCenter.default.addObserver(self, selector: #selector(YourClassName.methodOfReceivedNotification), name: notificationName, object: nil)

// Post notification
NotificationCenter.default.post(name: notificationName, object: nil)

// Stop listening notification
NotificationCenter.default.removeObserver(self, name: notificationName, object: nil)

All of the system notification types are now defined as static constants on Notification.Name; i.e. .UIApplicationDidFinishLaunching, .UITextFieldTextDidChange, etc.

You can extend Notification.Name with your own custom notifications in order to stay consistent with the system notifications:

// Definition:
extension Notification.Name {
    static let yourCustomNotificationName = Notification.Name("yourCustomNotificationName")
}

// Usage:
NotificationCenter.default.post(name: .yourCustomNotificationName, object: nil)

Swift 4.2 usage:

Same as Swift 4, except now system notifications names are part of UIApplication. So in order to stay consistent with the system notifications you can extend UIApplication with your own custom notifications instead of Notification.Name :

// Definition:
UIApplication {
    public static let yourCustomNotificationName = Notification.Name("yourCustomNotificationName")
}

// Usage:
NotificationCenter.default.post(name: UIApplication.yourCustomNotificationName, object: nil)

Find the similarity metric between two strings

BLEUscore

BLEU, or the Bilingual Evaluation Understudy, is a score for comparing a candidate translation of text to one or more reference translations.

A perfect match results in a score of 1.0, whereas a perfect mismatch results in a score of 0.0.

Although developed for translation, it can be used to evaluate text generated for a suite of natural language processing tasks.

Code:

import nltk
from nltk.translate import bleu
from nltk.translate.bleu_score import SmoothingFunction
smoothie = SmoothingFunction().method4

C1='Text'
C2='Best'

print('BLEUscore:',bleu([C1], C2, smoothing_function=smoothie))

Examples: By updating C1 and C2.

C1='Test' C2='Test'

BLEUscore: 1.0

C1='Test' C2='Best'

BLEUscore: 0.2326589746035907

C1='Test' C2='Text'

BLEUscore: 0.2866227639866161

You can also compare sentence similarity:

C1='It is tough.' C2='It is rough.'

BLEUscore: 0.7348889200874658

C1='It is tough.' C2='It is tough.'

BLEUscore: 1.0

Smooth scroll without the use of jQuery

I've made an example without jQuery here : http://codepen.io/sorinnn/pen/ovzdq

/**
    by Nemes Ioan Sorin - not an jQuery big fan 
    therefore this script is for those who love the old clean coding style  
    @id = the id of the element who need to bring  into view

    Note : this demo scrolls about 12.700 pixels from Link1 to Link3
*/
(function()
{
      window.setTimeout = window.setTimeout; //
})();

      var smoothScr = {
      iterr : 30, // set timeout miliseconds ..decreased with 1ms for each iteration
        tm : null, //timeout local variable
      stopShow: function()
      {
        clearTimeout(this.tm); // stopp the timeout
        this.iterr = 30; // reset milisec iterator to original value
      },
      getRealTop : function (el) // helper function instead of jQuery
      {
        var elm = el; 
        var realTop = 0;
        do
        {
          realTop += elm.offsetTop;
          elm = elm.offsetParent;
        }
        while(elm);
        return realTop;
      },
      getPageScroll : function()  // helper function instead of jQuery
      {
        var pgYoff = window.pageYOffset || document.body.scrollTop || document.documentElement.scrollTop;
        return pgYoff;
      },
      anim : function (id) // the main func
      {
        this.stopShow(); // for click on another button or link
        var eOff, pOff, tOff, scrVal, pos, dir, step;

        eOff = document.getElementById(id).offsetTop; // element offsetTop

        tOff =  this.getRealTop(document.getElementById(id).parentNode); // terminus point 

        pOff = this.getPageScroll(); // page offsetTop

        if (pOff === null || isNaN(pOff) || pOff === 'undefined') pOff = 0;

        scrVal = eOff - pOff; // actual scroll value;

        if (scrVal > tOff) 
        {
          pos = (eOff - tOff - pOff); 
          dir = 1;
        }
        if (scrVal < tOff)
        {
          pos = (pOff + tOff) - eOff;
          dir = -1; 
        }
        if(scrVal !== tOff) 
        {
          step = ~~((pos / 4) +1) * dir;

          if(this.iterr > 1) this.iterr -= 1; 
          else this.itter = 0; // decrease the timeout timer value but not below 0
          window.scrollBy(0, step);
          this.tm = window.setTimeout(function()
          {
             smoothScr.anim(id);  
          }, this.iterr); 
        }  
        if(scrVal === tOff) 
        { 
          this.stopShow(); // reset function values
          return;
        }
    }
 }

How does the vim "write with sudo" trick work?

This also works well:

:w !sudo sh -c "cat > %"

This is inspired by the comment of @Nathan Long.

NOTICE:

" must be used instead of ' because we want % to be expanded before passing to shell.

How to remove line breaks (no characters!) from the string?

I use 3 lines to do this job, so consider $s as your "stuff"...

$s=str_replace(chr(10),'',$s);
$s=str_replace(chr(13),'',$s);
$s=str_replace("\r\n"),'',$s);

CLEAR SCREEN - Oracle SQL Developer shortcut?

Use the following command to clear screen in sqlplus.

SQL > clear scr 

How to handle a lost KeyStore password in Android?

In my case I was getting the alias name wrong, even though I stored the correct password. So I thought it was the wrong password (using ionic package) so i used this command to get the alias name

keytool -list -v -keystore

And I was able to use the keystore again!

How to display a json array in table format?

DEMO

var obj=[
        {
            id : "001",
            name : "apple",
            category : "fruit",
            color : "red"
        },
        {
            id : "002",
            name : "melon",
            category : "fruit",
            color : "green"
        },
        {
            id : "003",
            name : "banana",
            category : "fruit",
            color : "yellow"
        }
    ]
    var tbl=$("<table/>").attr("id","mytable");
    $("#div1").append(tbl);
    for(var i=0;i<obj.length;i++)
    {
        var tr="<tr>";
        var td1="<td>"+obj[i]["id"]+"</td>";
        var td2="<td>"+obj[i]["name"]+"</td>";
        var td3="<td>"+obj[i]["color"]+"</td></tr>";

       $("#mytable").append(tr+td1+td2+td3); 

    }   

How can I remove a character from a string using JavaScript?

If it is always the 4th char in yourString you can try:

yourString.replace(/^(.{4})(r)/, function($1, $2) { return $2; });

How to detect a docker daemon port

Reference docs of docker: https://docs.docker.com/install/linux/linux-postinstall/#configure-where-the-docker-daemon-listens-for-connections

There are 2 ways in configuring the docker daemon port

1) Configuring at /etc/default/docker file:

DOCKER_OPTS="-H tcp://127.0.0.1:5000 -H unix:///var/run/docker.sock"

2) Configuring at /etc/docker/daemon.json:

{
"debug": true,
"hosts": ["tcp://127.0.0.1:5000", "unix:///var/run/docker.sock"]
}

If the docker default socket is not configured Docker will wait for infinite period.i.e

Waiting for /var/run/docker.sock
Waiting for /var/run/docker.sock
Waiting for /var/run/docker.sock
Waiting for /var/run/docker.sock
Waiting for /var/run/docker.sock

NOTE : BUT DON'T CONFIGURE IN BOTH THE CONFIGURATION FILES, the following error may occur :

Waiting for /var/run/docker.sock
unable to configure the Docker daemon with file /etc/docker/daemon.json: the following directives are specified both as a flag and in the configuration file: hosts: (from flag: [tcp://127.0.0.1:5000 unix:///var/run/docker.sock], from file: tcp://127.0.0.1:5000)

The reason for adding both the user port[ tcp://127.0.0.1:5000] and default docker socket[unix:///var/run/docker.sock] is that the user port enables the access to the docker APIs whereas the default socket enables the CLI. In case the default port[unix:///var/run/docker.sock] is not mentioned in /etc/default/docker file the following error may occur:

# docker ps
Cannot connect to the Docker daemon at unix:///var/run/docker.sock. Is the docker daemon running?

This error is not because that the docker is not running, but because of default docker socket is not enabled.

Once the configuration is enabled restart the docker service and verify the docker port is enabled or not:

# netstat -tunlp | grep -i 5000
tcp        0      0 127.0.0.1:5000          0.0.0.0:*               LISTEN      31661/dockerd 

Applicable for Docker Version 17.04, may vary with different versions of docker.

Get selected row item in DataGrid WPF

Well I will put similar solution that is working fine for me.

 private void DataGrid1_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            try
            {
                if (DataGrid1.SelectedItem != null)
                {
                    if (DataGrid1.SelectedItem is YouCustomClass)
                    {
                        var row = (YouCustomClass)DataGrid1.SelectedItem;

                        if (row != null)
                        {
                            // Do something...

                            //  ButtonSaveData.IsEnabled = true;

                            //  LabelName.Content = row.Name;

                        }
                    }
                }
            }
            catch (Exception)
            {
            }
        }

What's the right way to create a date in Java?

The excellent joda-time library is almost always a better choice than Java's Date or Calendar classes. Here's a few examples:

DateTime aDate = new DateTime(year, month, day, hour, minute, second);
DateTime anotherDate = new DateTime(anotherYear, anotherMonth, anotherDay, ...);
if (aDate.isAfter(anotherDate)) {...}
DateTime yearFromADate = aDate.plusYears(1);

{"<user xmlns=''> was not expected.} Deserializing Twitter XML

The error message is so vague, for me I had this code:

var streamReader = new StreamReader(response.GetResponseStream());
var xmlSerializer = new XmlSerializer(typeof(aResponse));
theResponse = (bResponse) xmlSerializer.Deserialize(streamReader);

Notice xmlSerializer is instantiated with aResponse but on deserializing I accidentally casted it to bResonse.

Confused about Service vs Factory

Adding to the first answer, I think .service() is for people who have written their code in more object oriented style(C#/Java) (using this keyword and instantiating object via prototype/Constructor function).

Factory is for developers who write code which is more natural to javascript/functional style of coding.

Take a look at the source code of .service and .factory method inside angular.js - internally they all call provider method:

  function provider(name, provider_) {
    if (isFunction(provider_)) {
      provider_ = providerInjector.instantiate(provider_);
    }
    if (!provider_.$get) {
      throw Error('Provider ' + name + ' must define $get factory method.');
    }
    return providerCache[name + providerSuffix] = provider_;
  }

  function factory(name, factoryFn) { \
    return provider(name, { $get: factoryFn }); 
  }

  function service(name, constructor) {
    return factory(name, ['$injector', function($injector) {
      return $injector.instantiate(constructor);
    }]);
  }

Split bash string by newline characters

Another way:

x=$'Some\nstring'
readarray -t y <<<"$x"

Or, if you don't have bash 4, the bash 3.2 equivalent:

IFS=$'\n' read -rd '' -a y <<<"$x"

You can also do it the way you were initially trying to use:

y=(${x//$'\n'/ })

This, however, will not function correctly if your string already contains spaces, such as 'line 1\nline 2'. To make it work, you need to restrict the word separator before parsing it:

IFS=$'\n' y=(${x//$'\n'/ })

...and then, since you are changing the separator, you don't need to convert the \n to space anymore, so you can simplify it to:

IFS=$'\n' y=($x)

This approach will function unless $x contains a matching globbing pattern (such as "*") - in which case it will be replaced by the matched file name(s). The read/readarray methods require newer bash versions, but work in all cases.

Excel Looping through rows and copy cell values to another worksheet

Private Sub CommandButton1_Click() 

Dim Z As Long 
Dim Cellidx As Range 
Dim NextRow As Long 
Dim Rng As Range 
Dim SrcWks As Worksheet 
Dim DataWks As Worksheet 
Z = 1 
Set SrcWks = Worksheets("Sheet1") 
Set DataWks = Worksheets("Sheet2") 
Set Rng = EntryWks.Range("B6:ad6") 

NextRow = DataWks.UsedRange.Rows.Count 
NextRow = IIf(NextRow = 1, 1, NextRow + 1) 

For Each RA In Rng.Areas 
    For Each Cellidx In RA 
        Z = Z + 1 
        DataWks.Cells(NextRow, Z) = Cellidx 
    Next Cellidx 
Next RA 
End Sub

Alternatively

Worksheets("Sheet2").Range("P2").Value = Worksheets("Sheet1").Range("L10") 

This is a CopynPaste - Method

Sub CopyDataToPlan()

Dim LDate As String
Dim LColumn As Integer
Dim LFound As Boolean

On Error GoTo Err_Execute

'Retrieve date value to search for
LDate = Sheets("Rolling Plan").Range("B4").Value

Sheets("Plan").Select

'Start at column B
LColumn = 2
LFound = False

While LFound = False

  'Encountered blank cell in row 2, terminate search
  If Len(Cells(2, LColumn)) = 0 Then
     MsgBox "No matching date was found."
     Exit Sub

  'Found match in row 2
  ElseIf Cells(2, LColumn) = LDate Then

     'Select values to copy from "Rolling Plan" sheet
     Sheets("Rolling Plan").Select
     Range("B5:H6").Select
     Selection.Copy

     'Paste onto "Plan" sheet
     Sheets("Plan").Select
     Cells(3, LColumn).Select
     Selection.PasteSpecial Paste:=xlValues, Operation:=xlNone, SkipBlanks:= _
     False, Transpose:=False

     LFound = True
     MsgBox "The data has been successfully copied."

     'Continue searching
      Else
         LColumn = LColumn + 1
      End If

   Wend

   Exit Sub

Err_Execute:
  MsgBox "An error occurred."

End Sub

And there might be some methods doing that in Excel.

How to mock a final class with mockito

Give this a try:

Mockito.mock(SomeMockableType.class,AdditionalAnswers.delegatesTo(someInstanceThatIsNotMockableOrSpyable));

It worked for me. "SomeMockableType.class" is the parent class of what you want to mock or spy, and someInstanceThatIsNotMockableOrSpyable is the actual class that you want to mock or spy.

For more details have a look here

Create mysql table directly from CSV file using the CSV Storage engine?

This is not possible. To create a table you need a table schema. What you have is a data file. A schema cannot be created with it.

What you can do is check if your file has a header row, and, in that case, you can manually create a table using that header row.

However, there is a way to generate a create table statement using a batch file as described by John Swapceinski in the comment section of the MySQL manual.

Posted by John Swapceinski on September 5 2011 5:33am.
Create a table using the .csv file's header:

#!/bin/sh
# pass in the file name as an argument: ./mktable filename.csv
echo "create table $1 ( "
head -1 $1 | sed -e 's/,/ varchar(255),\n/g'
echo " varchar(255) );"

Cross-thread operation not valid: Control accessed from a thread other than the thread it was created on

As per Prerak K's update comment (since deleted):

I guess I have not presented the question properly.

Situation is this: I want to load data into a global variable based on the value of a control. I don't want to change the value of a control from the child thread. I'm not going to do it ever from a child thread.

So only accessing the value so that corresponding data can be fetched from the database.

The solution you want then should look like:

UserContrl1_LOadDataMethod()
{
    string name = "";
    if(textbox1.InvokeRequired)
    {
        textbox1.Invoke(new MethodInvoker(delegate { name = textbox1.text; }));
    }
    if(name == "MyName")
    {
        // do whatever
    }
}

Do your serious processing in the separate thread before you attempt to switch back to the control's thread. For example:

UserContrl1_LOadDataMethod()
{
    if(textbox1.text=="MyName") //<<======Now it wont give exception**
    {
        //Load data correspondin to "MyName"
        //Populate a globale variable List<string> which will be
        //bound to grid at some later stage
        if(InvokeRequired)
        {
            // after we've done all the processing, 
            this.Invoke(new MethodInvoker(delegate {
                // load the control with the appropriate data
            }));
            return;
        }
    }
}

Sum of Numbers C++

You are just updating the value of i in the loop. The value of i should also be added each time.

It is never a good idea to update the value of i inside the for loop. The for loop index should only be used as a counter. In your case, changing the value of i inside the loop will cause all sorts of confusion.

Create variable total that holds the sum of the numbers up to i.

So

 for (int i = 0; i < positiveInteger; i++)
        total += i;

ESRI : Failed to parse source map

Further to just simply turning off Source Maps in Chrome - I've done a little digging and found that using Web Essentials to create the source maps seems to be the issue.

For whatever reason, if I use an external compiler (Koala) I can successfully create working source maps in Chrome (no errors). Whereas if I use Web Essentials, the source maps fail to parse.

Hope this helps someone.

Generating sql insert into for Oracle

If you have to load a lot of data into tables on a regular basis, check out SQL Loader or external tables. Should be much faster than individual Inserts.

HTML button calling an MVC Controller and Action method

If you are in home page ("/Home/Index") and you would like to call Index action of Admin controller, following would work for you.

<li><a href="/Admin/Index">Admin</a></li>

How to check a Long for null in java

As mentioned already primitives can not be set to the Object type null.

What I do in such cases is just to use -1 or Long.MIN_VALUE.

Insert line after first match using sed

Maybe a bit late to post an answer for this, but I found some of the above solutions a bit cumbersome.

I tried simple string replacement in sed and it worked:

sed 's/CLIENTSCRIPT="foo"/&\nCLIENTSCRIPT2="hello"/' file

& sign reflects the matched string, and then you add \n and the new line.

As mentioned, if you want to do it in-place:

sed -i 's/CLIENTSCRIPT="foo"/&\nCLIENTSCRIPT2="hello"/' file

Another thing. You can match using an expression:

sed -i 's/CLIENTSCRIPT=.*/&\nCLIENTSCRIPT2="hello"/' file

Hope this helps someone

How to start a background process in Python?

I found this here:

On windows (win xp), the parent process will not finish until the longtask.py has finished its work. It is not what you want in CGI-script. The problem is not specific to Python, in PHP community the problems are the same.

The solution is to pass DETACHED_PROCESS Process Creation Flag to the underlying CreateProcess function in win API. If you happen to have installed pywin32 you can import the flag from the win32process module, otherwise you should define it yourself:

DETACHED_PROCESS = 0x00000008

pid = subprocess.Popen([sys.executable, "longtask.py"],
                       creationflags=DETACHED_PROCESS).pid

Can the Android layout folder contain subfolders?

Within a module, to have a combination of flavors, flavor resources (layout, values) and flavors resource resources, the main thing to keep in mind are two things:

  1. When adding resource directories in res.srcDirs for flavor, keep in mind that in other modules and even in src/main/res of the same module, resource directories are also added. Hence, the importance of using an add-on assignment (+=) so as not to overwrite all existing resources with the new assignment.

  2. The path that is declared as an element of the array is the one that contains the resource types, that is, the resource types are all the subdirectories that a res folder contains normally such as color, drawable, layout, values, etc. The name of the res folder can be changed.

An example would be to use the path "src/flavor/res/values/strings-ES" but observe that the practice hierarchy has to have the subdirectory values:

+-- module 
   +-- flavor
      +-- res
         +-- values
            +-- strings-ES
               +-- values
                  +-- strings.xml
               +-- strings.xml
 

The framework recognizes resources precisely by type, that is why normally known subdirectories cannot be omitted.

Also keep in mind that all the strings.xml files that are inside the flavor would form a union so that resources cannot be duplicated. And in turn this union that forms a file in the flavor has a higher order of precedence before the main of the module.

flavor {
        res.srcDirs += [
            "src/flavor/res/values/strings-ES"
        ]
}

Consider the strings-ES directory as a custom-res which contains the resource types.

GL

How to specify the current directory as path in VBA?

I thought I had misunderstood but I was right. In this scenario, it will be ActiveWorkbook.Path

But the main issue was not here. The problem was with these 2 lines of code

strFile = Dir(strPath & "*.csv")

Which should have written as

strFile = Dir(strPath & "\*.csv")

and

With .QueryTables.Add(Connection:="TEXT;" & strPath & strFile, _

Which should have written as

With .QueryTables.Add(Connection:="TEXT;" & strPath & "\" & strFile, _

WiX tricks and tips

Put Components which may be patched individually inside their own Fragments

It goes for both making product installers and patches that if you include any component in a fragment, you must include all of the components in that fragment. In the case of building an installer, if you miss any component references, you'll get a linking error from light.exe. However, when you make a patch, if you include a single component reference in a fragment, then all changed components from that fragment will show up in your patch.

like this:

<Fragment>
    <DirectoryRef Id="SampleProductFolder">
        <Component Id="SampleComponent1" Guid="{C28843DA-EF08-41CC-BA75-D2B99D8A1983}" DiskId="1">
            <File Id="SampleFile1" Source=".\$(var.Version)f\Sample1.txt" />
        </Component>
    </DirectoryRef>
</Fragment>

<Fragment>
    <DirectoryRef Id="SampleProductFolder">
        <Component Id="SampleComponent2" Guid="{6CEA5599-E7B0-4D65-93AA-0F2F64402B22}" DiskId="1">
           <File Id="SampleFile2" Source=".\$(var.Version)f\Sample2.txt" />
        </Component>
    </DirectoryRef>
</Fragment>

<Fragment>
    <DirectoryRef Id="SampleProductFolder">
        <Component Id="SampleComponent3" Guid="{4030BAC9-FAB3-426B-8D1E-DC1E2F72C2FC}" DiskId="1">
           <File Id="SampleFile3" Source=".\$(var.Version)f\Sample3.txt" />
        </Component>
    </DirectoryRef>
</Fragment>

instead of this:

<Fragment>
    <DirectoryRef Id="SampleProductFolder">
        <Component Id="SampleComponent1" Guid="{C28843DA-EF08-41CC-BA75-D2B99D8A1983}" DiskId="1">
            <File Id="SampleFile1" Source=".\$(var.Version)\Sample1.txt" />
        </Component>

        <Component Id="SampleComponent2" Guid="{6CEA5599-E7B0-4D65-93AA-0F2F64402B22}" DiskId="1">
           <File Id="SampleFile2" Source=".\$(var.Version)\Sample2.txt" />
        </Component>

        <Component Id="SampleComponent3" Guid="{4030BAC9-FAB3-426B-8D1E-DC1E2F72C2FC}" DiskId="1">
           <File Id="SampleFile3" Source=".\$(var.Version)\Sample3.txt" />
        </Component>
    </DirectoryRef>
</Fragment>

Also, when patching using the "Using Purely WiX" topic from the WiX.chm help file, using this procedure to generate the patch:

torch.exe -p -xi 1.0\product.wixpdb 1.1\product.wixpdb -out patch\diff.wixmst
candle.exe patch.wxs
light.exe patch.wixobj -out patch\patch.wixmsp
pyro.exe patch\patch.wixmsp -out patch\patch.msp -t RTM patch\diff.wixmst

it's not enough to just have the 1.1 version of the product.wixpdb built using the components in separate fragments. So be sure to correctly fragment your product before shipping.

How do I style a <select> dropdown with only CSS?

Use the clip property to crop the borders and the arrow of the select element, then add your own replacement styles to the wrapper:

_x000D_
_x000D_
    <!DOCTYPE html>_x000D_
    <html>_x000D_
      <head>_x000D_
        <style>_x000D_
          select { position: absolute; clip:rect(2px 49px 19px 2px); z-index:2; }_x000D_
          body > span { display:block; position: relative; width: 64px; height: 21px; border: 2px solid green;  background: url(http://www.stackoverflow.com/favicon.ico) right 1px no-repeat; }_x000D_
        </style>_x000D_
      </head>_x000D_
      <span>_x000D_
        <select>_x000D_
          <option value="">Alpha</option>_x000D_
          <option value="">Beta</option>_x000D_
          <option value="">Charlie</option>_x000D_
        </select>_x000D_
      </span>_x000D_
    </html>
_x000D_
_x000D_
_x000D_

Use a second select with zero opacity to make the button clickable:

_x000D_
_x000D_
    <!DOCTYPE html>_x000D_
    <html>_x000D_
      <head>_x000D_
        <style>_x000D_
          #real { position: absolute; clip:rect(2px 51px 19px 2px); z-index:2; }_x000D_
          #fake { position: absolute; opacity: 0; }_x000D_
    _x000D_
          body > span { display:block; position: relative; width: 64px; height: 21px; background: url(http://www.stackoverflow.com/favicon.ico) right 1px no-repeat; }_x000D_
        </style>_x000D_
      </head>_x000D_
      <span>_x000D_
        <select id="real">_x000D_
          <option value="">Alpha</option>_x000D_
          <option value="">Beta</option>_x000D_
          <option value="">Charlie</option>_x000D_
        </select>_x000D_
        <select id="fake">_x000D_
          <option value="">Alpha</option>_x000D_
          <option value="">Beta</option>_x000D_
          <option value="">Charlie</option>_x000D_
        </select>_x000D_
      </span>_x000D_
    </html>
_x000D_
_x000D_
_x000D_

Coordinates differ between Webkit and other browsers, but a @media query can cover that.

References

datetime to string with series in python pandas

As of version 17.0, you can format with the dt accessor:

dates.dt.strftime('%Y-%m-%d')

Reference

Remove querystring from URL

If you're into RegEx....

var newURL = testURL.match(new RegExp("[^?]+"))

How to remove specific substrings from a set of strings in Python?

You could do this:

import re
import string
set1={'Apple.good','Orange.good','Pear.bad','Pear.good','Banana.bad','Potato.bad'}

for x in set1:
    x.replace('.good',' ')
    x.replace('.bad',' ')
    x = re.sub('\.good$', '', x)
    x = re.sub('\.bad$', '', x)
    print(x)

Printing pointers in C

"s" is not a "char*", it's a "char[4]". And so, "&s" is not a "char**", but actually "a pointer to an array of 4 characater". Your compiler may treat "&s" as if you had written "&s[0]", which is roughly the same thing, but is a "char*".

When you write "char** p = &s;" you are trying to say "I want p to be set to the address of the thing which currently points to "asd". But currently there is nothing which points to "asd". There is just an array which holds "asd";

char s[] = "asd";
char *p = &s[0];  // alternately you could use the shorthand char*p = s;
char **pp = &p;

Exception : AAPT2 error: check logs for details

I was also getting same error because of using & character directly in layout xml. So, please be careful about using html entities in your project.

Embedding JavaScript engine into .NET

I guess I am still unclear about what it is you are trying to do, but JScript.NET might be worth looking into, though Managed JScript seems like it may be more appropriate for your needs (it is more like JavaScript than JScript.NET).

Personally, I thought it would be cool to integrate V8 somehow, but I didn't get past downloading the source code; wish I had the time to actually do something with it.

Regex date validation for yyyy-mm-dd

A simple one would be

\d{4}-\d{2}-\d{2}

Regular expression visualization

Debuggex Demo

but this does not restrict month to 1-12 and days from 1 to 31.

There are more complex checks like in the other answers, by the way pretty clever ones. Nevertheless you have to check for a valid date, because there are no checks for if a month has 28, 30, or 31 days.

Git remote branch deleted, but still it appears in 'branch -a'

git remote prune origin, as suggested in the other answer, will remove all such stale branches. That's probably what you'd want in most cases, but if you want to just remove that particular remote-tracking branch, you should do:

git branch -d -r origin/coolbranch

(The -r is easy to forget...)

-r in this case will "List or delete (if used with -d) the remote-tracking branches." according to the Git documentation found here: https://git-scm.com/docs/git-branch

How can I suppress all output from a command using Bash?

Take a look at this example from The Linux Documentation Project:

3.6 Sample: stderr and stdout 2 file

This will place every output of a program to a file. This is suitable sometimes for cron entries, if you want a command to pass in absolute silence.

     rm -f $(find / -name core) &> /dev/null 

That said, you can use this simple redirection:

/path/to/command &>/dev/null

Rails Object to hash

You could definitely use the attributes to return all attributes but you could add an instance method to Post, call it "to_hash" and have it return the data you would like in a hash. Something like

def to_hash
 { name: self.name, active: true }
end

Find out where MySQL is installed on Mac OS X

If you downloaded mySQL using a DMG (easiest way to download found here http://dev.mysql.com/downloads/mysql/) in Terminal try: cd /usr/local/

When you type ls you should see mysql-YOUR-VERSION. You will also see mysql which is the installation directory.

Source: http://geeksww.com/tutorials/database_management_systems/mysql/installation/how_to_download_and_install_mysql_on_mac_os_x.php

Creating an R dataframe row-by-row

You can grow them row by row by appending or using rbind().

That does not mean you should. Dynamically growing structures is one of the least efficient ways to code in R.

If you can, allocate your entire data.frame up front:

N <- 1e4  # total number of rows to preallocate--possibly an overestimate

DF <- data.frame(num=rep(NA, N), txt=rep("", N),  # as many cols as you need
                 stringsAsFactors=FALSE)          # you don't know levels yet

and then during your operations insert row at a time

DF[i, ] <- list(1.4, "foo")

That should work for arbitrary data.frame and be much more efficient. If you overshot N you can always shrink empty rows out at the end.

Can't choose class as main class in IntelliJ

Select the folder containing the package tree of these classes, right-click and choose "Mark Directory as -> Source Root"

"PKIX path building failed" and "unable to find valid certification path to requested target"

It's addition to the answer https://stackoverflow.com/a/36427118/1491414. Thanks @MagGGG

  • Please make sure you have administrator permission
  • Please use double quotes for the keystore path (-keystore C:\Program Files (x86)\Java\jre1.6.0_22\lib\security\cacerts") because in Windows OS the default installs location will be Program Files and you will get an error because of space between Program Files.

What is the correct format to use for Date/Time in an XML file

If you are manually assembling the XML string use var.ToUniversalTime().ToString("yyyy-MM-dd'T'HH:mm:ss.fffffffZ")); That will output the official XML Date Time format. But you don't have to worry about format if you use the built-in serialization methods.

Keep the order of the JSON keys during JSON conversion to CSV

Tested the wink solution, and working fine:

@Test
public void testJSONObject() {
    JSONObject jsonObject = new JSONObject();
    jsonObject.put("bbb", "xxx");
    jsonObject.put("ccc", "xxx");
    jsonObject.put("aaa", "xxx");
    jsonObject.put("xxx", "xxx");
    System.out.println(jsonObject.toString());
    assertTrue(jsonObject.toString().startsWith("{\"xxx\":"));
}

@Test
public void testWinkJSONObject() throws JSONException {
    org.apache.wink.json4j.JSONObject jsonObject = new OrderedJSONObject();
    jsonObject.put("bbb", "xxx");
    jsonObject.put("ccc", "xxx");
    jsonObject.put("aaa", "xxx");
    jsonObject.put("xxx", "xxx");
    assertEquals("{\"bbb\":\"xxx\",\"ccc\":\"xxx\",\"aaa\":\"xxx\",\"xxx\":\"xxx\"}", jsonObject.toString());
}

Send Email Intent

If you want only the email clients you should use android.content.Intent.EXTRA_EMAIL with an array. Here goes an example:

final Intent result = new Intent(android.content.Intent.ACTION_SEND);
result.setType("plain/text");
result.putExtra(android.content.Intent.EXTRA_EMAIL, new String[] { recipient });
result.putExtra(android.content.Intent.EXTRA_SUBJECT, subject);
result.putExtra(android.content.Intent.EXTRA_TEXT, body);

Android:java.lang.OutOfMemoryError: Failed to allocate a 23970828 byte allocation with 2097152 free bytes and 2MB until OOM

You have to change the size of object in drawable. It's too big for android to display. e.g. If you are setting image try image with less pixels. It works for me. Thanks. :)

java: How can I do dynamic casting of a variable from one type to another?

You can write a simple castMethod like the one below.

private <T> T castObject(Class<T> clazz, Object object) {
  return (T) object;
}

In your method you should be using it like

public ConnectParams(HashMap<String,Object> object) {

for (Map.Entry<String, Object> entry : object.entrySet()) {
    try {
        Field f =  this.getClass().getField(entry.getKey());                
        f.set(this, castObject(entry.getValue().getClass(), entry.getValue()); /* <= CASTING PROBLEM */
    } catch (NoSuchFieldException ex) {
        log.error("did not find field '" + entry.getKey() + '"');
    } catch (IllegalAccessException ex) {    
        log.error(ex.getMessage());          
    }    
}

}

Generate a UUID on iOS from Swift

For Swift 3, many Foundation types have dropped the 'NS' prefix, so you'd access it by UUID().uuidString.

How to get the entire document HTML as a string?

To also get things outside the <html>...</html>, most importantly the <!DOCTYPE ...> declaration, you could walk through document.childNodes, turning each into a string:

const html = [...document.childNodes]
    .map(node => nodeToString(node))
    .join('\n') // could use '' instead, but whitespace should not matter.

function nodeToString(node) {
    switch (node.nodeType) {
        case node.ELEMENT_NODE:
            return node.outerHTML
        case node.TEXT_NODE:
            // Text nodes should probably never be encountered, but handling them anyway.
            return node.textContent
        case node.COMMENT_NODE:
            return `<!--${node.textContent}-->`
        case node.DOCUMENT_TYPE_NODE:
            return doctypeToString(node)
        default:
            throw new TypeError(`Unexpected node type: ${node.nodeType}`)
    }
}

I published this code as document-outerhtml on npm.


edit Note the code above depends on a function doctypeToString; its implementation could be as follows (code below is published on npm as doctype-to-string):

function doctypeToString(doctype) {
    if (doctype === null) {
        return ''
    }
    // Checking with instanceof DocumentType might be neater, but how to get a
    // reference to DocumentType without assuming it to be available globally?
    // To play nice with custom DOM implementations, we resort to duck-typing.
    if (!doctype
        || doctype.nodeType !== doctype.DOCUMENT_TYPE_NODE
        || typeof doctype.name !== 'string'
        || typeof doctype.publicId !== 'string'
        || typeof doctype.systemId !== 'string'
    ) {
        throw new TypeError('Expected a DocumentType')
    }
    const doctypeString = `<!DOCTYPE ${doctype.name}`
        + (doctype.publicId ? ` PUBLIC "${doctype.publicId}"` : '')
        + (doctype.systemId
            ? (doctype.publicId ? `` : ` SYSTEM`) + ` "${doctype.systemId}"`
            : ``)
        + `>`
    return doctypeString
}

How to create global variables accessible in all views using Express / Node.JS?

For Express 4.0 I found that using application level variables works a little differently & Cory's answer did not work for me.

From the docs: http://expressjs.com/en/api.html#app.locals

I found that you could declare a global variable for the app in

app.locals

e.g

app.locals.baseUrl = "http://www.google.com"

And then in your application you can access these variables & in your express middleware you can access them in the req object as

req.app.locals.baseUrl

e.g.

console.log(req.app.locals.baseUrl)
//prints out http://www.google.com

What are naming conventions for MongoDB?

I think it's all personal preference. My preferences come from using NHibernate, in .NET, with SQL Server, so they probably differ from what others use.

  • Databases: The application that's being used.. ex: Stackoverflow
  • Collections: Singular in name, what it's going to be a collection of, ex: Question
  • Document fields, ex: MemberFirstName

Honestly, it doesn't matter too much, as long as it's consistent for the project. Just get to work and don't sweat the details :P

How to specify 64 bit integers in c

Use stdint.h for specific sizes of integer data types, and also use appropriate suffixes for integer literal constants, e.g.:

#include <stdint.h>

int64_t i2 = 0x0000444400004444LL;

how to toggle attr() in jquery

If you're feeling fancy:

$('.list-sort').attr('colspan', function(index, attr){
    return attr == 6 ? null : 6;
});

Working Fiddle

What is HTML5 ARIA?

What is ARIA?

ARIA emerged as a way to address the accessibility problem of using a markup language intended for documents, HTML, to build user interfaces (UI). HTML includes a great many features to deal with documents (P, h3,UL,TABLE) but only basic UI elements such as A, INPUT and BUTTON. Windows and other operating systems support APIs that allow (Assistive Technology) AT to access the functionality of UI controls. Internet Explorer and other browsers map the native HTML elements to the accessibility API, but the html controls are not as rich as the controls common on desktop operating systems, and are not enough for modern web applications Custom controls can extend html elements to provide the rich UI needed for modern web applications. Before ARIA, the browser had no way to expose this extra richness to the accessibility API or AT. The classic example of this issue is adding a click handler to an image. It creates what appears to be a clickable button to a mouse user, but is still just an image to a keyboard or AT user.

The solution was to create a set of attributes that allow developers to extend HTML with UI semantics. The ARIA term for a group of HTML elements that have custom functionality and use ARIA attributes to map these functions to accessibility APIs is a “Widget. ARIA also provides a means for authors to document the role of content itself, which in turn, allows AT to construct alternate navigation mechanisms for the content that are much easier to use than reading the full text or only iterating over a list of the links.

It is important to remember that in simple cases, it is much preferred to use native HTML controls and style them rather than using ARIA. That is don’t reinvent wheels, or checkboxes, if you don’t have to.

Fortunately, ARIA markup can be added to existing sites without changing the behavior for mainstream users. This greatly reduces the cost of modifying and testing the website or application.

An error occurred while collecting items to be installed (Access is denied)

I solved the problem very easily.

Go to Control Panel -> Network and Sharing Center -> Windows Firewall -> Turn off Windows Firewall

And try to install again and see the magic :)

How to change the default background color white to something else in twitter bootstrap

I'm using cdn boostrap, the solution that I found was: First include the cdn bootstrap, then you include the file .css where you are editing the default styles of bootstrap.

Https Connection Android

I make this class and found

package com.example.fakessl;

import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;

import android.util.Log;

public class CertificadoAceptar {
    private static TrustManager[] trustManagers;

    public static class _FakeX509TrustManager implements
            javax.net.ssl.X509TrustManager {
        private static final X509Certificate[] _AcceptedIssuers = new X509Certificate[] {};

        public void checkClientTrusted(X509Certificate[] arg0, String arg1)
                throws CertificateException {
        }

        public void checkServerTrusted(X509Certificate[] arg0, String arg1)
                throws CertificateException {
        }

        public boolean isClientTrusted(X509Certificate[] chain) {
            return (true);
        }

        public boolean isServerTrusted(X509Certificate[] chain) {
            return (true);
        }

        public X509Certificate[] getAcceptedIssuers() {
            return (_AcceptedIssuers);
        }
    }

    public static void allowAllSSL() {

        javax.net.ssl.HttpsURLConnection
                .setDefaultHostnameVerifier(new HostnameVerifier() {
                    public boolean verify(String hostname, SSLSession session) {
                        return true;
                    }
                });

        javax.net.ssl.SSLContext context = null;

        if (trustManagers == null) {
            trustManagers = new javax.net.ssl.TrustManager[] { new _FakeX509TrustManager() };
        }

        try {
            context = javax.net.ssl.SSLContext.getInstance("TLS");
            context.init(null, trustManagers, new SecureRandom());
        } catch (NoSuchAlgorithmException e) {
            Log.e("allowAllSSL", e.toString());
        } catch (KeyManagementException e) {
            Log.e("allowAllSSL", e.toString());
        }
        javax.net.ssl.HttpsURLConnection.setDefaultSSLSocketFactory(context
                .getSocketFactory());
    }
}

in you code white this

CertificadoAceptar ca = new CertificadoAceptar();
ca.allowAllSSL();
HttpsTransportSE Transport = new HttpsTransportSE("iphost or host name", 8080, "/WS/wsexample.asmx?WSDL", 30000);

java.util.Date vs java.sql.Date

tl;dr

Use neither.

Neither

java.util.Date vs java.sql.Date: when to use which and why?

Both of these classes are terrible, flawed in design and in implementation. Avoid like the Plague Coronavirus.

Instead use java.time classes, defined in in JSR 310. These classes are an industry-leading framework for working with date-time handling. These supplant entirely the bloody awful legacy classes such as Date, Calendar, SimpleDateFormat, and such.

java.util.Date

The first, java.util.Date is meant to represent a moment in UTC, meaning an offset from UTC of zero hours-minutes-seconds.

java.time.Instant

Now replaced by java.time.Instant.

Instant instant = Instant.now() ;  // Capture the current moment as seen in UTC.

java.time.OffsetDateTime

Instant is the basic building-block class of java.time. For more flexibility, use OffsetDateTime set to ZoneOffset.UTC for the same purpose: representing a moment in UTC.

OffsetDateTime odt = OffsetDateTime.now( ZoneOffset.UTC ) ;

You can send this object to a database by using PreparedStatement::setObject with JDBC 4.2 or later.

myPreparedStatement.setObject( … , odt ) ;

Retrieve.

OffsetDateTime odt = myResultSet.getObject( … , OffsetDateTime.class ) ;

java.sql.Date

The java.sql.Date class is also terrible and obsolete.

This class is meant to represent a date only, without a time-of-day and without a time zone. Unfortunately, in a terrible hack of a design, this class inherits from java.util.Date which represents a moment (a date with time-of-day in UTC). So this class is merely pretending to be date-only, while actually carrying a time-of-day and implicit offset of UTC. This causes so much confusion. Never use this class.

java.time.LocalDate

Instead, use java.time.LocalDate to track just a date (year, month, day-of-month) without any time-of-day nor any time zone or offset.

ZoneId z = ZoneId.of( "Africa/Tunis" ) ;
LocalDate ld = LocalDate.now( z ) ;    // Capture the current date as seen in the wall-clock time used by the people of a particular region (a time zone).

Send to the database.

myPreparedStatement.setObject( … , ld ) ;

Retrieve.

LocalDate ld = myResultSet.getObject( … , LocalDate.class ) ;

Table of date-time types in Java (both legacy and modern) and in standard SQL


About java.time

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

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

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

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

Where to obtain the java.time classes?

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

In WPF, what are the differences between the x:Name and Name attributes?

One of the answers is that x:name is to be used inside different program languages such as c# and name is to be used for the framework. Honestly that is what it sounds like to me.

In PHP, how do you change the key of an array element?

I like KernelM's solution, but I needed something that would handle potential key conflicts (where a new key may match an existing key). Here is what I came up with:

function swapKeys( &$arr, $origKey, $newKey, &$pendingKeys ) {
    if( !isset( $arr[$newKey] ) ) {
        $arr[$newKey] = $arr[$origKey];
        unset( $arr[$origKey] );
        if( isset( $pendingKeys[$origKey] ) ) {
            // recursion to handle conflicting keys with conflicting keys
            swapKeys( $arr, $pendingKeys[$origKey], $origKey, $pendingKeys );
            unset( $pendingKeys[$origKey] );
        }
    } elseif( $newKey != $origKey ) {
        $pendingKeys[$newKey] = $origKey;
    }
}

You can then cycle through an array like this:

$myArray = array( '1970-01-01 00:00:01', '1970-01-01 00:01:00' );
$pendingKeys = array();
foreach( $myArray as $key => $myArrayValue ) {
    // NOTE: strtotime( '1970-01-01 00:00:01' ) = 1 (a conflicting key)
    $timestamp = strtotime( $myArrayValue );
    swapKeys( $myArray, $key, $timestamp, $pendingKeys );
}
// RESULT: $myArray == array( 1=>'1970-01-01 00:00:01', 60=>'1970-01-01 00:01:00' )

python capitalize first letter only

I came up with this:

import re

regex = re.compile("[A-Za-z]") # find a alpha
str = "1st str"
s = regex.search(str).group() # find the first alpha
str = str.replace(s, s.upper(), 1) # replace only 1 instance
print str

How to get height of <div> in px dimension

Use .height() like this:

var result = $("#myDiv").height();

There's also .innerHeight() and .outerHeight() depending on exactly what you want.

You can test it here, play with the padding/margins/content to see how it changes around.

How to return values in javascript

The answers cover things very well. I just wanted to point out that the mechanism of out parameters, as described in the question isn't very javascriptish. While other languages support it, javascript prefers you to simply return values from functions.

With ES6/ES2015 they added destructuring that makes a solution to this problem more elegant when returning an array. Destructuring will pull parts out of an array/object:

function myFunction(value1)
{
    //Do stuff and 
    return [somevalue2, sumevalue3]
}

var [value2, value3] = myFunction("1");

if(value2  && value3)
{
    //Do some stuff
}

check if "it's a number" function in Oracle

How is the column defined? If its a varchar field, then its not a number (or stored as one). Oracle may be able to do the conversion for you (eg, select * from someTable where charField = 0), but it will only return rows where the conversion holds true and is possible. This is also far from ideal situation performance wise.

So, if you want to do number comparisons and treat this column as a number, perhaps it should be defined as a number?

That said, here's what you might do:

create or replace function myToNumber(i_val in varchar2) return number is
 v_num number;
begin
 begin
   select to_number(i_val) into v_num from dual;
 exception
   when invalid_number then
   return null;
 end;
 return v_num;
end;

You might also include the other parameters that the regular to_number has. Use as so:

select * from someTable where myToNumber(someCharField) > 0;

It won't return any rows that Oracle sees as an invalid number.

Cheers.

How to create a listbox in HTML without allowing multiple selection?

For Asp.Net MVC

@Html.ListBox("parameterName", ViewBag.ParameterValueList as MultiSelectList, 
 new { 
 @class = "chosen-select form-control"
 }) 

or

  @Html.ListBoxFor(model => model.parameterName,
  ViewBag.ParameterValueList as MultiSelectList,
   new{
       data_placeholder = "Select Options ",
       @class = "chosen-select form-control"
   })

OS X Framework Library not loaded: 'Image not found'

The only thing that worked for me:

Target > Build Phases > [CP] Embed Pods Frameworks Uncheck "Show environment variables in build log" and "Run script only when installing"

Pad a number with leading zeros in JavaScript

Try:

String.prototype.lpad = function(padString, length) {
    var str = this;
    while (str.length < length)
        str = padString + str;
    return str;
}

Now test:

var str = "5";
alert(str.lpad("0", 4)); //result "0005"
var str = "10"; // note this is string type
alert(str.lpad("0", 4)); //result "0010"

DEMO


In ECMAScript 2017 , we have new method padStart and padEnd which has below syntax.

"string".padStart(targetLength [,padString]):

So now we can use

const str = "5";
str.padStart(4, "0"); // "0005"

Delete an element in a JSON object

with open('writing_file.json', 'w') as w:
    with open('reading_file.json', 'r') as r:
        for line in r:
            element = json.loads(line.strip())
            if 'hours' in element:
                del element['hours']
            w.write(json.dumps(element))

this is the method i use..

Truncate Two decimal places without rounding

Apart from the above solutions,there is another way we can achieve .

    decimal val=23.5678m,finalValue;

    //take the decimal part    
     int decimalPos = val.ToString().IndexOf('.');
     string decimalPart = val.ToString().Substring(decimalPosition+1,val.ToString().Length);
    //will result.56
   string wholePart=val.ToString().Substring(0,decimalPos-1);
   //concantinate and parse for decimal.
  string truncatedValue=wholePart+decimalPart;//"23.56"
  bool isDecimal=Decimal.tryParse(truncatedValue,out finalValue);//finalValue=23.56

how to make a specific text on TextView BOLD

public static Spanned getBoldString(String textNotBoldFirst, String textToBold, String textNotBoldLast) {
    String resultant = null;

    resultant = textNotBoldFirst + " " + "<b>" + textToBold + "</b>" + " " + textNotBoldLast;

    return Html.fromHtml(resultant);

}

Try this. It can help definitely

How to sort findAll Doctrine's method?

As @Lighthart as shown, yes it's possible, although it adds significant fat to the controller and isn't DRY.

You should really define your own query in the entity repository, it's simple and best practice.

use Doctrine\ORM\EntityRepository;

class UserRepository extends EntityRepository
{
    public function findAll()
    {
        return $this->findBy(array(), array('username' => 'ASC'));
    }
}

Then you must tell your entity to look for queries in the repository:

/**
 * @ORM\Table(name="User")
 * @ORM\Entity(repositoryClass="Acme\UserBundle\Entity\Repository\UserRepository")
 */
class User
{
    ...
}

Finally, in your controller:

$this->getDoctrine()->getRepository('AcmeBundle:User')->findAll();

jQuery: How to get the event object in an event handler function without passing it as an argument?

Since the event object "evt" is not passed from the parameter, is it still possible to obtain this object?

No, not reliably. IE and some other browsers make it available as window.event (not $(window.event)), but that's non-standard and not supported by all browsers (famously, Firefox does not).

You're better off passing the event object into the function:

<a href="#" onclick="myFunc(event, 1,2,3)">click</a>

That works even on non-IE browsers because they execute the code in a context that has an event variable (and works on IE because event resolves to window.event). I've tried it in IE6+, Firefox, Chrome, Safari, and Opera. Example: http://jsbin.com/iwifu4

But your best bet is to use modern event handling:

HTML:

<a href="#">click</a>

JavaScript using jQuery (since you're using jQuery):

$("selector_for_the_anchor").click(function(event) {
    // Call `myFunc`
    myFunc(1, 2, 3);

    // Use `event` here at the event handler level, for instance
    event.stopPropagation();
});

...or if you really want to pass event into myFunc:

$("selector_for_the_anchor").click(function(event) {
    myFunc(event, 1, 2, 3);
});

The selector can be anything that identifies the anchor. You have a very rich set to choose from (nearly all of CSS3, plus some). You could add an id or class to the anchor, but again, you have other choices. If you can use where it is in the document rather than adding something artificial, great.

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

How to map an array of objects in React

you must put object in your JSX, It`s easy way to do this just see my simple code here:

const link = [
  {
   name: "Cold Drink",
   link: "/coldDrink"
  },
  {
   name: "Hot Drink",
   link: "/HotDrink"
  },

{ name: "chease Cake", link: "/CheaseCake" } ]; and you must map this array in your code with simple object see this code :

const links = (this.props.link);
{links.map((item, i) => (
 <li key={i}>
   <Link to={item.link}>{item.name}</Link>
 </li>
 ))}

I hope this answer will be helpful for you ...:)

C# LINQ select from list

        var eventids = GetEventIdsByEventDate(DateTime.Now);
        var result = eventsdb.Where(e => eventids.Contains(e));

If you are returnning List<EventFeed> inside the method, you should change the method return type from IEnumerable<EventFeed> to List<EventFeed>.

JavaScript: undefined !== undefined?

var a;

typeof a === 'undefined'; // true
a === undefined; // true
typeof a === typeof undefined; // true
typeof a === typeof sdfuwehflj; // true

Django DB Settings 'Improperly Configured' Error

in my own case in django 1.10.1 running on python2.7.11, I was trying to start the server using django-admin runserver instead of manage.py runserver in my project directory.

How can I get argv[] as int?

/*

    Input from command line using atoi, and strtol 
*/

#include <stdio.h>//printf, scanf
#include <stdlib.h>//atoi, strtol 

//strtol - converts a string to a long int 
//atoi - converts string to an int 

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

    char *p;//used in strtol 
    int i;//used in for loop

    long int longN = strtol( argv[1],&p, 10);
    printf("longN = %ld\n",longN);

    //cast (int) to strtol
    int N = (int) strtol( argv[1],&p, 10);
    printf("N = %d\n",N);

    int atoiN;
    for(i = 0; i < argc; i++)
    {
        //set atoiN equal to the users number in the command line 
        //The C library function int atoi(const char *str) converts the string argument str to an integer (type int).
        atoiN = atoi(argv[i]);
    }

    printf("atoiN = %d\n",atoiN);
    //-----------------------------------------------------//
    //Get string input from command line 
    char * charN;

    for(i = 0; i < argc; i++)
    {
        charN = argv[i];
    }

    printf("charN = %s\n", charN); 

}

Hope this helps. Good luck!

Accessing items in an collections.OrderedDict by index

It's a new era and with Python 3.6.1 dictionaries now retain their order. These semantics aren't explicit because that would require BDFL approval. But Raymond Hettinger is the next best thing (and funnier) and he makes a pretty strong case that dictionaries will be ordered for a very long time.

So now it's easy to create slices of a dictionary:

test_dict = {
                'first':  1,
                'second': 2,
                'third':  3,
                'fourth': 4
            }

list(test_dict.items())[:2]

Note: Dictonary insertion-order preservation is now official in Python 3.7.

'const int' vs. 'int const' as function parameters in C++ and C

This isn't a direct answer but a related tip. To keep things straight, I always use the convection "put const on the outside", where by "outside" I mean the far left or far right. That way there is no confusion -- the const applies to the closest thing (either the type or the *). E.g.,



int * const foo = ...; // Pointer cannot change, pointed to value can change
const int * bar = ...; // Pointer can change, pointed to value cannot change
int * baz = ...; // Pointer can change, pointed to value can change
const int * const qux = ...; // Pointer cannot change, pointed to value cannot change

Start index for iterating Python list

Here's a rotation generator which doesn't need to make a warped copy of the input sequence ... may be useful if the input sequence is much larger than 7 items.

>>> def rotated_sequence(seq, start_index):
...     n = len(seq)
...     for i in xrange(n):
...         yield seq[(i + start_index) % n]
...
>>> s = 'su m tu w th f sa'.split()
>>> list(rotated_sequence(s, s.index('m')))
['m', 'tu', 'w', 'th', 'f', 'sa', 'su']
>>>

Delete specific line from a text file?

What? Use file open, seek position then stream erase line using null.

Gotch it? Simple,stream,no array that eat memory,fast.

This work on vb.. Example search line culture=id where culture are namevalue and id are value and we want to change it to culture=en

Fileopen(1, "text.ini")
dim line as string
dim currentpos as long
while true
    line = lineinput(1)
    dim namevalue() as string = split(line, "=")
    if namevalue(0) = "line name value that i want to edit" then
        currentpos = seek(1)
        fileclose()
        dim fs as filestream("test.ini", filemode.open)
        dim sw as streamwriter(fs)
        fs.seek(currentpos, seekorigin.begin)
        sw.write(null)
        sw.write(namevalue + "=" + newvalue)
        sw.close()
        fs.close()
        exit while
    end if
    msgbox("org ternate jua bisa, no line found")
end while

that's all..use #d

Get class name using jQuery

Try it

HTML

<div class="class_area-1">
    area 1
</div>

<div class="class_area-2">
    area 2
</div>

<div class="class_area-3">
    area 3
</div>

jQuery

<script src="https://code.jquery.com/jquery-1.11.3.js"></script>
<script type="application/javascript">
    $('div').click(function(){
        alert($(this).attr('class'));
    });
</script>

mysql.h file can't be found

You probably don't included the path to mysql headers, which can be found at /usr/include/mysql, on several unix systems I think. See this post, it may be helpfull.

By the way, related with the question of that guy above, about syntastic configuration. One can add the following to your ~/.vimrc:

let b:syntastic_c_cflags = '-I/usr/include/mysql'

and you can always check the wiki page of the developers on github. Enjoy!

How do I turn a python datetime into a string, with readable format date?

very old question, i know. but with the new f-strings (starting from python 3.6) there are fresh options. so here for completeness:

from datetime import datetime

dt = datetime.now()

# str.format
strg = '{:%B %d, %Y}'.format(dt)
print(strg)  # July 22, 2017

# datetime.strftime
strg = dt.strftime('%B %d, %Y')
print(strg)  # July 22, 2017

# f-strings in python >= 3.6
strg = f'{dt:%B %d, %Y}'
print(strg)  # July 22, 2017

strftime() and strptime() Behavior explains what the format specifiers mean.

Disabling browser caching for all browsers from ASP.NET

There are two approaches that I know of. The first is to tell the browser not to cache the page. Setting the Response to no cache takes care of that, however as you suspect the browser will often ignore this directive. The other approach is to set the date time of your response to a point in the future. I believe all browsers will correct this to the current time when they add the page to the cache, but it will show the page as newer when the comparison is made. I believe there may be some cases where a comparison is not made. I am not sure of the details and they change with each new browser release. Final note I have had better luck with pages that "refresh" themselves (another response directive). The refresh seems less likely to come from the cache.

Hope that helps.

Can I override and overload static methods in Java?

You can overload a static method but you can't override a static method. Actually you can rewrite a static method in subclasses but this is not called a override because override should be related to polymorphism and dynamic binding. The static method belongs to the class so has nothing to do with those concepts. The rewrite of static method is more like a shadowing.

Setting an environment variable before a command in Bash is not working for the second command in a pipe

You can also use eval:

FOO=bar eval 'somecommand someargs | somecommand2'

Since this answer with eval doesn't seem to please everyone, let me clarify something: when used as written, with the single quotes, it is perfectly safe. It is good as it will not launch an external process (like the accepted answer) nor will it execute the commands in an extra subshell (like the other answer).

As we get a few regular views, it's probably good to give an alternative to eval that will please everyone, and has all the benefits (and perhaps even more!) of this quick eval “trick”. Just use a function! Define a function with all your commands:

mypipe() {
    somecommand someargs | somecommand2
}

and execute it with your environment variables like this:

FOO=bar mypipe

How do I load a file from resource folder?

I faced the same issue.

The file was not found by a class loader, which means it was not packed into the artifact (jar). You need to build the project. For example, with maven:

mvn clean install

So the files you added to resources folder will get into maven build and become available to the application.

I would like to keep my answer: it does not explain how to read a file (other answers do explain that), it answers why InputStream or resource was null. Similar answer is here.

Null check in an enhanced for loop

You could potentially write a helper method which returned an empty sequence if you passed in null:

public static <T> Iterable<T> emptyIfNull(Iterable<T> iterable) {
    return iterable == null ? Collections.<T>emptyList() : iterable;
}

Then use:

for (Object object : emptyIfNull(someList)) {
}

I don't think I'd actually do that though - I'd usually use your second form. In particular, the "or throw ex" is important - if it really shouldn't be null, you should definitely throw an exception. You know that something has gone wrong, but you don't know the extent of the damage. Abort early.

VSCode Change Default Terminal

You can also select your default terminal by pressing F1 in VS Code and typing/selecting Terminal: Select Default Shell.

Terminal Selection

Terminal Selection

Limiting the output of PHP's echo to 200 characters

more flexible way is a function with two parameters:

function lchar($str,$val){return strlen($str)<=$val?$str:substr($str,0,$val).'...';}

usage:

echo lchar($str,200);

Fatal error: Please read "Security" section of the manual to find out how to run mysqld as root

The MySQL daemon should not be executed as the system user root which (normally) do not has any restrictions.

According to your cli, I suppose you wanted to execute the initscript instead:

sudo /etc/init.d/mysql stop

Another way would be to use the mysqladmin tool (note, root is the MySQL root user here, not the system root user):

/usr/local/mysql/bin/mysqladmin --port=8889 -u root shutdown