Javascript Boolean and Array – oh my!

<html>
<script type=text/javascript>
document.write("Never use new Boolean.<br>");
var b = new Boolean("false");
if (b) {
  document.write("new Boolean is an Object and it's always true.<br>");
}

var oh_my_god = new Boolean(false)
if (oh_my_god) {
  document.write("I told you. Object is true!<br>");
}

document.write("Also, stay away from new Array. Use [].<br>");
function PrintArray(ar) {
  for (var i = 0; i < ar.length; ++i) {
    document.write(ar[i]);
  }
  document.write("<br>");
}

document.write("See. new Array is confusing.<br>");
PrintArray(new Array(10));
PrintArray(new Array(10, 20));

document.write("[elem1, elem2, ...] is obvious.<br>");
PrintArray([10]);
PrintArray([10, 20]);

</script>
</html>

Output:
Never use new Boolean.
new Boolean is an Object and it’s always true.
I told you. Object is true!
Also, stay away from new Array. Use [].
See. new Array is confusing.
undefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefined
1020
[elem1, elem2, ...] is obvious.
10
1020

Simlar Posts:

Google Javascript style guide

Google Javascript style guide

Simlar Posts:

Javascript string and number

“3″ + 1 : “31″
1 + “3″ : “13″

But,
“3″-1 : 2
“4″ / 2 : 2
“2″ * 2 : 4
“2″ * “2″: 4

Simlar Posts:

Consistent Hashing

http://en.wikipedia.org/wiki/Consistent_hashing

A hash scheme that does not affects the entire hash table when a node is inserted or deleted. Machines are assigned to the circular nodes, and if a machine crashes, the keys in the crashed machine are moved to the following node in the circle. This is becoming really popular due to no SQL movements.

Used by distributed hash table (This is basically consistent hashing + node lookup algorithm) or amazon dynamo.

Simlar Posts:

Gossip Protocol

http://en.wikipedia.org/wiki/Gossip_protocol

Pairewise periodic comm. based protocol to spread information which resembles the way how gossip spreads among ppl. This protocol assumes a faulty network and decentralized. Epidemic algorithms are the ones that adopt gossip protocol.

Simple algorithm w/ cute name.

Simlar Posts:

Hash Teee(Merkle Tree)

http://en.wikipedia.org/wiki/Hash_tree

A tree where a parent contains hash of it’s children. Likewise, root has hash of all nodes. Useful for contents comparison without downloading entire tree or files. Also useful for file synchronization(e.g., Amazon Dynamo); detect missing files easily and sync.

Simlar Posts:

Interpolation search – beating the binary search

http://sna-projects.com/blog/2010/06/beating-binary-search/

Instead of just picking the middle, guess the position where the target value appears, and compares the value in the position with the target. This obtains O(loglogN).

Simlar Posts:

simhash (minhash)

Near duplicate documents 를 찾는 식 중에 Jaccard coefficient라는 것이 있습니다. 어떤 문서내 term id들이 T(d)로 정의된다고 하면, Jaccard coefficient는 (T(d_1) \cap T(d_2)) / (T(d_1) \cup T(d_2)) 로 정의됩니다. 즉 term이 몇개나 겹치나하는 것이죠.

이런 term의 겹침을 계산하는 방법 중 하나는 locality sensitive hashiing입니다. 위키의 식 중 하나를 인용해서 설명하면 Pr(h(a)=h(b)) = \phi(a,b) 가 localitiy sensitive hashing입니다. 즉, 어떤 해싱 함수를 써서 a와 b를 변환한다음 그 값이 같을 확률은 a와 b의 유사도와 같다라는 것입니다.

여기까지가 introduction이고 본문은 http://knol.google.com/k/simple-simhashing에 있습니다. 혹은 Soumen Chakrabarti, Mining the web, Morgan Kaufmann에도 설명되어있습니다. (좋은 책입니다.)

