Saturday, December 31, 2011

Books I read in 2011


These are the books that I read this year (in case I read a translation the original title is after the translated one and between parentheses):

February
- The Pragmatic Programmer: From Journeyman to Master, Andrew Hunt & David Thomas
- The Hobbit, J. R. R. Tolkien (third time)

March
- Sombras quemadas (Burnt Shadows), Kamila Shamsie
- El coronel no tiene quien le escriba, Gabriel García Márquez

April
- En el camino (On the Road), Jack Kerouac
- Sostiene Pereira (Una testimonianza), Antonio Tabucchi (second time)
- Focus, Leo Babauta

May
- Juego de Tronos (A Game of Thrones), George R. R. Martin
- Choque de reyes (A Clash of Kings), George R. R. Martin
- Storm of swords, George R. R. Martin
- Apprenticeship Patterns: Guidance for the Aspiring Software Craftsman, Dave Hoover, Adewale Oshineye

June
- A feast for crows, George R. R. Martin
- Object Oriented JavaScript, Stoyan Stefanov

August
- A dance with dragons, George R. R. Martin

September
- Clean Code, R. C. Martin

October
- Test Driven Development: By Example, Kent Beck

December
- Estructura de la informació. UOC.
- Estructura i tecnologia de computadors. UOC.

Example of using variadic functions in C

This is the translation into English of an old post.

In my master's thesis I used variadic functions (functions that can accept a variable number of arguments) to be able to pass different differential equations systems to the function in charge of computing Lyapunov exponents.

Since that code is too big to fit in here, I'll post the tiny tests that I did to understand how C variadic functions work.

You can find a great explanation of C variadic functions in a section of apendix A of The GNU C Library manual. In this manual there is an example in which an undetermined number of integers is passed to a function that adds them.

This is the example where I've highlighted and commented the most important lines:
#include 
#include 

int sum (int count,...){
    va_list ap; // List of arguments
    int i, sum;

    /* Initializes the list of arguments */
    va_start (ap, count);         

    sum = 0;
    for (i = 0; i < count; i++){
        /* Obtains the next argument */
        sum += va_arg (ap, int);    
    }
    
    /* Frees the list */
    va_end (ap);       
    
    return sum;
}

int main(void){
    /* This prints 16. */
    printf ("%d\n", sum (3, 5, 5, 6));

    /* This prints 19. */
    printf ("%d\n", sum (10, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10));
    
    return (0);
}

Several important things regarding this example must be remarked:
  • To work with an undetermined number of arguments we must include the header stdarg.h of the C Standard Library.
  • In the function's list of arguments three dots are used to signal the start of the undetermined arguments.
  • A variable of type va_list must be declared. This variable will contain the arguments list.
  • The macro va_start is used to initialize the arguments list. We must tell the macro which is the last determined argument.
  • The macro va_arg is used tp extract the arguments from the list. We must tell the macro the type of the extracted argument. 
  • The macro va_end is used to free the memory.  
This is the result of executing the previous example:
$ ./test1 
16
55

In the next example, I used the same procedure to pass an undetermined number of arguments. In this case, though, the type of the argument is a user defined type:
#include <stdarg.h> 
#include <stdio.h>

typedef struct s_Date{
    unsigned int year;
    unsigned int month;
    unsigned int day;
}t_Date;

void setDate(unsigned int day, unsigned int month, unsigned int year, 
             t_Date *date);
void printDate(t_Date date);

/* Prints several dates */
void printDates(unsigned int numberOfDates, ...){
    va_list ap;
    int i;

    /* Initializes the list of arguments */
    va_start(ap, numberOfDates);         

    for(i = 0; i < numberOfDates; i++){
        // Extracts next argument from the list
        printDate(va_arg (ap, t_Date));
    }
    
    printf("\n");
    
    // Frees the memory
    va_end(ap);          
    
    return;
}

int main(void){
    t_Date date1, date2, date3;
    
    setDate(1,1,2009, &date1);
    setDate(2,2,2009, &date2);
    setDate(3,3,2009, &date3);
    
    /* This prints 1/1/2009 */
    printDates(1, date1);

    /* This prints  1/1/2009 2/2/2009*/
    printDates(2, date1, date2);
    
    /* This prints 1/1/2009 2/2/2009 3/3/2009*/
    printDates(3, date1, date2, date3);

    return (0);
}

/* Initializes a t_Date variable*/
void setDate(unsigned int day, unsigned int month, unsigned int year, 
             t_Date *date){
    date->day = day;
    date->month = month;
    date->year = year;
}

/*Prints a date*/
void printDate(t_Date date){
    printf("%d/%d/%d ", date.day, date.month, date.year);
    return;
}
This is the output:
$ ./test2 
1/1/2009 
1/1/2009 2/2/2009 
1/1/2009 2/2/2009 3/3/2009 

Friday, December 30, 2011

Interesting talk: "Brownfield to green"

I found this talk very interesting:
It's about the re-engineering of a legacy system using some Agile techniques.
The speaker is Nat Pryce one of the authors of "Growing Object-Oriented Software, Guided by Tests" (which is in my reading queue).

Sunday, November 27, 2011

Interesting Talk: "Listening to test smells"

Probably most of you have already watched this Steve Freeman's talk about what test smells can teach us about the design of our code. I watched it last week and found it great. I post the link just in case:

Saturday, November 26, 2011

Sorting a vector of pointers to objects using STL and functors

Imagine you have a stl::vector container that contains pointers to objects of some class, and that you'd like to sort them based on the value of some member variable using a STL algorithm. The approach of overloading the < operator of the class wouldn't work in this case. It works only in case the vector contains objects.

What can we do then?

We can solve this problem using functors or function objects.

