Tuesday 30 March 2010

Call Stack based Breakpoint

Well, this is rather basic stuff, but anyway it's something I'd never done before and could be useful to someone out there.

The other day, while doing some debugging with Visual Studio I wanted to set a Conditional Breakpoint in one method that would break or not depending on what method did the call.

Well, it would make sense to have an option in the Breakpoint Menu or in the Breakpoint Condition window that would let you select that, a method in your Call Stack, but unfortunately there's not such option. I felt a bit lost at first, I'd only used Conditional Breakpoints for basic conditions such as argument1 = "troublesome string" or things like that, but well, the TextBox in the Breakpoint Condition Window lets you write any expression, that means, it's not just comparing two variables there, I can create new objects and so on... so, given that we have the StackTrace class, this is so simple as writing something like this:

new StackTrace().GetFrame(1).GetMethod().Name == "Method2"

you can go up the CallStack as you please by selecting the appropiate StackFrame...

I've tried to test this with lovely SharpDevelop, but I'm getting an exception when trying to set the Conditional Breakpoint...

I've used this dummy code for my testing.
Method1 is invoked both from Method2 and from Main, we only want to break when the immediate caller is Method2...



Wednesday 24 March 2010

Eradicate Disease

I watched last week a nice BBC documentary about Viruses. It touches many different topics:

  • Archaea are in a good proportion extremophiles and are full of viruses.

  • The last thing a virus really wants to do is to kill us. We're their hosts, they need us to live... so a successful virus is one that replicates and infects with ease, but does not cause too much harm to the host.

  • I'd never heard about the concept of Viral sex. This is a fun name for a rather tragic circunstance: when 2 viruses meet in one host and exchange their genetic material (this is what happened with the infamous N1H1 virus)

  • and many more things...


But what mainly called my attention was something that I already knew but hadn't paid too much attention to... eradicate disease
Well, it sounds so appealing, it should be the ultimate goal of medicine, but what have we really achived in that sense?
Over the centuries we've done tremendous advances: hygiene, all sort of treatments: antibiotics, vaccines, cirugy, transplants...
These techniques work in different ways: try to minimize our chance of falling ill, try to minimize the effects the illness has on us, try to restore our lost health...
but none of them has achieved the final goal, eradicating the disease from the face of the Earth for once and forever... except for smallpox.

Smallpox was a terrible viral disease affecting only humans, highly contagious and with a high death rate. It was a horrible inhabitant of Planet Earth until that in 1979, after many succesful vaccination campaings it was eradicated. It's not that it no longer can penetrate our cells or defeat our immune system, it's that it no longer exists!
It's been maybe the biggest achievement in the history of medicine.
Well, a few members of that damned lineage still exist, but securely trapped (well, that's what I'd like to believe) in some highly protected bio laboratory in Atlanta's CDC and in Russian Vector Institute

Another interesting thing the documentary deals with is AIDS. From this and other documentaries you learn how difficult is to find a full cure for it due to its enormous mutation rate, and at the same time how in the last years (and in wealthy countries) it has passed from being a death sentence to being a chronic disease that can be kept at bay thanks to a cocktail of antiviral drugs.
This is also a big achivement for a generation like mine, that grew up with the discovery of the disease, a disease that at a time was called to be one of the biggest threats to humanity (yes, the headlines in the news in the mid 80's were terrifying, and more for 10 years old kids...)
Let's hope the current genetic revolution will manage to bring to their knees many other of our so feared enemies...

Thursday 18 March 2010

Anonymous Methods and Iterator Blocks

Today, while doing a fast test with the Enumerable.SelectMany method (I'd used it mainly for flattening some IEnumerable<IEnumerable<T>>, and got a bit confused the other day when reading the signatures and realizing that's just a specific case of a broader scope) one "brilliant" idea came to my mind, use an anonymous method (a lambda statement) with an iterator block inside. A low priority background thread in my mind started to say "are you sure that can be done, schedule some processing time for me to think it better", but a higher priority thread was already hitting the keyboard.

Write some beautiful code like this:



   1:          IEnumerable<string> citiesList = cities.SelectMany(pair =>

   2:          {

   3:              yield return pair.MainCity;

   4:              yield return pair.SecondaryCity;

   5:          });



invoke the compiler from the command line (yes, sometimes I like it "old school") and let this error message wake you up from your aesthetic dreams...

The yield statement cannot be used inside an anonymous method or lambda expression

Do some googling and find this post from Eric Lippert explaining it. Worth reading material.

What I conclude from this is:
We sometimes forget all the logic behind the compiler magic. Anonymous methods mean the compiler has to create named methods in the background, or classes when these Anonymous methods grab variables from its lexical scope (closures). Iterator blocks mean the compiler has to create a nested class implementing IEnumerable and IEnumerator (well, more or less, if the iterator block is in the GetEnumerator method of an IEnumerable class, the nested class that gets created only needs to implement IEnumerator).
There is a sequence of steps to follow, first the compiler transforms all the Anonymous Methods, then the Iterator Blocks. When an Anonymous method contains an Iterator block we have a problem with that sequence...

You can check some code here

and to spice up this post, a Reflector screenshot showing some of the compiler generated code:

Saturday 13 March 2010

Triage and the volunteer witnesses

Another must see film,Triage, the last film from the Bosniak director Danis Tanović, the man that debuted with No man's land, that absolute masterpiece.
I had not read any review of the film before watching it, I just knew the director and that was enough. In fact, I didn't know that it's based on one book, and I even was unfamiliar with the triage word.

Once again Tanović confronts us with the reality of war, but unlike in his previous film, this time no comic situations are allowed to emerge from the drama, this time war is depicted as it is, brutal and painful, and suffering turns so infectious as the stupidity that causes it. Maybe the irony underlying his previous film was an attempt to reflect the Balkan character, this time hell is in Kurdistan, not in Bosnia, so there's no need for that.

A photojournalist spends one month in Kurdistan (just days before Saddam fancied to spray the civil population with chemical agents). He's about to die there, but he survives and makes it back to Europe where he'll live tormented by his previous experiences and will suffer some sort of posttraumatic stress disorder...

I quite like this film. It's a story about how we can internalize the suffering of the others and how it can devour us, a story about untold stories, a story about understanding and redemption... but above all this film is a tribute to those men who risk their lifes to tell us in images what many of us don't want or don't care to know, the pain and the misery of others, sometime so far and sometimes so close, but usually so ignored.

Since the first time that I attended to a photojournalism exhibition (one about fratricide wars that was held in my town in the late 90s) I've ever felt an enormous respect for these professionals who dare to cross the line and walk the mined fields in the back yard of our comfortable societies...
Nowadays, when there seems to be a camera in every hand and an internet connection in every corner, we could think that everyone can be a photojournalist, and furthermore in real time... but I don't think so. It's not the same portraying the reality that you and yours are suffering than travelling the world seeking the tragedies that complete unknowns are drowning in, being a volunteer witness of horror so that others can also see it and taste it, and vomit their discomfort on those that allow it and cause it.

The two pics below are not directly related to the film, but are 2 of the most impressive pics that I've seen in some time. I "stole" them with my camera in the Xixón photoperiodism exhibition in summer 2009. Iran and the green revolution, by Olivier Laban-Mattei, please, visit his site.




Sunday 7 March 2010

Retorno a Hansala

Last night I watched on TVE2 another very good Spanish film, released in 2009, and directed by the experienced (but totally unknown to me) filmmaker Chus Gutiérrez. It has received awards in Valladolid (Seminci) and El Cairo.

A young Moroccan guy drowns while trying to reach the Spanish coast in a "Patera" (small boat). His sister (that works legally in Spain) wants to take his body back to their hometown, Hansala, a small bereber village in Atlas mountains. The owner of the morgue offers to help in exchange for 3000 euros and both start a trip by van to Hansala. The Spaniard will live some days of profound experiences there...

I would describe the film as a "sweet drama". What I mean with this is that the story already starts in a terribly dramatic way (a view of the "promised coast" from the eyes of someone that is being swallowed by the waters), but though many other terrible experiences add to it as the story evolves, some positive things also happen that end up equilibrating the emotional balance.

Unfortunately, the real story that inspired this film is quite more tough, although some ONGs have been helping for sometime trying to redress the situation(please, click on the ONG link to know more about this sad story). A smallboat packed of "illegal" inmigrants sinks while crossing the strait. Eleven of the poor people there came from the same small place, Hansala. Shit, can you imagine the excruciating pain that had to devastate their village... The owner of the morgue starts a trip to Morocco...

While the film was in postproduction I attended a related exhibition in MUSAC that if well I liked a lot, laid forgotten in some corner of my mind until this night. There was a video installation there, "El Retorno" (2004) that set the basis for the first sequence of the film.

All in all, I absolutely recommend this film, specially for those (like me) that due to crime rates, fanatic Islam and Western Sahara bloody occupation by the Fascist State of Morocco feel a certain level of antipathy for Moroccan "visitors".

Wednesday 3 March 2010

jQuery Animation

I'm an absolute fan of jQuery. I have to admit that first time I checked it it didn't appeal to me that much. I was missing the Prototype.js "OOP on asteroids" features that turn JavaScript into an even more powerful beast. That's not what jQuery is for, jQuery is mainly thought for the User Interface (events, styling, animation...), AJAX and some utility functions. That's fine, cause if you need extra functionality in your Web Browser tier (some business logic, validators...) for which you would prefer a more "class based programming" approach, you still can add prototype.js to the mix (I haven't tried it, but in principle both libraries can play well together).

I already knew that the animation features in jQuery are a real joy to use, but the animation chaining is specially superb. This sample is, simply said, beautiful.
I guess (understanding jQuery source code is not an easy task, so I'm just doing guess work) that the jQuery object has some kind of animation queue, and each call to .animate() queues an animation there.

The problem is that I needed something the other way around. Instead of chaining different animations over a same object, I wanted to chain the same animation on different objects (and with a small delay between each animation to make the effect more noticeable).

So I've created an animator object that makes use of the jQuery animation features. It would be simple to generalize it to accept different animation functions, delays... It's rather simple code, but it involves closures, callbacks, and for some reason I feel like it could be useful to someone.

Here goes the main code:



var animator = function(items, delay)
{
this.animItems = items;
this.animatingIndex = 0;
this.delay = delay;
};

animator.prototype.animate = function()
{
this.animatingIndex = 0;
this.animateNext();
};

animator.prototype.animateNext = function()
{
//the old closure trick
var self = this;
//if this is the last one, do not invoke a new animateNext
if (this.animatingIndex == this.animItems.length -1)
{
$(this.animItems[this.animatingIndex]).toggle(this.delay);
}
else
{
//added the timeout thing to add a pause effect after each item is displayed
$(this.animItems[this.animatingIndex]).toggle(this.delay, function()
{
setTimeout(function(){self.animateNext();}, 300);
});
}
this.animatingIndex++;
}


and here goes what it does:






item1

item2

item3


you can get the full code here

Monday 1 March 2010

Fish Tank

When I talk or write about films I usually warn the audience about my little knowledge about cinema, and my not much common tastes (not only for films...)
This is one of the reasons why I rarely pay much attention to the winners list in Film Festivals. Almost by chance, I found out that some British critics seem to have wanted to make me feel like an educated film buff, by awarding 4 prices (among them, Best British Film and British director of the year) to a film that I strongly recommended a few months ago.

As I said in that post, Andrea Arnold has almost become a cult director with just 2 films. I think next time we think of tough stories in run-down neighborhoods, Andrea's name should come to our mind as one of the persons that better can create and tell those stories, to paint and depict an urban landscape that seems odd for those of us that only know the shiny CCTVed central streets of a few British cities.

My only complain with critics this time is, why didn't you give any award to Red Road in 2006???