802Objects and Key Array Length in Javascript

With arrays is trivial to get the length, with objects, the situations is slightly different. One approach would be to get all the keys and get the length of that array:

Object.keys(myObject).length;

More details at Stackoverflow. This functionality is part of EMCAScript 5 specs.

800Enabling root in OS X 10.7 (or 10.6)

sudo passwd root

After which you are prompted with a

Changing password for root.
New password:

Why the need for root? Surely, it's a dangerous weapon and things can go awry easily, so only use it as a last resort. (I used it for hiding the couchdb account folder from the GUI.)

791Combining stderr and stdout 2>&1

If you ever find yourself in a situation of having to call a perl script from within PHP, and you want to get the return values from the perl script, you might do it like the following:

$command = "perl /my/perl/script.pl";
$results = exec($command);
// does not print error

If the perl script generates error, you won't be able to see them, as they are written to stderr.

One solution might be to append the stderr to stdout, therefore getting it into the $results variable.

$command = "perl /my/perl/script.pl 2>&1";
$results = exec($command);
// Prints: Died at /my/perl/script.pl line 25.

As this post explains, 1 means stdout, 2 means stderr. 2>1 might look ok at first sight, but the '1' will be interpreted as a filename. Therefore it has to be escaped with &1, resulting in 2>&1.

785Filtering Arrays with ECMAScript 5 and filter()

Suppose you have an array of object:

var array = [   {a:13, b:false },
        {a:7, b:true },
        {a:78, b:true } ]       

The old, ECMAScript 3 way of checking for objects, in which b is true would be a simple for-loop:

