Wednesday, April 28, 2010

Doesnt have a point of view....

He's a real nowhere man,
Sitting in his Nowhere Land,
Making all his nowhere plans
for nobody.

Doesn't have a point of view,
Knows not where he's going to,
Isn't he a bit like you and me?

Nowhere Man please listen,
You don't know what you're missing,
Nowhere Man,the world is at your command!

(lead guitar)

He's as blind as he can be,
Just sees what he wants to see,
Nowhere Man can you see me at all?

Nowhere Man, don't worry,
Take your time, don't hurry,
Leave it all till somebody else
lends you a hand!

Doesn't have a point of view,
Knows not where he's going to,
Isn't he a bit like you and me?

Nowhere Man please listen,
you don't know what you're missing
Nowhere Man, the world is at your command!

He's a real Nowhere Man,
Sitting in his Nowhere Land,
Making all his nowhere plans
for nobody.
Making all his nowhere plans
for nobody.
Making all his nowhere plans
for nobody!

That just sums up my mood right now.

BTW, I got my GSoC :)
Lets hope I can do justice to the project.

Friday, April 9, 2010

Wait and watch

So finally, the day has arrived. I submitted my GSoC application for Mono. If selected I will be working on adding an infrastructure for on-the-fly code metrics analysis.
I could not execute my 'plan' completely however. Eitherway, the lessons learned this year I will apply next year. During the period of writing and submitting proposals I plan on staying in the cool confines of my room :)
I just hope I have not bitten off more than I could chew...

Sunday, March 28, 2010

Application patterns

Creating big applications is a long and difficult process. It is also very vague and non-linear. Design documents change as per the fluctuating needs of the client, limitations of the development environment and programming language, paucity of time and funding, and of course, developer competence. Before one sits down to start writing code, one must have a conceptual overview of the application. This is the architecture phase. Once this conceptual overview has been fleshed out, one starts thinking about the patterns, data types and algorithms to be used. Note that by patterns I mean application patterns and by data types, I mean abstract data types and not data structures. A queue or a stack is an abstract data type and NOT a data structure, queues and stacks can be implemented using either arrays, linked lists or heaps. These are data structures. Data types provide intent, while data structures provide the means. A pattern I want to discuss is the Producer/Consumer queue.
This pattern is useful if you have jobs that are generated which need to be executed in a sequential manner. So we have a queue of tasks and a worker thread that executes those tasks on-the-fly as they are enqueued in the queue. So how is it implemented? Very straightforward. We have a queue, a locking object, pool of threads and a thread monitor. To enqueue, first lock the locking object and call pulse in the monitor. To consume, simply lock the queue, dequeue, and pass on the task to a waiting thread. To dispose simply enqueue NULL in the queue and wait for the threads to terminate.

Friday, March 26, 2010

Lamer and lamer

