lunes, 20 de diciembre de 2010

PLOP Loops Over PLOP

Quines, like JAPHS, are great hobbies for us, little riddle-solvers.
Here are the 3 most amazing quines I found lately.

third order quine . And here's a SO post discussing a bit about it

ruby rotating earth quine

The new kid on the block. Judge yourself.

For those who didn't bother to google or wikisearch, here's a quine guide

And here, a lisp quine that shows the greatness of simplicity.

((lambda (x) (list x (list 'quote x)))
'(lambda (x) (list x (list 'quote x))))

PS: This post is under 'mis cosas' (personal) tag, because there's much more than programming involved in the mind process to understand these things. So yes, quines are a cool concept even IRL.

sábado, 18 de diciembre de 2010

Text Driven Development

As I already posted, I got a new job in Barcelona, doing mostly apps in Rails (particularly ubiquo, cms)

Luckily, the company is pro-gnu, so I can use linux with all my usual configs. Using ratpoison in a double screen is an awesome experience.

For the moment I lived between the two worlds (gnome vs ratpoison) because I'm continuously asking things to more experienced people, and they usually want to use the mouse when they are on my computer. And I haven't configured everything yet.


Last week, I was assigned a project and was given a 100+ pages document with the functional analysis of the project. First thing to do was reading it and making good outlines of it to create a mental model of the program.

I decided to use emacs org-mode to do the outlinings, and probably the TODOs and Schedules. IT's pretty neat, and doing everything with text files gives me a kind of relief, that everything is under control. In fact, that's one of the things that gets on my nerves about pharo. Being able to use your well known tools in a synergic way is great (IMHO)


After that, I created an UML class diagram.
"We use argouml" someone said. Well, argouml has improved amazingly since the last time I tried it, but honestly, for me it doesn't cut. It has some kind of code generator (for java) and some design-critics, that seem cool enough to use it, but given that the web development constrains you to use minimal oop features, I could not listen to the design-lint.

After finishing the damn UML, I looked for other tools that could do pretty UML diagrams from ascii. And they do exist. Great! I'll try to use them the next time. I think plantuml is a fairly good option and, guess what? you can integrate it in emacs.


On the other side, on wednesday, I did a talk at about pharo regexes. The slides where presented in a terminal, in plain ASCII, using a small app borrowed from fxn. Btw, the talk went pretty well. Very informal and kind of simple for people versed in regexes (smalltalk regexes do not have any special unique feature but the opposite, a bit simple IMO), but I think maybe 30% of the people didn't know about regexes and used them just copypasting, so I extended my talk to touch some more theoric side, and in the end, I think everyone learned something.

Btw, if you feel like implementing a regex engine for smalltalk, you can get ideas from this paper. A good read IMHO

jueves, 2 de diciembre de 2010

HAHA! You're not regular anymore!1

Via HN I saw praprog released another magazine, this one fully dedicated to ruby (What a coincidence! :) )

I skimmmed all the articles but paying more attention to a couple of them:

One of them talk about new features of Ruby 1.9.2. It seems ruby is getting faster and faster on every release (a good thing since speed is one of the major 'problems' I had read about ruby).

Another place where it has improved is on the regex side. Now ruby regexes allow named captures (feature added to perl in 5.10 IIRC), and recursive regexes (The not-so-regular regexes are here) there are some flags like /x /g and /k, that let you reference captures more easily than plain old \1, \2 ...

All in all, quite cool stuff that makes me feel a bit more at (perl) home.

Unfortunately, I couldn't practice with rails yet. I did some progress on ruby koans though. A busy week in Tenerife.

sábado, 20 de noviembre de 2010

I'm a LOL programmer (wannabie)

In my new job, it seems I'll be writing ruby (on rails).

I've been trying the language in my spare time, and it seems a fairly good compromise between Perl and Smalltalk.

Except a couple of features or idioms I saw, everything else was quite intuitive or easy to understand (at least coming from Perl/Smalltalk).

+ Sigils do exist, but denote scope oposed to type.
+ __DATA__
+ '=' can be part of a method name. And there's some magic involved there. def method=(attr) can be used as an assignment (sintactically) as parens are optional.
+ Integer class can be expanded or subclassed.

Here are the codes I wrote to grasp the language. These are the usual examples I write in every language I try to learn:

- a program to center paragraphs.
- guessing number
- Network with hosts that pass messages one to the other.

Here is a link that I found useful about ruby patterns and idioms.

lunes, 15 de noviembre de 2010

Last but not least

I'm leaving my current $work, and changing to another one. Being the first one I'm starting not as an university student but a 'professional' one feels strange, and I'm somewhat thrilled. Will I be good enough for the job? I hope so :)