knol의 글에서는 여러번반복해서 ((T(d_1) \cap T(d_2)) / (T(d_1) \cup T(d_2)))^n을 구한다고 되어있는데, Mining the web에서는 m개의 hash function을 찾은다음 그 중에서 k회 h(a)=h(b)가 성립하면 \phi(a,b)=k/m으로 계산하고 있습니다.

Simlar Posts:

Never, ever, swallow your stack trace.

I came across this kind of exception handling code.

import java.util.Observable;
import java.util.Observer;

public class Framework extends Observable {

  public void SendMessage(String msg) {
    setChanged();
    try {
      notifyObservers(msg);
    } catch (RuntimeException re) {
      throw new RuntimeException("Something bad happend.");
    }
  }

  public static void main(String[] args) {
    Framework f = new Framework();
    f.addObserver(new Observer() {
      @Override
      public void update(Observable o, Object arg) {
        System.out.println("I am fine: " + arg.toString());
      }
    });
    f.SendMessage("hello world");
  }
}

This is pretty common pattern. Right? You create a list of several instances and iterate over them to do something. Actually, that’s the beautiful pattern commonly used.

But, the code actually has a pitfall. Look at the error handling part. Can you identify it?

try {
  notifyObservers(msg);
} catch(RuntimeException re) {
  throw new RuntimeException("Something bad happend.");
}

At first glance, this looks fine. It’s trying to tell something to the user. It’s not even swallowing the exception. But that’s not all for the framework developer. What happens if I add an innocent observer but got some error?

  public static void main(String[] args) {
    Framework f = new Framework();
    f.addObserver(new Observer() {
      @Override
      public void update(Observable o, Object arg) {
        System.out.println("I am fine: " + arg.toString());
      }
    });
    f.addObserver(new Observer() {
      @Override
      public void update(Observable o, Object arg) {
        throw new RuntimeException("I got an error: " + arg.toString());
      }
    });
    f.SendMessage("hello world");
  }

Now the code spits out this:

Exception in thread “main” java.lang.RuntimeException: Something bad happend.
at Framework.SendMessage(Framework.java:11)
at Framework.main(Framework.java:29)

Seriously, that’s all I get. If this happens, I’m left with no clue but something went wrong.

Please do not swallow not just your exception but also your stack trace. How can I believe that all other observers are fine but it’s just my fault without any proof?

Keep the stack trace:

try {
    notifyObservers(msg);
} catch (RuntimeException re) {
    throw new RuntimeException("Something bad happend.", re);
}

Now I get this awesome trace:

Exception in thread “main” java.lang.RuntimeException: Something bad happend.
at Framework.SendMessage(Framework.java:11)
at Framework.main(Framework.java:29)
Caused by: java.lang.RuntimeException: I got an error: hello world
at Framework$2.update(Framework.java:26)
at java.util.Observable.notifyObservers(Unknown Source)
at Framework.SendMessage(Framework.java:9)
… 1 more

Simlar Posts:

Broken javascript word counting code that irritates me

Based on the Javascript: The Good Parts by Douglas Crockford.
(I highly recommend this book to everyone.)

<script type='text/javascript'>
var s = "Constructor is a Constructor";
var word_cnt = {};
var words = s.toLowerCase().split(/ /);
var i;
for (i = 0; i < words.length; i++) {
  if (word_cnt[words[i]]) {
    word_cnt[words[i]] += 1;
  } else {
    word_cnt[words[i]] = 1;
  }
}

for (w in word_cnt) {
  document.write(w + ": " + word_cnt[w] + "<br>");
}
</script>

Output:
constructor: function Object() { [native code] }11
is: 1
a: 1

Reason:
Because you have ‘Constructor’ in your parent class (or prototype) of word_cnt!!!!!!
And that’s a string! So you add 1 to that string! and 1 is coerced to a string, thus the result is a string!
Sigh… Given that javascript is now really the future, this makes me want to cry.

Simlar Posts: