miércoles, 30 de diciembre de 2009

startup lessons

Y combinator (Paul Graham's company, and hacker news hoster) publishes a list with links that talk about startups. Many of them are Graham's past articles (worth reading nonetheless).

I've quickly scanned the list, and some of the articles linked, and it seems quite interesting, so worth pointing it here.

As I don't have anything else to add, I'll just post an image I saw yesterday at #perl6 channel @freenode. It's funny and, maybe can add information if you are deciding what language will you base your startup on.

It's a pity there's no perl there.

martes, 29 de diciembre de 2009

Binary search and dumb compression in Common Lisp

In my quest to learn lisp, I've been alternating scheme and common lisp readings and lectures.

I find scheme really enlightening, but quite difficult to write in it. Maybe it's because I haven't officially reached the set! chapter in SICP, and I still find difficult to write (so) functional code.

The point is that I finished this book and then, I started Paul Graham's ANSI Common Lisp. I've been really enjoying this reading, because it shows you interesting things (from an experienced programmer point of view) from the very beginning.

During the first 3 or 4 chapters, threre are some code examples, that I've tried to write on my own (maybe grasping a bit on graham's code when I got stuck, but well)

First, here's a compress/decompress lists lisp code. When entered a list like (0 0 0 1 2 1 1 0 4 4), compress returns a list of atoms or lists themselves, that contain the number of repetitions and the value to repeat: ((3 0) 1 2 (2 1) 0 (2 4)) . It's nice to see that at such low level point, being able to ask for a type of a given element gives us enough power to code this in a very simple way. I don't even want to think how I'd code it in java/c++.

Decompress does obviously the reverse operation

The binary search is just what its name says. Does a binary recursive search on an already sorted vector (array of 1 x N dimension).

I'm getting very fond of 'cond'. It takes the best things of both if and switch/case worlds. A switch-case like syntax, with powerful conditionals (not just comparing with '=')

That's all for now. Sorry for the crappy gists code listings. it seems github doesn't know much about common lisp (syntax nor indenting).

Btw, I've received my SICP copy in dead-tree format, so I'll probably spend some time with scheme when I finish Ansi Common Lisp.

Oferta de trabajo

Aquí voy a trabajar yo.

viernes, 25 de diciembre de 2009

Programmers, improving productivity and salaries

Hello dear reader,
Today you'd better be prepared for a mashup post of several sites and articles about programming (in the most generic sense of the word), improving your programming skills, and what people think about how to divide the programmers set into two subsets: good ones, and bad ones {disjoin,complete}. Lots of links, yeah. It all depends on the time/willingness at your disposal.

Learn to program
Learning to program is not an easy thing, nor something that can be achieved in 21 days (see Peter Norvig Teach yourself programming in 10 years). But the nice thing about programming is that you can learn by practice, and start with babysteps, and improving little by little, learning about new paradigms(lisp,Io,haskell are nice tools for that), reading highly recommended books (you can get lots of them legally for free on the internetz), or joining a Opensource Project to learn from others.

Little by little, I feel how I get the knowledge, sometimes through slow readings, and sometimes with sudden "OH FUCK!, AHAHA!". This moments when your brain 'clicks' (mostly in functional programming) are priceless. I hope to have achieved a good level of programming skills in a couple of years. For the moment: keep learning.


Keeping the interest for something is very difficult nowadays, with so many potential distractions (beer,friends,girls).

What can keep you motivated to keep learning? I've no f*cking idea. For me, it's a mix of several things:

  • Keeping in touch with good hackers. This really pushes me to keep learning. I've found it priceless. After someone told me about Barcelona Perl Mongers, I joined them, there I met great programmers (now friends), and we could even start collaborating. Nowadays I'm at Barcelona.PM , GTSmalltalk and flibug.
  • Collaborating in some project is good to keep hype on something.
  • Open a new project to play with it.Even if it's nothing serious, but you'll get in touch with git/mercurial, and can try things as you learn elsewhere.
  • Be humble. Keep reminding yourself that everything you do, can be improved. Having a (false) feeling of superiority makes you lower the bar. However, of course, if you think you did something well, you can give yourself a cookie, pat your shoulder and show the code to your friends :)
  • IRC. yeah, ircing on freenode has teached me lots of things.
  • Keep it fun. please
Listen to the masters
Masters are so for a reason. foreach problem you may have now, they have "been_there_done_that", so listening to what they have to say it's very valuable.

I'll just paste some links, about guidelines to improve your coding. They tend to be very general (and language agnostic), from the well known "comment code", to "follow idioms". For me, knowing the idioms of a language has been a great improvement to feel more self confident when writing and reading code. Reading reddit and hacker news from time to time can show you new people to follow. (ALERT!: Addictive)

there are guidelines that can be splitted in small chunks and read a paragraph on a daily basis. I've been doing this for some time, and I think it's very useful. I've doing this TipOfTheDay style reading with "Perl Best Practices" and "Pragmatic programmer" too.

Other are more like checklists. Anyway, there are lots of similar lists.
Hire programmers
Here are some essays about recognizing a good programmer. It's interesting how most points in theese latter essays match with the points on the upper links in this thread. I guess we're on the right track.

