Rectangle 27 23

For a comprehensive and continually growing collection of links check AngularJS-Learning, a github repo that collects resources, links and interesting blog posts.

I've found very helpful the tutorials and videos on the AngularJS youtube channel. They go from the mostly basic stuff to some advanced topics, a good way to start.

The official twitter and google+ accounts are a good way to follow news and get some nice links. Also check the AngularJS Mailing list.

A nice aggregator of news/link is angularjsdaily.com.

Also there're some new books out there, so you can keep an eye on your favourite online library.

How to master AngularJS? - Stack Overflow

angularjs
Rectangle 27 23

For a comprehensive and continually growing collection of links check AngularJS-Learning, a github repo that collects resources, links and interesting blog posts.

I've found very helpful the tutorials and videos on the AngularJS youtube channel. They go from the mostly basic stuff to some advanced topics, a good way to start.

The official twitter and google+ accounts are a good way to follow news and get some nice links. Also check the AngularJS Mailing list.

A nice aggregator of news/link is angularjsdaily.com.

Also there're some new books out there, so you can keep an eye on your favourite online library.

How to master AngularJS? - Stack Overflow

angularjs
Rectangle 27 23

For a comprehensive and continually growing collection of links check AngularJS-Learning, a github repo that collects resources, links and interesting blog posts.

I've found very helpful the tutorials and videos on the AngularJS youtube channel. They go from the mostly basic stuff to some advanced topics, a good way to start.

The official twitter and google+ accounts are a good way to follow news and get some nice links. Also check the AngularJS Mailing list.

A nice aggregator of news/link is angularjsdaily.com.

Also there're some new books out there, so you can keep an eye on your favourite online library.

How to master AngularJS? - Stack Overflow

angularjs
Rectangle 27 396

More reading material about JavaScript asynchronicity

This topic has been iterated at least a couple of thousands times, here, in Stack Overflow. Hence, first off I'd like to point out some extremely useful resources:

Let's trace the common behavior first. In all examples, the outerScopeVar is modified inside of a function. That function is clearly not executed immediately, it is being assigned or passed as an argument. That is what we call a callback.

Now the question is, when is that callback called?

It depends on the case. Let's try to trace some common behavior again:

  • img.onload may be called sometime in the future, when (and if) the image has successfully loaded.
  • setTimeout may be called sometime in the future, after the delay has expired and the timeout hasn't been cancelled by clearTimeout. Note: even when using 0 as delay, all browsers have a minimum timeout delay cap (specified to be 4ms in the HTML5 spec).
  • jQuery $.post's callback may be called sometime in the future, when (and if) the Ajax request has been completed successfully.
  • Node.js's fs.readFile may be called sometime in the future, when the file has been read successfully or thrown an error.

In all cases, we have a callback which may run sometime in the future. This "sometime in the future" is what we refer to as asynchronous flow.

Asynchronous execution is pushed out of the synchronous flow. That is, the asynchronous code will never execute while the synchronous code stack is executing. This is the meaning of JavaScript being single-threaded.

More specifically, when the JS engine is idle -- not executing a stack of (a)synchronous code -- it will poll for events that may have triggered asynchronous callbacks (e.g. expired timeout, received network response) and execute them one after another. This is regarded as Event Loop.

That is, the asynchronous code highlighted in the hand-drawn red shapes may execute only after all the remaining synchronous code in their respective code blocks have executed:

In short, the callback functions are created synchronously but executed asynchronously. You just can't rely on the execution of an asynchronous function until you know it has executed, and how to do that?

It is simple, really. The logic that depends on the asynchronous function execution should be started/called from inside this asynchronous function. For example, moving the alerts and console.logs too inside the callback function would output the expected result, because the result is available at that point.

Often you need to do more things with the result from an asynchronous function or do different things with the result depending on where the asynchronous function has been called. Let's tackle a bit more complex example:

var outerScopeVar;
helloCatAsync();
alert(outerScopeVar);

function helloCatAsync() {
    setTimeout(function() {
        outerScopeVar = 'Nya';
    }, Math.random() * 2000);
}

Note: I'm using setTimeout with a random delay as a generic asynchronous function, the same example applies to Ajax, readFile, onload and any other asynchronous flow.

This example clearly suffers from the same issue as the other examples, it is not waiting until the asynchronous function executes.

Let's tackle it implementing a callback system of our own. First off, we get rid of that ugly outerScopeVar which is completely useless in this case. Then we add a parameter which accepts a function argument, our callback. When the asynchronous operation finishes, we call this callback passing the result. The implementation (please read the comments in order):

// 1. Call helloCatAsync passing a callback function,
//    which will be called receiving the result from the async operation
helloCatAsync(function(result) {
    // 5. Received the result from the async function,
    //    now do whatever you want with it:
    alert(result);
});

// 2. The "callback" parameter is a reference to the function which
//    was passed as argument from the helloCatAsync call
function helloCatAsync(callback) {
    // 3. Start async operation:
    setTimeout(function() {
        // 4. Finished async operation,
        //    call the callback passing the result as argument
        callback('Nya');
    }, Math.random() * 2000);
}

Most often in real use cases, the DOM API and most libraries already provide the callback functionality (the helloCatAsync implementation in this demonstrative example). You only need to pass the callback function and understand that it will execute out of the synchronous flow, and restructure your code to accommodate for that.

You will also notice that due to the asynchronous nature, it is impossible to return a value from an asynchronous flow back to the synchronous flow where the callback was defined, as the asynchronous callbacks are executed long after the synchronous code has already finished executing.

Instead of returning a value from an asynchronous callback, you will have to make use of the callback pattern, or... Promises.

Although there are ways to keep the callback hell at bay with vanilla JS, promises are growing in popularity and are currently being standardized in ES6 (see Promise - MDN).

Promises (a.k.a. Futures) provide a more linear, and thus pleasant, reading of the asynchronous code, but explaining their entire functionality is out of the scope of this question. Instead, I'll leave these excellent resources for the interested:

  • The Art of Node - Callbacks explains asynchronous code and callbacks very well with vanilla JS examples and Node.js code as well.

Note: I've marked this answer as Community Wiki, hence anyone with at least 100 reputations can edit and improve it! Please feel free to improve this answer, or submit a completely new answer if you'd like as well.

I want to turn this question into a canonical topic to answer asynchronicity issues which are unrelated to Ajax (there is How to return the response from an AJAX call? for that), hence this topic needs your help to be as good and helpful as possible!

In your last example, is there a specific reason why you use anonymous functions or would it work the same by using named functions?

The code examples are a bit weird as you're declaring the function after calling it. Works because of hoisting of course, but was it intentional?

You need to understand that the red circle code is only async because it is being executed by NATIVE async javascript functions. This is a feature of your javascript engine--whether it be Node.js or a browser. It is async because it is being passed in as a "callback" to a function that is essentially a black box (implemented in C etc..). To the hapless developer they are async...just because. If you want to write your own async function you have to hack it by sending it in to SetTimeout(myfunc,0). Should you do that? Another debate....probably not.

javascript - Why is my variable unaltered after I modify it inside of ...

javascript asynchronous
Rectangle 27 388

More reading material about JavaScript asynchronicity

This topic has been iterated at least a couple of thousands times, here, in Stack Overflow. Hence, first off I'd like to point out some extremely useful resources:

Let's trace the common behavior first. In all examples, the outerScopeVar is modified inside of a function. That function is clearly not executed immediately, it is being assigned or passed as an argument. That is what we call a callback.

Now the question is, when is that callback called?

It depends on the case. Let's try to trace some common behavior again:

  • img.onload may be called sometime in the future, when (and if) the image has successfully loaded.
  • setTimeout may be called sometime in the future, after the delay has expired and the timeout hasn't been cancelled by clearTimeout. Note: even when using 0 as delay, all browsers have a minimum timeout delay cap (specified to be 4ms in the HTML5 spec).
  • jQuery $.post's callback may be called sometime in the future, when (and if) the Ajax request has been completed successfully.
  • Node.js's fs.readFile may be called sometime in the future, when the file has been read successfully or thrown an error.

In all cases, we have a callback which may run sometime in the future. This "sometime in the future" is what we refer to as asynchronous flow.

Asynchronous execution is pushed out of the synchronous flow. That is, the asynchronous code will never execute while the synchronous code stack is executing. This is the meaning of JavaScript being single-threaded.

More specifically, when the JS engine is idle -- not executing a stack of (a)synchronous code -- it will poll for events that may have triggered asynchronous callbacks (e.g. expired timeout, received network response) and execute them one after another. This is regarded as Event Loop.

