Blog

peppè-peppèpeppè

A E I O U Ipsilòn, peppè…. Se ogni occasione è buona per fare festa, il Carnevale è l’occasione per antonomasia. Quest’anno le feste non sono state belle come l’anno scorso, ma noi ce l’abbiamo messa tutta ugalmente.

“Tutto il giorno sto / con una scimmietta e un cavallo bianco…”. Uguale! Mi ha quasi convinto che in realtà sia Pippi travestita da Mariana gli altri 364 giorni dell’anno.
Che curioso assortimento: scienziato pazzo e Pippi…
Tecniche di lancio di coriandoli… sempre meglio di tecniche per la conquista del mondo (bwa bwa ha ha! la risata diabolica ci vuole dopo una frase del genere). Probabilmente perchè per la conquista del mondo ha già risolto il problema.

Java vs. C++, last call

Well, I dragged this for too long. Now I have to pick the language for the next project. My language of choice is C++, but there are some serious motivation for using Java, one is that all of the junior programmers involved has some experience of Java, another is that middle management is biased toward Java. So, I can still chose C++, but I have to put forward strong and sound engineering reasons. Also because this can become a little … political. I mean – should the project be late for “natural” development reason, or whatever other reason, I don’t want to be blamed because I decided for a language perceived as complicated and rough.
The application isn’t going to need machoFlops or be resource intensive, therefore performance-wise there is no reason to avoid Java.
Java has a thorough and complete library, quite homogeneous even if not always well designed.
I consider C++ to be more flexible and expressive, but is there a more demonstrable software engineering property of C++ that I can use in my argumentations to favor the choice of this language?
(Or conversely is there any demonstrable advantage of Java the could convince me to switch my language of choice).

C++ lambda functions, my first time

Some days ago I wrote my first lambda expression in C++.

    int n=0;
    std::for_each( begin, end, [[&n]](std::uint8_t& a){a=n++;});

If you are back at the C++85 age, this could look like any other alien language from a Star Trek episode. If you are updated at the more recent C++98, the syntax would look funny at minimum.
At least, that is what it looked to me before starting to get some information about the new standard (you can find a brief yet comprehensive recap of what changed in C++ on this specific page of Bjarne’s website).
You should read the code above as follows. The square brackets defines the intro for the lambda function. Within the square brackets you should put what the lambda function should capture of the environment.
In the code, I stated that n should be captured by reference (&). I could have replaced the ampersand if I wanted to have the capture happen by value. Or I could have put nothing should I wanted the lambda function to capture everything.
Next the argument comes, not different from standard function. Eventually the function body.
Once you get this quick start, you will easily decode as a way to fill a range with increasing integers. Take a breath, get another look at the code, ok, now it should make sense.
Well, I’m quite with Stroustrup when he says that he has mixed feelings about lambda functions (I am looking for the quote, but I don’t have it handy). For simple function lambdas are a godsend. On the other hand, lambdas can yield a terrific potential of hiding mechanism and causing major headaches should they escape your control.
If you compare the line above with the code you have to write previously, it is obvious that lambda expressions are a giant leap forward.
In the C++98 days you ought to write –

class DisposableNameForClass
{
public:
    DisposableNameForClass() : n( 0 ) {}
    void operator() ( int& a ) { a = n++; }
private:
    int n;
};

//..
DisposableNameForClass disposableNameForInstance;
std::foreach( begin, end, disposableNameForInstance );

And that is very uncomfortable and inconvenient. By looking at code like this it easy to question whether it makes sense to use the std::for_each at all rather than roll your own code.
But, look at the traditional code

    int n=0;
    while( begin != end )
    {
        *begin++ = n++;
    }

This code is pretty clear to anyone has a minimum familiarity with C or one of the derived language (yes, there is the dereference operator which involves pointers, but shouldn’t pose real obstacles to comprehension).
Is it error prone? Possibly as any code longer than 0 bytes. std::for_each saves you at least two errors – messing up the loop termination condition (e.g. forgetting the ! from the comparison, or comparing for equality rather than inequality) and missing the increment of the iterator (this happened to me at least once).
These reasons may not be enough to recommend std::for_each in C++98, but it is hard to argue against if you can use the lambda functions.

A Matter of… Time

As promised, here I am to write about the other bug. This one needs a bit a background to be understood. At the beginning of the current project (that means some 2 years ago) I designed a software timer for providing time services. User code that needs notification about time event may register the software timer specifying the time event. When the time event occurs the user code is called back.
Software timers are identified by a numeric id. Being an 8bit architecture with a severely constrained data memory, I picked an unsigned 8 bit number as timer id. This id indexes a private array containing the software timer parameters.
There are two kind of timers – repeating and one shot. A repeating timer repeatedly calls you back at given intervals, while an one-shot timer just calls you back once when it expires.
Repeating timers need to be explicitly canceled, but when I was designing the class, it felt like a good idea to let one-shot timer self-cancel pending their expiration.
Time passed, Software timer component being tried and tested became trusted. Then I got some mysterious bugs – code that used to work stopped being called back by timer. It took a while to discover what happened. After the one-shot timer executed its callback the user code still had some dangling references to the timer id.
Occasionally user code could inadvertently cancel the timer pointed to by the dangling reference resulting either in an assertion about a non-existing timer (turned into a reset in release code), or in a deletion of an innocent bystander timer.
I thought a while on the matter and I came to the conclusion that it is not good for the timer to self-delete. Rather is must be up to the user code to get rid of the timer. Unfortunately I cannot apply the lesson learned on the current project because the code base is too large and we are releasing, nonetheless I’ll keep a reminder for the next project.
While talking about timer callback, a colleague found another problem – if you perform timer registration and removal during the callback you are in for serious trouble. In fact the code for the timer dispatcher was about like this –

for( id = 0; id < TIMER_COUNT; ++id )
{
    if( timerHasExpired(id) )
    {
        callbackUserCode( id );
        if( timerIsOneShot( id ))
        {
            deleteTimer( id );
        }
        else
        {
            // timer is repeat
            reloadTimer( id );
        }
    }
}

This code appears good as long as nothing happens on the timers repository during callback. Consider what happens if a one-shot timer is canceled and a new timer is created in the callback code…
There are two ways to deal with this – either queue timer creation/deletion operation during the callback and execute them when the above code is completed. The other is to re-consider the current time nature after the callback, i.e. consider the timer repository “volatile” across the callback. This is our choice –

for( id = 0; id < TIMER_COUNT; ++id )
{
    if( timerHasExpired(id) )
    {
        callbackUserCode( id );
        if( timerHasExpired( id ))
        {
            if( timerIsOneShot( id ))
            {
                deleteTimer( id );
            }
            else
            {
                // timer is repeat
                reloadTimer( id );
            }
        }
    }
}

Lessons learned – 1) don’t provide classes that mixes automatic and explicit object disposal – either the user must always delete objects or the user must never delete objects. 2) critical runs are not just about interrupts, but they may occur in callback as well. Calling back code should be programmed defensively expecting that the user code may wreak havoc on the structure. Should this not be possible then a state variable declaring whether the class is in “callback execution” or “normal execution” must be provided and functions that manipulates class state have to be made aware of the state so to act directly or to defer actions at the end of “callback execution” state.

Ehy dude, where did my frame go?

It is nearly three decades since I write bugs code and I am maturing the idea that each new bug I find should inspire a way to avoid it in the future or, at least, to reduce the chance of falling again in the same mistake. During the past weeks my team and I discovered two bugs and here is my ideas for improving the software quality.

The first bug is likely to be the longest-standing bug I had. As you may know, I am working on a proprietary field bus. We found evidence of the problem at least three years ago. Occasionally our devices lose a frame. It is not tragic – it is a frame in 250 – but, since the protocol does not account for transmission acknowledgment, it may result in wrong device behavior.

We got the assembly driver from our customer, therefore the code is granted to be correct. They use the same code in hundreds of devices and they said they never have such a bad figure in frame reception.

This bug had a chance to live so long for two reasons – first, the customer accepted our firmware with this known problem; second we were quite convinced that this problem should have appeared in their devices as well.

An event broke this impasse – first, we had big troubles in an installation and eventually, it turned out that one device has a slightly defective crystal that caused major frame dropout, wreaking havoc on all the system. This led to some investigation by the hardware guys that told me that crystal precision was very critical in device correctness. The crystal component has a tolerance of 0.5% and our device starts behaving weirdly when the frequency goes 0.4% away from the nominal frequency. This was clearly not acceptable and a solution was urged.

I went to some fruitless investigations before discovering that another firmware, mainly developed by our customer, was much more reliable than ours. After much head-scraping and head-banging against the nearest wall, I went through the aging documentation that the customer gave us to integrate the bus driver.

There I found that it was required to set a global variable, let’s call it FLEX with half of the value of a global constant.

