Saturday, August 02, 2014

A simple Rust `pow` function for the built-in numeric types

While playing with Rust I wrote a simple pow function:

fn pow<T: Num + FromPrimitive + Copy>(a: T, mut b: uint) -> T {
    if b == 0 {
        return FromPrimitive::from_int(1)
            .expect("1 must be convertible to type of a");
    let mut m: T = a;
    b -= 1;
    while b != 0 {
        m = m * a;
        b -= 1;
    return m;

Here is a link to the playpen where you can test it out:

Sunday, July 29, 2012

Installed Jelly Bean on my Nexus S

The Jelly Bean (Android 4.1.1) factory image was released by Google very recently. I did not want to wait any long this time. AT&T still did not push the ICS update, so nothing to expect from them. I went ahead and followed the same procedure I went through last time to install ICS. So far it seems like Jelly Bean is indeed faster than ICS. Right after the phone rebooted itself Google Play Store was downloading some 30+ apps I had before and I was browsing, setting up my exchange email account and synching it at the same time. I did not experience any significant lag even though such a large job was going on in the background, something unthinkable with Android before. I am certainly happy with the update but it still has to go a long way to match the instant reaction feel iOS gives to the user for any UI event. It is good to see that they finally started to address the issue.

Sunday, July 22, 2012

Blog composed by Ecto

Today I was trying to find a good desktop blog editor for Mac. I used Windows Live Editor few years back and found it to be very good at editing blogs. Not only that I don't use Windows any more but also Microsoft discontinued it. I found a long list of such editors by Hongkiat Lim. I tried QTM but it failed to connect to my blogger account. I tried Qumana, it failed to authenticate too. Then I tried ScribeFire for Firefox but to no avail. At this point I was wondering if my account is blocked or I forgot my credentials. However, I gave a chance to Ecto and voila it could connect. I will continue to use it for some time to see if it is worth to buy it.

Friday, June 22, 2012

Tree command in Mac

Linux and probably other Unix-y OSes have this nice "tree" command to list a directory in a nice tree view in command line interface. But Mac is missing that. There are plenty of workarounds using the "find" and "ls -R" command for this but I found the one below good enough for me:

find . -print | sed -e 's;[^/]*/;|____;g;s;____|; |;g'

I just created an alias in my bashrc file and enjoying it :)

alias tree="find . -print | sed -e 's;[^/]*/;|____;g;s;____|; |;g'"

Tuesday, May 22, 2012

How to install Android 4.0.4 on Google Nexus S

I have been waiting for AT&T to push ICS to my Google Nexus S since last December. Google started rolling out ICS at that time but stopped it because of phones being bricked by some bugs. In March 2012, they released another version after ironing out the bugs. Since then many carriers and handset makers pushed the update but AT&T seems to be not interested. Many internet article and even Google+ posts by Google engineers clearly mentioned that update is available from Google but when I chatted with a customer representative of AT&T he blatantly lied that they did not receive any update. I did not expect any better from AT&T but, in retrospective, for some unknown reason I foolishly believed AT&T will push the update in near future. Eventually my patience wore out and I started to find how to install the latest ICS myself. I found it surprisingly easy. It is so easy that I am wondering why I waited for a company, well known to ignore its customers, for so long. Anyway, here are the steps to follow to install Android 4.0.4 on my Google Nexus S:

DISCLAIMER: Be advised that this process involves risk of losing data or bricking the phone and I won't be responsible for any mishap. Please proceed at your own will.

1. Download and install Android SDK.
2. Download fastboot.
3. Unzip fastboot and copy it inside the "tools" directory.
4. Add "fastboot" to the PATH.
5. Download the Android image. Choose the image based on your phone's radio. You can find it by going to "Settings" -> "About Phone".
6. Unzip it.
7. Enable USB debugging on your phone.
8. Connect your phone to your computer and make a full backup.
9. Power off your phone and boot it in the bootloader mode by holding Volume Up and Power buttons simultaneously.
10. Open a terminal and run: "fastboot oem unlock" (this may void your warranty).
11. cd into the unzipped Android image directory.
12. Run "./".
13. The phone will take some time to install the image and reboot. Finish the setup process by going through the steps prompted by Android (e.g. signing in to your Google account).

Its a good idea to lock the bootloader again. So do the following to do that:

14. Enable USB debugging.
15. Connect phone to your computer.
16. On terminal, run "fastboot oem lock".
17. Reboot your phone.

If you have small data plan then you may want to connect to WiFi before signing into your Google account because after signing in Android will download and install all the apps you installed from Google Play before.

Thursday, February 23, 2012

Temporary fix for SSH broken pipe error with Mac OS X Lion

I recently upgraded from Snow Leopard to Lion. Since then my ssh sessions are timing out pretty quickly with the following error:

Write failed: Broken pipe

There is a lot of discussion going on in the web on how to fix this problem. I tried a few but none of them worked. Eventually I added an alias to my ".bash_profile" file:

alias ssh='ssh -o TCPKeepAlive=no -o ServerAliveInterval=15'

This seems to be working for now.

Thursday, January 19, 2012

A hadith we should take to heart but we won't

I subscribed to for daily hadith and got this one today:

Rasul Allah (sal Allahu alaihi wa sallam) once sent somebody to collect zakat from a certain region. When the man returned he handed some of the zakat over and kept some for himself saying that he had received it as a gift from the people. Allah’s Apostle then ascended his pulpit and addressed everybody. In it he said: “I employ some men from among you for some job which Allah has placed in my charge, and then one of you comes to me and says, ‘This (amount) is for you and this is a gift given to me.’ Why doesn't he stay at the house of his father or the house of his mother and see whether he is given gifts. By Allah whoever takes anything unlawfully will bring it on the Day of Resurrection by carrying it over his neck.” [Bukhari]

Giving or taking bribes is at the root of corruption. Islam clearly states that both the giver and the receiver of a bribe end up in Jahannum (Hell). But how is one to recognize that he or she is involved in this practice? In this hadith, Rasul Allah (sal Allahu alaihi wa sallam) describes a simple test that each person can perform to check themselves, when receiving favours while serving in a particular position. They should ask themselves whether what they receive is something they would be ‘gifted’ had they been sitting at home, i.e. not serving in that position. If the “gift” you receive is because of your office, so that you can use your position to do the gift-giver a favour, then this is a misuse of authority.

(Source:, 18 January 2012 CE | 23 Safar 1433 AH)

If at least 10% of our government officials learn anything from the hadith and practice in real life, our country will start to see dramatic changes. But the question is, would anyone do it?

Saturday, December 31, 2011

My first domain

Finally, I got my domain: At the time of this writing a web server is running there with a pretty bland welcome page: I am using a AWS EC2 Micro Instance, which is free for one year, as the server. I am thinking to have my own mail server there. I can't do anything heavy with the micro instance I guess. I am still thinking how I can use the server with its limited resources.

Thursday, November 10, 2011

C/C++ going stronger than what people think

TIOBE published their programming language index for November, 2011 today and as per the usual trend Java, C and C++ are the top three programming languages. I am surprised to see that even after becoming old compared to many of the widely used programming languages, C and C++ are still holding their spots. I am particularly happy to see those three languages at the top because those are also my top three favorite languages. I would be happy to see Python and Ruby doing better. Here is the graph on long term trends on top ten programming languages from that site:


Wednesday, November 09, 2011

Development model using Git branching

I just read the awesome post on a Git branching model for software development. Thanks Naseem bhai for sharing the link with me. Git is my most favorite SCM tool. I think I am going to use the model for all personal projects. The author of the blog made his points by providing very clear examples. It is surely worthwhile to read it.

Thursday, October 20, 2011

Quick and easy way to split lots of strings in Java

Recently, I had to split strings in a method which would be called potentially couple of billion times. The strings were delimited by only one character e.g. '#'. To be as efficient as possible, I just used String.indexOf(delimiter) and then String.substring(i, j) to get the splits. For this case, I think this certainly is the most efficient solution because the String.substring() method does not allocate new memory, it just returns a new String object which has some meta information to get the string from the original string's buffer (this is a nice optimization but it has its own pitfall). I was happy with it but the code looked messy with all those String.indexOf() calls and lots of index maintenance. Upon getting a review from a colleague I looked for ways to make it look better and easier to maintain. I found couple of alternatives to do the this:

1. StringTokenizer
2. Scanner
3. String.split

StringTokenizer had to be discarded immediately as it is getting old and is only there for backward compatibility. The Javadoc itself says, "StringTokenizer is a legacy class that is retained for compatibility reasons although its use is discouraged in new code." The Scanner is a great utility but seems to be bit heavy for that method. I had to keep in mind that the method would be called potentially billions of times in a row and it has to be as quick as possible. This left me with only the last option. String.split works in a simple way. It returns an array of strings. So, I could just use something like this:

String splits [] = str.split("#");
for (String split : splits) {
    // Do something ...

However, as noted here, there is a performance issue with this. Each String.split() call compiles a regular expression pattern and then uses the pattern to split the string. The pattern compilation is indeed very expensive and can slow the method down significantly. So, essentially what the String.split() method does is this:

public String[] split(String regex) {
     return Pattern.compile(regex).split(this);

By looking at the implementation, it becomes immediately obvious what one can do if lots of strings need to be split by the same regular expression. One can just have a pre-compiled pattern and call its split method repeatedly:

Patter pattern = Pattern.compile(regex);
for (String str : strings) {
    String splits [] = pattern.split(str);
    // Do something with the splits ...

The only thing unknown to me is whether the returned strings allocate new memory or the Pattern.split() method just behaves as String.substring(). But from running the code with more than 2.5 billion strings, I did not see any performance difference between the old and the new approach. It might mean that copies of strings are actually not made.

Tuesday, October 11, 2011

Netflix does not support Linux!

After getting annoyed by Netflix because of its recent dramas, I got pissed off today to see it does not support Linux. Its a shame for a new tech company like Netflix to not support a popular Linux distro like Ubuntu. May be the number of users is small compared to other OS users, but in this world of open source and open standards supporting Ubuntu is just a gesture of goodwill. I would say that the disliking that started to grow in me after the price hike just got bigger after discovering this.

Friday, August 12, 2011

A tortured choice in famine: Which child lives?

I read the story here. I think this is the most horrific story I have ever read. I can't imagine that a parent is forced to make a choice to abandon his/her child to die but this is what is happening in this world right now. Can't we do something about it? Surely we can. There are many organizations working in that area trying to help the famine affected people. We can donate some money to them, no matter how small the amount is. This page contains a list of charity organizations working on the problem. One can also donate to UNICEF. Islamic Relief is also taking donations. I am sure there are more organizations trying to help those people. All we need to do is to make up our mind to donate at least a small amount. I think the problem can be easily fixed if only a fraction of us donate some money. This is our chance to have a big impact on someone's life by making a very little effort.