A Simple Stop Watch / Timer using jQuery …

August 19th, 2010

I was just experimenting with jQuery Timers plug-in and came up with this simple timer in less than an hour.

Previously I worked with prototype and scriptaculous and haven’t done much java script this year – so it was fun to quickly read the jQuery docs and come up with some working code.

I have to say after working with a few frameworks like prototype / scriptaculous and dojo, I like jQuery better.

jQuery based Stop Watch / Timer

If you want to look at the code, you can just do a view source on the page to see the jQuery code – so I am not re-posting the java script code here again.

If you are interested in the details, most of the code is bookkeeping of the state and ‘presentation’ of the current timer state. I have wrapped around some of the important code with :
//*******************

Ciao!
Kiran

PE / .NET PE format(s) and a “Tiny PE” program

November 26th, 2009

While browsing for a quick read on the .NET PE format, I stumbled upon the article on Tiny PE : Creating the smallest possible PE executable. Your mileage from this article may vary because it goes deep into things that we do not necessarily need to know on a daily basis but take for granted in everything we do. (After all the sample program used in Tiny PE is nothing but a ‘hello world’ program but look at all that goes behind the scenes when you compile, link and run this simple program.)

Related links

Building and installing Google Go from the source on Linux/Ubuntu on x386 …

November 21st, 2009

The high-level steps in Installing Go from source are : Fetch source from repository , build the source, run tests.

The Google “Installing Go” page provides a sequence of steps that pretty much work just as expected. But, I hit 1 bug in the build process which was already reported. It has a quick workaround  (and is fixed on some platforms).

I will outline the steps I followed. I won’t go into too much detail because the Installing Go page does an excellent job at that. Why re-invent a new sub-standard wheel!

1) Make sure the current user is not ‘root’. So, if you are logged in as root, change to a non-root user before you build the sources. We will use the root priveleges, using sudo, only when necessary.

2) Set these variables in your .bashrc as below. For linux running on a Intel x386 box, you can use linux/386 for the GOOS/GOARCH combo. The GOROOT and GOBIN can be any valid directory. The latter defaults to $HOME/bin, if not specified.

export GOROOT=$HOME/go
export GOARCH=386
export GOOS=linux
export GOBIN=$HOME/gobin
 

3) Right below the above lines, add this line to your .bashrc to add $GOBIN to your path. This will be useful when you run the Go compiler, linker etc once you are done building from the Go source.

export PATH=$PATH:$GOBIN

4) Pick up the changes you added to your .bashrc and double check your environment that you have the latest updates:

$ env | grep '^GO'

You should see something like :

GOBIN=/home/kiranadmin/gobin
GOARCH=386
GOROOT=/home/kiranadmin/go
GOOS=linux

5) I’d suggest you make sure that $GOROOT and $GOBIN exist and are empty. Do an “ls” on them to confirm it.

If they are not already there, create them :

mkdir $GOROOT
mkdir $GOBIN

6) Fetch the repository.

If you have “hg” installed,  skip step (a).

a) We will install “hg” in this step.  I didn’t have “hg” installed and since I am using a brand-new-Ubuntu-box-with-nothing-much-on-it the following did the job for me:


sudo apt-get install python-setuptools python-dev
sudo apt-get install mercurial
s
udo apt-get install python-setuptools python-dev sudo apt-get install mercurial
At this point we have "hg" installed.

b) Now we’ll checkout the source:

$ hg clone -r release https://go.googlecode.com/hg/ $GOROOT

Do an “ls” on your $GOROOT to make sure that you now have the source.

7) Install Go

a) Get the Go tool chain (these are used to build the sources and create Go binaries)

$ sudo apt-get install bison gcc libc6-dev ed make

b) SHOW TIME! Now do the build :)

$ cd $GOROOT/src
$ ./all.bash

Assuming all goes well, depending on your machine speed,  you should see the following output in a few minutes.

The benchmark tests – I see Fasta and Mandelbrot! — that run after the Go binaries are built may take the most amount of time.

--- cd ../test
N known bugs; 0 unexpected bugs

where N is a number that varies from release to release.

For me, N == 1 (i.e., 1 known bug) on my Ubuntu box.

8) Now if you are at this point, be nice and run the ‘hello world’ program first.

First, create a file called hello.go with the following contents :

package main

import "fmt"

func main() {
	fmt.Printf("hello, world\n")
}

To compile, link and run on your 386 box, you will be using :

$ 8g hello.go
$ 8l hello.8
$ ./8.out
hello, world
$

If it says it can’t find 8g or 8l, check your PATH and ensure $GOBIN is on it! ( This should have happened in step (3)! )

