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

How to get md5 hash of files in current directory

The following command pretty useful when you need to get a md5 of specific files e.g. only video files in the current dir.

find * -iname '*.mp4' -exec md5 '{}' \; >output.txt


Does anybody know what '{}' \; means?

Removing dangling commits and those reachable from the reflogs

If you see something like that:
$ git fsck --lost-found
dangling commit 9dbd85d427b32773aee016efc7912f9d1c39aac4
dangling commit 604948146be1bdc2181962543cca039c18cc06b4


You might want to get rid of those dangling commits, in order to accomplish it, do following:
git reflog expire --expire=now --all #Dangerous command, it will be very difficult to recover stuff later on, if you execute it
git gc --prune=now

How to hide a folder in Finder

In order to hide a folder in Finder, open Terminal and write following:


setfile -a V /path/to/folder

Or

chflags hidden /path/to/folder


To unhide:


setfile -a v /path/to/folder

Or

chflags nohidden /path/to/folder

Installing Ruby & Rails & MySQL on Mac OS X Lion using Homebrew

1) install homebrew

$ ruby -e "$(/usr/bin/curl -fksSL https://raw.github.com/mxcl/homebrew/master/Library/Contributions/install_homebrew.rb)"

2) Install Xcode from App Store (4.3.2)

3) Install Command Line Tools for Xcode from https://developer.apple.com/downloads/index.action

4) Install MySQL

$ brew install mysql
$ unset TMPDIR
$ mysql_install_db --verbose --user="$(whoami)" --basedir="$(brew --prefix mysql)" --datadir=/usr/local/var/mysql --tmpdir=/tmp

By default, data files and the error log file ([HOSTNAME].err) will be located at:
/usr/local/var/mysql/

To start o stop the server:
$ mysql.server start
$ mysql.server stop

If you get «InnoDB: Operating system error number 13 in a file operation.» error when starting the server you forgot to run mysql_install_db.
«FATAL ERROR: Could not find ./bin/my_print_defaults» error means that you are trying to run mysql_install_db without all the --basedir option.
Optionally, we can place MySQL configuration file to /etc/my.cnf

5) Install git
$ brew install git

6) Install RVM

$ bash -s master < <(curl -s https://raw.github.com/wayneeseguin/rvm/master/binscripts/rvm-installer)

7) Install Ruby

rvm install ruby-1.9.3-p125

To use this version of ruby:
$ rvm use ruby-1.9.3-p125

To set it as default version:
$ rvm --default ruby-1.9.3-p125

We can verify that ruby-1.9.3-p125 was installed by running:
$ ruby -v

8) Install Rails:

gem install rails

Controlling fan speed on Macbook Air (handling noisy fan, by decreasing the fan speed)

Hello all!

Recently I've purchased Macbook Air mid 2011, I very like it so far.
However, I've noticed when I'm watching movies or YouTube videos, the fan is spinning really fast, iStats shows me something like about 6400 (!) RPM.
I've tried to use fan controlling apps like smcFanSpeed or Fan Control.
However, both of those apps doesn't allow you to decrease fan speed (probably it's designed that way in order not to burn the laptop in inexperienced user hands)

I'm kinda experienced user, so I took a risk and wrote simple script that allows you to set fan speed manually.
The instructions are pretty easy:
1) Download it setFanSpeed2011.tgz
2) Open the Terminal, go to folder where the file was downloaded
3) Extract it: tar xf setFanSpeed2011.tgz
4) Go to inside extracted folder: cd setFanSpeed2011
5) Run it: sudo ./setFanSpeed XXXX (Where XXXX should be needed RPM)

P.S. When I'm gaming or watching movies, I found that 3600 RPM work for me pretty well, the CPU stays on ~174F (~79C) temperature.
The same temperature as when fan was spinning at 6200 (!) RPM, but now it's not such noisy!
P.P.S Created and tested on OSX Lion 10.7.1

