text:
Q: Reporting tool for OLAP, *not* OLTP! I'm looking for a control that I can put on top of an already existing OLAP star schema to allow the user to define their own "queries" and generate reports.  Right now I have some predefined reports built on top of the cubes, but I'd like to allow the user to define their own criteria based on the cubes that I've created.  I've found lots of products that will allow you to treat a transactional table like an OLAP cube, but nothing specifically for pre-existing cubes.
EDIT: Let me be clear, I know there are countless reporting tools out there that claim to report on OLAP cubes.  The problem is they all assume they are looking at transactional data and try to create their own cubes.  I have tables that contain tens, if not hundreds of millions of records.  Most tools crash when handling this much data, the others just run incredible slowly.  I don't want a tool that is targeting the business people.
I want a tool that understands what a star and snowflake schema is.  I want to be able to tell it what the fact tables are and what the dimension tables are, and then creates a UI on top of them.  This is an easier problem to solve for the tool vendor because I am spoon feeding them the cubes.  I want to rely on the fact that cubes are a standardized pattern and I want a tool that takes advantage of this fact.  I want a tool that targets developers and starts with the assumption that I actually know how to manage my data, it just needs to build pretty reports for me and not crumble under the weight of my data.

A: Well SSRS for SQL Server is designed to be used with cubes (we query our data warehouses with this all the time), but that is a vendor specific implementation and if you don't have SQL server you can't use it as it comes with SQL Server. You can write MDX queries and not just straight t-sql. I know you can reference other databases in queries, but I have never tried to reference a different vendors' tables becasue our data warehous in a SQL Server data warehouse.

A: I've used various reporting tools, but by far the most familiar to the end users is MS Excel Pivot Tables. Please follow this link to further information.

A: If you want a full enterprise-level software, you're looking for a tool like the Cognos(IBM) reporting suite. Their tools have a single query framework for reporting against both relational and OLAP sources, depending on how you model it. That means you can do multidimensional reporting against SQL server and MSAS with the same tool if it's modeled properly. They support their own cubes, TM1, ORacle, Microsoft, SAPBW, etc... There's an sdk you can use to write your own front-end tool as well. Not cheap, but nothing enterprise is.
Competitors in this field (I haven't used) are Business Objects(SAP) and Hyperion(Oracle). And maybe JasperSoft (open source).
Also check out the answer to this question. He mentions BO and a Microsoft solution.

A: Stefan, if your end-goal is for reporting I would suggest a tool like Tableau. It is very simply to learn for the average user and it allows them to make reports on the fly using the interface or type custom queries against the database. If you are looking for something more advanced I would suggest a product like CockPit (I know...) developed by a German based company that is also really neat and starting to take off.

A: You could try Dundas solution which allows end users to create their own reports based on dimensions and measures created in the cube.

A: Are you after something like Mondrian? We used it on a previous project, and I seem to recall its OLAP reporting was pretty good. Can't remember if it had a gui, though; that wasn't my area. I only ever messed with the config files...

A: Hi you can use SSRS where user can build reports just browsing the cube or u can write custom mdx queries using the OLAP advantage.
You can use SQL Server Report Builder
And last not least Microsoft Excel 2007 has good capability of browsing a cube
You can even expose your cube in SharePoint via Microsoft excel services 2007

A: I hold my hands up and freely-admit that I'm not an expert in this domain, but you could have a look at InfoBright.  I understand it will still go off and index your existing data (I'm not sure if it forms its own cubes), but I'm led to believe it can handle massive amounts of data quickly.
There's a community edition and a commercial edition too.  I've never used the software, but from what I've read about it before, it seems impressive.

A: You could give Web Pivot Table a try and it is a web based reporting tool which connect to both CSV files and OLAP cubes just like excel pivot table. Here is demo and documents.
You can connect to multiple source data (for example, multiple OLAP cubes), create multiple pivot tables and pivot charts and then create multiple reports based on any combination of these pivot tables and pivot charts.


text:
Q: How to check if a table contains a text string in any cell I have two long lists of names, and I'm trying to see where the differences in the lists are i.e. are there extra people in one list, and if so who.
I'm thinking that a good way to do this would be to use the match function, and then you can see where there are any errors, and hence the differences in the list.
My problem is a name in one list is not the same as it is in the other list, for example in one list we have Bob Mortimer, and in the other list we gave Mr Bob J Mortimer. I tried to get around this by using wildcards, but it didn't seem to work and I just kept getting #N/A
The formula I used is =MATCH("*"&F9&"*"&G9&"*",ListPersonnel!$E$9:$E$1287,0) where F9 and G9 are first name and last name respectively
I also tried the search function =SEARCH("*"&B3&"*"&C3&"*",ListPersonnel!$E$9:$E$1287), but again, to no avail.
I'm fairly certain I'm using these forumlas wrong, but I'm unsure how I can use either correctly
Any help would be appreciated.
Thanks

A: Simply, you are trying to find Duplicate Name between two columns. But to execute the formula to produce accurate result, you need to work with basics other wise no formula could deliver 100%.
Like, you have to make pattern. Name start with Title like Mr. or MR or Ms., white space between Title, First & Last Name, also like Name start with Last or First name.
Check the screen shot below, I've used three simple formula to determine Match or No Match or Duplicate name.

=IF(EXACT(A2, B2), "Duplicate", "No Match")

=IF(COUNTIF($A2:$B20, $A2)>1, "Full match", "No Match")

=IF(COUNTIF($B2:$B20, $A2)=0, "No match in B", "Match in B")

redpajama_set_name: RedPajamaStackExchange


text:
Q: Converting mysql tables from latin1 to utf8 I'm trying to convert some mysql tables from latin1 to utf8. I'm using the following command, which seems to mostly work.
ALTER TABLE tablename CONVERT TO CHARACTER SET utf8 COLLATE utf8_general_ci;

However, on one table I get an error about a duplicate key entry. This is caused by a unique index on a "name" field. It seems when converting to utf8, any "special" characters are indexed as their straight english equivalent. For example, there is already a record with a name field value of "Dru". When converting to utf8, a record with "Drü" is considered a duplicate. The same with "Patrick" and "Påtrìçk".
Here is how to reproduce the issue:
CREATE TABLE `example` (   `name` char(20) CHARACTER SET latin1 NOT NULL,
  PRIMARY KEY (`name`) ) ENGINE=MyISAM DEFAULT CHARSET=latin1;

INSERT INTO example (name) VALUES ('Drü'),('Dru'),('Patrick'),('Påtrìçk');

ALTER TABLE example convert to character set utf8 collate utf8_general_ci;
ERROR 1062 (23000): Duplicate entry 'Dru' for key 1

A: UTF8_GENERAL_CI is accent insensitive.
Use UTF8_BIN or a language-specific collation.

A: The reason why the strings 'Drü' and 'Dru' evaluate as the same is that in the utf8_general_ci collation, they count as "the same". The purpose of a collation for a character set is to provide a set of rules as to when strings are the same, when one sorts before the other, and so on.
If you want a different set of comparison rules, you need to choose a different collation. You can see the available collations for the utf8 character set by issuing SHOW COLLATION LIKE 'utf8%'. There are a bunch of collations intended for text that is mostly in a specific language; there is also the utf8_bin collation which compares all strings as binary strings (i.e. compares them as sequences of 0s and 1s).


text:
Q: fabric.js - fill an image with pattern I'm using Fabcy product designer and fabric.js for custom t-shirts and I need to fill a png image with a pattern but I didn't found examples that do that.
I tried with some snippet like the follow but it didn't works:
fabric.util.loadImage(url, function(img) {
    element.fill = new fabric.Pattern({
        source: img,
        repeat: 'repeat'
    });
    stage.renderAll.bind(stage);
});

Can you help me?
Thanks!


text:
Q: String Filtering .. Any one..Contains only either of the selected characters or both I have a array from 0 to 10000.
problem
And i need to filter only the numbers containing either 3 or 4 or both and none other than that...
eg., 3,4,33,44,333,444,343,434,334
I tried the do while technique but I have made some mistake in the code..\
I'm not getting the output still..:(
the improved code is
import java.util.*;

import static java.lang.System.*;
public class numb {
public static void main(String[] args) {
    int num,c,cum;
    int i;
     Scanner in = new Scanner(System.in);
     out.println(3/10);

    out.println("How many elements u need to put in this array?");
    num=in.nextInt();
    int[] ray1 = new int[num];
    List<String> l1 = new LinkedList<String>();
    for (c=0;c<num;c++)
    {

        ray1[c]=c;
    }

            for(i=1;i<num;i++)
            {
         boolean baabu=true;
                do {
                    cum=ray1[i];
                    int lastdig = cum%10;
                    if(lastdig!=3||lastdig!=4)
                    {
                        baabu=false;
                    }
                    cum=cum/10;
                }
                while(cum>0&&baabu);
                if(baabu)
                {
                    String ad = String.valueOf(ray1[i]);
                    l1.add(ad);
                }

            }
            printme(l1);

}

public static void print (int[] array)
{
    for(int xc:array)
        out.println(xc);
}
public static void printme (List<String> l1)
{
    for(String yc:l1)
        out.println(yc);
}

}

A: Check if the last digit is a 3 or a 4: if it is, divide the number by 10 and check the next digit; otherwise, discard the number.
boolean add = true;
do {
  int lastDigit = num % 10;
  if (lastDigit != 3 && lastDigit != 4) {
    add = false;
  }
  num /= 10;
} while (add && num > 0);

if (add) {
  // Add to list.
}

A: Think of the string as a list of characters, eg 3435 is 3,4,3,5 and 39 is 3,9. You need to iterate over the characters in the string and check that each one is a 3 or 4. Your code checks for specific combinations of 3 and 4 but cannot handle all possible enumerations.

A: Since you're treating the numbers as Strings already, the simplest way to find {3,4} strings is by matching the Regex "^[34]+$"
Pattern threeFourStrings = Pattern.compile("^[34]+$");
...
if (threeFourStrings.matcher(ad).matches()) {
    l1.add(ad);
}

However, since you want all {3,4} strings up to 10000 (i.e. up to 4 digits), it would be far more efficient to construct them.  You might start looking here: How to get all possible n-digit numbers that can be formed using given digits?
(Of course since you only have 2 digits, "3" and "4", it might be even more efficient to just list the binary numbers from 0 to 1111 and transpose "0" to "3" and "1" to "4".)

A: Use this method for every int in the array (it worked for me):
public static String myMethod(int num){

String str = String.valueOf(num);

String ns ="";
for (int i=0; i<str.length(); i++) {
if (str.substring(i, i+1).equals("3"))
{
  ns += 3;
}

if (str.substring(i, i+1).equals("4"))
{
  ns += 4;
}
}
return ns;

}


text:
Q: JavaScript closure inside loops – simple practical example