That is, the asynchronous code highlighted in the hand-drawn red shapes may execute only after all the remaining synchronous code in their respective code blocks have executed:

In short, the callback functions are created synchronously but executed asynchronously. You just can't rely on the execution of an asynchronous function until you know it has executed, and how to do that?

It is simple, really. The logic that depends on the asynchronous function execution should be started/called from inside this asynchronous function. For example, moving the alerts and console.logs too inside the callback function would output the expected result, because the result is available at that point.

Often you need to do more things with the result from an asynchronous function or do different things with the result depending on where the asynchronous function has been called. Let's tackle a bit more complex example:

var outerScopeVar;
helloCatAsync();
alert(outerScopeVar);

function helloCatAsync() {
    setTimeout(function() {
        outerScopeVar = 'Nya';
    }, Math.random() * 2000);
}

Note: I'm using setTimeout with a random delay as a generic asynchronous function, the same example applies to Ajax, readFile, onload and any other asynchronous flow.

This example clearly suffers from the same issue as the other examples, it is not waiting until the asynchronous function executes.

Let's tackle it implementing a callback system of our own. First off, we get rid of that ugly outerScopeVar which is completely useless in this case. Then we add a parameter which accepts a function argument, our callback. When the asynchronous operation finishes, we call this callback passing the result. The implementation (please read the comments in order):

// 1. Call helloCatAsync passing a callback function,
//    which will be called receiving the result from the async operation
helloCatAsync(function(result) {
    // 5. Received the result from the async function,
    //    now do whatever you want with it:
    alert(result);
});

// 2. The "callback" parameter is a reference to the function which
//    was passed as argument from the helloCatAsync call
function helloCatAsync(callback) {
    // 3. Start async operation:
    setTimeout(function() {
        // 4. Finished async operation,
        //    call the callback passing the result as argument
        callback('Nya');
    }, Math.random() * 2000);
}

Most often in real use cases, the DOM API and most libraries already provide the callback functionality (the helloCatAsync implementation in this demonstrative example). You only need to pass the callback function and understand that it will execute out of the synchronous flow, and restructure your code to accommodate for that.

You will also notice that due to the asynchronous nature, it is impossible to return a value from an asynchronous flow back to the synchronous flow where the callback was defined, as the asynchronous callbacks are executed long after the synchronous code has already finished executing.

Instead of returning a value from an asynchronous callback, you will have to make use of the callback pattern, or... Promises.

Although there are ways to keep the callback hell at bay with vanilla JS, promises are growing in popularity and are currently being standardized in ES6 (see Promise - MDN).

Promises (a.k.a. Futures) provide a more linear, and thus pleasant, reading of the asynchronous code, but explaining their entire functionality is out of the scope of this question. Instead, I'll leave these excellent resources for the interested:

  • The Art of Node - Callbacks explains asynchronous code and callbacks very well with vanilla JS examples and Node.js code as well.

Note: I've marked this answer as Community Wiki, hence anyone with at least 100 reputations can edit and improve it! Please feel free to improve this answer, or submit a completely new answer if you'd like as well.

I want to turn this question into a canonical topic to answer asynchronicity issues which are unrelated to Ajax (there is How to return the response from an AJAX call? for that), hence this topic needs your help to be as good and helpful as possible!

In your last example, is there a specific reason why you use anonymous functions or would it work the same by using named functions?

The code examples are a bit weird as you're declaring the function after calling it. Works because of hoisting of course, but was it intentional?

You need to understand that the red circle code is only async because it is being executed by NATIVE async javascript functions. This is a feature of your javascript engine--whether it be Node.js or a browser. It is async because it is being passed in as a "callback" to a function that is essentially a black box (implemented in C etc..). To the hapless developer they are async...just because. If you want to write your own async function you have to hack it by sending it in to SetTimeout(myfunc,0). Should you do that? Another debate....probably not.

javascript - Why is my variable unaltered after I modify it inside of ...

javascript asynchronous
Rectangle 27 383

More reading material about JavaScript asynchronicity

This topic has been iterated at least a couple of thousands times, here, in Stack Overflow. Hence, first off I'd like to point out some extremely useful resources:

Let's trace the common behavior first. In all examples, the outerScopeVar is modified inside of a function. That function is clearly not executed immediately, it is being assigned or passed as an argument. That is what we call a callback.

Now the question is, when is that callback called?

It depends on the case. Let's try to trace some common behavior again:

  • img.onload may be called sometime in the future, when (and if) the image has successfully loaded.
  • setTimeout may be called sometime in the future, after the delay has expired and the timeout hasn't been cancelled by clearTimeout. Note: even when using 0 as delay, all browsers have a minimum timeout delay cap (specified to be 4ms in the HTML5 spec).
  • jQuery $.post's callback may be called sometime in the future, when (and if) the Ajax request has been completed successfully.
  • Node.js's fs.readFile may be called sometime in the future, when the file has been read successfully or thrown an error.

In all cases, we have a callback which may run sometime in the future. This "sometime in the future" is what we refer to as asynchronous flow.

Asynchronous execution is pushed out of the synchronous flow. That is, asynchronous code will never execute while the synchronous code stack is executing. This is the meaning of JavaScript being single-threaded.

More specifically, when the JS engine is idle -- not executing a stack of (a)synchronous code -- it will poll for events that may have triggered asynchronous callbacks (e.g. expired timeout, received network response) and execute them one after another. This is regarded as Event Loop.

That is, the asynchronous code highlighted in the hand-drawn red shapes may execute only after all the remaining synchronous code in their respective code blocks have executed:

In short, the callback functions are created synchronously, but executed asynchronously. You just can't rely on the execution of an asynchronous function until you know it has executed, and how to do that?

It is simple, really. The logic that depends on the asynchronous function execution should be started/called from inside this asynchronous function. For example, moving the alerts and console.logs to inside the callback function would output the expected result, because the result is available at that point.

Often you need to do more things with the result from an asynchronous function, or do different things with the result depending from where the asynchronous function has been called. Let's tackle a bit more complex example:

var outerScopeVar;
helloCatAsync();
alert(outerScopeVar);

function helloCatAsync() {
    setTimeout(function() {
        outerScopeVar = 'Nya';
    }, Math.random() * 2000);
}

Note: I'm using setTimeout with a random delay as a generic asynchronous function, the same example applies to Ajax, readFile, onload and any other asynchronous flow.

This example clearly suffers from the same issue as the other examples, it is not waiting until the asynchronous function executes.

Let's tackle it implementing a callback system of our own. First off, we get rid of that ugly outerScopeVar which is completely useless in this case. Then we add a parameter which accepts a function argument, our callback. When the asynchronous operation finishes, we call this callback passing the result. The implementation (please read the comments in order):

// 1. Call helloCatAsync passing a callback function,
//    which will be called receiving the result from the async operation
helloCatAsync(function(result) {
    // 5. Received the result from the async function,
    //    now do whatever you want with it:
    alert(result);
});

// 2. The "callback" parameter is a reference to the function which
//    was passed as argument from the helloCatAsync call
function helloCatAsync(callback) {
    // 3. Start async operation:
    setTimeout(function() {
        // 4. Finished async operation,
        //    call the callback passing the result as argument
        callback('Nya');
    }, Math.random() * 2000);
}

Most often in real use cases, the DOM API and most libraries already provide the callback functionality (the helloCatAsync implementation in this demonstrative example). You only need to pass the callback function and understand that it will execute out of the synchronous flow, and restructure your code to accommodate for that.

You will also notice that due to the asynchronous nature, it is impossible to return a value from an asynchronous flow back to the synchronous flow where the callback was defined, as the asynchronous callbacks are executed long after the synchronous code has already finished executing.

Instead of returning a value from an asynchronous callback, you will have to make use of the callback pattern, or... Promises.

Although there are ways to keep the callback hell at bay with vanilla JS, promises are growing in popularity and are currently being standardized in ES6 (see Promise - MDN).

Promises (a.k.a. Futures) provide a more linear, and thus pleasant, reading of asynchronous code, but explaining their entire functionality is out of the scope of this question. Instead, I'll leave these excellent resources for the interested:

  • The Art of Node - Callbacks explains asynchronous code and callbacks very well with vanilla JS examples and Node.js code as well.

Note: I've marked this answer as Community Wiki, hence anyone with at least 100 reputation can edit and improve it! Please feel free to improve this answer, or submit a completely new answer if you'd like as well.