UPDATE (09/12/30): In HN there has been linked a site with a programmer competency matrix according to knowledge of a given programmer. I don't know how useful or fair it is, but it matches quite good with my ideas. I'm glad to be between level 1 and 2 (mostly 2, and hey, there's level 0 ;) ) and I am in some level 3 situation, or will be in couple months (estimated time). I think it also leaves it misses some other important points, and eventually, real productivity can only be measured after the work is done. Mind you it's not easy to measure productivity (see "office enabler" below)


But, do great programmers (that can be 10x more productive than average ones) earn that proportional money? Clearly no. Read the complete article by John D.Cook.
It reminds me of the "office enabler" role I talked about last august.

martes, 22 de diciembre de 2009

1984. You never pushed that.

Rewriting history is one of those things we all would want to do at least once in our lives.

Well, unfortunately, I don't have a solution for that, but in the computer world, you know... we even have ctrl-z !

But when things are uploaded to external server or repository, it's not that easy. Until git.

I accidentally pushed a 600Mb file to a git repo that (luckily) never changed, but when I cloned the repo, I had to wait for several minutes until git downloaded the 30+ Mb file (git, or at least github compress files).
git filter-branch -f --index-filter 'git update-index --remove filename' HEAD
git push --force --verbose --dry-run
git push --force
With just theese lines, you can pretend you never uploaded it. The only thing to keep in mind is that you should work on a up to date working copy.

Now you could even convince Winston Smith in room 101 that a given file never existed.

Scared? Yeah, you should be.

domingo, 20 de diciembre de 2009

Dos hablando

- Es una pena que las mejores cosas de la vida, sean ilegales...
- Lo dices por las drogas?
- Nono, lo digo porque lo pienso de verdad.

viernes, 18 de diciembre de 2009

git clone and pull remote branches

I thought that when I pushed/pulled branches in git, I only acted on the active branch (unless I specified it).

Well, that is not (entirely) true.

The problem is that when I clone a repo, I can't specify a given branch, and git only seemed to fetch the master branch.

When you clone a repository, you fetch all branches, with all the history (I thought that happened in hg but not in git, well anyway).

What happens then, if I don't see other branches than 'master'?
git branch
And you'll only see master branch. Other branches are hidden. To see them you should type:
git branch -a

So your branches are effectively there. To use any of them, you should
git checkout -b local_branch_name origin/remote_branch_name
I think what that line does is create a new branch and filling it with the fetched branch with that name, and bind the pull and push paths to the remote ones.

Another way?

In other sources, I've found that simply pulling with:
git pull origin Branch_name
will do the same, but, when I tried it, it downloaded/extracted the files, but without changing to the branch name.


Now the question is:

What happens if I modify two branches, and then just "git push" ? will it push both branches? That's what I'll try in next days, and after a bit of experimenting, I'll post back.

Btw, here are a couple of links you can read for a bit more info.

domingo, 13 de diciembre de 2009

info is power

In planet emacs, I discovered that there's a version of SICP in info format.

If you don't know what's SICP, it is a computer science book about programming fundamentals, that teaches you how to think about programming, and algorithms in general.

I'm reading it little by little because there are many deep concepts that I need to interiorize with some extra time and rereads. The book is freely available in html format. There are other sites that offer a pdf version, but this info version at http://www.neilvandyke.org/sicp-texi/ , sounds like a great option, because I'll be able to read it in any info pager, without relying on slow pdf viewers, or having to be online and use a browser.

after downloading the sicp.info.gz file , I installed it moving the file to a info suitable place (/usr/share/info and /usr/info are good places for vectorlinux).

To make it available from info's top menu, you should add a link line in the 'dir' file, or you can use intall-info.

As I had my info 'dir' file somewhat outdated, that's what I did to rebuild the whole dir:
for i in $(ls /usr/info/*) do install-info $i /usr/info/dir
now, when I type "info" in my command line, I get a 2362 line info index and among library infos and so, there's
* SICP: (sicp). Structure and Interpretation of Computer Programs

Sorry, no puns, no music links, no OMFGWTFORLYFAIL links today.

jueves, 10 de diciembre de 2009

ǝʌısuǝɟɟo ʇsod sıɥʇ puıɟ I

Once upon a time, not in the west but in a far far not-very-reputable-site that I visit (too) often, I saw a few comments with letters flipped upside down.

After doing some copypastes, I decided to write a 10 line script to translate normal text to flipped text.

I had to deal with unicode chars (I never had to do this before), and I came with this little script, that isn't awesome nor cool, but it can make some friends happy (Txor), and adds -Ofun to programming.

miércoles, 9 de diciembre de 2009

mapping through many lists, perl vs lisp

Last night (or this if you prefer), I was reading about lisp mapcar function, and I mentally mapped it to perl's map. (More precisely, I was reading exactly page 224 (or 232) of This book)

In fact, they do quite the same, but mapcar (that is a specialized form of lisp's map) seems a bit more flexible because it can deal with many lists at once (perl's map can't, at least by default).

First we start with a usual applicative programming case:

For example, generating a list with the square of each element in another list.

perl version looks like this:

my @squares = map { $_ * $_ } @mylist;
map { $_ * $_ } (1..10);

lisp version. As lisp does not have the equivalent to (1..10), we can build a list builder by range :
(defun range (a b)
(loop for i from a to b collect i))
(range 1 10) => (1 2 3 4 5 6 7 8 9 10)
(mapcar #'(lambda (x) (* x x)) (range 1 10)) => (1 4 9 16 25 36 49 64 81 100)
That's the full interaction we have to do with lisp. define range function, test it, and then use mapcar. Notice that common lisp (unlike scheme) is a lisp-2, so has a namespace for variables and another for functions, so we have to provide the sharp quote, that refers to the function.

So far so good.

But when things get trickier is when you want to evaluate a function that takes two parameters and you want to get the parameters from two lists.

lisp mapcar can do it by default. (nice, eh?)
(mapcar #'+ '(1 2) '(2 1)) => (3 3)
Doing this in perl is not that straight, but it is possible, and you know, TIMTOWTDI:

A nice trick is doing a little mind change , and shift the point of view. You can take the index as the iterator, and get something like:

map { $a[$_] + $b[$_] } 0..$#a ;
Btw, remember that if you feed 2 or more lists to map, it will append them and treat as if only one list was entered.

There are other ways to get the map functionality, using some List::MoreUtils functions.

For example, if you only want to operate on two lists, you can use pairwise:
pairwise {$a + $b} @a , @b ;
There's also each_array, that builds an iterator , and with it, you can browse N arrays step by step.

As a last hacky resort, you could use zip (or mesh, they are the same) to build a new list like (11,21,31,12,22,32....) (I hope you get what I mean) , and then use natatime.

Want more perl ways to do it? Check that stackoverflow thread.

Plenty of options, yes, I know. For me, I stick with good old map {..} 0...$#a ;

As always, thanks to #emacs-es'ers for patiently answering my Offtopic lisp questions.
And thanks to Larry for the language that makes programming -Ofun.
And remember, comments allowed, even encouraged. :-)

domingo, 6 de diciembre de 2009

Common Lisp "beginner" books

Instead of writing my final degree project, I've spent the afternoon reading about lisp, and I found out that to learn lisp (in fact, to learn any language), it better to get a book and read it throughtfully than read a bit from here and a bit from there.

Maybe it's because I've already read a bit from here and a bit from there, now I can read 3 or 4 chapters in a row from a book.

Anyway, I'm going to put here a couple of them that seem specially good:

Ansi Common Lisp : Not free, but you can get the first two chapters for free from paul's site. Reading the first 100 lines conviced me about it. great style of writing and going right to the point.

Successful lisp: Free. Great (at least the first 3 chapters) Very well explained, and with good and well thought examples and code listings

sábado, 5 de diciembre de 2009

search in multiple buffers in emacs and vim

Want to look for a word in a number of buffers?

No problem, emacs can do it with a simple command (the problem is remembering hundreds of "simple commands" :/ )

emacswiki gave me the solution .

The command is multi-occur.

It lets you select in which buffers you wanna perform the search.

My use case though was knowing in which irc channels appeared a given user.

Then, the command is:
  C-u M-x multi-occur-in-matching-buffers
it lets you write a regex for buffers to search, so I wrote "#.*" , and then the word.

As simple as it can get.

Thinking how I'd do it in vim, normally I'd do a normal grep (using ack) or vimgrep, but as emacs can map buffers to non-files, grep wouldn't work.

Vim offers quickfix window that can be easily combined with both grep and vimgrep, and one can download theese two plugins. AFAIK none of theese plugins can search in some but not all opened buffers.

Any other vim solutions are very welcome.

viernes, 4 de diciembre de 2009

Perl December

Yay! It's december. At first, this doesn't seem that exciting, but every perl hacker knows a few facts related to december.

  1. Advent Calendars are here again
  2. Christmas is near.
This week I've been coding some perl, and revisited some practices/modules I've been some time without using.

I'll try to explain some of them, that I found particularly useful.

Starting a project

Although this is a small app, and could be thought as a script, following the "always code as if you uploaded the code to cpan", I used Module::Starter with Module::Install. I could have used Dist::Zilla, that seems to be more DWIM-ISH , but well, I already had the "magic" module-starter line, so

module-starter --module=My::App --author="Raimon Grau" --email="raimonster@gmail.com" --builder=Module::Install

Object oriented perl.

I used a simple OOP interface. As noone at $work follows the perl world , I decided not using Moose, and used plain OOP. I used a bit of sugar with Class::Accessor, so attributes accessors and mutattors could be autogenerated.

use base 'Class::Accessor';
__PACKAGE__->mk_accessors(qw/attr1 attr2/);

When there is some error, for example, opening a file (it may not exist), I couldn't just die (dying from a lib is not nice), nor warn, so I used Carp module, to get more informative info about when the code errs.

Testing and Pod Coverage

I did some tests to validate my code (at least some basic things), and also ran Pod coverage (module-starter added the test automatically).

In vanilla OOP perl, you can't write private methods (at least, easily), but there's a convention of methods begining with '_' being private helpers.

Pod::Coverage, a tool that ensures you write documentation for all your methods, also follows this convention, so you can leave _functions uncommented. Great way to guide you to best practices. There's also more sophisticated ways to use it.


Having to manipulate CSV files, I had a few options, but ended using Text::CSV__PP.
I needed only basic features so everything went ok with this.


Having to deal with paths and files typed by users is annoying because of trailing '/'. For example, you can easily end with a path like "/home/user//this/isa/pathFile".

Perl provides File::Spec::Functions::catfile to sanitize those cases. Great finding.

To dump structures, I've used Data::Dump, that, prints the smaller output (linewise).

Meanwhile, I've been enjoying both lhp and pp2 Casiano's courses. Seriously, I think it's jewel in the crown on spanish perl courses.

That's all for this post.

Remember, be nice, and fight for your rights. Well, fight for theese rights too. And theese.

miércoles, 2 de diciembre de 2009

A ver como me levanto mañana

Hay días que me voy a dormir pensando que todo es una mierda, y en comprarme un arma que me extinga. Hay otros que pienso que podría haber estado peor.

Hoy es de los segundos.

A ver como me levanto mañana.

martes, 1 de diciembre de 2009

Better perl dumps than Data::Dumper with xxx::yyy

Sometimes I feel like I don't have a path to follow in the perl world. There's always more and more to learn, and one can't seem to explore all similar modules to do a given task.

For example, some time ago, I posted about Data::Dumper::Perltidy, a way to better format D::D output.

Since then, I've been exploring some other options to do similar things, and today, as I had to start a new project at $work, I decided to give a stab at those other Dumper modules.

I Dicovered a few other modules to dump data, that can also be used for marshalling.

Data::Dump :Really small output, arrays are joined in a single line (if it fits)

Data:Dumper::Concise : Nice options for Data::Dumper, it prints sub codes, and prints \n in strings with newlines instead of the newline char. When its output is evaled, it delievers the same code and data (sub code is there!)

Data::Dump::Streamer :Highly configurable dumper. I haven't tested it. From what I've read, it seems to be the most complete dumper, ideal for complex things, but overkill for simple dumps.

Data::Inspect: Quite small output, very simple to use, and inspired in ruby's p and inspect functions. It has support for printing complete objects.

I haven't pasted examples as you can find them in the cpan page of every module.

Btw, writing perl at $work is great and makes me feel more productive than any other language/task I have to use/do. I'll try further Data::Dump, and Data::Dumper::Concise, and see how does it feel.

viernes, 27 de noviembre de 2009

Mastermind setter (scheme) and flibug meeting

Mastermind setter
Last week, I couldn't work on the mastermind solver, but at least, I finished the setter.

It was a good exercice to get in touch with scheme IO, like getting input from user, split strings, and the like.

I finally removed all the functions for IO, because I can supply the inputs as lists on the REPL. I've used drscheme, but as this week I also tried guile (embeding it in a c app. Pretty cool), I might try it for future hacks.
(check-sols '(1 2) '(1 3))

I'm quite excited about how easy it became to do it, and this weekend I'll spend some time on the solver.

On the other side, this tuesday we had another flibug meeting at oblong. Amazing, as always:
  • Aleix Conchillo made a live presentation about plt slideshow. A module to create slides using scheme. Given that I had invested some time to find a good slides maker and not finding it, this might be a good solution to study further.
  • Andy Wingo showed us a demo of the greatest technology I've seen in many many many (sorry) months. When I arrived home I said "Papa,mama, I'm back from the future".
  • Colin Fleming made a good (also with live demos) presentation about IntelliJ refactoring tools, and he expressed his feeling of the need for clever programing environments. It's impressive how an IDE parses your code, and how much it knows about good/bad practices and hints you with improvements. He started coding a scheme mode for this IDE that already managed some refactorings like var renaming. As editors are a religion matter, some of the assistants had a few doubts of the real benefits of using a 'cool' boxed IDE (although extensible) versus using a swissknife-and-the-kitchen-sink emacs. On my part, being a vim user for 4 years and just starting to dip in emacs, I'll follow this thread really close.
I'd like to thank all the flibuggers and oblong for sharing all that coolness. I wish I could share more with them giving something back (with a presentation). Maybe when I finish my degree project I can prepare something about stumpwm or fluxus.

I'd say it's been a pretty exciting scheme-y week.

miércoles, 25 de noviembre de 2009

lightweight window managers part 1

This is a post (maybe the start of a series of posts) that I was willing to do for some time.

It's related to light window managers. Those wm that do not have lots of dependencies, and that are quite well thought and let you get your job done in a fast and zen-y way.

They usually are a bit hard to get used to (for a wide range values of 'a bit'), but if you try them for some time, you can get hooked to them.

Most of them are made with programmers/geeks in mind, so if you don't feel like programming a bit to configure your wm, or editing a configuration file makes you cringe, you can definately skip this post.

Tiling vs non-tiling
If you don't know what are tiling window managers, it's probable that I won't convince you in this post, but anyway... When I started trying wm as crazy and say tiling window managers for the first time, I thought: "WTF?! I've lost my 'window' feeling" . It didn't convice me because your're too used to have to arrange windows by hand, so not being able to do it by yourself (at least with drag-n-drop) can make you feel caged. Just let time go by, and keep trying one of them from time to time, until you'll see they make you more productive.

Ratpoison wm

Ratpoison is the window manager I've been using for the last 4 years (more or less). It's the most minimalist one I've seen, and due to it's screen-ish keybindings, I just feel@home with it. It has no dependencies besides X, and the compiled binary is 116kb . ratpoison++;

It's a 100% tiling wm. with no window decorations, no menus, no icons, no nothing. It doesn't have a floating layer neither, so if you open multiwindow programs, like Gimp, you'll be probably srcewed until you know how to manage it. My recomendation for gimp is using Xnest and open gimp in a suboptimal wm. Another option is to use ratpoison's tmpwm command, that executes a wm temporally, and when you exit it, you're at your ratpoison home, with your session intact.

Basic usage of ratpoison is the same as GNU screen (click here for a chat-tutorial I did some years ago. Sorry for the bad formatting), but changing c-a for c-t (obviously, you can configure it). So ctrl-t c will open a new terminal, c-t n will show next window in the current frame.... just see 'man ratpoison', or type c-t :help, or info ratpoison.

Configuring ratpoison is really easy (well, depending on your estimation for 'really easy').
You can fill your ~/.ratpoisonrc with as many commands as you want, in the same way you'd type them in the ratpoison prompt (when you press c-t : ).

One really nice thing is that you can send commands to ratpoison through the command line.

For example, when you're on it, open a terminal, and just type:
ratpoison -c "split"
Then your running wm will receive the split command, and execute that.

Imagine all the nice things you can do with it :). In your favourite programming/scripting language. :D . system("ratpoison -c 'echo ratpoison rulez' ");

It has also multiscreen support (not as good as I'd like but...).

Now a screenshot of my splitted screen, (although there's really nothing to see):

Ah, and some more screenshots and configs here.
That's all for now. Next to come (in no particular order):
awesome wm, stumpwm and evilwm.


lunes, 23 de noviembre de 2009

El listillismo

Pocas cosas me joden tanto como los seguidores del 'listillismo'.

Son aquellas personas que aceptan decir chorradas, a cambio de chorradas. Porque tu tiempo no vale un duro. Y el suyo? Bueno, ellos se dedican a esto.

Que a veces yo estoy ahí, y me siento muy bien. Como oliendo nubes, como en un globo. Un rato rajando sin conocer, y sin interestarte. Pero no me jodas. Llega un punto, que ya dices basta, y te toca enfrentarte a los listillos profesionales, o callar y "morir un poco más por dentro".

Y mientrastanto buscas miradas cómplices en un vagón del metro. Eres como una letra A en la sopa. Buscando otras letras que se apunten a formar una palabra. Ya veremos cual, pero que jueguen. Con una B y una R, yo ya me conformo.

Aunque reconozco que no siempre apetece jugar. Que a veces se te acaban las ganas, y a mí se me han acabado, pero una y otra vez, cuando veo gente con ganas de CANT.R , o ganas de .PRENDER, o simplemente GAN.S, no me resisto. Porque un día, me ayudarán a escribir alguna palabra que ahora mismo no puedo ni pensar, pero que sería imposible sin ellas. O quizás evitaran mi suicidio, o quizas lo provocarán. Pero la cuestión es jug.r.

sábado, 21 de noviembre de 2009

Mastermind in scheme

3 Days ago I read a post on programming praxis blog about writing a mastermind
game. The author splitted the game in two parts, the first
being the setter
, so given a known solution, and a guess, returns a string
of B/W/.

The point is that when I tried to code it, I was in an internetless bar, so I
had to guess some parts of the exercise and I missunderstod some of the points
and the code didn't work as expected (but at least, I succeeded to make it work
as I thought it had to work)

When looking the solution proposed at programming praxis, I payed attention to
both the algorithm used, and the code.

The algorithm used is works calculating white pegs, and then substract black
pegs. Finally, it sorts the black and white pegs and prints the output.

I'll try to write my own version in near future, but, for the moment, I have
updated the perl Mastermind code I started some time ago, that until now, it only compared the solution to the given combination, and returned a good/bad value. Now it uses that algo to tell how accurated is your guess. It's still far from functional, (it only plays random (with or without repetitions (using a cache))), but I have little time to hack on those projects.

I will have to take a look at the programming praxis "standard prelude", where the author shows some generic functions that are used over his solutions.

Btw, Programming Praxis has been one of my last findings on the intertubez. A great find IMHO.

viernes, 20 de noviembre de 2009

Implement a scheme intepreter in X

It might be just a strange coincidence, but lately, every week I discover a new book/tutorial that guides you through writing a scheme interpreter in whatever language I look.

Theres's SICP , implementing scheme in scheme

Theres PLAI , implementing a variant of scheme in a variant of scheme

Also, there's "Exploring programming language architecture in Perl". A book that covers the implementation of a scheme interpreter in perl.

And now here's a new kid in the block I just discovered. Implementing a simple scheme interpreter in haskell. I'll leave it here, and see if I have some time in the near future to read it (I doubt I implement it as I know nearly no haskell)

So many good books to read and so little time and attention span....well, there's still hope on SICP and EPLAiP.

lunes, 16 de noviembre de 2009

Implementing list functions in scheme

I've been messing a bit with scheme lately, and one thing I want to get well is list mangling. As you know, lists are the most basic and pure datastructure in scheme (and I think they are the only true datastructure in scheme).

This is why I want to get them right, and I'm rewriting some basic functions related to lists.

First of all, a little explanation of lisp lists in general.

Lists are based on a more simple structure called "cons". A cons is just a pair. The only thing that can contain a cons in the first (car) or the second (cdr) cell are:
  • string
  • number
  • symbol
  • cons
Yeah, pretty simple, right? The funny thing is that with cons containing conses, we can write all kind of datastructures.

First we'll see two axioms that must always be true related to conses.

(= x (car (cons x y)))
(= y (cdr (cons x y)))

Everything that guarantees this is a cons. Well, at least at this level...

a cons is represented by (x . y) , and a cons with another cons in the cdr would be (x . ( y . z))

A list is a special kind of cons with a determined structure.

( x . (y . (z . nil))) . A way to visually simplify this is ( x y z ) . That means that in a list of n elements, there are n conses linked through cdr's, with the last cdr pointing to nil. If you had to build (1 2 3) with conses, you could do it with (cons 1 (cons 2 (cons 3 nil))) .

Here I show the few scheme functions I wrote along with some explanations that davazp kindly gave me at #emacs-es and #lisp-es.

Theese are my first versions of some functions.

Here we see build-list can be abstracted to a more general (and easier to write) procedure called build-range, and I just call it with a start point = 1.

On the reverse function, we can use a different "happy idea".

Enough for today. Thanks to davazp and other #emacs-es -ers for their help and motivation.

sábado, 14 de noviembre de 2009

VL 6.0 KDE Classic Review

Vectorlinux team has released another version of this beautiful distro.

This release is a kind of tribute to kde 3.* , as it's the last vl with kde 3 bundled in it. Next versions (6.0 SOHO is already in beta) will come with kde 4, so this one is for those who want rock stable and well known kde 3.5.10.

Installing Vectorlinux
As this version still uses the "old" text installer (a new one is in the oven atm), I could boot and install the iso without having to burn a CD using vinstall-iso

sh ./vinstall-iso VL6.0-KDE-Classic.iso

And let the fun start!

The process went flawlessly. I was surprised how few options I had to install extra packages. Well, sensible defaults are ok for me.

To manage usb and CD units user can choose between the resource hog (but well tested and known worldwide) HAL and quick (and VL idiosyncratic) VL-HOT. The default is HAL, but I changed it to VL-HOT.

Since running the iso till I restarted to my new VL-kde only passed 9 minutes. Yes, only nine minutes. In the first boot, I was asked some other questions and a new reboot was required. Then I already booted to a full KDM screen.

After the first tests, everything worked fine: Sound, graphics (I installed propietary ati drivers from their page, and I already have my dualscreen setup), and all the basic things I could test.

Software selection

Vectorlinux has always come with a sensible selection of software, and most of it is already configured to "just work". For example, firefox(3.5.3) comes with flash plugin, pdf plugin, java plugin, etc... Konqueror is also installed (it's a kde distro, remember?)

For IM we have pidgin and Kopete, and KSirc to irc.

Koffice with a whole lotta apps is there, from creating spreadsheets to flowcharts. Lots of apps.

It comes with lots of dev tools by default (g++, gcc, make) and interpreters like perl (5.10.0), python (2.5) and even ruby (1.8.6).


That's the main reason I like/use Vectorlinux. It's among the fastest linux distros. And it's pretty easy to install. Here's a screenshot of vl running kde, with a couple of terms and ksirc. Click the image for a larger sample.

More Software

Although the VL team selected very good apps to go into VL-kde, I *want* my desired apps NOW!. No problem at all.

I just had to edit (as root) /etc/slapt-get/slapt-getrc and uncomment the testing line from


After that, "slapt-get --update" and then, installing all my favourite software was trivial:

"slapt-get -i zsh screen vim-gvim emacs ...."

In no more than 30 minutes, I CAN HAS a workin environment with KDE 3.5.10.


In so little time, I can hardly make a conclusion about it, but knowing the average quality of Vectorlinux releases, and having tested it a bit, I think I can recommend it to people with a little linux knowledge (installer is in text mode, but it's really easy to follow) who want a fast distro to be used in browsing / office or, on the other side, as a developement platform I'd recommend to people who do not want to mess too much with the inners of linux
(it's not arch) but want to learn in a standard platform, that does not hides anything about pure slackware (so pure GNU/linux), and want to learn little by little (it's not ubuntu).

Personally, being a more minimalistic person, I'll stay with vl-std and vl-light, but this release is one I'd recomend to my non-so-techy friends.

There's only a way to see if it fits you. Try it and see. Make (good) use of vl community in case of trouble. It'll positively surprise you.

viernes, 13 de noviembre de 2009

Self modifying bash script

Last month, my ten years old lappy said enough. Well, it can boot, but it doesn't get the plug correctly, so it has to stay pretty static. It came with windows 98 installed, and I've done most of my uni tasks there, as well as installing tenths of linux distros (until vectolinux).

While moving files from its HD to a safer place, I found a bash script (works on zsh too) I did about 5 years ago, which emulated a 'mute' function, and could be called through a shell (or through xbindkeys / keylaunch / ratpoison binds).

The funny thing about it is that it modifies itself to remember the last volume that was set, to restore it afterwards.

I know it could be done using a file to store the previous volume value (and in fact, I use a trick of the same kind), but well, I liked to see that trick again. It uses sed to substitute a variable that is later tested if it's 0. Pretty easy stuff.

It makes me remember my first questions about self modifying code. Now, with lisp and smalltalk, living in a life environment, everything is clearer (sure?).

Comments and improvements are obviously welcome. Enlighten me!

miércoles, 11 de noviembre de 2009

using Vim regexes everywhere

I'm at class atm, and 5 minutes ago I had to download some exams from past years.

There are quite a lot of them, and I just thought downloading them all by hand would be too much work for a Lazy man like me.

Then I used vim to help me :)

I just got the code where there were the links I wanted. It looked more or less like this:

<a href="2006t-c-40-lc.pdf">g40</a>,
<a href="2006t-c-40-lc-s-test.pdf"> solució del test</a>;
<a href="2006t-c-50-dc-test+problema.pdf">g50</a>,
<a href="2006t-c-50-dc-test_resuelto.pdf"> solució del test</a>,

Just open vim, paste the code and let the magic begin.

:%s:^:wget :
:w /tmp/downThemAll.sh

Now you just have to execute the script, and enjoy :)

Btw, yeah, I know about downThemAll, but I like using my own tools (and I dislike bloat).

domingo, 8 de noviembre de 2009

Mi carro

Aveces voy por la calle y veo un zapato solo, tirado. Yo siempre me pregunto por la historia que tendrá el zapato, lo que habrá recorrido, los años que llevará viajando, y en qué situación alguien puede "perder" un solo zapato.

Qué habrá sido del otro? Corrió mejor suerte?

Pues bien, ayer, volviendo a casa (4:00 AM), andando de noche a buscar mi coche, cuando veo en la calle un zapato. Me lo quedé mirando con descaro, a medida que lo iba alcanzando, y mientras lo adelantaba, pues lo mismo: "¿quien cojones pierde un zapato, con el frio que hace...?".

Cuando ya no podia torcer más el cuello, miro al frente, y a lo lejos, en la acera por la que andaba yo, en la escena estática de la calle a las 4 de la madrugada, veo que hay algo en el suelo. Parece un chaqueta. A medida que me voy acercando, la voy mirando fijamente, examinandola con la vista, haciendole un tercer grado, queriendo descubrir detalles de sus tiempos pasados. Al llegar al bulto, le dí una patada para levantarla del suelo, y entonces vi que eran unos pantalones. Los pantalones se quedaron otra vez en el suelo, muertos, y me los miro otra vez fijamente, parado yo a su lado. Ostia, unos pantalones... los sigo mirando, buscando detalles en ellos, y cada vez que me fijaba, habia algo que los hacia familiares. Cuando ví que estaban rotos de una rodilla dije "mierda, son mios".

Los agarré con la mano, y efectivamente vi que eran los mios. Miro al frente, y veo más ropa en el suelo, y otra pieza más un poco más adelante. Entonces me viene instantaneamente a la cabeza mi coche. ¿Estará donde lo dejé? , ¿Cuantos cristales estarán rotos? ¿Tenia cosas de valor?. Pues resulta que llego al coche, y esta todo revuelto, pero no se hab llevado nada.

Ni la luna rota, ni nada. Mu profesionales. Bueno, pues claro, ordeno el coche otra vez, encuentro teletac, papeles, monedas... No sé qué pretendían encontrar en un coche de 15 años pero creo que no lo encontraron. Entonces me viene a la cabeza el zapato. Sería mío? Voy a ver, y efectivamente, el zapato es mio. Ya conozco su historia. Comprado en Tenerife hace 2 años. La conocía desde el primer momento.

El otro zapato no apareció, o sea que ahora mismo, hay un zapato huérfano, despertando curiosidades de otros peatones. Y és mio. O lo era.

jueves, 5 de noviembre de 2009

practical Perl 5 match operator

Here I am again, with some reminders about a few practical things I (and maybe you) should have in mind when doing pattern matching in perl. I'll mainly talk about retrieving results in matches, and the context things.

So I won't talk about the pattern part.

The match operator is called with the m/OHAI/ pattern, or just /OHAI/ . if you don't specify something to match against, perl will use our good friend $_ , so when you iterate through a file, you are probably ok with this convention:

my $yay;
$yay = $_ if /say/ ;
print $yay;

Sometimes we don't want to match against $_, and we'd like to parse another var. That's ok, we use the =~ operator, which tells 'm' the variable to do the match with. But there is where I get somewhat puzzled sometimes, because if I want to assign the match to a var, you have to chain it

$match = $string =~ /yay/;

And that doesn't do what we usually want.

I've written this little test script to help me remember how to do proper matchings, and get the info I want from them.

martes, 3 de noviembre de 2009


Cuando una noche te pasa tan rapido, que pierdes la nocion del tiempo, y a las 6 te gustaría volver a empezarla:

a) Has bebido como un cosaco.
b) Te has puesto como un chamán.
c) Te has reído como nunca.
d) Has compartido momentos únicos.
e) Todas las anteriores son correctas.

lunes, 2 de noviembre de 2009

Eficient implementation of Tail recursion in Perl 5

I'm getting more and more interested in fringe programming languages (some of them are use the functional paradigm).

I'm no pro by any means, but little by little, I think I'm starting to grasp what's all that about, and I understand small new tricks every now and then.

In the YAPC::EU::2009, there was a loooooong discussion while we were having dinner about tail recursion, the minimizing of stack space and so.

Until this week, in perl 5, you could emulate tail recursion optimization by implementing it manually in the place where you want the optimisation. An explanation of "HOW" can be found in chapter 13 of "Exploring Programming Language Architecture in Perl" (EPLAiP from now on) , when the author explains how you could implement a sort of CPS in perl.

Well, last week,
Yuval Kogman (a great perl hacker with *LOTS* of useful modules) released Sub::Call::Tail , a Perl 5 module that allows you to call a function and make perl optimize the stack usage. For a brief usage howto, you can visit Yuval's post.

Today, I see in another of his blog posts he just created Sub::Call::Recur , a kind of curried version of Sub::Call::Tail, that just loops over the current sub. As he sais, it's a kind of redo but for functions instead of blocks. The resulting code is quite optimized (nearly as fast as plain iteration), so we can say perl5 has now tail recursion optimization. nothingmuch++;


Seeing http://ezrakilty.net/research/2009/11/function_calls_are_not_stack_frames.html I think I might review the post.... sorry for my ignorance :(

domingo, 1 de noviembre de 2009

DrScheme halloween easter egg

Yesterday I was about to try some scheme code from HtDP, and when I ran drscheme, I was presented a different splash screen from the one I used to:

Well, that's all for now. In a few days I'll post about what I was trying (if I find the time)

Happy halloween hacking.

miércoles, 28 de octubre de 2009

quoting procedures in scheme and cl, first steps

Disclaimer: This is really newbie stuff for someone with 0.1 experience in scheme/cl, so bear with me.... I'm learning...

I've been a bit puzzled with the huge versatility of scheme functions, when reading the first chapters of this book. The code that made my brain halt was

((if (= 0 x) + -) 9 8)

Depending on the value of x, the result will be 1 or 17.

At first I thought why the symbols + and - shouldn't be quoted. But there's absolutely no need of it. Let's see how it works little by little. if we ask scheme (I'm using DrScheme with plain R5S5 here) about the plus sign, it answers it's a procedure, the same as if wrote a lambda function there.

For example, an expanded code, and somewhat less strange (to my eyes at least) would be:

((if (= 0 x)
(lambda (x y)
(+ x y))
(lambda (x y)
(- x y))) 9 8)

This would apply 9 and 8 to the resulting lambda. In that case, those lambdas do the same + and - do in the previous example.

Ok, I think I understand it.

In common lisp, it isn't that straightforward, because cl has 2 different 'namespaces' (probably it's not the right word but...), one for variables and the other one for functions, so if you want to eval a list as a s-exp, you have to use funcall.

(funcall (if nil '+ '-) 2 1)

Anyway, you can evaluate the if statement without the quoted + and - (if nil + -), but I haven't managed to make it evaluate the final sexp.

another way to modify a piece of code is accessing to a code (interpreted as a quoted list)

> (cons - (cdr '(+ 3 2)))
(# 3 2)
> (eval (cons - (cdr '(+ 3 2))))

Well, for the moment it's all I've hacked with this kind of self-reference evaluations.

Btw, I've started reading HtDP, to start with an easy introduction to scheme. For the moment, the first 5 chapters are pretty easy to understand, but I felt I needed this basic background to fully understand the upcomming subjects. I'm kind of stalled in PLAI, where I understand most of the text I've been reading, but I'd like to do the exercices, and lately I don't have enough time to hack.

lunes, 26 de octubre de 2009

A la puta ruina

El Banco Popular presentó hoy (o ayer) resultados del tercer trimestre de 2009.

Es una pena que solamente ganó un 30% menos que en el mismo período del año pasado. Hecatombe, perdición, cataclismo!! Vamos a ayudar a los bancos, que pobrecitos, no tienen para sobrevivir.

El Banco Popular sólo ha ganado la ingente cifra de 630 millones de euros.

Me cagoen su puta madre.

domingo, 25 de octubre de 2009

PRACE and BSC training

Last week, I attended the BSC PRACE, "code porting and optimization workshop" given by some of its researchers.

The course was 3 days long, and I can say I quite enjoyed it.

First day, OpenMP . Full day of an openMP training. from quite easy levels to more complicated stuff, like tasks and other features only present in OpenMP 3.

Second and third day were not as productive as the first one, partly because of the subjects was not so much appliable to my daily work, and partly because of the speakers.

Alex Duran made a great OpenMP training course, and Xavier Teruel (my mus partner 5 years ago) helped us (Jdiaz, JMassanas, and $self) with great explanations when doing the exercises.

I don't know if I can share the slides, but I'll ask BSC people, and upload them (If I can).

We didn't do real complex things, but the overall feeling was that it's really cheap to try simple optimizations here and there in a large program (incremental optimizing), but converting a whole program into a highly parallel one is quite thrilling.

We looked at private,shared,threadprivate... clauses to define the scope of variables.

Follows a helloWorld example using OpenMP, with some calls to omp APIs, to return the number of active threads, max threads, or accurate time to do benchmarks.

Then we took a look at 'task' clause (a bit more complex, but good for task parallelism). I won't publish the code in this post, as it needs a thought explanation I'm not willing to do now. If you feel the absolute need to see a omp code using 'task', mail/comment.

After that, we looked at data parallelism, having a look at 'for', and different schedules. Here, we have a parallel matrix multiplication code, optimized using not only the typical 'for' but also using collapse.

Some insights about balancing loads and other common problems ended up the session.

viernes, 23 de octubre de 2009

insert code listings in latex

I've been strugling with it for last 2 days, and finally found a solution (I should have googled before , and not so much blind guessing).

Depending on what you're writing about, you probably will have to put code in your documents. Inserting code in latex is not that trivial, because you have to tell latex that a given block has to be left 'as is' (that means not formating it, not squeezing the newlines, indenting it correctly, and syntax highlighting it).

My first attempts where quite hand-crafted solutions, mixing a verbatim environment and fitting it into a table with just one row and one column.

Then I found a package called listings. It's a farily complex package, with lots of options and parameters, but for me, I just can use it nearly vanilla.



If you want, you can use pretty complex configurations:

\lstset{ language=C++,
prebreak = \raisebox{0ex}[0ex][0ex]{\ensuremath{\hookleftarrow}},
% frame=single,
% backgroundcolor=\color{lbcolor},

Then, you just embed your code inside a lstlisting environment

class Funcio{
map dict;
operator()(int param1){
if( dict.exist(param1)){
return dict[param1];
double resultat;
// calcular i omplir resultat ...

return resultat;


With this you can paste codes with a great look.

As always, here are the sources I read to write this howto.

Ah, I know the code in the screenshot does not work, but it's just a kind of pseudocode to illustrate memoize, closures, and the c++ functors aproach (a half-solution to emulate closures and stateful functions in c++)


Bill and Ted

Una charla de TED, genial como siempre, pero si cabe más emocionante y emocional que la mayoria. Mezcla de las curiosidades tipicas de Ted en aspectos de la musica y las emociones que provoca. Buena reflexion sobre las expectativas de duración y de 'vida' de las cosas.

dying ? Nah.. you ain't seen nothing yet!



Por otro lado, microsoft lanzó ayer windows 7. Noticia en el mundo.

jueves, 22 de octubre de 2009



Yesterday, I got my google wave account (I was kindly invited by ecarnevale). For the moment, I haven't played with it yet, and added to the fact that I only have a handful of contacts that have their wave account, I still have to see its power...

Many friends already asked for invitations, but currently I don't have google wave invitations to give away.

So from now on, you can find me at raimonster googlewave.

Btw, contact me (by commenting) if you want an invitation (only if you think you deserve it ;) )


martes, 20 de octubre de 2009

cmake tutorial. First steps

We all have messed up with makefiles, and most of us have been really annoyed with them. Writing them is awful (and all that space-vs-tab thing...yuk!), and maintaining them for medium projects is not very pleasant either.

I've tried to understand autotools a couple of times, but never made through. Difficult and outdated docs, and when I passed the 'hello world' project, I didn't find it very intuitive. It's a pity when you have to study a tool for a month to get simple things done.

cmake tries to make the process easier while improving the dependency tracking between files. It's also multiplatform and multi-compiler , so you can use it for later use of gnu make, or VC++ projects.

First, we can start with a trivial use case. Good old 'Hello World'. Well, you imagine the code.

#include <stdio.h>
int main(int argc, char const* argv[])
printf("Hello world!\n");
return 0;

Save it in a file called helloworld.c and we're ready to write a file for cmake configuration.

Create and edit a file called CmakeLists.txt and add the following lines to it
PROJECT(helloworld C)

SET(SRC helloworld)

ADD_EXECUTABLE(helloworld ${SRC})

Then just execute "cmake ." in that directory, and you'll see you have a Makefile (and lots of other files and dirs. For the moment, what you have there is already usable. For example you can use make clean too.

After this baby steps, we can go to a more complex example. Let's use a c++ example, with a main file and a class file.

/*****Hola.cpp ****/
#include "Hola.h"

using namespace std;
void Hola::saluda(){
std::cout << "saludo" << endl;
/*****Hola.h ****/
#ifndef HOLA_H
#define HOLA_H

#include <iostream>
class Hola{
Hola() {};
~Hola() {};
void saluda(void);

#endif /* ----- #ifndef HOLA_H ----- */

/*****projecte.cpp ****/
#include <stdio.h>
#include <iostream>
#include "Hola.cpp"

using namespace std;

int main(int argc, char const* argv[])
Hola* a = new Hola();
return 0;

Then we'll have a little more complex CMakeLists.txt file

PROJECT(projecte CXX)

add_definitions(-Wall -W -ggdb)

SET(SRC projecte)



A few observations:

  • Note the change in the first line from C to CXX.
  • add_definitions directive is to add flags to the compiling process.
  • INSTALL directive enables 'make install'. DESTINATION bin tells to install in $prefix/bin (usr/local/bin normally) .
  • We don't even have to mention Hola file, because it's included by projecte.cpp, and cmake will track the dependency, and build only in case of modification.
Now we'll build the same program compiling Hola class into a separate library. That's how the CMakeLists.txt file looks like

PROJECT(projecte CXX)

add_definitions(-Wall -W -ggdb)







Everything is nearly self explanatory, right? well, you can then rerun 'cmake .' , and a new Makefile will be generated.

There are some good tutorials out there. Most of what I found explain the same in different blogposts with some example CMakeLists.txt


lunes, 19 de octubre de 2009

Leones polares

Estoy tan nervioso que me he ido a fumar un 'cigar' a la calle.
Con ese fresco pensaba que me despertaría, o al menos me refrescaría un poco.

Y resulta que no, que sigo igual que antes.

Dice Punset que el ser humano es el único animal tan 'avanzado', que puede hacer que su cuerpo esté en el mismo estado de tensión que cuando le está a punto de atacar un león, aunque el león sólo esté en su cabeza. No hay ningún puto león, ni ninguna hiena, ninguna cuchara, ni nada por el estilo. Estás en casa, aburrido y sin que pase absolutamente nada a tu alrededor, y sin embargo, cierras los ojos, ves el león de frente, te enseña los dientes, y tu arrancas a correr.

Pues colega, voy a soltar el yunque y voy a seguir corriendo hasta que esté bien lejos, pero no me gusta un puto pelo estar huyendo de fantasmas.

jueves, 15 de octubre de 2009

Mis palabras contra mi

Hay palabras que quieren estar en tu texto.
Aunque no peguen.
Aunque tú no quieras su significado.
Creen que el texto les pertenece,
y que tienen derecho a pedir aparecer.

Porque ellas estaban en tu mente antes,
porque ellas son más bellas que las otras.
Y tu les abres la puerta y les dices que 'pasen'
Pero que no toquen las pelotas.

Y ya no se si soy las palabras que digo,
o soy las palabras de las que escribo,
o un puto actor de 3 al cuarto,
al que se le han acabado las ganas de hacer rimas, cojones ya.

How I use Emacs + irc (or erc for dummies)

Given a certain interest by some about using emacs as an IRC client, I'll try to explain how I use it and the configurations I use.

First thing to know is erc. erc comes bundled with emacs from 22 on (IIRC). The way to run it is fairly intuitive to any emacs user: M-x erc

After that command, you'll be asked some questions, but defaults are ok for most situations (freenode, yourUser, :6667 ).

Tip: If you happen to be behind a corporative environment (ehem, $uni/$work) , try ports 8001 or 7001.
when you're in the main freenode buffer, you can use IRC commands like /join /nick /names (when in a channel) /query /dcc .... but you better learn some shortcuts.

As most major modes, erc shortcuts start with c-c. then:

c-c c-j : /join

c-c c-n : /names

When something new happens in any erc buffer, it will apear in the modeline, and you can move to it with old c-x b , or c-c c-b will use a cooler way to change between erc buffers (only erc buffers, using ido-mode and with acceptable guessing).

if you have to visit many erc buffers, you can use c-c c-space, to travel to erc buffers with changes. after the last erc buffer with changes, you'll go to the last non-erc buffer you where last time. Great, isn't it?

you can move pretty well around erc buffers. Now the autojoin thing.

(require 'erc-join) 
(erc-autojoin-mode 1)

(erc :server "irc.freenode.net" :port 6667 :nick "mynick" )
(erc :server "irc.perl.org" :port 6667 :nick "mynick" )
(setq erc-autojoin-channels-alist
'(("freenode.net" "#channel0" "#channel1")
("co.uk" "#channel2")))

With this config, every time you start emacs, it'll start an erc session and join automagically to channel0 and channel1 in freenode, and channel2 in perl.org server . if you don't want to autojoin automatically, well... deactivate autojoin.

Another good trick is the readonly channels.

That's all for now. If you investigate on erc, you'll see it can autosave logs, and so. It's quite powerful, but I think don't have the need for so much power :)

Me perdí woodstock, cause I was high...

Estaba haciendo un poco de ego-busqueda por google, para ver si mi post del hackathon-breakout se habia propagado de alguna forma por 'el internet'.

Pues, cual es mi sorpresa cuando hoy veo que había ganado una entrada para el pre-estreno de la penícula 'Destino Woodstock' en un concurso-mailing de radio3... para hace 2 semanas.

No es que fuese fumao (yo no consumo droja), lo que pasó es que yo iba confiando en que mandarían un mail en el caso de ganar, y resulta que no, que tenia que haber mirado en este link , para ver que sí, que era uno de los 150 seleccionados para ir con una pareja a ver la pelicula de marras.

Pues visto lo visto, acabo de suscribirme un google alert que buscará mi nombre por todo 'el internet'... osea que cuidado lo que dices de "raimon grau"..... Big Brother is watching you..... Al menos así me enteraré cuando me pongan una multa, o cuando me den un premio nobel :D .

miércoles, 14 de octubre de 2009

Breakout Cornella and Smalltalk-fluidDB hackathon

I just came back home from the Breakout event (Work outside your office initiative).

The balance is really positive. Although not having comunicated or met many people, I think I talked, met and saw after long time the right people :) .

We had internet connection just 20 minutes after arriving there (WIN). Just after that, I could download all the pharo stuff (vm, image and our starting codes). We had a small brainstorm of what we should do during the day, and reread the docs to clarify some things.

After a few minutes, Terry Jones broke into the party (WIN), and we sat down again in the grass and had a master explanation of fluiddb philosophy and expectatives. Then there were lightning talks which I attended partially because I found an 'old professor' of mine (Toni Cañabate, a great and wise guy) and we got distracted of the talks (WIN) . Xavier Noria then arrived, and explained to Jordi Delgado and me some gotchas he had to solve for his Net::FluidDB lib. A perl scalar internals masterclass in 15 minutes.WIN.

After hacking a bit more, we had lunch and some small talk (in the chitchat meaning). Terry and Xavier Noria were with us there too.

We spent the afternoon hacking a bit more, and we finally got to create, retreive, and get the info related to namespaces (Jose Garcia and Bernat Romagosa WIN). Although it's very little compared with what we'll have to write (FAIL) , we 'got' the concept, and we managed to have the basic comunication flow (POST and GET). Apparently, the rest of the lib (at this low-level lib) will be tunning the queries, but the conceptually difficult things are done (or at least, we like to think that).

Btw, fxn, the /(p(erl|ython)|ruby/ guy, explained me some tricks he used in his Net::FluidDB perl lib, for example, moose at its full power (WIN). That means lazy constructors, roles and the like. I'll post something about that soon.

I still don't have any photo (FAIL), so I'll update the post when I find the f*cking usb-mobilePhone wire that I think I lost (FAIL). Fxn has a twitt showing a photo

Overall it was pretty good, I only regret not having had the time to program a bit more (FAIL)... but well....

PS: I don't want to end with red colour, so I'll say that at the WTC (Breakout place) there were *lots* of nice chicks. Lots more than at my $workplace, so Breakout WIN and Citilab WIN for organizing it.

PS: I'm exhausted of adding links. If you want more links in this post, tag a word with a link and refresh.
You wish :)

martes, 13 de octubre de 2009

Stop tracking a file in Mercurial

Since I read The definitive guide to mercurial, I've been using mercurial daily at $work , and following a branch-per-feature workflow with more or less success (I'm very satisfied myself, but I keep forgetting the commands).

Today I took a project I was coding some time ago, and when I did my first commit... I saw mercurial was tracking a binary file I didn't particularly wanted to track (some temporal .o in CMakeFiles dir).

Here's what I did to untrack ChironEA.o file:

rgrau@ares [ ~/chiron ] %hg commit -m "FooBarBazQuux added"
rgrau@ares [ ~/chiron ] %hg vi
rgrau@ares [ ~/chiron ] %hg rollback
rolling back last transaction
rgrau@ares [ ~/chiron ] %hg remove src/CMakeFiles/ChironEA.dir/ChironEA.o
not removing src/CMakeFiles/ChironEA.dir/ChironEA.o: file is modified (use -f to force removal)
rgrau@ares [ ~/chiron ] %hg remove -f src/CMakeFiles/ChironEA.dir/ChironEA.o
removing src/CMakeFiles/ChironEA.dir/ChironEA.o
rgrau@ares [ ~/chiron ] %hg commit -m "FooBarBazQuux added"

Little by little, it seems I'm starting to do things the right way (tm).

Btw, I've packaged latest mercurial version for vectorlinux (yeah, that little fast distro I happen to use and recommend)

Good API Design

A great talk given by Joshua Bloch (google engineer) presented at Javapolis 2005 and OOPSLA 2006 about tricks and key points to keep in mind when designing an API and SPI. The recording is from Javapolis conference, and recorded by infoQ (the greatest platform to watch talks at present day).
Now the links:


I have to confess I didn't thought about most things that Joshua says there :( . Some things I do right (intuition?) and some of my APIs suffer from lots of bad habits commented here.... Well, It's never too late to learn...

lunes, 12 de octubre de 2009

gtd and speedreading

As you know, I've started to read the GTD book. For the moment it's being a fairly good read. Very clear concepts, written in a very straight way, and there's little to no 'boilerplate'.

Another book I recently started (that means, this very same weekend) is 'Teach yourself speed reading'. Another clear book with some key concepts to boost the reading proces.

Both books have some concepts in common (in fact, efficient reading is a particular and speciallized version of getting something done).

For example, knowing your concentration and don't forcing yourself to do things you will do better in other conditions. Or the 'prepare' or 'study your enemy' part. both books put lots of emphasis in this preliminar concept of knowing the 30000 feet picture.

Part of this phase is asking you "what you will get of completing this project (reading this book/article)" . Once you achieve it, stop reading. That's a very pragmatic approach, but GTD also have the 'next actions' list, where there are sentences of phisical actions that will move the project on, towards the desired direction.

They both sound like an agile methodology for life, don't they?

Well, I wanted to train a bit of speed reading, so I started to write a program to skim texts. ATM it uses opengl with glut. I'll post the code when it is something half decent.

Warning! c code ahead!!

Here's a good opengl survey about fonts.


sábado, 10 de octubre de 2009

Benchmarking perl

I had a little code that worked perfectly for what it had to do (process every line in a file, and get a list of unique lines (after being processed)).

The 'process' I had to run on every line was a simple substitution, so I thought of Algorithm::Loops. I used it and worked really well, but then I thought about performance, and tried some other approaches:

Well I could clearly see that while version is the winner, and it really makes a big difference. I suppose this is because Filter takes <$fh> as an array (in list context), and that is slower than the iterator version (just guessing).

Here's the code:

And the results:

Rate filterChomp match regexBarraN while
filterChomp 9.49/s -- -19% -24% -64%
match 11.8/s 24% -- -6% -55%
regexBarraN 12.5/s 32% 6% -- -52%
while 26.0/s 174% 121% 108% --

Well, appart from keeping the while version for my app, now I have a template for bencharking perl codes. Following the same technique than in one of my other perl posts, I've written a template file to be easy to paste in a .pl file from vim.

viernes, 9 de octubre de 2009

diario de sabadell PWNED!

I just browsed to www.diariosabadell.com, and the top front page seemed ok...

In the middle of the page.....


Last august, there was a massive spanish-journal-sites hack with similar photos (I was at YAPC::2009, so it was 3rd-6th Aug). Journals sites seem to attract hackers...

UPDATE: Keeping it -Ofun

4 hours later, I can't decide if the whole journal DiarioSabadell is a total joke , or they haven't noticed they are beeing fooled.

GTD tools: remind

As you probably seen in one of my last posts, a few days ago, I started David Allen's Getting things done book, and I think I'm starting to grasp the pragmatism of the method. I'm nowhere near fully implementing it in my life (I've only read 1/3 of the book) but googling a bit, I see tools and methods that people use.