Obsession is not a good thing. Well, most of the time it is, but becoming too obsessed with something will make you a very lonely person. Obsession is also a sign of greatness; no man who was a master of his craft was a sociable person (exceptions are always there though). Perhaps loneliness is the price one pays for everlasting glory? Anyway my "plan" is coming around quite nicely. If I am lucky I could get 3 maybe 4 slots. If that happens I can rest easy....for some time ;)
So for some news; placed 4th in Eastern Groups, 4th in powerlifting :( , completed Dragon Age: The Awakening, and cramming my head with a lot of code.
Presently I am working on a on-the-fly analysis of code. Lets see how this will turn out.

Wednesday, March 17, 2010

Code Metrics Addin update (beta version available)





I have been working quite a bit on the metrics addin. In the process I also learned quite a bit about the idiosyncrasies of the C# language as well as gained familiarity with NRefactory and the MonoDevelop Dom model. The next logical step would be to implement CQL which should be quite straightforward as I will just need to map CQL to LINQ queries and query the context data structure that I already have.
Here is a screenshot for you to enjoy. A very weird thing is that NRefactory refuses to parse lines in between # regions. So a namespace defined as
#if_something
namespace name1#else_something_else
namespace name2
{....

will not be parsed. Somehow the Dom model recognizes it though.


Saturday, March 6, 2010

Diligence and discipline

Two words that are definitely missing from my life right now. On the academic front I have lost all interest. Seriously, at this point of time in my life, I am sick and tired of never ending exams. They are totally pointless and a complete waste of time. I have no interest in suggesting alternatives because that will be an exercise in futility. Speaking of which I have a powerlifting event I have to participate in tomorrow. I did a 80 kg benchpress some time back. Hope I am in good form tomorrow!
My code metrics project is going on pretty well. Have a lot to learn though, especially the .NET threading model and GTK# as well. I also need to get started with all the pending work of SMS Invite :)

Thursday, February 18, 2010

A lot to write about....

...but no time to write it. Will write a long one after exams which end next Friday. Till then, must study, must study, must study....

Thursday, February 11, 2010

OCS# and Custom Invitations

Some time back I checked out an interesting project called Social Web for the KDE desktop. It brings the power of social networking into normal desktop apps. The back end of this systems is a REST based API called Open Collaboration Services. Although there is a QT based C++ binding for it called Attica, I thought it might be fun to whip up a C# binding for the library. And while I am at it, an Android client as well? ;)
Its quite fun to think about the kind of apps one could dream up using OCS. If normal desktop apps integrate OCS into their services, one would not need to start their browser, go to facebook or myspace or whichever social site they are a member of, login and access their apps. You could do all that from your desktop itself. Consider a music player. Say you really liked a particular song and want it to appear on the recommendation listing of your friends. All you have to do is mark it with a 5 star rating and make that data public. The backend will post this data to your profile on the web using OCS and your friends can pull this data as and when they need it. Creating a robust recommendation on top of this system should then be a pretty easy task.
Also I am taking care of custom messages in SMS Invite. I had a solution using XML in mind but I have not really started off on it yet. Lets see where this goes...

Saturday, February 6, 2010

Antibiotics and antihistamines

I have fallen ill thrice since the beginning of the new year. I recovered the last two times without taking any medicines but now I am not taking any chances. Primarily because I am running a fever and my throat's hurting. When this happens there is a chance that the infection will spread to the ear causing the worst suffering I could ever imagine. So I am currently taking Roxithromycin (150 mg) and Fexofenadine Hydrochloride. Roxithromycin is a broad spectrum antibiotic that takes care of most respiratory infections. Fexofenadine is an antihistamine, and is used as an antiallergen.
Anyway, all I can say is that never take good health for granted.

Wednesday, February 3, 2010

WeakAsyncTasks

My friend pointed out a very interesting construct used in the Android native app, Contacts.
I learned a couple of things along the way.
Firstly what are weak references? Well you need to know what is a strong reference. In Java, there is a garbage collector at work that removes dead objects from the heap. An object is dead when its reference goes out of scope.
So supposing I write a code

void foo()
{
myObj obj = new myObj();
// Do something

}

obj is my strong reference to an instance of the class myObj. When I am done with foo and return the flow of control to the function that called foo, it goes out of scope, and the memory allocated for that instance of the class myObj is garbage collected and freed.
As long as an object is reachable via a chain of strong references, it will not be garbage collected.

However there are some issues to consider. Suppose you want to track the number of objects in the program that are currently in play. Or suppose you want to assign serial numbers to instances of a class. Now although these problems can be easily solved by merely extending the classes in question, many a time that is not the case (in case the class is marked as final in Java or sealed in C#). So if you use, say a Hashmap to track the objects, you will have a strong reference to it. So when the object goes dead and should be garbage collected, it won't because of the strong reference to it. So despite the presence of a GC, the programmer will have to worry about when to garbage collect and has to perform manual memory management. Not good.

The solution to this conundrum is a weak reference. Simply put, having a weak reference to an object will not prevent it from being garbage collected. So if the hashmap stores weak references to live objects, once they go dead, you do not have to worry about the garbage collection. However you will have to poll the hashmap to see which objects have died and remove the corresponding weak references. So to save yourself the trouble, use the WeakHashmap generic.

Now what is an AsynTask. Asynchronous tasks in Android, are basically thread-like in their behaviour with a few key differences, they do not require you to worry about the complexities of threading and handlers, but you can call them ONLY from the UI thread. So you can perform background operations in the AsyncTask and then publish the result on the UI without holding up the UI thread.

A WeakAsyncTask allows you to perform asynchronous tasks on objects with weak references. Why is it required? Suppose you launch an AsyncTask , show a nice progress dialog while the AsyncTask is running, and have the progress result be posted back to your UI.
But what happens if the phone rings? Or you rotate your display? Your activity be terminated with extreme prejudice. But AsyncTask will continue to hold a stale reference to the object you created earlier, and although you cannot access it, the strong reference to that object within the AsyncTask will prevent it from being garbage collected. Also the result of the AsyncTask would have been posted to the original instance of your activity, but because it will have been restarted, AsyncTask will not post to this new instance and be effectively floating about in limbo. What we have here is essentially a memory leak.

This is where the WeakAsyncTask comes in. Since it has a weak reference to the target object, when the object is garbage collected, the WeakAsyncTask knows the target object has gone out of scope and will automatically terminate itself, thus solving the issue of memory leaks. This is a pretty useful class and I think it should be a part of the primary Android API.

Sunday, January 31, 2010

ShowAndTell

I had an idea for an app recently, that helped one to learn complex software. I remember a few years back, trying to understand 3ds Max. Anyone who has ever used Max will remember getting bewildered at the enormous amount of options that Max throws in your face. Although Max is very powerful and gives a lot of control in the hands of the experienced user, it can be very tedious to learn.
The idea I had was to record the mouse movements of an expert who is proficient in the software's uses. We can assume that a user trying to learn a software will most probably have it installed on his machine. So if we can capture the mouse movements of an expert and play it out on the learner's computer, it would be like a video tutorial without all the hassles of recording one. Audio recordings can also be played as and when required.
The hitch?
In order to record mouse movements, we need to set up a global mouse hook. I know how to do it in Windows, but that requires using kernel APIs like SetWindowsHookEx, which I think is crap. I have not figured out how to do this in linux however.
On the other hand, taking control of the mouse is trivially simple. In Java, there exists a class called Robot, which can be used to control the mouse. Similar APIs must exist for other languages as well I am sure.
I will post more ideas for apps that make learning intuitive.

Tuesday, January 26, 2010

A high point on the roller-coaster

We WON! HkB (Hijli ki Bijli) aka Malhar won gold in Sargam, the eastern groups events in Spring Fest for the second time around. It was pure awesomeness, check us out on youtube!
I also participated in Wildfire. We did not win anything as the bands that came were really good, but maybe next year, things might change! We did an original, whose lyrics and vocal melody I had composed. I will put up the recording in some time. Meanwhile, here are the lyrics

Torn

In a world of hate and fear,
despair, misery, everywhere
In the darkness, death awaits
Inside every man, there is a demon of the night

Strong as steel,
burning drive,
an invincible warrior,
with hatred in his eyes,
with a vow so strong,
to spread the blight,
he reads omens,
and strikes on time

With darkness in his heart,
a venom tainted soul,
dreams he tears apart,
reaps evil, wherever he goes

Take the leap,
in the darkness and you'll find,
a demon to possess you,
take over your mind.
With a vow so strong,
to spread the blight,
kill all who oppose,
crush the rest in time.

In your dreams,
in your nightmares it awaits
A demon to possess you
to show you the way
To make a binding oath,
to teach a creed that's sure and true
to do unto others
before they do unto you

Pretty extreme huh? :D

Now I need to learn latex....

Thursday, January 21, 2010

Trying times

Another crazy day, woke up at 7:30 for a morning class, wrote some code, started practice at 9, recorded two songs, finished practice at 4:30 in the a.m. , and now back in my room.
Hallelujah!
BTW, can't wait for Jan 26th for Mass Effect 2. Heard the XBox 360 version got leaked already!

Wednesday, January 20, 2010

A glass half full

Last night was a trying one for many different reasons.
Went to the gym and tried some front squats. The whole thing turned it out to be an epic fail, apparently I had hurt my back a few days ago and that injury resurfaced again.
For some days I had been working on integrating twitter with SMS Invite. Till last night I knew nothing about the Android threading model, asynchronous tasks, and my knowledge of services and activities were feeble at best. The simple problem of executing an http get request exposed my lack of knowledge in all the above topics (not that their knowledge is needed anyway to execute the above task). I spent a solid 5 hours learning the internals of the threading model, handlers, activities, intents, and what you have it...only to realize later that the Uses permissions:Internet was disabled. 0_0
Now if I had been a bit more careful, maybe I would have completed my task much earlier but without the knowledge that I had gained.
Just makes me wonder, is this God at work?

Listening to : Porcupine Tree - Trains

Saturday, January 16, 2010

ASTs and online judges

A very hectic week comes to an end!
Composed the vocal melody of a metal song (will post recorded mp3 somewhere), finished working on the cyclomatic complexity (which IMHO, is the most complicated part of designing any module that measures quality of code), successfully conducted the Algorithmik event at RSM, IIT Kgp 2010 and polishing twitter syncing of SMS Invite. Unfortunately, not much progress on the Latex end :(

Some thoughts:
1) NRefactory is quite well designed (I think) but it did take some time to get the hang of it. I cannot really comment on its ease-of-use as this is the first parser infrastructure I have leveraged for my own projects. I plan to should snoop around a bit more. Getting one's hands dirty with large compiler projects is a great way to learn about compiler techniques. Next stop is LLVM! \m/

2)Must must must learn how to effectively manage a linux based network. Conducting the event smoothly was a pain but we somehow managed. I plan to create an online judge for future events. Lets see how that will get implemented (probably using some CGI scripts).

3)Android is a pain in the ass....

Oh btw, SMS Invite v0.11 beta is out in the market. We have a separate version for CDMA phones as well so some problems encountered while on CDMA networks should be solved.

Signing off...

Wednesday, January 13, 2010

On coffee joints and lousy APIs

A friend of mine claimed about a year ago that he was in talks with the top honchos at Cafe Coffee Day, a hep coffee shop, to open a branch in Kharagpur. I found it hard to believe then. Not my friend's reach, no, but the idea that an urban phenomenon such as CCD could possibly work in the bucolic shit-hole that is Kharagpur. I stand corrected. CCD opened in my campus a few days ago and has already attracted a large crowd (mostly of the Page 3 variety). The fact of the matter is that the spending capacity of the modern Indian youth has increased. As our values become more westernized, our attitudes towards living a frugal life, consuming food items not traditionally considered healthy or "Indian" , change.
Now if that is a good or a bad thing is something that I will not touch upon, because honestly, I do not know. What I do know is that CCD will probably do good business, and may encourage investors to create franchises of other famous food brands like McDonalds and KFC. Generally these fast-food joints are located on or near prime real-estate. Thus, one of the major contributors to their costs are establishment and rent charges. Leasing land in Kharagpur on the other hand is relatively inexpensive. Add to it the fact that at present a lot of land in the IIT campus is not utilized. Hence the costs saved there can be passed on directly to the students. Its a win-win situation!
On a more technical note, I have been working with the Android API recently and I frankly, do not like it much. Sure its much better than the Symbian platform, but I cannot compare it with the IPhone as I have not really used it. The Android API is in a constant state of flux and Google keeps adding and removing stuff. Its not the adding I am concerned about, but the removing irritates me. Many important utility functions pertaining to text encoding have not been implemented which means writing a serious HTTP client is a major pain in the backside.
And of course, code breaks. When a method or class is deprecated it can have an adverse impact on your application if it depends on that method/class. Generally it means that you have to rewrite certain parts to make use of the new replacement. Occasionally it can mean having to completely rethink and reimplement the application logic in the framework provided by the new
API.
I have been experimenting a bit with REST based APIs recently and thought of incorporating a twitter client into SMS Invite. Here is the skeleton code that I came up with. Enjoy!

package com.android.test.webstuff;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.net.URLEncoder;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.ByteArrayBuffer;

import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;

public class HelloActivity extends Activity {

TextView tv;
String text;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

tv = new TextView(this);
postData();
setContentView(tv);

}

public void postData(){

String Username = "myusername";
String Password = "mypassword";
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.twitter.com/statuses/update.xml");
httpclient.getParams().setBooleanParameter("http.protocol.expect-continue", false);

try {
// Add your data
List nameValuePairs = new ArrayList(1);
nameValuePairs.add(new BasicNameValuePair("status", "test"));
/.setEntity(new UrlEncodedFormEntity(nameValuePairs));

httppost.addHeader("Authorization", "Basic "+Base64.encodeBytes((Username+":"+Password).getBytes()));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);

InputStream is = response.getEntity().getContent();
BufferedInputStream bis = new BufferedInputStream(is);
ByteArrayBuffer baf = new ByteArrayBuffer(20);

int current = 0;
while((current = bis.read()) != -1){
baf.append((byte)current);

}

/* Convert the Bytes read to a String. */
text = new String(baf.toByteArray());
tv.setText(text);


} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
}
}

