Tuesday, July 15, 2008

HashMap loop in java

This is how you loop through the Key Value pairs in a Hashmap

Iterator iter = values.keySet().iterator();

while (iter.hasNext()) {
String key = iter.next();
String value = values.get(key);
System.out.println("Key ="+key+"\n Value"+value)

Here, I have implicitly assumed that values is a HashMap but as you know it can be of any Object that you like. I just used it for string and felt it might be a good example if someone is looking for it

Friday, July 04, 2008

Viewing firefox status bar in full screen

Using firefox in full screen is rather cool but I was missing the status bar which gives a lot of information about the link whenever I hover or whatever is being done by the browser. After digging up a few places, I came to this link in mozilla's site
about editing configuration files and in particular
Used to change the appearance of the browser.
Used to change the appearance of web pages.
Can be used to change various preferences .
They are in the profiles folder of your user account. Go to your current firefox profile folder, and into the chrome folder. You should see two files. userChrome-example.css and userContent-example.css, remove the example and add this:

/* Make status bars visible */
visibility: visible;

restart firefox. And voila, you have your status bar in full screen.

My Links

I just added a links section there on the sidebar so that you can see what I'm bookmarking lately. Most of them might end up being incorporated on the front page. If they are any bit useful to you, tell me. I might not have read them(or sometimes might want to read them again, so that might be useful to go over.)

If you are a fellow programming, hacking enthusiast, I'll be glad to share some links in del.icio.us.

Thursday, July 03, 2008

A simple mjpeg streamer for python

I've been working with networking stuffs lately, like XML, parsing and lately streaming. Originally, I wanted to do this for my Android project which is still slightly veiled in secrecy. It will be open sourced completely though, when it matures. So, I wrote this application in an effort to understand the networking behind it and get it to work on Android. Frankly, I am not so good with Java and working with networking stuffs with objects. Everyday I appreciate more of that power though and it's fun to learn new things. I tend to practice with python first and after the proof of concept works there, I do it in Java. It's slightly roundabout way of doing things but it works for me.
What this application does is that it takes snapshots of the jpeg files from the server fast enough for making it seem like it's video.. Well, that's what it is anyways. Let's just say I haven't understood streaming and multi part files properly enough to implement. So, basically, it just sends a GET to the server and pulls the file one by one in a loop. It's really that simple.
The tricky part was to get it to display properly. Tkinter took care of that with Python Image Library. It would be easier if the files aren't jpeg though. That might be for future implementations but for now it's fine for what I'm doing with my Android project.
Anyways, I decided to open source it entirely at


That might be useful to someone, if nothing but just to learn a new thing or two about python. It' s fairly unpolished even as a basic tool but I hope to improve it to some degree to learn about multimedia streaming and threading concepts in python.

If the application was any bit useful, do drop a comment.

Here are the sources, if you wanted to view them right away



Here's my picture after I finally got video in Android.. hehe. That program did serve a purpose. Phew!


Out with Ads, In with analytics

Finally, I got rid of the annoying ads and included Google Analytics instead. I hope it helps me track users better (HEHE, evil laugh). Nah, I just want to see my traffic from a fairly trusted source. Since I've started updating the blog again, I want to see how many people are coming.

And yeah, the ads won't EVER come back on this site. PROMISE!!!

I wonder if that news belonged to twitter than over here. I've become a bit more conscious about twittering after I saw this.

Hah, I wonder what would take to make me a twitter shitter! (An iPhone perhaps?.... the Dark side is strong there I can feel it).

Thank You Firefox.

Yep, it's official. And I've grabbed my copy of the thank you letter that Mozilla is giving away.
I actually like the way this has been handled by Mozilla with all the hype about Firefox 3 that was circulating. Albeit, I felt it was a bit cheesy to go around downloading, or asking someone else to download for a while but it was fun. I had the download link on my desktop for every one to see.

So, here's my copy of mozilla certificate.

So you better get one from here
Hurry up, they might be in Limited supply. Hehee

Wednesday, July 02, 2008

positServer online

"Release early, release often"

These were the words that sparked the open source revolution.

I'm finally trying to follow this by releasing my positServer application under GPLv3 on googlecode. It's rather half baked right now and I intend to use it mostly for backup purposes. Hehe, it's hard to screw up when your backup server is the mighty Google Inc.


If you do checkout, do send me a comment. I'll start posting some screenshots and details about what I've been upto soon.

Monday, June 30, 2008

Sending Binary files over xml rpc

I'm posting this because I finally figured how to send files(pictures in particular) over xmlrpc. It took me a while to figure it out since I was mostly concerned with saving the files into database but here it is.

#!/usr/bin/env python

from twisted.web import xmlrpc, server
import os

class PositRPC(xmlrpc.XMLRPC):
        def xmlrpc_savefile(self, file):
                datum = file.data
                thefile = open('/tmp/gnu.jpg', "wb")
                #filebuffer = file
                #os.spawnl(os.P_NOWAIT, '/usr/bin/display', '/tmp/gnu.jpg')  
                print datum
                return 1

if __name__ == '__main__':
    from twisted.internet import reactor
    r = PositRPC()
    reactor.listenTCP(7080, server.Site(r))

Then I opened trusty IDLE
>>> import xmlrpclib
>>> s = xmlrpclib.Server('')
>>> d = xmlrpclib.Binary(open('/home/pras/PicasaDocuments/gnu.jpg', 'rb'))
>>> s.savefile(d)

The idea here is that although the file is sent as a Binary, we need to convert it to string(bytes) to save it. Since we have opened the file with 'rb' option in IDLE and with 'wb' option in our server (respectively for read binary and write binary), we get binary file at the server end.

Sunday, June 29, 2008

Locking screen from command line

I use gnome and so far I've been happy with my Ctrl+Alt+L shortcut in gnome. It used to lock up the screen when I was away from the desktop. However, recently, I've started to use XFCE and sometimes ratpoison, which didn't have this shortcut.
Anyways, the simpler way to lock your screen is from command line and it seems to work everywhere I've tried so far.

$xscreensaver-command -lock
I just kept in here so that I don't forget. Maybe this little tip would be useful for some.

I just found an alternate method that can work too.
$gnome-screensaver-command -l

Friday, June 27, 2008

Code Highlighting in Blogger

Don't you just love syntax highlighting that we've become so used to these days? Be it the venerable emacs editor or the new and upcoming Notepad++es, we love our syntax highlighting editors. But the codes on our sites still do suffer this problem of being black and white. I solved this problem for our college's hfoss wiki by installing the GeSHi CodeTag Extension for mediawiki but while looking at my own posts in here, it seems the idea needs to be extended to blogger. It really looks too ugly to my used-to-pretty-IDE eyes.
In my quest to look for a solution, I hit this blog http://codeshepherd.blogspot.com/2007/09/syntax-highlighting-for-code-embedded.html
Which had two ideas. First one, to use vim's TOhtml. But being lazy to modify all my files over and over again, I decided to forego it. I copied the prettfy.js and prettify.css files to my ubuntu.org.np server and followed the instructions at http://google-code-prettify.googlecode.com/svn/trunk/README.html
The effects were, well, wierd. Apart from rather slow loading times that javascript induces, my code looked horrible with
s after every line. Totally horrible and waste of space. I looked at the code and zeroed in on line 834 where I found this regular expression:

833 var htmlChunk = PR_textToHtml(
834 tabExpander(sourceText.substring(outputIdx, sourceIdx)))
835 .replace(/(\r\n?|\n| ) /g, '$1 ')
836 .replace(/\r\n|\n/g, '

After playing around with this, breaking it and everything, I realized I'm not really helping anyone here. Apart from the fact that not everyone uses javascript by default, including me (thanks to noScript) and even I use some unconventional browsers from time to time just for kicks like w3m, elinks, lynx (Ahh, those good old days, when they were my only browsers). So, I went for the vim solution.

Now, the next frontier: Posting to blogger automagically from vim/emacs whichever is easier to automate from. (Yeah I know there's something for emacs to do this) but with this functionality right there for recognizing the code and htmlifying it.

I think I've had too much coffee tonight. I just realized, "Why am I posting this at 2AM when I have some nice programming to do?" Anyways, back to my programming. Hope this post helps someone. Or, if you know some tool for doing these things automatically, tell me so that I can save some time (or even some google time if that's what you wanted to say :).

Follow me on Twitter

After facebook, I haven't really got around to most of the social networking things, but after reading about it (a lot) and seeing some really famous people actively using it, I decided to give it a try.
Guess what, I'm loving it. So, if you are interested in following me, do follow me at
Or if you want me to be notified of your tweets, do post in here so that I can give some thoughts to that :)

Implementing xmlrpc database server in twisted

A while back, for my POSIT project (for google android), I wrote a small application in python that sent out some data from the server's repository and saved to the database. I never really got around the saving part because I couldn't get the database to send pictures back and forth. In part, I went back to working on the phone itself and my studies because I was being a little too unfocused in necessary stuffs which was bugging me off. Yeah, that was during the semester.
Now, over the summer, I am getting to continue the same project and it's more fun with a better idea about what I want to do and especially how I need to do. Also, getting sick for a while helped because I wasn't really able to work much so I just read up a few books on software engineering. The best one undoubtedly is the Gang of Four's Design Patterns. I have yet to finish that one but truly good book indeed.
OK, enough ranting. You didn't come here to know about my reading patterns, did you? Ok, where was I? Yeah, I wrote the application but didn't really got through with it because I came up with some problems with transferring pictures, or blobs to and from the phone. So, this time around I decided to use the xmlrpc library from the twisted framework to the purpose.
First I created the server with the following script. I found it somewhere in the twistedmatrix site, (really excellent documentation btw).

#!/usr/bin/env python
from twisted.web import xmlrpc, server
#import DBconnect
import MySQLdb

class PositRPC(xmlrpc.XMLRPC):
"""An example object to be published."""

def xmlrpc_echo(self, x):
"""Return all passed args."""
return x

def xmlrpc_add(self, a, b):
"""Return sum of arguments."""
return a + b

def xmlrpc_getall(self):
"""Returns all the data from the sql server."""
db = MySQLdb.connect("", "username", "password", "posit")
c= db.cursor(MySQLdb.cursors.DictCursor)
c.execute("SELECT id, latitude, longitude, description FROM db")
arr = []
for row in result_set:
#print row
entry = []
return arr

def xmlrpc_savedb(self,latitude, longitude, description):
"""Save the data to the database"""
db = MySQLdb.connect("", "username", "password", "posit")
c = db.cursor()
c.execute ("INSERT INTO db (latitude, longitude, description) VALUES ('"+latitude+"','"+longitude+"','"+description+"')")
return "success"

if __name__ == '__main__':
from twisted.internet import reactor
r = PositRPC()
reactor.listenTCP(7080, server.Site(r))

So, the idea here is to run the server on the 7080 port and pull some data with the getall function and save some datawith savedb function. Yeah, I really need to use some standard names. Heck, even I got confused about the names.
Also, see the success return for it? Yeah, it's there for a wierd little reason. Whenever I was sending data to the server using the savedb function, I was getting the following error:
Traceback (most recent call last):
File "", line 2, in ?
File "/usr/lib/python2.4/xmlrpclib.py", line 1096, in __call__
return self.__send(self.__name, args)
File "/usr/lib/python2.4/xmlrpclib.py", line 1383, in __request
File "/usr/lib/python2.4/xmlrpclib.py", line 1147, in request
return self._parse_response(h.getfile(), sock)
File "/usr/lib/python2.4/xmlrpclib.py", line 1286, in _parse_response
return u.close()
File "/usr/lib/python2.4/xmlrpclib.py", line 744, in close
raise Fault(**self._stack[0])
First instict:Google the error message, which landed me to this page:
Hmm, after searching for pyro and whatnot for a minute or two and deciding I'd rather go with interoperability that xmlrpc provides than go with a shiny toy that I need to figure how to use with java (oh yeah, that one would bite real hard later in my experience).
I tried allow_none but didn't work. So, I finally decided to just return something as a response from the server which worked. Turns out (this is mentioned in the oreilly link above) that there's no None in xmlrpc. So, I need to return one thing or other to avoid that nasty error. Hope this one helps someone save some time. :)

Oh yeah, you do need to have a database with that table.
Here's the SQL script for creating the table if you need it. (Oh, gosh you probably want to have known these itsy bitsy things about databases by now though)

`id` int(11) NOT NULL auto_increment,
`latitude` double NOT NULL,
`longitude` double NOT NULL,
`description` text,
`photo` blob,
) ENGINE=MyISAM DEFAULT CHARSET=latin1 COMMENT='the main database for everything' AUTO_INCREMENT=15 ;

Now, I open up the python console and type this up

>>>import xmlrpclib
[Returns me an array of arrays]

Anyhoo, I go back to my work now. Happy Hacking :)

Friday, June 20, 2008

Firefox 3 on debian etch

First, some updates:
These days, I've been busy doing my summer research (finally learning to document properly) and working part/full time for the computing center here as the system administrator (well, assisting the system administrator to be correct).
OK, the release of firefox 3 was big and I participated heavily and encouraged everyone to participate by downloading the browser within the 24 hours. So, now everyone I know of is running firefox 3 except the computers in my lab that I am managing. So, today after my research was over, I decided to look into the matter. There were a few problems that I was facing
1. I didn't want to kill of the old firefox
2. I didn't want to use what's considered to be unstable by debian etch in the core system
First of all, I got the error that firefox 3 needed gtk+2.10. I just downloaded the file from http://ftp.gnome.org/pub/gnome/sources/gtk+/2.10/gtk+-2.10.14.tar.bz2 and installed it at /opt/gtk

Here are the commands:
$ wget http://ftp.gnome.org/pub/gnome/sources/gtk+/2.10/gtk+-2.10.14.tar.bz2
$ tar -xvjf gtk+-2.10.14.tar.bz2
$ cd gtk+-2.10.14
$ ./configure --prefix=/opt/gtk
$ sudo su
# make && make install
# exit

Then I downloaded firefox from http://www.mozilla.com/products/download.html?product=firefox-3.0&os=linux&lang=en-US
and modified the run-mozilla.sh to make it run.
Here are the commands:
$ wget http://www.mozilla.com/products/download.html?product=firefox-3.0&os=linux&lang=en-US
$ sudo tar -xvf firefox-3.0.tar.gz -C /opt
This will give us a /opt/firefox folder
First of all, we need to make sure that firefox actually run by run-mozilla.sh file.
So, I added this for firefox path in the beginning (right after ****END LICENSE BLOCK****)
and changed MOZ_PROGRAM="" to MOZ_PROGRAM="$FF_PATH/firefox". Now firefox should run with the
Since all this is about gtk+ 2.10, I added
GLIB210_PATH="/opt/gtk/lib" ( I know it's a misnomer, I don't care about it at this point, you can change it to appropriate name)
and added it to the
in line 357.
Now firefox runs with ./run-mozilla.sh command.

But that's not enough, we want to have firefox run with a command, we want it on the menu along with iceweasel. So, I added firefox.desktop in /usr/share/applications
with this data:
[Desktop Entry]
Name=Firefox 3 Web Browser
Exec=/opt/firefox/run-mozilla.sh %u
Comment= Firefox 3 - The latest and greatest from Mozilla

Then I copied the file into /var/lib/menu-xdg/applications/X-Debian-Apps-Net-firefox.desktop
I copied the bundled icon with firefox from /opt/firefox/icons/mozicon128.png to /usr/share/pixmaps/firefox3.png
and voila, firefox-3 in the menu without upgrading the system's gtk. You could use it in your home directory if your system administrator doesn't upgrade it soon enough

and do the following if you don't want to go through all that
$ wget ftp://ftp.ubuntu.org.np/firefox-3-lab.tar.bz2
This is for downloading, if you have downloaded already cd to that folder
$sudo tar -xjvf firefox-3-lab.tar.bz2 -C /
It saves the firefox 3 files in the /opt/firefox directory and adds icon to the Applications menu.
If you are on gnome do
$killall gnome-panel
wait a while for it to reload with your updated icons

Monday, May 26, 2008

What? a Beowulf in room?

I recently got 4 SUN ultrasparc 5 boxes from the compsci lab. The most interesting thing is that when I got them, basically 1 by 1, I had no idea what I was going to do with them. For a while, I tried assigning them static IPs and ran rtorrent through them. I wanted to put a web interface for it too. Then I turned them off for a substantial amount of time because playing around with them was disturbing my studies at that time.

Now they are on and running and the most interesting thing about them so far is that they were all part of a beowulf cluster before they got dismantled into what they are now. The next step here I guess is to turn them into a nice beowulf cluster. There are still a couple of computers left in the lab which I might be able to get to expand it but so far it seems like a rather worthwhile use of the summer time. At least I now have a nice 19" monitor to play with and with some extension cords I can manage these computers very easily. Hopefully, from my desk itself. I'll try to keep posting what I'll do with these babies as I progress in this idea.

The OS will be debian sparc. :)

Saturday, March 22, 2008

How to run sugar on ubuntu- the easy way

Are you finding yourself lazy to go through the installing, git-pull update procedure for your ubuntu system to work on the olpc sugar interface? There's an easier way to do it

$sudo apt-get install sugar-emulator sugar-activities

This should do it.
If you still want to do it the old way... go for it


Sunday, January 20, 2008


Hey, it's been 19 days since new year and I haven't made all the resolutions yet so I decided to make them now. I don't make resolutions often but keeping them here might actually force myself to stick to them

0. Improve grades
I admit they are really really important, it just can't be over stated. So, it obviously goes on the first.

1. Learn regular expressions
From experience, I know that learning regular expressions is he only way to be able to use them. You find their uses only later after you know some of them. I just need to learn them.
2. Get better at social stuffs
It doesn't mean getting drunk every so often in a frat. I learnt that last semester altho I didn't do that. It's just meeting new people, getting away from all the programming works for sometimes and maybe even socialize with fellow programmers every so often.
3. Become a better writer, write often to blogs
I'm not committing myself to a certain time scale but it's a good skill to have and like my point 0 can't be over stated.
4. Improve my Laptop's power performance
I've been rather worried about it for sometime although it gives around 2 hours on battery but I generally don't use it on battery power. So, it often gets neglected. I've got this on my priority now.
5. Get better at managing stuff. A clean Room
Maybe I need to make a ticker or sth on my desktop for this. I need to develop this habit so that I can keep thing better organized and especially keep my room clean.

Suggestions are always welcome. I'll keep posting any updates if I have been on the track or derailed somewhere else. :)

Saturday, January 19, 2008

Busybox on Android

As good as android is, it does lack some of the rather interesting linux tools that could be of a great use like busybox. Its good to have a command line interface to play around often to get information that click around in gui which makes things a bit too slow sometimes.
While I did try to compile the busybox binary and loading onto the phone, that didn't quite work. So I got one from here.

Then I copied the binary into the tools folder

after running the emulator with ./emulator, I ran the
./adb push busybox /data/busybox/busybox
I logged into the shell with
./adb shell
# cd /data/busybox
(you might need to set permissions here if you downloaded the file)
# ./busybox --install

remember to export the path
export PATH=/data/busybox:$PATH
voila! got my busybox applets!!

Tuesday, January 15, 2008

How to make your window Full Screen in gnome?