Some time ago, I installed remind on my box, and tried (read FAILED) to use it regularly, but now I think it's time to give it another spin in order to manage my timmed 'stuff'.

Remind is a commandline tool (O RLY?, YA RLY) that helps you to manage your schedule/calendar events. One of the big wins of remind is that everything is stored in a plain text file, making it really easy to be parsed or edited from everywhere.

The default file for reminders is ~/.reminders .

Let's see a sample reminder.
If I run remind command, it will print the MSG line.

Say you want it to mail your friends about your cheezburgr event.
REM Oct 2009 RUN mailfriends.sh
Easy, right?

Now let's go with periodic events. For example, I'd like to know when I have the next smalltalk meeting (every tuesday), and want to be alerted the day before (sometimes the same day is too late)
REM Tue +1 MSG Smalltalk meeting at Citilab %b.

Or Next Perl Mongers Barcelona meeting (last thursday of every month)
REM Thu 1 --7 +1 MSG PerlMongers meeting %b.
I think this deserves some explanation. Thu 1 matches when both Thu and 1st day of the month are true (That is the first tuesday of the month). Then the --7 substracts days to the previous date. That means the last Thursday of a month.

There are ways of setting reminders for a given day AT a given time, and set a duration, but I think that's all I need for this part of the GTD implementation.