I want to turn this question into a canonical topic to answer asynchronicity issues which are unrelated to Ajax (there is How to return the response from an AJAX call? for that), hence this topic needs your help to be as good and helpful as possible!

In your last example, is there a specific reason why you use anonymous functions or would it work the same by using named functions?

The code examples are a bit weird as you're declaring the function after calling it. Works because of hoisting of course, but was it intentional?

You need to understand that the red circle code is only async because it is being executed by NATIVE async javascript functions. This is a feature of your javascript engine--whether it be Node.js or a browser. It is async because it is being passed in as a "callback" to a function that is essentially a black box (implemented in C etc..). To the hapless developer they are async...just because. If you want to write your own async function you have to hack it by sending it in to SetTimeout(myfunc,0). Should you do that? Another debate....probably not.

javascript - Why is my variable unaltered after I modify it inside of ...

javascript asynchronous
Rectangle 27 383

More reading material about JavaScript asynchronicity

This topic has been iterated at least a couple of thousands times, here, in Stack Overflow. Hence, first off I'd like to point out some extremely useful resources:

Let's trace the common behavior first. In all examples, the outerScopeVar is modified inside of a function. That function is clearly not executed immediately, it is being assigned or passed as an argument. That is what we call a callback.

Now the question is, when is that callback called?

It depends on the case. Let's try to trace some common behavior again:

  • img.onload may be called sometime in the future, when (and if) the image has successfully loaded.
  • setTimeout may be called sometime in the future, after the delay has expired and the timeout hasn't been cancelled by clearTimeout. Note: even when using 0 as delay, all browsers have a minimum timeout delay cap (specified to be 4ms in the HTML5 spec).
  • jQuery $.post's callback may be called sometime in the future, when (and if) the Ajax request has been completed successfully.
  • Node.js's fs.readFile may be called sometime in the future, when the file has been read successfully or thrown an error.

In all cases, we have a callback which may run sometime in the future. This "sometime in the future" is what we refer to as asynchronous flow.

Asynchronous execution is pushed out of the synchronous flow. That is, asynchronous code will never execute while the synchronous code stack is executing. This is the meaning of JavaScript being single-threaded.

More specifically, when the JS engine is idle -- not executing a stack of (a)synchronous code -- it will poll for events that may have triggered asynchronous callbacks (e.g. expired timeout, received network response) and execute them one after another. This is regarded as Event Loop.

That is, the asynchronous code highlighted in the hand-drawn red shapes may execute only after all the remaining synchronous code in their respective code blocks have executed:

In short, the callback functions are created synchronously, but executed asynchronously. You just can't rely on the execution of an asynchronous function until you know it has executed, and how to do that?

It is simple, really. The logic that depends on the asynchronous function execution should be started/called from inside this asynchronous function. For example, moving the alerts and console.logs to inside the callback function would output the expected result, because the result is available at that point.

Often you need to do more things with the result from an asynchronous function, or do different things with the result depending from where the asynchronous function has been called. Let's tackle a bit more complex example:

var outerScopeVar;
helloCatAsync();
alert(outerScopeVar);

function helloCatAsync() {
    setTimeout(function() {
        outerScopeVar = 'Nya';
    }, Math.random() * 2000);
}

Note: I'm using setTimeout with a random delay as a generic asynchronous function, the same example applies to Ajax, readFile, onload and any other asynchronous flow.

This example clearly suffers from the same issue as the other examples, it is not waiting until the asynchronous function executes.

Let's tackle it implementing a callback system of our own. First off, we get rid of that ugly outerScopeVar which is completely useless in this case. Then we add a parameter which accepts a function argument, our callback. When the asynchronous operation finishes, we call this callback passing the result. The implementation (please read the comments in order):

// 1. Call helloCatAsync passing a callback function,
//    which will be called receiving the result from the async operation
helloCatAsync(function(result) {
    // 5. Received the result from the async function,
    //    now do whatever you want with it:
    alert(result);
});

// 2. The "callback" parameter is a reference to the function which
//    was passed as argument from the helloCatAsync call
function helloCatAsync(callback) {
    // 3. Start async operation:
    setTimeout(function() {
        // 4. Finished async operation,
        //    call the callback passing the result as argument
        callback('Nya');
    }, Math.random() * 2000);
}

Most often in real use cases, the DOM API and most libraries already provide the callback functionality (the helloCatAsync implementation in this demonstrative example). You only need to pass the callback function and understand that it will execute out of the synchronous flow, and restructure your code to accommodate for that.

You will also notice that due to the asynchronous nature, it is impossible to return a value from an asynchronous flow back to the synchronous flow where the callback was defined, as the asynchronous callbacks are executed long after the synchronous code has already finished executing.

Instead of returning a value from an asynchronous callback, you will have to make use of the callback pattern, or... Promises.

Although there are ways to keep the callback hell at bay with vanilla JS, promises are growing in popularity and are currently being standardized in ES6 (see Promise - MDN).

Promises (a.k.a. Futures) provide a more linear, and thus pleasant, reading of asynchronous code, but explaining their entire functionality is out of the scope of this question. Instead, I'll leave these excellent resources for the interested:

  • The Art of Node - Callbacks explains asynchronous code and callbacks very well with vanilla JS examples and Node.js code as well.

Note: I've marked this answer as Community Wiki, hence anyone with at least 100 reputation can edit and improve it! Please feel free to improve this answer, or submit a completely new answer if you'd like as well.

I want to turn this question into a canonical topic to answer asynchronicity issues which are unrelated to Ajax (there is How to return the response from an AJAX call? for that), hence this topic needs your help to be as good and helpful as possible!

In your last example, is there a specific reason why you use anonymous functions or would it work the same by using named functions?

The code examples are a bit weird as you're declaring the function after calling it. Works because of hoisting of course, but was it intentional?

You need to understand that the red circle code is only async because it is being executed by NATIVE async javascript functions. This is a feature of your javascript engine--whether it be Node.js or a browser. It is async because it is being passed in as a "callback" to a function that is essentially a black box (implemented in C etc..). To the hapless developer they are async...just because. If you want to write your own async function you have to hack it by sending it in to SetTimeout(myfunc,0). Should you do that? Another debate....probably not.

javascript - Why is my variable unaltered after I modify it inside of ...

javascript asynchronous
Rectangle 27 375

More reading material about JavaScript asynchronicity

This topic has been iterated at least a couple of thousands times, here, in Stack Overflow. Hence, first off I'd like to point out some extremely useful resources:

Let's trace the common behavior first. In all examples, the outerScopeVar is modified inside of a function. That function is clearly not executed immediately, it is being assigned or passed as an argument. That is what we call a callback.

Now the question is, when is that callback called?

It depends on the case. Let's try to trace some common behavior again:

  • img.onload may be called sometime in the future, when (and if) the image has successfully loaded.
  • setTimeout may be called sometime in the future, after the delay has expired and the timeout hasn't been cancelled by clearTimeout. Note: even when using 0 as delay, all browsers have a minimum timeout delay cap (specified to be 4ms in the HTML5 spec).
  • jQuery $.post's callback may be called sometime in the future, when (and if) the Ajax request has been completed successfully.
  • Node.js's fs.readFile may be called sometime in the future, when the file has been read successfully or thrown an error.

In all cases, we have a callback which may run sometime in the future. This "sometime in the future" is what we refer to as asynchronous flow.

Asynchronous execution is pushed out of the synchronous flow. That is, asynchronous code will never execute while the synchronous code stack is executing. This is the meaning of JavaScript being single-threaded.

More specifically, when the JS engine is idle -- not executing a stack of (a)synchronous code -- it will poll for events that may have triggered asynchronous callbacks (e.g. expired timeout, received network response) and execute them one after another. This is regarded as Event Loop.

That is, the asynchronous code highlighted in the hand-drawn red shapes may execute only after all the remaining synchronous code in their respective code blocks have executed:

In short, the callback functions are created synchronously, but executed asynchronously. You just can't rely on the execution of an asynchronous function until you know it has executed, and how to do that?

It is simple, really. The logic that depends on the asynchronous function execution should be started/called from inside this asynchronous function. For example, moving the alerts and console.logs to inside the callback function would output the expected result, because the result is available at that point.

Often you need to do more things with the result from an asynchronous function, or do different things with the result depending from where the asynchronous function has been called. Let's tackle a bit more complex example:

var outerScopeVar;
helloCatAsync();
alert(outerScopeVar);

function helloCatAsync() {
    setTimeout(function() {
        outerScopeVar = 'Nya';
    }, Math.random() * 2000);
}