I have often had this problem of getting quite seriously distracted while coding and I always like to use as much screen real state to work on but then again, there are other applications that need it too and it can be a lot of distraction with gmail messages popping up and all sorts of nasty stuff happening. One option is to just go into some other desktop manager but I kind of like solving the problems at hand and gnome does provide me with some really good features that I've become used to.

I started wondering if I could make eclipse full screen so that I can just focus on the code and hopefully nothing else.

Then I came across this useful link http://www.enigmacurry.com/2007/02/17/gnome-kiosk-mode-make-any-app-fullscreen supposed to be a rant about the feature gnome lacked but updated to add this instruction.
There is a nice feature that lets users set keybindings.

Here are the steps:

1. Open gconf-editor using the trusty old Alt-F2 combination

Now go to /apps/metacity/window_keybindings/toggle_fullscreen and set the Key Binding

Also, if you're using Beryl instead of metacity, this option is reasonably easy to find in the beryl settings manager: "General Options"->"Shortcuts"->"General Options"->"Bindings"->"Toggle Window Fullscreen"

As you can see, I have set it to F11.

There is a somewhat easier way to do this too using the System>Preferences>Keyboard Shortcuts tool

Find the Toggle Fullscreen mode and set the key. As easy as that. I generally prefer the gconf-editor mode because it gives more control to whatever I type. I have unwittingly changed some shortcuts from the Keyboard Shortcuts tool couple of times already to know better now :).

So, finally my eclipse screen is full.. and hopefully without distractions :P

Powered by ScribeFire.

Wednesday, January 09, 2008

Checking integrity of cdrom drives

I had this problem for a while, so I wanted to take a look at it... how do i check the integrity of the drive.
I did this... to find that it was quite okay... the same can be done with md5sum but sha1sum is better sometimes

$ sha1sum KNOPPIX_V5.1.1CD-2007-01-04-EN.iso | grep cdc0e9181d9dd2f2fc71aa9c59391001c46afa3e
cdc0e9181d9dd2f2fc71aa9c59391001c46afa3e *KNOPPIX_V5.1.1CD-2007-01-04-EN.iso
but then again, after burning the cd, I wasn't too sure if it had data integrity. So, I had to check if it was working
I tried md5sum on /dev/cdrom but that was taking a lot of time.
Then I saw a description on http://wiki.sabayonlinux.org/index.php?title=HOWTO:_Checking_the_integrity_of_a_LiveCD_or_LiveDVD

The process goes like this:
$ isoinfo -d -i /dev/cdrom
CD-ROM is in ISO 9660 format
System id: LINUX
Volume id: KNOPPIX
Volume set id:
Publisher id: KNOPPER.NET
Data preparer id: www.knopper.net
Copyright File id:
Abstract File id:
Bibliographic File id:
Volume set size is: 1
Volume set sequence number is: 1
Logical block size is: 2048
Volume size is: 356532
El Torito VD version 1 found, boot catalog is in sector 763
Joliet with UCS level 3 found
Rock Ridge signatures version 1 found
Eltorito validation header:
Hid 1
Arch 0 (x86)
Key 55 AA
Eltorito defaultboot header:
Bootid 88 (bootable)
Boot media 0 (No Emulation Boot)
Load segment 0
Sys type 0
Nsect 4
Bootoff 312 786
See the things in bold? that's the data we're interested in: logical block size and volume size. So, we just output the data and md5sum that instead of just the /dev/cdrom

$dd if=/dev/cdrom bs=2048 count=356532 conv=notrunc,noerror | md5sum
356532+0 records in
356532+0 records out
730177536 bytes (730 MB) copied, 233.479 seconds, 3.1 MB/s
379e2f9712834c8cef3efa6912f30755 -

$ cat KNOPPIX_V5.1.1CD-2007-01-04-EN.iso.md5 | grep 379e2f9712834c8cef3efa6912f30755
379e2f9712834c8cef3efa6912f30755 *KNOPPIX_V5.1.1CD-2007-01-04-EN.iso
so it works...

another method is to redirect the dd output to the iso and run diff on it.