Btw, If you want more info on remind, there are some good howtos and tutes online, and remind has a mail-list too (the mail archive is only accesible to subscribers though).

miércoles, 7 de octubre de 2009

Time to change passwords!

Thousands of hotmail passwords have been magically revealed on the intertubez.

Mabe iz time to change ur pazz , just in case.

In fact, when you last changed your hotmail password? O RLY? Never? yay, then you're like me, and kept your password since 1995.

More info in this link.


lunes, 5 de octubre de 2009

Learning to Learn

When talking about curiosity, and learning in general, I've got itchy feet. That's a well known fact.

Unfortunately, it's also a known fact that my perseverance in a field is not very notable. I've only managed to keep the interest for a long time in a handful of things (from 16 y.o. to 18 in reverse engineering, from 20-now optimizing procedures (say bash, vim, zsh, screen, tiling wm...) and since I was 24 on I've been quite fond of perl) .

I get amazed by new technologies, or programming languages too often, and although that makes me a very aware person of the state of art, I'm not an expert in any of theese. I call myself the 'master of hello worlds' .

Examples are:
  • Io
  • Haskell
  • Smalltalk
  • Catalyst
  • Lisp
  • Scheme
  • zsh
  • factor
  • emacs
  • ...and a looong list...
For some time I've been addicted (among other things) to trying new programming languages, and read a good amount of literature about those (paradigms, implementations, tips 'n tricks)... But lately I've felt the need for something more general. A kind of 'programming best practices', or some patterns book (not the GoF one but one I can read from cover to cover).