PS: The Base64 routine converts a byte array of characters to its Base 64 encoding. Its a bit long so I have not posted that.

Saturday, January 9, 2010

Unpowered by Caffeine

That was the would-be tag line of WithoutCoffee, a portal that I am helping out my buddy with. We plan on developing Android apps that would prove useful in the day to day life of smart phone users. Our first app, SMS Invite v0.1 Beta, which is the undergraduate project of my friend, has been released and is getting rave reviews. Which is as it should be considering the effort he put in polishing the product.
Simultaneously he has launched http://www.withoutcoffee.com as well as a blog that we intend to use to connect with our readers. It will mostly focus on short tutorials explaining the working of the different apps we develop and reflections on the experience gained working on the Android platform.
We invite you to give SMS Invite a whirl! Don't have an Android phone? Fret not, because we plan on porting it to the other major mobile OSs that there exist. Feedback and constructive criticism is always welcome.
Remember, with SMS Invite, the party is only an SMS away! :)

Friday, January 1, 2010

Help -> About

Dear Readers
This blog will mainly contain ramblings regarding technology and the events in my life that change my perspective and views. I have never been a good writer, mainly because I did not have anything to write about. However I am convinced that blogging may be useful as a tool of introspection and help us learn more about ourselves because we are forced to THINK, which is the logical precursor to an ACT, which is the making of a HABIT. (I have started rambling already :)
Either way, happy new year to you folks and all the very best for your future endeavors.
Sincerely
diffoperator