var funcs = [];
// let's create 3 functions
for (var i = 0; i < 3; i++) {
  // and store them in funcs
  funcs[i] = function() {
    // each should log its value.
    console.log("My value:", i);
  };
}
for (var j = 0; j < 3; j++) {
  // and now let's run each one to see
  funcs[j]();
}

It outputs this:

My value: 3
My value: 3
My value: 3

Whereas I'd like it to output:

My value: 0
My value: 1
My value: 2

The same problem occurs when the delay in running the function is caused by using event listeners:

var buttons = document.getElementsByTagName("button");
// let's create 3 functions
for (var i = 0; i < buttons.length; i++) {
  // as event listeners
  buttons[i].addEventListener("click", function() {
    // each should log its value.
    console.log("My value:", i);
  });
}
<button>0</button>

<button>1</button>

<button>2</button>

… or asynchronous code, e.g. using Promises:

// Some async wait function
const wait = (ms) => new Promise((resolve, reject) => setTimeout(resolve, ms));

for (var i = 0; i < 3; i++) {
  // Log `i` as soon as each promise resolves.
  wait(i * 100).then(() => console.log(i));
}

It is also apparent in for in and for of loops:

const arr = [1,2,3];
const fns = [];

for (var i in arr){
  fns.push(() => console.log("index:", i));
}

for (var v of arr){
  fns.push(() => console.log("value:", v));
}

for (const n of arr) {
  var obj = { number: n }; // or new MyLibObject({ ... })
  fns.push(() => console.log("n:", n, "|", "obj:", JSON.stringify(obj)));
}

for(var f of fns){
  f();
}

What's the solution to this basic problem?

A: Another way of saying it is that the i in your function is bound at the time of executing the function, not the time of creating the function.
When you create the closure, i is a reference to the variable defined in the outside scope, not a copy of it as it was when you created the closure. It will be evaluated at the time of execution.
Most of the other answers provide ways to work around by creating another variable that won't change the value for you.
Just thought I'd add an explanation for clarity. For a solution, personally, I'd go with Harto's since it is the most self-explanatory way of doing it from the answers here. Any of the code posted will work, but I'd opt for a closure factory over having to write a pile of comments to explain why I'm declaring a new variable(Freddy and 1800's) or have weird embedded closure syntax(apphacker).

A: First of all, understand what's wrong with this code:
var funcs = [];
for (var i = 0; i < 3; i++) {          // let's create 3 functions
    funcs[i] = function() {            // and store them in funcs
        console.log("My value: " + i); // each should log its value.
    };
}
for (var j = 0; j < 3; j++) {
    funcs[j]();                        // and now let's run each one to see
}

Here when the funcs[] array is being initialized, i is being incremented, the funcs array is initialized and the size of func array becomes 3,  so i = 3,.
Now when the funcs[j]() is called, it is again using the variable i, which has already been incremented to 3.
Now to solve this, we have many options. Below are two of them:

*

*We can initialize i with let or initialize a new variable index with let and make it equal to i. So when the call is being made, index will be used and its scope will end after initialization. And for calling, index will be initialized again:
var funcs = [];
for (var i = 0; i < 3; i++) {
    let index = i;
    funcs[i] = function() {
        console.log("My value: " + index);
    };
}
for (var j = 0; j < 3; j++) {
    funcs[j]();
}

*Other Option can be to introduce a tempFunc which returns the actual function:
var funcs = [];
function tempFunc(i){
    return function(){
        console.log("My value: " + i);
    };
}
for (var i = 0; i < 3; i++) {
    funcs[i] = tempFunc(i);
}
for (var j = 0; j < 3; j++) {
    funcs[j]();
}

A: Use closure structure, this would reduce your extra for loop. You can do it in a single for loop:
var funcs = [];
for (var i = 0; i < 3; i++) {
  (funcs[i] = function() {
    console.log("My value: " + i);
  })(i);
}

A: What you need to understand is the scope of the variables in javascript is based on the function. This is an important difference than say c# where you have block scope, and just copying the variable to one inside the for will work.
Wrapping it in a function that evaluates returning the function like apphacker's answer will do the trick, as the variable now has the function scope.
There is also a let keyword instead of var, that would allow using the block scope rule. In that case defining a variable inside the for would do the trick. That said, the let keyword isn't a practical solution because of compatibility.

var funcs = {};

for (var i = 0; i < 3; i++) {
  let index = i; //add this
  funcs[i] = function() {
    console.log("My value: " + index); //change to the copy
  };
}

for (var j = 0; j < 3; j++) {
  funcs[j]();
}

A: Till ES5, This problem can only be solved using closure.
But now in ES6, we have block level scope variables. Changing var to let in first for loop will solve the problem.

var funcs = [];
for (let i = 0; i < 3; i++) {      // let's create 3 functions
  funcs[i] = function() {          // and store them in funcs
    console.log("My value: " + i); // each should log its value.
  };
}
for (var j = 0; j < 3; j++) {
  funcs[j]();                      // and now let's run each one to see
}

A: If you're having this sort of problem with a while loop, rather than a for loop, for example:

var i = 0;
while (i < 5) {
  setTimeout(function() {
    console.log(i);
  }, i * 1000);
  i++;
}

The technique to close over the current value is a bit different. Declare a block-scoped variable with const inside the while block, and assign the current i to it. Then, wherever the variable is being used asynchronously, replace i with the new block-scoped variable:

var i = 0;
while (i < 5) {
  const thisIterationI = i;
  setTimeout(function() {
    console.log(thisIterationI);
  }, i * 1000);
  i++;
}

For older browsers that don't support block-scoped variables, you can use an IIFE called with i:

var i = 0;
while (i < 5) {
  (function(innerI) {
    setTimeout(function() {
      console.log(innerI);
    }, innerI * 1000);
  })(i);
  i++;
}

If the asynchronous action to be invoked happens to be setTimeout like the above, you can also call setTimeout with a third parameter to indicate the argument to call the passed function with:

var i = 0;
while (i < 5) {
  setTimeout(
    (thisIterationI) => { // Callback
      console.log(thisIterationI);
    },
    i * 1000, // Delay
    i // Gets passed to the callback; becomes thisIterationI
  );
  i++;
}

A: Here's another variation on the technique, similar to Bjorn's (apphacker), which lets you assign the variable value inside the function rather than passing it as a parameter, which might be clearer sometimes:

var funcs = [];
for (var i = 0; i < 3; i++) {
    funcs[i] = (function() {
        var index = i;
        return function() {
            console.log("My value: " + index);
        }
    })();
}

Note that whatever technique you use, the index variable becomes a sort of static variable, bound to the returned copy of the inner function. I.e., changes to its value are preserved between calls. It can be very handy.

A: This describes the common mistake with using closures in JavaScript.
A function defines a new environment
Consider:
function makeCounter()
{
  var obj = {counter: 0};
  return {
    inc: function(){obj.counter ++;},
    get: function(){return obj.counter;}
  };
}

counter1 = makeCounter();
counter2 = makeCounter();

counter1.inc();

alert(counter1.get()); // returns 1
alert(counter2.get()); // returns 0

For each time makeCounter is invoked, {counter: 0} results in a new object being created. Also, a new copy of obj
is created as well to reference the new object. Thus, counter1 and counter2 are independent of each other.
Closures in loops
Using a closure in a loop is tricky.
Consider:
var counters = [];

function makeCounters(num)
{
  for (var i = 0; i < num; i++)
  {
    var obj = {counter: 0};
    counters[i] = {
      inc: function(){obj.counter++;},
      get: function(){return obj.counter;}
    };
  }
}

makeCounters(2);

counters[0].inc();

alert(counters[0].get()); // returns 1
alert(counters[1].get()); // returns 1

Notice that counters[0] and counters[1] are not independent. In fact, they operate on the same obj!
This is because there is only one copy of obj shared across all iterations of the loop, perhaps for performance reasons.
Even though {counter: 0} creates a new object in each iteration, the same copy of obj will just get updated with a
reference to the newest object.
Solution is to use another helper function:
function makeHelper(obj)
{
  return {
    inc: function(){obj.counter++;},
    get: function(){return obj.counter;}
  };
}

function makeCounters(num)
{
  for (var i = 0; i < num; i++)
  {
    var obj = {counter: 0};
    counters[i] = makeHelper(obj);
  }
}

This works because local variables in the function scope directly, as well as function argument variables, are allocated
new copies upon entry.

A: The most simple solution would be,
Instead of using:
var funcs = [];
for(var i =0; i<3; i++){
    funcs[i] = function(){
        alert(i);
    }
}

for(var j =0; j<3; j++){
    funcs[j]();
}

which alerts "2", for 3 times. This is because anonymous functions created in for loop, shares same closure, and in that closure, the value of i is the same. Use this to prevent shared closure:
var funcs = [];
for(var new_i =0; new_i<3; new_i++){
    (function(i){
        funcs[i] = function(){
            alert(i);
        }
    })(new_i);
}

for(var j =0; j<3; j++){
    funcs[j]();
}

The idea behind this is, encapsulating the entire body of the for loop with an IIFE (Immediately-Invoked Function Expression) and passing new_i as a parameter and capturing it as i. Since the anonymous function is executed immediately, the i value is different for each function defined inside the anonymous function.
This solution seems to fit any such problem since it will require minimal changes to the original code suffering from this issue. In fact, this is by design, it should not be an issue at all!

A: Try:

var funcs = [];

for (var i = 0; i < 3; i++) {
    funcs[i] = (function(index) {
        return function() {
            console.log("My value: " + index);
        };
    }(i));
}

for (var j = 0; j < 3; j++) {
    funcs[j]();
}

Edit (2014):
Personally I think @Aust's more recent answer about using .bind is the best way to do this kind of thing now. There's also lo-dash/underscore's _.partial when you don't need or want to mess with bind's thisArg.

A: You could use a declarative module for lists of data such as query-js(*). In these situations I personally find a declarative approach less surprising
var funcs = Query.range(0,3).each(function(i){
     return  function() {
        console.log("My value: " + i);
    };
});

You could then use your second loop and get the expected result or you could do
funcs.iterate(function(f){ f(); });

(*) I'm the author of query-js and therefor biased towards using it, so don't take my words as a recommendation for said library only for the declarative approach :)

A: I prefer to use forEach function, which has its own closure with creating a pseudo range:
var funcs = [];

new Array(3).fill(0).forEach(function (_, i) { // creating a range
    funcs[i] = function() {
        // now i is safely incapsulated
        console.log("My value: " + i);
    };
});

for (var j = 0; j < 3; j++) {
    funcs[j](); // 0, 1, 2
}

That looks uglier than ranges in other languages, but IMHO less monstrous than other solutions.

A: And yet another solution: instead of creating another loop, just bind the this to the return function.

var funcs = [];

function createFunc(i) {
  return function() {
    console.log('My value: ' + i); //log value of i.
  }.call(this);
}

for (var i = 1; i <= 5; i++) {  //5 functions
  funcs[i] = createFunc(i);     // call createFunc() i=5 times
}

By binding this, solves the problem as well.

A: Another way that hasn't been mentioned yet is the use of Function.prototype.bind

var funcs = {};
for (var i = 0; i < 3; i++) {
  funcs[i] = function(x) {
    console.log('My value: ' + x);
  }.bind(this, i);
}
for (var j = 0; j < 3; j++) {
  funcs[j]();
}

UPDATE
As pointed out by @squint and @mekdev, you get better performance by creating the function outside the loop first and then binding the results within the loop.

function log(x) {
  console.log('My value: ' + x);
}

var funcs = [];

for (var i = 0; i < 3; i++) {
  funcs[i] = log.bind(this, i);
}

for (var j = 0; j < 3; j++) {
  funcs[j]();
}

A: Here's a simple solution that uses forEach (works back to IE9):

var funcs = [];
[0,1,2].forEach(function(i) {          // let's create 3 functions
    funcs[i] = function() {            // and store them in funcs
        console.log("My value: " + i); // each should log its value.
    };
})
for (var j = 0; j < 3; j++) {
    funcs[j]();                        // and now let's run each one to see
}

Prints:

My value: 0
My value: 1
My value: 2

A: try this shorter one

*

*no array

*no extra for loop

for (var i = 0; i < 3; i++) {
    createfunc(i)();
}

function createfunc(i) {
    return function(){console.log("My value: " + i);};
}

http://jsfiddle.net/7P6EN/

A: The main issue with the code shown by the OP is that i is never read until the second loop. To demonstrate, imagine seeing an error inside of the code
funcs[i] = function() {            // and store them in funcs
    throw new Error("test");
    console.log("My value: " + i); // each should log its value.
};

The error actually does not occur until funcs[someIndex] is executed (). Using this same logic, it should be apparent that the value of i is also not collected until this point either. Once the original loop finishes, i++ brings i to the value of 3 which results in the condition i < 3 failing and the loop ending. At this point, i is 3 and so when funcs[someIndex]() is used, and i is evaluated, it is 3 - every time.
To get past this, you must evaluate i as it is encountered. Note that this has already happened in the form of funcs[i] (where there are 3 unique indexes). There are several ways to capture this value. One is to pass it in as a parameter to a function which is shown in several ways already here.
Another option is to construct a function object which will be able to close over the variable. That can be accomplished thusly
jsFiddle Demo
funcs[i] = new function() {
    var closedVariable = i;
    return function(){
        console.log("My value: " + closedVariable);
    };
};

A: Your code doesn't work, because what it does is:
Create variable `funcs` and assign it an empty array;
Loop from 0 up until it is less than 3 and assign it to variable `i`;
    Push to variable `funcs` next function:
        // Only push (save), but don't execute
        **Write to console current value of variable `i`;**

// First loop has ended, i = 3;

Loop from 0 up until it is less than 3 and assign it to variable `j`;
    Call `j`-th function from variable `funcs`:
        **Write to console current value of variable `i`;**
        // Ask yourself NOW! What is the value of i?

Now the question is, what is the value of variable i when the function is called? Because the first loop is created with the condition of i < 3, it stops immediately when the condition is false, so it is i = 3.
You need to understand that, in time when your functions are created, none of their code is executed, it is only saved for later. And so when they are called later, the interpreter executes them and asks: "What is the current value of i?"
So, your goal is to first save the value of i to function and only after that save the function to funcs. This could be done for example this way:
var funcs = [];
for (var i = 0; i < 3; i++) {          // let's create 3 functions
    funcs[i] = function(x) {            // and store them in funcs
        console.log("My value: " + x); // each should log its value.
    }.bind(null, i);
}
for (var j = 0; j < 3; j++) {
    funcs[j]();                        // and now let's run each one to see
}

This way, each function will have it's own variable x and we set this x to the value of i in each iteration.
This is only one of the multiple ways to solve this problem.

A: var funcs = [];
for (var i = 0; i < 3; i++) {      // let's create 3 functions
  funcs[i] = function(param) {          // and store them in funcs
    console.log("My value: " + param); // each should log its value.
  };
}
for (var j = 0; j < 3; j++) {
  funcs[j](j);                      // and now let's run each one to see with j
}

A: Use let(blocked-scope) instead of var.

var funcs = [];
for (let i = 0; i < 3; i++) {
  funcs[i] = function() {
    console.log("My value: " + i);
  };
}
for (var j = 0; j < 3; j++) {
  funcs[j]();
}

A: Using an Immediately-Invoked Function Expression, the simplest and most readable way to enclose an index variable:

for (var i = 0; i < 3; i++) {

    (function(index) {

        console.log('iterator: ' + index);
        //now you can also loop an ajax call here
        //without losing track of the iterator value:   $.ajax({});

    })(i);

}

This sends the iterator i into the anonymous function of which we define as index.  This creates a closure, where the variable i gets saved for later use in any asynchronous functionality within the IIFE.

A: JavaScript functions "close over" the scope they have access to upon declaration, and retain access to that scope even as variables in that scope change.

var funcs = []

for (var i = 0; i < 3; i += 1) {
  funcs[i] = function () {
    console.log(i)
  }
}

for (var k = 0; k < 3; k += 1) {
  funcs[k]()
}

