Thursday, September 9

And now ...

... from the "Something Completely Different" department, here are some pictures taken with my phone:











Sunday, August 8

A Python Syntax Highlighter for HTML, Written in Python

As of late, I wanted to post some python code on my blog and the formatting options I found kind of sucked (actually I was getting bored and looked for excuses to roll my own).

I had a look at some options, but the most known, either had to be installed locally (and I didn't want to do that), or they worked online, but the generated code was incomplete or the formatting sucked (in my self-absorbed opinion).

Long story short, I wrote my own, in Python.

The formater generates HTML code separating operators, keywords, tokens (identifiers, variables and numbers), comments and text.

The colors for these can be set in the COLORS global map.

Here's the code (the formatter err ... formatted itself for this post, as a test):

import sys
import re

# alphanumeric character escaped
# for regular expressions
ALPHANUMS = 'a-zA-Z0-9_'

# python operators, escaped
# for regular expressions
OPERATORS = r'\.\(\)\[\]\{\}\:\'\"\!=,%\+\-\*\/\^\&<>'

# python keywords
KEYWORDS = ['if', 'for', 'while', 'do', 'def',
    'class', 'None', 'True', 'False', 'and',
    'or', 'not', 'import', 'else', 'elif',
    'raise', 'except', 'break',    'continue',
    'lambda', 'return', 'yield', 'global']


# how many spaces should a tab character be:

escape = lambda source, replacements: \
    ''.join( [ c if c not in replacements \
        else replacements[c] \
        for c in source ] )

# escape a string so it will be parsable
# by the re module
def rxEscaped(source):
    replacements = {
    return escape(source, replacements)

SPACES = ' \t'

class TokensList(list):

    replacements = {
        ' ':'&nbsp;',

    def __init__(self):

    def add(self, key, value):
            (key, \
                TokensList.replacements)) )

class Tokenizer(object):
    '''Transforms a line in a group of tokens,
    where each token is represented by a pair:
        line -> [ (key, token), (key, token), ... ]

    The key represents the type of the token:
        kw = keyword
        tk = word
        sp = spacing
        op = operator
        cm = comment
        qu = quotes
        txt = string contents
        ?? = unidentified (for any errors)


    rxToken = re.compile(r'''
        ^(?P<tk>[%s]+)        # string token
        |(?P<sp>[%s]{1})    # or space
        |(?P<op>[%s]{1})    # or operators
        |(?P<cm>\#.*$)        # or comment

    quotes = None

    def __init__(self):

    def _init(self, line=''):
        self.line, self.parsed = line, line
        self.tokens = TokensList()

    def _parseRx(self, rx):
        '''Search for rx against line and return
        the found match and the groups dict.

        found =, self.parsed)
        if found:
            return (found, found.groupdict())
            return (None, None)

    def _parseStringStart(self):
        quotes = \
            self._parseRx(r'^(?P<qu>[\']{3})')[1] or \
            self._parseRx(r'^(?P<qu>[\"]{3})')[1] or \
            self._parseRx(r'^(?P<qu>\')')[1] or \
        if quotes:
            quotes = quotes['qu']
            self.parsed = self.parsed[len(quotes):]
            Tokenizer.quotes = quotes
            return True
        return False

    def _getTokens(self):

        while self.parsed:
            ## are we in a string?
            if Tokenizer.quotes:
                if len(Tokenizer.quotes) == 3:
                    # rx for multiline string
                    rx = '(?P<qu>%s)' % \
                        (('\\' + Tokenizer.quotes[0])*3)
                    # rx for single line string
                    rx = r'(?P<qu>%s)' % \
                token, gd = self._parseRx(rx)
                if gd:
                    start, end = token.span('qu')
                    if start > 2 and \
                        self.parsed[start-1] == '\\' and \
                        self.parsed[start-2] != '\\':
                        self.parsed = self.parsed[end:]
                        self.tokens.add('qu', gd['qu'])
                        Tokenizer.quotes = None
                        self.parsed = self.parsed[end:]
                elif len(Tokenizer.quotes) == 3:
                    # a multiline string is legal
                    # add everything as text
                    self.tokens.add('txt', self.parsed)
                    # singleline string not closed
                    # pass everything as '??'
                    self.tokens.add('??', self.parsed)
                    # process next line correctly
                    Tokenizer.quotes = None

            # are qe opening a string now?
            if self._parseStringStart():
                self.tokens.add('qu', Tokenizer.quotes)

            # we're not parsing a string
            token, gd = self._parseRx(Tokenizer.rxToken)
            if not gd:
                self.tokens.add('??', self.parsed)

            for key in gd:
                value = gd[key]
                if not value:
                elif value in KEYWORDS:
                    self.tokens.add('kw', value)
                    self.tokens.add(key, value)
            self.parsed = self.parsed[token.end():]

    def parse(self, line):
        # reset the object
        # get list of tokens
        # merge like tokens
        retval, currentKey, currentList = [], '', []
        for key, value in self.tokens:
            if key == currentKey:
                retval.append( (currentKey, currentList) )
                currentKey, currentList = key, [value]
        if len(currentList):
            retval.append( (currentKey, currentList) )
        self.tokens = retval
        return self.tokens

def generateFormattedFile(source, destination):
    '''Generate a formatted HTML block
    from the source code.


    dest = open(destination, 'wt')
    dest.write('''<div style="background-color:%s;">
        <pre>''' % COLORS['bg'])

    tokenizer = Tokenizer()

    NEWLINE = '\n'

    for line in open(source).readlines():
        line = line.rstrip()
        if not line:
        formattedLine = ''
        for name, list in tokenizer.parse(line):
            if name in COLORS:
                formattedLine += \
                    '<span style="color:%s;">' % \
                        COLORS[name] + \
                    ''.join(list) + '</span>'
                formattedLine += ''.join(list)
        dest.write(formattedLine + NEWLINE)

if __name__ == '__main__':
    if len(sys.argv) < 2:
        print('Syntax: %s <sourcefile>' % sys.argv[0])
        generateFormattedFile(sys.argv[1], sys.argv[1] + '.html')


Thursday, July 29

On Inception - an amateur critique

Like many armies of movie goers, I saw Inception last evening and was ... not disappointed. I can't say the movie was good, but I think I can say it was not bad either.

Here's a trailer:

WARNING: Spoilers ahead.

I found it to be a combination of some opposed styles, combining on one side the exploration of the mind through dreams and symbols with Matrix-style effects and Mission Impossible-style action.

While it's a good combination of styles, none of them prevailed, and each style was sacrificed somewhat  in favor of the others. As such you have a movie that could have been a great effects-movie (but it's a bit too convoluted for that), a great action movie (but it's a bit too convoluted for that also) and a great psychological movie (but it's too action-packed for that).

Also, the trailer makes you think the movie is about the power of an idea. It's not (well ... it is about that, to the degree that say ... Ronin was about the power of a suitcase - that is to say, not at all).

I liked a few themes in it (the "going deeper" in the subconscious by entering a dream within a dream for example). Maybe I found it interesting because it sounds like a plausible hypnosis technique (I'm not sure).

I also liked the symbols (though some were repetitive and simplistic), the ending, some of the dialogues and I especially liked the idea put-forward at the end:
Mal (a figure within Cobb's subconscious) tells Cobb that maybe his reality is the dream because it's implausible for nameless corporations to chase you all over the globe - it sounds too much like a dream.
This idea, striking to Cobb at the time, seems to support one of the possible interpretations of the ending of the movie.

I also found the idea that at the deepest subconscious level there's a common ground very ... attractive. It gives you something to think about (if nothing else).

What I didn't like about the movie was ... well for one, I would have expected Cobb to actually be an expert in the mind (considering the movie starts by portraying him as such). Instead, he appeared more like an action man who "knows all the tricks".
Cobb: I know how to find secrets from your Mind, I know all the tricks!
(see? :-D)

First, there's not much about those tricks in the movie. There's the Totem idea (actually that was quite good), the idea of things being hidden in symbols of safety (a safe within a house within a house and a safe within a wall and a safe within a fortified fortress? I mean ... subtle much?). Then you just have some veiled references and explanations in conversations that didn't touch on much of anything (some explanations on how the mind builds the dreamscape, why you shouldn't change somebody else's dreamscape endlessly and so on).

Through the movie, Ariadne - a beginner in the field trained by him - trumps him over and over again; and ... err ... Ariadne constructs mazes. It must have been a coincidence.

In this light, it seemed like, while Cobb knew all the tricks, he was not so much of an expert on "all things mind". He also ignored the problems in his own mind to such a blatant degree that he risked ruining mission after mission (the first mission is complicated by his issues, the second even more so, and we're left to understand this had been going on for a while), while the most important thing in his real-life (living with his kids) was at stake. I understand having a troubled past and living with your own demons, but this looks a bit like a plot-hole, or like dilettantism on Cobb's side.

Second, the mind-scape issue is also lacking a bit and incomplete. I found a much better exploration of the subconscious and symbols the mind creates in What Dreams May Come for example.

While the movie abounds in dream-specific symbols and items (a spinner that goes on and on in a dream, the coherence of reality being broken, heavy rain because the dreamer had to go to the bathroom, or walls that squeeze you while you struggle to get through) any dream-like feeling is completely missing. There are other movies that manage it way better (see the tensioned atmosphere in Lester Burnham's dream in American Beauty, or Mary Lomax' dream in The Devil's Advocate). Such an atmosphere would have probably detracted from the intense action though, so it was probably sacrificed (if it was even considered).

Third, there was the whole "going deeper in the subconscious than anyone else in the whole world, and synchronizing three things falling at the same time and at different speeds, and in three different dream levels, by three different people with Robert break into his own mind to construct a false idea in a way his own subconscious will not reject" thingy. Did I mention convoluted? I thought I did.

I had two friends ask me "Did you understand anything?" the moment we met outside the cinema. I understand the question is being asked by others who saw the movie also.

All in all it was an entertaining movie for me. If you want an action movie (that's not about the power of an idea - as the trailer suggests) but more about Mission Impossible-style action using Matrix-style effects in convoluted overlaid dream-scapes, go and see it.

It was entertaining.



Wednesday, June 2

Fire Poker Zen


Hakuin used to tell his pupils about an old woman who had a teashop, praising her understanding of Zen. The pupils refused to believe what he told them and would go to the teashop to find out for themselves.

Whenever the woman saw them coming she could tell at once whether they had come for tea or to look into her grasp of Zen. In the former case, she would server them graciously. In the latter, she would beckon to the pupils to come behind her screen. The instant they obeyed, she would strike them with a fire-poker.

Nine out of ten of them could not escape her beating.

utnapistim's comment:

If you wanted to find Zen, forget about it!

Tuesday, May 4

At Nemo33, Bruxelles

First dive at Nemo 33, Bruxelles.

You don't need an insulation suit, or any weights. The visibility is perfect and the environment is great for exercises. A dive takes around 40-50 minutes (max - in our case it was 27 minutes) and costs 22 Euros.

Dive data for the dive:
Time In: 12:24
Time Out: 12:51
Max Depth: 11.4m

Water temperature: high (no insulation suit needed)
Weights: none (no insulation suit, 12L steel)
Visibility: perfect

Air consumption (12L):
In: 180 BAR
Out: 100 BAR

Thursday, April 29

quality music ... in a garrage

on forgiveness

In ultimate analysis, your choice to make is between being right and being happy.
(excerpt from "The Book of Utnapistim", which is not yet written)

Forgiveness is not something you do for another but something you do for yourself. I am talking here of the exact moment when you let go of all the pain, of all the anger and resentments and your shoulders drop suddenly. You all of a sudden feel very relieved and ... possibly happy again.

It is a moment of great release.

This kind of forgiveness is not about accepting everything that happens to you, or letting someone walk over you - in fact you should remove yourself from a situation where you get hurt as soon as possible. What I am talking about is not clinging to the pain after you've been hurt.

Forgiveness is the awesome power to let go of what happened, to be fresh again in the next moment. This is one of the keys of lasting happiness.

When seen from this angle, forgiveness is the opposite of letting someone walk all over you. It is a way of saying "my life is not about <whatever hurt me>". In fact, what happened matters so little that I have already gotten over it - it just doesn't matter in the long run.

In the end, this king of forgiveness is simply the right perspective to go with.

This forgiveness begins with acceptance - with the unconditional acceptance of the situation as it is now. If you were hurt, accept you were hurt. If you are angry about it, accept your anger.

Accepting means that you will stop rationalizing it, justifying it, thinking about what happened, spinning it, reinterpreting and going over it again and again, thinking <what ifs>, and <I should have>s, making scenarios, explaining it in your head, and generally all that jazz*.

We do this all the time: some event makes us feel pain, then we spin it in our heads for minutes (the lucky ones), for days (that would be ... me) or - in the worst cases - for years to come. Instead of moving on, your whole existence becomes "about that".

I don't mean that it's bad to keep it going, or that you should or shouldn't or any such crap.

It's just that this kind of suffering comes from what is basically clinging to your own pain and what you get out of the whole process is just more pain (although while you're at it, it may look like some kind of "justice", some form of "I was injured", or "poor me", a settling of accounts or proving yourself right). In the end, clinging to your pain is just more pain (just like getting revenge, in the ultimate analysis is just more pain).

In the end the key to forgiveness is this: look at all the hurt and face it like an upstanding human being (to the degree that there is such a thing as an upstanding human being). Embrace all the pain you may feel with all that you are at this moment.

When you do this, your tension towards it is gone, and you may come to realize something startling: you're not actually that hurt, it's not as bad as it seemed while you were fighting it and it is in fact quite small; You may even discover it's insignificant.

When you are here, forgiveness has already happened (and no, nobody walked over you in the process).

* Come to think of it, jazz is actually quite nice. Don't go starting to associate it with mental pain now.

Friday, February 26

Change is Good

This is my last day in this company. I was hired for two projects here, both of which were successes (methinks) and now it's time to depart.

I will have to clear my browser cache, my local files (I kept my CV in My Documents and all that), and I will have to make sure I didn't leave any incriminating papers on my desk (err ... not that I'd have anything to hide - I mean).

Seriously though, as strange as it may sound, I will miss the one hour drive to office every morning (I drove with the window open as I came uphill this morning, to catch the morning's fresh air in the small forest).

I will also miss the too-sweet-not-warm-enough-cappuccino made by the machine down the hall and these guys that I've known for three months, and whose jokes I still don't understand (as they speak French among themselves and they speak too fast for me to understand).

Through all that, I have this feeling of change, of new beginnings.

I still have no idea where I'll be Monday morning, but at this point it doesn't matter.

Change is good.

Wednesday, February 17

The Dark Side ... of Your Resumé

If you were to look at my resumé, youd' see a lot of wonderful things:

It says I have ten years of experience in IT and five years working with C++.

It sais I have a very varied experience, having worked with performance-critical apps, multi-server systems, cryptography, security protocol design and some others.

It's designed to make you feel you know what I'm talking about, after you have read it.

Here's what my resumé won't say:
I also have experience with having to maintain inefficient crap that should have never seen the light of day.

I've maintained over-engineered code, redundant and dead code and generally things that should have been rejected, before seeing the light of source control. To be fair, I've also written that kind of code, mainly in my first two-three years as a software developer.

I have seen obvious mistakes being made in early design that were taken all the way to implementation and maintenance because (probably) someone didn't want to admit their mistakes.

I've seen code that was so ugly that it survived only because those who saw it's ugliness for ugliness were not mad enough to touch it, and the others who were not savvy enough to recognize the ugliness just didn't bother.

I have been asked to stay over the weekend to fix my mistakes, or (in the last years) someone else's mistakes in design (as I tend to learn a bit from mine - as slowly as I sometimes do).

My resumé doesn't say all that, and it will not, because the software engineers who understand that aspect of the job, do not participate much in the hiring process.

Instead you have to impress the others: the ones not savvy enough to understand - either the managers, or the people we tend to talk about over a beer ("I have this guy at work who ...").

Very seldom will you see the hiring decisions being touched by the people that will be actually affected by those decisions, the people that you will be directly working with.

In the last company I worked with, I was interviewed by my would-be manager - the technical guy I was to be dirrectly under, once I passed the interview.

I was lucky that way.

Most of the times, in order to get hired, you need to put on a suit (that you will not wear past the interview) and your best business face, then speak to somebody that evaluates your skills based on your own description and the amount of achronyms on your CV (my CV says I've done OOA/D and maintained a HP/HA server system with a MTBF of a year or so).

In a typical interview you will probably speak to somebody that is interested in the business side only, or that has (at best) seen some code a few years ago. The only apport technical people have in these jobs is (maybe) to advise the management on a test they should give to potential candidates.

In the cases where you have a technical interview it is usually the second (that is, if you pass the non-technical one).

Sadly most companies dismiss the best developers at the interview stage (because if they were able to speak business they'd be business people, not developers).

Thursday, January 21

Nothing Else Matters - on Cimbalom

My mother called me tonight and told me about a youtube video of Radu Seu, playing Nothing Else Matters ... on a cimbalom.

The movie was shot with a phone camera, in a Restaurant. It started circulating a short while ago and it's apparently been passed around the internet virally.

It's good to see that people recognize it for what it is.

I mean, it's shot badly, and people still forward it.

It's in a restaurant, with people's voices in the background, and people still forward it.

The sound quality is bad and people still forward it.

It gives me a good feeling to see this.

Edit: Here's some more:

Bach's Ave Maria

He Who Loves and Lets Go (traditional Romanian Folk):

Sunday, January 17

not a zen koan

These are all things I've done before: the thoughts, the actions, the gestures, the ideas, the aspirations, the wishes, the illusions of illusion and truth, the sensations, the search, the questions and the answers.

I'm trapped in the iron circle, and the only exit is through the middle of a puzzle, burned to ashes, scattered by the wind and washed away by rain.

Where is my exit now?

Impromptu Skiing - in France

Quite late, too late for any sane organizing to be done, I was asked if I wanted to ski this weekend.

I said yes, without thinking about it.

I spent Friday morning getting winter tires, Friday evening driving (then drinking) and today morning coming back, as it rained all of Saturday night.

We got through a good day of skiing though, which is a lot more than no skiing at all in my book, and I got some good rain pictures to boot.



snow out the window

A good weekend all in all.

Saturday, January 9

C taking a picture

C taking a picture


I took this on the flight home. We had window seats and A was sitting on the row in front of me.

This is her, staring through the window.