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))))
1


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.

\usepackage{listings}
\usepackage{textcomp}
\usepackage[]{color}

\lstset{language=c++,
tabsize=4}
\lstset{commentstyle=\textit}



If you want, you can use pretty complex configurations:

\lstset{ language=C++,
keywordstyle=\bfseries\ttfamily\color[rgb]{0,0,1},
identifierstyle=\ttfamily,
commentstyle=\color[rgb]{0.133,0.545,0.133},
stringstyle=\ttfamily\color[rgb]{0.627,0.126,0.941},
showstringspaces=false,
basicstyle=\small,
numberstyle=\footnotesize,
numbers=left,
stepnumber=1,
numbersep=10pt,
tabsize=2,
breaklines=true,
prebreak = \raisebox{0ex}[0ex][0ex]{\ensuremath{\hookleftarrow}},
breakatwhitespace=false,
aboveskip={1.5\baselineskip},
columns=fixed,
upquote=true,
extendedchars=true,
% frame=single,
% backgroundcolor=\color{lbcolor},
}

Then, you just embed your code inside a lstlisting environment


\begin{lstlisting}[frame=trbl]{}
class Funcio{
private:
map dict;
public:
Funcio(){};
~Funcio(){};
operator()(int param1){
if( dict.exist(param1)){
return dict[param1];
}
double resultat;
// calcular i omplir resultat ...

dict[param1]=resultat;
return resultat;
}
}

\end{lstlisting}


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++)

Bye!

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!

http://www.ted.com/talks/benjamin_zander_on_music_and_passion.htmlj

Ted++;

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

jueves, 22 de octubre de 2009

I CAN HAS GOOGLE WAVE

OH HAI.

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 ;) )

KTHXBAI

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;
return;
}
/*******************/
/*****Hola.h ****/
#ifndef HOLA_H
#define HOLA_H

#include <iostream>
class Hola{
public:
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();
a->saluda();
return 0;
}


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


PROJECT(projecte CXX)

add_definitions(-Wall -W -ggdb)

SET(SRC projecte)

INSTALL(FILES projecte DESTINATION bin)

ADD_EXECUTABLE(projecte ${SRC})

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)

SET(LIBSRC
Hola
)

SET(SRC
projecte
)

INSTALL(FILES libHola.so DESTINATION lib)
INSTALL(FILES projecte DESTINATION bin)


ADD_LIBRARY(Hola SHARED ${LIBSRC})

ADD_EXECUTABLE(projecte ${SRC})

TARGET_LINK_LIBRARIES(projecte Hola)

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

Cya!