Then I turned to the code and found an old comment of mine that went like this /* FLEX and GIZMO seem not to be used anywhere in the code, they must be private variables */

Of course, removing the comment and properly initializing the variable sent the problem the way of Dodos.

How this could have been prevented? That’s a simple shot – avoid the programmer manually setting obscure and arcane magic values in oddly named global variables. Either provide a complete setup function or let the magic value be computed at compile time.

I’ll write about the other bug, tomorrow. In the meantime, your comments are welcome, as always.

xubuntu and my /var/storage

It was back in the mid-nineties, when I first received a Slackware 3 install CD. I somewhat recall the install process, the terror of wiping out the other OS from the single disk I had. Since then I tried many releases of RedHat and Fedora Core, until recently I turned to Xubuntu for old PCs.
I used Xubuntu also for my media server, which is a network-only small box filled with a 1Tb hd I keep beside my TV. This media server hosts my video and, most important, all my pictures. I have photographies back from 10 years ago, tons of photographies… when I stored (a downsized version of) them into my wife Digital Photo Frame, I counted 14000 pictures.
So, last Friday (Friday 17th, I am not superstitious, mind that) I had a couple of hours of free time and I decided to upgrade the XUbuntu version of my media server.
I saved main configuration files, a couple of packages I installed that were not part of the distribution. Since the linux is located on a CF card and the 1Tb disk is just data, I didn’t mind about backing it up. I mean I have a backup disk I sometimes sync with my actual data, but I didn’t feel the urge to do so.
I started the installation and selected to update the current installation.
After a while I heard my disk head tickling… and the fear rose. I went into a shell, checked for the mounted partition and found my data disk was mounted, issued a ls in the directory and found that more than half of the directories were gone.
Terrified I switched the box off, and turned to the other computer to search for an undelete.
What happened? My data disk was mounted under /var/storage. I choose this because this was a permanent presence in the file system and because under /var is where mysql and postgresql keep their database data. By analogy I thought it was a proper place for my media data base. Well I was wrong (or at least Xubuntu install program thought this was wrong), in fact Xubuntu upgrade wipes out the content of /var, maybe it preserves something, but nothing is asked.
Googling for the right words, I found the way to recover deleted files on a reiserfs partition. Information is a bit dated, but everything worked as expected. I guess I got back 90% of the original data. Recovered stuff was in /lost+found directory, some files had their real name, other files were renamed after their i-node number. Luckily being Picture, I could recover information from the Exif data.
Well… at the end it was just a big panic moment, but everything was sorted out. I have still maybe two/three evenings of work to put everything back in place.
As my esteemed colleague often says – if it nearly works that’s enough, do not change it or it breaks (in Italian sounds much better “Se tanto va che quasi basta, non toccar se no si guasta).

Filastrocca dei segreti pesanti

Ho nascosto quella cosa in fondo a me
perché se non la vedo lei non c’è.
Non ne parlo per non essere più triste
perché se non la dico non esiste.
Ma laggiù in fondo a me nel buio denso
anche se non la vedo io ci penso
e lei beve quel buio come inchiostro
e cresce sempre più, diventa un mostro.
Ma io so cosa ai mostri fa paura:
il sole che taglia in due la notte scura.
Apro la mia finestra a questo sole
ed apro la mia bocca alle parole.
Ne parlo con la mamma, con l’amico…
tu mi spaventi Mostro ed io… ti dico!
E tu ti sciogli in un po’ di porcheria.
Mi dai un ultimo morso e fuggi via.
Mi rimane una bella cicatrice dove
è scritto “Mostro morde, uomo dice!”
(da “Il segreto di Fata Lina”)

To the Moon and Blackwell

I’ve always been convinced that you don’t need big bucks to create masterpieces. Masterpieces are masterpieces regardless of the technology, the cast, the equipment, and the AAA team. Masterpiece is when you’ve got great inspiration and great capabilities. Technology is just something that is in your way. Recently I played two games that prove this theorem.

Blackwell Deception is an old-style point-n-click adventure. Do you remember the good ol’ Zak McKraken and the Alien Mindbenders? Or the more recent Monkey Island series? Well, that’s the genre. But that’s just the technology. There’s a great story, greatly narrated through the pixellated characters. There’s this strange pair – a young woman and the ghost of her uncle. They help just passed away people to understand their new condition and leave this world. While you play you discover both the current story and the characters’ background – their lives. There are 3 (at least) titles in this series, I played some, and I’d like to play more, but I have a life. Nonetheless, if you like either adventures or stories, give this a try, money will be worth spending.