Quoting the link above:
"Functors are functions with a state. In C++ you can realize them as a class with one or more private members to store the state and with an overloaded operator () to execute the function."
Let's see a simple example using functors to sort a vector of pointer to objects. As I cannot show examples from the code I write at work ( it's top secret ;) ), I've just made up an example using my favorite food: chocolate.

This is the Chocolate class:
#ifndef __CHOCOLATE_H__
#define __CHOCOLATE_H__

#include <string>

class Chocolate {
  public:
    Chocolate(std::string name, double cocoaPercentage, double price)
    {
      this->cocoaPercentage = cocoaPercentage;
      this->price = price;
      this->name = name;
    };
    ~Chocolate();

    double getCocoaPercentage() { return this->cocoaPercentage; };
    double getPrice() { return this->price; };
    std::string getName() { return this->name; };

  private:
    double cocoaPercentage; 
    double price;
    std::string name;
};
#endif /* __CHOCOLATE_H__ */

Imagine we'd like to sort the following vector:
vector<Chocolate*> chocolates;
using the STL sort algorithm and two different sorting criteria: by price and by cocoa percentage. 

There are two versions of STL sort. The first one takes two parameters, first and last, which are iterators to the initial and final positions of the sequence to be sorted, the range [first, last). This version uses the operator< to compare the elements of the class. As I said above, this version will not work.
The second version accepts, besides first and last, a third parameter, comp, which according to sort's C++ reference is a:
"Comparison function object that, taking two values of the same type than those contained in the range, returns true if the first argument goes before the second argument in the specific strict weak ordering it defines, and false otherwise."
So, to sort our chocolates vector, we'll first have to create two functors: one for each sorting criteria.
I called them ComparatorByPrice and ComparatorByCocoaPercentage:
#ifndef CHOCOLATE_COMPARATORS
#define CHOCOLATE_COMPARATORS

#include "Chocolate.h"

class ComparatorByPrice {
  public:
    bool operator() (Chocolate *a, Chocolate *b) {
      return a->getPrice() < b->getPrice();
    }
};

class ComparatorByCocoaPercentage {
  public:
    bool operator() (Chocolate *a, Chocolate *b) {
      return a->getCocoaPercentage() < b->getCocoaPercentage();
    }
};

#endif /* CHOCOLATE_COMPARATORS */
Notice how we've implemented the () operator for both classes.

Once we have the functors, we just need to pass them to the sort function as its third parameter.
sort(chocolates.begin(), chocolates.end(), ComparatorByPrice());
Notice how we needed to add the () after ComparatorByPrice in order for it to work.

Ok, now that we finally have all the required ingredients to sort our chocolates, let's see the sorting in action:
#include "Chocolate.h"
#include "ChocolateComparators.h"
#include <vector>
#include <algorithm>
#include <iostream>

using namespace std;

void showChocolates(vector<Chocolate*> & chocolates);

int main(int argc, char **argv)
{
  vector<Chocolate*> chocolates;
  chocolates.push_back(new Chocolate("ChocoKoko", 80., 20.));
  chocolates.push_back(new Chocolate("ChocoLolo", 70., 30.));
  chocolates.push_back(new Chocolate("ChocoBebo", 25., 10.));
  chocolates.push_back(new Chocolate("ChocoBrian", 24., 15.));
  chocolates.push_back(new Chocolate("ChocoMiko", 30., 45.));
  
  cout<<"Sorted by price:"<<endl;
  sort(chocolates.begin(), chocolates.end(), ComparatorByPrice());
  showChocolates(chocolates);
  
  cout<<endl<<"Sorted by cocoa percentage:"<<endl;
  sort(chocolates.begin(), chocolates.end(), 
               ComparatorByCocoaPercentage());
  showChocolates(chocolates);
  
  for(unsigned int i=0; i<chocolates.size(); ++i) {
    delete chocolates[i];
  }
  return 0;
}

void showChocolates(vector<Chocolate*> & chocolates) {
  for(unsigned int i=0; i<chocolates.size(); ++i) {
    cout<<chocolates[i]->getName()<< " " 
      <<chocolates[i]->getPrice()<<" "
      <<chocolates[i]->getCocoaPercentage()
      <<"%"<<endl;
  } 
}
This is the output we get:
$ g++ main.cpp ChocolateComparators.h Chocolate.h -o sorters
$ ./sorters
Sorted by price:
ChocoBebo 10 25%
ChocoBrian 15 24%
ChocoKoko 20 80%
ChocoLolo 30 70%
ChocoMiko 45 30%

Sorted by cocoa percentage:
ChocoBrian 15 24%
ChocoBebo 10 25%
ChocoMiko 45 30%
ChocoLolo 30 70%
ChocoKoko 20 80%
In C++11 we could use lambdas instead of functors, but that will be material for a future post.

Update:
See how to do it using lambdas in this newer post: Sorting a vector of pointers to objects using STL and C++11 lambdas

Friday, November 25, 2011

Bash one-line for loops

Bash has become the standard shell on many Linux distributions.
One of my favorite features in Bash are the one-line loops, specially the for ones. Even though you might have listened many times that Bash scripting can become a nightmare due to its complicated and rigid syntax, one-line loops can save you a lot of time.  
As an example, imagine that you have two folders and you need to copy all the files from one folder to the other:
$ ls
folder1  folder2
$ cp folder1/* ../other_folder
$ cp folder2/* ../other_folder
That's alright, but now imagine that you have 1000 folders. Will you manually execute 1000 commands? The answer is obviously no. Here's when one-line bash loops become handy:
$ for i in `ls -d */`;do cp $i/* ../other_folder;done

Let's have a look at how the previous line works. The basic syntax for a for loop in bash is: 
for variable in some_list; do command(s); done 
In our example, we iterate over a list of directories in the current folder using the command `ls -d */`. Note that the "`" is used to execute a command and to be able to assign its output to a variable.

