Monday, February 2, 2009

Snippets: Filename padder [Python]

I recently downloaded nearly 1400 pictures (a complete webcomic). The problem came with the naming. The files were named from 1.png to 1400.png, making CDisplay and other programs display them in ASCII sort (1.png, 10.png, 100.png, 1000.png, 2.png...). Maybe there is a better solution but what I did was pad the filenames with zeros, so they became 0001.png, 0010.png and so.

This is what I did:

import os

dir = "D:\\Directory\\"
for file in os.listdir(dir):
splitfilename = file.split(".")
name = splitfilename[0]
extension = splitfilename[1]

newname = "0" * (4 - len(name)) + name
print file + " => " + newname + "." + extension
os.rename(dir + file, dir + newname + "." + extension

Thursday, January 29, 2009


Let me start saying something: The mouse ISN'T evil. Things like "everything is faster using the keyboard" are not only zealotism, but also false. If you don't believe me, try moving all the pictures of your family folder where your dog is jumping or something like that using the command line and then using your favourite file explorer.

But then, there are things that are truly faster when you can avoid using the mouse and focus only on the keyboard. I'm talking, of course, about programming. Programming is all about focus. You need to be 100% focused on what you're doing, or else it won't be good, and, for me, having to take my hands off the keyboard, reach for the mouse and follow the movement for whatever the task I must do is a great drawback. That's why I love Vim.

Little disclaimer: VIM is hard to learn. This remembers me of a quote I once read on "Everyone's first vi session. ^C^C^X^X^X^XquitqQ!qdammit[esc]qwertyuiopasdfghjkl;:xwhat". What I am saying here is that VIM's intuitiveness is counter-intuitive. It doesn't make any sense until you finally start using the correct mindset. These are the rules I am using to learn it:

  • Hands on the home row.
    This is precisely VIM's philosohpy. Everything should be doable without having to leave the writing position on the keyboard.

  • Insert mode should be only used on short bursts.
    You don't move in insert mode. You only write on it. If you have to do any other task, press ESC and do it in normal mode.

  • There's always an easier way to do it.
    For example, changing a simple character. You've written "clash", but you wanted "class". The cursor is located just before the h you want to change and you have several ways:

    • dlis (delete, right, insert, s). You delete one character right of the cursor, enter insert mode and then write "s".

    • xis (delete character, insert, s). Same as before, but x does "dl" with one less keypress.

    • cls (change, right, s). "Change" deletes the designed text and enters insert mode automatically.

    • s. That's right. VIM uses 48 keys of the keyboard, and everyone has at least two functions: One when you press the key and another when you press shift + key. In this case, "s" is the key for "substitute character".

But that's not the only thing I like about VIM. I'm actually using it a lot for my PFC (I don't know how it's called in English. It's a project we, Spanish students must do before the end of our degree), which is a Django application. As I often work from several locations (the university, my house, my office...) it's easier for me to log in to the server that runs it and program there. That leaves me without some possibilities, like using Eclipse + PyDev, but thanks to VIM, it's not much of a problem. My usual session goes like this:

cd /var/project
:e code/app/ (open file /var/project/code/app/
:sp templates/app/template.html (open file /var/templates/app/template.html in an horizontal separator)

This way, I can write the template and alter the view at the same time if I need it. To move between the two horizontal windows, I press Ctrl + W and then the direction. For example, to move to the upper window from below: Ctrl + W k. But that's not all.

VIM is very customizable. That means you can alter it's behavior in almost any way you can imagine, like mapping keys to commands. I have four mappings in my .vimrc file:

nmap <F1> :!invoke-rc.d apache2 restart<Enter>
Issue a restart without leaving the editor, pressing just one key.

nmap <F2> :!svn commit -m ""<Left>
I just love this one. It writes the commit command and then the moves the cursor one charater to the left, effectively leaving me between the double quotes to write the commit message.

nmap <F3> :!svn update<Enter>
I'm not alone in this project, and sometimes my partner does some important modifications that I must load from the version control system.

And the strangest one:
imap ñ ;
As I said before, I'm a Spaniard, which means my keyboard has a different layout, with "ñ" and "ç", and "ñ" is located where the semicolon is in an English keyboard. My semicolon is actually shift + comma, making it harder to write, and it being a usual programming character, it's just not acceptable. That's why I remap it in the configuration so "ñ" writes a semicolon. Code doesn't use "ñ" ever, and the html templates have it as "&ntilde;", so I just don't need it.

So this is it, an editor that let's you do any task without breaking your focus on the text, all configured to your liking, with more than seventeen years of experience on his back (and that's if you only take vim into account, and not vi), and, best of all, open-source. That's free and mantained by a big community for you, folks, a very good thing. Love it or hate it, but try it first.


Tuesday, January 27, 2009

Snippets: Creating a matrix in python

There's two easy ways to do this:


def matrix(rownumber,columnumber):
matrix = []
for i in range(rownumber):
a = [0]*columnumber
return matrix

List comprehensions:

def matrix(rownumber, columnumber):
return [[0]*columnumber for x in range(rownumber)]

Monday, January 26, 2009

Code is Music

Coding is an art. It may look boring, like an indecipherable wall of strangely coloured text, but, like one of those cubist paintings it's not the look but the message what matters in the end. You can look at it and think "It's just garbled characters. I will never get it" and you will never get it, but, try thinking about it, talking to the computer, giving it instructions in a manner not only understood by it, but also by the programmer, and then it makes sense.

Like music, code is an universal language. Sure, there is actually a lot of programming languages, but that doesn't matter. You hear Johann Sebastian Bach and think "It's music", and then some Metallica and also recognize it as music. That's the beauty of coding. That's why code is music.

Think of it, you, the programmer, the composer, sit in front of an empty sheet. You are thinking of a message, something you want to convey to your audience. The melody is already on your head. It's the basic structure of the program. Then, you start giving shape to your creation, adding layers, making them work in harmony until it's done. Your first creations, as in music, don't make sense to anybody. You think you're saying A and they hear B, just like the computer keeps doing anything else but what you want, but it's ok, it's a learning process. Failure teaches a lot more than boring success.

I'm in no way an expert. My "songs" are still punk-rock simple, noisy and fun, but pretty limited. Still, it's a fun road to walk and I want to share my experiences, so welcome to "Code is Music", and now... Start playing!