Friday, April 28, 2006

HTMLizer for emacs

This is a cool tool to have in your emacs.

This lets yoiu convert any syntax highlighted (or otherwise formatted) buffer into HTML for use in web pages etc. It supports two styles: css and font that can be controlled via a variable - see the header comments of the file for details.

I used it here and here ...

Jaundiced?

At universe of discourse, mark dominus writes about colour perception.

Well, at exam, if a question is ambiguous(obviously, the student must think of at least two possible variant interpretations of the questions if the student thinks the question as ambiguous at that time) the best strategy would be to write an answer that pinpoints that fact. There is this anecdote about Neils Bohr - you can find it here for example:

The following concerns a question in a physics degree exam at the University of Copenhagen:

"Describe how to determine the height of a skyscraper with a barometer."

One student replied:

"You tie a long piece of string to the neck of the barometer, then lower the barometer from the roof of the skyscraper to the ground. The length of the string plus the length of the barometer will equal the height of the building."

This highly original answer so incensed the examiner that the student was failed immediately. The student appealed on the grounds that his answer was indisputably correct, and the university appointed an independent arbiter to decide the case.

The arbiter judged that the answer was indeed correct, but did not display any noticeable knowledge of physics. To resolve the problem it was decided to call the student in and allow him six minutes in which to provide a verbal answer that showed at least a minimal familiarity with the basic principles of physics.

For five minutes the student sat in silence, forehead creased in thought. The arbiter reminded him that time was running out, to which the student replied that he had several extremely relevant answers, but couldn't make up his mind which to use. On being advised to hurry up the student replied as follows:

"Firstly, you could take the barometer up to the roof of the skyscraper, drop it over the edge, and measure the time it takes to reach the ground. The height of the building can then be worked out from the formula H = 0.5g x t squared. But bad luck on the barometer."

"Or if the sun is shining you could measure the height of the barometer, then set it on end and measure the length of its shadow. Then you measure the length of the skyscraper's shadow, and thereafter it is a simple matter of proportional arithmetic to work out the height of the skyscraper."

"But if you wanted to be highly scientific about it, you could tie a short piece of string to the barometer and swing it like a pendulum, first at ground level and then on the roof of the skyscraper. The height is worked out by the difference in the gravitational restoring force T =2 pi sqr root (l /g)."

"Or if the skyscraper has an outside emergency staircase, it would be easier to walk up it and mark off the height of the skyscraper in barometer lengths, then add them up."

"If you merely wanted to be boring and orthodox about it, of course, you could use the barometer to measure the air pressure on the roof of the skyscraper and on the ground, and convert the difference in millibars into feet to give the height of the building."

"But since we are constantly being exhorted to exercise independence of mind and apply scientific methods, undoubtedly the best way would be to knock on the janitor's door and say to him 'If you would like a nice new barometer, I will give you this one if you tell me the height of this skyscraper'."

The student was Niels Bohr, the only Dane to win the Nobel Prize for physics.


And the problem arises only when the student does not think of more than one variant at that point (indicating that they were not aware of the potential ambiguity) - now in that case, that cannot be used as an excuse for claiming the correctness of the answer later, as the answer becomes correct later during a process of "somehow justify this answer and get more marks" period that follows the handing out of marked answer scripts...

Now the situation described my mjd is of course slightly different - the student had a different interpretation in mind. But how does one distinguish between this situation and the one described in the previous para?

The teacher is only left with the recourse of marking the answer wrong, therefore.


Education
New web site
New Blog location

Thursday, April 27, 2006

Rake it using LISP!