9) Well folks, you now have Go installed and you are on your own now :)

Explore the resources on the Google Go home page and definitely listen to Rob Pike’s talk or read the corresponding PDF.

Let’s finish on a pontifical note :)

Hemingway – I think it was him! – said the only way to become  a good writer is by writing. Same goes with programming :  the only way to be a “good” programmer is by writing programs.

Cheers,

Kiran

p.s. Thanks for Google and Virgin America for providing complimentary in-flight wireless access during the holidays. This blog was written on my way from SFO to SAN. So any errors in my blog must be blamed on high altitude dizziness.

Ubuntu Karmic Koala here I came!

November 20th, 2009

Quick update : After a trial run on Ubuntu 9.10 on LiveCD for < 1 day, I found myself a happy Ubuntu “customer” and upgraded fully to Ubuntu on one of my older laptops.

So now I have a Linux laptop and 2 Windows ones. Hmm, I’d rather have 1 Linux, 1 Mac and 1 windows, which is not impossible to achieve ;)

Trying out Ubuntu 9.10 – Karmic Koala on LiveCD …

November 18th, 2009

Noted the other day that Google Go is only availabe at this time for Mac OS X and Linux, neither of which I have. So, I am in the process of converting my old DELL XP laptop into a Linux box. A friend suggested Ubuntu …

Before I install Ubuntu, I am just trying Ubunto 9.10 out from a LiveCD and I am surprised how easy it is to use it and get everything up and running. The first chance I get tomorrow I will raze the XP installation on this old DELL laptop and install Ubuntu. Can’t wait …

Oh, ofcourse I needed a Linux box for installing and trying out Google Go, so that is my primary goal anyway so look for updates on that front …

Cheers and YaWns!

Kiran

P.S. BTW, I opened firefox that is available on the Ubuntu LiveCD and wrote this blog. How’s that for a good out of box experience …

The Go Memory Model

November 15th, 2009

While reading about The Go Programming Language, I found some information on the Go Memory Model. This page describes the ‘happens-before‘ partially-ordered relation I briefly talked about in my JMM article.

So I went back to the JMM article and updated it so that it refers to the Go Memory Model page. This should give folks more information on what ‘happens-before‘ is.

Google Go!

November 15th, 2009

Planning to install Go and give it a test drive today.

The FAQ looks interesting. And Rob Pike’s talk is great. As with all talks, the speaker spends a lot more time on basic things initially (probably have to) and then it gets much steeper as it goes into the 2nd half.  I had to pause it a few times to get the details in the slides esp. as the talk had gone past the 30 minute point, it got a bit steeper to catch in real time in a few seconds.

The parts of Rob Pike’s talk that I liked the most  :

  • channels
  • the goroutines slide that describes a multiplexed server. Very interesting.
  • the ‘select‘ keyword – which seems a lot more general than what I am used to. In the continuation of the multiplexed server example, Rob shows how to use it to  ’select’ between different channels and in that particular example, if the request comes on the ‘quit’ channel, the server stops listening to requests by getting out of the loop. Neat!
  • the ‘chaining‘ example – to illustrate how to create and chain 100000  go routines. The chaining is done using the “channels” and domino mechanism is triggered when the go routine’s “left” channel gets input from the “right” channel. Once everything is  setup, the code triggers the “collapse” of the whole domino by putting some arbitrary value in the rightmost channel which gets picked up by a go routine, increments it and feeds the new value to the immediate left channel and so on. It’s pretty cool functionality with so little code. Elegant too.

I’ll post my experience with setting up the installation and writing/running a few good programs soon …

The Java Memory Model (JMM)

November 11th, 2009

It is not uncommon for someone to be pretty good at multi-threaded programming using Java but hasn’t really heard of The Java Memory Model (JMM).  Happily, the main reason this may have worked for you is because synchronization automatically triggers some safety nets beyond the good old ‘mutual exclusion’ we all desire in our critical sections.

As of this writing, there is no memory model for C or C++. I haven’t checked but there’s gotta be one for C#.

We will start with a quote from Java Concurrency in Practice .

“Locking is not just about mutual exclusion; it is also about memory visibility. “

Roughly speaking, it means that when you have a synchronized code block, not only are you guaranteed to have ‘thread safety’ but also, in association with the JMM, synchronization promises that any side-effects to the shared state (e.g. a static variable) in the synchronized block by a Thread T are visible to the next thread Thread T+1 that works with the same shared state.

This may sound trivial. After all, I wouldn’t expect  or accept anything else from my multi-threaded programs that I usually write during my breakfast routine.  Fair enough. So, let’s get into a few details.