I took a look at some smalltalk book, or more generic books (O'Reilly beautiful XYZ) . But I wanted to go more meta. And remembered a thing I wanted to do since I was about 20. Empower and speed up daily tasks.

Some time ago I read 'Mind Performance Hacks', and was good enough, but most hacks weren't appliable to my daily life.

As an example, this weekend, I started to read articles of:
  • lisp
  • Catalyst
  • squeak
  • FluidDB
  • Perl
As you see, I need to focus (or a girlfriend). And organize myself. And Thought that in order to focus, I'll read David Allen's "Getting things done" once for all. It's been in my TODO list for some time and now I feel it's the moment.

So my TODO ReadList, has grown by 2: GTD, and a Speed Reading book. That's not a very good start :) . Meta-procrastinating Rulez!

Bah, I doubt this post can be useful to anybody but me... If you've read until here, sorry ... that's all... at least you can google some of the words I put here, and learn real things.


PS: Want more titles? ask in comments.

domingo, 4 de octubre de 2009

Perl 5.10 regexes

It's been around for 2 years (Perl 5.10 was released in December 2007), but I mostly used it as 5.8.8 (I didn't think that my perl level would make any difference between so near versions).

I've seen some of the improvements from 5.8.X and I think there are some things that even for newbie/intermediate perlers like me might be of interest.
Say "eeeoo"