Rake - I saw this sometime back when martin fowler wrote about this - and I remember thinking "WOW, Ruby must be cool - its much trickeier to implement a domain specific language in perl!!". And I tried to write a small perl script inteprepretter on lines of rake and made similar progress - 60% functional build in some hours. Now that I am learning LISP I tried my hand at this problem of a build DSL... in LISP - and even a LISP newbie like me could role out a couple of macros - and I am sure, if I spent a whole day at it ever it wil be pretty cool (and I intend to do just that contibute via cliki

(defmacro task (name (&rest dependencies) &body body)
(let ((exec-task-fn-symbol
(intern (string-upcase
(concatenate 'string "exec-task-" (symbol-name name))))))
`(defun ,exec-task-fn-symbol ()
,`(fulfil-task-dependencies
,@(loop for d in dependencies collect `(quote ,d)))
,@body)))

(defun exec-task(task)
(let ((exec-task-fn-symbol
(intern (string-upcase
(concatenate 'string "exec-task-" (symbol-name task))))))
(print exec-task-fn-symbol)
(funcall exec-task-fn-symbol)))

(defun fulfil-task-dependencies(&rest dependencies)
(dolist (d dependencies) (exec-task d)))


;;Examples usage
(task foo (bar bar1 bar2)
(echo "HUM"))
(task bar nil (echo "HOOO"))
(task bar1 nil (echo "HOOO1"))
(task bar2 nil (echo "HOOO2"))

(exec-task-foo)


;;Some file set , file selector like stuff(as in Ant)
(defmacro file-set(&body selectors)
(let (
(root-dir (gensym))
(file-set (gensym)))
`(lambda (,root-dir)
(let (
(,file-set (make-array 32 :fill-pointer 0 :adjustable t)))
,@(loop for s in selectors collect `(funcall ,s ,root-dir
,file-set))))))

(defmacro file-selector((&key type)&rest args)
(cond
((string-equal type "regexp")
`(regexp-file-selector ,@args))
(t (format t "ERROR: type cannot be ~a~%" type))))

(defmacro regexp-file-selector(&key expr)
(let (
(root-dir (gensym))
(file-set (gensym)))
`(lambda (,root-dir ,file-set)
(format t "SELECT FILES FROM ~a~% BASED ON ~a~%" ,root-dir ,expr))))


(defun test-file-set(file-set)
(funcall file-set "ROOT-DIR"))

(defun test-file-selector(file-selector)
(let ((file-set (make-array 32 :fill-pointer 0 :adjustable t)))
(funcall file-selector "ROOT-DIR" file-set)))

;;(test-file-selector (file-selector (:type "regexp") :expr "\\.lisp$"))
;;(test-file-set (file-set (file-selector (:type "regexp") :expr "\\.lisp$")))



DSLs

Monday, April 24, 2006

Doing it

I was wondering (call me perverted if you want), at any minute, whats the chance some couple is doing it in a community? Actually, my mind wandered off to "what is the size of polulation (in units of "number of sexually active couples") to say with a confidence of (say) 90% that at least one couple is doing it" - you know similar to that other problem of "how many people must be present in a room in order to say with 90% confidence that at least two poeple share thier birt day".

So this looks like something nicely modeled using poisson distribution.

I modeled it like this, the probability that "at least some couple is doing it" is actually 1 - "probability that no couple is doing it". I also assumed that an average couple does it between 4 and 10 times a month - and add to this the fact that there are 30 * 24 * 60 minutes in a month, you get the rate parameter for the poisson distribution.

It all boils down to at least (ln(1/(1-0.9)) * 30 * 24 * 60)/4 (when its 4 times a month) and (ln(1/(1-0.9)) * 30 * 24 * 60)/10 (when its 10 times a month). (Where ln(x) is the natural logarithm of x (log to the base e)).

Hold you breath:

Its about 24867 and 9947.

That is, if there were 24897 (9947) couples doing it 4 (10) times a month living in a community, then at any minute, you can say with 90% confidence (10 % chance of being wrong - odds of 1 to 9), thaty at least some couple is doing it (Assuming that couples do it at any moment that strikes their fancy, completely randomly).

Hmmmmmmm.


Maths

Sunday, April 23, 2006

LISP!

Hmmm. So here is my first functional lisp!

This is also the first time I tried to reverse the digits of an integer (with digits interpretted in a given base) using recursion. I am not very sure if I cannot unpack the multiple returns into individual variables - like in python. That would be very cool!

I am also pretty sure the lisp I have written is not very idiomatic ... but writing tons of code alone can instill the idioms in the code-thought channels of the brain. In fact, I tend to think that one does not think in the usual sense of the term while writing programs - it seems to be more of a subconscious activity. But that can hapen only after a language ingrains itself deeply in one's brain. Till then its very consciously code and hence code that is not very beautiful - its code that looks contrieved to the initiated.


(defun pow(n i)
(let ((p 1))
(dotimes (i i) (setf p (* p n)))
p))


(defun rev(n base)
(let ((worker (lambda (n base self)
(if (= 0 n)
(list 0 0)
(let ((temp (funcall self (floor (/ n base)) base self)))
(list
(+ (* (mod n base) (pow base (second temp))) (first temp))
(1+ (second temp))))))))
(first (funcall worker n base worker))))


(rev 1357924680 10)

(rev #b1111011101101 2)


LISP

Thursday, April 20, 2006

Cross Browser Issues

Some additional cross browser issues "we" have faced while developing a reasonable UI based on a home grown AJAX like idiom predating AJAX ...

Comma Mysteries

If the comma contributes an undefined element to arrays, it causes very mysterious errors to be thrown for objects with JSON syntax. (And this happens quite frequently due to copy pasting of stuff or removal of a last element etc etc). For example
var foo = {bar:'bar',};
The above causes mysterious syntax errors on IE and if you use the debugger provided by Microsoft the code window points at a vague location. The secret to locating the errors is to move over to a background window in that MDI window - and that window will have highlighted the right error location!

slow string additions

Incremental string formation using '+=' is extremely slow in IE, especially as the string grows larger. This can be gotten around by creating arrays of strings and using array 'join' method to create a large string. The funny thing is that on mozilla/firefox the latter is very slow :-). So the following code can be used (implement amIInIE function suitable to detect IE browser ...)

function StringBuffer(sz)
{
if(amIInIE())
{
if(!sz)
{
sz = 128;
}

var buffer = new Array(sz);
var index = 0;

var text = new Array();

this.append = function(piece)
{
if(index == sz)
{
text.push(buffer.join(''));
index = 0;
}

buffer[index++] = piece;
}

this.toString = function()
{
if(index > 0)
{
for(var i = index;i < sz;i++)
{
buffer[i] = '';
}

text.push(buffer.join(''));
}

return text.join('');
}
}
else
{
var text = '';

this.append = function(piece)
{
text += piece;
}

this.toString = function()
{
return text;
}
}
}

///Example usage
var start = new Date().getTime();
var buff = new StringBuffer(128);
for(var i = 0; i< 1024000;i++)
{
var f = i + '12345678901234567890123456789012345678901234567890123456789012345678901234567890';

buff.append(f);
}
var end = new Date().getTime();

alert(end - start);

Method Sublimation

When 'core' objects such as arrays are stored say in a frameset scope while the frame page keeps changing they mysteriously lose their methods. The data stays intact, though. For example if you store an array, it loses methods like push, join etc - invoking them causes errors which imply that there is no such method. But data is intact.

This can be overcome by creating a new array each time and copying data onto it. Very mysterious - just the 'vtable' seems to disappear! The following example suggests a work around:


function arrayPush(array,newItem)
{
if(!xHasValue(array))
{
array = [];
}

if(!amIInIE())
{
array.push(newItem);
return array;
}
else
{
var newArray = [];
for(var i = 0;i &lt; array.length;i++)
{
newArray.push(array[i]);
}

newArray.push(newItem);

return newArray;
}
}



Seems to have something to do with the scope from where the function is invoked.
JavaScript

Friday, April 07, 2006

Heron's Formula

Universe of Discourse blog has a writeup on Heron's formula where the author talks about how it might be derived (apart from using trigonometry, of course).

I found a nice writeup here on that.



Maths

Thursday, April 06, 2006

Area of a Triangle

I was thinking about the area of a triangle and how one might show that area of a triangle is indeed half the product of breadth and height. Its simple to demonstrate when the triangle is right angled as the triangle is evidently half the rectangle and hence area is half the area of the rectangle.

When the triangle is acute or obtuse, the following demonstrates how the triangle area continues to be the same and is determined by the base and height (not the acuteness or obtuseness).

Take the case of an acute triangles:


Clearly the triangle ABC is a sum of triangles ABD and ACD and the areas of triangles ABD and ACD are easy to calculate (they being right angled triangles).

Therefore, area of ABC = 1/2*(x*h) + 1/2*(y*h) = 1/2*(x+y)*h = 1/2*b*h

Similarly , consider the obtuse angled triangle:


Now the triangle ABD is the sum of triangles ABC and ACD. Therefore, triangle ABC is the difference between triangles ABD and ACD.

Therefore area of ABC = 1/2*x*h - 1/2*y*h = 1/2*(x-y)*h = 1/2*b*h.


Maths

Saturday, April 01, 2006

Reverse Engineering a solution....

I was recently reading an article in "A Gardner's Workout - Training the Mind and Entertaining the Spirit" by Martin Gardner.

Title: Covering the cube with congruent polygons", Page 73.

The problem is about cutting the cubical "surface" into a tiling made of a specific number (n) of congruent polygons. And examining if any cases are impossible ...

n=2,3 etc are simple(he states - and the tiles are basically rectangles.

He also gives an example of a very "esoteric" tiling using Latin crosses as tiles. This is wonderful - I have no idea how someone could have come up with that solution. (Unfortunately, I don't have the drawing skills are patience to draw a picture of that solution here. May be one of these days ...)

He challenged his readers to give a solution for n=7, that is tile using 7 congruent polygonal tiles. And he was astonished that "Anneke Treep" came up with not one solution, but four solutions each of which solves the problem for any number of polygonal tiles (Ignoring limitations imposed by structure of matter , of course). I have depicted one of those solutions below.


I was thinking of the process by which this solution could be obtained. And here is one possibility.

The key insight is that the cube needs to be unwrapped(development of surfaces) such that there are no branches in the resulting planar development.I shall not rigorously define branching here, but intuitive definition will do: if you draw the mid line of the strip it does not branch as a Y anywhere. Of course its tautological. You know what I mean, c'mon. Its not like the picture below. So there.



Now that allows us to draw "parallels" inside the development and divide the figure into any number of polygonal pieces. So lets start with the following attempt.



The problem with the above solution is obvious - the polygonal pieces A, B, C and D are not congruent - this is because of the varying lengths - sides becoming longer as we progress towards D. This is because of a sloping diagonal and the non-sloping edge. If the edge was also sloping, it would allows us to retain the same length of the "arm" and hence obtain a solution. So lets move a piece of triangle from the top square to the bottom square. Like so:



Now, this seems like a plausible solution. But wait a second! the two squares are actually "lids" for opposite faces of a cube. Therefore, If a cube was brought to life from a piece paper that looks like above, it would be cancerous. One big triangular hole on one face and a triangular Growth" on the opposite face.

What this tells us is that, if the face from which we cut and and the face to which paste are adjacent this solution works. And so we obtain this:




Puzzles