kalyanchakravarthy.net – Kalyan’s Weblog, Rantings, Projects, Designs….and more blah


About Kalyan (me)

I am a 21yr old Student, Web Designer, Developer, Photography freak, PHP fanatic & a Tech addict. This is my online space, which would showcase my works. If you have any questions, comments , feedback or requests feel free to shoot them

I am currently working as a developer at ESPN Cricinfo.com, before which i freelanced for about 3 yrs while at college!

Read more about me »

Read the rants

Jython script to compile jython scripts to java class files

  June 18th, 2010 | In Jython, Programming | No Comments »

Jython, the python implementation in Java, is one of the most amazing things i have come across in quite some time, the environment is a seamless fusion of both the languages.

Playing around with it since yesterday, from what i have noticed, the jythonc compiler is missing in 2.5.x version of jython. But on doing a quick search i found a java based jython compiler scripts ( here and here ). Also there don’t seem to be any jython compiler scripts in jython, perhaps i maybe looking at wrong place. So i wrote up a quick script which tries to do that.

"""
Author:Kalyan (18-Jun-10)
Usage: $jython jcompile.py
"""

from java.io import *
import _py_compile
import imp as pyimp
import org.python.core.imp as jimp
import os.path
import sys

#Show info
def jcompile_usage():
	print "Usage $:jython jcompile.py"
	print "file.py gets compiled to file$py.class"

#Compile .py to .class
def jcompile_compile( fname ):
	#java file object
	jfile = File( fname )
	#Get module name
	mname = _py_compile.getModuleName( jfile )
	#Compile and get bytes
	bytes = jimp.compileSource( mname, jfile )
	#Dump bytecode into a file
	jimp.cacheCompiledSource( os.path.abspath( fname ), os.path.abspath( "./" + mname + "$py.class" ), bytes )

if( len(sys.argv) != 2 ):
	jcompile_usage();	#insufficient arguments
	sys.exit(0)			#exit

if( os.path.exists( sys.argv[1] ) ):
	print "compiling %s" % sys.argv[1]
	jcompile_compile( sys.argv[1] )
else:
	print "Given file doesn't exist"
	jcompile_usage();

The code is a loose translation of the java code. The only catch is, there are two “imp” important internals libraries, org.python.modules.imp and org.python.core.imp, former the python implementation and the later one being the java python implementation.

Usage : to compile

kalyanc$ jython jcompilec.py foo.py
compiling foo.py

at this point foo$py.class is created

Usage : To execute

kalyanc$ java -classpath .:/Library/Jython/2.5.1/jython.jar foo\$py
foo bar

.

  Tags : , , , ,

21 years of life

  April 3rd, 2010 | In General Chatter, Ramblings and Rantings | No Comments »

21 years, 21 trips around the sun, 7665 sunrises, 183960 hours of life, 11037600 breath taking minutes, 662256000 seconds, 46357920000 heart beats ( also accounting for the arbitrary unexpected losses for known reasons ), it amazes me how fast time flies.

Thinking in retrospect, all i can feel is so much has changed, evolved, come and gone in the most drastic, dramatic, unexpected,  unexplainable, unfathomable ways. No matter what the outcome has been life has left me spellbound at the beauty in which things have happened whether for good, bad, sad or worse.

Sometimes the feeling of “i wish it happened that way” multiplied with every damn thing, tries to creeps into the head, puncture the peace, but the very moment to make peace i am reminded that the very reason i am the way i am and i am what i am is only because of whatever that has happened. If anything would have happened in any other way other than the way it has happened, the very essence of what i really am right now would be lost. Though i still would be what i would have been, it certainly would be different from what i am at this instant of time.

21 for me, kinda is aptly the half of 42 ! The reason for everything being what it is being starts with us being what we are. And this last year has significantly contributed towards the understanding of myself in a better way. Sometimes feel things could have happened differently i could have done few things differently which would have changed my life for better, i don’t find myself complaining because the very reason i am myself is because they have happened.

