Monthly Archive for March, 2009

MonoDevelop 2.0 Released

MonoDevelop 2.0 has officially been released, it’s an incredible project though I don’t know why it gets so much flak from the open source hippies along with the rest of the Mono Project. I can’t wait to see Ryan Paul’s review of this tool on Ars Technica.

The new features are really cool. Unlike Eclipse’s what’s new list, which mostly lists a few new buttons and keyboard shortcuts, and technologies which are all three or four letter acronyms to simplify the process of generating long java function names. (My ignorant bigotry against Java is bordering on racism), then again, my opinions are biased, unfounded and more importantly – irrelevant.

The screenshots don’t do justice to the application. Screenshots only do justice to mac applications, because most apps are just pretty screenshots that occasionally respond to clicking. (I really really should stop this).

Here’s a screenshot of how the IDE manages to dwarf my 19″ monitor, while I try to add a tiny fix to Tasque and fail spectacularly while doing the same:

So if you feel like it, you should take a look, from their shiny new website.

I warn you though, if you want to install it on Ubuntu it’s nearly unpossible, and I had to doo a significant amount of voodoo to get it to run.

Monkey Madness – Day 2

I’ve been spending a bit more time with Mono, and I’m liking it more and more as I use it.

Here are my thoughts on the second day with Mono and C#, after Michael pointed out in an earlier post, I really don’t want to assume that Feature X is missing, as the people who designed and implemented these prolly had a really really good reason for doing/not doing so.

  1. Delegates rock! I haven’t gotten the hang of it yet, but I was able to write a GTK# app and I could attach tiny anonymous functions as callbacks. MonoDevelop even offered to create a new separate function with the appropriate arguments and let me fill in the blanks. MD is far far smarter than I could ever imagine.
  2. I gave NUnit a try, and after a little shakiness, I was able to assert that 1=1 and the world was safe for another day. I read about some tools forcing test-driven development by generating stubs based on the tests that you write in first.
  3. I wasn’t able to get the hang of linq in the fifteen minutes I gave it, considering I was quite comfortable with Python’s lambda functions. These are one of those features which make me wonder “Why not just iterate over the list and filter manually by condition”, and then I try doing it manually and see the difference.
  4. I was a little annoyed at the amount of work I had to do to fetch content from the internet. While it took just under a few lines, the System.Net namespace is gargantuan, and I used to spend more time scrolling through autocomplete before I gave up and searched the internet for the same. Python’s urllib2 has spoiled me.
  5. I was a little thrown off by the constructors which followed a pattern similar to C++’s pointers to objects. For regular objects I could say ClassName obj(”some”, “arguments”); but in C# apparently that’s not possible, I have to say ClassName obj = new ClassName(”some”, “arguments”);.

One thing that really annoys me is that search engine treat the Hash “#” a little odd. If I search for GTK#, and search for GTK, I get completely identical results. But if I search for C#, and C the results are different.

I get completely identical results for almost all queries with a Hash next to it as the results without a hash. I guess this is sort of like the case, where words like “the” and “who” can be excluded from your query but a query for “The Who” (I’m listening to Pinball Wizard right now btw.) means something else.

So remember kids, always brush your teeth before bedtime and never put a # in front of your library just because it’s designed for C#.

On Work Culture

Yesterday I was talking to a friend about the great beyond after college, and working at companies. The topic of work culture came up.  A lot of people are always curious to know how my experience working at Google for a few months was, and I usually say as little as I can, partially because of Non Disclosure Agreements, and a lot to do with not appearing like a little kid describing a candystore (the offices all looked like candy stores, with lots and lots of real candy).