Assume that the aforementioned Thread T is working with a cached copy of the static variable,  and assume that you have no synchronization or any other JMM safety net triggering mechanisms in place (we will get to these other mechanisms  later). You got lucky and Thread T was gifted with exclusive access (at least this time, anyway) to the static variable. Thread T ‘atomically’ updates the shared state and goes about on its way.

Enter Thread T+1 into the same section of code. It too got lucky and magically got mutual exclusive access to that section of the code. But alas, it may not see the Thread T updates done to the static variable. “How so?” you may ask.

For starters, and we’ll leave it there, it could be because Thread T running on processor P1 – ah! your wife is rich and you own a multi processor machine – might have been using a processor cache and someone didn’t think it necessary to reconcile the main memory with the latest value for the uniqueTransactionIDCounter static variable value. Instead, for now, that most up to date value is sitting in a cache (or a couch) watching re-runs of Seinfeld. In other words, it is not visible to the outside world, specifically, Thread T+1.

This is the memory visibility referred to in the quote above.

So synchronization, in some way, is the aspirin pill you take to definitely fix your (short-term) mutual exclusion et al headaches but it also wards-off any subtle (long-term) memory visibility myocardial infarctions.

To summarize, note that JMM :

-          is , in practice, only relevant in a multi-threaded program

-          is a set of ground rules about program semantics guaranteed at the language level, independent of the underlying operating system, # of processors, processor architectural elements (e.g. caches) and other execution-time parameters.

Of course, there are many other ways to get the guarantees of the JMM without having to use synchronization. Some of these are essential and are at play whether you are aware of it or not.

Without getting too formal (we will pay the price for it soon, as you will see), we will just list the 8 rules for memory visibility as mentioned in the Brian Goetz’s book . For now, we will informally use the terms ‘can see’, ‘is visible’, ‘memory visibility’ instead of the more exact terminology (the ‘happens-before’ partially-ordered relation) used in Brian’s book. (This Java happens-before relation is similar to the one described on the Google Go Memory Model page.)

The first one – Program Order Rule – is a gem. Really. We will put extra love into the first one so that you get the spirit of these 8 commandments. Just remember that if you trigger these rules, implicitly or explicitly, you get the memory visibility guarantees provided by JMM.

Program Order Rule – It just means that a thread’s actions will always be visible to its own subsequent actions.

Amuse me, if you haven’t already, while I expand on this gem. Without this rule, even a single threaded program does not yield the result of 101 consistently (in all Java runtime environments) when you print the value of i after the i = i+1 statement in the code fragment below:

i = 100

//…  ten intervening statements none of which modify i

i = i + 1                  //same variable i that was assigned 100

//print the value of i

What the Program Order Rule guarantees is that the thread definitely see the most up to date value (i.e., 100) of i just before it increments i’s value by 1. Of course, the thread at i = i + 1 also sees all the intervening statements ; it just does not need or use them at this particular statement that increments i.

Monitor Lock Rule : If a thread T1 released a lock and another thread T2 subsequently gets the same lock, then the unlock statement executed by T1 when it released the lock is visible to the lock statement executed by T2 when it got hold of the lock.  In fact, we can generalize this and say that, even the lock statements executed by other threads T3, T4, T5 etc on the same lock can ‘see’ the lock statement executed by T1.

The previous statement  is not 100% accurate. This is because without a precise mathematical terminology, like the partial-ordered relation ‘happens-before’ defined in Brian Goetz’s book, it gets tricky to cover all the bases using informal prose.

Volatile Variable Rule :

Here is the main gist of volatile:

Locking can guarantee both visibility and atomicity; volatile variables can only guarantee visibility.” (Java Concurrency in Practice )

Without going into the details I will quickly mention that one scenario where this comes into play if you implement Double-Checked Locking using a volatile.

For a good description of Double-Checked Locking , see Joshua Bloch’s ‘depressingly’ ubiquitous book :  Effective Java (Second Edition) Item #71 – Use lazy initialization judiciously.

Note that Double-Checked Locking using volatile only works from JDK5 onwards with the extended volatile semantics. (See the link :  The “Double-Checked Locking is Broken” Declaration)

Hopefully that gave you a flavor of the JMM rules and so instead of going through the rest of the rules, I will merely mention the names of the other rules for completeness sake : Thread Start Rule, Thread Termination Rule, Interruption Rule, Finalizer Rule, Transitivity.

It is easy to guess the general drift of the Transitivity Rule (the last one in the list above); Roughly speaking it says :  if A sees B and B sees C, then A sees C.