For all those things i should thank all, who aren’t, who still are friends, who will always be, who understood my way of expression, who tried to, who didn’t. And you all know who you are.

PS: if you are still wondering whats the philosophical speech is all about, i turned 21 :)

Cheers. Kalyan

Java synchronization over multiple shared objects

  March 27th, 2010 | In Java, Programming | No Comments »

When developing a multi-threaded application in Java or any threaded environment as a matter of fact,  the first and the foremost issues that one would need to consider is synchronization of shared resources.

To synchronize a shared object or resource in java, its as straight forward as using the “synchronized” keyword while declaring a function or as a code block

public class Foo() {
	//Way 1
	public synchronized void bar() {}
	//Way 2
	void baz() {
		synchronized(boo) {
			//some sync foo
		}
	}
} 

Whether to synchronize the code block by wrapping them under a synchronized function, or a synchronized code block over the shared resource, is upto the programmer. For a single object, the synchronized code block works just fine, but when there are more than one object to be shared by multiple threads simultaneously, one of the very important thing that usually skips the mind leading to deadlocks in the execution are – keep the statements in the same order throughout the application thread.

Consider (the bad way)


final Object foo;
final Object bar;
Runnable tObj = new Runnable {
	public void run() {
		while(true) {
			//sync #1
			synchronized(foo) {
				synchronized(bar) {
				//sync foo
				}
			}

			//More code foo
			//Some more code

			//sync #2
			synchronized(bar) {
				synchronized(foo) {
				//sync foo
				}
			}
		}
	}
}
Thread t1 = new Thread(tObj);
Thread t2 = new Thread(tObj);

Note the different synchronization block order in step #1 and #2. As the execution starts, the first thread t1 obtains locks on foo in the first block, and then on bar if its free as well. Until the synchronized block execution is complete, the second thread is kept waiting for resources.

If each thread cycle is guaranteed equal execution time, it doesn’t pose a problem as the execution across different threads won’t fall out of phase. Most often than not it is not the case and each thread cycle is gets different amount of cpu time each time, and if the thread depends upon external resources such as db, files, sockets, etc, the order of execution is unpredictable.

As the execution starts to fall out of phase, Thread t1 currently executing at Stage #1, obtains the lock on foo, and requests for lock on bar. But the other thread t2 which is already out of phase might be executing at Stage #2, and obtained a lock on bar. The first thread t1 waits for t2 to release bar, the second thread waits for thread t1 to release foo, so that each can complete their execution. This leads for each thread wait for resources obtained by each other leading to a deadlock.

In an actual application scenario, the deadlocks don’t appear immediately until such an instant where the threads are executing out of phase, depending upon the application, it might take minutes or even hours.

I have come across such a situation while writing a java based multi threaded web crawler, which maintained two shared objects a Queue and a HashSet. Queue contained a list of all URL’s to be parsed, and HashSet contained the completed set of URL’s. Initially when tested with 1 thread, it just worked fine, for the obvious reason being there are no other competing threads. But when the number of threads were increased to two, it took about 10 minutes for the deadlock to happen and the program halted. Increasing the number of threads even further increased the deadlock state was reached a bit faster, the reason being the probability of increase in concurrent requests for locks.

One of the better ways of staying safe is to wrap the sync logic inside a synchronized method itself, but again one has to make sure that if there are many different functions, the order of objects should remain the same.

Similarly deadlocks can occur even when nested synchronization is done inside a loop, i.e a nested synchronized block inside a loop which is inside another synchronized block.

  Tags : , , ,

Raphael snake

  March 26th, 2010 | In JavaScript, Programming, Projects | No Comments »

RaphaelJS is an interesting SVG based javascript graphics library for the web browser, provides an intuitive and easy to use way to draw elements, animate them, add event handlers, etc. It even lets us plug in event handlers from other libraries such as YUI, jQuery. Inspite of apparent advantages in Canvas tag, one thing about SVG which can make a designer cry in happiness is, it works on IE. Period.