As a second example, imagine that you need to count the number of lines of a bunch of files whose names are comprised of a prefix, such as, "FILE_NAME_" and a suffix that can be a number ranging from 1 to N.
A possible solution using one-line bash loops would be:
$ for i in {1..N}; do cat "FILE_NAME_$i" | wc -l; done
You could also have a list of file names in a file and iterate over them:
$ cat files.list
file_1
file_2
file_3
$ for file in `cat files.list`;do echo $file; done
file_1
file_2
file_3

I hope this post will help you to take advantage of one of my favorite features in Bash :)

Monday, November 21, 2011

Technical friction

A great way to think about the technical debt metaphor to avoid misunderstandings posted by chromatic at Modern Perl Books, a Modern Perl Blog:

Python idioms: Building strings

I'll start a series of posts about Python idioms.
What is a programming idiom? According to Wikipedia's Programming Idiom article, a programming idiom is defined as "the use of an unusual or notable feature that is built in to a programming language".
Python is very rich in useful idioms. Python programmers who take advantage of them are known as pythonistas. On that sense, I highly recommend you to read the famous article Code like a Pythonista: Idiomatic Python by David Goodger.

Once defined the concept of programming idiom and introduced the concept pythonista, let's talk about one of favorite idioms: building strings from substrings.

Imagine that you have a list of strings,
bands = ['Machine Head','Metallica','Opeth','Veil of Maya']
and you want to concatenate each item in the list to form a unique comma separared string. If you come from the C, Java syntax world, you would write something like this:
output = ''
for band in bands[:-1]:
    output += band + ', '
output += bands[-1] 
If you print the content of the output variable, you will get a list of the bands:
print output
>>> Machine Head, Metallica, Opeth, Veil of Maya
This is a very inefficient way to concatenate strings in Python because in each iteration of the for loop, a temporal string is generated before the string addition and thrown away after.

The pythonic way is faster and more elegant:
>>> print ', '.join(bands)
Machine Head, Metallica, Opeth, Veil of Maya

I coded a small example to compare the performance of both techniques:
from functools import wraps
import time

def timed(f):
  @wraps(f)
  def wrapper(*args, **kwds):
    start = time.clock()
    result = f(*args, **kwds)
    elapsed = time.clock() - start
    #print "%s took %d time to finish" % (f.__name__, elapsed)
    print "%.5gs" % (elapsed)
    return result
  return wrapper

bands = ['Machine Head','Metallica','Opeth','Veil of Maya']*100000

@timed
def func1():
  output = ''
  for band in bands[:-1]:
    output += band + ', '
  output += bands[-1]
  return output

@timed 
def func2():
   output = ', '.join(bands)
   return output

func1()
func2()

The result is:

$ python test.py
0.07s
0.01s

If we increase one order of magnitude the bands list:

$ python test.py
0.62s
0.1s

the difference in performance becomes more relevant.

PS: In my toy example, I used the timed decorator that can be found in this stackoverflow thread.

Saturday, November 19, 2011

Dictionary of Algorithms and Data Structures

I've just found "a dictionary of algorithms, algorithmic techniques, data structures, archetypal problems, and related definitions":
Since one of the courses I'm taking at the UOC is about Data Structures I think this place will prove really useful.

Friday, November 18, 2011

Question about different TDD schools at My Agile Education blog

Angela Harms has asked an interesting question at My Agile Education:
I think that J. B. Rainsberger's answer is great.
This is his conclusion:
"The Detroit style leads me to discover types as I go, and the London style leads me to guess-and-refine types as I go. I’m happy to feel comfortable doing both."

Configuring Eclipse for TDD in Python: The Nosetests way

In my daily work, Python is my main (and really beloved) programming language. For coding in Python, I usually work with vim in remote machines and Eclipse IDE in my desktop one. In the next sections I'll explain how to convert Eclipse in the killer TDD Python-IDE, but you can have a look at the official Python Wiki for more options: Python IDE's and Python Editors.