These last days I'm reviewing some of my old code with the guy who will inherit my codes. A cool programmer, with lots of knowledge I wouldn't expect from an average young programmer (it's actually a bit older than me but, you know... not everyone reads 'refactoring', code complete, and GoF just for fun :) ). We've had good times. Transfering info would be quite more difficult without such a good learner. In little less than a week, he also explained me some ins and outs about some agile methodologies, or good programming practices (some cool refactorings, Log4X modules, etc...). We both learned quite a lot from each other.

Some of the neat advices that I liked.

- use Logging modules. They pay off. And they are quite easy to set up (opposed to what I thought)
- refactor any piece of code that is repeated more than 1 time (if it's easy to do). calling a simple join(',' , @array) three times in the same function can be refactored into a meaningful name sub. You get the name explaining what your code does, and if you want to change ',' to ':', only one change does it.
- Codes that you write separated by 2 newlines, like paragraphs, and start with a comment that explains what that snippet does, are screaming for a new function. You can use the first words of the comment as a hint for the function name.
- Take a look at AOP, it's cool. a really cool thing.

jueves, 4 de noviembre de 2010

I'm in ur shell, watching your repos

I'm using more and more a little script that Cornelius called (for cpan search)

It's dead simple, but great anyway, and, it lets me use ratfinder to browse cpan modules. And to give credit where the credit is due, I'll just embed his gist.

Simple idea, neatly used. curl, file tests, zgrep and some bash bits.

lunes, 18 de octubre de 2010

Courier new WTF (or, monospaced is not enough)

Via reddit , I found this pearl:

From wikipedia:
Courier New is used extensively in programming. For example, online forums, such as phpBB, SMF, and vBulletin, will use Courier New for <code> blocks; on Microsoft Windows it is a default monospaced font for a variety of applications, such as Notepad, Visual Studio (although the Consolas font family is provided as an alternative

Seriously, if you have to write code, go and get a font that doesn't suck. Monospaced is not enough.

viernes, 15 de octubre de 2010

ubigraph: an interactive 3D graph creator

A few days ago I read a funny post on HN. A guy was presenting some clojure code that used ubigraphto produce 3d navigable graphs.

To make ubigraph portable and interoperable with many languages, they present the app as an independent window (embedable, I hope) with its own process that acts as a XML-RPC server, so if you don't have an specific API for your language, you can use plain XML-RPC calls.

I've written a simple fibonacci function with a callback that draws the flow of the calculations.
Here's the code, and a (static) image of the graph.

To See how memoizing works, I've modified the code a bit using Memoize and a normalizer function and now we see how the number of steps is O(n).

domingo, 19 de septiembre de 2010

ESUG 2010: It's awesomeness all way down

ESUG 2010 was held at Barcelona (well, technically, Cornellà). For people that don't know what's ESUG, it's one of the most important smalltalk events worldwide.

A week full of talks, great fun, hours of hacking and chatting with other smalltalkers.

The weekend before the conference, citilab was open to all smalltalkers who wanted to participate in the SmalltalkCamp. Two days of coding and meeting with other smalltalkers. I started rereading the seaside book and got some help from Bernat. It was fun to see the creators of what I was trying to understand (seaside) walking and coding around. Another nice curiosity was when someone entered the SmalltalkCamp with an OOPSLA t-shirt. It was like: "wow, important people around!" :)

Monday, at 9:00 the conference started officially, but by then, I had already met some great smalltalkers. Here is the schedule of the whole esug.

90% of the talks where amazing, I mean, good contents, with an accurate dose of humour, and talks given by people with nice speech skills.

Xtreams (Martin Kobetic), Design decisions behing Patagonia(Hernán Wilkinson), All Esteban Lorenzano's talks (mars and reef), Helvetia (Lukas Renggli), Stephane Ducasse's talks, Richie and ..... too many good ones to remember the name of all.

Citilab made a great job organizing it all, and we, the local group had very little to do (thanks to volunteers too). Myself I just had to help some people with maps, subways and take some smalltalkers to 'visit' Barcelona. :)

I bought a special edition of the seaside book and got it signed by Ducasse and Renggli. WOW!

Well, it's been a short and late post, but I can't write a post with all cool things I learned there, so it's more a "I've survived" post than a "hey, look what they showed us".

Soon, citilab will make the recordings of ALL the talks available on the web. I think they'll be hosted in cincom's servers. I'll post about that when it effectively happens.

I met many people and had lots of fun talking not only about smalltak but technology in general, and life, universe and everything. Mostly argentinians but not only them. Gabriel, Gabriela, Hernán Wilkinson, Leandro, Richie, Javi, Nico, Ricardo, Esteban Lorenzano,... Great people.

martes, 7 de septiembre de 2010

Capture the flag with Moose

In today's post, I'll show some ways to get program options via flags (--flags) I discovered recently.

CPAN is crowded with Getopt::* modules, but I'm going to explore the Moose universe.


At $work, we often have write commandline apps that end with lots of parameters and flags, and 'shift @ARGV' is not an elegant nor flexible solution. I've been using GetOpt::Long for years, but now, using Moose, I discovered an extension Called MooseX::Getopt.


This Moose eXtension allows you to fill attributes of an object directly from commandline.

We just have to use MooseX::Getopt in our Class, and change the creation of the object from Foo->new to Foo->new_with_options.


Now, our program can get all Foo's attributes through the commandline. Note that if you try an invalid flag, it will output the accepted ones.

- But wait, I do not want to allow users initialize all attrs.

Ok, then we should hide the attr under a name beginning with underscore, and set the accessor to our desired name. MooseX::Getopt will understand you don't want it to be accessible through command line options.


The summum of DWIM is you can also exploit the same introspection capabilities to enable configuration files to setup the execution of the files. And it costs you just one line.
with 'MooseX::SimpleConfig';

The code above will activate an extra flag (--configfile) where you can indicate where to reach the configuration file.

There are more goodies you can add on top of these modules, but for now, I think it's enough for me. :)

From these findings, you can see, Moose is not only a great OOP platform for perl but a higher level base for perl hackers to put stuff on.

Thanks Perl community.

viernes, 3 de septiembre de 2010

Parallel::Iterator. Independent tasks are independent


Today's module is Andy Armstrong Parallel::Iterator. I discovered it through Dagolden's blog, and tried it by myself that same day.

The idea is simple. You may have many slow tasks to do that don't have dependencies between each other. A typical example is fetching for webs using lwp, but I can think of lots of processes doing similar things, for exmple, ssh-ing some command to many different servers.

So it's like an autothreading map. Well sort of.

As tasks are not guaranteed to end in order, and you probably want to know which source procuded each result, the function you'll apply to each element will have to take not one but two parameters, the first being just an index that you can throw away. At least it seems so. I'm not sure I understand it fully, but for the moment that's what I gathered.

The module provides two sets of functions, iterate, and iterate_as_(array|hash), iterate returning tuples ($index, $result), and the others returning the wanted structure.

But what puzzles me is that I cannot easily migrate a normal map to this parallel::iterator because functions sent to map have to accept an extra parameter (just to throw it away?). Two days ago I read another post related to it but it didn't comment anything about that 'strange' use of it.

So I hacked a higher order function that mimics map signature but uses parallel::iterator. I'm probably missing something because it's strange the author didn't provide something like that in the module. Anyway, here it is:

I'm using the iterate_as_array because I want to mimic map signature, so the array to iterate can't be lazy built. That's another feature of Parallel-Iterator : not only the evaluation of the method can be lazy but also the generation of the list.

Ideas? Suggestions? Insults? Go on and comment :)

miércoles, 25 de agosto de 2010

Using AUTOLOAD to build html code

Last week I found a new blog about Io. It's been a long time since I used Io, but maybe this blog will make me look at Io Language again.

In his last post, Dennis Ferron comments on _why's web server yown written in Io. One thing he comments is the slot 'forward'.

As he says, forward is a kind of catch that gets called when a message has been sent to an object and that object didn't have a selector with that name. _why exploits this feature to write an html builder based on that.

What he doesn't mention (I think he's leaving this for another post) is about lazyness. The way _why wrote forward method.

If you define a method without arguments but you call it with some, you can still access them, but with the difference that they won't be evaluated by default. That's called lazyness, and allows you to define the evaluation order of things.

So in the code

title("O HAI")

forward will trap html message before title or strong.

In Perl, there's a 'lightning rod' function too, called AUTOLOAD. You can do pretty much the same, but the difference is that perl will ALWAYS evaluate parameters sent to a function before calling it, so the same code would trigger AUTOLOAD on the 'title' call, then 'strong', and last, 'html' and you have to fill the string from the inner tag to the most generic one.

Here's a gist code that emulates Yown in Perl 5.

Good luck Dennis with your new blog!


lunes, 16 de agosto de 2010

Memoizer in common lisp

Last weekend I finished a fast-read of Ansi Common Lisp. I didn't do the exercices but I did pay attention to code examples (those are what make me really understand things).

Overall I find it pretty good, but a bit simple provided you already know something related to the lisp world.

After finishing it, I tried a couple of tricks in lisp, and was surprised how easy it was to come with working codes of a memoized function. Once you have a memoized function, why not convert it to a memoizer function?

Here it is. (If you're reading it on google reader you won't be able to see it, better read blogposts from the original site)

(setf memofib (memoizer #'fib))
(funcall memofib 10)

And you have now a faster fib than before.

Question: how should I change it to make a generic memoizer that memoizes not only unary functions.
In perl I'd have to just pass @_, I suppose changing arg to '&rest arg' and change funcall to apply would do the trick... I have to try it. Later.

More readings: Scheme R5RS.
I read the part I hadn't read before. I have to say even the scheme spec is minimalist, well written, and didactic. Following the language philosophy even at docs level. :)

And a bit more: A paper on Scheme macros. I think I get them, but I don't see much use for them. I suppose I'm still an average blub programmer.

jueves, 12 de agosto de 2010

Sharing interests with others

Here's another of those shitty trackback posts that add nothing to the original post:

I've read a blog entry that explains what I think about sharing interests with others better than I could ever have written.

I found it in HN, so it talks about sharing prorgamming interests with your partner.

Another funny post of the same kind, in a Bug report format. Hilarious too.

martes, 27 de julio de 2010

Rakudo * is next door

Rakudo *, the first official distribution of stable (yet incomplete) perl6 interpreter rakudo. Devs haven't focused on optimizations but features, and it's quite useful as it is IMHO. It brings lots of the crazy Perl 6 features announced in the synopsis like hyperoperators, metaoperators, lazyness, junctions, introspectable OOP, and regex and grammars as first class citizens in the language. That last thing means you can plug a new parser for your program in lexical scope. Welcome DSL world. Early adopters, language geeks, perl hackers, you have no excuse now not to try rakudo :) .

Myself I haven't toyed enough with Perl 6 to do anything useful, but I have done quite a few conceptual tests, and, although I'm still baby-talking Perl 6, it's quite nice to hang around at #perl6 and see perl6 heroes stressing rakudo's features till the unthought limits.

More good news: Audrey Tang appeared a few days ago on #perl6 (I think thanks to masak's post), and started hacking on niecza (sorear's perl6 implementation focused on compiler and interpreter optimization techniques).

I tried to solve one of moritz's perl6 Challenge, implementing Str.trans (á la p5 tr// ) in perl6. Mine, is the (really incomplete babyperly) submitted on a gist pastie. I didn't win the rakudo T-shirt.

More on Perl6. A couple of perl6 related posts reached HN and reddit top page and stayed more than 1 day there. buzz buzz buzz buzz :)