There are a few things I’d like to note on work culture and my feelings about it, this is strictly my personal observations, and the usual disclaimer applies. In other words, you can never misinterpret this and use this against me.

  1. Work culture for me is *people*, not setting. A lot of people see pictures of google with bean bags, balls and lava lamps and naturally assume it’s great to work there. I liked it more because of some great people, who were incredibly talented and very nice hearted. My thumb rule is that any non-cutthroat geeky company will be interesting enough. So if you work at a hardcore engineering company you’ll have a fun time, compared to, say an investment bank or something.
  2. Most people think a laid back culture is great, I used to think so too. I used to work all night in the office and turn up late in the morning like all other interns. Heck, I even had my guitar and amplifier which I used to whip out when everyone around me had moved out(with a very low volume of course :) . But now I’m thinking how much does it compromise on professionalism. True you can be professional in your behavior and your work and get along fine, and dress codes are pure evil – but I didn’t know where the boundaries were to what you can and cannot do, while everyone else seemed to sort of know. While I don’t remember doing anything utterly tactless and callous at work(which I’m really relieved about), there is always the looming fear that something you take for granted might really offend people and they won’t tell you.
  3. To me, food is the thing you put in your mouth to prevent your stomach from hurting and grumbling. I am not really bothered about the taste of food that I eat, mostly due to desensitization from a vigorous workout routine. Yet I used to look forward to lunch at google. The food was very nice, as you’ve all heard, and it took a good amount of willpower to prevent me from stuffing myself senseless. One other thing great about lunch was that you’d get to interact with a lot of neat people. It’s a great excuse to sit at a table with someone you don’t know and join in on the conversation. I met some awesome people this way.
  4. I love the fact that in a good engineering company, they aren’t as worried about you staying till a particular time everyday. A lot of us keep hearing stories about people selling their souls to soulless banks for a huge paychecks, and have to work with assholes twelve hours a day, and have no social life whatsoever. Heck, I knew a guy who worked at Google who dropped in to work at 3 in the afternoon, and left at 1 in the morning, simply to avoid the traffic rush.
  5. I like the possibility to socialize outside the workplace. It’s hard to make new friends in a new city, and it’s much more comfortable if you hang out with a bunch of jolly folks who write code during the daytime, rather than in other companies with cut-throat competition and hierarchy.
  6. Oh god the coffee machines!! I know for a fact that all engineering companies take their coffee very very seriously. I take my coffee very very regularly.

Want to share some thoughts? then, use the force. And by “the force”, I mean the comment form.

So far, so good… So what?

Warning, this post has absolutely no useful information whatsoever. It contains my thoughts and opinions (yuck). Close your browser and go outside.

I decided it’s time I break the python addiction. Python is a very nice language but it’s utterly utterly indisciplined, hard to maintain and very hard to find any logical bugs. I wanted to go back to C++, but while it’s a gorgeous language which is object oriented in the truest sense, and when coupled with the incredible Boost library, makes it an unbeatable package with great tools to develop and debug those applications.

I know people really passionate about their language of choice, some passionate about C like a first love that they met in kindergarten and will chase halfway across the country just to find them again, and one bloke in particular who eats programming languages like the flavor of the week because he didn’t find one that “fits”(Last I checked, it was clojure).

For me, languages are only as good as the API that they expose. At the end of the day you’re just abstracting assembly (you know I’m right). Name any language and all it does is create machine code which are executed, or interpreted. At the end of the day python is best known for it’s vast library support. If it didn’t have the fantastic library which handled everything from URL fetching, SOAP, and virtually anything you could throw at it. You could also download and install additional libraries.

I decided I’ll give C# a shot. I decided to give MonoDevelop a shot, and really really liked that tool. The trunk build which I’m using has some great functionality, including VI emulation, which makes me feel right at home.

Anyways, I decided I’ll jump right in and write a patch for a small Gnome project. I decided to add a small feature to Tasque, but turns out a basic implementation of the feature I have already exists.

An afternoon and 300 lines later, I wrote in a patch (you can find it here) which seemed to do the trick. Making the transition to C# was surprisingly smooth, and MonoDevelop was very gentle and helped quite a bit along the way.

What I liked about C#+MonoDevelop:

  • Dicipline: Curly braces, semicolons, oh my!
  • Very robust autocomplete: A plesant change from Python, when no IDE can even guess what type your variable is.
  • Static Language: No more reading someone else’s python code, and wondering where this symbol came from and who’s instance is it.
  • Mixing traditions with modernity: There is great support for closures, iterating using “foreach”, strong adherance to namespaces, and many great features which made python really nice.
  • Great libraries: Mono’s open source implementation of .net is really nice, and cross platform for added bonus. I’ve never worked with .net so I wouldn’t know how it compares with Microsoft’s .net implementation.
  • Nice documentation support: I’m a documentation freak, and MonoDevelop does a very nice thing with generating a very nice boilerplate documentation 

Few features in C# I’d like to see:

  • Anonymous functions: ECMAScript does this one thing fantastic, where you can create a function on the fly when you want to pass a closure to a function, and a function is just another datatype. That would be neat – yeah.
  • A repository of libraries like the python cheese shop and an easy way to install them.
  • Hmm, that’s about it for now :\
  • Pointers!!! *ducks and hides*



Student death at IIT Kharagpur due to hospital negligence

On the afternoon of Sunday, March 22nd, a few of my friends told me that something horrible had happened. The short of it was that a Third year undergraduate student of the prestigious Indian Institute of Technology, Kharagpur had passed away primarily due to the negligence and fault of the on-site hospital.

Over the period of a few minutes, virtually everyone in the campus got to know about the incident, and decided to rally in front of the residence of the Director. For those of you not aware, the director is perhaps the most powerful person in the administration, and people go to him in times of great distress, when no other option seems available.

The information I am going to present here is compiled from several sources, mostly my various friends and acquaintances, pieced together for the purpose of anyone who wishes to know it. In no way am I claiming the information is presented is accurate, and these aren’t my opinions, they’re facts. By accepting it, you are releasing me from any liabilities.

Rohit Kumar was a third year student in the Electrical Engineering Department, and was part of several of the important and popular organizations on campus. On sunday morning, he felt ill, dizzy and collapsed. Worried, his friends took him to the B.C. Roy Hospital, upon reaching which, he was visibly in serious condition. He was asked to wait for three hours or for a doctor to come as the day was an “off day” or something, and barely any aid was administered. His friends wanted to take him to a government hospital, in BCR’s ambulance, but the staff insisted he stay.

Upon the doctor’s arrival and inspection, he claimed that he does not have the expertise/facilities to help Rohit, and that they should take him to a hospital in Calcutta or Midnapore (two nearby towns), which would take four hours for thre commute itself. The hospital offered that they take the ambulance, nearly four hours after he’d come in.

His friends decided to take him to the hospital, but on the way, he was no longer with them.

Word gets back to people in his hostel, who are torn between fury and sorrow. Within a few minutes, word spreads like wildfire, and a few people turn up in front of the director’s residence, as they do not know what else to do.

The story goes that the director appears nonplussed about the whole situation(the stories I’ve heard how he actually responded, I hope were an exaggaration). While talks continue, many people turn up, and a mob of students is formed. Angry and demanding change, some property is defaced and slogans are shouted, while a select few students and the director are negotiating talks inside.

Well over four to five hundred people start demanding resignation of the director, who initially refuses, but ultimately bows to the public pressure, seeing no choice. While I and many others felt that this wasn’t the right way to go ahead, the opinions of the mob trumps everyone else’s.

After four tense hours, and a signed letter, sealed and faxed to the board of directors, the mob eases, almost like it’s forgotten the events of the day so far. We are yet to know about what is happening to Rohit, or exactly what took place to lead to such an unfortunate turn of events.

I may or may not post my two cents on this issue eventually, though somewhere in the dark corner of my thoughts, I knew something like this was a long time coming, and only something that’s shocking can make people realize the level of the situation. While I’ve heard some pretty scary stories about experiences of people at B.C.Roy hospital, I’ll keep them to myself, as they don’t need any more defacing in particular. The only thing that bothers me is a complete lack of antivenom, despite the district it’s in being one of the most dense cobra-population areas in the world, and that people encounter venomous snakes on a regular basis.

Again, I state that these are details gathered from various sources, and the chinese whispers always prevail. I’ve tried to be as neutral and impassionate as possible while writing this, and publish it only with the hopes that it is useful and informative. Please do not contact me for any information. You can find more information soon on The Scholars Avenue(our institute newspaper), and Ramkumar’s Article(This one’s with pictures and additional details).

Bash Bookmarking Snippet

Here’s a little snippet that allows you to bookmark paths in Bash. Simply type “bookmark tagname”(only one word allowed, rest is ignored), and you can type go-tagname to go to that path.

The best part is that these are preserved across all terminals and sessions, and there’s TAB completion – simply press tab after typing go-.

Feedback, suggestions and bug reports go in the comments box. Put the following code in your ~/.bashrc to get started. You may need to re-source your terminal.

</p>

<h1>BASH BOOKMARKING v0.1</h1>

<h1>anirudh -@t- anirudhsanjeev.org</h1>

<p>#</p>

<h1>Bookmark a path in bash to be able to go back to it later</h1>

<h1>Navigate to the path you want to bookmark, and say</h1>

<p>#</p>

<h1>bookmark bookmarkname</h1>

<p>#</p>

<h1>This will add an alias, go-bookmarkname. Now you can type go-bookmarkname</h1>

<h1>from any path and you'll be taken there. Bash will also do TAB-completion</h1>

<h1>for you, and it's more efficient than creating aliases.</h1>

<p>function bookmark()
{
echo "alias go-$1='cd "<code>pwd</code>"'" >> ~/.bashbookmarks
source ~/.bashbookmarks
}</p>

<h1>Make sure to load the bookmarks beforehand</h1>

<p>touch ~/.bashbookmarks
source ~/.bashbookmarks

[tutorial]How to: Django, Comet, Orbited, Stomp, MorbidQ, js.io

UPDATE Sep 15th 2009 – This material needs improvement, bug-fixing and updating. Since I’m no longer working with Orbited, I will appreciate any changes (”patches”, if you will) to the article. Please email me (anirudh -at- anirudhsanjeev -dot- org) if you would like to contribute.

Note, this tutorial is highly technical and targeted to people who want to use Django with Orbited, and really know what they’re doing. I’ll give a brief introduction to comet, and how I found workarounds to my problems, but that’s it.

Django is a wonderful web framework, though like all regular web applications, you need to return a http response as soon as the request is made. But what if you want to stream HTTP, like a stock ticker, live blog, etc – when you don’t want the user to reload the page every few seconds, and you want to push data to the browser real time.

There are three standard techniques for the same. 1. Polling – Make XmlHTTPRequests (XHRs) every few seconds to the server. This is very bad as it wastes bandwidth, has high latency and isn’t scalable. 2. Long Polling – Make an XMLHttpRequest that doesn’t return until data is available on the server. This reduces latency but still is inefficient and unscalable. 3. HTTP Streaming – the best option so far – Never finishes returning a HTTP Response, but this causes a thread to lock up, and the server will run out of threads and memory before you can say “RAM”.

This paradigm of real time content delivery is called “COMET”, it’s an umbrella term similar to AJAX, and describes a concept rather than a technique. There are several comet servers available, some open source, some not. Examples are Jetty, Cometd, Meteror, Liberator, and Orbited.

I will be using Orbited, a comet server, and discussing my personal workarounds to get it to work with Django, and create a “Live Shoutbox”.

Prerequisites: 1. You know about Django, Python. 2. You have installed Orbited (orbited.org)

Recommended Reading: 1. http://ajaxpatterns.org/HTTP_Streaming 2. http://orbited.org/wiki/Documentation 3. http://cometdaily.com/2008/10/10/scalable-real-time-web-architecture-part-2-a-live-graph-with-orbited-morbidq-and-jsio/

No. 3, written by Michael Carter, a lead developer of orbited, is highly recommended. This is because my tutorial is based primarily on that. I’m going to be referring to that frequently.

Now, let’s begin:

Step 1. Create a django application.

Let’s call our application “ShoutBox”. I’m going to define two endpoints in our urls.py going to two views: xhr, and views.

$ django-admin.py startproject shoutbox

And, I create a new app – shout. $ django-admin.py startapp shout

I add two forwarders in urls.py:

    (r'^shoutbox/', include('shoutbox.shout.index')),
    (r'^xhr/', include('shoutbox.shout.xhr')),
    (r'^static/(?P<path>.*)$', 'django.views.static.serve', {'document_root':'./static'}),

copy all the files from “orbited/static” from the downloaded tarball to ./shoutbox/static. This will ensure that you’ll get your static files from the same port you’re serving on. Also, download the latest version of jquery and move it to static/jquery.js

Now, go and edit shoutbox/shout/views.py to look like this:

</p>

<h1>Create your views here.</h1>

<p>from django.template import Context, loader
from django.template.loader import get_template
from django.http import *</p>

<p>def index(request):
    """
    handle the index request
    """
    # here, we will simply fetch a template and expand it
    my_template = get_template("index.html")</p>

<pre><code># no context in particular
return HttpResponse(my_template.render(Context({})))
</code></pre>

<p>def xhr(request):
    """
    handle an XMLHttpRequest
    """
    # see what message has been sent
    message = request.POST["message"]
    # for now, let's just print the message
    print message</p>

<pre><code>return HttpResponse("OK")
</code></pre>

<p>

Step 2: Create a HTML Page:

<title>ShoutBox</title></p>

<script>
    document.domain = document.domain; // I don't know why
    // we need to do this, but we just need to
</script>

<script src="http://localhost:8000/static/Orbited.js">
</script>

<script>
    // set the orbited settings and port
    Orbited.settings.port = 9000;
    Orbited.settings.hostname = "localhost";
    //Orbited.settings.streaming = false;
    TCPSocket = Orbited.TCPSocket;
</script>

<script src="http://localhost:8000/static/protocols/stomp/stomp.js">
</script>

<script src="http://localhost:8000/static/jquery.js" type="text/javascript">
</script>

<script>
    var add_message = function(payload){
        var message1 = payload.toString();
        message_div = document.createElement("div");
        message_div.innerHTML = message1;
        document.getElementById("messages").appendChild(message_div);
    };

    // execute once the document is ready
    $(document).ready(function(){
        stomp = new STOMPClient();
        stomp.onopen = function(){
            //console.log("opening stomp client");
        };
        stomp.onclose = function(c){
            alert('Lost Connection, Code: ' + c);
        };
        stomp.onerror = function(error){
            alert("Error: " + error);
        };
        stomp.onerrorframe = function(frame){
            alert("Error: " + frame.body);
        };
        stomp.onconnectedframe = function(){
            //console.log("Connected. Subscribing");
            //alert("subscribing");
            stomp.subscribe("/topic/shouts");
        };
        stomp.onmessageframe = function(frame){
            // Presumably we should only receive message frames with the
            // destination "/topic/shouts" because that's the only destination
            // to which we've subscribed. To handle multiple destinations we
            // would have to check frame.headers.destination.
            add_message(frame.body);
        };
        stomp.connect('localhost', 61613);
    });
        $(document.getElementById('send_shout')).click(function(){
        // send an XMLHttpRequest to /xhr
        var message_text = document.getElementById('shout_text').value;
        $.ajax({
            type:'POST',
            url:'http://localhost:8000/xhr/',
            data:{
            'message':message_text,
            },
        });
        });