To The Moon is a narrative RPG, really there is little G and not much RP, but there is playable poetry. Besides if you are a bit clumsy – as I am – in adventures, and sometimes it happens to get stuck, this is the game for you. I never doubted what to do or where to go.

The graphics is pixel art, classic RPG pixel art. But the story is light years ahead of everything I played. This is so gentle, so touching… I am just sad it is over.

There are two agents/scientists that help people in realizing their wish. When someone is about to die, they can help him (or her) in achieving the strongest wish they had in life.

So the scientists are called to help a dying men in realizing his wish – going to the moon. They travel back in memories, with the help of virtual reality machinery, in search of the proper spot to insert new memories of their travel to the moon. The mission wouldn’t turn out so simple, but the story of the man, his infancy, his love, his passion, lived in a great flash-back, is something that ties you to the PC and won’t let you go. Here, too, your money will be well spent.

So I’d say, you’ve got no excuses, pick the technology you can afford and create your masterpiece.

Is this the time for Java?

Once upon a time I was a strenuous ZX Spectrum fan, then time changed, technology evolved and, fighting back my feelings, I switched to Commodore Amiga (yes, it took me a detour over the Amstrad cpc, to get ready for change).Then I was fond of the Amiga, but time changed again, Commodore filed bankruptcy and I changed to anonymous PC clone with Windows 3.1.
Sad story, time changes and you must adapt and change as well, saying goodbye to your comfortable little home.
Now I am faced with a hard decision and it seems that it is time for change again. For the incoming project at the company I work for, I will have to lead the development team (and likely to put in some project management as well, but this is another story) and I have been already told that I don’t have to expect we are going to hire top programmer. On the contrary the company is like to get some instances of Joe Slightly Below Average junior programmer.
The project itself is ambitious (as all projects we tackle), there will be Linux, IP communication, complex system, audio and video communication, proprietary and open field bus communication, zig bee localization and the like… So for sure the team will have to find as much as possible from COTS (Components Off The Shelf) and integrate them.
Now I have to select (apparently I am still free of doing this) the language for the main application. Would have been it my project I would have chosen C++ blindly – no discussion. I am also curious about the new C++11 and this would have been a perfect occasion for getting used to the new tools in the language.
But… I have to deal with junior, possibly below the average programmers (and to make things worse, the development team will be far away from me, but this is another story as well).
From my last weekly report:

I am still undecided about the language to use for this project. There are really only two (maybe three) alternatives.

    • Java. Java is quite accessible. It is likely that every college programmer has been exposed (at various degree) to Java. Java prevents you to do simple mistakes on pointers and memory management at the cost of allowing you to enter terrible pains and sufferance by mindlessly making complex mistakes. Java is mature and stable, performance could be sometimes troublesome. Integrating third part components is easy only if they are written in Java or have a Java wrapper.
    • C++. C++ is unfortunately a less obvious choice, many people have it on their resume, just to pair C, but are quite lost at what is C++ today. C++ helps you strongly in avoiding the terrible pains and sufferances of complex mistakes, by letting yourself tie a knot around your neck with simple errors of pointers and memory management. Although C++ is with us since a long time, the latest standard is still young and many programmers still don’t have a clue about the previous one. Performance is not an issue. Integrating third party components should be easy.
    • Python. Ok, I am not really a script language fan, but I reckon that for integration work, these could be the right tools. Write few “glue” code that just works and ignore the rest. Performance are not what you want to look at, but it is up to third party components to be quick. Though resources can be limited on an embedded system to use a scripting language as it was thought to be used.

Despite the silly wording, Java seems to be the reasonable answer, and for sure is the one preferred by management, but is it the right one?

Domenica pomeriggio

Domenica pomeriggio, fuori potrebbe nevicare, forse si, forse no, le previsioni meteo non sono uno dei fiori all’occhiello della nazione.

Finalmente Juan scopre il fascino del meccano (è bastato un mesetto, da Natale ad oggi). L’elicottero l’ha costruito tutto lui e se pensate che sia semplice provateci voi.
Intanto, sulla porta della cucina appariva questo strano messaggio.
Entro e mi trovo davanti mani che impastano e preparano focaccine con movimenti esperti.
Ed ecco Mariana la Cuoca (come il suo cappello ricorda ai più distratti).
E c’è anche la “socia”.
Queste focaccine, fatte con tanta maestria e tanto amore, erano buonissime, ce le siamo pappate a quattro palmenti.