And last but not least, Barcelona Perl Mongers are living a celebration, on July 29th of July, the R* Day (and being the last thursday of the month, which is the usual meeting day) will join at UPC Campus Nord, and Alex Muntada will give a Perl6 introductory talk. Of course, you're all invited. Unfortunately, I won't be able to be there as I'll be in Malta. O HAI Holidays!

Happy 1st anniversary

martes, 13 de julio de 2010

Back to the future?

Llego al currele, y mientras estoy haciendo mi navegacion de
reconocimiento, encuentro porahí un link interesante: Google’s
Do-It-Yourself App Creation Software
. Alguna frikada de google
labs... ya verás. Total, que empiezo el articulo y leo que el
proyecto esta liderado por un tal "Harold Abelson". H.Abelson en
google? (pues se ve que se ha pillao un sabático del MIT). Bueno, el
proyecto va encaminado a que todo el mundo pueda ser programador de
sus miniaplicaciones.

Recibo un mail en una maillist Que pone "se nos acabóo el trabajo".
Coño! Esto es scratch!!!
Reflexión: Los Schemers chupando de smalltalk? Bueno, puede ser,
entre comunidades pioneras... pero en google, hacen algo en
scheme/smalltalk? Bueno, de hecho, scratch tambien sale del MIT, creo.

Llego a la pagina oficial del proyecto y efectivamente al final de la pagina.
(...) Open Blocks visual programming is closely related to the Scratch
programming language, a project of the MIT Media Laboratory's Lifelong
Kindergarten Group.

The compiler that translates the visual blocks language for
implementation on Android uses the Kawa Language Framework and Kawa's
dialect of the Scheme programming language, developed by Per Bothner
and distributed as part of the Gnu Operating System by the Free
Software Foundation. (...)

Me pregunto si contestar al mail de la maillist contando de donde
viene todo esto, quien es Abelson, y entro en otra
batalla épica? Respondo con un : "joer, estos de google son la ostia,
estas cosas, solo las pueden inventar ellos...", me callo?.

En fin... Esta claro que poco a poco van alcanzándonos, pero la
verdad es que me encanta estar en este mundillo (pionero después de
casi 30 años), y estas aproximaciones que hacen 'los grandes' le dan a
uno la confirmación de la sospecha: "yeah, voy un paso por delante,
que se jodan" :D

lunes, 12 de julio de 2010

Wasn't there a command to do XYZ?...

At $work, many times I'm asked about ways to optimize little annoying processes of other people (I'm a kind of office enabler).

There's a typical dialog of some $coworker, and $self.

- Hey Rai, I've got a little question for you.
- Ok, go on.
- Wasn't there a linux command to put lines of two files in one file, one line after the other? Like a columnwise join.
- M... yeah... I think so. Was it 'join'? Nah, man doesn't seem to say anything about it... Well, you can use Perl, you know, the swiss knife.
- Yeah, but I don't think a script is needed, For now, I'm doing it with excel, you can copypaste each file in different columns, and then save as CSV, then you just have to remove the commas, using vim.
- ¬_¬ .... Gimme 30 secs.

echo 'a' >a
echo 'a' >>a
echo 'a' >>a
echo 'b' >b
echo 'b' >>b
echo 'b' >>b
perl -e 'open $a,shift;open $b,shift; while(chomp($_=<$a>)){print $_, scalar(<$b>)}' a b


miércoles, 30 de junio de 2010

Redirect STDOUT to file in Perl 5

Every now and then, I need to write little scripts (or not so little) that output *lots* of lines of text. Those lines belong to a single file, so my common idiom is printing the output to STDOUT, and tell the user to redirect the output to a file if he wants it toasted into a file.

But there's a more elegant way to do it that doesn't rely on shells, and works more consistently. In fact TIMTOWTDI.

One way is fill the code with:

if ($outputInFile) { print $file "foo";}
else{print "foo"}

/me shivers ...

I found a way to do it quite elegantly redirecting a file handler where I'll be printing to STDOUT, using Typeglobs. I'm not too confident managing typeglobs, but it seems to work :)

I asked at and alexm (O HAI! president) told me I could think it the other way around, and overwrite STDOUT to an opened filehandle in case I needed the redirection. I didn't know I could handle STDOUT like any other fh. It's nice to know it.

I think Casiano taught me (back in university times) another way to do it (maybe it was using tee, or some IO::Handle funky stuff).

Is there any cpan module that does that kind of Stdout vs file output? I haven't found it, but it MUST be there. Or maybe the code to do it is so small it doesn't make sense writing a module for that

miércoles, 23 de junio de 2010

lunes, 21 de junio de 2010

Kill Buffers Illustrated (emacs)

A side effect of using emacs intensively is that you end with lots (I mean *LOTS*) of open buffers scattered on your emacs.

This is not necessarily a problem (provided you use ido/iswitchb/icicles modes), but it kind of gets on my nerves having 30+ buffers opened knowing that I don't need them anymore. Most of them are temporary buffers like dired-mode ones, or perldoc ones. Like most things in emacs world, someone has already thought of it and there is already a function to do what you want.

For example, scattered dired-mode buffers.

(defun kill-all-dired-buffers()
"Kill all dired buffers."
(let((count 0))
(dolist(buffer (buffer-list))
(set-buffer buffer)
(when (equal major-mode 'dired-mode)
(setq count (1+ count))
(kill-buffer buffer)))
(message "Killed %i dired buffer(s)." count ))))
And you're done.

great, isn't it?

What if you want to purge some buffers, that have no name in common, nor mode? You can kill them one at a time with kill-buffer (c-x k) but if you want to do it faster, you can use Buffer List buffer.

c-x c-b will open a buffer with a list of all buffers. That's not a normal (Fundamental) buffer, but a 'Buffer Menu' buffer. If you press 'd', the buffer that has the point (cursor) will be marked for deletion. Once you have the list of buffers to kill, just press 'x', and buffers will be killed.

If you press 'x', 3 erc buffers will be killed. Mnd you, once a buffer has been killed, it cannot be unkilled. :)

That's all for now.

viernes, 11 de junio de 2010


There's a (sadly too common) practice consisting of asking about something before having tried anything related to it. I mean, if you're working on nuclear fision, better ask first, but if you're trying a software library, or want to know which advantage gives you using this db vs that other one, just TIAS (or its NSFW version TITS The link is SFW, don't worry). This will give you a fairly good overview of what does this language/lib/anything can do for you, and how easy/difficult is FOR YOU to use it.

python (or this if you have MS Silverlight)

Btw, combo pun for the ones that came to the last FestaFIB '10. A pun on a pun on a pun on "I love ..." T-shirts .

jueves, 10 de junio de 2010

Talk talk talk

A new conference was born 3 months ago. It's called Emerging languages, and it will take place this summer. It'll be full of language designers, talks about innovative programming languages, and *lots* of enlightening ideas (I'm sure). There will be talks about lots of langs all by the language designers. Myself, I'm particularly interested in Io, Ioke , Newspeak, Factor and Clojure.

The bad thing is that it's going to be held in OSCON 2010, so It's a bit far from me... Let's hope there will be recorded talks after summer.

It seems this summer I'm not going to YAPC::EU neither, so I'll have to take my conference dose from somewhere else.

Luckily, there are lots of good talks already recorded .

Erlang and haskell

scheme talks

Google Io sessions

And lots of good papers to read:

Any other suggestions are very welcome.

miércoles, 12 de mayo de 2010

You can stay at $HOME, Perl :)

Evolution is the way to keep up with times, and lots of things are happening in the perlsphere lately:
  • Perl 5.12 went stable on April 2010, with lots of fixes, and a few new features. See the deltas.
  • Rakudo is making progress at a good rate, with new contributors, and it's getting faster and more complete every day. Parrot guys are doing a great job there too.
  • cpanminus seems to be the next big thing of the language, and it's a perfect companion of local::lib and even perlbrew.