As i started to explore raphael for a module on espnf1, it tempted me to write a snake game as always i did when i was learning other libs such as pygame, sdl, etc.

Using just Raphael.js for the vector graphics to display the snake and jQuery for handling the keystrokes and other little things, It was entirely written in JavaScript, as a lunch time project, and timed myself at 2 hours. It can be accessed here -

http://kalyanchakravarthy.net/projects/fun/rsnake/snake.html

Feel free to view the source and do whatever you fancy.
PS : Use <space> to start, pause, resume the game. And if u feel like, post ur scores as comments

  Tags : , , , , , ,

flipkurl – php/curl api library to access flipkart.com

  March 8th, 2010 | In PHP, Programming, Projects | No Comments »

Flipkurl is a php-curl based api library to access the contents of flipkart.com site, login into it, search book listings, add books to cart, move books from to wishlist, read contents of cart, etc.

Usually shopping carts don’t persist the user’s selection across logins, but this one does. So whatever books you add via the library will stay in your account, so you can checkout/pay later from there.

Some possible uses of the API include Custom User Interfaces, Mobile UI’s, Mashups with other API’s, Automate stuff, etc.

The library is released under GPL. You can find the code, more details regarding the library and examples here – http://code.google.com/p/flipkurl

It was done as a fun weekend project.

  Tags : , , , ,

Curl & handling cookie sessions

  March 1st, 2010 | In PHP, Programming | No Comments »

Curl is a very interesting utility library which lets one connect and interact with any remote url via any of the supported standard protocol. Though curl is essentially a command line tool, various bindings are available for access via programming languages, popularly php

From a php perspective, curl can be used to remotely access any URL, login, authenticate, and perform other actions. Directly using curl to retrieve content is a no brainer like fetching rss feeds, etc.

<?php
$ch = curl_init( "http://www.foo.com/test.php");
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, 1 );
curl_setopt( $ch, CURLOPT_FOLLOWLOCATION, 1 );
$content = curl_exec( $ch );
?>

Going beyond that a common scenario can be a contacts grabber, in which the user specifies the auth details, the script logins into email servers, fetch the contacts in a usable format. More interesting applications can be interacting with payment gateways, shopping carts, etc.

This weekend has been spent with curl after long time, extracting data and fooling around with it, it just too much fun !

There are lots of examples and documentation regarding handling of cookies with php curl. But there are couple of catches which always turned into dead ends for me in the past couple of years, and i never really bothered to find way around as i didn’t needed them in the past. The curl documentation suggests you set the cookie handlers for curl this way, and usually as with any other php function relative paths should work, like this…

<?php
curl_setopt( $ch, CURLOPT_COOKIEFILE, "file.txt" );
curl_setopt( $ch, CURLOPT_COOKIEJAR, "file.txt" );
?>

But weirdly for some reason relative path doesn’t work !  Since my weekend fooling with curl needed it, on playing around with it a little and discovered that giving absolute path works, it just works. So using the realpath() makes it all easy.

<?php
//$fileName = "/home/kalyan/curlfoo/file.txt";
//or just use the real path function
$fileName = realpath( "file.txt" );
curl_setopt( $ch, CURLOPT_COOKIEFILE, $fileName );
curl_setopt( $ch, CURLOPT_COOKIEJAR, $fileName );
?>

  Tags : , , ,

Broken sight

  February 20th, 2010 | In Photography | No Comments »

I am sitting here,
with mind somewhere
wondering what in life,
am i looking at ?

though my other senses are
functional and intact
but with broken sight,
what am i looking at ?

Exif information

Camera: DSLR-A200
Exposure: 1/4
Aperture: f/5.6
Focal Length: 70 mm
Exposure Bias: 0 EV
ISO Speed: 400
Flash: Off, Did not fire

  Tags : , , , , , ,