Note: I'm using setTimeout with a random delay as a generic asynchronous function, the same example applies to Ajax, readFile, onload and any other asynchronous flow.

This example clearly suffers from the same issue as the other examples, it is not waiting until the asynchronous function executes.

Let's tackle it implementing a callback system of our own. First off, we get rid of that ugly outerScopeVar which is completely useless in this case. Then we add a parameter which accepts a function argument, our callback. When the asynchronous operation finishes, we call this callback passing the result. The implementation (please read the comments in order):

// 1. Call helloCatAsync passing a callback function,
//    which will be called receiving the result from the async operation
helloCatAsync(function(result) {
    // 5. Received the result from the async function,
    //    now do whatever you want with it:
    alert(result);
});

// 2. The "callback" parameter is a reference to the function which
//    was passed as argument from the helloCatAsync call
function helloCatAsync(callback) {
    // 3. Start async operation:
    setTimeout(function() {
        // 4. Finished async operation,
        //    call the callback passing the result as argument
        callback('Nya');
    }, Math.random() * 2000);
}

Most often in real use cases, the DOM API and most libraries already provide the callback functionality (the helloCatAsync implementation in this demonstrative example). You only need to pass the callback function and understand that it will execute out of the synchronous flow, and restructure your code to accommodate for that.

You will also notice that due to the asynchronous nature, it is impossible to return a value from an asynchronous flow back to the synchronous flow where the callback was defined, as the asynchronous callbacks are executed long after the synchronous code has already finished executing.

Instead of returning a value from an asynchronous callback, you will have to make use of the callback pattern, or... Promises.

Although there are ways to keep the callback hell at bay with vanilla JS, promises are growing in popularity and are currently being standardized in ES6 (see Promise - MDN).

Promises (a.k.a. Futures) provide a more linear, and thus pleasant, reading of asynchronous code, but explaining their entire functionality is out of the scope of this question. Instead, I'll leave these excellent resources for the interested:

  • The Art of Node - Callbacks explains asynchronous code and callbacks very well with vanilla JS examples and Node.js code as well.

Note: I've marked this answer as Community Wiki, hence anyone with at least 100 reputation can edit and improve it! Please feel free to improve this answer, or submit a completely new answer if you'd like as well.

I want to turn this question into a canonical topic to answer asynchronicity issues which are unrelated to Ajax (there is How to return the response from an AJAX call? for that), hence this topic needs your help to be as good and helpful as possible!

In your last example, is there a specific reason why you use anonymous functions or would it work the same by using named functions?

The code examples are a bit weird as you're declaring the function after calling it. Works because of hoisting of course, but was it intentional?

You need to understand that the red circle code is only async because it is being executed by NATIVE async javascript functions. This is a feature of your javascript engine--whether it be Node.js or a browser. It is async because it is being passed in as a "callback" to a function that is essentially a black box (implemented in C etc..). To the hapless developer they are async...just because. If you want to write your own async function you have to hack it by sending it in to SetTimeout(myfunc,0). Should you do that? Another debate....probably not.

javascript - Why is my variable unaltered after I modify it inside of ...

javascript asynchronous
Rectangle 27 375

More reading material about JavaScript asynchronicity

This topic has been iterated at least a couple of thousands times, here, in Stack Overflow. Hence, first off I'd like to point out some extremely useful resources:

Let's trace the common behavior first. In all examples, the outerScopeVar is modified inside of a function. That function is clearly not executed immediately, it is being assigned or passed as an argument. That is what we call a callback.

Now the question is, when is that callback called?

It depends on the case. Let's try to trace some common behavior again:

  • img.onload may be called sometime in the future, when (and if) the image has successfully loaded.
  • setTimeout may be called sometime in the future, after the delay has expired and the timeout hasn't been cancelled by clearTimeout. Note: even when using 0 as delay, all browsers have a minimum timeout delay cap (specified to be 4ms in the HTML5 spec).
  • jQuery $.post's callback may be called sometime in the future, when (and if) the Ajax request has been completed successfully.
  • Node.js's fs.readFile may be called sometime in the future, when the file has been read successfully or thrown an error.

In all cases, we have a callback which may run sometime in the future. This "sometime in the future" is what we refer to as asynchronous flow.

Asynchronous execution is pushed out of the synchronous flow. That is, asynchronous code will never execute while the synchronous code stack is executing. This is the meaning of JavaScript being single-threaded.

More specifically, when the JS engine is idle -- not executing a stack of (a)synchronous code -- it will poll for events that may have triggered asynchronous callbacks (e.g. expired timeout, received network response) and execute them one after another. This is regarded as Event Loop.

That is, the asynchronous code highlighted in the hand-drawn red shapes may execute only after all the remaining synchronous code in their respective code blocks have executed:

In short, the callback functions are created synchronously, but executed asynchronously. You just can't rely on the execution of an asynchronous function until you know it has executed, and how to do that?

It is simple, really. The logic that depends on the asynchronous function execution should be started/called from inside this asynchronous function. For example, moving the alerts and console.logs to inside the callback function would output the expected result, because the result is available at that point.

Often you need to do more things with the result from an asynchronous function, or do different things with the result depending from where the asynchronous function has been called. Let's tackle a bit more complex example:

var outerScopeVar;
helloCatAsync();
alert(outerScopeVar);

function helloCatAsync() {
    setTimeout(function() {
        outerScopeVar = 'Nya';
    }, Math.random() * 2000);
}

Note: I'm using setTimeout with a random delay as a generic asynchronous function, the same example applies to Ajax, readFile, onload and any other asynchronous flow.

This example clearly suffers from the same issue as the other examples, it is not waiting until the asynchronous function executes.

Let's tackle it implementing a callback system of our own. First off, we get rid of that ugly outerScopeVar which is completely useless in this case. Then we add a parameter which accepts a function argument, our callback. When the asynchronous operation finishes, we call this callback passing the result. The implementation (please read the comments in order):

// 1. Call helloCatAsync passing a callback function,
//    which will be called receiving the result from the async operation
helloCatAsync(function(result) {
    // 5. Received the result from the async function,
    //    now do whatever you want with it:
    alert(result);
});

// 2. The "callback" parameter is a reference to the function which
//    was passed as argument from the helloCatAsync call
function helloCatAsync(callback) {
    // 3. Start async operation:
    setTimeout(function() {
        // 4. Finished async operation,
        //    call the callback passing the result as argument
        callback('Nya');
    }, Math.random() * 2000);
}

Most often in real use cases, the DOM API and most libraries already provide the callback functionality (the helloCatAsync implementation in this demonstrative example). You only need to pass the callback function and understand that it will execute out of the synchronous flow, and restructure your code to accommodate for that.

You will also notice that due to the asynchronous nature, it is impossible to return a value from an asynchronous flow back to the synchronous flow where the callback was defined, as the asynchronous callbacks are executed long after the synchronous code has already finished executing.

Instead of returning a value from an asynchronous callback, you will have to make use of the callback pattern, or... Promises.

Although there are ways to keep the callback hell at bay with vanilla JS, promises are growing in popularity and are currently being standardized in ES6 (see Promise - MDN).

Promises (a.k.a. Futures) provide a more linear, and thus pleasant, reading of asynchronous code, but explaining their entire functionality is out of the scope of this question. Instead, I'll leave these excellent resources for the interested:

  • The Art of Node - Callbacks explains asynchronous code and callbacks very well with vanilla JS examples and Node.js code as well.

Note: I've marked this answer as Community Wiki, hence anyone with at least 100 reputation can edit and improve it! Please feel free to improve this answer, or submit a completely new answer if you'd like as well.

I want to turn this question into a canonical topic to answer asynchronicity issues which are unrelated to Ajax (there is How to return the response from an AJAX call? for that), hence this topic needs your help to be as good and helpful as possible!

In your last example, is there a specific reason why you use anonymous functions or would it work the same by using named functions?

The code examples are a bit weird as you're declaring the function after calling it. Works because of hoisting of course, but was it intentional?

You need to understand that the red circle code is only async because it is being executed by NATIVE async javascript functions. This is a feature of your javascript engine--whether it be Node.js or a browser. It is async because it is being passed in as a "callback" to a function that is essentially a black box (implemented in C etc..). To the hapless developer they are async...just because. If you want to write your own async function you have to hack it by sending it in to SetTimeout(myfunc,0). Should you do that? Another debate....probably not.

javascript - Why is my variable unaltered after I modify it inside of ...

javascript asynchronous
Rectangle 27 372

More reading material about JavaScript asynchronicity

This topic has been iterated at least a couple of thousands times, here, in Stack Overflow. Hence, first off I'd like to point out some extremely useful resources:

Let's trace the common behavior first. In all examples, the outerScopeVar is modified inside of a function. That function is clearly not executed immediately, it is being assigned or passed as an argument. That is what we call a callback.

Now the question is, when is that callback called?

It depends on the case. Let's try to trace some common behavior again:

  • img.onload may be called sometime in the future, when (and if) the image has successfully loaded.
  • setTimeout may be called sometime in the future, after the delay has expired and the timeout hasn't been cancelled by clearTimeout. Note: even when using 0 as delay, all browsers have a minimum timeout delay cap (specified to be 4ms in the HTML5 spec).
  • jQuery $.post's callback may be called sometime in the future, when (and if) the Ajax request has been completed successfully.
  • Node.js's fs.readFile may be called sometime in the future, when the file has been read successfully or thrown an error.

In all cases, we have a callback which may run sometime in the future. This "sometime in the future" is what we refer to as asynchronous flow.

Asynchronous execution is pushed out of the synchronous flow. That is, asynchronous code will never execute while the synchronous code stack is executing. This is the meaning of JavaScript being single-threaded.

More specifically, when the JS engine is idle -- not executing a stack of (a)synchronous code -- it will poll for events that may have triggered asynchronous callbacks (e.g. expired timeout, received network response) and execute them one after another. This is regarded as Event Loop.

That is, the asynchronous code highlighted in the hand-drawn red shapes may execute only after all the remaining synchronous code in their respective code blocks have executed:

In short, the callback functions are created synchronously, but executed asynchronously. You just can't rely on the execution of an asynchronous function until you know it has executed, and how to do that?

It is simple, really. The logic that depends on the asynchronous function execution should be started/called from inside this asynchronous function. For example, moving the alerts and console.logs to inside the callback function would output the expected result, because the result is available at that point.

Often you need to do more things with the result from an asynchronous function, or do different things with the result depending from where the asynchronous function has been called. Let's tackle a bit more complex example:

var outerScopeVar;
helloCatAsync();
alert(outerScopeVar);

function helloCatAsync() {
    setTimeout(function() {
        outerScopeVar = 'Nya';
    }, Math.random() * 2000);
}

Note: I'm using setTimeout with a random delay as a generic asynchronous function, the same example applies to Ajax, readFile, onload and any other asynchronous flow.

This example clearly suffers from the same issue as the other examples, it is not waiting until the asynchronous function executes.

Let's tackle it implementing a callback system of our own. First off, we get rid of that ugly outerScopeVar which is completely useless in this case. Then we add a parameter which accepts a function argument, our callback. When the asynchronous operation finishes, we call this callback passing the result. The implementation (please read the comments in order):

// 1. Call helloCatAsync passing a callback function,
//    which will be called receiving the result from the async operation
helloCatAsync(function(result) {
    // 5. Received the result from the async function,
    //    now do whatever you want with it:
    alert(result);
});

// 2. The "callback" parameter is a reference to the function which
//    was passed as argument from the helloCatAsync call
function helloCatAsync(callback) {
    // 3. Start async operation:
    setTimeout(function() {
        // 4. Finished async operation,
        //    call the callback passing the result as argument
        callback('Nya');
    }, Math.random() * 2000);
}

Most often in real use cases, the DOM API and most libraries already provide the callback functionality (the helloCatAsync implementation in this demonstrative example). You only need to pass the callback function and understand that it will execute out of the synchronous flow, and restructure your code to accommodate for that.

You will also notice that due to the asynchronous nature, it is impossible to return a value from an asynchronous flow back to the synchronous flow where the callback was defined, as the asynchronous callbacks are executed long after the synchronous code has already finished executing.

Instead of returning a value from an asynchronous callback, you will have to make use of the callback pattern, or... Promises.

Although there are ways to keep the callback hell at bay with vanilla JS, promises are growing in popularity and are currently being standardized in ES6 (see Promise - MDN).

Promises (a.k.a. Futures) provide a more linear, and thus pleasant, reading of asynchronous code, but explaining their entire functionality is out of the scope of this question. Instead, I'll leave these excellent resources for the interested:

  • The Art of Node - Callbacks explains asynchronous code and callbacks very well with vanilla JS examples and Node.js code as well.

Note: I've marked this answer as Community Wiki, hence anyone with at least 100 reputation can edit and improve it! Please feel free to improve this answer, or submit a completely new answer if you'd like as well.

I want to turn this question into a canonical topic to answer asynchronicity issues which are unrelated to Ajax (there is How to return the response from an AJAX call? for that), hence this topic needs your help to be as good and helpful as possible!

In your last example, is there a specific reason why you use anonymous functions or would it work the same by using named functions?

The code examples are a bit weird as you're declaring the function after calling it. Works because of hoisting of course, but was it intentional?

You need to understand that the red circle code is only async because it is being executed by NATIVE async javascript functions. This is a feature of your javascript engine--whether it be Node.js or a browser. It is async because it is being passed in as a "callback" to a function that is essentially a black box (implemented in C etc..). To the hapless developer they are async...just because. If you want to write your own async function you have to hack it by sending it in to SetTimeout(myfunc,0). Should you do that? Another debate....probably not.

javascript - Why is my variable unaltered after I modify it inside of ...

javascript asynchronous
Rectangle 27 372

More reading material about JavaScript asynchronicity

This topic has been iterated at least a couple of thousands times, here, in Stack Overflow. Hence, first off I'd like to point out some extremely useful resources:

Let's trace the common behavior first. In all examples, the outerScopeVar is modified inside of a function. That function is clearly not executed immediately, it is being assigned or passed as an argument. That is what we call a callback.

Now the question is, when is that callback called?

It depends on the case. Let's try to trace some common behavior again:

  • img.onload may be called sometime in the future, when (and if) the image has successfully loaded.
  • setTimeout may be called sometime in the future, after the delay has expired and the timeout hasn't been cancelled by clearTimeout. Note: even when using 0 as delay, all browsers have a minimum timeout delay cap (specified to be 4ms in the HTML5 spec).
  • jQuery $.post's callback may be called sometime in the future, when (and if) the Ajax request has been completed successfully.
  • Node.js's fs.readFile may be called sometime in the future, when the file has been read successfully or thrown an error.

In all cases, we have a callback which may run sometime in the future. This "sometime in the future" is what we refer to as asynchronous flow.

Asynchronous execution is pushed out of the synchronous flow. That is, asynchronous code will never execute while the synchronous code stack is executing. This is the meaning of JavaScript being single-threaded.

More specifically, when the JS engine is idle -- not executing a stack of (a)synchronous code -- it will poll for events that may have triggered asynchronous callbacks (e.g. expired timeout, received network response) and execute them one after another. This is regarded as Event Loop.

That is, the asynchronous code highlighted in the hand-drawn red shapes may execute only after all the remaining synchronous code in their respective code blocks have executed:

In short, the callback functions are created synchronously, but executed asynchronously. You just can't rely on the execution of an asynchronous function until you know it has executed, and how to do that?

It is simple, really. The logic that depends on the asynchronous function execution should be started/called from inside this asynchronous function. For example, moving the alerts and console.logs to inside the callback function would output the expected result, because the result is available at that point.

Often you need to do more things with the result from an asynchronous function, or do different things with the result depending from where the asynchronous function has been called. Let's tackle a bit more complex example:

var outerScopeVar;
helloCatAsync();
alert(outerScopeVar);

function helloCatAsync() {
    setTimeout(function() {
        outerScopeVar = 'Nya';
    }, Math.random() * 2000);
}

Note: I'm using setTimeout with a random delay as a generic asynchronous function, the same example applies to Ajax, readFile, onload and any other asynchronous flow.

This example clearly suffers from the same issue as the other examples, it is not waiting until the asynchronous function executes.

Let's tackle it implementing a callback system of our own. First off, we get rid of that ugly outerScopeVar which is completely useless in this case. Then we add a parameter which accepts a function argument, our callback. When the asynchronous operation finishes, we call this callback passing the result. The implementation (please read the comments in order):

// 1. Call helloCatAsync passing a callback function,
//    which will be called receiving the result from the async operation
helloCatAsync(function(result) {
    // 5. Received the result from the async function,
    //    now do whatever you want with it:
    alert(result);
});

// 2. The "callback" parameter is a reference to the function which
//    was passed as argument from the helloCatAsync call
function helloCatAsync(callback) {
    // 3. Start async operation:
    setTimeout(function() {
        // 4. Finished async operation,
        //    call the callback passing the result as argument
        callback('Nya');
    }, Math.random() * 2000);
}

Most often in real use cases, the DOM API and most libraries already provide the callback functionality (the helloCatAsync implementation in this demonstrative example). You only need to pass the callback function and understand that it will execute out of the synchronous flow, and restructure your code to accommodate for that.

You will also notice that due to the asynchronous nature, it is impossible to return a value from an asynchronous flow back to the synchronous flow where the callback was defined, as the asynchronous callbacks are executed long after the synchronous code has already finished executing.

Instead of returning a value from an asynchronous callback, you will have to make use of the callback pattern, or... Promises.

Although there are ways to keep the callback hell at bay with vanilla JS, promises are growing in popularity and are currently being standardized in ES6 (see Promise - MDN).

Promises (a.k.a. Futures) provide a more linear, and thus pleasant, reading of asynchronous code, but explaining their entire functionality is out of the scope of this question. Instead, I'll leave these excellent resources for the interested:

  • The Art of Node - Callbacks explains asynchronous code and callbacks very well with vanilla JS examples and Node.js code as well.

Note: I've marked this answer as Community Wiki, hence anyone with at least 100 reputation can edit and improve it! Please feel free to improve this answer, or submit a completely new answer if you'd like as well.

I want to turn this question into a canonical topic to answer asynchronicity issues which are unrelated to Ajax (there is How to return the response from an AJAX call? for that), hence this topic needs your help to be as good and helpful as possible!

In your last example, is there a specific reason why you use anonymous functions or would it work the same by using named functions?

The code examples are a bit weird as you're declaring the function after calling it. Works because of hoisting of course, but was it intentional?

You need to understand that the red circle code is only async because it is being executed by NATIVE async javascript functions. This is a feature of your javascript engine--whether it be Node.js or a browser. It is async because it is being passed in as a "callback" to a function that is essentially a black box (implemented in C etc..). To the hapless developer they are async...just because. If you want to write your own async function you have to hack it by sending it in to SetTimeout(myfunc,0). Should you do that? Another debate....probably not.

javascript - Why is my variable unaltered after I modify it inside of ...

javascript asynchronous
Rectangle 27 15

@EdSpencer is correct. If you have a lot of elements and you use ng-if to only instantiate the relevant ones, you are saving resources. @CodeHater is also somewhat correct, if you are going to remove and show an element very often, hiding it instead of removing it could improve performance.

The main use case I find for ng-if is that it allows me to cleanly validate and eliminte an element if the contents is illegal. For instance I could reference to a null image name variable and that will throw an error but if I ng-if and check if it's null, it's all good. If I did an ng-show, the error would still fire.

angularjs - what is the difference between ng-if and ng-show/ng-hide -...

angularjs
Rectangle 27 15

@EdSpencer is correct. If you have a lot of elements and you use ng-if to only instantiate the relevant ones, you are saving resources. @CodeHater is also somewhat correct, if you are going to remove and show an element very often, hiding it instead of removing it could improve performance.

The main use case I find for ng-if is that it allows me to cleanly validate and eliminte an element if the contents is illegal. For instance I could reference to a null image name variable and that will throw an error but if I ng-if and check if it's null, it's all good. If I did an ng-show, the error would still fire.

angularjs - what is the difference between ng-if and ng-show/ng-hide -...

angularjs
Rectangle 27 15

I have a slightly different approach that might be useful/more beneficial to some.

Under your main project folder, create a resource folder. Your folder structure should look something like this.

Go to the properties of your project. You can do this by right clicking on your project in the Projects tab window and selecting Properties in the drop down menu.

Under categories on the left side, select Sources.

In Source Package Folders on the right side, add your resource folder using the Add Folder button. Once you click OK, you should see a Resources folder under your project.

You should now be able to pull resources using this line or similar approach:

MyClass.class.getResource("/main.jpg");

If you were to create a package called Images under the resources folder, you can retrieve the resource like this:

MyClass.class.getResource("/Images/main.jpg");

i used this method but i found a disturbing effect. after the build netbeans loads all the resources inside the jar, and i really want the resources to stay out of the jar! so is there a workaround for this problem ?

Unfortunately, the java resource method might not be exactly what your looking for. However, if your files reside within the classpath, you may be able to use ClassLoader.getSystemResource("somefile.txt")...you also would no longer want to include the resources folder as stated above. Another option would be to look in the jar's parent directory (or static path) for a given file (resource) and open them using File or some other equivalent to fit your needs. If the file does not exist, create it from the resources stored within the jar. They would be more like templates in this case.

java - How to correctly get image from 'Resources' folder in NetBeans ...

java netbeans resources
Rectangle 27 13

I find these functions very helpful to cache any expression. The interesting thing here for these two functions is that the held expression itself is used as a key of the hashtable/symbol Cache or CacheIndex, compared to the well-known memoization in mathematica where you can only cache result if the function is defined like f[x_] := f[x] = ... So you can cache any part of a code, this is useful if a function is to be called several times but just some parts of the code must not be recomputed.

To cache an expression independently of its arguments.

SetAttributes[Cache, HoldFirst];
c:Cache[expr_] := c = expr;

Ex: Cache[Pause[5]; 6]
Cache[Pause[5]; 6]

The second time the expression returns 6 without waiting.

To cache an expression using an alias expression that can depend on an argument of the cached expression.

SetAttributes[CacheIndex, HoldRest];
c:CacheIndex[index_,expr_] := c = expr;

Ex: CacheIndex[{"f",2},x=2;y=4;x+y]

For a variation of these functions in order to have a localized cache (ie. the cache memory is automatically released outside the Block construct) see this post Avoid repeated calls to Interpolation