</script>

<p><body></p>

<div id="shoutbox">
        <input type="text" id="shout_text" /><br /><div id="send_shout"><button>Shout it</button></div>
    </div>

<pre><code>&lt;div id="messages"&gt;
&lt;/div&gt;
</code></pre>

<p></body>

Move this to templates/index.html and don’t forget to add this path in your settings.py

What the HTML does is fairly obvious if you’ve read the tutorial written by Michael Carter. I’m not going to explain what it does exactly.

Let’s test the django application. It should send an XMLHttpRequest and the console that you’re running django from should print the message that you type in the box, though we’re far from finished.

Step 2: Configure Orbited to serve stomp. We’re going to follow nearly the same steps that was followed in Michael Carter’s tutorial,

We’re first going to create an orbited.cfg

[listen]
http://:9000
stomp://:61613</p>

<p>[access]
* -> localhost:61613</p>

<p>[static]
graph=index.html</p>

<p>[global]
session.ping_interval = 300

I don’t want to explain what this exactly does, because the other tutorial manages to do it so well.

Step 3: The key component: AN RPC SERVER

Now if you run the orbited server, and the django application you will see that there’s no way you can actually send data to the MorbidQ message queue, primarily because you cannot start up a reactor send/receive system inside your django view.

My solution? run a seperate python script, that talks to stomp, and also runs an XML-RPC server, that can be called by other applications. We’re planning to migrate our RPC to thrift, which is better for local transmission, but for our tutorial, xml-rpc will do just fine.

Now there is another problem. If you create an XML-RPC server, and try to run that and a reactor server, you won’t be able to because both functions block the thread. I worked around this by running the XMLRPC server in a separate thread.

Once you configure it, it finally looks something like this:

</p>

<h1>!/usr/bin/python</h1>

<h1>relay.py</h1>

<h1>Author: Anirudh Sanjeev (anirudh -at- anirudhsanjeev -dot- org)</h1>

<p>from stompservice import StompClientFactory
from twisted.internet import reactor
from twisted.internet.task import LoopingCall
from random import random
from orbited import json
from SimpleXMLRPCServer import *</p>

<p>from threading import Thread
import stompservice
class DataProducer(StompClientFactory):
    def recv_connected(self, msg):</p>

<pre><code>    print 'Connected; producing data'


    # the next two lines are probably the biggest workaround
    # for the weirdest bug I've seen in my entire life
    # it repeatedly calls a function that absolutely does nothing
    # however, if I remove them, there's a ten second delay
    # between when the DataProducer transmits a message to
    # when the browser actually receives the data. Me and my
    # friend were mindfucked thinking about how something like
    # this could possibly happen. But right now we are more worried
    # about the rest of the code
    self.timer = LoopingCall(self.test_data)
    self.timer.start(INTERVAL/1000.0)

def send_data(self, channel, data):
    print "Transmitting: ", data
    # modify our data elements
    self.send(channel, json.encode(data))

def test_data(self):
    # WHAT THE F***?
    pass
</code></pre>

<p>orbited_proxy = DataProducer()</p>

<p>class RPCServer(Thread):
    def <strong>init</strong>(self, orbited):
        self.orbited = orbited
        Thread.<strong>init</strong>(self)
    def run(self):
        class RequestHandler(SimpleXMLRPCRequestHandler):
            rpc_paths = ('/RPC2',)
        #create a server
        server = SimpleXMLRPCServer(("localhost",8045),
                                    requestHandler = RequestHandler)</p>

<pre><code>    server.register_introspection_functions()
    def transmit_orbited(channel, message):
        """
        @param channel: The stomp channel to send to
        @param message: The message that needs to be transmitted
        """
        self.orbited.send_data(channel, message)
        return ""

    server.register_function(transmit_orbited, 'transmit')
    server.serve_forever()
</code></pre>

