Saturday, December 27, 2008

First flight

I went paragliding again last week, to finish my Elementary Pilot course. I had my first solo flight from a height of 45m on 24th Dec 2008. It was an exhilarating feeling, although short. After 3 days of solo top to bottoms, I now have 15 min of total air time. I'll put up the pictures soon. The sight is Shinde Wadi, around 125km from Mumbai.

I also had great fun at the Native Place, home to Nirvana Adventures. Hoping to go back in May and make progress towards Club Pilot.

Monday, December 01, 2008

Filtering QTreeView

While working on my newest project, I had a miserable time figuring out how to filter sub-items in QTreeView and its associated models (like in kopete/pidgin). The first thing to do is to use QSortFilterProxy as a middleman. The problem is that QSortFilterProxy will only search top level tree nodes.
The way to implement custom filters is to subclass QSortFilterProxy and reimplement filterAcceptsRow(). But I couldn't figure out any way to quickly access sub elements using QModelIndex, nor could I find anything on the 'net. So after quite a lot of fiddling around, I managed to get this, which works. So to save someone else some time, here is the code

bool MemberFilter::filterAcceptsRow(int sourceRow, const QModelIndex& sourceParent) const
if( sourceParent.isValid() && sourceModel()->data(sourceParent).toString().contains(filterRegExp()) ) return true;

QString data = sourceModel()->data(sourceModel()->index(sourceRow, 0, sourceParent)).toString();

bool ret = data.contains(filterRegExp());

QModelIndex subIndex = sourceModel()->index(sourceRow, 0, sourceParent);
if( subIndex.isValid() )
for(int i = 0; i < sourceModel()->rowCount(subIndex); ++i)
ret = ret || filterAcceptsRow(i, subIndex);
return ret;

On a side note, this has been a post after a long long time. This is because I've decided only to post important things or code related stuff. Right now I finished one semester of college, and will be home for a month.

Monday, October 27, 2008

Installing Arch linux on the HP DV6910TX

This is a record of my attempt to put Arch (2008.06 Core Dump) on the HP DV6910TX.
Here is my system configuration
  • Intel Core 2 Duo T5750 @ 2.00GHz
  • Ram : 3GB
  • Nvidia GeForce 8400M GS with 256Mb dedicated memory
  • 320Gb harddisk


Here was my original partitioning scheme:
  • C: 308Gb
  • D: (Recovery) ~10Gb
Make sure you create your HP Recovery Discs first!

Since the arch install CD doesn't have ntfsprogs ( it has the packages, but not as part of the setup boot ), I booted from dreamlinux (you can use any liveCD) and used ntfsresize to shrink the C: (/dev/sda1) to 35Gb.

Then I used gparted to create a proper partition layout. Here is how it goes
  • /dev/sda1 - ntfs - 35Gb (C:)
  • /dev/sda2 - ntfs - 10Gb (D:)
  • /dev/sda3 - swap - 4Gb ( to hibernate, you need atleast as much swap as your RAM )
  • /dev/sda4 - extended
  • --- /dev/sda5 - ext3 - 20Gb (/)
  • --- /dev/sda6 - ext3 - 50Gb (/home)
  • --- /dev/sda7 - ntfs - 180Gb (/shared)
After committing these changes I began the installation.

The rest of the settings were normal Arch installation procedures, which can be found elsewhere.



The dv6910tx has an nVidia 8400M GS with 256Mb of dedicated memory. Installing the nvidia drivers ( pacman -S nvidia nvidia-utils ) and running nvidia-xconfig generated the required xorg.conf, and the card worked perfectly.


Installing the synaptics package and merging the required changes into xorg.conf ensured that the touchpad worked too, including scroll areas and locking.

CD/DVD drive

Works perfectly without any configuration.


Arch correctly used the r8169 driver


Arch was able to identify the card, but there is no hotspot here to test the connection.

Card reader

The 6910 has a 5-in-1 reader from Ricoh. But I could test only for SD cards.


Detected fine,, but no device to test.

Power management