DeleteCachedValues[f_] := 
       DownValues[f] = Select[DownValues[f], !FreeQ[Hold@#,Pattern]&];

To delete cached values when you know the number of definitions of a function (goes slightly faster).

DeleteCachedValues[f_,nrules_] := 
       DownValues[f] = Extract[DownValues[f], List /@ Range[-nrules, -1]];

This uses the fact that definitions of a function are at the end of their DownValues list, cached values are before.

It is already well known that you can store data in symbols and quickly access them using DownValues

mysymbol["property"]=2;

You can access the list of keys (or properties) of a symbol using these functions based on what dreeves submitted in a post on this site:

SetAttributes[RemoveHead, {HoldAll}];
RemoveHead[h_[args___]] := {args};
NKeys[symbol_] := RemoveHead @@@ DownValues[symbol(*,Sort->False*)][[All,1]];
Keys[symbol_] := NKeys[symbol] /. {x_} :> x;

I use this function a lot to display all infos contained in the DownValues of a symbol:

PrintSymbol[symbol_] :=
  Module[{symbolKeys},
    symbolKeys = Keys[symbol];
    TableForm@Transpose[{symbolKeys, symbol /@ symbolKeys}]
  ];

Finally here is a simple way to create a symbol that behaves like an object in object oriented programming (it just reproduces the most basic behaviour of OOP but I find the syntax elegant) :

Options[NewObject]={y->2};
NewObject[OptionsPattern[]]:=
  Module[{newObject},
    newObject["y"]=OptionValue[y];

    function[newObject,x_] ^:= newObject["y"]+x;
    newObject /: newObject.function2[x_] := 2 newObject["y"]+x;

    newObject
  ];

Properties are stored as DownValues and methods as delayed Upvalues in the symbol created by Module that is returned. I found the syntax for function2 that is the usual OO-syntax for functions in Tree data structure in Mathematica.

x = NewObject[y -> 3];
function[x, 4]
x.function2[5]

You can go further if you want to emulate object inheritance using a package called InheritRules available here http://library.wolfram.com/infocenter/MathSource/671/

You could also store the function definition not in newObject but in a type symbol, so if NewObject returned type[newObject] instead of newObject you could define function and function2 like this outside of NewObject (and not inside) and have the same usage as before.

function[type[object_], x_] ^:= object["y"] + x;
type /: type[object_].function2[x_] := 2 object["y"]+x;

Use UpValues[type] to see that function and function2 are defined in the type symbol.

@rcollyer: Many thanks for bringing SelectEquivalents to the surface, it's an amazing function. Here is an improved version of SelectEquivalents listed above with more possibilities and using options, this makes it easier to use.

Options[SelectEquivalents] = 
   {
      TagElement->Identity,
      TransformElement->Identity,
      TransformResults->(#2&) (*#1=tag,#2 list of elements corresponding to tag*),
      MapLevel->1,
      TagPattern->_,
      FinalFunction->Identity
   };

SelectEquivalents[x_List,OptionsPattern[]] := 
   With[
      {
         tagElement=OptionValue@TagElement,
         transformElement=OptionValue@TransformElement,
         transformResults=OptionValue@TransformResults,
         mapLevel=OptionValue@MapLevel,
         tagPattern=OptionValue@TagPattern,
         finalFunction=OptionValue@FinalFunction
      }
      ,
      finalFunction[
         Reap[
            Map[
               Sow[
                  transformElement@#
                  ,
                  {tagElement@#}
               ]&
               , 
               x
               , 
               {mapLevel}
            ] 
            , 
            tagPattern
            , 
            transformResults
         ][[2]]
      ]
   ];

Here are examples of how this version can be used:

These two posts point to useful functions for debugging:

Here's another function based on Reap and Sow to extract expressions from different parts of a program and store them in a symbol.

SetAttributes[ReapTags,HoldFirst];
ReapTags[expr_]:=
   Module[{elements},
      Reap[expr,_,(elements[#1]=#2/.{x_}:>x)&];
      elements
   ];
ftest[]:=((*some code*)Sow[1,"x"];(*some code*)Sow[2,"x"];(*some code*)Sow[3,"y"]);
s=ReapTags[ftest[]];
Keys[s]
s["x"]
PrintSymbol[s] (*Keys and PrintSymbol are defined above*)

Here's a list of interesting links for learning purpose:

Related: "The best way to construct a function with memory". WReach has given there an amazing example of simple function that not only remembers its values but also writes them to a file and reads backward on restart.

f[x_] := f[x] = some code

+1 There is a nice notational convenience that eliminates the need to repeat the left-hand side of the definition in a caching function, e.g.: c:Cache[expr_] := c = expr.

Nice variant of SelectEquivalents. I think, I'd keep TagOnElement as the second param defaulting to Identity as it is the most used of them, though. I don't think I'd included FinalOp, either, as it can be handled within OpOnTaggedElems. I'd also shorten the option names, as their length makes it awkward to type out. Try TagFunction, TransformElement, TransformResults, and TagPattern instead. Both, TagPattern and MapLevel are great additions to the functionality, and a good rewrite, overall.

Thanks for your comment rcollyer. I took it into account and improved also the readability of the code. I keep FinalFunction because it operates on the result of Reap, for example if you want to sort your final result by tags if you keep them.

resources - What is in your Mathematica tool bag? - Stack Overflow

resources wolfram-mathematica
Rectangle 27 13

I find these functions very helpful to cache any expression. The interesting thing here for these two functions is that the held expression itself is used as a key of the hashtable/symbol Cache or CacheIndex, compared to the well-known memoization in mathematica where you can only cache result if the function is defined like f[x_] := f[x] = ... So you can cache any part of a code, this is useful if a function is to be called several times but just some parts of the code must not be recomputed.

To cache an expression independently of its arguments.

SetAttributes[Cache, HoldFirst];
c:Cache[expr_] := c = expr;

Ex: Cache[Pause[5]; 6]
Cache[Pause[5]; 6]

The second time the expression returns 6 without waiting.

To cache an expression using an alias expression that can depend on an argument of the cached expression.

SetAttributes[CacheIndex, HoldRest];
c:CacheIndex[index_,expr_] := c = expr;

Ex: CacheIndex[{"f",2},x=2;y=4;x+y]

For a variation of these functions in order to have a localized cache (ie. the cache memory is automatically released outside the Block construct) see this post Avoid repeated calls to Interpolation

DeleteCachedValues[f_] := 
       DownValues[f] = Select[DownValues[f], !FreeQ[Hold@#,Pattern]&];

To delete cached values when you know the number of definitions of a function (goes slightly faster).

DeleteCachedValues[f_,nrules_] := 
       DownValues[f] = Extract[DownValues[f], List /@ Range[-nrules, -1]];

This uses the fact that definitions of a function are at the end of their DownValues list, cached values are before.

It is already well known that you can store data in symbols and quickly access them using DownValues

mysymbol["property"]=2;

You can access the list of keys (or properties) of a symbol using these functions based on what dreeves submitted in a post on this site:

SetAttributes[RemoveHead, {HoldAll}];
RemoveHead[h_[args___]] := {args};
NKeys[symbol_] := RemoveHead @@@ DownValues[symbol(*,Sort->False*)][[All,1]];
Keys[symbol_] := NKeys[symbol] /. {x_} :> x;

I use this function a lot to display all infos contained in the DownValues of a symbol:

PrintSymbol[symbol_] :=
  Module[{symbolKeys},
    symbolKeys = Keys[symbol];
    TableForm@Transpose[{symbolKeys, symbol /@ symbolKeys}]
  ];

Finally here is a simple way to create a symbol that behaves like an object in object oriented programming (it just reproduces the most basic behaviour of OOP but I find the syntax elegant) :

Options[NewObject]={y->2};
NewObject[OptionsPattern[]]:=
  Module[{newObject},
    newObject["y"]=OptionValue[y];

    function[newObject,x_] ^:= newObject["y"]+x;
    newObject /: newObject.function2[x_] := 2 newObject["y"]+x;

    newObject
  ];

Properties are stored as DownValues and methods as delayed Upvalues in the symbol created by Module that is returned. I found the syntax for function2 that is the usual OO-syntax for functions in Tree data structure in Mathematica.

x = NewObject[y -> 3];
function[x, 4]
x.function2[5]

You can go further if you want to emulate object inheritance using a package called InheritRules available here http://library.wolfram.com/infocenter/MathSource/671/

You could also store the function definition not in newObject but in a type symbol, so if NewObject returned type[newObject] instead of newObject you could define function and function2 like this outside of NewObject (and not inside) and have the same usage as before.

function[type[object_], x_] ^:= object["y"] + x;
type /: type[object_].function2[x_] := 2 object["y"]+x;

Use UpValues[type] to see that function and function2 are defined in the type symbol.

@rcollyer: Many thanks for bringing SelectEquivalents to the surface, it's an amazing function. Here is an improved version of SelectEquivalents listed above with more possibilities and using options, this makes it easier to use.

Options[SelectEquivalents] = 
   {
      TagElement->Identity,
      TransformElement->Identity,
      TransformResults->(#2&) (*#1=tag,#2 list of elements corresponding to tag*),
      MapLevel->1,
      TagPattern->_,
      FinalFunction->Identity
   };

SelectEquivalents[x_List,OptionsPattern[]] := 
   With[
      {
         tagElement=OptionValue@TagElement,
         transformElement=OptionValue@TransformElement,
         transformResults=OptionValue@TransformResults,
         mapLevel=OptionValue@MapLevel,
         tagPattern=OptionValue@TagPattern,
         finalFunction=OptionValue@FinalFunction
      }
      ,
      finalFunction[
         Reap[
            Map[
               Sow[
                  transformElement@#
                  ,
                  {tagElement@#}
               ]&
               , 
               x
               , 
               {mapLevel}
            ] 
            , 
            tagPattern
            , 
            transformResults
         ][[2]]
      ]
   ];

Here are examples of how this version can be used:

These two posts point to useful functions for debugging:

Here's another function based on Reap and Sow to extract expressions from different parts of a program and store them in a symbol.

SetAttributes[ReapTags,HoldFirst];
ReapTags[expr_]:=
   Module[{elements},
      Reap[expr,_,(elements[#1]=#2/.{x_}:>x)&];
      elements
   ];
ftest[]:=((*some code*)Sow[1,"x"];(*some code*)Sow[2,"x"];(*some code*)Sow[3,"y"]);
s=ReapTags[ftest[]];
Keys[s]
s["x"]
PrintSymbol[s] (*Keys and PrintSymbol are defined above*)

Here's a list of interesting links for learning purpose:

Related: "The best way to construct a function with memory". WReach has given there an amazing example of simple function that not only remembers its values but also writes them to a file and reads backward on restart.

f[x_] := f[x] = some code

+1 There is a nice notational convenience that eliminates the need to repeat the left-hand side of the definition in a caching function, e.g.: c:Cache[expr_] := c = expr.

Nice variant of SelectEquivalents. I think, I'd keep TagOnElement as the second param defaulting to Identity as it is the most used of them, though. I don't think I'd included FinalOp, either, as it can be handled within OpOnTaggedElems. I'd also shorten the option names, as their length makes it awkward to type out. Try TagFunction, TransformElement, TransformResults, and TagPattern instead. Both, TagPattern and MapLevel are great additions to the functionality, and a good rewrite, overall.

Thanks for your comment rcollyer. I took it into account and improved also the readability of the code. I keep FinalFunction because it operates on the result of Reap, for example if you want to sort your final result by tags if you keep them.

resources - What is in your Mathematica tool bag? - Stack Overflow

resources wolfram-mathematica
Rectangle 27 89

Returning the new object fits with the REST principle of "Uniform Interface - Manipulation of resources through representations." The complete object is the representation of the new state of the object that was created.

To prevent an API consumer from having to hit the API again for an updated representation, have the API return the updated (or created) representation as part of the response.

Seems nicely pragmatic to me and it fits in with that REST principle I mentioned above.

how about returning the entire set of relevant objects? this way, possible sorting can be done server-side, and it eases front-end implementation

rest - 'Best' practice for restful POST response - Stack Overflow

rest angularjs angularjs-resource
Rectangle 27 3

Google search results have returned a few useful resources that answer your problem.

The first option would be to include your python version in the file you wish to execute using something along the lines of

To execute in Python 2, or

For running the code in your Python 3 version. Then you would simply use "python yourscript.py" and the python version would be specified by the Python script.

Note: Hashbang (#!) is ignored on Windows. You can't use it switch Python versions (but it's still a good idea to show which version you expect).

Not that I'm aware of. You can install MinWG to get a unix-like environment but it's just an emulation and you'll notice a few oddities. Maybe ask a new question?

The Shebang (#!) works if you use the py launcher.

windows - Using multiple versions of Python - Stack Overflow

python windows python-2.7 python-3.x
Rectangle 27 213

Thanks to a huge amount of valuable sources I've got some general recommendations for implementing components in AngularJS apps:

Treat scope as read-only in templates and write-only in controllers. The purpose of the scope is to refer to model, not to be the model.

When doing bidirectional binding (ng-model) make sure you don't bind directly to the scope properties.

Model in AngularJS is a singleton defined by service.

Model provides an excellent way to separate data and display.

Models are prime candidates for unit testing, as they typically have exactly one dependency (some form of event emitter, in common case the $rootScope) and contain highly testable domain logic.

As model should encapsulate some logic in terms of data and state, it should architecturally restrict access to its members thus we can guarantee loose coupling.

The way to do it in AngularJS application is to define it using factory service type. This will allow us to define private properties and methods very easy and also return publically accessible ones in single place that will make it really readable for developer.

angular.module('search')
.factory( 'searchModel', ['searchResource', function (searchResource) {

  var itemsPerPage = 10,
  currentPage = 1,
  totalPages = 0,
  allLoaded = false,
  searchQuery;

  function init(params) {
    itemsPerPage = params.itemsPerPage || itemsPerPage;
    searchQuery = params.substring || searchQuery;
  }

  function findItems(page, queryParams) {
    searchQuery = queryParams.substring || searchQuery;

    return searchResource.fetch(searchQuery, page, itemsPerPage).then( function (results) {
      totalPages = results.totalPages;
      currentPage = results.currentPage;
      allLoaded = totalPages <= currentPage;

      return results.list
    });
  }

  function findNext() {
    return findItems(currentPage + 1);
  }

  function isAllLoaded() {
    return allLoaded;
  }

  // return public model API  
  return {
    /**
     * @param {Object} params
     */
    init: init,

    /**
     * @param {Number} page
     * @param {Object} queryParams
     * @return {Object} promise
     */
    find: findItems,

    /**
     * @return {Boolean}
     */
    allLoaded: isAllLoaded,

    /**
     * @return {Object} promise
     */
    findNext: findNext
  };
});

Try to avoid having a factory that returns a new able function as this begins to break down dependency injection and the library will behave awkwardly, especially for third parties.

A better way to accomplish the same thing is to use the factory as an API to return a collection of objects with getter and setter methods attached to them.

angular.module('car')
 .factory( 'carModel', ['carResource', function (carResource) {

  function Car(data) {
    angular.extend(this, data);
  }

  Car.prototype = {
    save: function () {
      // TODO: strip irrelevant fields
      var carData = //...
      return carResource.save(carData);
    }
  };

  function getCarById ( id ) {
    return carResource.getById(id).then(function (data) {
      return new Car(data);
    });
  }

  // the public API
  return {
    // ...
    findById: getCarById
    // ...
  };
});

In general try to avoid such situations and design your models properly thus it can be injected into controller and used in your view.

In particular case some methods require global accessibility within application. To make it possible you can define common property in $rootScope and bind it to commonModel during application bootstrap:

angular.module('app', ['app.common'])
.config(...)
.run(['$rootScope', 'commonModel', function ($rootScope, commonModel) {
  $rootScope.common = 'commonModel';
}]);

But do not define any methods directly in your $rootScope. This can lead to unexpected behavior when used with ngModel directive within your view scope, generally littering your scope and leads to scope methods overriding issues.

Resources are injected in models and provide possibility to send/retrieve data.

A factory which creates a resource object that lets you interact with RESTful server-side data sources.

The returned resource object has action methods which provide high-level behaviors without the need to interact with the low level $http service.

Both model and resource are services

Services are unassociated, loosely coupled units of functionality that are self-contained.

Services are a feature that Angular brings to client-side web apps from the server side, where services have been commonly used for a long time.

Services in Angular apps are substitutable objects that are wired together using dependency injection.

Angular comes with different types of services. Each one with its own use cases. Please read Understanding Service Types for details.

A service is an abstract resource that represents a capability of performing tasks that form a coherent functionality from the point of view of providers entities and requesters entities. To be used, a service must be realized by a concrete provider agent.

In general client side of the application is splitted into modules. Each module should be testable as a unit.

It is also much easier for developers to find some parts of code and all its dependencies.

An example of folders structuring

|-- src/
|   |-- app/
|   |   |-- app.js
|   |   |-- home/
|   |   |   |-- home.js
|   |   |   |-- homeCtrl.js
|   |   |   |-- home.spec.js
|   |   |   |-- home.tpl.html
|   |   |   |-- home.less
|   |   |-- user/
|   |   |   |-- user.js
|   |   |   |-- userCtrl.js
|   |   |   |-- userModel.js
|   |   |   |-- userResource.js
|   |   |   |-- user.spec.js
|   |   |   |-- user.tpl.html
|   |   |   |-- user.less
|   |   |   |-- create/
|   |   |   |   |-- create.js
|   |   |   |   |-- createCtrl.js
|   |   |   |   |-- create.tpl.html
|   |-- common/
|   |   |-- authentication/
|   |   |   |-- authentication.js
|   |   |   |-- authenticationModel.js
|   |   |   |-- authenticationService.js
|   |-- assets/
|   |   |-- images/
|   |   |   |-- logo.png
|   |   |   |-- user/
|   |   |   |   |-- user-icon.png
|   |   |   |   |-- user-default-avatar.png
|   |-- index.html

I have a one concern about: "It is highly recommended to avoid business logic in controller. It should be moved to model." However from official documentation you can read: "In general, a Controller shouldn't try to do too much. It should contain only the business logic needed for a single view.". Are we talking about the same thing?

I would say - treat Controller as View Model.

+1. Some great advices here! 2. Unfortunately the example of searchModel doesn't follow the re-usability advice. It would be better the import the constants via the constant service. 3. Any explanation what is meant here?: Try to avoid having a factory that returns a new able function

Also overwriting object's prototype property breaks the inheritance, instead one can use Car.prototype.save = ...

@ChristianAichinger, this is about the nature of JavaScript prototype chain that forces you either to use an object in your two-way binding expression to make sure you write to the exact property or setter function. In case of using the direct property of your scope (without a dot) you have a risk to hide the desired target property with the newly created one in the nearest upper scope in the prototype chain when writing to it. This is better explained in Misko's presentation

javascript - AngularJS: Understanding design pattern - Stack Overflow

javascript angularjs design-patterns architecture client-side
Rectangle 27 5

I think it's better to use ng-if. ng-show creates an element in the dom and sets it's display:none. The more dom elements you have the more resource hungry your app becomes, and on devices with lower resources the less dom elements the better.

TBH <span ng-if="!$last">, </span> seems like a great way to do it. It's simple.

I like this approach, as it's simple and still supports html based separators. Thanks @the7erm!

Using comma as list separator with AngularJS - Stack Overflow

angularjs angularjs-ng-repeat