Tuesday, 30 December 2014

As Above, So Below

In my first trip to Paris, back in January 2009, I spent a few hours visiting the Catacombs. It was OK, but probably was the only thing in that trip that didn't meet my expectations (while for all the rest, I'd never imagined that Paris would be such a fascinating place for me). I'm not saying the Catacombs are not worth a visit, but I would put it way after many, many other things in a Parisian "to see" list.

However, they have worked as the backdrop for 2 pretty good horror films, Catacombs, and As above, so below. It's the latter why I'm writing this post (I watched the former some years ago and have not much to say at this time).

"As above, so below" is one of the best horror/thriller films I've watched in a long while. This is one of those found-footage, hand-held (well, head-held for good part of the film) kind of films, which at first put me a bit off (I loved The Blair Witch Project, but usually I prefer a more classic filming approach), but in the end seemed quite appropriate for this work.

I've called it a Horror film, but indeed it spans over some other genres, like (archaeological) adventures and thriller. The plot is quite original and straight forward (don't expect some complex twist or different possible interpretations) and the pace is quite frantic, making a really effective production. At first I was expecting that the causes of the horror would be "natural" ones (getting lost in that maze, maybe some crazy folks...) but after a while it will move into the terrain of the supernatural, which at first disappointed me a bit, but turned out pretty well. I find this film pretty fresh, having nothing to do with the "haunted house", "possessed person" or "evil child" kind of horror that so repetitive and ineffective has turned in the last years.

To sum up, if you want something fresh and powerful that will keep you glued to the screen from the first to the last minute, just go for it.

Sunday, 28 December 2014

Metaprogramming, Reflection and MOP's

Metaprogramming, Reflection and MOP's (Metaobject Protocols) are some of the most interesting topics in Computer Science that I can think of. The idea of a program inspecting itself and modifying itself is for sure beautiful. The specific meaning of each of these terms can be a bit confusing though, and the borders and relations among them rather blurry. My understanding has changed a bit over the years and I think it's good to write here my current view on it.

When reading this excellent and very in depth article about Metaprogramming in ES6 with Proxies, I felt a bit confused by the notion of Reflective Metaprogramming exposed there and its different subparts. It was a bit different from how I used to think of Reflection and Metaprogramming and their different classifications, so I've been doing some reading to clarify this nomenclature and taxonomy.

Metaprogramming is a wide topic, and from the Wikipedia entry we can read:

Metaprogramming is the writing of computer programs with the ability to treat programs as their data. It means that a program could be designed to read, generate, analyse and/or transform other programs, and even modify itself while running

so Reflective Metaprogramming deals with the itself (analysing, transforming and even modifying itself while running)

Reflective Metaprogramming is indeed what I'd always called just Reflection. However, the way I used to subdivide it is a bit different, while Axel Rauschmayer talks about:

  • Introspection: you have read-only access to the structure of a program.
  • Self-modification: you can change that structure.
  • Intercession: you can redefine the semantics of some language operations.

I used to think in these terms (obviously is not something invented by me, I had read it years ago in some book, copy-pasted it in my personal notes and stick to it):

  • Introspection: same as in the above classification, the ability to ask for the type of an object, the methods of a type, its parameters...
  • Structural Reflection: the ability to access properties or invoke methods based on runtime decisions, and even creating new classes (runtime metaprogramming). To a greater or lesser extent most languages possess this feature. In .Net for example it has evolved from the initial Reflection API to the current Roslyn superstar, going through LCG and the DLR.
  • Computational Reflection. This would be a way more complex beast. It would include things like modifying the semantics of a language, from how method resolution and invokation is done or how property or indexed access is performed, to adding new constructs to the language at runtime (yes, crazy stuff like adding new types of loops...). I used to see this related to the existence of a MOP.

The terms Structural Reflection and Computational Reflection don't seem to be particularly popular (you'll find some references along with Behavioral Reflection), so I'll try to change my mindset and use the ones given by Axel Rauschmayer in the future.

The another big and confusing topic is the MOP. Everyone seems to have a different idea of what a MOP is, so I'll give first some definitions that I've found over time:

From StackOverflow

The MOP exposes some or all internal structure of the interpreter to the programmer. The MOP may manifest as a set of classes and methods that allow a program to inspect the state of the supporting system and alter its behaviour. MOPs are implemented as object-oriented programs where all objects are metaobjects.

From Wikipedia

A metaobject protocol (MOP) provides the vocabulary to access and manipulate the structure and behavior of objects. Typical functions of a metaobject protocol include:

Creating and deleting new classes
Creating new methods and properties
Changing the class structure so that classes inherit from different classes
Generating or modifying the code that defines the methods for the class

The metaobject protocol is contrary to the "closed" aspect of Bertrand Meyer's open/closed principle. It reveals and allows a system to modify the internal structure of the objects. For this reason it is usually used sparingly and for special circumstances such as software that transforms other software, for example for reverse engineering.

From Moose Documentation

A meta object protocol is an API to an object system.

To be more specific, it abstracts the components of an object system (classes, object, methods, object attributes, etc.). These abstractions can then be used to inspect and manipulate the object system which they describe.

It can be said that there are two MOPs for any object system; the implicit MOP and the explicit MOP. The implicit MOP handles things like method dispatch or inheritance, which happen automatically as part of how the object system works. The explicit MOP typically handles the introspection/reflection features of the object system.