Installing Guidance (pacman -S guidance-power-manager) will allow you to quickly view battery performance and perform suspend or hibernate ( I'm using pm-utils ).
To enable different power modes ( governors ), install cpufreq and follow the Arch Wiki Page on CPUfreq.

A special entry has to be made to mount/unmount NTFS partitions. Put the following in /etc/pm/sleep.d/66ntfs:


MOUNTS="/windows/C /shared"

function 66ntfsmount() {
for i in $MOUNTS
mount $i

function 66ntfsumount() {
for i in $MOUNTS
umount $i

case $1 in

echo "BAD!"

Now make it executable ( chmod +x /etc/pm/sleep.d/66ntfs ).


Not tested yet.

NTFS partitions

I installed ntfsprogs and used the fuse.ntfs system to mount ntfs in userspace as read and write. Here are the additions to /etc/fstab

UUID=... /windows/D fuse.ntfs defaults 0 0
UUID=... /windows/C fuse.ntfs defaults 0 0
UUID=... /shared fuse.ntfs defaults 0 0

NOTE: The arch shutdown scripts kill the fuse ntfs system rather than unmounting the drives. To fix this issue edit /etc/rc.local.shutdown and insert the following:

. /etc/rc.conf
. /etc/rc.d/functions

# Unmount NTFS partitions
stat_busy "Unmounting NTFS partitions"
umount /shared
umount /windows/C
umount /windows/D


Device detected. I could scan for my cell phone, but I've yet to figure out how to exchange files.


If you use KDE4, go to System Settings -> Regional and Language -> Keyboard Layout. Enable keyboard layouts and change the keyboard model to Hewlett-Packard Pavilion ZT11xx. All the keys EXCEPT Quickplay and DVD work after that. The mute key does not turn red, but it does work. Of course it is your job to actually configure application shortcuts to use the keys.


The volume keys respond. Other keys should be configured to work with the respective applications using application specific settings.

Tuesday, September 30, 2008

Random Ramblings

Sorry for not blogging in a long time. This has been a very busy week, and so I'm just going to drop some snippets.

First RMS and Larry Ellison both commented against cloud computing.

Graffiti is uploaded and ready to use ( but not necessarily stable ).

I read Snow Crash and >loved it.

I'm confused between getting a Dell Studio 15 and HP Pavilion dv6767tx.

Meanwhile I'll be leaving for Pune tomorrow for SUMMIT '08 at MIT Pune. This is a sports fest, and I'm proud to be the only first year in the football team. This is the first time I'll be playing football as part of an official team with jerseys ( no. 2 ) and all, so it will be fun.

I'll be back on the 5th after which I will probably start with a new project. Right now I'm thinking of something like hyperlink visualizations, though I've no idea how to accomplish this.

Sunday, September 14, 2008

Graffiti is almost released

Aside from some code cleanup, testing, and writing architecture documentation, Graffiti is good to go. You can Download it

Wednesday, August 27, 2008

Reworked Graffiti's first render

After quite a few weeks of work, Graffiti has (again) reached the stage where it can render it's first words. It's now at 488 lines of code, of which the CSS related stuff itself comes in at 288 lines! There is no word wrapping yet, or any layout logic. I've been busy fixing quite a few bugs in the CSS overlays and so on.

This is how you would use it.

import pygame
from pygame.locals import *

import graffiti as g # 1


g.init() # 2

pygame.display.set_caption('Graffiti Render Test')

screen = pygame.display.set_mode((800, 600))
screen.fill((0, 0, 0))

page ='<body><p>Testing Graffiti</p></body>') # 3

page.render.on(screen) # 4

while True:
for event in pygame.event.get():
if event.type == QUIT or (event.type == KEYDOWN and event.key == K_ESCAPE):


Sunday, August 17, 2008

Nikhil meet Archlinux and KDE4

I've been home (Mumbai) this weekend and have been hacking away for the last two days to get Arch running on my external HDD, since I can't stand Mandriva anymore. The cool thing about Arch and Pacman is their flexibility. Following this guide I was able to install Arch from within my internal hdd arch, and have all the latest packages (including KDE 4.1).

There was only one problem which wasn't mentioned. External HDDs require usb support in the initrd which is not done in Arch by default. So before rebooting just edit /etc/mkinitcpio.conf and add "usb" to the line HOOKS="base udev …". Then remake the initrd using "mkinitcpio -g /boot/kernel26.img".

I must say I'm pretty impressed with KDE 4.1. There are still a few rough edges like the khotkeys keyboard shortcuts not working and some KWin effects not exactly doing anything. But overall a great effort.

Wednesday, August 13, 2008

Custom hash objects in Python

It's quite common to use strings, integers and other 'native' Python data types as hash keys. But sometimes it is much easier to be able to use your own class instances as keys. Python's magic methods allow you to do this.

Note: This is not a tip on implementing hash functions, this is how you can remove a certain layer of peeking around into objects

__hash and __cmp__

Consider a useless HTML parser with a simple node design where you want to associate the node name with its attributes.

You want to use the absolute node name as a unique hash.

The solution is to define custom implementations for __hash__ and __cmp__, two magic methods. For more information and constraints about them take a look at the Python docs.

The builtin functions hash(obj) and cmp(obj1, obj2) will attempt to call there __underscored__ counterparts on objs.

import UserDict # allow NodeAttrs to behave like a dictionary, not significant for this example

class NodeName(object):
def __init__(self, name, parent=None): = name
self.parent = parent

def __str__(self):
return (parent and str(parent) or '') +

def __hash__(self):
# the hash of our string is our unique hash
return hash(str(self))

def __cmp__(self, other):
# similarly the strings are good for comparisons
return cmp(str(self), str(other))

class NodeAttrs(UserDict.UserDict):
def __init__(self, attrs={}):

Where we assume that the parser is doing the heavy lifting of parsing the name, and putting the attributes in a dictionary. Now to use this in a dictionary you would do the following:

>>> d = {}
>>> d[node_name] = attrs # node_name is an instance of NodeName and attrs

... # do anything which can be done to a dictionary and its keys

Thats it! For more magic methods see Python __Underscore__ Methods

Monday, August 04, 2008

Sierpinski, my first fractal

The Sierpinski triangle in Python, inspired by HTDP, and using Pygame

import sys
import pygame
from pygame.locals import *

class Point(object):
def __init__(self, x, y):
self.x, self.y = x, y

def distance_sq(self, other):
return (self.x-other.x)**2 + (self.y-other.y)**2

def distance(self, other):
return sqrt(self.distance_sq(other))

def tupl(self):
return (self.x, self.y)

def midpt(p1, p2):
return Point( (p1.x+p2.x)/2, (p1.y+p2.y)/2 )

def too_small(p1, p2, p3):
return max([ p1.distance_sq(p2), p2.distance_sq(p3), p3.distance_sq(p1) ]) < 5

def draw_line(p1, p2, surf, col):
pygame.draw.line(surf, col, p1.tupl(), p2.tupl())

def draw_triangle(a, b, c, screen, col):
if too_small(a, b, c):
a_b = midpt(a, b)
a_c = midpt(a, c)
b_c = midpt(b, c)

draw_line(a, b, screen, col)
draw_line(b, c, screen, col)
draw_line(a, c, screen, col)

draw_triangle(a, a_b, a_c, screen, col)
draw_triangle(b, a_b, b_c, screen, col)
draw_triangle(c, b_c, a_c, screen, col)

screen = pygame.display.set_mode((640,480))
screen.fill((0, 0, 0))

draw_triangle(Point(10, 10), Point(630, 10), Point(310, 450), screen, (255, 0, 0))
draw_triangle(Point(50, 10), Point(630, 240), Point(310, 0), screen, (0, 255, 0))

while True:
for event in pygame.event.get():
if event.type == QUIT or (event.type == KEYDOWN and event.key == K_ESCAPE):


Great Weekend

So my second weekend in this place went pretty great. Now that I've found the right computer which easily boots from external devices I'm ready to slowly begin coding. On saturday five of us saw Ugly and Pagli — crappy movie — but I got my first pair of studs. Its been raining a lot for the last three days here. It starts at around 7 and goes on till late into the night, which means a lot of fun football (I've discovered that playing barefoot is better than playing with normal shoes), but being cooped up in the rooms afterwards.

I also made some headway into How To Design Programs which is a really great book, and read almost all of Joel On Software (the book) which is entertaining to say the least.

So right now I'm sitting here after attending a particularly boring calculus lecture. I haven't had a bath because there was no water, and I'm reading a boring story as part of the assignment for Communication Skills.

Right now I'm replanning Graffiti since I wiped it out a few weeks ago. I've also been messing around with Scheme, but can't think of what application to write to dig deeper into it.

Tuesday, July 29, 2008

A bit of improvement

I'm in the institute lab right now, booting from a pen drive (Slax). But tomorrow I'll get my external HDD and plug it in and try to be productive. These labs are only meant for 'academics' which means there are caps on downloads, so I can't even download firefox without it being interrupted. Also we haven't got our IDs yet, so this connection is thanks to a senior who was kind enough to let me use his account.

Also there is a firewall/proxy which means no IM sites or IM protocols are allowed. This does kind of suck, but it is better than nothing. And this is only till December ( or so I hope ). Cheers, I'll update this tomorrow.

PS. No CD drives on any computer, how do I install Arch? Probably go home and do it

Monday, July 28, 2008

Still no computer

So the second time I'm in a cyber cafe. In certain respects private universities aren't much better than public ones. We still haven't got ID cards, which means no net/linux access. Which means no coding too.

Other than that its been pretty good, playing football and table tennis. But a bit tiring too. Its been raining a lot today, which means there isn't much to do. We had the first couple of lectures today, but nothing new was taught.

This is boring, but the situation is likely to improve in a few days.

Friday, July 25, 2008


Well, I'm here, or I've been here for 5 days now. Since we haven't got ID cards yet, there is no computer access, so I'm writing this from a cyber cafe. The last few days have been a bit boring. With no studies, playing and reading seem to be the only things you can do in 24 HOURS!.

I haven't written any code in days, but I have managed to read Hutton's Haskell book, which is really good. This place's library is awesome for all the computer science/programming related books they have, now I just hope I'll have linux access in the labs. For atleast four more months personal computers are not allowed in the rooms. So it might be next year (read Jan 2009) before I actually have my own computer again. Till then I'll just hang on to the external harddisk.

Thursday, July 17, 2008

Graffiti: disaster

I Gitted Graffiti yesterday, and made an error in adding the files to version control, so I decided to undo the changes and because Git complained, I added -f.

git rm graffiti -rf

BOOM! Graffiti is gone.

Except for the basic style parser which I was writing at that time, which was saved by Kate.

I'm not blaming Git, just my stupidity.

I usually don't version control as soon as I begin a project, since I like to get the structure right, without having really bad log comments. From next time, versioning first.

In retrospect this is a really bad week. Experience isn't the most fun teacher.

Programming: The invisible wall

In the past few weeks, as I've tried and failed at various projects, there has been a realisation that you can only go so far with random reading and coding.

The first few years of programming are spent coding projects pretty minor on the algorithms/data structures side.

But when you finally start growing out of it and when 'cool' projects for you start to become more complex, a seemingly invisible wall smacks you. The wall seperates amatuer and scientist. And unless you are/I am prepared to study, that wall isn't gonna give way.

Crossing the wall is going to require some serious studying, where I actually try to solve the exercises at the back of Algorithms rather than just read the book. At college I'll probably be able to get my hands on a hard copy.

And once this wall is broken, there will be more walls to break.

A failure in the codejam or how I blew up my brain

Thursday morning, I saw the problems and took a printout of the Flyswatter. Then I spent about 3 hours figuring out the right area calculations, without success.

Then I tried hacking away at the other 2 problems for a total of 1.75 hours. Again failed.

Result: A total brain burnout

Feeling: Really down for my not so leet algorithmic skills.

Lesson learned: I seriously need 4 years of formal computer science education.

Monday, July 14, 2008

Graffiti and more

It turns out parsing CSS according to specifications is no mean feat. So I am going to stall that for a moment, or implement a bare bones parser specifically written for Graffiti, and just plow along with Graffiti and doing what I can do, properly.

Maybe later ( read quite a few months ) I'll write a nice SAC compliant CSS parser and hook it into Graffiti.

Whatever I want to do, things aren't going to be moving fast. On Sunday I'm leaving for university ( DA-IICT ) and that involves a lot of pre-leaving things to do. And the week after that will go in getting settled there and taking a look at the computing facilities. I'll probably be taking a external HDD with all my files and I might just do a blind copy of this hard disk itself so I can boot Arch their if it is allowed.

Thursday, July 10, 2008

Always Turn Left

This is with reference to the Google Code Jam practice problem.


This problem initially seemed vexing. After a little bit of thought about using bit twiddling to represent directions, generating the right codes was easy.

If you have any experience with hexadecimal numbers, it should strike you that the direction table with 4 directions each of which can be yes or no, is a big hint that bit twiddles are exactly what is needed. Which means powers of two

N, S, W, E = 1, 2, 4, 8

Now I'm not going to show how you combine them, but here is how you get the code directly in Python ( somewhat similar in C ):

def code(dirs):
return '%x'%dirs

After this I scribbled a lot on paper, mapping the small input to the maze. It was easy to figure out that the problem could easily be solved by going both ways because always turn left means that you will visit every part of the maze if you go both ways. I wasted a lot of time thinking how to orient the grid, until I read the specification that the entrace is always at the north.

But there was another problem, how to generate a perfect size grid for a dynamic problem like that. I didn't want a 10000*10000 grid all the time, that would be very inelegant. First I tried using links for each Cell, but the problem is resolving W-E or N-S relationships would involve backtracking to find the adjacent Cell. This flummoxed me for a LONG time. Then I read João's idea [perfect maze size] and it hit me like a rock. This problem really requires you to break some preconceived notions, like a multidimensional array being the best representation for a Grid. A dictionary with coordinates as keys turned out to be perfect for this problem. After this the solution was dead simple, walk forward, preserving the right coordinates, then turn around and walk back, overlaying existing directions with new ones you find.

Write a simple comparator function for coordinates, and use it to sort the grid and print it, and you have the solution in Python

In general the practice problems are creative, all they require a bit of common sense, some unconventional thinking and perhaps a few years of experience. Mainly it's about how elegant your code can be. I'm just hoping the real ones will be easy too. But irrespective of that, I'm not qualified to receive even a T-shirt, since I'm under age.

Saturday, July 05, 2008

Book Review: The Curious Incident of the Dog in the Night-time

The Curious Incident of the Dog in the Night-time by Mark Haddon is a crime novel. Except it's written from the point of view of a 15 year old autistic boy.

This book was actually released in 2003 so I'm a bit late for the review, but I just stumbled upon it a few days ago at a friend's place. And the bright colour and really long rambling title really intrigued me.

So, meet Cristopher Boone, who wants to be an astronaut, loves animals more than humans, has a photographic memory and brilliant logic but can't tell what other people feel and has no notion of metaphors and cultural references. Unlike many of us he cannot follow the 'I am thinking about what you are thinking about what I'm thinking' process that often happens. The only concept of emotion he has is a list of emoticons expressing common faces.

Haddon does not try to invoke pity, Christopher is in no way purposely projected as someone worse than us. He lives with his Father and thinks his Mother is dead. When his neighbour's dog is killed he sets off to find the killer in an independent manner, in the process escapes to London and comes to reality with the fate of his Mother.

Since the story is told from his view, and his lack of emotion and future projection means that he has no reason to lie leads to a very truthful story, even to the point of making normal readers squeamish. He writes about poo, and sex and swear words with no change in tone than if he was talking about the weather. He doesn't feel death when he narrowly misses it and when he gets an A grade in his Math A-levels the only thing he feels is

At 134 pages the book is a quick read and there is no actual crime-solving but Christopher's need to fit into the world is very well written and a window into the mind of autistic people. At the same time it lets us marvel at the beauty of our brain to reject so much information and yet generate so much of its own with no bindings to any law.

Along the way the book has a sprinkling of math, including naming all chapters with prime numbers. Christopher almost always goes on cubing natural numbers or mentally calculating powers of 2 just to overcome nausea.

I doubled 2's in my head because it made me feel calmer. I got to 33554432, which is 225, which was not very much because I've got to 243 before, but my brain wasn't working very well.
-- Christopher Boone

But at the core the book is humourous with Christopher's long rambling sentences and attention to details leaving you chuckling. Mark Haddon has done an excellent job.

Friday, July 04, 2008

He stole the words out of my mouth :)

CamenDesign: A List Of People Who Need To Stop Writing Software

I'd also add Creative Nero, Adobe PDF Reader and Falcon.

Half of "Windows Pain" comes from the crummy applications sitting on top of it.

Wednesday, July 02, 2008

Graffiti first view

Word wrapping is now implement and I've got a fairly decent design for the first version

So here is the client code it took

import sys
import pygame
from pygame.locals import *

import graffiti as g # Line 1

g.init() # Line 2

s = g.spraybuilder.parse_string(

Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean id diam. Curabitur lectus. Nullam ultricies ultrices tellus. Praesent id turpis vitae lorem varius posuere. Donec id diam. Nam risus sem, aliquet ac, dignissim eget, aliquam ac, dolor. Aenean lacus metus, eleifend eu, elementum ut, lacinia non, nisi. Morbi odio. Aenean id massa. Ut arcu urna, elementum et, iaculis ac, lacinia eget, dolor. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Maecenas eleifend facilisis dolor. Quisque eget nulla. Sed ut eros. Maecenas ut diam. Nullam tellus urna, sodales ac, cursus nec, tempus ac, purus.

Aenean malesuada est quis velit. Nulla vitae nunc. Integer gravida. Curabitur purus velit, egestas quis, aliquet quis, mattis ac, orci. Aliquam ac lectus. Mauris congue orci faucibus est. In orci odio, sodales at, pretium nec, dignissim et, neque. Suspendisse potenti. Fusce eget ante. Etiam purus ligula, placerat tempor, pellentesque quis, tincidunt accumsan, turpis.

) # Line 3

surf = g.spray.SprayRenderer(s.sprays[0]).render() # Line 4

pygame.display.set_mode((800, 600))
pygame.display.set_caption('Spray Rendering')
screen = pygame.display.get_surface()


while True:
for event in pygame.event.get():
if event.type == QUIT or (event.type == KEYDOWN and event.key == K_ESCAPE):

screen.blit(surf, (50, 50, 800, 600)) # Line 5

to generate this

I'm doing a bit of internal access in Line 4 right now, but that will be fixed.
If the design remains good, it should remain that easy ( just 5 lines! ) to use for all time

Sunday, June 29, 2008


A new project of mine is Graffiti, a library over Pygame which allows application developers to write HTML and some CSS-like styling information and let Graffiti manage styling and rendering. It's no Gecko. Just something to solve an itch of handling word wrapping and styling in raw Pygame/SDL. The distinction between CSS and CSS-like is important and will be explained later. Write now I'm just on basic API design with no CSS parser, and all styles currently encoded in source. But I'll do it eventually, in a few days if there are no distractions

Public thin clients

Another cool new idea, and this time it is seriously cool ( unlike this ), though it may not be feasible with today's technology and economics. So here it goes:

Everybody has a cellphone these days, most of them support Internet access and they are pretty powerful in terms of processing power for most of the things anyone does on the web.
But I for one hate browsing on that disgusting little screen and typing URLs on the keypad. Even the iPhone can't match the joy of being able to view the entire page at once and still read every word. Maybe these are just my aesthetic idiosyncries but I like to be pampered.

So we have a collection of TFT touchscreens ( called PDA - Public Display for All ) all around us in public. They could look just like whiteboards. All you've to do is go near one and (assuming there is no queue) hook your cellphone up to the PDA using Bluetooth or some protocol not yet invented. Which means your data is available on the move, but you still get great visualisation and interaction. Once your work is done, you just leave and the phone disconnects itself.

Suppose your friend has this really cool video that you'd like, both of you latch onto the PDAs and drag-and-drop the photo.

The PDAs have absolutely no memory or trace of 'who' connected with them, they just display output and take input and pass it on to the anonymous user.

Additional features can of course be added:
  • Restrictions on how much time one person can use it, we don't want hoggers/freeloaders.
  • Privacy features like PDAs in phone booth like structures for all your secure transaction needs.
These could be charged for, free on advertisement based models or just paid for by the government as a public service ;)

I hope anyone who implements this before I grow up or the technology isn't available yet will please thank me and give me a share of the profits.

Thursday, June 26, 2008

DA-IICT decision

Today I'm leaving for Gandhinagar, to take a look around the DA-IICT campus and if seats are available, get in. Hoping I will, it has a great campus and faculty and, in a way, Gandhinagar is pretty close to home.

Sunday, June 15, 2008

New concept, old language. New language, old concept

So this is something I just bumped on while reading Monadic Parser Combinators. After reading a few pages I thought I should do this practically. Unconsciously I decided to use Python. I could very well have used Factor, since it is more functional.

This led me to realise that I should take one thing at a time.

Two new things at a time == frustration

I'm already finding Factor pretty tough. Its got a really hard curve and some of the concepts which simplify the language need some pretty solid comp. sci. education. Implementing monads or parser combinators in it would have been horrible, because I don't understand them either. It can get very very frustrating, it's like writing a science paper in, say, German when you're just learning in it.

Frustration kills learning

But I'm comfortable with Python. Except for a few things I haven't tried (decorators), the language and its limitations are known, and logic flow emerges naturally.
So I'm free to concentrate on absorbing
the new concept instead of trying to make it fit to the language.

What all the above verbosity essentially wants to say is that it's hard to learn two things at once.

Friday, June 13, 2008

URL memory

I'd like to add a new member to spatial, visual and verbal memory groups. The new one is URL memory.

URL Memory(n) - the arcane talent of unconsciously remembering all human readable URLS.
Usually predominant among power users only.

How cool is contextfree!

This is all it took:

startshape sun

rule sun {
sq { }
36* { r 10 } sq { }

rule sq {
SQUARE { hue 46 saturation 250 }
sq { x 1 y 1 s 0.8 brightness 0.4 }

to make this:

This is slightly context free

I've recently (re)discovered Contextfree, so here is Contextfree 103. Its a ram wearing a hat, w/o a face.

Here is the code

startshape foo

rule foo {
hornleft { y 1 b 0.2 }
hornright { y 1 r -90 b 0.2 }
TRIANGLE { size 0.8 y 1.5 b -10 }

rule hornleft {
CIRCLE { size 0.7 }
hornleft { x -0.3 y 0.3 r 30 size 0.8 b 0.1 }

rule hornright {
CIRCLE { size 0.7 }
hornright { x -0.3 y 0.3 r -30 size 0.8 b 0.1 }

Thursday, June 12, 2008

Pypes beta, please try it out


Extract the archive, switch to the directory and run or if you are on windows cd to src/ and run "python".

You should have Python and Pygame ( Numpy is not required ).

You'll notice that one of the pieces is green, others are red. Any piece which connects to the green one becomes green, and propagates. Your task is to rotate the pieces to make a complete green grid. There shouldn't be any disconnected branches, the entire structure should be one, without any loops. If you see loops or disconnected branches, let me know.

Mouse click to rotate pieces. To resize the grid, press R and then use the arrow keys. pressing R again will bring you back to play mode.

Wednesday, June 11, 2008

Meet Pypes

Pypes is almost done, except for the loops, which shouldn't be there. Have a screenie.

Yahoo! free up my form

If you use 'Tab' to quickly move between form fields then I'd say that its now muscle-memory to 'type username. press tab. type password. press enter'. Well yahoo manages to break it, by introducing a linked email id, right between them. which means i end up typing my password twice. Its 2008 people! If you don't know what to type in the username box, you shouldn't be using it.

Saturday, June 07, 2008

The cooldown

This year's hot hot summer is finally drawing to a close as the rains have finally arrived in Mumbai. This has led to a nice drop in temperatures which means I went the entire day yesterday without getting sweaty even once! I love the rains! The football, the volleyball, and now Euro 2008...

Saturday, May 31, 2008

@ the Native Place: Paragliding

The actual paragliding while pretty less in the amount of time was a lot of fun. It was hard work too.

Day 1 involved learning the parts of the glider and wearing the harness, opening the wing and setting it up. This was followed by about 15 runs from forward launch trying to hold the glider dead centre. Then we moved to a downward slope. By the end of the day, after carrying quite a few kgs for a few kilometres I was totally exhausted. Not to mention all the friction burns on the arms. So it was good that a hot cup of soup awaited us at home.

Day 2 was an early morning rise. Fortunately we went to a landing site instead of takeoff site at Shelar and practised a few runs. This was my first lift ( ~ 3 feet ) and also the first fall. At these moments when you first learn something there are so many things going on in the mind. Like riding a bicycle you keep doing a hundred things wrong or in excess or just not enough. Yogi kept telling everyone to FEEL the glider. And everyone was 'feel what? Is this some Jedi thing?'. But just like riding a bicycle some things slowly start to seep into the unconscious and muscles start thinking. By day 2 this was beginning to happen to some extent.

Day 2 in the evening was another set of runs finally followed by some bunny hops. By the end of that day I probably sustained permanent wrist damage due to lifting badly formed mushrooms and heavy paragliders.

Day 3 had the morning for theory. This involved watching a video about all the crap rules and conventions, stages and system of teaching/learning paragliding.

Day 4 had nothing important to say except that I flew pretty much perfect

Day 5 was a big day. First the written test for the P1 stage in which I managed to scrape a pass mark ( 16/20 ). The evening had pathetic winds which means we had about 3 bunny hops before we packed up and went up the hill to the 70m top to bottom launchpad. But the strong winds meant that we only got a tandem. Ofcourse I was allowed to use the brakes and bring in the glider for landing. But the view from the top was amazing, and the rush of air when skirting a ridge is worth its weight in gold. I'm going back ASAP!

Ofcourse since we didn't complete the required solo flights, I'm not a Elementary Pilot. All of us had a paltry 7 minutes of total airtime over 5 days... :(

Thursday, May 29, 2008

Changes while I was away

So I was totally disconnected from the outside world for 6 days. There have been a few changes on the Net. First Reddit has a new design with more colours, though for some reason it appears cramped to me. Orkut has a TLD for India. KDE caused a bit of a stir

@ the Native Place: Getting started with Paragliding

I took a 5 day break from my monotonous boredom to go Paragliding. First time pilot, no experience. The location was Native Place, the base for Fly Nirvana, at Kamshet.

First it was absolutely worth the money and the remote location and the bad roads. We had a hell of a great time. We ( me and cousin ) were lucky to meet two other people of a similar age - Rishabh and Apoorva.

For the first three days, I jotted down small notes on my cellphone, so here they are paraphrased. I'll recount the trip in detail in more posts. There will be quite a few of them.

24th May

  • 1:30pm - finished lunch. sitting in a hammock. leave for practice at 3.
  • 8:45pm - drinking soup. shoulders hurt, arms burned by friction, crap it was fun. ( This was first practice, ground handling and forward launch @ Shelar )

Shelar hill - our paragliding site

25th May

  • 6:23am - awake for 20min now. last night's bath will suffice. not much pain, shoulders tender though, will risk short sleeves ( For all 5 days we established a convention to only have a bath at night, although we could have used 2 a day, we were just too lazy )
  • 11:42am - more ground handling, got a few pushes to go about 3 ft in the air. fell once. rishabh had an encounter with a bush. Also practised Parachute Landing Falls - hopefully I'll never need them. I wore a long sleeved t-shirt after all.
  • 8:37pm - back to base from Shelar. Began bunny hops and short flights. upper body is crap ( it hurt so much! ) . chest jarred ( did a bad landing, the harness locked the jerk in ) . old injury haunts. ( this is something stupid that has been bothering me for 4 years now, some internal muscle out of place )

26th May

  • 8:54pm - another day of bunny hops. good success rate this time. stupid radio fails... sorry ravi :( ( The radio got switched off and I couldn't hear instructions when everyone else could here them. Ravi [ instructor ] was helping another student, and I bumped into him before killing the glider )


A Jenga structure just before it fell. We built lots of these, one went 13 storeys. ( Yes, those are fresh gooseberries at the back! )

Monday, May 19, 2008

Markdown and Pypes

For some reason I've decided to take on two really difficult projects. One is the markdown convertor. As I ranted below, I've been stuck at various dead ends. So I've been studying the Lua source. It uses minimum pattern matching and some line scans. That might give me some headway into a proper parser in Factor.

Pypes is based on Pipes, a mobile game I'm addicted to. Now it may not be very difficult, but generating unique structures will take some thinking...

Friday, May 16, 2008

Markdown what does it take to parse you

Its been 4 designs trashed since I've got this need to write a Markdown to HTML convertor in Factor. The catch: I don't want to use regular expressions. I'm trying to make it really generic but some stupid edge case comes along and crashes the parser. Talk about morale sapping. Particularly when I'm already quite frustrated. This is the only frustration which I can rant about in public.

Thursday, May 15, 2008

Gold-titanium alloy man

I just saw Iron Man, almost 2 weeks after its release due to certain circumstances.

And it is bloody good! Great special effects and acting. What I really loved was the believability, that that suit is really possible with today's technology (almost). Also there was a certain depth of character, not just good-guy-bashes-macho-egoistic-bad-guy.

And the script writers did well to put some humour. The best was probably the excess charge on the repulsor thing which resulted in Stark hitting the walls.

Perhaps it was too realistic, there wasn't any stunned expression as I left, the kind that happens after living in a fantasy world for 2 hours. 4/5

Monday, May 12, 2008

BITSAT bitsad

I gave BITSAT today, and got a score of 304/450. Considering the cutoffs for the previous year, I might not get CS, unless everybody finds the exam tougher.

With that done, I'm free, free for around 15 days after which all the results will start coming in.

Oddly I'm still not out of the exam mindset.

Friday, May 09, 2008


Great song to listen to when um... well you'll get the point after reading the lyrics

Death Cab for Cutie

The Atlantic was born today, and I'll tell you how
The clouds above opened up and let it out
I was standing on the surface of a perforated sphere
When the water filled every hole
And thousands upon thousands made an ocean
Making islands where no islands should go (oh no...)

Most people were overjoyed; they took to their boats
I thought it less like a lake and more like a moat
The rhythm of my footsteps crossing flatlands to your
Door have been silenced for evermore
And the distance is quite simply much to far for me to row;
It seems farther than ever before (oh no...)

I need you so much closer...

So come on; come on...

Thursday, May 08, 2008

Chyrp: Bloody good design

Chyrp has a great black design

Eating with my hands

As far as I know there are only three styles of eating: hands, chopsticks, knives and forks (spoons are universal).

And if you had to categorize what to eat with what, it would be

Hands: most indian food, fast food

Chopsticks: Oriental, South East, Asian, Japanese

knives and forks: most of the western world

So I find it pretty funny when people try to eat Indian breads which are flat and non porous with knives and forks. The forks don't pierce very well, the knives don't cut very well because the structure of the bread is different. It's all great to appear well educated in table manners, but I'll stick to my hands. Certain things are made to be eaten in a certain way.

Wednesday, April 30, 2008


I have a bloody cold

I read packrat parsers in Haskell [PDF], and understood only about 25%.

I read 'Do androids dream of electric sheep?' by Philip K. Dick and 'In search of Schrödinger's cat' by John Gribbin and understood both.

I also got a deadtree version of 'Programming Pearls' by Jon Bentley

I still have two exams to give.

I am still having some trouble with parsing Markdown in factor.

I am an egoist for starting all the sentences with I.

Sunday, April 20, 2008

opensocial recent tracks

After two days of OpenSocial hacking, here is my app, which fetches the users Recent tracks and displays it on the profile. Now since there is no way to directly fetch the username, I had to resort to asking the user. Also 1.0 although usable has a few errors which aren't handled smoothly. But they do not pose security risks. For now its in the sandbox, if you have access you can view it here Recent Track and give me some feedback. It won't be on Orkut for a few days since there is a pretty large queue for applications waiting to be moderated.

Oh yeah, here's the project page on Google Code.

Thursday, April 17, 2008

Firefox feature request

I love to hack URLs to navigate the web, especially for sites with clean urls. What I'd love is if Firefox could hack the address bar text field so that the slash '/' is the default word seperator, instead of the usual space. This way just pressing Shift + Left/Right Arrow would allow power users to quickly select clean url tokens and edit them faster. This could even be improved so that the ampersand '&' is also a tokenizer.

Why haven't I posted this on Mozilla's bug tracker as a feature request, because I don't want to create an account, and I'm hoping that some reader who has one will do it for me :p

Tuesday, April 15, 2008

OOXML: The public doesn't care

The past few months, the web has been buzzing with criticisms of OOXML. Every geek with some unbiased and proper understanding is against OOXML. Now the International Suckups Organisation has ratified it as a standard, which means people will most certainly use it if the decision isn't revoked in a few months. The thing is that for all the non geeks Microsoft is this demi-God and if it makes a standard they are going to use it. They don't care how bad it is, how long it is, or how it was standardized in a corrupt manner. They will just squeak along "Ooh! its by Microsoft, lets use it."
Now what the community should be doing is to spread FUD about Microsoft the way it does about us. Unfortunately, we know to stick with the ethics of the industry/world. Fortunately we atleast aren't losing our decency to make money or acheive world domination.

Slashdot, ISO calls for OOXML ceasefire. This reminds me of the HD-DVD key fiasco on Digg, they are just telling people to start screaming.

Sunday, April 06, 2008

Choosing the right defaults

A big part of creating a good user experience is choosing the right defaults. A calendar is a particularly striking example. When you use a calendar widget to fill in a date, the context should determine a reasonable default date.

If you were booking a plane ticket, today's date would be a nice default.

But if you are entering your birth date, today is so NOT a good default, but it is seen here

This was found at which is a page for an exam in India. Now who gives an exam on the day they are born? This should ideally be 1990 since the majority of people giving this exam will be 17/18 now.

So choose good defaults

Thursday, March 27, 2008

2 things pissing me off right now

Microsoft, for their persistence in monopolizing (?) document formats, and hounding countries which reject it [1]
And of course its associated allies in the NASSCOM, and the Indian media, who are Microsoft's pet dogs.

China, for all the shit going on in Tibet and for all the human rights violations going on behind closed doors. Boycott the Olympics! ( Hey china? will my blog be blocked now? )

Tuesday, March 25, 2008

Why Java sucks : Highly subjective

Java was the first language I learned properly. I cobbled together stuff in BASIC for a few weeks, but for Java I bought 2 books and programmed a lot of stuff. That was 4 years ago, I was young, not so experienced, and Java was God to me. It was cool, it had GUI libraries, and lots of people used it. And the WORA concept was quite cool to me then.

But since about a year, Java is slowly moving from Cool to Crappy in my dictionary.
Some how the whole thing seems to be a plot to let mediocre programmers take over the world, cobbling together 'stuff' in their spiffy IDEs. ( Yes there is some good software, Azureus is one that I have experience with )

To me the very fact that a language needs an IDE to get any big stuff done is a big turn off.


Every shitty small task needs a framework. Bloated pieces of shit with so many classes and fancy UML diagrams that it gets boring to even learn them.

And there are so many IDEs and so many addons that I'd probably waste a lot of time finding the perfect tool, before I started coding.

Code Noise

Java programmers seems to have this penchant for Really.Long.Names.In.DeeplyNestedPackages.

Design Patterns seem to be a half-hearted cure for the disease that is Java. I mean how many other languages do you know where people actively use the term Design Pattern. You have these big classes, with big names that basically convert one thing to another. Like AbstractFactoryDecoratorSingleton ??

Then there is the need to type a lot of stuff for something which should be simple. Where other languages have print, Java has System.out.println. I don't care about preserving your heirarchy! I want to print quickly. Where other languages have open("file") Java has

try {
f = new FileReader("./words.txt");
} catch (FileNotFoundException e) {}
BufferedReader in = new BufferedReader(f);

Even C/++ is not that bad. Even assembly is better considering its level

Java also has too many acronyms. JNI, EJB, JEE, AOP, ORM, JDBC, DAO. This again is due to Java's corporate nature. You should have realised by now that I'm quite against corporate programming :). I mean isn't Swing much cooler than SWT/AWT.

Less Code, more on How to Code

Apart from the Code Noise, Java programmers are forever arguing about the (de)merits of Agility, Aspects and Models.


In Java almost everything needs double or triple wrappers and lots of passing around. Supposedly for security, but most probably to prevent lousy programmers from messing something up. There are so many things you can't do. Considering the context that Java aims for, in web services and desktops and games rather than mission critical application, I'd thought that keeping things simple and flexible would be much better. I'm not saying dump the type system, but simplify the APIs, lose the structure, drop the formality. I think Python and Ruby have done this very well. The only bit of humour in Java seems to be 0xCAFEBABE.

Give me duck typing any day.

BEFORE YOU COMMENT, THIS IS SUBJECTIVE, MIND YOUR LANGUAGE. You can call me a egoistic ignorant moron, but not something which would make a profanity filter shudder.

Tuesday, March 18, 2008

the Music that makes me

Music has only recently become a great thing for me. Till age 14, I didn't listen to music. Then for two years I only listened to about 2/3 bands. It was only this year that I really got into music. And the indie scene just captured me, so almost all the bands below are indie rock/pop. I haven't listed all the artists, just my Top 5 and their Top 5 songs. ( Profile )

  • Arctic Monkeys - Mardy Bum, Fake Tales of San Francisco, The View from the Afternoon, This House Is A Circus

  • Bloc Party - Helicopter, Uniform, Skeleton, Hunting For Witches, Luno

  • Radiohead - Paranoid Android, Just, Bodysnatchers, Jigsaw Falling Into Place, Street Spirit ( Fade Out )

  • The Arcade Fire - Black Mirror, (Antichrist Television Blues), Neighbourhood #1 ( Tunnels ), The Well and the Lighthouse, Black Wave Bad Vibrations

  • The Strokes - Reptilia, Automatic Stop, You Talk Way Too Much, Alone Together, Take It Or Leave It

I'm free, not, I'm FREE!

The board exams were over yesterday, and I was surprised that it wasn't really as euphoric as I thought it would be. Somehow studying, atleast for some time was pretty cool, writing the exams was fun, it was kind of like being pumped with adrenaline and keeping it in control. And now thats never gonna happen again. Its not like I'm having some huge attack of sentimentality, and of remembering all the cool times in school/college, its just that the relief is not as it should be.

So some guy said "It's more satisfying to want something, than it is when you get it", I can't remember who, so if you can, please comment.

In other news, I've got a couple of long posts lined up which I'll complete if I stop procrastinating ;)

Friday, March 07, 2008

.57142857 way through

Hey the name's KodeClutz, I had to be precise.

4 papers down, 3 to go, after which I'm one step closer to freedom, and quite a major step because all the exams after that are just one day affairs, 4 of them.

In going stupid, I'm thinking of writing a Markdown parser in Factor. The problem isn't Factor, I'm just not that well qualified. But I might just do it.

Thursday, February 28, 2008

The end of e

After a long life of wandering and explaining a lot of things, e was trying to figure out what class of numbers to put himself in, then he realized he was transcendental and went to heaven. Unfortunately he got stuck in God's pie and died with the taste of lemon. R.I.P. e.

Qrappy Quotes 3

One man's embarassment is another man's fun


Board exams begin from tomorrow. I'll be having fun for 18 days. The situation is really starting to hit.

Wednesday, February 27, 2008

If Programming Languages were Lego...

  • Assembly would be a huge set of 1x1 blocks. You could do everything other blocks could do, and more, but it took a lot of time and planning to put them all together the right way.
  • C would be 1x1 with a few 2x1 and 4x1 thrown in for convenience.
  • C++ would be just like C, but there would be all these new highly specific pieces which would only be used by a few people. Of course, there would be a large collection of prebuilt objects like roads, and doors and windows, and roofs that you could put together.
  • Java would be a set of Duplo. Easy to learn, but bulky, crappy, and basically needing about 2 layers of blocks below your own to be able to do anything useful. And you would need all kinds of wrapping objects to reach to a particular height, because Duplos are twice the height
  • Python would be a mix of Legos and Technic, easy to read, yet able to do all kinds of complex cool stuff you wanted too. But each part would be made out of silicone, to be moulded to almost any kind of arrangement.
  • Ruby would be like Python, but with a added Framework and a community with their own Religion.
  • PHP would be what happens when different Legos end up mixing on the floor. You would have thousands of pieces, but gluing them together would be difficult, because you wouldn't know what they were called.
  • Factor and other stack based languages, would be the dark horses. Lego bricks with connectors on only one side. Fun to use, but a bit challenging as well.

This is a work in progress, I haven't got all the right comparisons yet.

Monday, February 25, 2008

Spartan Spartan

This guy was doodled in my Physics notebook for a long time, I chanced upon him yesterday, and decided to give him a life. SPARTAAAAAA!!!

Sunday, February 24, 2008

USA: a light wave

At the risk of sounding really corny, the US is like a light wave, it interferes in the internal affairs of other countries, diffracts situations to its own needs and polarizes the world about every issue.

Saturday, February 23, 2008

3 levels to go

Now I understand why developing and third world countries have such low contributions to the sciences and other creative stuff which contributes to global human potential. Because only a small percentage of people have the resources to reach the 4th and 5th levels. Most of the population is on par with animals, sometimes even lower. It's sad, isn't it, that ironically the lack of resources gives rise to people who have a 'me-me-me' mentality. Even when they get the resources they aren't willing to put their knowledge into practice for the greater good. Yes, I am referring to the bureaucrats.

Qrappy Quotes 2

Technology is clever people getting cleverer, so that dumb people can get dumberer.

Variation 1:

Technology is clever people doing clever stuff, so that dumb people can do even dumber stuff.

Monday, February 18, 2008

Qrappy Quotes 1

My Quote.

When a boy calls a girl, he pays double, listening to the girl talk and talk, and the phone company charge and charge

Sunday, February 17, 2008

Why factor is cool

Before beginning, I must admit I haven't messed with Factor for a couple of weeks now, nor do I contribute to it, I'm a Factor n00b. Please contradict peacefully.

Of course there are the usual reasons that it is open source, most of the standard libraries are in Factor itself, and that it has a really cool development environment. But almost every popular language these days has all that stuff.

The real reason I think factor is cool is because it still isn't near complete!

It's small and so the sense of community is much stronger, you can be the first to do things in Factor, when they've already been done elsewhere, and anyone with a decent education and experience could easily grok the theory too.

Small syntax

I would say Factor's basic constructs are even smaller than Python's. Just knowing a few shuffle words and USING:, defining words and quotations, gives you almost everything you need to know.

Everything else is just built on top of this.

Small population

At present Factor users are probably just in 2 digits. And there are no products (that I know of). Which means you could probably restructure the whole language without affecting anyone. This allows Factor to improve by rewrite, rather than by add-on.


Writing libraries for a new language means doing stuff that most have probably never done. So you have to learn about Unicode, or just traverse strings recursively (?!?) like I had to do in brainfacktor. ( Could it be better? )

Basically by keeping the core small, keeping a single stack and enforcing recursion by not having loops, Factor really forces iterative programmers to go stack based/functional. And that itself is a lot of fun, even though it is hard.

Reading about all the developers coding the standard libraries is also very informative, as is looking through the Factor sources.

And it would be fun to look at the interpreter, though I've never done it.

So that was my attempt at some evangelism :D

Most programmers are atheists

If this survey represents a signifact portion of them. Of course these are the programmers who are involved on the web, not much of all the zombies coding for the sake of it.

Thursday, February 14, 2008

This thing creeps along

Not much posts here, and nothing of interest. Well there really isn't much I've been doing.

I hacked a brainf**k interpreter in Factor, but since I've no time for Turing tarpits, someone should test it on more complex programs. Besides the number to string conversion does cause output problems.

I also have a refresh ready for my website, but it isn't going online any time soon, because its not for 22bits, but a new one, which I might do after a few months.

Other than that I'm just messing around with a few ideas, I really haven't got time for anything else.

The only thing new I've been doing is listening to a LOT of new music, by Radiohead, Broken Social Scene, and other alternative bands. See my

Friday, January 25, 2008


But it won't be enough. Because this is not, fundamentally, a technological problem. Nor is it, fundamentally, a political problem. This is a problem of appetites, and of narcissism, and of self-deceit. The planet is breaking, and it is breaking under the weight of our hunger for more. To reform the world, we must first reform ourselves." --
This really resonated with me. It's so true and yet so few people know it. BTW I searched for this after reading Oliver James's articles in The Economic Times.

Thursday, January 24, 2008

I like that

As found on IIT Bombay's Techfest

On a side note, I SO NEED to be at BarCamp. Too bad I've got exams. Seriously next year I'm going to every damn festival.

Tuesday, January 15, 2008

Pain, Horror and Redemption 1

Welcome to the first of many PHR incidents to come in my life.

I updated grub and rebooted.
What followed was 6 hours of endless bootloader overwriting, staying awake till 2am, wiping out the windows bootloader twice, installing Elive, Arch, Mandriva on spare partitions, hoping that somehow i could get the bootloader to boot into my system.

It kept complaining about not being able to find /dev/hdd2, the root filesystem.
Then i realized that in the error messages, it was just mounting all sd* drives.

So I change hdd to sdb and voila!

Today I find out that the IDE and SATA code was merged in the kernel, and the bootloader update probably rewrote the paths or something

Lesson Learned: Read errors properly before doing all sorts of crap.

PHR stories are stories about my own incompetence/stupidity. No product mentioned herein is being insulted unless I specifically say so.

Saturday, January 12, 2008

KDE 4.0 out!

Well it isn't in the Arch Repos yet, but the release announcement and visual guide do make me drool :D.

And its good they made the panel go all the way to the edge of the screen.

Thursday, January 10, 2008

Factor: Guess the number

My first useful factor program.

! A guessing game
USING: calendar random strings namespaces prettyprint math.parser io io.files math kernel combinators ;

IN: guess

! lets choose our number
SYMBOL: answer

! initialize the generator
now timestamp>unix-time init-random

! get a number [1..100] and put it in answer
100 random answer set

answer get .

! keep asking the user
: start-guessing ( -- )
"Enter number: " print
! get the number as a string
stdio get stream-readln
! convert to integer

! push on answer
answer get
! now stack top is : input, answer
{ [ 2dup < ] [ "try higher" print start-guessing ] }
{ [ 2dup > ] [ "try lower" print start-guessing ] }
{ [ 2dup = ] [ "Thats right!" print ] }
} cond


You might want to try it in the UI, the command line listener seems to have issues flushing the I/O streams. To run go:

"<path>/<filename>" run-file

Notice the lack of looping in Factor ( it's available but not recommended ) and using recursion in its place.

Tuesday, January 08, 2008

Programming: What they don't teach in school

This is my honest opinion, feel happy to flame or contradict me, but be polite.

Much has already been written about how much High School computer science teaching sucks ( High school computer science education ). As a student who has just left high school I just wanted to present my 2 cents on how bad the seperation between RealWorld programming and ClassRoom programming is. A common rebuttal is that there isn't enough time. I agree there isn't, but half-baked knowledge is dangerous. If you teach something, teach it qualitatively, not quantitatively.

The Problems

Tool Power

A programmer is only as good as his tools, and how well he can use them. But schools generally lock down students to a specific ( often crappy ) tool. For example, we've Turbo C++ 3.0 ( 1992 ) on all computers. That is a 16 year old environment, supporting 16 year old standards. That's bad! In the days of Linux and Wikipedia do you really want kids raised on old proprietary standards. The ICSE board is very good atleast in their terms. They say that any Operating System ( why are we still on Windows ) with a latest C++ compiler should be used. It seems our school isn't listening.

If you are on Java, you probably have BlueJ. Now I've nothing against the BlueJ folks, but hiding all the compilation details from the student is denying knowledge. Students ( especially the ones who got into CS just for fun ) are of course happy that they don't muck around with "hard" stuff. But thats not how things work in the RealWorld. You should know how to use the command line, invoke javac and java. And, fricking, you should know that Java files have a .java extension and .class is the compiled byte code.

Another issue is shortcuts, quick search and replace, commenting. Kids don't know any of these things. It's type, click, type. Click Save. Click Compile. And to change something there is always manual replace.

File Management

Typical high school level programs, if well written, are never longer than 2 pages. They are often crappy, in the fact that the logic is repetitive, their is no purpose to the program and that students still don't get it!

So when it's project time, what the instructor gets is a dump of humongous shit, often with all the code in main, bad indentation and no comments. That's because the instructor hasn't taught the kids anything about decoupling programs, and seperating classes in files, and using header files. Often the instructor himself has no idea about build systems.

Bad Core Concepts

One really bad thing I see among my fellow students, is the complete inability to realise that each statement is an individual component. It evaluates to something, and other statements can use that value to do their job. This causes repetitive coding. To illustrate see this code sample.

function isSpam(email) {
return true;
return false;

Students aren't taught that email.contains is returning true or false, and all we care about is true and false. They are never taught to see function documentation, just use it the way the instructor tells them too. This code can be simplified to the following, because email.contains is already doing what we want it to do, why decorate it?

function isSpam(email) {
return email.contains('$$$');

Beautiful Code: Of Readability

Bad indenting. Student code is full of bad indenting. Instructor code is full of bad indenting.

Learn to appreciate code people. It's just as much art as painting or poetry. Encourage right indentation, make liberal use of whitespace, clean up your logic, don't nest too much. You should be able to go back to it after a few months and not have to spend time just cleaning it up.

Follow standard conventions for variable names, make sure your method names and parameter names make sense. Use camelCase or _underscores_. Make booleans start with 'is' or simply the condition you're representing. If any variable has more purpose than a loop counter or a position marker, it should have a meaningful name.

Name your files meaningfully, keep it lowercase, and keep all your fake 31337 ness to yourself.

Type for today, Think for tomorrow

It's a matter of thinking for 3 hours, writing 3 minutes worth of elegant code, versus thinking for 3 minutes, spending 3 hours typing up code.


The post above also mentions some of the crap I've mentioned here, like the 4600 line Sudoku.
Student code is littered with conditionals highly specific. The very reason you're using a high level language is to avoid this. I've seen quiz programs where each question and its answer is in an if clause, embedded in the program! Cardinal sin. Use a file and parse the file, if you can't do that, atleast put all the questions and answers in two arrays ( don't tell me about maps ). Then you can just use a loop to pick out the question and its right answer.

Make your code extensible. Just because this is some dumb program which you're writing in school, doesn't mean it should be a waste of muscle energy, disk space and time.

If you have to choose day's of the week, put them in an array. You want to find out the number of days in a month, use a 12 element array. Or better yet, use your brain a bit more and write this:

int daysInMonth(int month) {
return 28;

else if((month%2 == 1 && month <= 7) || (month%2 == 0 && month >= 8))
return 31;

else return 30;

It might seem like more code, but you can write this code once and use it anywhere. And you are using your brain.


Use better languages

Far too many schools have jumped on the Java bandwagon. If you are teaching kids who don't have much programming experience start with a higher level, small language. Use Python. You should be able to finish explaining most of the language within a week. Besides the interactive interpreter is great for messing around to know exactly how something works, how to make it go wrong and where it can fail. You will also spare them from the compile cycle ( I know, it kind of contradicts my first problem :p ), allowing them instant gratification. Spare them the brackets and let them develop the logic. Logic is far more important than syntax. Syntax changes, but logic is immortal.

Real World Knowledge

Once in a while just stop the programming, and discuss technology related issues, latest news, ethical considerations. Anything which expands their minds and gets them more interested in computers. There are more than enough anecdotes and quotes about programming, use them. Instructors should stay on top of news stories. You don't have to know what monads are, but at least know what Linux is. One of my instructors had never heard of Opera and Mozilla ?!? Whatever language you are teaching, make sure you know it well. The same instructor above didn't know that the Java GUI framework is called Swing. Make sure you are aware of atleast major upgrades and integrate them.

The Open Source ecosystem is set to flourish. Make sure your students are aware of what it is. Encourage them to try out FLOSS. If you can't convert to Linux, atleast use open source compilers, tools and languages on your Windows machines. Set aside a computer where you can mess with distros.

Encourage frequent group projects. Let the kids make plans. Tell them how to go about design. Make sure its extensible and adaptable. If the project will need something more than what is taught, tell them to read about it, while you do too.

Good Reading

I don't know about the rest of the world, but in India, Computer Science textbooks for high school are crap. They are full of errors, bad practices, incorrect language, and often old software. There are hundreds of better quality books available online, often royalty free. There is Wikipedia and Wikibooks. While using them, remember to tell your students how cool the Internet is, and teach them about sharing.

Mark for the big picture

There is this huge emphasis on theory at the high school level, mostly due to lack of time for practical assessment. Which means students have to often write programs and submit them without testing. In such situations, don't cut marks for syntax errors, unless they mess up the logic ( missing braces ). The compiler/interpreter is going to catch them anyway. As long as the program works correctly logically, missing semicolons are OK.

Rank readability above extensibility, extensibility above just-getting-it-done. If a student has used some cool logic, or exploited the specifications, give him some appreciation. After all programming is all about getting the best out of constraints, and pushing the limits. If he/she has looked to optimize, that's good too.

Don't hand hold

Far too many instructors help students fix their errors. Don't help them fix the errors, help them understand what the error is. Any decent language is quite verbose at error reporting, and in case of languages which support exceptions, the class name is often a very good indicator. Any decent compiler also reports line numbers. Let them fix the problem for themselves. Time well used now, is time saved later. Tell them it's called debugging.

Create some passion

Kate Masukomi sums it up nicely. Most programmers today are doing it to pay the bills. Don't let your students be one of them. If someone just doesn't seem to have any aptitude, maybe he should look into some other field. Encourage the good ones to expand out of the syllabus, mess with different languages and read sites like Proggit. Tell them to blog and learn HTML/CSS and create their own site. Don't create hundreds of typists, the world would prefer fifty real programmers ( thanks to lankythoughts for the link! ).


If something isn't done quickly, the IT world will be in a mess. Already the lack of real talent is leading to a shortage of employees. According to me, the only real coders are the people who are up breast with new developments and technologies. They don't have to know how everything works, but they should know that it exists. That's passion. They are the ones who read blogs, write them, comment on articles, are always hacking on side projects and have commits on some open source project. Make your students a part of that group.

P.S. Forgive my immodesty in certain areas :)

Saturday, January 05, 2008

Friday, January 04, 2008

Factor -ize

Its been a week since i discovered Factor. So first, it's stack based, it's small, it's almost tiny. I've never programmed in a stack based language before. But I liked it, really makes you think. Infact I haven't got any program written yet, just playing around in the interactive interpreter. It's got really good documentation by way of the API, what it could use is a quick start guide, ie. a list of some basic operations of the stack, using conditionals and looping and arrays and hashmap, because right now you've to look through the documentation for each concept, which means the unity is broken.

But great language, small community, even smaller existing code. What is bad is that most of the 'responders' give 404s. :(