Cpanminus is miyagawa's (quite successful) attempt to simplify, in a DWMI-Y way. by default, it follows dependecies, uses your prefered path to install modules (it knows about local::lib) , and will just install and get out of your way. It's better for perl newbies (and pseudo-newbies like me) and speeds up the installation of the whole environment.

local::lib is one of the wizard mst's magic spells to enable local repositories of libs per project. That means you can attach cpan libs to your apps, and then control the exact version you ship with each app.

the complete install process of the environment is the following:

mkdir ~/myperltmp
cd ~/myperltmp
chmod +x cpanm
tar zxvf local-lib-1.006000.tar.gz
cd local-lib-1.006000
perl Makefile.PL --bootstrap
make test && make install
echo 'eval $(perl -I$HOME/perl5/lib/perl5 -Mlocal::lib)' >>~/.bashrc

And now you're ready to go.
./cpanm DBIx::Class
./cpanm Moose

And with 0 questions, you'll have DBIx::Class and Moose in your ~/perl5 directory.

If you added the last line to your .bashrc, then everything should work. You can use local::lib "~otherpath"; to have multiple scenarios to try your modules/apps on. Next thing to try is perlbrew, but that's for another day.

Mainly I extracted the info from here and here (and perldocs, of course)

Before leaving, let me leave you with a great talk by mst. Full of info, and full of lolz, and nearly no swearing (Wow! surprise!)

miércoles, 5 de mayo de 2010

Comparing functions. How similar are we?

Sometimes I have two functions, maybe in different subclasses, and I would like to do a diff on them, because they look very similar but not the same. Most of the times, they are come from a past copypaste, so variables have the same names.