All object systems have implicit MOPs. Without one, they would not work. Explicit MOPs are much less common, and depending on the language can vary from restrictive (Reflection in Java or C#) to wide open (CLOS is a perfect example).

The distinction done above between implicit and explicit MOP is unclear to me. The way Java or C# handle inheritance is hardcoded and there's not an API to modify it (excluding dynamic C#). There's not API for intercepting method calls or property access (other than creating proxy objects), there's no methodmissing/aoutoload/nosuchmethod, no way to modify inheritance chains or inheritance behavior... All in all nothing to do with the power found in Groovy

Groovy's MOP system includes some extension/hooks points that you can use to change how a class or an object behaves, mainly being:
getProperty/setProperty: control property access
invokeMethod: controls method invocation, you can use it to tweak parameters of existing methods or intercept not-yet existing ones
methodMissing: the preferred way to intercept non-existing methods
propertyMissing: also the preferred way to intercept non-existing properties

And finally from the article by Rauschmayer

The ECMAScript specification describes how to execute JavaScript code. It includes a protocol for handling objects. This protocol operates at a meta level and is sometimes called the meta object protocol (MOP). The JavaScript MOP consists of own internal methods that all objects have. “Internal” means that they exist only in the specification (JavaScript engines may or may not have them) and are not accessible from JavaScript. The names of internal methods are written in double square brackets.

Notice how in ES6 if you want to alter the way property access or method invokation works you can not directly alter the [[GET]] internal method of an object, but to create a proxy and set a get trap. While the article praises this separation between the base level and meta level, I see some disadvantages on it. In Groovy, you can directly alter "the protocol" of an existing object by just adding or redefining its invokeMethod method, so all your references to that instance will get the new behaviour, in JavaScript you would have to update all your references to point to the proxy instance rather than the proxied one. For me this means losing transparency.

So you can see different perspectives on what a MOP is.Iinspired by the article when it says "The term protocol is highly overloaded in computer science" I guess we can say right the same for MOP, it's highly overloaded. I'll give now my own practical definition of what a MOP is:

For me a practical definition of a MOP would be any support (in the form of some sort of API) given by a language in order to modify how property access, method invokation or inheritance work.
Less advanced topics like the way to add new methods or properties (expand) to an existing class or instance, or modify the inheritance (or prototype) chain would be part of that MOP.
More advanced features like modifying/expanding the syntax of the language, changing how exceptions propagate, how loops behave (think for example of a calling a method that would turn all or certain loops into parallel loops), changing methods from sync to async, making those methods memoize results, throttle... would also be part of a MOP.

Thursday, 25 December 2014

Paris Street Art, December 2014

In this previous entry after a weekend breakaway in Paris I said I had not come across much Street Art there if compared to Berlin, but it was probably cause I had not been in the right area. This weekend I was lucky to do another short escape to Paris right before Christmas, and had my hostel in an area that I had read somewhere that could be considered like the Parisian Kreuzberg. I'm talking about Menilmontant-Belleville, an area in the juncture of districts (arrondissements) XIX and XX. Well, it's not Kreuzberg/Fridrieschain cause France is not Germany, and in spite of globalisation (the good parts and the bad parts) cities with such a character and history still manage to keep a big degree of uniqueness. Anyway, there were some moments where I really had a sort of "I'm in Berlin" feeling (lots of left-wing political posters, stickers and slogans on the walls). Something that really helps to it is coming across with pieces done by Artists which works I'm used to find in Berlin.

I found this piece by Alias in Rue Belleville:

this work by Alice in Montmartre

and 2 impressive "small" murals by a genious (with socio-political motivations in most of his works) called Alaniz. This beautiful Arab woman face:

and this "young artist" one:

His style seemed familiar to me, so searching on the net it made quite sense to find that he's based on Berlin, and that some impressive works that remain in my mind from strolling around Berlin, are indeed his creations.

Notice that on the top right of the Arab woman you'll see one of those omnipresent "it's time to dance" paste-ups, that though particularly everywhere in Berlin, are indeed the product of French artist, SOBER.

If you're into Urban landscapes, the point where Canal St Martin and the elevated M2 tracks cross will quite delight your eyes. The similarity with places like KottbusserTor in Kreuzberg is quite clear. I found there a really good work denouncing the drama of child soldiers.

I love the elevated Metro stations around there. The design is almost a clone of those in Berlin; I don't know when these stations were built, but I assume it was well before the EU dream started (however incomplete it is and wrong things have been done, 70 years of peace between European countries is like a dream), so at a time when the French-German relations were pretty bad (as always throughout history save for the last 50 years)... so it's interesting to see how elements of both cities were developed following the same patterns.

I quite liked this "Urban Angel" paste-up:

And obviously pretty enjoyed this Antifa mural

One form of Street Art that is "very French" is painted vans and trucks (I've seen quite a few in Toulouse, but they're everywhere in Paris). In too many occasions it's just ugly Street Crap, but you can find beautiful pieces like these:

I could continue to add pictures here for a good while, but I think it's time to end the post, so will just add this cute tree:

Kurdish Obsession, December 2014

I can't really understand the lack of any real support to the war against ISIS. On the government side, the air strikes are just a bad joke, just a strategy of deception to keep calm that small part of the population that are really horrorized by the drama being lived in Irak and Syria. Without troops on the ground (and that means many troops) there's nothing to do. The negative of Western powers to put troops on the ground there really makes me sick, politicians do not want to go through the trouble of seeing some of those troops coming back in coffins, it won't play nice for the next elections. Sure the idea of sending Westerns to die there is painful, but it's much more painful to see how women and children are enslaved by ISIS terrorist (on a different topic, I can't understand why the media continue to call these beasts "militants", they are real TERRORISTS, and not the PKK fighters), men get their heads chopped off, and the most interesting experiment in social transformation in the last 50 years, Rojava, is kept under attack. As for the "drama" of sending our "guys" to die in a foreign war... well, this is not a foreign war, this is a war against Humanity, and if someone enlists in the army it should be clear to him than dying in combat is one of the chances he faces, it's part of the job.

As for the normal population, this lack of support is deeply revolting. While in 2003 there were massive movilizations against the war in Irak, now we've hardly seen anyone on the streets urging the Government to fight this monstrosity. Well, in the end it makes sense, most people is unable to go beyond the dichotomic views they were instilled with. So basically violence and war are bad, regardless of whether they'll be use to colonize and oppress other people or to try to save other people from oppression and brutality, so a politically correct person can not demonstrate in favor of a military intervention, cause military interventions are always bad... Society of idiots.

It can be quite shocking that I could agree with anything said by Marine Le Pen... but the other they she reminded us in an interview in Euronews (I'm not linking it, I don't want to give any further publicity to the FN) how absurd is to be in a coalition against ISIS with the states that have been funding radical Islam for decades (yes, all those IslamoFascist medieval kingdoms: Saudi Arabia, Quatar... you name it)

Hopefully, as already shown in previous posts, there's a small portion of our society that is aware of this drama and are trying to raise awareness. These are my last street findings in France/

Financial support for Kobane in Toulouse:

And different stickers and posters in Paris, in an area quite full with Antifascist "propaganda":

Parc des Buttes-Chaumont

Paris has such an incredible architecture that at this point, after having enjoyed on several occasions of the main jewels that make up the European Treasure (Prague, Vienna, Budapest, Lyon...) I would dare to say that it's the most beautiful city on earth (sorry for this act of treason, my beloved Prague and Vienna :-D Visiting right before Christmas is maybe one of the best occasions to enjoy its beauty in all its magnificence. Walking along the river banks on a cloudy day, from Notre Dame to the Eiffel Tower, with a Seine flowing dark because of the last rains, a cold but bearable temperature (6 degrees, below that it means pain for me)... buff; those are memories that get intermixed with dreams. Sure France is renowned worldwide for its taste for fashion and perfumes (not that I'm any interested on that...), but in this year living here I've also realised that their taste for many other things like gardens or chocolate is supreme. So being here in Christmas you'll also learn that their taste for Christmas lightning is astonishing (it's pretty nice in Toulouse, but in Paris is just outstanding, those "trees on fire" in Champ Elysees are impressive).

There are so many things to see and that compete to take the first positions on any tourist guide that probably the place I'm recommending in this post does not rank particularly high, but is a must do (at least for your second visit to Paris). The Parc des Buttes-Chaumontis one of the most beautiful urban parks that I can think of. I like it even more than Primrose Hill in London, that for years has been my favourite. This park has several artificial hills, one of them being an island in the middle of a cute artificial lake. This island is crowned by the Temple de la Sibylle, a beautiful and "melancholic" viewpoint. There are also some cascades (they are off now due to restoration works that intend to do the ecological footprint of the park much lower) and 2 bridge giving access to the island, one of them a suspension bridge that will slightly move under your feet when walking along it (designed by the very Gustave Eiffel)

Right in front of the main entrance to the Park you'll see the building of the Mairie du Quartier (the Hall town of the district), typical French Architecture that you find here in every corner, but that in my hometown would be top of the top.

Saturday, 6 December 2014

Pass File Content as Parameter

I've learnt a pretty sweet Windows command line trick today by looking into someone's code at work, so I'll share it here.

It's clear that if we want to pass the contents of a file as standard input to a program all we need is:
myProgram.exe < myFile.txt

But what if we want to pass the content of that file as a parameter to the program? For example you have a program that encrypts a password that you pass as parameter, and you have that password already in a file. The solution is assigning the content of that file to an environment variable, and then passing the value of the environment variable as parameter to the program, I mean:

set /P myVar=<myPasswordFile.txt
encrypt.exe %myVar%

In Linux, as explained here, the thing is more simple:

./encrypt `cat myPasswordFile.txt`

Sunday, 30 November 2014

The Catalonian Issue

I think that it's important that before I start this post I give a bit of background about myself (something that I've quite avoided over these years posting). I have (and this has been so for many years) a deep respect for the right of people's to self determination, to decide whether they want to be part of another country or be a country on its own (whether this means breaking away or joining). In the past we could say that I was a left wing Asturian nationalist that for years tried to harmonize left-wing and internationalism with the idea of nationalism. I've always said that nationalism does not have to involve that your nation is better, that your nation is closed to newcomers or that new borders are to be erected... but though this is possible, it's not easy... For years I defended that both worlds (left-wing and nationalism) were compatible, though I think in that case it would be better to talk about sovereign movements and/or anticolonialist movements. The moment the flag of your nation starts to be omnnipresent in acts and propaganda is when an alarm should be triggered, cause you're moving in the wrong direction, the next step ends up being that your nation is better, and after that horror comes...

Overtime my perception of myself and what surrounds me has quite evolved. I still have a special feeling for the land where I was born and where I've lived most of my life, I still consider it different from the rest of Spain, its different natural set up has given place to a different history and culture, but the concept of nation has turned quite blurred to me. In part it's cause I no longer want to be part of a particular nation, in part it's cause it scares me. It's more and more difficoult to me to reconcile the idea of nation with open borders and multiculturalism, understanding this as a real mix of cultures taking the good parts of each one, not as a less evolved culture invading and destroying a more advanced one. I'm not thinking only about fundamentalist Islam, but also about homophobic, racist, prone to violence (in particular towards women) human groups. I'm less and less interested in "defending the cultural legacy of my ancestors, bla, bla, bla..." and more and more interested in defending the right of people to prosper in and contribute to whatever society they choose, rather than the one where they were lucky or unlucky to be born. In the end our biology is moving in that direction. Our far ancestors were dark skin nomads, then they settled and their skin changed to adapt to that specific place conditions, and now we're all nomads again, searching the place to be happy for a few days, a few years or a life time. As people mix skin color moves to different scales of shades of grey, as an act of natural wisdom as an "umbral" skin color is no longer the wisest evolutionary choice for a creature that moves around the world and which descendants can end up in whatever corner of this planet.

Well, as usual I'm moving this write up to a different dimension of the initially intended, so, to the point. Some weeks ago Catalonia conducted a sort of referendum about breaking away from the rest of Spain. I have to admit that I have a total lack of interest for Catalonia's "fight for freedom". It's a territory I don't relate to, neither for geography, history or culture. If it were the Basques who were doing this poll I would be absolutely supportive. I have this empathy for that land. On one side their natural frame is almost like Asturies (you don't see any sort of natural border when you go from one place to another), their culture, economy, history, is more related to ours, so it's easy to have a certain feeling for that place. On the other side, I've always perceived Basque left wing nationalism as more internationalist and inclusive (but maybe it's just what I want to believe and not what reality is). I have a deep disdain for the main Catalonian "left-wing" (sort of...) nationalism, i.e, ERC. I perceive them as 'we are better than you' types... and I obviously don't like that. "We deserve to be a nation cause we've been much more than you, poor Asturians, all over history..." well, that kind of bullshit sure does not help to get other people's support (and also that constant focus on economy makes the whole thing seem more like a "capitalist" rather than left nationalism).

That said, I quite don't care about whether they break away or not, up to them, it's not my business. However, this whole thing of the referendum appears like a bad joke to me. Probably Catalonian economy is in better shape than Spanish one, but for European standards it's quite broken. The conservative Catalonian government has been undertaking all sort of cuts to the welfare state, starting by the health system, and are using this abrupt switch to the pro-independence mode (they are nationalists in a particular economic level, so as long as being a federal part of Spain was positive for them, there was no real interest in independence, but now they need something to keep the population busy with and prevent them from questioning their very damaging policies). Then the referendum itself has been pretty stupid. They were comparing it with the Scottish referendum, well, Scots had two years to mull over what to do with their future. The UK government had agreed on it, so the vote was for real, if you vote "yes" you break away (of course there was a huge level of economic blackmailing from London, so it's unrealistic to say that Scots could freely decide about their future, but well, that would give for a whole post). Furthermore, breaking away would have much stronger consequences in the Spain-Catalonia case that in the UK-Scotland case, so it's an even more sensitive issue that would need of a really serious reflection for Catalonians (only Catalonians, of course, the idea that the rest of Spain should vote whether to allow them to go independent is so crazy and stupid that could only come from the mind of stupid Spanish nationalist pseudo-democratic politicians). In the Scottis case most British people were talking about a "divorce" and were asking to Scots "please stay with us". In the Catalonian case there's much more hate involved. A part of Spanish people has developed over the years a certain antipathy for Catalonia, and a break away would not be considered as a divorce, but more as almost a war declaration. Even worse, a good part of the Catalonian population (there was massive immigration from other parts of Spain in the 60's, and while some of the kids of this generation are now pro-independence, others are still deeply linked to Spain), would also oppose, and we would end up with a broken/split society like Latvia or Estonia... and that's for sure not a good prospect.

So, after such a long and boring post, time to add something funny/interesting. In my second visit to Carcasonne, while going from the Train Station to La Cité I came across a Pub with a rather crazy mix of identities. It had on display both a Spanish and a Catalonian independentist flag. This would not be particularly odd if the Spanish flag were a Republican one and the Catalonian a left wing one, but this was not the case. The Spanish flag was one of those disgusting ones with a bull on it (as you can imagine a flag showing proud of the tradition of torturing and murdering an animal mainly appeals to conservative Spaniards) and the Catalonian flag was the one used by conservative independentists, so both kinds of dudes do not mix unless they want to have a fight...

A few days later I ran across a very, very funny piece of let's say "sticker art" in one car here in Toulouse. Conservative Spaniards have a tendency to use a bull as a symbol or their country (if the best symbol you can find for your country is one that many of us associate with torture and slaughter, that says quite a lot about the idea of nation that you defend), and Catalonians use a donkey, as some Asturians use an Asturcon (the Asturian pony) and some Galicians a cow. So you will see many Spanish or Catalonian cars with a sticker of a bull or a donkey. This car had a cool mix where a donkey was fucking a bull :-D

Putting aside any considerations as to whether this sexual act was of mutual agreement, the thing was pretty, pretty funny.

Heroes Against Terror

All over our existence Humans have shown and incredible capacity for the creation of horror and misery, for the construction of oppressive systems, for building a hell with bricks of fear, repression and pain, both for the minds and for the bodies. We've certainly have exceeded on that, but as depressive as it sounds it's also inspiring, as all these stories of horror, all these monstrosities have led to a counterpart, to stories of dedication and sacrifice for the others, human beings willing to give their lives to save others from those horrors, looking for no other reward than the awareness of being doing what their morality dictates them as correct. It can be those saving innocent Jews from the orgy of blood of Nazism, or volunteers running to unknown places to save unknown souls from diseases which dangers they know well, or Kurdish heroes saving Yazidis from the madness of IS...

Fundamentalist Islam, Salafism, or whatever denomination we give to that sickening ideology built upon the perverted misinterpretation of the Muslim faith is the biggest threat to human freedom and dignity that has ever existed, and hence it requires from the biggest stories of human sacrifice to protect others from it, combat it and eventually destroy it and wipe off any traces of it from this planet. In the last weeks I've written about the fight of the Kurdish fighters against IS, I've read about left wing Turkish warriors or Western volunteers joining the Kurds in their war against madness, and it's things like those that renew my faith in humanity, in our capacity to overcome all the many other horrors we've created, from ecological catastrophes to economical ones.

Today I've read a beautiful piece of inspiration in The New York Times, an Arab (Jordanian) comic writer trying to combat the indoctrination conducted on kids by radical Islamists. There's been a lack of "normal" heroes for the Muslim kids, there's not an "Arab Superman" or "Arab Spiderman", and Islamists have tried to sell Bin Laden or IS scum as heroes, as the role model, and this guy is confronting that by creating a Universe of heroes in his comics that can counteract the poison instilled by fundamentalists. Normal heroes that try to help others rather than chop the heads of the "infidels". It's very interesting, not only for this particular case but on a broader sense. It all comes down to the same, we can call it heroes, sources of inspiration, guides... in one degree or another we all need them, it's what the first paragraphs of this post have been about, our need to see some light in the empty darkness that we've created.

Friday, 21 November 2014

Kurdish Obsession

While checking some German sites supporting the Kurdish Resistance I came across S.Castro, a German, left-wing rapper. Most information about him is in German (so it's not much helpful to me), but google translate helps a lot with this interview. He's of Kurdish ascent and says interesting things like this:

The S in my stage name is my second name Sinan. The Castro is Fidel Castro, because I greatly admire him as a person and I'm a big supporter of the Cuban Revolution.

In this video one of the guys next to him wears a t-shirt with what I think is the face of the Venezuelan Revolutionary Comandante Hugo Chávez. The music, same as in this other one, is pretty interesting, it sounds rather epic and powerful.

This site contains some very interesting articles about the heroic fight of the Kurdish people. It's quite noteworthy how they stress the fact that this Kurdish fight is more than just the (very noble) cause of defeating the biggest monstrosity humanity has ever seen (IS), it's a fight for a new model of society, more egalitarian and let's say "socialist" (assemblies, cooperatives...). I had already mentioned here my perception of Kurdish nationalism as inclusive and left-wing, and how inspiring it is to find something like that in a human group that is mainly Muslim; what has been going in Rojava in the last years seems to corroborate such perception. Who knows, if hopefully some day the IS monster is dead and buried Rojava will turn into a hot spot for left-wing tourism.

What I've just said is a clear sign of the moral decline of our society. Someone that for so many years has felt such an enormous hate for fundamentalist Islam and other kinds of fascist, discriminatory and oppressive ideologies, should not be thinking of going as a tourist to a calm and free Kurdistan, should be thinking of getting a weapon and joining some sort of XXI century International Brigades and go to Rojava to defend humanity from such abomination of hate and madness. We should all feel Kurdish blood flowing through our veins, but let's assume it, in spite of the economical crisis, most Europeans still live comfortable lives when compared to other generations, and that has made us coward bastards. This article drawing parallelisms between Rojava and the fight against fascism during the Spanish Civil War is real food for thought. If you can read Spanish you must also check this page.

I can't find a better way to finish this article than treating you with this brilliant sentence taken from this brilliant article

To forget is to betray

Saturday, 15 November 2014

Berlin-Kurdistan Connection

I've recently spent a few days (again) in Berlín. This European metropolis is the most free and inspiring place that I can think of, and no matter how often I go there, I always find something inspiring there, be it new street art, some great concert, a new fresh perspective of world affairs...

This time, I was delighted to find out that the German Left and the Antifascist Movement are deeply involved in supporting the fight of the Kurdish people against that monstrosity called ISIS. They've realised (it should be quite obvious, but seems like that stupid sense of "colonial guilt" present in so many Europeans prevents many of them of raising their voice against radical Islam) that nowadays Fascism is much more than just neo-nazi scum and the NPD; ISIS and radical Islam are the most threatening and destructive fascist force the world has ever faced, and anyone with a brain and a bit of common sense should support somehow the fight against them.

You'll find all over Kreuzberg posters and stickers asking to support the Kurdish revolutionary self-defense forces, here you have some samples:

  • Poster of a fundraising party

  • End the criminalization of PKK

  • Poster

  • Sticker

  • Beatiful t-shirt with the word "Resistence" in Kurdish.

The bad part is that I found some of these stickers torn up. One guy told me that some months ago there were clashes between Kurdish people and a disgusting join force of Islamists and far-right Turkish (yeah, it's sickening). I have not been able to found much information about it. These clashes between Kurds and the Islamist scum have been happening in other places in Germany, but the worst ones took place in Hamburg.

I used to think that fundamentalist Islam was quite less prevalent in Germany than in England, but obviously they also have a problem. When you read that there's a salafist mosque in Hamburg and it's well known by the Government one wonders why such a factory of hate has not been closed and anyone related to it either deported or if unfortunately they have European citizenship put in jail and let to rot there for life. It's common sense, but political correctness and a twisted understanding of "tolerance" have deprived our continent of such sense. If the government does nothing, sooner or later it'll be us, aware citizens, who will have to take action, same as with racism, xenophobia or homophobia, we can not leave any room in this continent for any sort of religious fundamentalists.

Apart from all these calls to support the Kurdish people, I also came across this reminder of another long lasting monstrosity, the imprisonment of Mumia Abu-Jamal.

Friday, 14 November 2014

Well Done Europe

In the last years I've lost almost all interest in space exploration. Indeed as I've been drawn more and more into geography, history, human societies (that's why I so much love/need traveling) my interest in science has quite decreased (save for programming). Maybe for that, I've welcomed the success of the Rosetta mission even more than I would have done years ago. It's cause more than in the scientific discoveries that this mission can achieve, I'm interested in the "European rediscovery" that it can bring about (and well, the fact that part of the mission were managed from Toulouse also makes it more appealing).

After so many years being instilled with that feeling of disenchantment and decadence by our enemies, even the more proudly Europeans among us have ended up believing their lies, that Europe is over, that we're an old, declining society with no more future than using the memories of our glorious past to try to attract tourists or students from the new "big players": China, India, Arab medieval kingdoms... I hope this small success could be a key to open that prison of apathy and self-pity in which Europe has been locked up. It would be false to say that "Europe is back" cause we've always been here. In spite of the crisis, of our lame governments, of the USA... Europe has continued to be for all these years the most advanced and dynamic society in the world. After having been almost destroyed for so many internal wars we voided the chances of new ones by tearing down our internal borders, we've avoided depopulation by welcoming and integrating newcomers (however much I hate the radical Islam or the conservative trends with which some of these new inhabitants have tried to infect the continent, the overall result of this immigration flow is a clear enrichment of our society). We've continued to create and innovate, and we'll continue to do so, cause Europe is a land of Future, all we need is to believe in ourselves. If during so many centuries of fratricidal wars we developed the most advanced culture in this world, just think what we can achieve if we were to completely erase our internal borders and open the external ones to anyone willing to contribute to these achievements and be one of us.

As the French media has been saying these days, "Bravo Europa"

Sunday, 2 November 2014


It's quite odd that someone like me, with such an interest on Geography, History and Social issues, and that so strongly supports people's right to self-determination, has never paid much attention to the Kurdish people and their fight for their rights, but this previous sort of indiference has now turned into a deep admiration.

I can remember having come across with posters of some left wing Kurdish organization in Frankfurt in 2010 and how they called my attention, but thought of it as some isolated case, as all the mess of the last decades with Fundamentalist Islam has made me think of the Middle East and Left politics as antagonists terms (which is particularly painful if one thinks of the many left wing groups that in the 70's existed in the region, from Palestine to Afghanistan, the Arab Socialism, the Iranian communists later on slaughtered by that beast called Khomeini...). This last May in Berlin, while enjoying the delightful atmosphere of the May Day celebrations (it's really one beautiful experience), I found a lot of stands of left wing Kurdish organizations (along with Turkish ones, which makes the whole thing particularly inspiring), but for whatever the reason, my lack of interest in the Kurdish people remained.

It's been in the last weeks, when witnessing the heroic fight of the Kurdish Army and Kurdish volunteers against Islamic State that my interest in them has grown to the point of admiration. Almost one half of the Kurdish troops are women, courageous, unveiled women willing to give their lives in the fight against the biggest monstrosity the world has witnessed since the Nazi Germany times (the other day my uncle draw a comparison that I pretty liked between the advent of Islamic State and the arrival of an alien race willing to enslave and destroy Humanity). PKK forces, yes, that group branded as terrorist by the Turkish government (that so "friend of the West" government with a clear Islamist agenda, that supports Islamist terrorists in Syria, that represses Turkish left-wing organizations, kills demonstrators and that continues to deny the Armenian Genocide), helped rescue the Yazidis in Mount Sinjar from the torture and death that the Islamic State had in store for them. While starting as a Marxist-Leninist organization, they have moved now into more modern left-wing positions, with a deep commitment to the freedom of the different human groups (Arabs, Christians, Yazidis...) living in their territory.

It's also very interesting to see what's happening in the Syrian Kurditan, Rojava with the People Protection Units (YPG). This militia works on a democratic basis and as happens with the rest of Kurdish troops (PKK, Peshmerga) have the support of the non Kurdish population in their territory. While I'm not much fond of Vice News in general, this video is pretty interesting.

This last months Kurdish people living in Toulouse have been gathering on occasion at Place du Capitole to try to raise concern about the drama being lived in their land.

I could be wrong as I've said I had never been interested in Kurdish affairs until recently, but the Kurdish nationalism seems to me as having mainly a left wing flavour, which makes it an inclusive nationalism (or better, let's call it a sovereign movement) rather than an exclusive one.

Before finishing, I want to note what should be obvious, that while I have an enormous contempt for the current Turkish Islamist ultra-nationalist government, this disdain does not extend to the Turkish population. Obviously the idiots that vote for Erdogan and/or those that continue to deny the Armenian Genocide are scum to me, but there are many secular, civilized Turks that oppose and rebel against their tyrannical government. Even today, hard-line far-left groups (it has sort of a 70's feeling to me) operate in the country.

Friday, 24 October 2014

The Power of Eval

In this interview Eric Lippert does an interesting statement about the power of JavaScript's eval:

As for if there will be an eval-like facility for spitting fresh code at runtime, like there is in JavaScript, the answer is sort of. I worked on JavaScript in the late 1990s, including the JScript.NET langauge that never really went anywhere, so I have no small experience in building implementations of JS "eval". It is very hard. JavaScript is a very dynamic language; you can do things like introduce new local variables in "eval" code.

Yes, I had already noticed and profited of the astonishing behaviour of JavaScript's eval time ago. You're invoking a function, but in a way it's as if its code were running right inside the calling function (from a "classic" perspective you get access to the Stack of that calling function). So you can write code where the code inside eval gets access to variables in the current function scope or where eval declares new variables in such scope that can be used later on, like this:

var name = "xuan";
 console.log("name: " + name);
 eval("name += 'lluis';");
 console.log("name: " + name);

 eval ("var city='Toulouse';");
 //access to a variable defined in an eval works fine
 //so it's as if eval were adding the variable to the executio context of the enclosing function
 console.log("city: " + city);

and even like this (where a closure is accessing a variable that was created later than the closure itself:

var var1 = "hi"; 
 var closure = function(){
  console.log("closure start");
  //normal access to trapped variable  
  console.log("var1: " + var1);
  //access to trapped variable defined in an eval run after defining the closure
  console.log("var2: " + var2);
  var2 += " world";
  console.log("var2: " + var2);
  console.log("closure end");

 eval("var2 = 'hello';");
 console.log("var2: " + var2);
 console.log("var2: " + var2);

You can find the code here

So powerful and given how JavaScript Execution Contexts and [[scope]] work, the implementation does seem quite natural (well, for the case of defining a var in an eval and accessing to it later on it seems like the interpreter is adding that variable to the execution context of the enclosing function).

This is clearly much more powerful that the sort of eval that you can implement yourself in C# via Reflection (no need for Roslyn, Mono and linqPad has had this for many years).

All this reminded me about a post JavaScript needs blocks that I had come across some time ago. It's written by a Ruby guy and from my non Ruby perspective (that probably means that I'm not getting the full idea of the article) I don't see any major need for blocks in JavaScript. Anyway, I was thinking you could implement something similar to blocks by passing "code strings" and running them with eval. But there's a problem that I've found with such approach, trying to return from inside an eval. It would be a bit adventurous to think that such return would exit the enclosing function (this has nothing to do with the [[scope]] chain, so for such behaviour the interpreter would have to be designed with this case in mind). So to my surprise, when I did a test I found that JavaScript does not allow returning from inside an eval!

//trying to run this:
eval("return 1;");

//in node.js you'll get:
Illegal return statement
//and in FireFox you'll get:
SyntaxError: return not in function

Perl is the other language that I use on a regular basis that features an eval function. From the documentation:

In the first form, often referred to as a "string eval", the return value of EXPR is parsed and executed as if it were a little Perl program. The value of the expression (which is itself determined within scalar context) is first parsed, and if there were no errors, executed as a block within the lexical context of the current Perl program. This means, that in particular, any outer lexical variables are visible to it, and any package variable settings or subroutine and format definitions remain afterwards.

So yes, if you run some tests you'll see that the code inside eval will have access to the local variables of the enclosing function and to package ones, but local variable declared inside eval will exist only there, won't be accessible outside. Regarding a return statement inside an eval, it'll return from the eval itself, not from the enclosing function.

I've always complained about Perl not coming with a REPL, but well, thanks to eval writing a basic one on your own is that simple as this:

# repl.pl
# A simple REPL for Perl
# Copyright (c) 2014 by Jim Lawless (jimbo@radiks.net)
# MIT / X11 license
# See: http://www.mailsend-online.com/license2014.php
$t="\"Jimbo's Perl REPL\"";
while($t) {
   chomp $t;
   print eval($t),"\n";

Monday, 20 October 2014

Method Missing And AUTOLOAD

I firstly encountered the ability for an object to invoke a default method when an invokation is attempted on a missing one many years ago, when all the frenzy (at the time) around Ruby prompted me to have a look into the language. This feature in Ruby is called method_missing, and at the moment seemed to me like the most "innovative" feature that I could find in the language (for different reasons I didn't like the language too much and have never paid it any attention ever since). At that time, when JavaScript seemed stagnated because of the very different views (wars) on how the language should evolve (all that ECMAScript 4 madness), Mozilla decided to push the language forward adding different experimental features, some of them (generators, let scope, destructured assignment) will finally make it into ES6, others have fallen into oblivion, some of them sadly (I loved the list comprehensions thing copied from Python). One of them was __noSuchMethod__, that as the name suggests, was the same as method_missing.

Years later I came across this same feature in Groovy, and at in parallel the same feature was made possible in C# through TryInvokeMember when using dynamic. All this made me think of this as a state of the art feature (but to my surprise I've found a long list here of languages supporting this idea), so when I started to learn Perl I felt shocked when finding out that such an apparently deprecated language (the true is that the language continues to grow in power and is at this moment a really, really modern language (though quirky, that's for sure)) could sport such a modern feature. The support for this is given under the name of AUTOLOAD, and though I guess it was not born with O.O. programming, proxies or AOP in mind... it really plays nicely.

The basic use is like this:

package Person;
	use strict; use warnings;

    sub New {
		my $class = shift;
		my $self = {
			Name => shift
		bless $self, $class;
		return $self;

    sub SayHi{
		my $self = shift;
		return $self->{Name} . " is saying Hi";
        my $self = shift;
		my $methodMissing = our $AUTOLOAD;
		$methodMissing =~ s/.*:://;
		#do not intercept calls to a non defined DESTROY 
		if($methodMissing eq 'DESTROY') {return;}

        print "unknown method: " . $methodMissing . " invoked on " . $self->{Name} . " with params : " . join(', ', @_);

Notice that I've added a line to prevent action when a missing DESTROY is invoked.

And thanks to it creating Proxies is so damn simple like this:

package AroundProxy;
	use strict; use warnings;

    sub New {
		my ($class, $targetObj, $interceptorFunc) = @_;
		my $self = {
			targetObj => $targetObj,
			interceptorFunc => $interceptorFunc
		bless $self, $class;
		return $self;

        my $self = shift;
		my $methodName = our $AUTOLOAD;
		$methodName =~ s/.*:://;
		#do not intercept calls to DESTROY (as most classes won't define it and we'll get a warning)
		if($methodName eq 'DESTROY') {return;}
		return $self->{interceptorFunc}->($methodName, $self->{targetObj}, @_);

sub aroundTest{
	print "". (caller(0))[3] . "\n";
	my ($p1) = @_;
	my $proxy = AroundProxy->New($p1, 
			my $methodName = shift;
			my $targetObj = shift;
			print "$methodName started with params:" . join(", ", @_) . "\n";
			my $res = $targetObj->$methodName(@_);
			print "$methodName finished\n";
			return $res;
	print $proxy->SayHi() . "\n";

Bear in mind that Perl supports multiple inheritance. If you had a class inheriting from several classes that in turn define AUTOLOAD, the AUTOLOAD that will be invoked will be the one of the leftmost class in the inheritance chain (@ISA array), just the same that is done to resolve any other method.

I won't close this post without taking the opportunity to complain about ES6 not including this feature. Some will argue that it's covered by ES6 proxies (using the get trap), but it's quite different. With proxies you're creating a new object to wrap the existing one, if we had methodMissing we would have it directly in the object, which means the possibility of addressing more complex use cases: we could expand an existing object with methodMissing and later on remove it, so we could be enable/disable dynamically the feature in one object

Sunday, 12 October 2014

Canceling "Functional Style" Iteration

Somehow the other day I ended up in this StackOverflow question about how to get out (break) from an Array.prototype.forEach "functional loop". I gave it some thought before reading the answers, and all I could think of was throwing an specific Exception that you could later on catch and swallow. All this brought to my mind memories of those times when the venerable prototype.js was all the rage, as I thought to remember that they were using something similar for the each method that they were mixing into Array.prototype.

To my surprise, when looking into the current documentation, I could not find any mention about it. However, you'll find some old discussions referring to that solution:

So hopefully I was not hallucinating. This led me to think why at some point they decided to remove that feature from prototype.js. Well, if we think of each/forEach as the equivalent of the classic for (..;..;..) I think it makes sense. The most common (correct I would say) use of the classic for (..;..;..) loop is to traverse a whole collection (i.e. the stop condition is having reached the end of the collection). If you are going to traverse a collection until other certain condition is met, the normal, semantic way to do it is by means of a While loop. So if you need to break from a for loop, in most cases I think you should switch to a while loop.

This said, it occurred to me that probably we should have some sort of Array.prototype.while method, something like this:

//function stopCondition(item, index, array) returns true to indicate stop
//function action(item, index, array)
Array.prototype.while = function(stopCondition, action){
 var curPos = 0;
 while (curPos < this.length && !stopCondition(this[curPos], curPos, this)){
  action(this[curPos], curPos, this);

var items = ["Asturies", "Armenia", "Austria", "France", "Germany"];

  return it[0] != "A";

I think it's obviously much better that using forEach and a "break" exception that we'll later on ignore:

  if(it[0] != "A"){
   throw "break";
catch (ex){
 if(ex != "break"){
  throw ex;

Well, actually rolling out your own prototype.while function is unnecessary. In the end what we are doing is selecting elements until a condition is met and applying a function to them, so we already can achieve the same effect by leveraging some of the functionality provided by for example lodash.js: first for doing the selection and then a normal forEach.

var _ = require('./libs/lodash.js');
_.first(items, function(it){
 return it[0] == "A";

Saturday, 11 October 2014

The Returned

I've just come from watching The Returned. The setting can seem rather weird, an allegedly Zombies film from the last year in La Cinemateque de Toulouse, a venue mainly dedicated to classic, cultured works. Moreover, it was a Spanish-Canadian film, shot in English (because of Denis Villeneuve I tend identify Canadian cinema with the French speaking Quebec), and with Spanish rather than French subtitles. Funny, isn't it?

The "arty" modern terror style shot that opens the film already gave me pretty good feelings. After that came what is (mainly) not a zombies film, but an intense action drama/thriller, where the infectious disease is just the base on which a gripping, emotional and desperate story develops, showing the best and the worst of the human condition. Unconditional love and treason fuck together to spawn pain and suffering, fear and hate removes from some human beings the last traces of civilization. This is also a story of survival, of how pressure sharpens our instincts for the best and for the worse.


The final part of the story is bitter and painful, and we see how the past comes to haunt you determining the future, old errors causing new horrors. OK, enough writing, I'm sleepy and I can not add much more other than strongly recommending you to give it a watch.

Sunday, 28 September 2014

Notable Toulousains

There are several renowned people associated with Toulouse. If you live here for some time, chances are that you'll find out on your own about 2 of them: Paul Sabatier and Pierre de Fermat, as 1 of the main faculties of the city and one of the most important Lycees (High Schools) are named after them. Another one, Jean Jaures, was also an affiliate of the city, but his presence extends over the whole country (and the Sud in particular): streets, sculptures and all sort of references. I'd never heard of him before coming here, but he seems like a really interesting man, a social-democrat (way before Social Democracy had turned into the bad joke it's now) with profound anti-militarist feelings that caused him his death in the aftermath of the WWI that so much he tried to avoid (by the way, the story of how his assassin found death in hands of Spanish Republicans is really interesting, sometimes Justice just happens).

If you ever pay a visit to the interior of Le Capitole or to the Musee des Augustins, and I would urge to do so, as both are very pleasant visits (and free each Sunday for the former and each first Sunday of the month for the latter), 2 painters will become quite well known to you: Henri Martin, and Paul Gervais. Bearing in mind that Gervais lacks of an English entry in Wikipedia, and that the one for Henri Martin is very basic (the French one is much more complete), it seems like they didn't gain much international recognition, but I find them both pretty interesting.

As for Henri Martin and his neo-impressionism, while I really like the room bearing his name in le Capitole, with different images of the Garonne (with Jean Jaures in one of them) and the year seasons (I particularly like the Autumn and Winter ones), the work that really caught my attention since the first moment is Beauté, displayed in Musee des Augustins, a really outstanding representation of female beauty.

For Paul Gervais, I mainly know his works in Le Capitole, both in his eponymous room an in La Salle des Ilustres. I've also admired his work in the Palais Consulaire (last week, during the "Journees du Patrimoine" there was free access to many buildings usually closed to the public), and I know he has some paintings in "les Augustines", but I've overlooked them in previous visits, so I have some homework for the next one. All his works known to me revolve around the same noble goal, the careful and delicate portrait of female nudity.

This is done in a very interesting way, a nude beauty that aims to be enjoyed and admired, and it achieves this by doing such contemplation a part of the scene. In all these works, these nude women are not alone, but accompanied by dressed men turned into permanent worshipers of these goddesses. In this sense, "la bain de la Padilla" is probably his most shocking work:

If this man had lived in our times, he well could have become a painter of strippers :-D

Saturday, 27 September 2014

Putting Science back into Fiction

Years ago I used to be pretty much into both General Science and Science Fiction, but over the years I've been going away from it, moving towards history/geography/social issues for the former, and towards drama kind of films for the latter. For the first switch I think it's mainly due to having had the chance to do some travelling, which has awaken my early interests (when I was a kid I was crazy about geography), for the second, I just would say that in the last years I haven't come across too many good SciFic films.

With such set up, Europa Report has come as a particularly beautiful surprise. No doubt that the backbone of the story is pretty exciting, the first manned trip to Europa (that Jupiter's moon that many scientists believe could be home to other life forms), but over similarly promising base ideas the ensuing development fails miserably in too many occasions. In this case a powerful and excellent story is built upon it. A bit slow paced, a bit claustrophobic, a bit emotional, with an interesting narrative formula (parts of the story are told by external sources that seems unclear how have gained that information). No unnecessary "easy horrors" or flamboyant FX, but a beautiful portrait of the human thirst for knowledge, for understanding... and the noble willingness to sacrifice it all in that search for answers.

To me, great part of the success of this film lies on how they've been able to weave a passionate work of fiction around an appealing scientific fact, that chances are that Europa hosts life. Furthermore, it seems like they've pretty much stick to current scientific knowledge when depicting the Moon.

The aspect of the moon Europa was based for accuracy on data from NASA and JPL's maps of the moon's surface

Well, I don't think there's much more that I can say other than recommending you to watch it.

Sunday, 14 September 2014

Java Closures Limitations

I had read some time ago something about the limitations of Java 8 lambdas with regards to modifying state, but I hadn't had time to test it myself. Finally I've been able to give it a go and here are my findings.

This is one of the most typical examples of closures that I can think of, a function that keeps a counter of how many times it's been invoked:

	public static Supplier<String> getPrinterCounterFails(){
		int counter = 0;
		Supplier<String> f1 = () -> {
			System.out.println("function invokation: " + Integer.toString(counter));
			return "a";
		return f1;

The compiler will reject it with this message: local variables referenced from a lambda expression must be final or effectively final

So well, I felt quite puzzled by this limitation. Closures are functions with state, Java 8 does not seem to provide that, it's more like it provides functions with immutable state.

That said, it's indeed quite easy to work around this limitation. If you're trapping a primitive value, as Java 8 forces you to declare it final you can't modify it's state, but if you Wrap that value into another object, then the reference to that object will be final, but you can change the contents of that object, hence the primitive value that you've wrapped there.

	public static Supplier<String> getPrinterCounter(){
		//don't need to explicitely set it as final, as it's not being reassigned, it's effectively final
		/*final*/ int[] counterWrapper = new int[]{0};
		Supplier<String> f1 = () -> {
			System.out.println("function invokation: " + Integer.toString(counterWrapper[0]));
			return "a";
		return f1;

It's been many years since the last time I wrote any Python code (I quite liked the language at first, but over time I ended up moving away from it because of the syntax, seriously, I've turned really intolerant to "non-C syntax"), but I think to remember that closures there had this same kind of limitation.

C# closures don't have this limitation, so this code will work nicely.

	public static Action GetPrinterCounter(){
		int counter = 0;
		return () => {
			Console.WriteLine("function invokation: " + counter.ToString());

It's needless to say that the almighty JavaScript also lacks this limitation.

Well, if we think in terms of how closures are implemented, and not in terms of what a closure should be, things look more clear. In JavaScript, variable resolution is based on [[scope]], ExecutionContext Objects and so on. Basically, a function points to an object where all the arguments and local variables are stored, and that in turn points to the same kind of object in the "parent function". These objects form a chain (similar to the prototype chain) and variables are looked up in this chain of objects. With such implementation, it's clear that this limitation can not exist in JavaScript.

C# and Java have nothing to do with the above. While .Net languages and now Java support functions as first class objects, their underlying platforms, the CLR and the JVM do not. I mean, neither of them has the notion of an object being a function. In both cases lambdas (and anonymous methods) will be desugared into normal (oddly named) methods. In C#, if the function needs state (i.e. it's a closure) this method will be created in a separate class containing fields for the state trapped by the closure. I think it's the same that Scala does. Java follows a more complex approach, the method is created inside the current class, and it's not until runtime (through invokeDynamic and Lambda MetaFactory magic) that a new class (implementing the required functional interface) is created. Then, in .Net a delegate object will be used to invoke this method, in Java we'll use directly the functional interface. Please, note that the above explained for java is a rough approximation based on my incomplete understanding of how lambda translation, invokedynamic and MethodHandles work in Java, I plan to write a long post about it once I've had more time to dive into it.

The problem comes for cases where the variable trapped by the closure could be trapped by another closure, or be modified by the outer function where the closure is created. In that case the compiler would need to do some black magic so that those different variables (a local variable in the outer function, a field contained in the generated class for the Closure) are kept in sync, meaning that if one is changed to point to another memory location or contain a different value (reference vs value type/primitive type), the other does so. Java compiler designers decided not to go through that trouble and just force you to declare these variables final (or be effectively final), while C# compiler designers considered it worth the effort. This means that even code like this works nicely in C#

	public static void ComplexTest(){
		int counter = 0;
		Action a1 = () => {
			Console.WriteLine("inside a1, counter: " + counter.ToString());
		Action a2 = () => {
			Console.WriteLine("inside a2, counter: " + counter.ToString());
		Console.WriteLine("ComplexTest, counter: " + counter.ToString());
		Console.WriteLine("ComplexTest, counter: " + counter.ToString());
		Console.WriteLine("ComplexTest, counter: " + counter.ToString());

//then invoke ComplexTest
//and this is the output
ComplexTest, counter: 0
inside a1, counter: 0
inside a1, counter: 1
ComplexTest, counter: 2
inside a2, counter: 2
inside a1, counter: 3
ComplexTest, counter: 4

Indeed, I had already talked about this more than 2 years ago in this post. You'll find there more information about what the C# compiler is doing and the generated bytecodes.

Sunday, 7 September 2014


Before coming to Toulouse several people told me that for sure I had to pay a visit to Carcasonne, that it was such a beautiful and impressive place. Of course once I'd had a first taste of Toulouse my next steps were visiting Bordeaux (likewise some people had insisted on how nice it was, and yes, it's an incredible place) and then visiting Carcasonne. Obviously I liked the place, "la cité" (the medieval citadel) is impressive, but the rest of the city has no much to see and as my expectations were so high I didn't feel so amazed.

On the other side, when I paid my first visit to Albi, back in February, my expectations were not that high. I mainly expected a smaller version of downtown Toulouse, which of course would be nice, but nothing new to me. Wow, once there I felt fascinated by this "ville", it's much more than a "small Toulouse". Of course, you'll draw much similarities between both old towns (and with Montauban's one), as the 3 of them make up the trinity of Languedoc-style red brick architecture. I was back in Albi a few weeks ago, and the feeling of delight was the same.

My first impressions when walking from the train station to the "Centre de Ville" reinforced that perspective of being in a small Toulouse: the tree lined old boulevards, the Jeanne d'Arc statue (you'll find them in all French cities, but I think this is the only one I remember were she's standing rather than riding a horse), a nice park with astonishing gardens (since I'm here I've gone crazy about gardens, French people have such an incredible taste for gardens, and for architecture and cakes :-) a "Monument aux Morts" that is like a brick brother of the one in Toulouse...

Once in the city center, my first view was that of the Cathedral. Yeah, it's as impressive as all guide books say. The harsh and imposing walls remind me of Los Jacobinos in Toulouse, but taken to another dimension. I remember how much it captivated me many years ago when I read that the main idea of Gothic cathedrals with their large windows and towers and those high ceilings that seem to get lost in heaven... was to make men feel so small before the power of God. That vision is taken one step further here, those walls made me feel before an unconquerable military fortress, and probably that's what their constructors aimed, as it was built in the middle of a land of "heretics" after the bloody Albingensian Crusade. Once inside, things could not get any better, it's astonishing. Those painted ceilings are like a Gothic Sistine Chapel, and then the superb Rood Screen, sporting some of the most elaborate sets of gothic stone filigrees that I can think of.

The old town is much more than the cathedral: the beautiful Saint Salvi church, the red brick medieval buildings everywhere (I've ever felt a fascination for timber-frame houses, but the brick timber-frames that you find in Languedoc are a next level), the so charming Castelviel district... but the real ice of the cake will come when once in the Berbie palace you first get the astonishing views of the garden, the Tarn river with its soft waterfall, the houses leaning over the river and the imposing bridges, it's one of those images that will stay forever in your memory. In a way, this mesmerizing view reminded me of the one that you get from the castle in Cesky Krumlov, though the houses and the river are so different, something established the connection in my mind.

After enjoying the views and the garden for a long while, you should stroll to the river walking through some of the most ancient streets in the city, cross the Pont-View to the right bank, and then cross back to the main bank via the "Pont du 22 Aout 1944" (marking the liberation of Albi from the Nazi scum, just 3 days after Toulouse) that rises proudly over the Tarn for quite some meters (this elevated position could remind you of the bridges in Porto). If you continue along the Boulevard Pompidou you'll end up in another beautiful French garden and enjoy some "modern" (after so much medieval buildings) classic French architecture. Stroll back to the station and carry these memories forever with you. Then, you can even write a crappy post that in no way can express how enjoyable this little city is.

Saturday, 6 September 2014

Seul Contre Tous

Seul Contre Tous (I Stand Alone) is a quite shocking film. I was not aware of it until I got it recommended by one friend. Bearing in mind that it's the first work by Gaspar Noé, the guy behind the devastating Irreversible, I should have already laid my eyes on it long ago. Indeed, I find it odd that this film is not framed in the French Extremity genre.

We're before a rather unconventional film: the story, the narrative, the aesthetic... We could consider the leading character as a sort of Antihero, but in my concept of Antihero it's necessary to be able to gain some sort of identification with him, and in this case I can't. Having been a Vegetarian on moral basis for almost 20 years, it's clear that it would be difficult that I could feel any affection for a butcher (that's our man's "profession") from the start, but as the film goes on things don't get any better, he's a piece a shit (no matter how deeply he's been a victim of society), a rather stinky one. At several points of the story it seems like there's going to be a twist and he's going to transform into a hero, but it never happens. First, when he expounds his philosophical views on loneliness, I pretty agree on start up, but then he takes it way too far. Then, when he's in a bar and the bartender rejects to serve a coffee to a well-behaved customer just cause he's an Arab (with a "you can go for a mint-tea somewhere else" and crap like that) you think our man is going to explode and blow the head of that racist scum, but nothing happens, and furthermore, later on he'll end up showing his homophobic and racist side. About his sickening approach to sexuality, well, I think that's all I can say, sickening.

The film is set in the allegedly crisis-riddend late 80's France. I say allegedly cause also at present newspapers here (I'm still living in France, though sadly I think that only for just a few more weeks) are always talking about how stagnant the economy is and how terrifying the unemployment figures are, but being an Asturian, my notion of crisis is somehow different (25% unemployment, rows of closed shops, rows of "Gold buy and sell" shops, very aged population...). There are several shots in the film that I think try to transmit a sense of political unrest: some disgusting far-right graffiti ("our land, our blood"), walls with huge slogans asking for the vote for the PCF (French Communist Party) and CGT (one trade union).

When he was he was strolling along Lille beside that nurse I had the feeling that the architecture looked quite more British than French, well, seems it's not my mind playing tricks as you can read here


Sunday, 31 August 2014

New IT Jargon

IT is a complex, constantly evolving world where it's rather difficoult for someone with an average brain to keep up with just a small part of the many things one can find interesting. What is quite simple (and sometimes can be pretty helpful) is keeping up with the new vocabulary. When I say helpful, I mean that knowing to name a few of the last cool IT things can make you look smarter than you are (but notice that some managers can consider that knowing what an Acronym stands for is right the same as being an expert on it, so it can end up causing you some trouble).

In the last weeks I've come across with some names/acronyms that can help you look cool :-D

  • NoSQL is one of the most misleading terms of the last years. OK, NoSQL stores do not use SQL, but that's not the real point, the real point is that those Data Stores are not based on the Relational Model we find in RDBMS's. So when I read somewhere that some people had started to use the term NoRel I immediately loved it.
  • Polyglot Persistence. When I first knew about the term polyglot programming I really liked it, it was a fast way to define what the programming world had evolved into, it's no longer enough to be proficient in one language/platform and blindly choose it for all your projects. I guess with Polyglot Persistence it's going to be right the same.
  • BASE. The counterpart to ACID in a NoRel world.
  • MEAN. I think it's been some years since the last time I heard about LAMP, and suddenly a modern, geek incarnation of that web stack is here: MongoDB, Express, AngularJS and Node. I'm almost certain I'll never use this combination. I love Node (but mainly as a scripting platform or just as a way to test JavaScript "proofs of concept") and I'm looking forward to have some time to play with Mongo and AngularJS, but I don't see myself doing any personal Web Development project, and in most companies the LOB (Line of Business) web applications are and will continue to be Java or .Net.
  • MVW. Probably you're a bit fed up of having to stop to think about the distinction among MVC, MVP, MVVM... to explain someone which one (or variation of which one) you're using. Saying "I'm using Model View Whatever" can come really handy to spare you time in fruitless debates.
  • Hoisting. In JavaScript variables declarations (but not initializations) are hoisted (that is, moved to the top). Function declaration (not function expressions) are also hoisted.
  • IIEF. If you've been into JavaScript development in the last years is pretty likely that you've done some use of them, but chances are that you don't know their name: IIFE (Immediately Invoked Function Expression), I mean:
    (function () {  // open IIFE
                    var tmp = 100 - x;

Sunday, 17 August 2014

File Locking

I've gone through some problems with File Locking at work lately, so I think I'll write some notes about it here. We had an application appending lines (results) to a csv file in a shared folder. If that file is opened with Notepad++, results will continue to be appended successfully (and notepad++ will ask you to reload the file as it's been modified), however, if it's opened with Excel by someone with write access permissions on that file, new lines will fail to be appended to the file (we won't lose them as in that case we write to a secondary file, with means that in the end we'll have to consolidate both files). So Excel is locking the file while notepad++ isn't.

We requested Write access to be removed for our users, and just in case we also asked them to always copy the file to a local folder and open their local copy. Anyway, we've found lately that errors continue to happen (as we can see that new lines get added to the secondary file). After some bewilderment we finally found the reason, the errors were happening when a user was copying the file to their local folder (the file has grown enough to take some seconds to get copied, time enough for experiencing collisions with the main process trying to append new results to the file).

I have to admit that I had not much clear how "file locking" works, and I was quite confused on some points. The only kind of locking that I had in mind was that 2 processes (threads indeed) can not write to the same file at the same time, but from the above it seems like there are more cases where locking happens (I guess copying a file would mean just opening it in Read mode), so first I've done some basic tests with a .Net program opening a file with a StreamReader, StreamWriter or FileStrem with differen parameters, and trying to read/write from/to that file with some basic commands: echo hi ≶≶ File.txt / type File.txt.
Notice that I've performed all these tests on Windows, I'll test this on Linux when I have a chance.

1)One process opens a file for writing to it (either with a StreamWriter or a FileStream):

using (StreamWriter sw = new StreamWriter(filePath)) //careful, the StreamWriter empties the file!


using (FileStream fs = new FileStream(filePath, FileMode.Append, FileAccess.Write))

As expected, if another process tries to write to the same file (just a simple echo time >> file.txt), it'll fail with a The process cannot access the file because it is being used by another process error.

Notice however, that there will be no problem to read from this file from another process (a simple type file.txt)

2)Now, let's go for the interesting case, let's open a file for reading(with a StreamReader or a FileStream):

using (StreamReader sr = new StreamReader(filePath))


using (FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read))

and let's try to write to it (again with just a simple echo time >> file.txt), It'll fail So it seems like by default opening a file for reading prevents us from writing to it. This quite fits with the unexpected behaviour that we'd come across when trying to write while copying.
Again, notice that there will be no problem to read from the file from another process.

These results disconcerted me a bit, I guess there has to be a way to open a file for reading while allowing other processes to write to it. Trying to find some more information about File Locking in Windows it happened again that the Wikipedia seems to have just the perfect amount of information.

Microsoft Windows uses three distinct mechanisms to manage access to shared files:

  • using share-access controls that allow applications to specify whole-file access-sharing for read, write, or delete
  • using byte-range locks to arbitrate read and write access to regions within a single file
  • by Windows file systems disallowing executing files from being opened for write or delete access


The sharing mode parameter in the CreateFile function used to open files determines file-sharing. Files can be opened to allow sharing the file for read, write, or delete access. Subsequent attempts to open the file must be compatible with all previously granted sharing-access to the file. When the file is closed, sharing-access restrictions are adjusted to remove the restrictions imposed by that specific file open.
Byte-range locking type is determined by the dwFlags parameter in the LockFileEx function used to lock a region of a file. The Windows API function LockFile can also be used and acquires an exclusive lock on the region of the file.

If you look at the different overloads for the FileStream constructor you'll find a few ones with a FileShare parameter. This is what the article refers to as "file access sharing". In my examples, I've not been using any of those overloads, so I guess I'm in this case:

Windows inherits the semantics of share-access controls from the MS-DOS system, where sharing was introduced in MS–DOS 3.3. Thus, an application must explicitly allow sharing; otherwise an application has exclusive read, write, and delete access to the file (other types of access, such as those to retrieve the attributes of a file are allowed.)

I found then this excellent answer, where a guy opens a file with FileShare.ReadWrite and then copies it by blocks. I've put it into my own FileCopyTaker class and done some tests, and it works like a charm. I can copy a large file and at the same time append additional information to it from another process.

I've uploaded it here.

It's clear from this that doing a file copy from Windows Explorer (or via the copy command) is not using this file-sharing feature at all, and one could wonder why. Well, I think that's the correct default behaviour. In most cases, modifying a file while it's being copied would leave the file in an unusable state (when the copy finishes the other process could still be writing information to the file, so it would be incomplete, and in most cases (save for my particular case of appending a line to a text file) it would mean broken.

You'll find people wondering why there's not a Windows function to check whether a file is Locked. The answer is clear, it would not be useful, as you could run into synchronization issues, I mean, given this code

if (!isFileLocked(filePath)){
	//Do stuff with the file

between the moment when isFileLocked returns false, and the moment you start to do things with it, another process could be locking the file and your code would crash... so in anyway, you should always put your file access code into a try-catch to deal with the possibility of the file being locked