Ok, this is probably a feature that won't make you migrate to 5.10, but it's there, and starting using it is trivial. Put it short, For all x , say x == print x ,"\n"; it's shorter to write, and you don't have to write the "\n". It's like writeln or println of other languages. We're done with that.

Defined or

I love shortcuts, from ||= to 'open or die' . I think it's a very elegant way of avoiding an extra if.
As you know $x ||= 'foo' is the same as $x = $x || 'foo' , so if $x evaluates to false, then $x becomes 'foo'. The problem with perl is that 0,'' (that's empty string), and undefined , all evaluate to false. //= is the way to check if something is defined in a shortcut way.


Finally, perl had a switch/case statement. In fact, to emulate the 'switch/case' statement from other languages, we could use dispatch tables (being much more flexible than java'sor c++'s one). Given/when is far more flexible and advanced than usual (comparison by ==) cases. It uses the new smartmatch operator, allowing to compare different type of things and doing 'The correct thing" (tm)

Smart Match

Ok, so what's the smart match operator?. It's a binary operator whose syntax is ~~ , and it tries to compare left operand with right operand in a DWIM (tm) way.

For example, %hash ~~ $scalar searches if exists $hash{$scalar} . Array ~~ Regex , greps the array with the Regex. You get what I mean.... for more info, look at perldoc perlsyn.


Now what had to be the main topic of the post (that will end in just another section).
As you can see in perldoc perldelta of 5.10.0 , there have been many improvements on 5.10 regex engine. I'll only cover a few of them basically because of 2 things:

1) I don't understand everything there
2) laziness

The most practical new feature is "possessive quantifiers". We know perl regex quantifiers are greedy unless we put the '?'. That works when the given match has lots of possible matches, but there's a backtracking involved that maybe you don't need.

Maybe you want really greedy matches, as in greedy algorithms (when a decision is made, it stays forever). If you add a plus sign just after any quantifier, you make it 'non-backtracking', so if it 'eats' a character, it won't permit it to be in the next token in any circumstance.

I've come with a stupid example. Say we want to match pairs of letters in a string, and have the last pair or the last one (odd length) in a separate place:

print $2,"\n";

print $2,"\n";

what happened in the first case was that the pair matching advanced untill the end of the string and when noticed that the last (a+) had to match something, it backtracked twice until both conditions where satisfied.

The second example was easier because when it couldn't match a pair, a spare 'a' was there to fit in (a+) slot.

Now we'll try with ++ .

print $2,"\n"; #error

print $2,"\n"; #ok

As (aa)++ makes it unbacktrackable, there's no match. So, keep in mind it can really speed up things, but it won't match same things, so be aware of this.

Another regex new feature is named captures. now you can name captures with (?<foo>pattern) . after doing the match, you can retreive the matches through the %+ hash : $+{foo} .

There are other improvements, but I'll leave them for now.

Only tell you that 5.10.1 is already here, and just improved on that, allowing more funny ways of using smart match and given/when. Perl 5.11 is out too (but it's a development release).

If you're hungry of perl new things, have a look at Perl 6. If you want more regex hardcore, take a look at Damian Conway's Regexp::Grammars.

That's all for now. Thanks for reading.

sábado, 3 de octubre de 2009

squeak (pharo) + fluidDB + UIBuilder

There hasn't been much activity in my blog last week. That's partly because I was on vacation, but I haven't stopped hacking completely.

For instance, I could finish reading 'Effective Perl Programming', by Joseph Hall and Randal Schwartz. A very good book, full of little tricks on how to optimize perl codes, or good practices, or even tipical gotchas perl 'offers' you.

It's a very practical book, and I could apply what I learned from the first minute I started reading it. Thanks to CDamian for giving me this book. If you happen to know me, and you want to read it, just drop me a line.

I've been reading a bit about FluidDB, the new database technology with wiki essence. At GTS (grup de treball Smalltalk (Barcelona smalltalk users group)), we thought it'd be a good idea to write a library to manage fluidDB from squeak. We mostly want to port fxn's perl lib to squeak.

We chose fxn's one because his implication on fluidDB project. It seems to give us more confidence.

Anyway, I had looked at some docs last week and commented some things on gts meeting, and this week, when I returned from holidays, I saw Jose had already written a mini lib to query fluidDB sandbox. For the moment, it's a simple lib that only allows GETting queries, but it's ok for us to get used to fluiddb usage.

When I was trying it, I got tired of modifying the query string, and thought of doing a GUI to ease my work. Then nullPointer's UIBuilder called CLFramework came to my mind. I installed it through monticello, and ran it. No problems so far.

I found a little bug that got fixed immediately (It's great when devs are around at IRC, isn't it? ). Well, and here it is! a fully Barcelona pseudo-application, unifying FluidDB, with some gts work.

The point is that writting a handful of lines, I got something quite pretty and acceptably useful. I also had the oportunity to learn how to make simple GUIs using nullPointer's CLFramework (and spotting a bug) that always adds -Ofun to the journey.

Now the screenshot...

Have fun, and keep hacking my friends.

More to come on fluidDB next week (I hope so)

PS: Ah! When I was trying to fix the bug, I looked at some keyStroke methods, and discovered that cmd-Del ( alt-Del ) closes the foxused window in pharo. It's like Alt-F4 on most win/linux systems. You're welcome