Related links :

  1. Java concurrency in practice By Brian Goetz, Tim Peierls et al
  2. The “Double-Checked Locking is Broken” Declaration. See the section : Under the new Java Memory Model
  3. Effective Java (Second Edition) By Joshua Bloch
  4. Java Memory Model – Wikipedia article
  5. The Go Memory Model

Hello World from the TM SELF …

November 7th, 2009

Recently, I stumbled upon my copy of Michael Sipser’s “Introduction to the Theory of Computation.”  I eagerly browsed through the first 6 chapters and the Turing Machine (TM) SELF described in Chapter 6 (Lemma 6.1) caught my eye.

Basically, SELF TM is defined as :

TM SELF = A Turning Machine which when run computes and outputs  its own description

So the TM SELF is roughly equivalent to a program written in a high-level language that, when run, outputs its source code by computing it. The crucial requirement is that the program compute its description (i.e., the source code) from transient memory (e.g., RAM) and should not resort to reading the code from a persistent store (i.e., opening up its own source code file or some source code database and printing it would be cheating).

I spent a few hours doing a literal translation of the idea in the book to implement a Java program that prints its own source code.

We use angle brackes “< >”  around a TM to denote its description.

For example, <SELF> represents the description of the Turning Machine  SELF. Or equivalently, <SELF> denotes the string representation of the source code in Turning Machine SELF.

From here on, we will just follow the idea in the book which divides SELF into two modules A and B. In programming terms, it means SELF contains 2 methods :  method A followed by method B. Therefore the description (source code)  of SELF is nothing but a juxtaposition of the description (code) of  A followed by description (code) of B.

Therefore,   <SELF> = <A><B>

When SELF is run :

1) the control starts with A  which prints <B>. This is because we arranged that a copy of <B> is literally embedded in <A> as a string.

2) After A outputs the string <B>,  A calls the method B(). In TM terminology, this  is equivalent to passing the control to module B.

3) B computes <A> from the output left on the tape after A has finished execution.

This is to say that the code in method B() will read the contents of the “tape” (as you will see, in the code below,  the “tape” is nothing but a StringBuffer) and somehow from that B will figure out what A’s code (i.e., <A>) looks like.

4) This part is crucial so it’s worth repeating : when method A finished its run, we have <B> on the tape. So this is the ‘input’ B will work on when A passes the control to it.

5) After B gets the input of <B>, all it does is compute the code that A uses to print a string (the string being <B>). Effectively, computing <A>.

6) Once it computes <A>, B just “prepends” <A> to what is already there on the tape (remember that the “tape” / StringBuffer still has <B> from when A finished running)

Module/Method  –>   Tape contents after execution of this module

A           –>                    <B>

After A outputs <B> to the tape, it calls module B and the control  goes to B.  B computes A’s description by adding some additional “code” around  the existing tape contents i.e., <B>. In TM speak, we can say that B applies a computable function “q” to its input and computes  <A>. That is :  q(<B>) = <A>.  Then B prepends its output <A> to the tape contents.

Module/Method  –>   Tape contents after execution of this module

B           –>              q(<B>) <B>  = <A><B>  = <SELF>

So that means, when module B finishes,  the whole program finishes (because calling method B is the last statement in method A) and the tape contains the code for both methods A and B which is nothing but the entire program <SELF>.

That is to say : the program prints itself.

====

Here’s the program cut-n-pasted below. Note that it’s a literal translation of the above idea without any regard for program length.

You can copy the whole code into a file called Self.java and compile and run it. The output from running Self.java should be exactly identical to the source code in Self.java.

A few technicalities :

Of course, you would not exactly write code on a mathematical TM or for that matter directly in machine code. What we do is write it on a computer in some high-level programming language like Java. This itself engenders a few differences between the theory of computation and the practice of programming.  For example, in Java, you cannot just have methods A and B, you have to have a Class that encompasses these methods. Also, if you want to run Self.java (the code below)  from the command line, you need to have a Main() method. Which is why in our implementation below, the module A is the  method Main and not some method “A”.  Module B is method B which gets the contents of the tape (i.e., StringBuffer) as its input when A calls it.

In the end, we output the contents of the tape to the standard output.

Also, I resorted to a hack to avoid using ‘escaped double-quotes’  instead choosing

char[] s = {'f', 'o', 'o'}

instead of

String s = "foo"

Actually, I wrote a quick program that does this kind of code translation from the String s to the char[] s syntax.

The actual program is only 2 “lines” long!

Essentially, the first line is <A>. The second line is <B>.  I have mentioned in Step (1) that we will embed a copy of <B> in <A>. In fact, in the following code, if you search for the second line in the first line, you will find an exact copy of the second line in the first.