1. Installing Eclipse
In the Eclipse downloads section, get the Eclipse Classic package that corresponds to your platform (I'll focus on Linux in this post, but it should be easy to follow the same steps in Windows and Mac OS platforms as well).
Installing Eclipse is as easy as extracting the downloaded package if you have an existing Java Virtual Machine installed in your system. If not, check this FAQ.

2. PyDev
PyDev is a Python IDE for Eclipse with a lot of goodies such code completion, syntax highlighting, debugger, unit testing support and refactoring options. You can find a very nice installation manual in the offical project page: PyDev Manual (Installing). For lazy readers, it should be as easy as opening Eclipse, go to Help > Install New Software, adding a new software location with the Add button and fill in the location field with the url http://pydev.org/updates. Once added, check PyDev option and follow the instructions.

3. Nosetests
python-nose or nosetests is an unit test-based framework that is capable of discover and execute your tests without having to register them first. Nose makes my life much easier writing test functions to check for exceptions and discovering and executing my test packages. However, I strongly suggest you to read this article to understand which are the main motivations to use a unit test framework and why choosing nose.

Nose is available via setuptools:
$ easy_install nose

Now try to import nose in python:
$ python
Python 2.6.6 (r266:84292, Sep 15 2010, 16:22:56)
[GCC 4.4.5] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import nose
>>>

If nose installation is fine, you shouldn't see any error messages after importing the nose package in the Python console.

If you don't have setuptools installed in your system, there are a few more options to install nose package, check the official installation guide.

4. Configuring Eclipse for continuous-testing
First of all, create a new PyDev project: File > New > Project, navigate to PyDev and choose "PyDev Project". Click "Next", choose a project name (in our case "tdd-example"), select Grammar Version as 2.6 or 2.7 (nose supports Python 3 syntax, but many plugins not) and select the option "Add project directory to the PYTHONPATH?". Finally, click "Finish". You should see now in the PyDev Package Explorer view your new tdd-example project.

Now, go to RunExternal Tools > External Tools Configurations. In Program option, create a new one. Name could be "NoseTestTool", working directory will be "${project_loc}" and in location the path to nosetests binary, in my case "/usr/local/bin/nosetests".

Right click in the project tdd-example > Properties and navigate to Builders. Click in Import and choose the previous created NoseTestTool. Make sure is the first option selecting it and clicking the Up button. Now, click in Edit. In the Main tab, add in Arguments field "--processes=4" where processes is the number of simultaneous threads that will be used to execute your tests. In my case, I use 4 cores, so I set processes to 4.
In the Environment tab, create a new variable with name "PYTHONPATH" and value "${project_loc}".
In Build Options tab, check the options "Allocate Console (necessary for input)", "Launch in background", "After a Clean", "During manual builds" and "During auto builds".

To test that everything is configured fine, create a new Python file in your project, test_all.py and include the following code:

def test1():
    assert True
    
def test2():
    assert False 

At the time that you save the file, nose may execute your tests automagically and an ouput like this should be shown:

.F
======================================================================
FAIL: test_all.test2
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/usr/local/lib/python2.6/dist-packages/nose-1.1.2-py2.6.egg/nose/case.py", line 197, in runTest
    self.test(*self.arg)
  File "/dev/workspace/python/tdd-example/test_all.py", line 6, in test2
    assert False
AssertionError

----------------------------------------------------------------------
Ran 2 tests in 0.002s

FAILED (failures=1)

Nose searches for files and functions that start with "test*". In our case, two functions will be tested, test1 and test2, and one of them will fail (assert False) as seen in the previous output.

I hope this howto will motivate people working with continuous TDD in Python :)

Thursday, November 17, 2011

Watched at work: "STL with Stephan T. Lavavej"

Lately I've been very busy after work because I had some assignments to submit to the UOC (what I'm doing there), so I haven't posted the links of the last three videos we've watched at work.

We're currently watching a series of talks about the STL library published in Microsoft's Channel 9 by Stephan T. Lavavej who is a software engineer that works developing and maintaining Microsoft's STL version. I like his talks very much.
These are the ones we've watched so far:
  1. Sequence Containers.
  2. Associative Containers
  3. Smart Pointers.
There are a lot of videos about C++ in C9.

Wednesday, October 26, 2011

Interesting Talk: "So you think you need a rewrite?"

I've just watched this great talk about what I'm currently working on: a rewrite.
It contains a lot of pearls of wisdom.
They also recommended the book Working effectively with legacy code by Michael Feathers.
Coincidentally, I'm reading this book at the moment and I'm loving it. I think it's interesting to read it even if you're not working with legacy code because it makes you think a lot about dependencies, design and tests.

Watched at work: "Panel on C++11"

Today we watched another talk about C++11:
This talk was part of the C++ and beyond 2011.
The content of the talk was really deep and advanced (at least for my current C++ level). Still, I found some parts of it very interesting and useful. The speakers are top guys in C++.

Sunday, October 23, 2011

Two nice TDD videos in Spanish

I found two nice TDD videos published by Sebastián Hermida as part of his project HolaTDD:
I really like the way he starts doing top-down testing using interfaces.

Thursday, October 20, 2011

Watched at work: "Designing Software with SOLID principles "

We watched another video about SOLID principles:
The example that he showed in his presentation comes from this article in Code Magazine:
In my opinion the article does a better job at explaining the SOLID example.

Sunday, October 9, 2011

Interesting talk: "Is it possible to do OOP in Java?"

I've just watched this interesting talk:
It arose my curiosity. Now I have a couple of papers to read:

Watched at work: "SOLID principle short videos" and "Writing modern C++ code"

We watched the two Jason Gorman's videos about S.O.L.I.D. principles that we didn't have time to watch last week:
I've been following Jason Gorman's blog, Software People Inspiring, for a while now. I find it very interesting and it has a lot of great resources for apprentices like me.

We also watched half of Herb Sutter's talk about C++11:
C++ has turned much cleaner and safer. I'm looking forward to see the rest of it next week.

Sunday, September 4, 2011

Interesting Talk: "Effective Sketches"

I found this talk very interesting:
Effective sketches by Simon Brown

Play and stop an alarm sound using HTML5 audio in a Backbone view

I'm using Backbone.js in my toy project.
I had to adapt the example in my previous post so it could be used in a backbone view.
This is how I did it:
AlarmView = Backbone.View.extend({    
    events: {
        'click #alarmButton': 'alarmButtonPressed',
    },

    initialize: function(){
        _.bindAll(this, 'render', 'alarmButtonPressed', 
                  'preSelectElements', 'playAlarm', 
                  'stopAlarm');                
        this.preSelectElements();        
        this.render();
    },

    preSelectElements : function () {
        this.alarmText = this.$('#alarmTime');
        this.alarmButton = this.$('#alarmButton');
    },

    render: function(){
        return this;
    },

    alarmButtonPressed : function() {
        this.playAlarm();
    },
    
    playAlarm : function () {    
        this.alarmSound = new Audio("alarm.wav");
        setTimeout(this.stopAlarm, this.alarmText.val() * 1000);
        this.alarmSound.play();
    },
    
    stopAlarm : function () {   
        this.alarmSound.pause();
        this.alarmSound.startTime = 0;
    },    
});

$(function(){
    var alarmView = new AlarmView({el: $(document)});
});

And this is the HTML:
<!DOCTYPE HTML>
<html>
    <head>
        <meta http-equiv="content-type" content="text/html; charset=utf-8">
        <script src="libs/jquery-1.6.min.js" type="text/javascript" charset="utf-8"></script>
        <script src="libs/underscore.js" type="text/javascript" charset="utf-8"></script>
        <script src="libs/backbone.js" type="text/javascript" charset="utf-8"></script>
        <script src="alarm.js" type="text/javascript" charset="utf-8"> </script>
    </head>

    <body>
        <input type="text" id="alarmTime" value="1"/>
        <button type="button" id="alarmButton">Start alarm</button>
    </body>    
</html>

Saturday, September 3, 2011

Play and stop an alarm sound using HTML5 audio tag

In my current toy project, I wanted to reproduce an alarm sound every time some event happened.
The alarm sound I found was a bit long, so I wanted to stop it after a given time stored in the application settings.

It seems that HTML5 audio doesn't have a stop method. It has only a pause method. So following the advises in here and here, I managed to write the following code to check how it worked before adding it to my toy project:

var alarmButton = document.getElementById("alarmButton");

alarmButton.addEventListener(
    "click", 
    function() {
        alarmSound = new Audio("alarm.wav");
        window.setTimeout(stopAlarm, 
            document.getElementById("alarmTime").value * 1000);
        alarmSound.play();
    }, 
    true
);

function stopAlarm () {    
    alarmSound.pause();
    alarmSound.startTime = 0;
} 

This is the HTML file:
<!DOCTYPE HTML>
<html>    
    <body>
        <input type="text" id="alarmTime" value="1"/>
        <button type="button" id="alarmButton">Start alarm</button>
    </body>
    
    <script src="alarm.js" type="text/javascript" charset="utf-8">
    </script>    
</html>

Sunday, August 28, 2011

How to use greek symbols in a Gnuplot graphic

This is the translation into English of a previous post in Spanish.

Using the Enhanced Postscript (EPS) terminal it's possible to add a lot of symbols to a Gnuplot graphic. The syntax is very similar to the Latex one.

There's a syntax guide which includes many examples.

To create the following graphic I used the EPS terminal to label the axes with greek letters:


This is my script:
reset 
#Range
set xrange [0:3]
set yrange [-2.5:4.5]
#Range and xtic interval
set xtics -3,0.5,10
#Range and ytic interval
set ytics -2.5,0.5,4.5

#Labels with greek letters
set xlabel "t/{/Symbol p}"
set ylabel "{/Symbol q}"

#Legend position
set key
#Origin
set origin 0,0
#Ratio between heigth and width
set size ratio 0.5

#Color EPS terminal with Arial font is set as outoput terminal
set term post eps enhanced color "Arial" 11

#Graphic size
set size 1,1
#With Border
set border

#Output file
set output "theta.eps"

#Plot command
plot 'pos1.dat' using 1:2 title 'E=0.25' with lines, \
        'pos2.dat' using 1:2 title 'E=0.50' with lines, \
        'pos3.dat' using 1:2 title 'E=0.75' with lines, \
        'pos4.dat' using 1:2 title 'E=1.00' with lines, \
        'pos5.dat' using 1:2 title 'E=1.25' with lines

Thursday, July 21, 2011

En la UOC el próximo semestre

Después de darle unas cuantas vueltas, me decidí finalmente a matricularme de algunas asignaturas de Enginyeria Tècnica d'Informàtica de Sistemes en la UOC para el semestre de otoño:
Me volvió a picar el gusanillo y me volví a liar... ;)

Monday, July 18, 2011

Podcast muy interesante

Acabo de escuchar un podcast muy interesante en Podgramando sobre frameworks actuales para JavaScript, tanto de aplicaciones como de TDD, BDD y testing.
Este es el link: Podgramando: Javascript con Guillermo Pascual

PUMPS Summer School 2011

This week I'll attend the PUMPS Summer School.
Most of my coworkers will attend it to, because we'd like to eventually code some critical parts of our PELE++ application using CUDA. I will follow the beginner's track, (PUMPS 2011 program).
Let's see how it goes.

Wednesday, July 6, 2011

Books I read in June

These are the books I read last month:
  • A feast for crows, George R. R. Martin
  • Object Oriented JavaScript, Stoyan Stefanov

C++ reading club at work

We started a C++ reading club at work several weeks ago.
The chosen book to start was Bruce Eckel's Thinking in C++, Volume One that you can download from here. We read one chapter per week and meet on Fridays after lunch to comment it. So far, we've read the first 5 chapters and we are learning and/or recalling many things.

Friday, June 24, 2011

Clean code thrilled

This afternoon I received a parcel from Amazon with the two books I had ordered:
I'm thrilled, I've just read Clean Code's first chapter and I'm already loving it. 
I'm looking forward to read the rest of the book.

Sunday, June 19, 2011

Revisiting Introduction to Algorithms

I'd like to add some information to my recent post about MIT Introduction to Algorithms course.

Peteris Krumins followed this course online some time ago and posted his personal notes for every lecture in his interesting blog: Good coders code, great reuse.

Learning TDD

TDD stands for Test-driven development and quoting the Wikipedia definition is
"a software development process that relies on the repetition of a very short development cycle: first the developer writes a failing automated test case that defines a desired improvement or new function, then produces code to pass that test and finally refactors the new code to acceptable standards".
I've been hearing a lot about it since I started programming again. That aroused my curiosity and I'd like to learn how to use it.

These are the resources that I plan to use:

Thursday, June 16, 2011

Software Carpentry version 4

Some time ago I posted about Software Carpentry.

Software carpentry is a wonderful initiative to teach scientists and engineers the concepts, skills, and tools that will help them use and build software more productively.

I recently revisited the Software Carpentry site, and they have released the version 4.