Disclaimer,
Note, I'm not taking any responsibilities if you will burn your laptop by using my tool! Decreasing the fan speed is very dangerous!
Since, if you don't watch the CPU temperature it might be overheated!

Finding Sophie

In this article we will discuss a solution to a software puzzle “Find Sophie”. The puzzle is a modification of the famous NP-hard “Traveling Salesman” problem.

Unfortunately many job interviews require software engineers to solve hard programing puzzles. The puzzles do not test abstract thinking, understanding, communication skills, reasoning, learning, planning, and problem solving. In short, it does not test any of those things that define intelligence (http://en.wikipedia.org/wiki/Intelligence).

Luckily, Microsoft is no longer the front runner of the software industry and majority of the companies stopped imitating Microsoft and do not as “Four People on a Bridge” type puzzles. It is fair to say that Google, Facebook, and Apple have taken Microsoft’s place as software industry leaders. So now every company wants to be the next Google or Facebook and, as a result, they ask the same questions that Google, Facebook, and Apple ask – algorithmic puzzles.
It is almost impossible to solve those puzzles without the knowledge of basic (and not so basic) algorithms. “Find Sophie” solution is based on graph theory algorithms so before we get into details we have to review some of them.

First, some useful terms:

Vertices are the circles in a graph and edges are the lines connecting the vertices. Big-O notation is used to quantify the running time of each algorithm. Graphs can also be conveniently described using a two-dimensional matrix that contains 1 if there is an edge connecting the two vertices and 0 otherwise. Weighted graphs have a number assigned to each edge. For weighted graphs, ones can be substituted with the non-zero weight of the edge. Trees are a subset of graphs – directed graphs. For trees, vertices are called nodes. Each node can have zero or more children (nodes that can be navigated to from the parent node).

Depth First Search
DFS Mostly used to traverse a tree, and it does so by going as deep as it can until it hits a node that has no children. Then it backtracks. Non-recursive implementations use a stack to keep track of the nodes traversed.
O(V + E)

Breadth First Search
BFS Instead of going into depth, like in DFS, we first explore all the branches (children) before backtracking. O(V + E)
Dijkstra's Used to find shortest paths in non-negative weighted graphs between a pair of vertices. A queue is frequently used to implement the algorithm. O(V^2) (basic implementation)

Floyd–Warshall
Used to find shortest paths in weighted graphs between all pairs of vertices. Unlike Dijkstra’s algorithm will also work for negative weights. Fails to calculate the shortest path if negative cycles exist.
O(V^3)

Prim's algorithm
Used to find a minimum spanning tree (a tree that connects all vertices together and has the minimum total weight) in a weighted undirected graph.
O(V^2)(basic implementation)

Now we are finally ready to explore the THE PUZZLE.

After a long day of coding, you love to head home and relax with a loved one. Since that whole relationship thing hasn't been working out for you recently that loved one will have to be your cat, Sophie. Unfortunately you find yourself spending considerable time after you arrive home just trying to find her. Being a perfectionist and unable to let anything suboptimal be a part of your daily life, you decide to devise the most efficient possible method for finding Sophie.
Luckily for you, Sophie is a creature of habit. You know where all of her hiding places are, as well as the probability of her hiding in each one. You also know how long it takes you to walk from hiding place to hiding place. Write a program to determine the minimum expected time it will take to find Sophie in your apartment. It is sufficient to simply visit a location to check if Sophie is hiding there; no time must be spent looking for her at a location. Sophie is hiding when you enter your apartment, and then will not leave that hiding place until you find her. Your program must take the name of an input file as an argument on the command line.

Input Specifications:
The input file starts with a single number, m, followed by a newline. m is the number of locations available for Sophie to hide in your apartment. This line is followed by m lines, each containing information for a single location of the form (brackets for clarity): where probability is the probability that Sophie is hiding in the location indicated. The sum of all the probabilities is always 1. The contents of these lines are separated by whitespace. Names will only contain alphanumeric characters and underscores ('_'), and there will be no duplicate names. All input is guaranteed to be well-formed. Your starting point is the first location to be listed, and in effect it costs you no time to check if Sophie is there.
The file continues with a single number, c, followed by a newline. c is the number of connections that exist between the various locations. This line is followed by c lines, each of the form: where first entry is the name of location and the second one is the number of seconds it takes you to walk between them. Again these lines are whitespace-delimited. Note that the locations are unordered; you can walk between them in either direction and it will take the same amount of time. No duplicate pairs will be included in the input file, and all location names will match one described earlier in the file.

Output Specifications
Your output must consist of a single number followed by a newline, printed to standard out. The number is the minimum expected time in seconds it takes to find Sophie, rounded to the nearest hundredth. Make sure that the number printed has exactly two digits after the decimal point (even if they are zeroes). If it is impossible to guarantee that you will find Sophie, print "-1.00" followed by a newline instead.

EXAMPLE:
It definitely looks like a graph problem but it is almost impossible to solve a problem like that without a good example:


In our example, Vertex A is the entrance to the apartment (the first possible hiding place of the cat). The probability that the cat is hiding there is 0.2. It takes 2 second for the guy to walk from A to B (another hiding place), and the probability of the cat being there is 0.3.
By definition, expectation, in a discrete case, is x1*p1 + x2*p2 + x3*p3 + … where x is the value with probability p. For example, expected value of finding Sophie if we go to location C and on the way pass location D is probability of cat being at location D multiplied by time it takes to reach location D plus probability of cat being at location C multiplied by time it takes to reach location C –> 0.4 * 5 + (5+9)*0.1 = 3.4.
We have to visit all vertices to find the expected value. In our example there are 6 possible paths.
ABCD, ABDC, ADCB, ADBC, ACBD, ACDB
Mathematically speaking, we want to rearrange 3 (BCD) different objects into a sequence. In discrete math, this is called n-factorial (3! = 3*2*1 = 6).
Now it might seem obvious that ADCB is a better choice than ABDC (via A) because going from B to D we have to come back to A but this is not correct. While for ADCB we have 5*0.4 + 0.1*14 + 20*0.3 = 9.4, For ABDC (via A), we have 2*0.3 + 9*0.4 + 18 *0.1 = 6. It is easier to represent all 6 paths as a tree.


If we calculate all six paths we will see that ABDC (via A) gives us the best expected value. So the algorithm that we used to solve this example does the following:
1) Find all permutations (ABCD, ABDC, ADCB, ADBC, ACBD, and ACDB).
2) For each permutation find shortest path for each pair of vertices on the path (for ABCD, find shortest path between AB, BC, and CD)
3) For each permutation calculate the expected value using the shortest paths.
4) Choose the minimum expected value
That is a good solution but it has a problem. Its time complexity is at least O(N!). So solving the problem for 20 nodes will be unrealistic (20! = 2432902008176640000). So we really need to find some optimization. And by looking at the tree we can see that we can easily disregard at least some of the paths without calculating the entire path. So if we start from the left, and calculate ABCD and then ABDC we know that current minimum expected value is 6 and there is no need to calculate ACDB because ACD already sums up to 6.1. While in case of 4 nodes the optimization is minimal, for 20 nodes this simple optimization will help us to disregard entire branches, transforming the solution from to O(N^3). Of course, the worst case is still O(N!) but let’s hope for the best.

SOLUTION:

Once we understand the example, it is easy to see the solution. For N hiding places, we construct a tree that has (N-1)! paths (each permutation is a path). For each path we calculate the shortest (in terms of expectation) path between every two vertices on the path and sum them up. This way we calculate the expected value of each path, and all we have to do now is to find the minimum one. And yes, as discussed above, we have to add some optimization to achieve a better average running time then O(N!).



( Read more )