What I want to know then is what has really changed, or if they changed at all.
#in file foo/
sub normalize {
my ($self) = shift;
$self->attr($self->attr / $self->total);

#in file foo/
sub normalize {
my ($self) = shift;
$self->attr($self->attr / $self->total +1);

Emacs comes to rescue!

We'll use two great emacs features, narrow and ediff.

narrow lets us hide uninteresting parts of a given buffer. It's usage is pretty simple: Mark a region, m-x narrow-to-region (or c-x n n). There's also a shorctut, and there are predefined narrowings, like narrow-to-defun... you know, emacs butterflies.

Once you narrowed two buffers to the interesting regions, you can use ediff (m-x ediff-buffers) and select the two buffers you want to narrow.

To widen the narrowed buffers, you can 'm-x widen' (or c-x n w) to see the complete buffers again.

Tip for ratpoison users (or any other tiling wm user): (setq ediff-window-setup-function 'ediff-setup-windows-plain) in your .emacs will tell emacs to open the ediff window in a different window, but not opening a new frame. (window and frame have inverse meanings in emacs world than in the rest of the world)

theese would be the steps:

  1. open
  2. go to normalize function.
  3. c-m-h (mark-defun)
  4. c-x n n
  5. open
  6. (steps 2-4)
  7. m-x ediff-buffers
  8. select both buffers (emacs will suggest them already)
  9. check diffs
  10. q (quit ediff-mode)
  11. c-x n w (widen)
  12. go to the other file, and widen again.
  13. You're done

Endnote: Although being a big fan of vim myself and having used it for 5 years, these features available in emacs by default, are not (at least easily) doable in vim. emacs, the kitchen sink, and m-x butterflies DO have their uses :)

viernes, 30 de abril de 2010

Fiuchar is nau

Es acojonante interactuar con el mundo. Unas veces ganas, otras no, pero interactuas. Y eso mola, no me jodas.

Lo que recientemente me sucede, y me doy cuenta, es que el futuro esta íntimamente relacionado con el presente, y aunque eso parezca una trivialidad, no siempre soy consciente de ello.

En la historia que no sale en los libros, la del día a día, la mía, y seguramente la tuya, uno mismo es el prota de su película, y si no esperas nada más de ella que ir pasandolo bien minuto a minuto, pues no importa mucho a donde te lleve el proximo capítulo. Carpe Diem.

Pero no hace falta tener previsiones a años vista para ver que tus pasos no son gratis. Cada movimiento es un turno, y eso ya no vuelve. Y la jugada que empiezas ahora, te condiciona tu siguiente turno. Y pasar no entra en las reglas del juego. Llamémos a este epsilon de tiempo, "el proximo turno".

Una entrevista de trabajo mal llevada, te cierra puertas a currar, a dejar el curro, o a cambiar de ciudad.

Un policía que casi te pilla, te podía haber jodido tu expediente, o tu carnet. Y tu estabas jugando en el juego. Un borracho que por la calle te pega un puñetazo porque ha ganado su equipo, te deja, a parte de en el suelo, te deja pensando en que cojones haces viviendo un día a día, que no te lleva a ningun lado, porque simplemente apuntas a media altura, apuntas a mañana. al proximo turno, pero solo con llegar ya te basta.

Un paso mal dado, te puede dejar cojo, y no poder irte de viaje, aunque ya hayas pagado tu billete. Pero esto no es como Dallas, donde te puedes inventar que la muerte de JR era un sueño. Los turnos pasan, y cada jugada es una opción de encarrilar, o cagarla.

Este próximo turno (futuro immediato) se crea a partir de esta gran bola de mierda que es el presente, y que va ladera abajo, llevandose por delante todo lo que pilla. Y es tan grande y gorda, que uno no la puede parar conscientemente. Digamos que es una version del S.XXI del concepto del "train of knowledge"(al final) y Quality que conocí en Pirsig, paralelismo del tren, pero remasterizada, actualizada, y con 7 segundos inéditos. Los del puñetazo.


Ok, you hate documenting. But it's part of the deal.

As you may know, there are tools that generate browseable documentation provided you document your code in a proper way.

Perl is no exception, and you can convert POD documentation to html, formatted plain text, LaTeX, etc...

To ensure you documented (at least, put the boilerplate) every non private function in your code, there's a module called Pod::Coverage that checks for undocumented functions, parsing your code, parsing your pod, and doing the match, and the diff.

Once that we're at it, we can bundle the check as a test for our application, and, in fact, there's Test::Pod::Coverage, that is exactly what we're looking for.

Ok, let's write a minimal module (BankAccount will do), using the right tools for each job.

module-starter --module=BankAccount --author="Raimon Grau" --builder="Module::Install"

This will generate all the boilerplate and the directory scaffold needed, and it will include (at least if you have both packages installed).

This code will fail the pod coverage test, because the method withdraw is not documented.

Well, we have a new tool in our toolbox, that makes sure at least every method has its associated POD documentation. The module won't force you to document subs starting with underscore (thank god for DWIM). There's also other modules that build on this, like the one RJBS explains here.

lunes, 26 de abril de 2010

Iterator::Simple, as simple as it gets

We're all feeling spring is coming again. That's not new though, so you could have guessed that after winter, spring was about to come.. ¬¬

We could build a circular list to retrieve a list of consecutive seasons, but as I discovered
Iterator::Simple, Here follows a stupid example of its usage.

We can also wrap an iterator, "á la" stream (I'm reading the stream chapter in SICP, and nowadays, I can only think in streams :p ), delaying the evaluation of the wrapping until the given elements are needed using imap. We also have ifilter, igrep, and so.

Here's a code that wraps (or decorates, in python slang IIRC) our iterator modifying the string returned, and it limits the iterator to 6 seasons.

miércoles, 14 de abril de 2010

Versioning in squeak/pharo using Monticello

Lately I've been working on a simple website I'm doing in smalltalk. It's not a complex thing, but it's someway new being my first serious website I've done.

To build it I'm using pier and seaside. And it's mostly fantastic. But sometimes, all of the sudden, some unknown error occurs and my image freezes. And my last codes are lost. No way to recover it even using the recovery tool.

So I remembered something Mr. Ducasse said in the course he did in UPC. The idea is you could throw away your image every day, and start with a fresh new one, EVERY DAY.

One option is fileOuts and fileIns, and in fact, it's simple, reliable and it just works (tm), but you cannot store different versions, and if you did the manual filename juggling, the versions would not have any relationship between them.

Then, here comes monticello. A kind of apt-get + launchpad. It's a package browser and installer (no dependency tracking AFAIK), where repos can be lots of different places, from local directories, to squeaksource remotes, or ftp, or ....

The trick is opening a create a new package (+package button) with the name of the category you want to save. Then, it will appear in the left panel of monticello browser. After that, create a new repository (+Repository button) and add a directory where you want to save it. Then just press the save button.

When you open a new image and want to load the package, open monticello browser, open the repository (+Repository again), click it, and browse. There you'll be able to load the package, and once it's loaded, it will appear in the left panel of the main Monticello Browser.
In the second screenshot you see top left, the different repository types. on the right, the main Monticello screen with the two panels.  My advise is to play a bit with it, selecting and unselecting items to get the feeling of it.

Btw, there's a new project related to source maintaining and versioning called Metacello that seems to be the next iteration of monticello, or "monticello done right", adding full support for package managing, being aware of versions and so.  I'm just guessing as I'm a newbie in both projects and I just skimmed the docs, so please, correct me if I'm wrong.

lunes, 12 de abril de 2010

MP3 fail

Me compré un mp3 y ha ido conmigo a todas partes. Y con él comparto momentos en los que él pone la banda sonora a mis accions, y a las situaciones en las que me veo envuelto.

Es capaz de potenciar una situación, o apartarme del mundo. Un perfecto aliado. Hasta he ido a discotecas a escuchar mi mp3 (HAI TENERIFE). Y a pasear a las 5AM. Me ha hecho conocer gente, y ha dormido en casas ajenas, siempre como una extension mía, como un embajador.

Lo habrán escuchado unas 100 personas distintas.

Me lo compré el 12 de Abril de 2008, lo cargué de música, y no la cambié jamás. A medida que lo escuchaba más y más, me recordaba a cada una de estas 100 personas. Pues el 10 de abril de 2010 dejó de funcionar. Kaput. 2 años menos 2 dias. Con las mismas 2 Gigas.

La pregunta es: Debo llenar mi nuevo mp3 con la misma música?

Portishead, Fat Boy Slim, Michel Camilo, Pearl Jam, Mama ladilla, Janis Joplin, Rare Earth, Ten years after, Zuco 103.

Ya veremos si os vuelvo a ver en mi bolsillo...o os cambio por Mika ;).

Si cambio, una que cae seguro va a ser move to the city.

Parece un cutre-post (y seguramente lo es), pero mi compi de viajes se merece una mencion. ¿no?

jueves, 1 de abril de 2010

First step to Zurich

Many of you know that I've been skimming job-hunting sites. I'm not to change unless I find a cool job.

Well, after talking to a good friend and wise advisor, he told me to go hunting myself. Real good jobs have to be seeked in a smart way.

So I did, and I send a few CVs to cool companies where I would really love to work. And one of those, is (yeah, you guessed) Big Bro^WGoogle.

The surprising thing is that they answered me, and told me They'll contact me further, explaining the process of the interviews and so. I don't know if I'll be able to talk further about it, so...

I'm extremely excited, but today, being the April 1st, I thought for a moment, it could be an April Fools' Day joke. I hope not...but you never know... Google acts in mysterious ways :)

A journey of a thousand miles begins with a single step.

lunes, 29 de marzo de 2010

Scheme and home-made objects

Scheme is functional. Functional and minimalist.

But its power to build higher abstractions with the basic toolset it provides, allows us to build a pseudo Object oriented system by ourselves.

That's what SICP 3.1 - 3.4 exercices are about:

Using the closure property we have learnt about in chapter 2, and the just revealed set! function, we can build objects with private state to the world.

We'll use the classical bank account exercice. We create it with a initial amount of money and we can deposit money and withdraw money (iif we have enough money there).

At the end of the 4 exercices we should have a way to generate password protected bank accounts, which remember not only the password but how many wrong passwords you have entered in a row. If you fail thrice, it'll call the cops.

To solve this little problem (that, on the other hand I love because of its well defined objectives and dose of reality) we'll first have a make-monitored function, that counts how many times it's been called. make-monitored procedure gets a procedure as a parameter, and outputs a prodecure that is like the one entered, but with the counter stuff added. we could say it makes wrapped functions (decorated if you come from python).

The password protected account uses just an extra local variable to the closure that has the password.

the usage is like

(define pw-acc (make-protected-account 'secretp4ss 100))
((pw-acc 'secretp4ss 'deposit) 10) => ok
((pw-acc 'wr0ngpass 'deposit) 10) => fail
((pw-acc 'wr0ngpass 'deposit) 10) => fail
((pw-acc 'wr0ngpass 'deposit) 10) => call-the-police

I don't like that when a wrong pass is passed as an argument, the output is applied to the argument (10 in this case), and scheme doesn't know how to apply it.

I've worked partial solutions but none convinced me one being flattening the way to call the functions (pw-acc 'pass 'deposit 10) but this way, the password protected account had to know about how many parameters received each function. The other solution is returning a dummy functions that accepts one parameter in case of wrong password. Unfortunately, here we just accept 1 parameter, so we are limited too.

Any suggestions are very welcome

viernes, 26 de marzo de 2010

Let's go everywhere

Last month has been a pretty busy one.

Breakout 4.0, erlang course, Barcelona.PM, Valencia (Fallas) gts, and some hard partying. It's quite difficult to make a synopsis of all the new info and thoughts I've been flooded with, but anyway, this is not a personal explain-my-life blog, or is it? anyway.

On the hands-on techincal side, I've started a web using Pier. I've never worked with any cms to do anything productive, and I decided to use pier due to my mental commitment to smalltalk. It's one of the best languages I've found, and I'd like to learn it well, not only to do a few hacks here and there.

I've been reading The last seaside book, which goes right to the point (IMHO) and is pretty well structured (maybe too verbose at times, but well).

Being a great language itself, smalltalk has a few drawbacks that make me think of going to something more mainstream.

Probably it's more a problem of me being unexperienced in this environment than a problem of pier or smalltalk on their own, but anyway.

Image based persistance is enough for me, but in case I needen some db backend, using magma is not interoperable with other systems, so data is closed to the world.

Apart from that(and random hangs) creating a new class for products, a template view for them, and edit view is really easy, introspection friendly, and fun.

I've been dabbling a bit with tornado, a python minimalist framework to develop simple and fast RESTful Webapps(similar to Dancer and Mojolicious) I'm on a secret project for world domination, and it'll be in python (bummer, I always thought world domination would be in Perl.

miércoles, 24 de marzo de 2010

Ada Lovelace day

Ada Lovelace Day is an international day of blogging to draw attention to women excelling in technology.

I could think of several women that have done really amazing work in technological side (audreyt,etc.). I have read some technical books written by women too (Smalltalk-80 The language by Adele Goldberg).

But for me, being involved in software projects is the first step to be (maybe) a great software programmer.

So my 'tribute' to these (still today) pioneer women involved in a world traditionally forbidden to them is a talk by Kirrily Robert at OSCON '09 called "Standing out in the crowd". It's quite interesting IMO. Here are some notes on the talk.

viernes, 12 de marzo de 2010

Finite automata in erlang... well, in perl

I've been hacking some erlang after the third class with Johan Montelius. Last lecture was about failure handling, exeptions, linking and monitoring processes.

I've been tempted to translate some classical problems of concurrent or parallel computing to erlang. First chapters in some books are about what they call LTSA. They are mostly state machines, that can be composed, concatenated, intersected, and some other operation.

At first, I started doing an erlang little program that has three states, and receives messages to travel from one state to other.

Here's the basic code for the hello->converse->goodbye LTSA

Theres's a couple of things to note here:
  • Erlang syntax is a bit tricky. so many different line endings (, ; . nothing).
  • It's an ad-hoc code, but it follows a clear pattern.

Then, I thought about going meta. Why can't we build a program builder, that with a simplifyed input of our desired behaviour, writes erlang code?

I've used perl to hack a simple script that builds the code structure (or the whole program depending on your needs). I won't have to tell you it's quite unstable, and you can make it produce failing codes. Of course, it's quite shaky, but well... Just for the fun of it.

Try it, play with it, break it, or fix it. I don't think it can be useful for anything in this state, but maybe implementing composing functions...

For the moment the program just gets information on states, transitions, and destination states.
Then it builds a function for every state, and builds a receive statement, with each possible transition, and and ending _ -> fun to discard unrecognized messages. Keep in mind it won't keep order, so non disjoint cases aren't guaranteed to work. When entering a function, it's name (and actual parameters) are printed on the screen.

Yeah, the perl syntax highlight problem... try here to see a hightlighted version.

Check out my other erlang posts

lunes, 8 de marzo de 2010

My name is erlang

I've been introduced to erlang by Prof.Johan Montelius.

I'm enjoying the lectures a lot (the two so far). He's a great speaker (is's quite fun to attend classes) and he managed to explain the basic concepts of concurrent erlang programming in 2 hours (provided you already knew the basic erlang syntax).

I'm taking some notes at class, and I'll eventually clean them and upload them in a blogpost format.

For the moment, here is a silly code I wrote the other day while I was in the bus.

It's interesting how:

  • Concepts learnt previously in scheme and perl (Higher Order Perl ftw!) become useful and appliable here.
  • Pattern matching is stressed to become the basis of method dispatch (with or without guards), variable binding, if/case/any_conditional and message receiving.
  • The Message Passing system is GREAT. Not just the "forget about low level sockets" but the mailbox
    system of each process, and the transparency that frees you from thinking low level.
  • Being a functional language, it does tail call optimization, and in most cases you better take advantage of it, because processes (if you think of them as DFA's) have a long life, and they just travel from one state to other by calling themselves recursively with an updated argument (you can
    pass the state along through the function arguments).

Here's the code. Just a Proof of concept. Two processes sending pings and pongs one to the other. Pretty simple, but there's pretty much a synopsis of the erlang (ugly) syntax and expressions.

miércoles, 3 de marzo de 2010


Este es un saludo a toda la gente que nunca saludo, a las personas que
nunca saludaré y a los que no he saludado.

A aquella gente que me encuentro en el bus, cada día, y casi ni nos
miramos. A los que estan en la puerta del edificio, lloviendo y
pasando frío, y compartimos un cigarro de silencio. A quién lleva un
libro en la mano que he leído y me gustó, y podría pasar horas
hablando de él. Pero no nos decimos nada.

A un telefono que acabo de descolgar, y me he quedado mudo para que no
me vendieran enciclopedias ("hola buenas tardes" - han dicho). A los
que tengo al lado en un concierto de Mamá Ladilla.

A los que hacen guasas de Top Secret y Mucachada Nui en la mesa de al
lado en un bar.

A los visitantes silenciosos del blog,

Personalmente necesito empezar a decir "hola", porque por lo general,
el día a día me lleva al asco más absoluto. Mientras digo "hola", no
me estoy cagando en, ni arrepintiendo de, ni pensando si, ni
conspirando contra.


Ala, aquí el temazo del dia. Estranged.

sábado, 27 de febrero de 2010

Mastermind in scheme. Now with GUI!!

plt scheme has a wide collection of libraries, some bundled with the basic package, and some which have to be installed through PLaneT.

GUI library is from the first group, so if you have plt-scheme already installed (not mzshceme alone, but the complete suite, with drscheme and so) you already have everything you need.

WARNING: It seems there's some programming course in NY with an assignment related to writing a mastermind. If it's your case, please, do not use my code blindly. I'm a novice scheme programmer, and probaly, my code is not very idiomatic. Anyway, have fun.

I've been using the mastermind game as a toy project to learn scheme for the last month. And now, it even has a little GUI. I also have a solver in 5 tries (in the worst case) but I haven't embedded it yet in the GUI.

The process of writing GUIs using plt-scheme is easier than I thought. It's great to write little things (we could say it makes easy things really easy). I don't know how difficult it'd be to write a more complex GUI, for example, I haven't found any grid component. Only comboboxes, radiobuttons, buttons and text-fields.

The good part is that it's really easy to assemble these compoonents in layouts, panels, frames, and so. It's also really easy adding menus to windows.

Here follows a little code that lets you play mastermind, fully coded in scheme.

Btw, This is (more or less) what I used last wednesday at flibug meeting to show an example of GUIs in plt. I really enjoyed the meeting: Learning, sharing, having fun, and beers :) .There's some more info about the last flibug meeting in my last post.

viernes, 26 de febrero de 2010


This has been a frenetic week. It seems that flibug and Perl Mongers meet at the same week every month.

But first things first.

Monday: Erlang.

I attended to the first class of an introductory erlang course. For the moment, we only looked at erlang syntax (btw, it sucks), and some points of functional programming. Pattern matching, tail recursion, consing, lists, and some erlang's BIFs to manage lists (we have neither while nor for). I'll expand a bit more on erlang on a future post.

Wednesday: Flibug.

A small and familiar meeting. Thomas H. Marc-André L., Andrew B., Andy W and me. As always, we talked about what we are hacking on lately and did some lightning talks.

  • I did my first lightning talk, about making GUIs using plt-scheme. A bit simple for the general level of flibug talks, but well, I think it's a good way to start doing talks. And probably, Thomas will do a talk next month on an alternative way to write GUIs in scheme. I'll post about it in a future post.
  • Andrew B. talked about an app he did some time ago in OCaml to apply morphologic filters to images. Pretty interesting but I couldn't understand the details. All in all, I think I got a good overview and I got 'the message': "functional pays off more times than we think".
  • Wingo showed us some interesting parts of guile code. Mostly the evaluator, and he explained us the multilevel scheme compiler/interpreter (c -> scheme -> scheme). He also showed us the guile-gtk bindings.
Great meeting, as always, and it makes you feel like hacking more and more.

Thursday: Breakout && Barcelona Perl Mongers.

After $work, I went to borneo bar, the place where this month's Breakout was held. Some chitchat while having lunch with other smalltalkers, then some hacking, and at 20:00, we had a PerlMongers meeting.
  • Alexm brought some round tuits for us. He explained some of his experiences at last FOSDEM.
  • Esteve did a talk about FluidDB implementation and it's intended usage. Pretty cool stuff, and little by little, I think I start to understand the amplitude of the concept.
  • Fxn ended the session with a talk on his Net::FluidDB module, and the difficulties he had to coerce floats,ints and booleans between fluiddb and Perl. He talked about some Perl internals I didn't know. And he's a great speaker, so it's always a pleasure to hear.
  • It was probably the most crowded PM meeting I've been to. It was a really great meeting.

You see... pretty busy week, isn't it? Well, in fact, at $work I've been busy too, reading about evolving graphs in genetic algorithms. I've done some literature fetching on GA parallelization.

My brain's gonna explode in 5, 4, 3, 2,.... Ah no, I'm just in coma.

Btw, when writing this post, I've started a new tiny tool which I called LinkAdder, that's just intended to add some common html links I insert over and over on my posts. Its repo is here. It's a very simple translator for now, but I have some ideas for it.

viernes, 19 de febrero de 2010

Roboshop 0.01

This is an addendum to my last post on web scraping with perl and HTML::TreeBuilder. I've named the script Roboshop.

Ok, I've rewritten the roboshop script. Now it's shorter, and more reliable (as reliable as a webscrapper can be)
So If you want code(you got it) (yeah, I know it sounds better with "if you want blog, you got it", but there's little chance I can make this pun, and AC/DC is cool anyway).

The site seems to send different html pages depending on some (unknown to me) variables.

So I analyzed the two variants. At present version (alpha 0.01) it just outputs an array with prices, but I'm in the process of making it cooler, and send me mails when it finds some interesting thing in the INTERNETZ.

Here you can see the use for HTML::Element look_down with chained calls to get the desired node. Apart from cpan, there's more info here.

I'm thinking about writing a WWW::Search subclass too. We'll see...

Btw, I don't understand why perl isn't syntax-highlighted when embedded in the blog. If you have any pointers, I'd be very happy to hear a way to solve that. Sorry for the inconvenience.

See ya in the next post.

Thanks for the shopped Artwork go to nabax. =)

jueves, 18 de febrero de 2010

Mi último sueño

De pequeño escribía historias imposibles y las acababa diciendo que el personaje se despertaba. Estaba bien la impunidad que daba el sueño, y la invencibilidad de la que disponías.

De mayor a veces me pasan cosas que al despertarme recuerdo, y hubiera preferido estarlas soñando. Pero no. Hay pruebas reales.

Entonces me doy la vuelta e intento volver a dormir, para soñar con la noche anterior, y mandar la historia entera al mundo de Morfeo. Pero ya no me duermo.

lunes, 15 de febrero de 2010

robots go shopping!

One way to go shopping is spending long afternoons walking among crowds. I imagine it can be less boring than I think but anyway... I've written a little perl program that finds cheap books for me, and mail me if there's any good oportunity. This makes shopping more fun for sure. :)

I've used HTML::TreeBuilder to parse the html. Yo'll have to take a look at HTML::Element too.

The site I'm parsing has changed three times since I started writing this script (2 weeks ago), so it will get outdated very soon, but well...

HTML::TreeBuilder can treat any given html as a Tree (huh, really? ¬¬ ) and lets you navigate through it in multiple ways. A very intuitive way to traverse a tree looking for some tag is using look_down. it accepts an even number of arguments, the first being an attribute name, and the next being the content you want to match.

For example here's a stupid code that extracts some tables from an html.

my $tb = HTML::TreeBuilder->new();
my $root = $tree->root;
my @res = $tb->look_down('_tag', 'table', 'class' , 'result');
say $_->as_text for (@res);

The steps are really easy and this lib gives you the power to write web spiders fairly easy. If you're more fond of python, you can use beautiful soup (which has a smalltalk port too).

As the code is pure unstable crap, I'm not going to upload it for the moment...

OFF-TOPIC PS for last Saturday hardparty-ers: I'm still alive, well and kicking. Thanks, sorry, and good luck!

jueves, 11 de febrero de 2010


WARNING: Este post fue escrito el mismo dia de presentar, y lo he dejado talcual, aunque con perspectiva se ve cutre-friki-quieroYNoPuedo de cojones. Pero lo dejo talcual.

Todos como uno solo, alcemos la voz al cielo, porqué $DEITY (en caso de que hayas definido esa variable) nos escucha desde $DEITY->location. Gritad conmigo: Hallelujah! Hallelujah! Hallelujah! Hallelujah!

Porqué al final del camino, la luz brilla más que a la mitad de él. Gritemos Hallelujah!

Después de estar recibiendo enseñanzas durante 8 años (y pico) en el monte FIB, hacer un viaje para aprender de otros en La Laguna, de donde volví con el espíritu cargado de fuerzas gracias a profetas y discípulos, el viaje de aprendizaje formal terminó hace 2 semana, con un resultado francamente bueno.

Aquí os dejo, amigos míos, el resultado de mis 6 meses, entregados para vosotros. Mirad, y sonreír todos, que esto es lo mejor que se hacer, hablar de frikadas, y delante de gente. Y no me juzguéis si no queréis ser juzgados, que ahí me puntuaban, y no podía ser Rai 100%. Disfrutad de los primeros 10 minutos viéndome hablar a 2x en un baile 33% funky cold medina, 33% macarena y 33% saturday night (esta os la buscáis vosotros/as).

Quiero dar las gracias a mis padres, y también a todos los que no son mis padres. A todos los que me han dejado un sofá para pasar una noche (sóis más gente de la que os pensáis), quiénes me han iluminado y gentuza en general. Ya sabéis quien soys. Os quiero, gracias por este sueño, que os den por el culo, etc...

Venga, ahora unos links y los videos
El pe de efe: genetic algorithms memoria

Las transpas: genetic algorithms slides

Los códigos fuente de la memoria estan en mi github

La presentación.

Algoritmes genètics aplicats a ciències de la vida from Raimon Grau on Vimeo.

Las preguntas (y sus respuestas (y sus coñas marineras)).

Algoritmes genètics aplicats a ciències de la vida - preguntes from Raimon Grau on Vimeo.

Ahora por fin tengo tiempo de aprender.

miércoles, 10 de febrero de 2010

Are you attending more classes? No I'm just charging my batteries

I'm fucking amazed. I mean, I'm really FUCKIN amazed.

These Advanced OOP Design classes are more meta than I ever could have thought. Stéphane is that kind of guy that charges your batteries when listening him. A great and passionate speaker.

Today's class was more like a open-your-eyes session than a hardcore technical lecture. Maybe many people does not like these kind of things, but myself, I love them. It's when you feel you're not sure you're in the right path, or don't feel motivated enough to hack on things, the right person cracks in and explains his experiences, and gives you metarules to clear your ideas. Like giving you the toolkit and materials to build your toolchain to eval on yourself, and then, make or break.

Instead of doing the explanations on "why tiny methods matter", or discussing about aggregation vs composition (luckily I did my homework yesterday anyway), he pointed us some ideas of "how stuff should work" (Note to self: buy www.howstuffshouldwork.something), or better said, "where things are going". Also, explained his opinions about some dynamic languages. And explained the beauty of uniformity (object -> class -> metaclass-> metaclass class).

Some points I got (all bullets multiplied by my vision of things):
  • Gimme a man(1) with examples, or better still: gimme access to the code that uses XYZ function.
  • Simple and small m/(systems|rules)/ make $1 powerful and extensible. Don't break the simplicity as far as you can.
  • Systems should be small, but not smaller than useful (They're trying to do that in pharo)
  • Object -> Classes -> Metaclasses -> Metaclass class is so beautiful
  • Marketing is capable of amazing things.

On the meta side (all bullets multiplied by my vision of things):
  • Do stuff you like. Be a kid. play with stuff, break things, fix them, or throw them away, but don't be passive about the world.
  • Take the time to learn things. Invest in yourself. And now it's easier than ever getting info about anything you like. No more traveling 30 km to get a book that iif you're lucky, you can take home. "OH HAI INTERNETZ".
  • Value your time. Signal / noise is low nowadays. Evaluate what you spend time on.
  • Use internet wisely. After you downloaded all the crap you won't have time to watch/listen, take a look at , , or just take a project you like, and play. You can mail your 'idols' and probably they will answer you kindly.
  • You're not obliged to do anything of that, but keep in mind we're part of our community (the REAL world), and it depends on us building the future of the culture, community and so. Choice is yours.
I want to make clear that he didn't say anything of this textually, so most of the bullets are versions of high-level-ideas-he-said strongly modified by my highly biased way of thinking.

It's difficult to express how happy I am to attend these lectures. Thanks again to JD and SD. I think I'll subscribe to pharo mail list, and try to collaborate in anything I can do. Even if I only can do little support on IRC to smalltalk newbies.

lunes, 8 de febrero de 2010

Advanced OOP design with Smalltalk and Stéphane Ducasse

I've just been in the first lecture of Dr Ducasse's course on advanced OOP design here in Barcelona.

And I've to say it's been GREAT. A guru that talks with hackers in mind, being a great one himself. And with lots of good points in the prespective one should care about when entering a new world of hacking/amusement.

He started with an introduction to smalltalk while jumping back and forth to meta-level . We already saw the boolean implementation in the first 20 minutes, and jumped to ifTrue:ifFalse: implementation.

During the talk, he spoke about some real cases he encountered in his life, talking about india, china, project costs in "Old Europe" vs eastern, and the importance of having a delta that makes you different from your co-workers (oponents?). I've always thought like that too, so this guy seems really cool to me :).

On the technical side, He talked about the importance of taking advantage of the object system, and keep in mind that the dispatcher on message sends act as case statements, so we should use them as such. Minimizing logic in our code make it faster, more solid, and prettier.

We're following these slides mixed with these others.

While doing the lecture, he mentioned some cool books, some of them I already heard about (even read them), but others not, so I'm afraid my TOREAD list is about to grow a bit.

All in all, I had a really good time, and it's been only the first class!. It seems I'll be hacking some smalltalk in near future :)

Thanks to Jordi Delgado for making this possible, and to Stéphane for coming to Barcelona and sharing his knowledge.

Btw, if you don't know what is smalltalk nor who Stéphane Ducasse is, you should check pharo and you'll get a fair idea of what's smalltalk about and you'll be watching what is Stef working on.

viernes, 5 de febrero de 2010

Mysql from Perl

There's a lot of texts written about perl+sql . In fact there's a whole O'Reilly book about this.

But in perl, often the TIMTOWTDI motto fuzzies me a bit. So here's what I've chosen to use for my simple Mysql accesses (For complex and scalable things, there's DBIx::Class).

For small updates, or writting tests, you could go with plain DBD::DBI, but DBIx::Simple seems to fit better in my brain rules. There are plenty of well thought examples here.
my $dbh = DBIx::Simple->new(
$pwd, {RaiseError => 1}
#my $sql = SQL::Abstract->new;
my @fields = qw(codi A Br P S SA ZN e d);
my $result = $dbh->select('vGRID', \@fields, { idExp => $idExp, error => 0 }) ;

It's pretty confortable being able to use select, update, etc. as methods, and not bundled into strings. SQL::Abstract does a good job here too, giving the option to build hashes dinamically and passing to the select method.

domingo, 31 de enero de 2010

Higher higher order functions in Perl

I've been toying with functional programming on and off for some time now, and there are already some apps at $work that use some FP approach.

One example of this is an app I had to do some time ago that filtered a file following user given constraints. To simplify the case, let's imagine we have a textfile with names of students followed by a qualification. We'd like to do some data managing on them. For example, get the average qualification of all students that passed.

In my case, I couldn't keep everything in memory, As I had to parse multiline objects in a 2Gb file, so I had to filter them "á lá" File::Find.

Here's the basic (simplifyed) code.

What if we wanted to change the condition based on a parameter? I thought of two different approaches, one being more clear on the code side, and the other being more robust.

One option would be getting the parameter before the closure. That way, the constraint function will be able to access the $par variable. This option works, and the code does not get much affected. On the other side, The code becomes flaky in the extensibility side. Changing the location of the closure makes the program fail. Using global variables this way isn't really nice either.

Last way I tried is making a higher order function that generates the constrain function. It ressembles some kind of currying. Well, here's the code.

The'@keep' juggling isn't needed on newer perl versions, but you'll need it in perl 5.8.8 .

Dear lazyweb, do you have any preference for one or other technique? Is there another trick to use in this case that could help me?

Here's a bit of help on 'variable X will not stay shared' warning.


sábado, 23 de enero de 2010

permutations with repetition in scheme

With my exams finished and my final project at uni also finished, I had some time to spend with my already-started-but-not-finished small coding challenges.

As you may know, some time ago I started not one but two implementations of mastermind.

One in Perl, and the other in Scheme.

I wanted to finish the scheme implementation, so I started to look at Donald Knuth's paper about Mastermind. It's not so complicated, but as I've been far from complex algorithms for some time, it scared me a bit.

First thing to do is having available all possible combinations (strictly speaking they are permutations as order matters) of colours (in our case numbers). Two nested maps, a recursive call, and you're done.

As I don't have time to comment all the code, I'll just post here the permutations part, and keep the complete code private for now. When I have the time, I'll post it all, with appropiate comments. It's a minimax algorithm, so not daunting at all, but....

Here it is:

Apart from this, I've hacked with a few things (as time permitted). If you're specially interested in something, ask.

  • net sniffing
  • Image analyzing and video tracking
  • html parsing and web scraping

lunes, 18 de enero de 2010

Variaciones de una misma historia


Cuando aún el negro reinaba yo ya estaba levantado.

Mecagoen la puta, hoy tendría que dormir para estar bien concentrado para el examen, y no hay quién pegue ojo.

Me pasaba por la cabeza una mezcla de medidas de eficiencia de ethernet y gifs de 5 segundos recordando momentos mágicos de la uni. Algunos chulos, algunos embarazosos, que me hacían escabullirbe debajo del edredon, escondiéndome de la luz que entraba por la ventana.

Al final me levanto. Un día lluvioso. Un mal día para acabar este período de 9 años.

Voy a por el bus, aparco el coche en un descampado, pongo el pie en el suelo, y piso un charco. MIERDA.

El trayecto duró más de lo que esperaba. Y ya empezaban los nervios. A las 10 en la uni. 100% de desconocidos, menos los camareros del bar. "Ya te toca largarte de aquí", me digo por dentro.

Tras bastantes horas de medio estudio medio crisis nerviosa llega el examen. Tengo la sensación de irme vaciando. Llevo días vaciándome de tensión porqué he entendido que realmente no hay nada a esperar después del último examen.

El examen está en Chino. Mierda. Me he vuelto a equivocar de clase... ah pues ve que es el examen de redes.
Mientras lo hago, intento escribir concienzudamente, como queriendo marcar que éstas son mis últimas palabras en esta universidad. Pero al salir, comparo soluciones y veo que no lo llevaba tan bien como creía. FAIL.

Mecagondiós! Un cuatri más. Ya me lo veo. El orgullo por los suelos. El año que viene, a ver a más desconocidos, y esos pocos perennes de la uni. Los que me interesan y los que no. La gente que esperabas perder de vista, porqué no te llevaban a ningun sitio. Pues tendras que verlos más.

Y ya son las 21:30, voy a cojer el bus y...lo pierdo. Venga, perfecto, voy a llegar a casa a las 23:30.
Y al llegar al coche otra vez, me vuelvo a encontrar con (léase pisar) el charco porque ha llovido todo el día. ¿Lo véis? un mal dia para acabar


No he podido dormir de nervios. Acabo la carrera!

Desde las 6 que estoy en danza. Joder, esque no cada día acabas la carrera. Una mierda de carrera, sí, pero no me digas que no la has disfrutado. Aún en la cama, me acuerdo de los grandes, y las.

Venga, me levanto, a ver si avanzo un poco. Aunque no por mucho madrugar, amanezca blablabla, siempre puedes empezar a currar en la oscuridad.

Oh, mierda, llueve. Seguro que el tráfico esta fatal, ya verás.
Al entrar en el bus, me encuentro un euro en 1 asiento, y decido sentarme ahí. Quizás es mi "euro de la suerte".

Nah, me lo gasto en una cocacola nada más llegar a la uni.

En mi tercera cocacola de la mañana, veo a unos colegas. Y todos: "venga tío, dale fuerte y cómetelos con patatas!". Aunque no les escucho y sólo estoy mirando de reojo a la izquierda. Joder, que guapa está....

Consciencia: Tio, no te comas la olla, y a lo tuyo, que tienes que pirarte de aquí en 2 días.
Yo: yaya, pero...
Consciencia: Shhhhsthtt!!!

El examen, pues una mierda, como todos, pero con un poco de suerte apurebo sin rodilleras.

Salgo del examen y llamo a uno: "tío, creo que me pasa algo, creo que ya soy ingeniero". He apañao unas birras para mañana y otras para el jueves. :)

Cuando voy a por el bus, lo veo pasar por delante, pero ni me afecto. Tengo la preocupación en huelga. Voy a por el tren, lo pillo, me siento, respiro hondo 3 veces, pongo FatBoySlim y me digo: "tio, intenta escribir lo que te ha pasado hoy desde esos 2 prismas que te hablan todo el tiempo".

A todo esto, ¿Os acordáis que llovía?, pues ahora ya no.

jueves, 14 de enero de 2010

Ocean's one

Es como preparar robar un casino. Todo tiene que ir rodao.
Pero aquí estas más solo que la one.

El crono está en marcha.
Mañana imprimo, finde de estudio, el lunes examen, el miercoles entrego, y el siguiente presento.

Estoy de algoritmos genéticos hasta donde pueda estar uno.
Para motivarme ya escuho musica para robar casinos.

En dos semanas, finikitao. Y a volver a lo de antes: Musiquita los martes, frikismo los miercoles, cervecitas, futbolines, ensayos.... Hasta que me vuelva a cansar de casi todo.

Solo falta que aparezca Julia Roberts en el último momento. Y nos piramos a México. O donde sea.