<p>rpcthread = RPCServer(orbited_proxy)
rpcthread.start()</p>

<p>reactor.connectTCP('localhost', 61613, orbited_proxy)
reactor.run()

So this is what happens: your application calls the XMLRPC server with a message, which is pushed to the morbidq message queue, along with a channel.

Now, to do just that, we modify the xhr() function in our views.py

def xhr(request):
    """
    handle an XMLHttpRequest
    """
    # see what message has been sent
    print "POSTDATA: ", request.POST
    message = request.POST["message"]
    # send the message across
    import xmlrpclib
    proxy = xmlrpclib.ServerProxy("http://localhost:8045")</p>

<pre><code># push the data to all clients.
proxy.transmit("/topic/shouts", message)

# That's it, thread's not locked
return HttpResponse("OK")
</code></pre>

<p>

Putting it all together

You have to run everything in this particular order:

  1. run orbited: $ orbited –config=orbited.cfg
  2. run the relay: $ python relay.py # warning – this is a non-daemonized thread. you won’t be able to quit it with Ctrl+C this is a bug, though you can pgrep and kill it manually.
  3. run the django application $ python manage.py runserver

Open up http://localhost:8000/shoutbox in multiple tabs, browsers (though it won’t work from other computers as we hardcoded “localhost”, but if you’re smart enough to use a hostname, it would work fine).

Enter a message in one textbox, and click “Shout” and it comes up simultaneously in different windows, and you can easily scale this up to thousands of simultaneous idling users, and there still won’t be any significant load on your machine.

I’m pretty new to orbited, comet and django, and thought this tutorial is helpful. If you find errors, or have suggestions, please leave a comment.

Please please do not email me with doubts or questions, I won’t be responding. You can ask the awesome folks on #orbited at irc.freenode.net.

Presenting at Startup Saturday, Kolkata

I’ve been working on a pretty top secret, though really simple app. In order to get some insight and feedback from the community, I decided to give a rough demo and talk about the app in Startup Saturday, Kolkata. The talk by me and the other cheerful bloke working with me will last under fifteen minutes and is solely to get advice and ideas from more experienced people. Though there are also some impressive events like talks by Krishnendu Sengupta and Siddharth Goyal.

If you’re in Kolkata, and not doing anything special, drop by and we can meet up and talk. The details of the event are at this page.

The page lists the timings as 1500hrs to 1800hrs. It’s taking place at the International School of Business and Media. Hope to see you there.

[Code]Test driving facebook thrift

An application I’m working on has several components. There’s an opensource erlang message broker, a django frontend, a multithreaded python message relay, and among others, a particular part of the application to do some work in a very performance critical and thread safe manner. Since I was started to get sick of python I decided to get back to C++.

The trouble with having multiple applications is that they need to talk to each other, and do it in an efficient manner. It’s easy enough to expose an XML rpc server in python and use a client. The trouble is lack of support for the same in c++ without getting libxmlrpc. Moreover, I’m not happy with an application having to handle possibly XML several hundred times a second. JSON is better from performance, size and readability, but I wanted something extra.

I’d worked with Google’s Protocol Buffers. These allow you to define arbitrary data structures and serialize and unserialize them at will, and pretty fast. But Google hadn’t open sourced the RPC components, probably because the RPC generation system relied too much on internal infrastructure.

I’d heard earlier that Facebook had released Thrift, something that generates cross-language structs that can be sent across the wire, and generates native RPC methods for several languages. I got even more interested when I was doing research on how to design our application to scale, and I read this article (from facebook engineering). The note was incredibly informative and I’ll be writing more about my experience with comet servers, and stomp message queues later.

Nevertheless, I always had an incredible amount of respect for facebook’s engineers, though maybe not for facebook itself. Some of the stuff that they’ve done, moreover with PHP, is not easy. I got hold of the head revision of thrift. It didn’t even build properly, though “make install” somehow managed to put the libraries where they belonged.