When you run Self.java , it outputs its own code.

=====Copy the code to a file Self.java and run it=====

public class Self { public static void main(String args[]) { StringBuffer sb = new StringBuffer();sb.append("private static void B(StringBuffer sb) {StringBuffer sb2 = new StringBuffer(sb); char[] arrChars = {'p','u','b','l','i','c',' ','c','l','a','s','s',' ','S','e','l','f',' ','{',' ','p','u','b','l','i','c',' ','s','t','a','t','i','c',' ','v','o','i','d',' ','m','a','i','n','(','S','t','r','i','n','g',' ','a','r','g','s','[',']',')',' ','{',' ','S','t','r','i','n','g','B','u','f','f','e','r',' ','s','b',' ','=',' ','n','e','w',' ','S','t','r','i','n','g','B','u','f','f','e','r','(',')',';','s','b','.','a','p','p','e','n','d','(',34,}; String str2 = new String(arrChars); sb2.insert(0, str2); char[] arrChars2 = {34,')',';',}; str2 = new String(arrChars2); sb2.append(str2); char[] arrChars3 = {' ','B','(','s','b',')',';','}',}; str2 = new String(arrChars3); sb2.append(str2); System.out.println(sb2.toString());System.out.println(sb.toString());}}"); B(sb);}
private static void B(StringBuffer sb) {StringBuffer sb2 = new StringBuffer(sb); char[] arrChars = {'p','u','b','l','i','c',' ','c','l','a','s','s',' ','S','e','l','f',' ','{',' ','p','u','b','l','i','c',' ','s','t','a','t','i','c',' ','v','o','i','d',' ','m','a','i','n','(','S','t','r','i','n','g',' ','a','r','g','s','[',']',')',' ','{',' ','S','t','r','i','n','g','B','u','f','f','e','r',' ','s','b',' ','=',' ','n','e','w',' ','S','t','r','i','n','g','B','u','f','f','e','r','(',')',';','s','b','.','a','p','p','e','n','d','(',34,}; String str2 = new String(arrChars); sb2.insert(0, str2); char[] arrChars2 = {34,')',';',}; str2 = new String(arrChars2); sb2.append(str2); char[] arrChars3 = {' ','B','(','s','b',')',';','}',}; str2 = new String(arrChars3); sb2.append(str2); System.out.println(sb2.toString());System.out.println(sb.toString());}}

public class Self { public static void main(String args[]) { StringBuffer sb = new StringBuffer();sb.append("private static void B(StringBuffer sb) {StringBuffer sb2 = new StringBuffer(sb); char[] arrChars = {'p','u','b','l','i','c',' ','c','l','a','s','s',' ','S','e','l','f',' ','{',' ','p','u','b','l','i','c',' ','s','t','a','t','i','c',' ','v','o','i','d',' ','m','a','i','n','(','S','t','r','i','n','g',' ','a','r','g','s','[',']',')',' ','{',' ','S','t','r','i','n','g','B','u','f','f','e','r',' ','s','b',' ','=',' ','n','e','w',' ','S','t','r','i','n','g','B','u','f','f','e','r','(',')',';','s','b','.','a','p','p','e','n','d','(',34,}; String str2 = new String(arrChars); sb2.insert(0, str2); char[] arrChars2 = {34,')',';',}; str2 = new String(arrChars2); sb2.append(str2); char[] arrChars3 = {' ','B','(','s','b',')',';','}',}; str2 = new String(arrChars3); sb2.append(str2); System.out.println(sb2.toString());System.out.println(sb.toString());}}"); B(sb);}

private static void B(StringBuffer sb) {StringBuffer sb2 = new StringBuffer(sb); char[] arrChars = {'p','u','b','l','i','c',' ','c','l','a','s','s',' ','S','e','l','f',' ','{',' ','p','u','b','l','i','c',' ','s','t','a','t','i','c',' ','v','o','i','d',' ','m','a','i','n','(','S','t','r','i','n','g',' ','a','r','g','s','[',']',')',' ','{',' ','S','t','r','i','n','g','B','u','f','f','e','r',' ','s','b',' ','=',' ','n','e','w',' ','S','t','r','i','n','g','B','u','f','f','e','r','(',')',';','s','b','.','a','p','p','e','n','d','(',34,}; String str2 = new String(arrChars); sb2.insert(0, str2); char[] arrChars2 = {34,')',';',}; str2 = new String(arrChars2); sb2.append(str2); char[] arrChars3 = {' ','B','(','s','b',')',';','}',}; str2 = new String(arrChars3); sb2.append(str2); System.out.println(sb2.toString());System.out.println(sb.toString());}}

============