Thursday, January 13, 2011

Selecting random record in MySQL

The random number generators are often used in almost all  kinds of application. The random numbers are generated using well known random number generator API. But what about selecting a random record from a database. There are cases we need this. for example- if you want to suggest a random picture to user in a web application. Pictures are stored in database. Fortunately databases provide this kind of feature but unfortunately different databases have different query to achieve this. Here is how this is achieved in MySQL  - 
SELECT columnName FROM tableName
ORDER BY RAND()
LIMIT 1

The value of limit can be changed to number of records to fetch.

Tuesday, January 11, 2011

Scripting langauges

I have always been working with the compiled and statically typed languages like C, C++, Java, C#. I used to avoid scripting languages and also used to hate little bit these scripting languages. But recently started exploring PHP and JavaScript and it changed my perception. Now I started loving these languages. Programming in the these languages needs little bit of different mind set. It takes some time to think in terms of loosely typed coding style.

There are, of course, pro and cons. Here is what I have started observing about the scripting languages -

- You dont need to think in terms of types of data. Most of the time this is very good but some time this is very problematic, especially when you are dealing with string and integer together. In such case you need to explicitly cast to other type. Here is one PHP code which confused me at first glance -
$var = "false";
if ($var) {
echo "This is true";
} else {
echo "This is false";
}

First time when I was dealing with similar code, I was expecting it to print "false". But this prints true. I was thinking, as this is loosely typed language, it will convert the string to boolean automatically. But later found that the string is converted to boolean on the basis of null check. There are other instances, which are potentially confusing. This proves that the these languages are not completely type-less. Sometime you are forced to think in terms of their type and and some complicated rules about the conversion from one type to another.

- You dont need to compile! good or bad?? As I am coming form the background of complied languages, I am feeling this is as a bad thing. The compiler catches lot of error at the compile time but here I have to wait for runtime even for common syntax errors.

- Scripting languages saves you from writing lot of code that you end up writing in languages like Java or C#. Particularly writing the interfaces and thinking what class will implement what interface. As the function name and variable name resolution happens at run time, you can pass around object of any class provided that object
has that particular method or variable with that.

- The scripting language makes your life easier for most frequent operation on string, array, pattern matching etc.

Sunday, December 12, 2010

Translating C to assembly

When you compile a C code, the c compiler translates the c code into assembly language. Then the assembler translates the assembly to machine instruction code.
During my college time (B.Tech from IIIT - Allahabad), I did some reverse engineering of how a C code is translated into assembly by looking into the generated assembly code by gcc compiler.
Now I have put all those things in a form of online book.
Here is the link to the book.

Friday, December 10, 2010

Weak References

Java or .NET has a feature called garbage collection. That means all unreferenced objects will be garbage collected automatically. Does that mean that there can not be memory leak in Java or .NET? If you say Yes, then you are wrong! poorly written Java or C# code can leak memory. For example, if you create a static dictionary and keep on adding object which are not needed anymore. There is common misunderstanding in C# and Java programmer that whatever not needed, will be garbage collected. But the correct statement is what ever not referenced will be garbage collected. Sometime this difference in understanding leads poor code which leaks memory. There is common mistake of some static object holding the reference to some object which is not needed anymore.

Most of the time leak happens in these two cases:
(1) Static object holding reference to object which no more needed.
(2) Object which has long life span holds the reference to object which has shorter life span.

Ideally you can write clean code to avoid these situations. But there are cases it becomes too difficult to maintain such kind of code. A typical example is WPF event handler. If you have registered a event handler, then object that contains the event handler method will be referenced by the event source. Even if the object is not needed, the event source will keep the reference and hence the object will remain in memory. The simplest solution to un-register the event handler.

There another way is to use weak event handler. The weak event handler will keep the weak reference to the event handler target object.

The weak references are the references which are ignored by garbage collector. If the object has only weak references to it, the garbage collector will collect this.

The weak event handler is implemented using the WeakReference class. Here I am describing the WekReference class and the readers can go ahead and implement weak event handler using WeakReference class.

Here is a Java code with WeakReferece usage
import java.lang.ref.*;

public class Weak
{
    public static void main(String[] args)
    {
        Object obj = new Object();
        WeakReference<Object> weak = new WeakReference<Object>(obj);
        checkReference(weak);

        obj = null;
        // setting obj = null makes the object left with
        // only a weak reference to it.
        // although the object has weak reference,
        // the garbage collector will collect this.
        System.gc();
        checkReference(weak);
    }

    public static void checkReference(WeakReference<Object> weak)
    {
        if(weak.get() != null)
        {
            System.out.println("Object Exists!!");
        }else
        {
            System.out.println("Object Garbage Collected!!");
        }
    }
}

And Here is C# code:
public class Weak
{
    public static void Main()
    {
        object obj = new object();
        WeakReference weak = new WeakReference(obj);
        CheckReference(weak);

        obj = null;
        // setting obj = null makes the object left with
        // only a weak reference to it.
        // although the object has weak reference,
        // the garbage collector will collect this.
        GC.Collect();
        CheckReference(weak);
    }

    public static void CheckReference(WeakReference weak)
    {
        if(weak.IsAlive)
        {
            Console.WriteLine("Object Exists!!");
        }else
        {
            Console.WriteLine("Object Garbage Collected!!");
        }
    }
}

Friday, December 3, 2010

The first blog

I am very excited to write my first blog. I have been postponing it from very long time. I never found any reason to start. But recently I found a reason.

Recently I was on a vacation to my village. This was the first time I went to my village with my laptop. In past I always used to avoid carrying laptop with me while I am on vacation. I wanted to be just away from computers for few days. But this time I decided to carry a laptop. In my village I did not have any internet connection, so the laptop was kind of useless. So I decided to do something that can help me pass my time during the vacation. Then I thought to write something. Write what? a blog! yes.. I started thinking what to write in the blog. Then idea came to write some technical stuff. What kind of technical stuff? So many ideas came then finally decided to write something on C++ object model.

This reminded me of my college days. I had a hobby project of writing a OS kernel in C++. During that time I explored a lot about the C++ object model by reverse-engineering. I used to generate assembly code from C++ code then used to study the assembly to figure out how classes, inheritance, virtual functions etc are implemented.

But after long time I had forgotten most of the things. As my job keeps me busy writing code in C# only, I was out of touch in C++. But again the same process helped me. As I had the laptop with me. I started looking at the disassembled code and recollected most of the things that I explored during the college days.

Then I started writing. Initially I thought to write some blog-post only. But the content became too big to be fit for a blog post. So I decided to write as online book on some website.

By the time I had a rough-draft, my vacation was over. After the vacation, I spent some time to find a domain and then put my stuff there. Again, this is the first time I was making a website. Although I am not new to HTML but I am not good at making web-pages. I found some free web template from the internet and used that for my web site.

After this, it took me few more days to add my all stuff to HTML and post it to the website. I covered most of the topic of the C++ object model, but still few things are left. These are exception handling, run time type identification, object copy and copy constructor, pointer to member function. I will add these topics later.


Here is the link the book.

I guess this is enough for my first blog post.