Thrift is pretty cool so far, though they didn’t bother to put in the least bit of documentation or tutorials. There’s just a simple reference file to start from. It’s almost like they just plucked the code out of their systems and released it.

Nevertheless, I wrote the standard “ping” rpc, which is sortof like the “hello world” for thrift.

</p>

<h1>!/usr/local/bin/thrift --gen cpp</h1>

<p>namespace cpp Test</p>

<p>service Something {
    i32 ping()
}
And after running thrift, it spit out several C++ files, with threatening “Do not edit” and one “Edit here” file. Easy enough. It even looks like a standard RPC implementation:
class SomethingHandler : virtual public SomethingIf {
 public:
  SomethingHandler() {
    // Your initialization goes here
  }</p>

<p>int32_t ping() {
    // Your implementation goes here
    printf("ping\n");
    return 0;
  }
};
After some sweaty work, and meddling around with g++ flags, I got it to work. I used eclipse CDT to take care of my makefiles for me, so that was a little relief. I decided to generate a client in python, though I haven’t figured out how to use it yet.

Dear facebook employees: Please stop super-poking each other and write us a tutorial.

[Code] Implementation of a "back button" for bash

I was navigating around the directories in my terminal as usual, and I thought, “Why does the terminal not have a back button”. I should be able to cd to some directory, and then go back to my previous one. Why do I need to type out each and every paths again and again.

I thus, came out with a simple solution, replace the stock “cd” with an enhanced bash command “cdb”. I wrote this command to push the current path onto a file, and a “back” command pops that path and moves to it, while you can also use a “forward” which goes back to the older directory.

I won’t try to explain, but you can see the commands I input on the lower right terminal. The font is pretty tiny, and you might have to click on the image to view the text. I do warn you that the image is a screenshot of resolution 1440×900, which might require you to do a little scrolling, which is well worth it.Screenshot of bash back button

The Code: There is a slight modification from the code that was open in my editor and the code that’s displayed, this one is newer.

To use cdb and back and forward, just pop this code into your ~/.bashrc:

</p>

<h1>back button implementation</h1>

<p>function cdb()
{
    # Store the current path in back history
    echo <code>pwd</code> >> ~/.backhist
    # Clear forward history. No point maintaining a record of forward now
    echo '' > ~/.forwardhist
    # Go to the new directory
    cd $*
}
function back()
{
    # put current directory in forward history
    echo <code>pwd</code> >> ~/.forwardhist
    # read the last line from ~/.backhist, and go there
    cd <code>cat ~/.backhist|tail -n1</code>
    # remove the last line
    # TODO: is there a smarter way to do this?
    sed '$d' &lt; ~/.backhist > ~/.backhist.temp ; mv ~/.backhist.temp ~/.backhist
}
function forward()
{
    # put current path in back history
    echo <code>pwd</code> >> ~/.backhist
    # Read last line from ~/.forwardhist, and go there
    cd <code>cat ~/.forwardhist|tail -n1</code>
    # remove the last line
    sed '$d' &lt; ~/.forwardhist > ~/.forwardhist.temp; mv ~/.forwardhist.temp ~/.forwardhist
}

Wishlist:

I would have ideally liked to replace the stock cd. The trouble is that if I rename the function from “cdb” to “cd”, then I have no way of moving to a different directory. Moreover if any fancy shell scripts use cd a lot, it might pollute your backhistory file.

Another thing is that since there’s a common file used across all terminals, it means that if I “cdb” in one terminal and go “back” in the next, I go to the path I was at in the first terminal. Some people might find it annoying, but since I usually spend time doing one task at once, the path the “back” goes to is probably relevant.

If you have any improvements you want to suggest, either in code or words, feel free to hit it up below.

I’m actually surprised that such an implementation didn’t exist. I’m sure it does, probably with some machine learning algorithm which learns where you want to go, but I never heard of it.