Each function in the array above closes over the global scope (global, simply because that happens to be the scope they're declared in).
Later those functions are invoked logging the most current value of i in the global scope. That's the magic, and frustration, of closure.
"JavaScript Functions close over the scope they are declared in, and retain access to that scope even as variable values inside of that scope change."
Using let instead of var solves this by creating a new scope each time the for loop runs, creating a separated scope for each function to close over. Various other techniques do the same thing with extra functions.

var funcs = []

for (let i = 0; i < 3; i += 1) {
  funcs[i] = function () {
    console.log(i)
  }
}

for (var k = 0; k < 3; k += 1) {
  funcs[k]()
}

(let makes variables block scoped. Blocks are denoted by curly braces, but in the case of the for loop the initialization variable, i in our case, is considered to be declared in the braces.)

A: Well, the problem is that the variable i, within each of your anonymous functions, is bound to the same variable outside of the function.
ES6 solution: let
ECMAScript 6 (ES6) introduces new let and const keywords that are scoped differently than var-based variables. For example, in a loop with a let-based index, each iteration through the loop will have a new variable i with loop scope, so your code would work as you expect. There are many resources, but I'd recommend 2ality's block-scoping post as a great source of information.
for (let i = 0; i < 3; i++) {
  funcs[i] = function() {
    console.log("My value: " + i);
  };
}

Beware, though, that IE9-IE11 and Edge prior to Edge 14 support let but get the above wrong (they don't create a new i each time, so all the functions above would log 3 like they would if we used var). Edge 14 finally gets it right.

ES5.1 solution: forEach
With the relatively widespread availability of the Array.prototype.forEach function (in 2015), it's worth noting that in those situations involving iteration primarily over an array of values, .forEach() provides a clean, natural way to get a distinct closure for every iteration. That is, assuming you've got some sort of array containing values (DOM references, objects, whatever), and the problem arises of setting up callbacks specific to each element, you can do this:
var someArray = [ /* whatever */ ];
// ...
someArray.forEach(function(arrayElement) {
  // ... code code code for this one element
  someAsynchronousFunction(arrayElement, function() {
    arrayElement.doSomething();
  });
});

The idea is that each invocation of the callback function used with the .forEach loop will be its own closure. The parameter passed in to that handler is the array element specific to that particular step of the iteration. If it's used in an asynchronous callback, it won't collide with any of the other callbacks established at other steps of the iteration.
If you happen to be working in jQuery, the $.each() function gives you a similar capability.

Classic solution: Closures
What you want to do is bind the variable within each function to a separate, unchanging value outside of the function:

var funcs = [];

function createfunc(i) {
  return function() {
    console.log("My value: " + i);
  };
}

for (var i = 0; i < 3; i++) {
  funcs[i] = createfunc(i);
}

for (var j = 0; j < 3; j++) {
  // and now let's run each one to see
  funcs[j]();
}

Since there is no block scope in JavaScript - only function scope - by wrapping the function creation in a new function, you ensure that the value of "i" remains as you intended.

A: This is a problem often encountered with asynchronous code, the variable i is mutable and at the time at which the function call is made the code using i will be executed and i will have mutated to its last value, thus meaning all functions created within the loop will create a closure and i will be equal to 3 (the upper bound + 1 of the for loop.
A workaround to this, is to create a function that will hold the value of i for each iteration and force a copy i (as it is a primitive, think of it as a snapshot if it helps you).

A: Many solutions seem correct but they don't mention it's called Currying which is a functional programming design pattern for situations like here. 3-10 times faster than bind depending on the browser.
var funcs = [];
for (var i = 0; i < 3; i++) {      // let's create 3 functions
  funcs[i] = curryShowValue(i);
}
for (var j = 0; j < 3; j++) {
  funcs[j]();                      // and now let's run each one to see
}

function curryShowValue(i) {
  return function showValue() {
    console.log("My value: " + i);
  }
}

See the performance gain in different browsers.

A: COUNTER BEING A PRIMITIVE
Let's define callback functions as follows:
// ****************************
// COUNTER BEING A PRIMITIVE
// ****************************
function test1() {
    for (var i=0; i<2; i++) {
        setTimeout(function() {
            console.log(i);
        });
    }
}
test1();
// 2
// 2

After timeout completes it will print 2 for both. This is because the callback function accesses the value based on the lexical scope, where it was function was defined.
To pass and preserve the value while callback was defined, we can create a closure, to preserve the value before the callback is invoked. This can be done as follows:
function test2() {
    function sendRequest(i) {
        setTimeout(function() {
            console.log(i);
        });
    }

    for (var i = 0; i < 2; i++) {
        sendRequest(i);
    }
}
test2();
// 1
// 2

Now what's special about this is "The primitives are passed by value and copied. Thus when the closure is defined, they keep the value from the previous loop."
COUNTER BEING AN OBJECT
Since closures have access to parent function variables via reference, this approach would differ from that for primitives.
// ****************************
// COUNTER BEING AN OBJECT
// ****************************
function test3() {
    var index = { i: 0 };
    for (index.i=0; index.i<2; index.i++) {
        setTimeout(function() {
            console.log('test3: ' + index.i);
        });
    }
}
test3();
// 2
// 2

So, even if a closure is created for the variable being passed as an object, the value of the loop index will not be preserved. This is to show that the values of an object are not copied whereas they are accessed via reference.
function test4() {
    var index = { i: 0 };
    function sendRequest(index, i) {
        setTimeout(function() {
            console.log('index: ' + index);
            console.log('i: ' + i);
            console.log(index[i]);
        });
    }

    for (index.i=0; index.i<2; index.i++) {
        sendRequest(index, index.i);
    }
}
test4();
// index: { i: 2}
// 0
// undefined

// index: { i: 2}
// 1
// undefined

A: Bit late to the party, but I was exploring this issue today and noticed that many of the answers don't completely address how Javascript treats scopes, which is essentially what this boils down to.
So as many others mentioned, the problem is that the inner function is referencing the same i variable. So why don't we just create a new local variable each iteration, and have the inner function reference that instead?

//overwrite console.log() so you can see the console output
console.log = function(msg) {document.body.innerHTML += '
' + msg + '
';};

var funcs = {};
for (var i = 0; i < 3; i++) {
    var ilocal = i; //create a new local variable
    funcs[i] = function() {
        console.log("My value: " + ilocal); //each should reference its own local variable
    };
}
for (var j = 0; j < 3; j++) {
    funcs[j]();
}

Just like before, where each inner function outputted the last value assigned to i, now each inner function just outputs the last value assigned to ilocal. But shouldn't each iteration have it's own ilocal?
Turns out, that's the issue. Each iteration is sharing the same scope, so every iteration after the first is just overwriting ilocal. From MDN:

Important: JavaScript does not have block scope. Variables introduced with a block are scoped to the containing function or script, and the effects of setting them persist beyond the block itself. In other words, block statements do not introduce a scope. Although "standalone" blocks are valid syntax, you do not want to use standalone blocks in JavaScript, because they don't do what you think they do, if you think they do anything like such blocks in C or Java.

Reiterated for emphasis:

JavaScript does not have block scope. Variables introduced with a block are scoped to the containing function or script

We can see this by checking ilocal before we declare it in each iteration:

//overwrite console.log() so you can see the console output
console.log = function(msg) {document.body.innerHTML += '
' + msg + '
';};

var funcs = {};
for (var i = 0; i < 3; i++) {
  console.log(ilocal);
  var ilocal = i;
}

This is exactly why this bug is so tricky. Even though you are redeclaring a variable, Javascript won't throw an error, and JSLint won't even throw a warning. This is also why the best way to solve this is to take advantage of closures, which is essentially the idea that in Javascript, inner functions have access to outer variables because inner scopes "enclose" outer scopes.

This also means that inner functions "hold onto" outer variables and keep them alive, even if the outer function returns. To utilize this, we create and call a wrapper function purely to make a new scope, declare ilocal in the new scope, and return an inner function that uses ilocal (more explanation below):

//overwrite console.log() so you can see the console output
console.log = function(msg) {document.body.innerHTML += '
' + msg + '
';};

var funcs = {};
for (var i = 0; i < 3; i++) {
    funcs[i] = (function() { //create a new scope using a wrapper function
        var ilocal = i; //capture i into a local var
        return function() { //return the inner function
            console.log("My value: " + ilocal);
        };
    })(); //remember to run the wrapper function
}
for (var j = 0; j < 3; j++) {
    funcs[j]();
}

Creating the inner function inside a wrapper function gives the inner function a private environment that only it can access, a "closure". Thus, every time we call the wrapper function we create a new inner function with it's own separate environment, ensuring that the ilocal variables don't collide and overwrite each other. A few minor optimizations gives the final answer that many other SO users gave:

//overwrite console.log() so you can see the console output
console.log = function(msg) {document.body.innerHTML += '
' + msg + '
';};

var funcs = {};
for (var i = 0; i < 3; i++) {
    funcs[i] = wrapper(i);
}
for (var j = 0; j < 3; j++) {
    funcs[j]();
}
//creates a separate environment for the inner function
function wrapper(ilocal) {
    return function() { //return the inner function
        console.log("My value: " + ilocal);
    };
}

Update
With ES6 now mainstream, we can now use the new let keyword to create block-scoped variables:

//overwrite console.log() so you can see the console output
console.log = function(msg) {document.body.innerHTML += '
' + msg + '
';};

var funcs = {};
for (let i = 0; i < 3; i++) { // use "let" to declare "i"
    funcs[i] = function() {
        console.log("My value: " + i); //each should reference its own local variable
    };
}
for (var j = 0; j < 3; j++) { // we can use "var" here without issue
    funcs[j]();
}

Look how easy it is now! For more information see this answer, which my info is based off of.

A: With ES6 now widely supported, the best answer to this question has changed.  ES6 provides the let and const keywords for this exact circumstance.  Instead of messing around with closures, we can just use let to set a loop scope variable like this:

var funcs = [];

for (let i = 0; i < 3; i++) {
    funcs[i] = function() {
      console.log("My value: " + i);
    };
}

val will then point to an object that is specific to that particular turn of the loop, and will return the correct value without the additional closure notation.  This obviously significantly simplifies this problem.
const is similar to let with the additional restriction that the variable name can't be rebound to a new reference after initial assignment.
Browser support is now here for those targeting the latest versions of browsers. const/let are currently supported in the latest Firefox, Safari, Edge and Chrome. It also is supported in Node, and you can use it anywhere by taking advantage of build tools like Babel.  You can see a working example here: http://jsfiddle.net/ben336/rbU4t/2/
Docs here:

*

*const

*let
Beware, though, that IE9-IE11 and Edge prior to Edge 14 support let but get the above wrong (they don't create a new i each time, so all the functions above would log 3 like they would if we used var). Edge 14 finally gets it right.

A: After reading through various solutions, I'd like to add that the reason those solutions work is to rely on the concept of scope chain. It's the way JavaScript resolve a variable during execution.

*

*Each function definition forms a scope consisting of all the local
variables declared by var and its arguments.

*If we have inner function defined inside another (outer) function, this
forms a chain, and will be used during execution

*When a function gets executed, the runtime evaluates variables by searching the scope chain. If a variable can be found in a certain point of the chain it will stop searching and use it, otherwise it continues until the global scope reached which belongs to window.

In the initial code:
funcs = {};
for (var i = 0; i < 3; i++) {
  funcs[i] = function inner() {        // function inner's scope contains nothing
    console.log("My value: " + i);
  };
}
console.log(window.i)                  // test value 'i', print 3

When funcs gets executed, the scope chain will be function inner -> global. Since the variable i cannot be found in function inner (neither declared using var nor passed as arguments), it continues to search, until the value of i is eventually found in the global scope which is window.i.
By wrapping it in an outer function either explicitly define a helper function like harto did or use an anonymous function like Bjorn did:
funcs = {};
function outer(i) {              // function outer's scope contains 'i'
  return function inner() {      // function inner, closure created
   console.log("My value: " + i);
  };
}
for (var i = 0; i < 3; i++) {
  funcs[i] = outer(i);
}
console.log(window.i)          // print 3 still

When funcs gets executed, now the scope chain will be function inner -> function outer. This time i can be found in the outer function's scope which is executed 3 times in the for loop, each time has value i bound correctly. It won't use the value of window.i when inner executed.
More detail can be found here
It includes the common mistake in creating closure in the loop as what we have here, as well as why we need closure and the performance consideration.

A: With new features of ES6 block level scoping is managed:
var funcs = [];
for (let i = 0; i < 3; i++) {          // let's create 3 functions
    funcs[i] = function() {            // and store them in funcs
        console.log("My value: " + i); // each should log its value.
    };
}
for (let j = 0; j < 3; j++) {
    funcs[j]();                        // and now let's run each one to see
}

The code in OP's question is replaced with let instead of var.

A:
We will check , what actually happens when you declare var and let
one by one.

Case1 : using var

Now open your chrome console window by pressing F12 and refresh the page.
Expend every 3 functions inside the array.You will see an property called [[Scopes]].Expand that one. You will see one
array object called "Global",expand that one. You will find a property 'i' declared into the object which having value 3.

Conclusion:

*

*When you declare a variable using 'var' outside a function ,it becomes global variable(you can check by typing i or
window.i in console window.It will return 3).

*The anonymous function you declared will not call and check the value inside the function unless you invoke the
functions.

*When you invoke the function , console.log("My value: " + i) takes the value from its Global object and display the
result.

CASE2 : using let
Now replace the 'var' with 'let'

Do the same thing, Go to the scopes . Now you will see two objects "Block" and "Global". Now expand Block object , you
will see 'i' is defined there , and the strange thing is that , for every functions , the value if i is different (0 , 1, 2).

Conclusion:
When you declare variable using 'let' even outside the function but inside the loop , this variable will not be a Global
variable , it will become a Block level variable which is only available for the same function only.That is the reason , we
are getting value of i different for each function when we invoke the functions.
For more detail about how closer works , please go through the awesome video tutorial https://youtu.be/71AtaJpJHw0

A: I'm surprised no one yet has suggested using the forEach function to better avoid (re)using local variables. In fact, I'm not using for(var i ...) at all anymore for this reason.
[0,2,3].forEach(function(i){ console.log('My value:', i); });
// My value: 0
// My value: 2
// My value: 3

// edited to use forEach instead of map.

A: The reason your original example did not work is that all the closures you created in the loop referenced the same frame. In effect, having 3 methods on one object with only a single i variable. They all printed out the same value.

A: This question really shows the history of JavaScript! Now we can avoid block scoping with arrow functions and handle loops directly from DOM nodes using Object methods.

const funcs = [1, 2, 3].map(i => () => console.log(i));
funcs.map(fn => fn())

const buttons = document.getElementsByTagName("button");
Object
  .keys(buttons)
  .map(i => buttons[i].addEventListener('click', () => console.log(i)));
<button>0</button>

<button>1</button>

<button>2</button>

A: Just change the var keyword to let.
var is function scoped.
let is block scoped.
When you start you code the for loop will iterate and assign the value of i to 3, which will remain 3 throughout your code. I suggest you to read more about scopes in node (let,var,const and others)
funcs = [];
for (let i = 0; i < 3; i++) {      // let's create 3 functions
  funcs[i] =async function() {          // and store them in funcs
    await console.log("My value: " + i); // each should log its value.
  };
}
for (var j = 0; j < 3; j++) {
  funcs[j]();                      // and now let's run each one to see
}

A: Let's take advantage of new Function. Thus i stops to be a variable of a closure and becomes just a part of the text:
var funcs = [];
for (var i = 0; i < 3; i++) {
    var functionBody = 'console.log("My value: ' + i + '");';
    funcs[i] = new Function(functionBody);
}

for (var j = 0; j < 3; j++) {
    funcs[j]();
}

A: While this question is old and answered,  I have yet another fairly interesting solution:
var funcs = [];

for (var i = 0; i < 3; i++) {
  funcs[i] = function() {
    console.log("My value: " + i);
 };
}

for (var i = 0; i < 3; i++) {
  funcs[i]();
}

The change is so small it's almost difficult to see what I did. I switched the second iterator from a j to an i. This somehow refreshes the state of i in time to give you the desired result. I did this by accident but it makes sense considering previous answers.
I wrote this up to point out this small, yet very important difference. Hope that helps to clear up some confusion for other learners like me.
Note: I am not sharing this because I think it's the right answer. This is a flakey solution that probably will break under certain circumstances. Actually, I'm quite amazed that it really works.

A: Let's say you don't use ES6;
You can use IIFEs:
var funcs = [];
for (var i = 0; i < 13; i++) {
    funcs[i] = (function(x) {
      console.log("My value: " + i)
     })(i);
   }

But it will be different.

A: Ok. I read through all of the answers. Even though there is a good explanation here - I just could not get this to work. So I went looking on the internet. The person at https://dzone.com/articles/why-does-javascript-loop-only-use-last-value had an answer which is not presented here. So I thought I'd post a short example. This made a lot more sense to me.
The long and short of it is that the LET command is nice but is only now being used. HOWEVER, the LET command is really just a TRY-CATCH combo. This works all the way back to IE3 (I believe). Using the TRY-CATCH combo - life is simple and good. Probably why the EMCScript people decided to use it. It also does not need a setTimeout() function. So no time is lost. Basically, you need one TRY-CATCH combo per FOR loop. Here is an example:
    for( var i in myArray ){
       try{ throw i }
       catch(ii){
// Do whatever it is you want to do with ii
          }
       }

If you have more than one FOR loop, you just put a TRY-CATCH combo for each one. Also, personally, I always use the double letter of whatever FOR variable I am using. So "ii" for "i" and so on. I am using this technique in a routine to send mouseover commands to a different routine.

A: This proves how ugly javascript is with regard to how 'closure' and 'non-closure' works.
In the case of:
var funcs = [];

for (var i = 0; i < 3; i++) {      // let's create 3 functions
  funcs[i] = function() {          // and store them in funcs
    console.log("My value: " + i); // each should log its value.
  };
}

funcs[i] is a global function, and 'console.log("My value: " + i);' is printing global variable i
In the case of
var funcs = [];

function createfunc(i) {
    return function() { console.log("My value: " + i); };
}

for (var i = 0; i < 3; i++) {
    funcs[i] = createfunc(i);
}

because of this twisted closure design of javascript, 'console.log("My value: " + i);' is printing the i from outer function 'createfunc(i)'
all because javascript can not design something decent like the 'static' variable inside a function like what C programming language is doing!

A: Already many valid answers to this question. Not many using a functional approach though. Here is an alternative solution using the forEach method, which works well with callbacks and closures:
let arr = [1,2,3];
let myFunc = (val, index) => {
    console.log('val: '+val+'\nindex: '+index);
};
arr.forEach(myFunc);

A: Why not simply call each function inside the first (and only) loop just after they were created, such as:
 var funcs = [];
    for (var i = 0; i < 3; i++) {
    // let's create 3 functions
    funcs[i] = function() {
    // and store them in funcs
    console.log("My value: " + i); // each should log its value.
    };
    funcs[i]();// and now let's run each one to see
    }

A: With the support of ES6, the best way to this is to use let and const keywords for this exact circumstance. So var variable get hoisted and with the end of loop the value of i gets updated for all the closures..., we can just use let to set a loop scope variable like this:
var funcs = [];
for (let i = 0; i < 3; i++) {
    funcs[i] = function() {
      console.log("My value: " + i);
    };
}

A:   asyncIterable = [1,2,3,4,5,6,7,8];

  (async function() {
       for await (let num of asyncIterable) {
         console.log(num);
       }
    })();


text:
Q: KNIME node extension fails to execute: "Support code location could not be determined" I'm creating a node extension for KNIME with the KNIME SDK (which is just an adapted Eclipse). I'm done with my code, I tested it in Eclipse, it worked perfectly. So I exported it, copied the .jar to the subfolder dropins in my KNIME installation, and started KNIME. Made a new workflow, added my node, tried to execute it and then the following error appeared:
Execute failed: Support code location could not be determined. Could not convert from URL to URI location.
URL Location: file:/C:/Program Files/KNIME_2.11.2/configuration/org.eclipse.osgi/bundles/528/1/.cp/matlabcontrol-4.1.0.jar
Code Source: (file:/C:/Program Files/KNIME_2.11.2/configuration/org.eclipse.osgi/bundles/528/1/.cp/matlabcontrol-4.1.0.jar <no signer certificates>)
Protection Domain: ProtectionDomain  (file:/C:/Program Files/KNIME_2.11.2/configuration/org.eclipse.osgi/bundles/528/1/.cp/matlabcontrol-4.1.0.jar <no signer certificates>)
 null
 <no principals>
 java.security.AllPermissionCollection@6ac1c077 (
 ("java.security.AllPermission" "<all permissions>" "<all actions>")
)

Class Loader: org.eclipse.osgi.internal.baseadaptor.DefaultClassLoader@b836456
Class Loader Class: class org.eclipse.osgi.internal.baseadaptor.DefaultClassLoader

According to a thread on the KNIME forums, a similar problem also occurs with the community extension "Matlab Snippet", which builds on the same matlabcontrol framework I use (which is also the one mentioned in the error).
I tried evading the problem by including the matlabcontrol as a package in my project (it's open source, so I could just import the sources), then the same error appeared and mentioned the package .jar created by the OSGI system (in my case, matlab.jar, which is the name I chose in my build.properties), so I assume it was just the first one alphabetically and all of the files in the OSGI bundle folder are affected by this problem.
What confuses me is that the problem only occurs once I try to execute the node and connect to MATLAB. Unfortunately, the problem doesn't seem to have been resolved in the KNIME forum thread linked above, apparently an older version of that extension didn't have the issue and users just installed the old version.
So, can I somehow make the URL correctly convert to URI? Is the Protection Domain the cause and can I change it? Does it have anything to do with the default Class Loader?

I have now installed the plugin via a feature in a folder (see comments). The error persists, but the path changed:
Execute failed: Support code location could not be determined. Could not convert from URL to URI location.
URL Location: file:/C:/Program Files/KNIME_2.11.2/plugins/org.knime.ext.matlab_1.0.0/matlab.jar
Code Source: (file:/C:/Program Files/KNIME_2.11.2/plugins/org.knime.ext.matlab_1.0.0/matlab.jar <no signer certificates>)
Protection Domain: ProtectionDomain  (file:/C:/Program Files/KNIME_2.11.2/plugins/org.knime.ext.matlab_1.0.0/matlab.jar <no signer certificates>)
 null
 <no principals>
 java.security.AllPermissionCollection@2da869b5 (
 ("java.security.AllPermission" "<all permissions>" "<all actions>")
)

Class Loader: org.eclipse.osgi.internal.baseadaptor.DefaultClassLoader@372bf03c
Class Loader Class: class org.eclipse.osgi.internal.baseadaptor.DefaultClassLoader


text:
Q: Why is my ContextMenu item bound to a RelayCommand is always disabled? I'm working on my first big WPF MVVM application now, which uses MVVM Light Toolkit in combination with Josh Smith's RelayCommand.
The problem I run into is that I bound this command to an item in a ContextMenu, which keeps disabled all the time.
Here's a code snippet of the MenuItem:
<MenuItem
    Header="Verwijderen"
    Command="{StaticResource DeleteNoteCommandReference}"
    CommandParameter="{Binding}" />

Now what I've done with the commandbinding is the following: I used a class called CommandReference which I found here.
This is the commandreference itself:
<command:CommandReference
    x:Key="DeleteNoteCommandReference"
    Command="{Binding DeleteNoteCommand}" />

The reason why I've done this is because of problems with commandbinding on a ContextMenu that I noticed (caused by the fact that a ContextMenu is not part of the logical/visual tree). I found several topics about this subject on the net and in some of them I spotted the CommandReference class, which seemed a good solution to my problem.
These commandbinding issues where indeed gone but it seems that the CanExecute of my command isn't recognized or something because the MenuItem keeps disabled.
In the ViewModel (which is bound to the view as its DataContext), I have the following code for the command:
    /// <summary>
    /// Command for deleting a note.
    /// </summary>
    public RelayCommand<NoteViewModel> DeleteNoteCommand {
        get;
        private set;
    }

    /// <summary>
    /// CanExecute method for the DeleteNoteCommand.
    /// </summary>
    /// <param name="note">The NoteViewModel that CanExecute needs to check.</param>
    /// <returns>True if the note can be deleted, false otherwise.</returns>
    public bool DeleteNoteCommandCanExecute(NoteViewModel note) {
        return Notes.Contains(note);
    }

    /// <summary>
    /// Creates all commands for this ViewModel.
    /// </summary>
    private void CreateCommands() {
        DeleteNoteCommand = new RelayCommand<NoteViewModel>(param => DeleteNote(param), param => DeleteNoteCommandCanExecute(param));
    }

What am I missing here to get my code functional?
I thought it might have something to do with the CommandReference I'm using, but I don't know what to look for.
Really hope you guys can help!

A: Try setting a breakpoint inside of DeleteNoteCommandCanExecute and checking:

*

*if it is being called before opening the context menu and

*the code inside DeleteNoteCommandCanExecute doesn't throw an exception (e.g. note parameter being null)

In the first case, if it is not being called, try calling the InvalidateRequerySuggested method on the CommandManager to force a requery of the CanExecute method.
Good luck!


text:
Q: Client to Client communication over PHP server for Android App What is the best way to connect an android application and a php server?

*

*Using sockets (TCP request)

*HTTP request

I am trying to implement a chat system between multiple clients, but I know that PHP does not allow multithreads for sockets.
I basically want to create an app simmilar to google latitude, and I also want to implement a chat system between the users. I have aldready decided that I am going to use a MySQl DB and therefore a PHP server so the client communicates with the DB (using JSON for data exchange). I found out that the easiest way to do this is using HTTP requests, but I don't know exactly how I should implement this.
I am quite new to this and I don't know how the architecture Client-Server-Client communication should look like. Could you give me some guidelines about how to do this? Or  if there is any other easier way?

A:
What is the best way to connect an android application and a php server?
1.Using sockets (TCP request)
2.HTTP request

it depends , if you use sokects (TCP request) it will be more secure and you will transfer a small amount of data to the server for each request so there is a small traffic , but it is harder to implement over http request , http request is not secure and will carry alot of data for each request i.e(Http headers) so there is more traffic.
read about (push technologies)http://en.wikipedia.org/wiki/Push_technology


text:
Q: dblclick() method in jQuery I am writing a jQuery dblclick() method. I am trying to show a hidden menu when double clicked on a button. I am creating a button named "Menu" in my html file with href attribute.
The href attribute in HTML file is this:
Menu

          Youtube

          Facebook

          Apple

So, when "Menu" is double clicked it show three options - youtube,facebook,apple
and then in js file, I am creating a dblclick() function and giving them id "menu_link" and then using show() to display the hidden menu.
This is what I have in js file:
$('#menu_link').dblclick(function(){
      $('#menu').show();
    });

It doesn't work. When I doubleclick the "menu" option it doesn't show me anything.
In Html file :
Menu

          Youtube

          Facebook

          Apple

In js file :
$(function() {
$('#menu_link').dblclick(function(){
      $('#menu').show();
    });
  });

The link to the project - https://glitch.com/edit/#!/comp484-proj2-km

A: I just inspected your project and found 2 problems.

*

*You'll need to fix checkAndUpdatePetInfoInHtml();
According to my inspections, this function is causing some problems and not letting the program finish. Therefore the double-click check won't be called.

*In the A tag, the href is just refreshing the page. Removing the menu. Just remove the href.
Before
Menu

After
Menu

Hope this helps :)

A: Maybe you try like this:
add in js-File:
function openMenu(){
    $("#menu").css("display", "block");
  }

change your div id=menu to:
Menu

              Youtube

              Facebook

              Apple

I've tried it at glitch and it worked.

A: change css display to block
$('#menu_link').dblclick(function(){
      $('#menu').css("display", "block");
    });
  })


text:
Q: Why is the __stdcall calling convention ignored in x64? I know what the differences between __cdecl and __stdcall are, but I'm not quite sure as to why __stdcall is ignored by the compiler in x64 builds.
The functions in the following code
int __stdcall stdcallFunc(int a, int b, int c, int d, int e, int f, int g)
{
    return a + b + c + d + e + f + g;
}

int __cdecl cdeclFunc(int a, int b, int c, int d, int e, int f, int g)
{
    return a + b + c + d + e + f + g;
}

int main()
{
    stdcallFunc(1, 2, 3, 4, 5, 6, 7);
    cdeclFunc(1, 2, 3, 4, 5, 6, 7);

    return 0;
}

have enough parameters to exceed the available CPU registers. Therefore, some arguments must be passed via the stack. I'm not fluent in assembly but I noticed some differences between x86 and x64 assembly.
x64
main    PROC
$LN3:
        sub     rsp, 72                             ; 00000048H
        mov     DWORD PTR [rsp+48], 7
        mov     DWORD PTR [rsp+40], 6
        mov     DWORD PTR [rsp+32], 5
        mov     r9d, 4
        mov     r8d, 3
        mov     edx, 2
        mov     ecx, 1
        call    ?stdcallFunc@@YAHHHHHHHH@Z          ; stdcallFunc
        mov     DWORD PTR [rsp+48], 7
        mov     DWORD PTR [rsp+40], 6
        mov     DWORD PTR [rsp+32], 5
        mov     r9d, 4
        mov     r8d, 3
        mov     edx, 2
        mov     ecx, 1
        call    ?cdeclFunc@@YAHHHHHHHH@Z                ; cdeclFunc
        xor     eax, eax
        add     rsp, 72                             ; 00000048H
        ret     0
main    ENDP

x86
_main   PROC
        push    ebp
        mov     ebp, esp
        push    7
        push    6
        push    5
        push    4
        push    3
        push    2
        push    1
        call    ?stdcallFunc@@YGHHHHHHHH@Z          ; stdcallFunc
        push    7
        push    6
        push    5
        push    4
        push    3
        push    2
        push    1
        call    ?cdeclFunc@@YAHHHHHHHH@Z                ; cdeclFunc
        add     esp, 28                             ; 0000001cH
        xor     eax, eax
        pop     ebp
        ret     0
_main   ENDP

*

*The first 4 arguments are, as expected, passed via registers in x64.

*The remaining arguments are put on the stack in the same order as in x86.

*Contrary to x86, in x64 we don't use push instructions. Instead we reserve enough stack space at the beginning of main and use mov instructions to add the arguments to the stack.

*In x64, no stack cleanup is happening after both calls, but at the end of main.

This brings me to my questions:

*

*Why does x64 use mov rather than push? I assume it's just more efficient and wasn't available in x86.

*Why is there no stack cleanup after the call instructions in x64?

*What's the reason that Microsoft chose to ignore __stdcall in x64 assembly?
From the docs:

On ARM and x64 processors, __stdcall is accepted and ignored by the compiler

Here is the example code and assembly.

A:

*

*Why does x64 use mov rather than push? I assume it's just more efficient and wasn't available in x86.

That is not the reason. Both of these instructions also exist in x86 assembly language.
The reason why your compiler is not emitting a push instruction for the x64 code is probably because it must adjust the stack pointer directly anyway, in order to create 32 bytes of "shadow space" for the called function. See this link (which was provided by @NateEldredge) for further information on "shadow space".
Allocating 32 bytes of "shadow space" with push instructions would take 4 64-bit push instructions, but only one sub instruction. That is why it prefers to use the sub instruction. Since it is using the sub instruction anyway to create 32 bytes of shadow space, there is no penalty to change the operand of the sub instruction from 32 to 72, which allocates 72 bytes of memory on the stack, which is enough to also pass 3 paramters on the stack (the other 4 are passed in CPU registers).
I don't understand why it is allocating 72 bytes on the stack, though, as, according to my calculcations, it only has to be 56 bytes (32 bytes of "shadow space" and 24 bytes for the 3 parameters that are passed on the stack). Possibly, the compiler is reserving those extra 16 bytes for local variables or for exception handling, which may be optimized away when compiler optimizations are active.

*Why is there no stack cleanup after the call instructions in x64?

There is stack cleanup after the call instructions. This is what the line
add rsp, 72
does.
However, for some reason (probably increased performance), the x64 compiler only performs the cleanup at the end of the calling function, instead of after every function call. This means that with the x64 compiler, all function calls share the same stack space for their parameters, whereas with the x86 compiler, the stack space is allocated and cleaned up at every function call.

*What's the reason that Microsoft chose to ignore __stdcall in x64 assembly?

The keywords _stdcall and _cdecl specify 32-bit calling conventions. That's why they are not relevant for 64-bit programs (i.e. x64). On x64, there is only the standard calling convention and the extended __vectorcall calling convenction.


text:
Q: GNU GCC compilor error "multiple definition of main" I am new to ubuntu, now I need to develop my assignment in C++.
I am using codeblocks IDE to write c++ programs.
Whenever I compile something in it, it gives these errors:
multiple definition of main
warning: control reaches end of non-void function

Here is the code I want to compile for now:
#include <iostream>
#include <stdlib.h>
using namespace std;
/* The Node class */
class Node
{
    public:
        int get() { return object; };
        void set(int object) { this->object = object; };
        Node * getNext() { return nextNode; };
        void setNext(Node * nextNode) { this->nextNode = nextNode; };
    private:
        int object;
        Node * nextNode;
};
/* The List class */
class List
{
    public:
        List();
        void add (int addObject);
        int get();
        bool next();
        friend void traverse(List list);
        friend List addNodes();

    private:
        int size;
        Node * headNode;
        Node * currentNode;
        Node * lastCurrentNode;
};
/* Constructor */
List::List()
{
    headNode = new Node();
    headNode->setNext(NULL);
    currentNode = NULL;
    lastCurrentNode = NULL;
    size = 0;
}

/* add() class method */
void List::add (int addObject)
{
    Node * newNode = new Node();
    newNode->set(addObject);
    if( currentNode != NULL )
    {
        newNode->setNext(currentNode->getNext());
        currentNode->setNext( newNode );
        lastCurrentNode = currentNode;
        currentNode = newNode;
    }
    else
    {
        newNode->setNext(NULL);
        headNode->setNext(newNode);
        lastCurrentNode = headNode;
        currentNode = newNode;
    }
    size ++;
}
/* get() class method */
int List::get()
{
    if (currentNode != NULL)
        return currentNode->get();
}
/* next() class method */
bool List::next()
{
    if (currentNode == NULL) return false;
    lastCurrentNode = currentNode;
    currentNode = currentNode->getNext();
    if (currentNode == NULL || size == 0)
        return false;
    else
        return true;
}
/* Friend function to traverse linked list */
void traverse(List list)
{
    Node* savedCurrentNode = list.currentNode;
    list.currentNode = list.headNode;

    for(int i = 1; list.next(); i++)
    {
        cout << "\n Element " << i << " " << list.get();
    }
    list.currentNode = savedCurrentNode;
}
/* Friend function to add Nodes into the list */
List addNodes()
{
    List list;
    list.add(2);
    list.add(6);
    list.add(8);
    list.add(7);
    list.add(1);
    cout << "\n List size = " << list.size <<'\n';
    return list;
}
int main()
{
    List list = addNodes();
    traverse(list);
    return 0;
}

Can anyone explain, where do I messing up?

A: It seems that your IDE is not just compiling one single file, but another one which also contains a definition of the main function. Please check out how many files are being compiled.
In addition, your compiled is treating all the warnings as errors (-Werror) or disable this flag.

A: The program compiles fine with (yourcode.cc contains your sourcecode):
$ CXXFLAGS="-Wall -Werror -Wpedantic" make yourcode

stack.cc: In member function 'int List::get()':
stack.cc:76:1: error: control reaches end of non-void function [-Wreturn-type]
 }

and invoking ./yourcode outputs:
 List size = 5

 Element 1 2
 Element 2 6
 Element 3 8
 Element 4 7
 Element 5 1

Obviously your IDE is going to add some flags to the linker. Please show us your compile flags/setting. See the compile log or run the make command executing more verbose.
May have a look at. Code::blocks verbose build

A: The Problem was just, my IDE was compiling multiple files at once,
and also in the function int List::get() ,
I got to add else return -1 at the end of this function after if statement,

I mean before editing my code the int List::get() function was like this:
int List::get() {
    if (currentNode != NULL)
        return currentNode->get();
}

I replaces this one with:
int List::get() {
    if (currentNode != NULL)
        return currentNode->get();
    else return -1;
}

and it worked fine.


text:
Q: Remove Mandrill unsubscribe link Is there any way in Mandrill to remove their unsubscribe link :  *unsubscribe from this list* & use just mine  : *|UNSUB:http://mywebsite.com/unsub|* ?

A: In the mandrillapp > settings > sending defaults you can disable the setting of mandrill to add an unsubscribe footer.
Then add your own link in the html or text of the mail message.


text:
Q: When checkbox is checked insert data if checkbox is unchecked remove data I need help.
I want to create a system when the checkbox is checked inserts data into the database when it is unchecked it removes it from the database. Maybe there is another solution
HTML

Perm 1

<input value="1" name="permchecked[]" type="checkbox">

Usuwanie/Perm 2

<input value="2" name="permchecked[]" type="checkbox">

Perm 3

<input value="3" name="permchecked[]" type="checkbox">

PHP
if(isset($_POST['u_permissions_update'])){
   if (isset($permcheckeds)){
        foreach ($permcheckeds as $permchecked) {
            $query = $db2->prepare("INSERT INTO permissions_users SET user_id = :u_permissions_update, permissions_id= :permchecked");
            $query->bindValue(':u_permissions_update', $u_permissions_update);
            $query->bindValue(':permchecked', $permchecked);
            $query->execute();
            $_SESSION['success']  = "Work";
        }
    } else {
        $_SESSION['success']  = "Not Working";
    }
}

DB permissions_users
permissions_users_id | permissions_id | user_id

A: Since I'm not sure what javascript framework you are using if any, here is a blueprint to what you can do.
If you are planning on sending the data to the server when the switch is changed, you check the onchange for the checkbox and you don't need it to be an array. And submit the process that you want to happen along with the value of the permission to be changed.
var _checks = document.querySelectorAll("input[name=permchecked]");

_checks.forEach(function(el){
  el.addEventListener("change",function(){
    var field_data = {
      "process" : (this.checked) ? "add" : "delete",
      "permission": this.value
    };

    //using ajax, submit field_data to the server

  });
});

PHP
In your PHP, then check for process:
if(isset($_POST['process'])){
  if($_POST['process'] == "delete"){
  //delete from database where that permission equals the value passed plus that user. Even if the permission doesn't exist in the database already, still just run the single delete query. No reason to add an additional query to check that it exists.
 }
elseif($_POST['process'] == "add"){
  //add that permission to the database
 }
}


text:
Q: jqgrid setting custom formatter to dynamic column collection I am using jqgrid. We are building a dashboard functionality with jquery. Different application just have to register respective application page and dashboard will render that page.To achieve this we are using jqgrid as one of the jquery plugin. Following is my code
 var ph = '#' + placeHolder;
    var _prevSort;
    $.ajax({
        url: dataUrl,
        dataType: "json",
        async: true,
        success: function(json) {
            pager = $('#' + pager);
            if (json.showPager === "false") {
                pager = eval(json.showPager);
            }
            dataUrl += "&jqSession=true";
            $(ph).jqGrid({
                url: dataUrl,
                datatype: "json",
                sortclass: "grid_sort",
                colNames: JSON.parse(json.colNames),
                colModel: JSON.parse(json.colModel),
                forceFit: true,
                rowNum: json.rowNum,
                rowList: JSON.parse(json.rowList),
                pager: pager,
                sortname: json.sortName,
                caption: json.caption,
                viewrecords: true,
                viewsortcols: true,
                sortorder: json.sortOrder,
                footerrow: summaryFooter,
                userDataOnFooter: summaryFooter,
                jsonReader: {
                    root: "rows",
                    row: "row",
                    repeatitems: false,
                    id: json.sortName
                },
                gridComplete: function() {
                    if (showFooter) {
                        $(ph).append("
" + json.footerRow + "
");
                    }
                    if (json.additionalContent != null) {
                        $("#" + xContID).html(json.additionalContent);
                    }
                    $("ui-icon-asc").append("IMG");
                    var _rows = $(".jqgrow");
                    if (json.rows.length > 0) {
                        for (var i = 1; i < _rows.length; i += 1) {
                            _rows[i].attributes["class"].value =   _rows[i].attributes["class"].value.replace(" ui-jqgrid-altrow", "");
                            if (i % 2 == 1) {
                                _rows[i].attributes["class"].value += " ui-jqgrid-altrow";
                            }
                        }
                        var gMaxHeight = getGridMaxHeight();
                        var gHeight = ($(ph + " tr").length + 1) * ($($(".jqgrow")  [0]).height());
                        if (gHeight <= gMaxHeight) {
                            $(ph).parent().height(gHeight);
                        }
                        else {
                            $(ph).parent().height(gMaxHeight);
                        }
                    }
                    else {
                        $(ph).prepend("
" + gridNoDataMsg + "
");
                        $(ph).parent().height(60);
                    }
                },
                onSortCol: function(index, iCol, sortorder) {
                    dataUrl = dataUrl.replace("&jqSession=true", "");
                    $(ph).jqGrid().setGridParam({ url: dataUrl }).trigger("reloadGrid");
                    var _colName = "#jqgh_" + index;
//                    $(_prevSort).parent().removeClass("ui-jqgrid-sorted");
//                    $(_prevSort).parent().addClass("ui-state-default");
//                    $(_colName).parent().addClass("ui-jqgrid-sorted");
//                    $(_colName).parent().removeClass("ui-state-default");
                    _prevSort = _colName;
                    var _rows = $(".jqgrow");
                    for (var i = 1; i < _rows.length; i += 1) {
                        _rows[i].attributes["class"].value =   _rows[i].attributes["class"].value.replace(" ui-jqgrid-altrow", "");
                        if (i % 2 == 1) {
                            _rows[i].attributes["class"].value += " ui-jqgrid-altrow";
                        }
                    }
                }
            }).navGrid('#' + pager, { search: false, sort: false, edit: false, add: false,   del: false, refresh: false }); // end of grid
            $("#" + loadid).empty();
            gGridIds[gGridIds.length] = placeHolder;
            SetGridSizes();
        },
        error: function() {
            $("#" + loadid).html(loadingErr);
        }
    });

As you can see from the code i am getting column collection dynamically(Appication page which i am calling will give me JSON in the response and will have colNames collection in it. Evrything is working fine but, only issue is coming when we are trying to apply custom formatter to  column. This issue comes only when we are dynamically assign "colModel" to jqgrid.
Appreciate help
Thanks in advance

A: I find your approach very interesting. Mostly for the purpose will be used jqGrid.jqGridExport see http://www.trirand.com/jqgridwiki/doku.php?id=wiki:import_methods. The only thing which I find a little strange, that you don't use contentType: 'application/json' as a $.ajax option. In this case the received data will be converted to an object by $.ajax. Next suspected thing is that you don't decode the JSON respond with respect of one JSON.parse call.
If this advise will not help you I'll suggest that you post a test JSON response contains custom formatter with which you have problems. Then I'll be able to reproduce your problem without having connection to your server.


text:
Q: SQLSTATE[28000] [1045] Access denied for user 'root'@'localhost' (using password: YES) I keep getting this error:

SQLSTATE[28000] [1045] Access denied for user 'root'@'localhost'
  (using password: YES)

And I don't know how to fix it.
I have installed MySQL, Apache2, PHP and phpMyAdmin. Then I've changed a few things in the .htaccess file and changed AllowOverride from none to all (not sure where I did this again). That's all I've done with the server. I read people talking about databases, but I've only got 1 DB.

A: It seems you're attempting to access the database with the root user, without providing the corresponding password.
If you have no idea what the password is, I suggest you attempt to recover it, using this procedure.


text: Q: Launching iPhone App - Do I need separate names for the App and the Landing Page/website or can I use the same name? I am launching a iPhone App.  Do I need two separate domain names for the app and the landing page website or can I use the same name for both.  The website will solely be used to advertise the app information.


text:
Q: SQL SERVER Select MAX Procedure I'm trying to make a procedure that changes the user login on a table,but change only the last entry if its in a specific status:Here is the procudure i'm trying:
Update T_STATUS_CLIC
SET iEDV = @iEDV
WHERE
    iClic = @iClic and iStatus = '9' and dtDateCreated =
    (select max (dtDateCreated)  FROM T_STATUS_CLIC where iclic = @iClic );

I can only change the iEDV if the last row of the table the max date,is in the iStatus 9,i dont know if this is possible,i'm trying something like this:
iStatus = (select iStatus = '9' where max(dtDateCreated))

But didn't work,is there a way to do this?

A: If i understand correctly, you can have many rows per "iClic" and only want to update the row if the most recent has a status = 9.
It would help if the table had a true PK.
But I believe this will work, given:
CREATE TABLE T_STATUS_CLIC (iClic INT , iEDV INT, iStatus CHAR(1), dtDateCreated DateTime)
DECLARE @iEDV int = 123;
DECLARE @iClic int = 8888;

this script:
; -- WITH must be preceeded by a semicolon
WITH clicmax as (SELECT iClic
                ,   max(dtDateCreated) as maxdt
                ,   max(case when mc.iStatus = '9' THEN mc.dtDateCreated ELSE null END) as Max9dt
                FROM dbo.T_STATUS_CLIC mc WHERE iClic = @iClic GROUP BY iClic)
UPDATE tt
SET iEDV = @iEDV
FROM dbo.T_STATUS_CLIC tt
    JOIN clicmax on clicmax.iClic = tt.iClic
WHERE tt.iClic = @iClic
and tt.dtDateCreated = clicmax.Max9dt
and tt.dtDateCreated = clicmax.Maxdt
and tt.iStatus = '9';

The WITH clause determines BOTH the actual max date and the max date for status 9.  The update can then reference both of these in its WHERE clause.


text:
Q: Maven deploy exclude logback.xml file I have a maven project that uses logback, and it has a logback.xml file. The project is meant to run on it's own. But I have another maven project that needs to use a couple of classes from the first project. So when I deploy my first maven project, how do I exclude the logback.xml file?

A: There should be one logback.xml per application. If you have this sort of issue, it probably means that one application includes another, which suggests a design error.
Consider making these "couple of classes" a separate library, so you can use them from both applications. And remove the dependency between your two executable units.


text:
Q: JAVA Wrapping Socket as a Singleton class in a multiscreen Swing app I am writing a chat application in Java swing which has a custom protocol and server backend using sockets. I am in the process of making the ClientSide connection handler. Here is my code up to this point:
package Client;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.*;

import Common.Message;

public class ConnectionHandler {
    Socket socket;
    DataInputStream input;
    DataOutputStream output;

    public ConnectionHandler() throws UnknownHostException, IOException {
        socket = new Socket(Client.HOST_INET,Client.PORT);
        input = new DataInputStream(socket.getInputStream());
        output = new DataOutputStream(socket.getOutputStream());
    }

    public void sendMessage(Message message) throws IOException {
        output.writeUTF(Message.disasseble(message));
    }

    public Message getMessage() throws IOException {
        String message;
        message = input.readUTF();
        return Message.assemble(message);
    }

    public void closeConnection() {

    }

    private void reconect(){

    }
}

The app is composed of a CardLauut holding the Login, Registration and and Chat JPanels. Each JPanel needs the connection and the connection should be maintained as long as the app is functioning. Login screen sends Login message/answer the same with Registration and of course the Chat screen.
QUESTION
Should I use a singleton design pattern for the connectionHanler? And would the referece also work if it was on a separate thread like a connection thread with a que? (I know that I need to ping the server every now and then or connection can be lost so I need to reconect and let the UI know)

A: It makes sense to keep ConnectionHandler singleton for the following reasons:

*

*You can manage connection state centrally, inside the ConnectionHandler instance. For e.g., don't send a chat message if user isn't logged in.

*Allows messages to be sent in sequence. If you don't use Singleton pattern, it is theoretically possible that messages can be sent out of order in a multi-threaded application.

*Decrease load on server, because it only has one socket connection per client.

A: Holding the connection in a singleton has one additional advantage: you will very likely want to run all of your network communication in dedicated Thread. A singleton can greatly help there.
Also all Connection related properties (logged in?, transport encryption, ...) can be handled on a "per connection" base.
Handling out-of-band communication ("log out" or notifications while the Socket is busy) should be considered beforehand.


text:
Q: Microsoft Bot FormFlow Prompt Missing Date or Time I have a bot that uses a FormFlow dialog to collect some information, one of which is the built in DateTime. It is working great but if the input is a date and not a time it defaults to 12am on the correct date - is there a way to have it prompt for a time as well?
Similarly is there a way to prompt a date if the input is only a time?

A: You could have a separate date and time field and skip the time field if specified when doing date.


text:
Q: GET with query string with Fetch in React Native I am making a request like this:
fetch("https://api.parse.com/1/users", {
  method: "GET",
  headers: headers,
  body: body
})

How do I pass query string parameters? Do I simply add them to the URL? I couldn't find an example in the docs.

A: Your first thought was right: just add them to the URL.
Remember you can use template strings (backticks) to simplify putting variables into the query.
const data = {foo:1, bar:2};

fetch(`https://api.parse.com/1/users?foo=${encodeURIComponent(data.foo)}&bar=${encodeURIComponent(data.bar)}`, {
  method: "GET",
  headers: headers,
})

A: Here's an es6 approach
const getQueryString = (queries) => {
    return Object.keys(queries).reduce((result, key) => {
        return [...result, `${encodeURIComponent(key)}=${encodeURIComponent(queries[key])}`]
    }, []).join('&');
};

Here we're taking in a queries object in the shape of key: param
We iterate and reduce through the keys of this object, building an array of encoded query strings.
Lastly we do a join and return this attachable query string.

A: I did a small riff on Mark Amery's answer that will pass Airbnb's eslint definitions since many teams seem to have that requirement these days.
function objToQueryString(obj) {
  const keyValuePairs = [];
  for (let i = 0; i < Object.keys(obj).length; i += 1) {
    keyValuePairs.push(`${encodeURIComponent(Object.keys(obj)[i])}=${encodeURIComponent(Object.values(obj)[i])}`);
  }
  return keyValuePairs.join('&');
}

A: Short answer
Just substitute values into the URL like this:
const encodedValue = encodeURIComponent(someVariable);
fetch(`https://example.com/foo?bar=${encodedValue}`);

Longer answer
Yes, you just need to add the query string to the URL yourself. You should take care to escape your query string parameters, though - don't just construct a URL like
`https://example.com/foo?bar=${someVariable}`

unless you're confident that someVariable definitely doesn't contain any &, =, or other special characters.
If you were using fetch outside of React Native, you'd have the option of encoding query string parameters using URLSearchParams. However, React Native does not support URLSearchParams. Instead, use encodeURIComponent.
For example:
const encodedValue = encodeURIComponent(someVariable);
fetch(`https://example.com/foo?bar=${encodedValue}`);

If you want to serialise an object of keys and values into a query string, you could make a utility function to do that:
function objToQueryString(obj) {
  const keyValuePairs = [];
  for (const key in obj) {
    keyValuePairs.push(encodeURIComponent(key) + '=' + encodeURIComponent(obj[key]));
  }
  return keyValuePairs.join('&');
}

... and use it like this:
const queryString = objToQueryString({
    key1: 'somevalue',
    key2: someVariable,
});
fetch(`https://example.com/foo?${queryString}`);

A: My simple function to handle this:
/**
 * Get query string
 *
 * @param   {*}   query   query object (any object that Object.entries() can handle)
 * @returns {string}      query string
 */
function querystring(query = {}) {
  // get array of key value pairs ([[k1, v1], [k2, v2]])
  const qs = Object.entries(query)
    // filter pairs with undefined value
    .filter(pair => pair[1] !== undefined)
    // encode keys and values, remove the value if it is null, but leave the key
    .map(pair => pair.filter(i => i !== null).map(encodeURIComponent).join('='))
    .join('&');

  return qs && '?' + qs;
}

querystring({one: '#@$code', two: undefined, three: null, four: 100, 'fi##@ve': 'text'});
// "?one=%23%40%24code&three&four=100&fi%23%23%40ve=text"
querystring({});
// ""
querystring('one')
// "?0=o&1=n&2=e"
querystring(['one', 2, null, undefined]);
// "?0=one&1=2&2" (edited)

A: Yes you should, there are a few classes in JS, that can help you a handy one is https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams
e.g. if you had the params in a javascript object say
let params = {one: 'one', two: 'two'}

you could say this function
let queryString = new URLSearchParams()
for(let key in params){
  if(!params.hasOwnkey())continue
  queryString.append(key, params[key])
}

then you can get your nicely formatted query string by saying
queryString.toString()

A: The accepted answer works, but if you have more params than one it doesn't generalize. I suggest the following approach, which also handles array parameters:
let route = 'http://test.url.com/offices/search';
if (method == 'GET' && params) {
  const query = Object.keys(params)
    .map((k) => {
      if (Array.isArray(params[k])) {
        return params[k]
          .map((val) => `${encodeURIComponent(k)}[]=${encodeURIComponent(val)}`)
          .join('&');
      }

      return `${encodeURIComponent(k)}=${encodeURIComponent(params[k])}`;
    })
    .join('&');

  route += `?${query}`;
}


text:
Q: Given a string array, return all groups of strings that are anagrams Given a string array, return all groups of strings that are anagrams.
My solutions:
For each string word in the array, sort it O(m lg m), m is the average length of a word.
Build up a hash Table < string, list >.
Put the sorted word  into the hash table as key and also generate all permutations (O(m!)) of the word, search each permutation in a dictionary (a prefix tree map) with O(m), if it is in the dictionary, put (O(1)) it into the hash table so that all permutated words are put into the list with the same key.
Totally, O(n * m * lg m *  m!) time and O(n* m!) space , n is the size of the given array.
If m is very large, it is not efficient , m! .
Any better solutions  ?
thanks

A: use counting sort to sort the word so that sorting can be done in O(m).
after sorting generate key from word and insert a node (key,value) into hashtable. Generating key can be achieved in O(m).
You can take value in (key,value) as some dynamic array which can hold more than one strings.
Each time you insert a key which is already present just push the original word from which key is generated on value array.
So overall time complexity O(mn) where n is the total number of words (size of input).
Also this link has solution to similar problems->
http://yourbitsandbytes.com/viewtopic.php?f=10&t=42

A: We define an alphabet, which contains every letter we may have in our wordlist. Next, we need a different prime for each of the letters in the alphabet, I recommend using the smallest you can find.
That would give us the following mapping:
{ a => 2, b => 3, c => 5, d => 7, etc }
Now count the letters in the word you want to represent as integer, and build your result integer as follows:
Pseudocode:
result = 1
for each letter:
....result *= power(prime[letter], count(letter,word)

some examples:
aaaa => 2^4
aabb => 2^2 * 3^2 = bbaa = baba = ...
and so on.
So you will have an integer representing each word in your dictionary and the word you want to check will be able to be converted to an integer. So if n is the size of your wordlist and k is the size of the longest word it will take O(nk) to build your new dictionary and O(k) to check a new word.
Hackthissite.com has a programming challenge which is: Given a scrambled word, look it up in a dictionary to see if any anagrams of it are in the dictionary. There is a good article on an efficient solution to the problem from which I have borrowed the answer, it also goes into detail on further optimisations.

A: #include <map>
#include <iostream>
#include <set>
#include <algorithm>

int main () {
  std::string word;
  std::map<std::string, std::set<std::string>> anagrams;
  while(std::cin >> word) {
    std::string sortedWord(word);
    std::sort(sortedWord.begin(), sortedWord.end());
    anagrams[sortedWord].insert(word);
  }
  for(auto& pair : anagrams) {
    for(auto& word : pair.second) {
      std::cout << word << " ";
    }
    std::cout << "\n";
  }
}

I'll let someone who is better at big-O analysis than I am figure out the complexities.

A: turn the dictionary into a mapping of the sorted characters of a word mapped to every word of those characters and store that. For each word you are given, sort it and add the list of anagrams from the mapping to your output.

A: I don't believe you can do better in O terms than

*

*sorting the letters of each word

*sorting the list of sorted words

*each set of anagrams will now be grouped consecutively.


text:
Q: How to verify a number on a web-page using robot framework I need to verify a number on a web-page, can anyone helpe me? Do i get the ID of the number and then conver this into an int then log to console?
Log To Console

A: Assuming you are using SeleniumLibrary, you can use the keyword:
${myvalue}=    Get Text    <locator for the number>

Or, if you just want to check if the Element is there:
Page Should Contain Element    <locator for the number>

See the SeleniumLibrary keywords doc


text:
Q: Change all solid parts of eps file to certain color in graphicsmagick Very new to graphicsmagick but I can see that it is very powerful.  I have a decal site and I am looking to update my images.  I do this in my spare time so I don't really have budget for anything so I try and do all work I can myself.
All of the 'patterns' I use are in EPS vector format.  They are all monochrome.  I send this EPS pattern to my vinyl plotter and it cuts the shapes out on whatever colored vinyl I have loaded.
For the website images what I would ultimately like to do is take an image of the back glass of a truck, and overlay the EPS in one of the colors I sell with a transparent background.  This would give my customers an idea of how the decal would look on their vehicle.
Is it possible to use graphicsmagick to generate different versions of each EPS in different colors or will I have to create a version of the EPS for each color?
Does anyone know of any good examples for doing any of this?  I've succesfully resized and merged an EPS with another image, but I'm a bit lost when it comes to adding transparency. Do I need to select a color?  If so, do I choose white as that's the background color of the resulting jpg?  The EPS files don't have a background color as far as I know.
Any help is most appreciated.

A: Assuming your EPS represents a black decal on white, you can use "-transparent white" to make the white part (the vinyl scrap) transparent, and "-fill #FF0000 -opaque black" to make the rest of it the color of your vinyl (in this example, red, which is hex #FF0000), and write the result as a PNG with transparency:
gm convert decal.eps -transparent white -fill "#FF0000" \
           -opaque black -matte decal_red.png

Then rescale decal.png and overlay it on your truck image as you have already done:
gm convert truck.jpg -draw "image over x,y 0,0 decal_red.png" \
           truck_with_red_decal.jpg

where you replace x and y with the coordinates of where you want to place the upper left corner of the decal on the truck image. "0,0" are the width and height of the overlay image (if 0 they default to the dimensions from the image file)