Tuesday, 19 September 2017

Promises and Tasks

.Net Tasks and JavaScript Promises are rather similar, as both are used for the same. They hold a value that will be available at some point, moment at which they will invoke some code that we've provided to them as a continuation. There are differences though. In the multithreaded world of .Net the creation of a promise can involve the execution of another thread (when we do Task.Run for example), this is not the case with Promises, as at the Javascript level everything is single-threaded. Another difference is the parameter passed by to the (callback) function that will be executed as a continuation. While Promise.prototype.then will pass just the result of the precedent Promise, Task.ContinueWith will pass the Task itself. This stems from the fact that while we can access the result of a Task via the (blocking) Task.Result property, the only way to access the result of a Promise is by the Promise itself passing that result to us.

I've found another not so obvious difference that I'll share here. In .Net there was only a 2 years gap between the introduction of Tasks (.Net 4.0 in 2010) and the arrival of the magic async/await pair (C# 5 in 2012). In JavaScript the gap between Promises and the introduction of ES7 async/await in some environments (let's put aside libraries that simulated it via iterators) has been much bigger. This means that in .Net the exposure of programmers to ContinueWith has been rather low when compared to how much Javascript developers have dealt with then. To work with "then" we need to clearly interiorize this: Given a Promise P1, when we invoke then on it and obtain a P2 promise, if the callback/handler function that we have passed to then returns another promise (P3), then P2 will not be resolved until when P3 is resolved. This allows us to chain calls to "then" rather than nesting them. I mean (from Exploring ES6):

.then(function (value1) {
    .then(function (value2) {

The flat version looks like this:

.then(function (value1) {
    return asyncFunc2();
.then(function (value2) {

The above is well explained in MDN:

A Promise in the pending status. The handler function (onFulfilled or onRejected) gets then called asynchronously (as soon as the stack is empty). After the invocation of the handler function, if the handler function:
• returns another pending promise object, the resolution/rejection of the promise returned by then will be subsequent to the resolution/rejection of the promise returned by the handler. Also, the value of the promise returned by then will be the same as the value of the promise returned by the handler.

In .NET the behaviour of ContinueWith when the delegate passed to it returns in turn a Task is not so straightforward. This internal Task can be either an Attached Child Task or a Detached Nested Task. By default it'll be a Detached Nested Task, meaning that the outer task does not need of this internal task to be finished to be finished on its own. So this behaviour is different from JavaScript. If we want that the completion of the outer task depends on the completion of the inner task, we have to create this inner task with the TaskCreationOptions.AttachedToParent flag. It is explained here and here.

... the Task being created registers with that parent Task as a child, leading to two additional behaviors: the parent Task won’t transition to a completed state until all of its children have completed as well, and any exceptions from faulted children will propagate up to the parent Task (unless the parent Task observes those exceptions before it completes).

I've tested it myself, but the code using Tasks is rather ugly and odd and won't upload it here. Hopefully using async/await abstracts us of all of this.

The Last Face

To make things clear from the beginning, forget all the crap reviews that you could have read, The last face is an excellent movie. Tough, touching, almost captivating, and the performances of Bardem and Charlize Theron are impressive.

When I found that there was a film directed by Sean Penn and starred by Bardem and Charlize Theron I assumed that it had many chances to be a good film. The plot: 2 doctors working on humanitarian missions in war ravaged Africa end up falling in love, but the relation proves to be too difficoult given their circumstance. Well, the "love story" thing is not my cup of tea, but the attrocities in the different African conflicts are of quite more interest to me, so all in all it still could be a good watch. Then I read the critics and felt shocked. Seems like all the "educated and intelectual critics" (and the so cool attendants to its premier in Cannes) were treating it like shit, mocking it and calling it "the laughing stock of Cannes" and "refugees porno"... I felt quite puzzled, so I decided to see by myself.

The film is amazing. Its 3 components: brutality of senseless conflicts in Africa, the risks taken by Humanitarian workers in their uncompromising devotion to saving unknown lives, and the difficoult (to say the least) love story between two of them, play together masterfully. There are many gripping moments like for example when a kid is being forced to shoot his father (that will literaly blow your head away), or the amazing speech of Charlize Theron in a fund raising event. Also when Charlize advocates for focusing efforts on trying to stop the conflicts and allowing development, questioning what sense it makes to try to save these human beings now, just to keep them living in biggest misery, and Bardem tells her that even in all this misery, they manage to find dignity and joy, loving their children and living on. This film is emotional and inspiring, and I really can't understand the bad reviews. Well, maybe I can.

It seems like much criticism comes from relating this film to the White Savior complex. So it seems portraying whites trying to save black lives is a sort of "neocolonial product". It's as if all these humanitarian heros were just trying to purge the "evil white man" culpability, and furthermore they have no right to fall in love (precisely people that show so much love for others sacrificing their comfortable lives as doctors in wealthy western countries to go deep in hell... ) Fuck off, all this criticism denotes all the stupid colonial shame so predominant in western (sort of) leftists. This film is not about colonialism (the past), it's about people dying now and people that will continue to die tomorrow... And by the way, sure many bad things were done in the past, but thinking that all the current misery is just a consequence of "evil white colonial powers" is an oversimplification and for sure will not help at all.

Maybe some "critics" will also dislike the introduction of the AIDS drama in the film by means of a white woman and not an African. I don't think the intent is to denounce how devastating AIDS is Africa, but to remember us that it's even one more threat stalking these doctors that do not doubt in getting soaked in the blood of a stranger to try to save his life.

Monday, 18 September 2017

Cool Neighbourhoods

When in Copenhagen last month I went for a stroll to Norrebro, a neighbourhood about which you'll hear quite different opinions. From Alternative, arty, multicultural paradise to non-integrated immigrants ghetto passing by Far-left stronghold. I was there just a few hours, but I guess there's a bit of true in each of those opinions. I mainly got the Alternative/Arty/leftwing cool side of the coin, but a shop with a "burkinis" advertisement also gave me a glimpse of the communitarist-islamist crap side. Anyway, the overall impression was nice, and the place reminded me a bit of Berlin's Kreuzberg (my lovely Kreuzberg)

I searched the net to see if this Norrebro-Kreuzberg link was a common impression and I ended up reaching this site ranking the best "Hipster" neighbourhoods in Europe. Notice that the terms Alternative and Hipster, while lacking of a clear and universal meaning, mean pretty different things to me. I guess I'm interested in "Alternative" (but not "too alternative", as I grow older I tend to enjoy a bit of gentrification and "boboization" and a decrease in the number of squats) and not that much in "Hipster", but the thing is that alternative areas tend to become targets for a Hipster invasion, so probably these Hipster neighbourhood should be quite interesting to me.

I've been to some of the places listed there. Some are amazing, but others did not leave any particularly remarkable impression in me when I was there, so I wondered about the criteria they used to rank a neighbourhood as "Hipster". At the same time, I wondered also about the criteria that (in good part unconciously) I use to put an area in my "list of cute alternative hoods". I'll give you a list of the criteria that I think I follow:

  • A tolerant, international, multicolor, multilanguage population
  • Stree Art everywhere
  • Community managed micro-gardens, pots lining the streets and climbing the buildings (Marseille!!!)
  • Aboundance of old buildings (early XX century is still OK) some beautifully restored, some still waiting for better times, but few abandoned ones. Being dotted with some ugly 60's/70's mid-rise buildings can be a plus (like in Kreusberg).
  • Independent Book stores, art shops
  • Creative spirit, social links among residents
  • Nice cafes with outdoor sitting
  • Affordable prices and availability of small studios so that a single person can pay the rent and live alone (like in France) rather than sharing the flat with strangers (like in UK)

There's an element that I have not put in the list cause it's so important that if not present the neighbourhood can not even be taken into consideration. The neighbourhood must be in a city (and hopefully a country) where islamism, racism, xenophobia, homophobia and nationalism are illnesses that have hardly affected the population (well, indeed, having some isolated cases of these scumheads can be nice to hunt them on the streets and inspire some reivindicative art and social awareness). An open society that won't pay attention to how much melanine you have, how you dress, who you fuck with, where you or your ancestors were born... This said, it would be very difficoult to me to consider cities in the USA or most of Eastern Europe as sound candidates to be high in an "alternative places" list. This also applies to the capacity of a city to attract creative minds. Sometime ago I felt shocked when I read somewhere that Warsaw was going to be the next Berlin in terms of creative industry and appeal for digital entrepenours. Come on, Warsaw has a nice skyline and a beautifully rebuilt downtown, but Polish society is in general very conservative and religious (old style Christianism, not the universalist and "altermundialist" kind of Christianism that we see with certain frequency in Western Europe), nationalistic and not particularly keen of people that are "different"... A place like that can not be a hotspot for creative minds.

Without meeting that premise, a place can for sure be still interesting to pay a visit, but won't be a "lovely place where I'd love to live for a while".

I can see here the criteria that they used for their rank. Basically it makes their cities list rather useless to me.
They don't mention at all anything regarding the tolerance and openness of the society... and use stuff that I could not care less, like Vintage fashion, vinyl shops, co-working spaces... Having being a vegetarian for half of my life I'm pretty happy to see that veganism has become more and more common, but seeing it associated to "trendiness and coolnes" rather kicks my balls... Also, I use my bike rather often to move around Toulouse, but I don't see the presence of "independent bike shops" as particularly important.

Saturday, 9 September 2017


Collioure is quite of a hidden gem, or at least, given that I found it by chance and had not heard about it before, that's how it seems to me. During the summer there's a special train "Le train des plages" that for a reduced price (still not cheap, but trains in France are pretty expensive) takes you from Toulouse to different Mediterranean resorts spanning between Narbonne and the Spanish border. Over these years I've been several times in Leucate, that is 2 hours far from Toulouse, so it's pretty good for a day trip to the beach. There are 3 different beach villages in the area (La Franqui, Leucate Plage and Port Leucate), and a cute small village, Leucate Village, nice for taking a coffee in the "Place de la Republique", between a morning bath in La Franqui and several afternoon baths in Leucate Plage. These beachs are OK, but lack of any particular charm (they're mainly a simple touristic resort built from the 70's), but if you like swimming in calm and warm water, they are a nice option for a summer day in Occitanie.

Last year I visited one day in Port la Nouvelle, OK for some swimming, but the lack of any charm here is almost painful... So this year I decided to give it a try to some of the more distant locations (3 hours), I settled on Collioure mainly cause the village and the beach are just adjacent to the train station (no need to take a shuttle bus like in other destinations) and because one of the beachs had (at least partially) sand, rather than painful pebbles. I leveraged this first trip to stop for a couple of hours in Perpignan where I pretty enjoyed a fast stroll around the city center that was good to show me that the city well deserves a full day visit (I guess this autumn).

Once in Collioure I was immediately amazed. The narrow pedestrian streets of the city center with those 2 or 3 stories buildings in bright colors, with those nice art shops and the beautiful plants growing next to most buildings and climbing up their walls (I absolutely love this) really captivated me.

Then I got to the sea side to be confronted with the views of the Notre Dame des Anges church on one side and the imposing Chateau Royal on the other. As I hate pebbles (I guess I have delicate soles) I headed to the second beach (Port d'Avall), on the other side of the chateau (where part of the surface is sand). Wow, it's just beautiful. Swimming in the calm, warm water with the castle on your left and the nice buildings and nearby small mountains behind you is one of those memories that will be coming up to my mind every now and then.

It seems people have been mesmerized by this small village for quite a while, which made it one of the essential locations in the development of Fauvism. Matisse and Derain lived in the village for a while, producing here some of their main works.

Collioure also hosts the grave of the Spanish left-wing poet Antonio Machado, who died in exile in this village, few days after having crossed the border fleeing from the fascist beasts that were destroying his country and would keep it in the darkness for the ensuing 40 years.

On a related note, something pretty interesting in the portion of French coast going from Leucate to Marseille is the proliferation of lagoons between the coast line proper and the main land, it's what is called "etangs". The first time I noticed this was when going by train to Montpellier. When approaching Sete I could see water to both sides of the rail track! Sete sits just between the sea and the lagoon, being traversed by canals and bridges, and though it's not a "French Venice" or something of the sorts... is well worth a visit. When you take "le train des plages", the portion between Narbonne and Port la Nouvelle is pretty amazing, the train goes along a narrow land strip traversing the lagoon, which is surrounded by small mountains with some ugly factory on their feet and eolic parks on their tops.

Wednesday, 23 August 2017

Oresund Bridge

Maybe you know that there is a bridge that joins Denmark to Sweden, bridging the 16 kms gap between Copenhagen and Malmo. Maybe you've seen some pic like this:

A beautiful piece of engineering, for sure. But if you see a picture like this you'll probably be shocked!

What the fuck? A bridge to nowhere? This is a joke or what?

Well, I didn't go through that astonishment cause I had watched this documentary before. There they explain that the Oresund link is indeed a tunnel and a bridge.
The Copenhagen side of the link is just next to the Airport, and having started a high rise bridge there would have caused trouble with air traffic. A 16 kms tunnel would have been too expensive, so the solution was to mix both. A 4 kms tunnel starts in Copenhagen and goes up into an artificial island where the road/tracks run for 4 kms until reaching the 8 kms bridge that ends in the Swedish coast.

Crossing it by train as I recently did is pretty fast. When travelling from Denmark to Sweeden, when you emerge into the surface you'll see the so famous Turning Torso on your left, dominating the whole region of Scania.

By the way, I should write a post about this trip, but as maybe I won't find the time, I'll mention it here. Copenhagen is a really beautiful city. There's not any astonishing spot, but the city as a whole is really cute. I pretty loved the predominance of harmonious architecture, the main canal and its modern buildings, the imposing Christianborg, the lively, relaxed atmosphere...

Regarding Malmo, probably you've heard about it because of the Turning Torso skyscrapper. Well, honestly there is not much more to it. There are a few nice old buildings, but the old town is really, really small, and for the rest, there a few more nice modern buildings like Malmo live, the water front is OK, there is a small canal... but in general the city reminded me of Xixon, A Corunha or some of the cheap, modern and not particularly tasty areas of Toulouse... so, it's not bad, but for sure it's not too interesting.

Monday, 21 August 2017

Some C# dynamic coolness

In the last days I've found some interesting things regarding the use of C# dynamic. I'll put it here.

Implementing Multiple Dispatch. The common use of dynamic is calling a method in a dynamic object. We are getting runtime single dispatch based on the object on which the method is invoked. Either the object itself if it implements IDynamicMetaObjectProvider, or the runtime via reflection, will find the method to invoke. I was not aware that this also applies when the dynamic object is used as parameter. The runtime will check its type and if several methods with the same name exist but with different argument types, it will invoke the correct one based on the runtime type. You can find a cute example here. This is pretty interesting because the runtime will use Reflection to match types with methods, doing on your behalf something that in the almighty JavaScript you would have to do on your own. By the way, this brings to my mind this explanation by Eric Lippert of the differences between using Reflection "manually" and Dynamic

Dynamic and Anonymous Types. At the time of its inception (C# 3) Anonymous Types were pretty limited. The compiler will create a class for your Anonymous Type, but you have no access to its name (so you can not do a cast), meaning that you can only access "freely" to its fields inside the method where they are created (you'll declare it as var and the compiler will use the correct type inside that method). If you return an instance of an Anonymous Object from your method, you'll be returning just an Object (you can not cast them to an inteface nor anything), so in order to access its fields you'll have to use Reflection manually.
Well, we know that dynamic will take care of using Reflection of its own (and pretty effectively thanks to caching), so we can do this:

//It's just the same if we set the return type to "dynamic" or "object" in both cases the compiler will generate a method return "Object"
//static dynamic CreateObject(int flag)
static object CreateObject(int flag)
  return new {Name="Francois"};
static void Main(string[] args)
 dynamic ob = CreateObject(0);

You should notice an important limitation. Fields in Anonymous Types are internal, and when dynamic uses Reflection it plays by the rules, so it won't work if the Anonymous Type was defined in another Assembly.

Json.Net, JValue and implicit conversions. Json.NET has had an excellent dynamic support since quite a few years. This makes accessing the tree of properties in a JObject a real bargain:

var jsonString = @"{
 ""city"" : {
  ""name"": ""Toulouse"",
  ""population"" : 466000
 ""otherData"" : ""aaaa"" 
dynamic obj = JObject.Parse(jsonString); //returns a JObject
string cityName = obj.city.name;
Console.WriteLine("City Name: " + cityName);   

JToken (from which the different JContaine, JObject, JValue objects inherit) supports the dynamic machinery by implementing IDynamicMetaObjectProvider and returning a DynamicProxyMetaObject<JToken> (that extends DynamicMetaObject). The use of dynamic for dynamically accessing properties (or methods) of an object is what we are used to, but when you get to the last element, the "name" in my sample, you have a JValue object, so how does the assignment of a JValue to a string work?
This has quite confused me. It seems like there should be some sort of implicit conversion. Well, the thing is that DynamicMetaObject provides a BindConvert method. I've been having a fast look into the Json.NET source code and honestly, I get a bit lost with all those proxies, metaObjects and binders, but I assume somehow the BindConvert somewhere is who is doing "the magic".

Friday, 18 August 2017

Covariance and Contravariance in Delegates

Delegates covariance and contravariance is a rather confusing topic and I'm not going to put any theory here, you can check any MSDN or stackoverflow response for that, I'll just put here a fast, personal reference. For an excellent approach to Variance in Programming languages, you should read this.
Short ago I talked about Converting from one delegate type to another different delegate type with the same signature. Covariance and contravariance in Delegates is a different topic, but we'll see that in one case it saves us having to do that conversion.

Since C# 2.0 covariance and contravariance applies to the rules that dictate that you can create a delegate of a certain type that points to a method of a certain return type and signature. We no longer need a perfect match between return types and the signature. You can read about it in Variance in Delegates.

What C# 4 brought to the table was covariance and contravariance between related generic delegates. Basically, now you have a relation between Func<Animal> and Func<Cat> and between Action<Cat> and Action<Animal>. It's explained in Variance in Generic and Non-Generic Delegates

I'll put some examples here for easy reference

Delegate Covariance (for return types)

If we have these custom delegate types and method:

  public delegate Animal CreateAnimalDelegate();
  public delegate Cat CreateCatDelegate();
  public static Cat CreateCat(){
   return new Cat();

Since C# 2.0 (one MSDN article mentions 3.0, it's wrong) we can do this, bind a delegate type (returning an Animal) to a method returning a more derived type (Cat):

CreateAnimalDelegate animalCreator = CreateCat;

If we are using generic delegates we can do the same (this is not related to the out keyword introduced in C# 4), here this continues to be delegate binding.

Func<Animal> animalCreatorFunc = CreateCat;

C# 4 brought something new, you can point a variable of a certain delegate type to an instance of a delegate of a different but related type. From MSDN

In .NET Framework 4 or later you can enable implicit conversion between delegates, so that generic delegates that have different types specified by generic type parameters can be assigned to each other, if the types are inherited from each other as required by variance.

//so thanks to C# 4 I can do this assignment of a different delegate type, there is no conversion it's just type compability
Func<Cat> catCreatorFunc = CreateCat;
Func<Animal> animalCreatorFunc = catCreatorFunc;

//so in C# 4 there is type compability, but not really inheritance ("is" works, but "IsSubclassOf" does not)
Console.WriteLine("catCreatorFunc " + ((catCreatorFunc is Func<Animal>)? "IS" : "IS NOT" ) + " Func<Animal>"); //IS 
Console.WriteLine("Func<Cat> " + ((typeof(Func<Cat>).IsSubclassOf(typeof(Func<Animal>)))? "IS" : "IS NOT" ) + " Func<Animal>"); //IS NOT!!!

As you see in the example I can point a Func<Animal> to a Func<Cat>, it's as if they were in an inheritance hierarchy, but it's not really the case, cause while the is operator will tell us that Func<Cat> is a Func<Animal>, the IsSubclassOf will tell us that no inheritance exists.

All in all Covariance for return types seems pretty natural, same as we can do Animal an = new Cat(); , we can do Func<Animal> fAn = new Func<Cat>...;

Delegate Contravariance (for arguments)

Delegate Contravariance seems a bit less natural, cause basically we can do: Action<Cat> aCat = new Action<Animal>.... So it seems we are reversing the way we use type compability (a Cat is an Animal for sure, but here we seem to say that an Animal is a Cat). If we think that this applies to parameters it makes total sense. We invoke aCat passing a Cat to it. aCat points now to a function that expects an Animal, so if it receives a Cat it will behave nicely.

I'm putting here the equivalent contravariant samples for the ones above

public delegate void ManageAnimalDelegate(Animal an);
public delegate void ManageCatDelegate(Cat cat);
public static void ManageAnimal(Animal an){

Bind a delegate type (expecting a Cat) to a method expecting a less derived type (Animal):

ManageCatDelegate catManager = ManageAnimal;

If we are using generic delegates we can do the same (this is not related to the out keyword introduced in C# 4), here this continues to be delegate binding.

Action<Cat> catManagerAction = ManageAnimal; //this one looks a bit odd cause we are sort of doing Cat = Animal;

And what was added in C# 4

Action<Animal> animalManagerAction = ManageAnimal;
Action<Cat> catManagerAction = animalManagerAction;

Console.WriteLine("animalManagerAction " + ((animalManagerAction is Action<Cat>) ? "IS" : "IS NOT" ) + " Action<Cat>"); //IS
Console.WriteLine("Action<Animal> " + ((typeof(Action<Animal>).IsSubclassOf(typeof(Action<Cat>)))? "IS" : "IS NOT" ) + " Action<Cat>"); //IS NOT!!!

To finish this article, I'll mention that while return type covariance applies to delegates, unfortunately (in C#) it does not apply to overriden methods in a derived class (Java has support for this since a long while). For contravariant arguments, again it applies only to delegates. The feature is not available for methods in hardly any language.
To my surprise, I learn that Eiffel supports Covariance in method arguments