These are the lectures in this last version:


All the lectures are freely available under a Creative Commons license.

Learning Design Patterns with PatternCraft

John Lindquist's PatternCraft is a collection of videos that explain design patterns using illustrative examples.

We're using them to help introducing design patterns in our team.

Monday, June 13, 2011

Introduction to Algorithms

I've started to watch the videolectures from the course:
MIT 6.046J/18.410J Introduction to Algorithms (SMA 5503), Fall 2005.

You can find them on youtube or download them from the course site in the MIT OCW.

I hope to learn a bit about data structures, algorithms and complexity.

Tuesday, June 7, 2011

OpenLibra

It's just been released a new and improved version of the Creative Common Library I mentioned in an earlier post: OpenLibra
---
Acaba de salir una nueva versión mejorada de la Biblioteca Creative Common que mencioné en un post reciente: OpenLibra

How to install JsonCpp in Ubuntu and use it in Eclipse CDT

You need to follow these instructions (I slightly modified this installing guide for Mac OS X) to install JsonCpp in Ubuntu and use it from Eclipse:

1. Download JsonCpp from here.

2. Create a new folder decompress and extract JsonCpp there:
$ mkdir /home/youruser/JsonCpp
$ tar xzf /home/youruser/JsonCpp/jsoncpp-src-0.5.0.tar.gz

3. Donwload the SCONS software construction tool from here and decompress and extract it in the jsoncpp-src-0.5.0 folder.
$ tar xzf /home/youruser/JsonCpp/jsoncpp-src-0.5.0/scons-local-1.3.0.tar.gz

4. Copy the contents of scons-local-1.3.0 inside jsoncpp-src-0.5.0

5. Go to jsoncpp-src-0.5.0 and build JsonCpp using SCONS:
$ cd /home/youruser/JsonCpp/jsoncpp-src-0.5.0
$ python scons.py platform=linux-gcc check

5. Install the JsonCpp library and header files:
$ sudo cp /home/youruser/JsonCpp/jsoncpp-src-0.5.0/libs/linux-gcc-4.4.5/libjson_linux-gcc-4.4.5_libmt.so /usr/lib
$ sudo mkdir /usr/include/jsoncpp
$ sudo cp /home/youruser/JsonCpp/jsoncpp-src-0.5.0/include/json/* /usr/include/jsoncpp/

6. Finally open your Eclipse project, go to Project -> Properties -> C/C++ Build -> Settings -> GCC C++ Linker -> libraries and add json_linux-gcc-4.4.5_libmt.

That's all you need to start using JsonCpp in Eclipse

Monday, June 6, 2011

Using JsonCpp to parse JSON in C++

We are using JSON (JavaScript Object Notation) to write the configuration files for our simulations.

JSON is a lightweight data-interchange format. The good thing is that JSON is easy for humans to read and write and that you can find good C++ libraries that parse and write it.

We're using one of them: JsonCpp.

There were several other C++ libraries listed in the JSON project website, but JsonCpp's documentation convinced me to use it.

I installed JsonCpp as a shared library (I'll soon post here how to do it in Linux and MacOs) and wrote a tiny example to test it:

#include <cstdio>
#include <cstring>

// This is the JSON header
#include "jsoncpp/json.h"

using namespace std;

int main(int argc, char **argv)
{
 string json_example = "{\"array\": \
                            [\"item1\", \
                            \"item2\"], \
                            \"not an array\": \
                            \"asdf\" \
                         }";

 // Let's parse it  
 Json::Value root;
 Json::Reader reader;
 bool parsedSuccess = reader.parse(json_example, 
                                   root, 
                                   false);
  
 if(not parsedSuccess)
 {
   // Report failures and their locations 
   // in the document.
   cout<<"Failed to parse JSON"<<endl 
       <<reader.getFormatedErrorMessages()
       <<endl;
   return 1;
 }
  
 // Let's extract the array contained 
 // in the root object
 const Json::Value array = root["array"];
 
 // Iterate over sequence elements and 
 // print its values
 for(unsigned int index=0; index<array.size(); 
     ++index)  
 {  
   cout<<"Element " 
       <<index 
       <<" in array: "
       <<array[index].asString()
       <<endl;
 }
  
 // Lets extract the not array element 
 // contained in the root object and 
 // print its value
 const Json::Value notAnArray = 
               root["not an array"];
 
 if(not notAnArray.isNull())
 {
   cout<<"Not an array: "
       <<notAnArray.asString()
       <<endl;
 }
 
 // If we want to print JSON is as easy as doing:
 cout<<"Json Example pretty print: "
     <<endl<<root.toStyledString()
     <<endl;
 
 return 0;
}

And this is the output:
$ g++ -o test_json test_json.cpp -ljson_linux-gcc-4.4.5_libmt
$ ./test_json 
Element 0 in array: item1
Element 1 in array: item2
Not an array: "asdf"

Json Example pretty print: 
{
   "array" : [ "item1", "item2" ],
   "not an array" : "asdf"
}

There are many other useful methods in JsonCpp's API.

Using a library like JsonCpp, we avoided all the parsing and could focus only on how to use the configuration data. This saved us a lot of time.

Interesting C++ blog

I'm following this interesting C++ blog:
Advanced C++ with examples 
My favourite posts so far have  been a series about design patterns and their implementation in C++.

Saturday, June 4, 2011

My Agile Education

I love Angela's blog My Agile Education.

I think the best description for this blog is Angela's one:
"As far as I know, no one offers a university degree in Agile software development. Since I'm an unschooler by nature, that's ok with me. I'm learning to write software, understand Agile principles, and connect those things to business. This website is for me to learn, and to process and record some of that learning.
And maybe you can do some teaching and learning, too."
The structure of the blog is the following:
  1. She asks a question, expressing her doubts about some concept or technique.
  2. A lot of people from the Agile community answer her, and this way, a profound and interesting debate is started.
I found these debates really informative and worth to read.

There are two other things about this blog that I consider specially interesting:
  • How career switching at a mature age is a more usual phenomenon in USA than here in Spain. I think that it's a great thing and that people switching careers can give a lot to their new fields. I wonder if this type of blog would be so successful here.
  • The amount of people who are able to go on as developers in their forties, fifties and sixties without having to switch to some management job.
To conclude, I'd like to thank Angela for letting us follow her Agile education and giving us an opportunity to learn with her and her community of mentors.

Wednesday, June 1, 2011

Biblioteca Creative Commons | Creative Commons Library

Hace poco descubrí una Biblioteca Creative Commons que contiene libros de informática muy interesantes. Algunos están escritos en inglés y otros en español.

Además el blog de Etnassoft tampoco tiene desperdicio, sobre todo si te interesa JavaScript y jQuery.
---
Recently I've found a Creative Commons Library which has lots of very good computer science books. Some books are written in Spanish and some in English,

Besides Etnasoft's blog (in Spanish) is also really interesting, specially if you're interested in JavaScript and jQuery.

Saturday, May 28, 2011

Video talks and lectures at work so far

A couple of months ago we started a new initiative at work.

I had read Dan North's post about Deliberate Discovery, and had been struck by the idea of learning as the main constraint in a project and the concept of second order of ignorance.

I thought that technical conferences and talks could be a possible way for us to improve. Unfortunately we can't afford to invite people to talk before our team on a regular basis as Google does.

So the idea was to take advantage of the internet and the kindness of people who had shared their talks or lectures online, and, at least, watch them on video. It surely was not like the real thing, but still it was better than nothing. After each talk, if there was time, we could debate about what we had seen.

So I commented it to a work colleague and we asked our boss if we could do it.
He agreed and this way we started the PELE Developers Tech Talks.

These talks are meant to be an informal way of learning about technology and best practices that might be relevant to our project.

So far we've seen the following videolectures:
  1. Debt metaphor by Ward Cunningham.
  2. Technical Debt by Anthony Eden.
  3. The Clean Code Talks: Unit Testing by Misko Hevery
  4. The Clean Code Talks: Don't Look For Things! by Misko Hevery.
  5. The Clean Code Talks: Global State and Singletons by Misko Hevery.
  6. How to design a good API and why it matters by Joshua Bloch.
  7. The Clean Code Talks: Inheritance, Polymorphism & Testing by Misko Hevery.
  8. PatternCraft: Strategy Pattern by John Lindquist.
  9. MIT OCW Multicore Programming Primer, Lesson 5: Parallel Programing Concepts.

Any suggestion about other interesting videolectures would be appreciated.

Wednesday, May 25, 2011

Some fractal music links

One of my friends is taking part in the next Sonar Music Hack Day.
I think that some of the following links might be useful for him:

Wallace, el otro Darwin

Y esta es otra:
20/03/2009
He disfrutado mucho leyendo el artículo que la versión española de National Geographic dedica este mes a la figura del naturalista inglés Alfred Russel Wallace.
Wallace fue codescubridor de la teoría de la evolución y fundador de la biogeografía. Mucho más joven que Darwin, viajero, aventurero, autodidacta y con un caracter novelesco tardó menos tiempo que Darwin en llegar a desarrollar la idea de la selección natural y la evolución.
No es el primer caso de la historia en que varios científicos realizan el mismo descubrimiento de forma simultánea en puntos alejados, pero en esta ocasión, no se produjeron agrias discusiones por el reconocimiento, como por ejemplo en el caso Newton-Leibniz. Esto tuvo que ver mucho con el caracter generoso de Wallace. Respetaba mucho a Darwin y le comunicó por carta sus ideas. Darwin llevaba más de una década trbajando sobre su teoría de la evolución, pero aún no la había publicado. Poco después de recibir la carta, ambos presentaron ante la Linnean Society of London un artículo común detallando sus ideas. Además, espoleado por la carta de Wallace, Darwin se decidió finalmente a publicar El origen de las especies.
Lo más curioso es que Wallace no estaba en Londres en el momento de la presentación del artículo, sino en Malasia. Ni siquiera sabía lo que había pasado. Se enteró de todo por carta. Poco después recibió por correo un ejemplar del libro de Darwin. En una situación en la que otros se hubieran molestado, Wallace se sintió muy agradecido, escribíó muchas cartas a sus amigos alabando lo bien que expresaba Darwin las ideas de la evolución. Lo importante para él eran las ideas no la fama individual. De hecho, cuando recopiló en un libro todos sus pensamientos sobre la evolución lo tituló Darwinismo.
Espero haber despertado su interés sobre Wallace.

Blas Cabrera

Estoy recuperando las entradas que más me gustan de un blog privado que tenía.
Esta es la primera de ellas:
02/10/2009
En el blog La Aldea Irreductible aparece una entrada sobre Blas Cabrera muy interesante.
Blas Cabrera fue el físico español más importante de la primera mitad del siglo XX, (me atrevería a decir que también de todo el siglo).
Formaba parte de la élite de la física mundial en la época dorada de la física en la que aparecieron la teoría de la relatividad y la cuántica. Fue un gran especialista en electromagnetismo, invitado en numerosas ocasiones a las famosas Conferencias Solvay junto a grandes científicos como Einstein, Fermi, Heisenberg, Bohr, Pauli o Curie.
El gran desconocimiento sobre su figura se debe probablemente a que, al terminar la guerra civil, como muchos otros intelectuales republicanos, tuvo que exiliarse a Méjico.

Installing PostgreSQL and pgAdmin3 in OpenSuse

This is a guide I made for my work colleagues:
  1. Install PostgreSQL.
    Do it from the repositories using yast2 and then follow the instructions given in: http://dev-loki.blogspot.com/2008/04/postgresql-on-opensuse.html and http://www.susegeek.com/database/install-and-configure-postgresql-in-opensuse-110/
  2. Populate the data directory.
    Once the package is installed, we must stop and start the server to populate the data directory, which is /var/lib/pgsql/data/ in this case.
    # rcpostgresql stop
    # rcpostgresql start
    
  3. Change the random password assigned to postgres user during installation.
    First in postgresql server:
    # sudo su postgres
    postgres@linux-2dqb:/var/lib> psql
    psql (8.4.4)
    Digite «help» para obtener ayuda.
    postgres=# alter user postgres with password 'pk84';
    ALTER ROLE
    postgres=# \q
    
    And then in Linux:
    # postgres@linux-2dqb:/var/lib> exit
    exit
    # passwd -d postgres
    # passwd postgres
    
  4. Change authentication mode from ident to md5.
    First stop the server.
    # /etc/init.d/postgresql stop 
    
    Then modify the following lines in /var/lib/pgsql/data/pg_hba.conf (the initial lines remain in the file but commented)
    # "local" is for Unix domain socket connections only 
    #local all all ident local all all md5 
    # IPv4 local connections: 
    #host all all 127.0.0.1/32 ident host all all 127.0.0.1/32 md5 
    # IPv6 local connections: 
    #host all all ::1/128 ident host all all ::1/128 md5  
    
    After saving the changes in pg_hba.conf, restart the server for them to take effect.
    # /etc/init.d/postgresql start
    
    You can find an explanation about pg_hba.conf in: http://developer.postgresql.org/pgdocs/postgres/auth-pg-hba-conf.html
  5. Install pgadmin3 from the repositories
  6. Install instrumentation functions to allow pgadmin3 to modify configuration files.
    When connecting to a PostgreSQL database using pgAdmin3 you may receive an error letting you know that the server instrumentation is not installed.
    To install it I followed the instructions given in:
    http://www.question-defense.com/2010/09/17/postgresql-server-instrumentation-not-installed-the-server-lacks-instrumentation-functions
    • Install PostgreSQL Contrib.
      First install the postgresql-contrib package using the yum package manager with the below syntax.
      # zypper install postgresql-contrib   
      
      Another way to do it would be using yast2 to get it from the repositories.
    • Locate adminpack.sql.
      # find / -name adminpack.sql /usr/share/postgresql/contrib/adminpack.sql  
      
    • Install adminpack.
      # /etc/init.d/postgresql start 
      # su postgres postgres@linux-2dqb:/usr/share/postgresql/contrib> postgres@linux-2dqb:/usr/share/postgresql/contrib> psql -U postgres < adminpack.sql 
      
    • Verify that adminpack is working.
      Launch pgAdmin3 and connect to the Postgres server you just installed adminpack on. Once connected to the PSQL server click Tools in the top navigation menu, select Server Configuration from the drop down, and then select either pg_hba.conf or postgresql.conf to view a configuration file. You shouldn't get any error. With the adminpack contribution installed you will now be able to edit pg_hba.conf and postgresql.conf configuration files directly from pgAdmin3.

Recording what I read

Last February I started to record the books I read,

These are the ones I've read so far:

  • February
    • The Pragmatic Programmer: From Journeyman to Master, Andrew Hunt & David Thomas
    • The Hobbit, J. R. R. Tolkien (third time)
  • March
    • Sombras quemadas (Burnt Shadows), Kamila Shamsie
    • El coronel no tiene quien le escriba, Gabriel García Márquez
  • April
    • En el camino (On the Road), Jack Kerouac
    • Sostiene Pereira, Antonio Tabucchi (second time)
    • Focus, Leo Babauta
  • May
    • Juego de Tronos (A Game of Thrones) , George R. R. Martin
    • Choque de reyes (A Clash of Kings), George R. R. Martin
    • A Storm of swords, George R. R. Martin
    • Apprenticeship Patterns: Guidance for the Aspiring Software Craftsman, Dave Hoover, Adewale Oshineye

Sunday, January 2, 2011

Dark Fortran: EQUIVALENCE / Fortran oscuro: EQUIVALENCE

Lately I've been very busy at work translating a library, written in old Fortran 77, into C++.
Besides finding a lot of goto statements and really "creative" ways of passing arguments that change the control flow of functions, I've come across several pretty funny sentences that I've never seen before, such as, for instance, EQUIVALENCE.
Googling a bit I found a site that has turned very useful:
Forbidden / Esoteric / Obsolete Statements
In this site, you can find out the origins of many of this Fortran statements, often present in old Fortran 77 legacy code, and what they are for. In addition to this, whenever possible, alternatives to these sentences are proposed which are more compatible with good programming practices.

---------------------------------------------------------------------------------------------

Últimamente he estado bastante liado en el trabajo reescribiendo en C++ algunas librerías bastante antiguas que estaban programadas en Fortran 77.
Además de infinitud de sentencias goto, y formas "creativas" de pasarle opciones a funciones, me encontré con algunas sentencias bastante curiosas que nunca había visto, como, por ejemplo, EQUIVALENCE.
Buscando en Google encontré un sitio que me ha resultado muy útil:,
Forbidden / Esoteric / Obsolete Statements
En él se explica el origen y funcionamiento de ciertas sentencias de Fortran 77 que uno puede encontrar (desgraciadamente, con frecuencia) en códigos heredados que tengan cierta antiguedad.
Además de esto, siempre que existan, proponen alternativas compatibles con buenas prácticas de programación.