var results = [];
for (var i=0; i

Ok, that's working, but not very elegant nor concise. Luckily, ECMAScript 5 offers a nicer way:

var results = array.filter( function(item) {
    return item.b;      // if item.b is true
});

779Sums and NaNs in Javascript

var array = [132, 32, 14, 525, 52, 12, 52];
var sum;
for (var i=0; i

I was slightly puzzled, why the above code outputs Nan instead of the consecutive sums of the array.

var array = [132, 32, 14, 525, 52, 12, 52];
var sum = 0; // sum needs to be init...?
for (var i=0; i

After declaring sum with a number, it works. Still have to find out why.

770Typekit and HTTPS

Just a quick reminder for myself.

Serving Typekit fonts to https sites only works with the Performance Price Plans.

764WordPress and Numbers as Page Slugs

If your are using Wordpress you might have run into the following situation. Let's say the main usage of this particular Wordpress installation is not so much blogging (articles), but as light-weight CMS (pages). Wordpress' Page and Subpage system works quite well in this respect, but I am no happy with one thing: Numbers as Page Slugs.

While it's possible to create a new page, name it with a number "2012", the page slug automatically turns to 2012-2. Manually editing the page slug back to "2012" and publishing it should solve that. Unfortunately not. Back to "2012-2".

In most cases, when the page slug is not a number, the presence of a "-2" and the end of the slug suggests, that the page already exists in the database. Make sure it's not in the Trash, empty the trash, if it is.

trembl.org/2012/

It does not seem to be a huge problem, because even when the page slug is "2012-2" and you ask for a page named trembl.org/2012/, Wordpress will happily forward (redirect?) you to trembl.org/2012-2/. So... Working: Yes? Nice solution: No!.

No other choice than to have a look at the MySQL itself. If you are not comfortable doing it on the CL, have a look at phpMyAdmin. Actually, if you are not comfortable editing MySQL, don't do it at all. Messing up the MySQL will mess up you Wordpress installation! And I assume you have a recent backup.

So, with that out of the way, open your Wordpress MySQL DB in phpMyAdmin. The wp_posts table holds all your posts, pages, as well as all the revisions to them. Look for the one you want to edit, in this case "2012-2". Open the entry for editing (the small crayon on the left). You'll want to edit "post_name". Change it to whatever you live ("2012"), save (it's called "Go") and you're done.

Wordpress Version: 3.1.3

759Creating soft symbolic links between two directories

ln -s /path/to/existing/directory /path/to/new/symbolic/link

After that, a

cd /path/to/new/symbolic/link

brings you to

/path/to/existing/directory

Sometimes a little magic is necessary.

Symbolic link can be removed with a simple 'rm'. This only removes the symbolic link, and not the linked files.

rm /path/to/new/symbolic/link

749Javascript, Array and For-Loops

Ok, looping over an array is something that we do all the time, for most of us it has become a second nature.

var myArray = ["a", "b", "c", "z"];

for (int i=0; i

But I recently came across a Javascript loop that puzzled me slightly.

var myArray = ["a", "b", "c", "z"];

for (var i=0,f ; f=myArray[ i++]; ) {
    console.log(f);
}

Let's have a closer look what's happening here. As a reminder, For-statements have the following structure: for (initiation; condition; increment) { block }

In the initiation, variables are initiated; Condition tests this var, and if it returns true, continues another loop; and here's something funny; the increment is left blank. Don't panic, because we are already incrementing i at the condition test.

This is equivalent:

var myArray = ["a", "b", "c", "z"];

for (var i=0,f ; f=myArray[ i]; i++) {
    console.log(f);
}

This, however, is not the same:

var myArray = ["a", "b", "c", "z"];

for (var i=0,f ; f=myArray[ ++i]; ) {
    console.log(f);
}

i gets incremented before it is used to traverse myArray, therefor resulting in this output:

b
c
z

In nice and simple arrays like in this example, it should not make any difference to test the array length at every time coming around, but a larger ones it might be beneficial.

As usual, take care that the array does not contain any falsy objects. And don't loop an object that way.

Thanks to the Re-introduction to Javascript https://developer.mozilla.org/en/a_re-introduction_to_javascript for clarifying that issue for me.

Update

Turns out things are not so clear after all. Let's consider the following case: I have an array of numbers, I'd like to get the sum of all numbers in the array. One way to do it:

var myArray = [1,2,3,5,7];
for (var i=0, sum=0; i

So, shouldn't this work too...?

var myArray = [1,2,3,5,7];
for (var i=0, sum=0; sum = myArray[i]; i++) {};
console.log(sum);       // undefined

Apparently not... I am trying to find out why not.

This, on the other hand works:

for (var i=0, sum=0; this[i]; sum+=this[i++]){};

737Processing Math convenience methods in pure Javascript

Like everybody else, I am huge fan of Processing, and like everybody else I find myself working more and more with Javascript.

There is a implementation port of Processing (aptly called ProcessingJS) by John Resig of jQuery fame. It's still lacking the 3D features, but not because they would be hard to implement in JS, but rather the OpenGL bindings in the browsers don't exists wide-spreadly (yet). Let's hope WebGL is going to change that soon.

After working a lot with Processing, one becomes quite spoilt with it's methods. The two best kept secrets of Processing are on the one hand the matrix state operations - pushMatrix(), and popMatrix() - and on the other hand the very handy map() method, basically mapping a number from one range to another.

In Javascript's canvas you have the pushMatrix() popMatrix() equivalents as save() and restore(). The map() methods does not exists as such, but it is easy implemented. I took a look at the Processing source and rewrote the Java methods in Javascript.

var p5 = {};

p5.sq = function(a) {
    return a*a;
}

p5.constrain = function(amt, low, high) {
  return (amt < low) ? low : ((amt > high) ? high : amt);
}

p5.degrees = function(radians) {
  return radians * (180/Math.PI);
}

p5.mag = function(a, b) {
  return Math.sqrt(a*a + b*b);
}

p5.dist = function(x1, y1, x2, y2) {
  return Math.sqrt(p5.sq(x2-x1) + p5.sq(y2-y1));
}

p5.lerp = function(start, stop, amt) {
  return start + (stop-start) * amt;
}

p5.norm = function(value, start, stop) {
  return (value - start) / (stop - start);
}

p5.map = function (value, istart, istop, ostart, ostop) {
    return ostart + (ostop - ostart) * ((value - istart) / (istop - istart));
}

The code including comments and a minified version is also up on GitHub, show you love and fork it. https://github.com/trembl/p5.Math.js/

Update - Extending Math

Rather than creating a dedicated object, and as all the function are kind of related to Math, I thought it would be a good idea to extend the Math object itself. (Well, it's a good idea for my project - your mileage, especially if you are flying with a lot of libraries might vary).

And how to you extend a Javascript build-in object? With prototype, right?

Math.prototpe.sq = function(a) {
    return a*a;
}

Wrong. Because Math does not have a constructor, it therefore hasn't been constructed and therefore does not have the prototype method. It has been instantiated and you add methods (or functions?) like this:

Math.sq = function(a) {
    return a*a;
}

You get the idea. The new code also lives at GitHub, check it out. https://github.com/trembl/p5.Math.js/