How to check how many threads node.js is using on Linux?

We all know Node is single threaded, however, it's single threaded for a client (to you as a programmer), but the platform itself is multi-threaded (internally). In order to check how many threads your node is using on Linux machine you have 3 different options:

1.
cat /proc/`pidof node`/status | grep Threads

2.
ls /proc/19899/task/ | wc -l

3.
ps hH p `pidof node` | wc -l


Sometimes, it come in handy when you want to automate the load monitoring for example.

What If you want to to determine whether is 64bit or 32bit node executable installed?

You can try 3 following options:

1) Run node cli and type there:
require('os').arch()

3) Or type there:
process.arch

3) Or type there:
process.env.PROCESSOR_ARCHITECTURE


One of them will work for sure! (The latest one doesn't work on my Macbook but does on Win10 machine)

Mongoose 4.0.2 doesn't create indexes

Mongoose 4.0.2 doesn't create indexes automatically for some reason despite of its docs.
So I've found if you add {autoIndex: true} as it's shown bellow, it solves the issue.


var path = require('path');

module.exports = function (mongoose) {
    var Schema = new mongoose.Schema({
        name: {type: String, trim: true, required: true},
        uuid: {type: String, required: true, unique: true, index: true},
        device: {type: mongoose.Schema.Types.Mixed},
        updated_at: {type: Date, default: Date.now}
    }, {autoIndex: true});
    return mongoose.model(path.basename(module.filename, '.js'), Schema);
};

How JSONP works

JSONP is really a simple trick to overcome the XMLHttpRequest same domain policy. (As you know one cannot send AJAX (XMLHttpRequest) request to a different domain.)

So — instead of using XMLHttpRequest we have to use script HTML tags, the ones you usually use to load js files, in order for js to get data from another domain. Sounds weird?

Thing is — turns out script tags can be used in a fashion similar to XMLHttpRequest! Check this out:
script = document.createElement('script');
script.type = 'text/javascript';
script.src = 'http://www.someWebApiServer.com/some-data';


You will end up with a script segment that looks like this after it loads the data:
<script>
   {['some string 1', 'some data', 'whatever data']}
</script>


However this is a bit inconvenient, because we have to fetch this array from script tag. So JSONP creators decided that this will work better(and it is):

script = document.createElement('script');
script.type = 'text/javascript';
script.src = 'http://www.someWebApiServer.com/some-data?callback=my_callback';


Notice the my_callback function over there? So — when JSONP server receives your request and finds callback parameter — instead of returning plain js array it'll return this:
my_callback({['some string 1', 'some data', 'whatever data']});


See where the profit is: now we get automatic callback (my_callback) that'll be triggered once we get the data.
That's all there is to know about JSONP: it's a callback and script tags.

NOTE: these are simple examples of JSONP usage, these are not production ready scripts.

Basic JavaScript example (simple Twitter feed using JSONP)
<html>
    <head>
    </head>
    <body>
        <div id = 'twitterFeed'></div>
        <script>
        function myCallback(dataWeGotViaJsonp){
            var text = '';
            var len = dataWeGotViaJsonp.length;
            for(var i=0;i<len;i++){
                twitterEntry = dataWeGotViaJsonp[i];
                text += '<p><img src = "' + twitterEntry.user.profile_image_url_https +'"/>' + twitterEntry['text'] + '</p>'
            }
            document.getElementById('twitterFeed').innerHTML = text;
        }
        </script>
        <script type="text/javascript" src="http://twitter.com/status/user_timeline/padraicb.json?count=10&callback=myCallback"></script>
    </body>
</html>


Basic jQuery example (simple Twitter feed using JSONP)

<html>
    <head>
        <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
        <script>
            $(document).ready(function(){
                $.ajax({
                    url: 'http://twitter.com/status/user_timeline/padraicb.json?count=10',
                    dataType: 'jsonp',
                    success: function(dataWeGotViaJsonp){
                        var text = '';
                        var len = dataWeGotViaJsonp.length;
                        for(var i=0;i<len;i++){
                            twitterEntry = dataWeGotViaJsonp[i];
                            text += '<p><img src = "' + twitterEntry.user.profile_image_url_https +'"/>' + twitterEntry['text'] + '</p>'
                        }
                        $('#twitterFeed').html(text);
                    }
                });
            })
        </script>
    </head>
    <body>
        <div id = 'twitterFeed'></div>
    </body>
</html>

JSONP stands for JSON with Padding.

© ThatGuy

The "open with" context menu shows twice the same item fix

If you get something like:



The following command could help this issue, just copy paste this whole line into your terminal

/System/Library/Frameworks/CoreServices.framework/Frameworks/LaunchServices.framework/Support/lsregister -kill -r -all s,l,u; killall Finder

Really crazy Javascript's Fibonacci implementation

Run it in console and see it's really working :)


  var fib = function (_) {
      for(_=[+[],++[[]][+[]],+[],_],_[++[++[++[[]][+[]]][+[]]][+[]]]=(((_[++[++[++[[]][+[]]][+[]]][+[]]]-(++[[]][+[]]))&(((--[[]][+[]])>>>(++[[]][+[]]))))===(_[++[++[++[[]][+[]]][+[]]][+[]]]-(++[[]][+[]])))?(_[++[++[[]][+[]]][+[]]]=++[[]][+[]],_[++[++[++[[]][+[]]][+[]]][+[]]]-(++[[]][+[]])):+[];_[++[++[++[[]][+[]]][+[]]][+[]]]--;_[+[]]=(_[++[[]][+[]]]=_[++[++[[]][+[]]][+[]]]=_[+[]]+_[++[[]][+[]]])-_[+[]]);
      return _[++[++[[]][+[]]][+[]]];
  }

  console.assert(fib(-1) === 0);
  console.assert(fib(0) === 0);
  console.assert(fib(1) === 1);
  console.assert(fib(2) === 1);
  console.assert(fib(3) === 2);
  console.assert(fib(4) === 3);
  console.assert(fib(5) === 5);
  console.assert(fib(6) === 8);
  console.assert(fib(7) === 13);
  console.assert(fib(32) === 2178309);
  console.assert(fib(46) === 1836311903);
  console.assert(fib(47) === 2971215073);
  console.assert(fib(63) === 6557470319842);

  console.log('done!');


More could be found at: wtfsjs

Twisted logic: understanding truthy and falsy

An upcoming article I'll be doing for Smashing Magazine will look at the oddities and gotchas of Javascript — and lordie does it have a few.

One of these is the concept of truthy and falsy. These are sort of like true/false-lite, which will anger you somewhat if you majored in logic or philosophy. You mean you didn't know true and false were in fact gradable, not absolute concepts!?

In Javascript, every value has an in-built flag denoting its boolean equivalent. This is called upon when you ask the value to behave like a boolean, e.g. by comparing it to a real boolean. Javascript coerces your value into a boolean, such that the comparison is possible (after all, you can't compare apples with pears). See below for more on data coercion. So:

var someVar = 0;
alert(someVar == false); //evaluates true

Since we are attempting to compare zero to a boolean, Javascript coerces the zero to its truthy/falsy equivalent — and zero is a falsy (along with null, undefined, NaN, empty strings and false — everything else is a truthy). So the expression effectively becomes:

alert(false == false); //evaluates true, of course


It's important to realise that this does not mean your value is a boolean — it simply means Javascript temporarily converts it to a boolean to make the comparison possible. If we did the same comparison with the === operator (which compares not only by value but also by type), the result would be different:

alert(someVar === false); //evaluates false - someVar is a number, not a legitimate boolean


It gets worse

Clear enough? It gets more complex.

A well known quirk of Javascript is that an empty array appears to be equal to false.


( Read more )

Have you ever wondered how does look the computation of Fibonnaci number in assembly?

Have you ever wondered how does look the computation of Fibonnaci number in assembly?

For sake of curiosity I chose Pep/8 Assembler and Simulator which could be found on http://code.google.com

The original C uncached version looks as following:


#include <iostream>
using namespace std;
int fib (int n)
{
    if (n == 0)
    {
        return 0; 
    }
    else if (n == 1)
    {
        return 1;
    }
    else
    {
       return fib (n - 1) + fib (n - 2);
    }
}
int main ()
{
    int num;
    cout << "Which Fibonacci number? ";
    cin >> num;
    cout << "The number is " << fib (num) << endl; 
    return 0;
}


The Pep/8 implementation:


( Read more )

Properties vs Attributes

A DOM element is an object, a thing in memory. Like most objects in OOP, it has properties. It also, separately, has a map of the attributes defined on the element (usually coming from the markup that the browser read to create the element). Some of the element's properties get their initial values from attributes with the same or similar names (value gets its initial value from the «value» attribute; href gets its initial value from the «href» attribute, but it's not exactly the same value; className from the «class» attribute). Other properties get their initial values in other ways: For instance, the parentNode property gets its value based on what its parent element is; an element always has a style property, whether it has a «style» attribute or not.

Let's consider this anchor in a page at example.com/testing.html:

<a href='foo.html' class='test one' name='fooAnchor' id='fooAnchor'>Hi</a>

Some gratuitous ASCII art (and leaving out a lot of stuff):

+-------------------------------------------+
| a                                         |
+-------------------------------------------+
| href:       "http://example.com/foo.html" |
| name:       "fooAnchor"                   |
| id:         "fooAnchor"                   |
| className:  "test one"                    |
| attributes:                               |
|    href:  "foo.html"                      |
|    name:  "fooAnchor"                     |
|    id:    "fooAnchor"                     |
|    class: "test one"                      |
+-------------------------------------------+

Note that the properties and attributes are distinct.

Now, although they are distinct, because all of this evolved rather than being designed from the ground up, a number of properties write back to the attribute they derived from if you set them. But not all do, and as you can see from href above, the mapping is not always a straight «pass the value on», sometimes there's interpretation involved.

When I talk about properties being properties of an object, I'm not speaking in the abstract. Here's some non-jQuery code:

var link = document.getElementById('fooAnchor');
alert(link.href);                 // alerts "http://example.com/foo.html"
alert(link.getAttribute("href")); // alerts "foo.html"

(Those values are as per most browsers; there's some variation.)

The link object is a real thing, and you can see there's a real distinction between accessing a property on it, and accessing an attribute.

The vast majority of the time, we want to be working with properties. Partially that's because their values (even their names) tend to be more consistent across browsers. We mostly only want to work with attributes when there is no property related to it (custom attributes), or when we know that for that particular attribute, the attribute and the property are not 1:1 (as with href and «href» above).

The standard properties are laid out in the various DOM specs:

DOM2 HTML
DOM2 Core
DOM3 Core

These specs have excellent indexes and I recommend keeping links to them handy; I use them all the time.

Custom attributes would include, for instance, any data-xyz attributes you might put on elements to provide meta-data to your code (now that that's valid as of HTML5, as long as you stick to the data- prefix). (Recent versions of jQuery give you access to data-xyz elements via the data function, but that function does more than that and if you're just dealing with a data-xyz attribute, I'd actually use the attr function to interact with it.)

The attr function used to have some convoluted logic around getting what they thought you wanted, rather than literally getting the attribute. It conflated the concepts. Moving to prop and attr is meant to de-conflate them. There will be some brief confusion, but hopefully a better understanding of what's really going on going forward.

Via (stackoverflow)

Add "Recent Applications" icon to the dock, and disable windows animation

1) To add Recent Applications icon to the dock, open Terminal and copy paste following:

defaults write com.apple.dock persistent-others -array-add '{ "tile-data" = { "list-type" = 1; }; "tile-type" = "recents-tile"; }' && killall Dock


Don't forget to check recent Items settings in System Preferences>General

2) To disable windows animation, open Terminal and copy paste following:
defaults write NSGlobalDomain NSAutomaticWindowAnimationsEnabled -bool NO