Friday 29 September 2017

Expirable Promises

I'd read some samples of using Promise.race to implement timeouts for Promises (reject the promise if it has not finished after x time). You can see an example here. Looks good, but it's not what had come to my mind when thinking about this issue and not having had the race function into account.

Given that I can not reject and existing promise, I would have to create a new one, that would be rejected if the timeout expires, or resolved if the original promise finishes before the timeout. I call this new promise an "expirable promise". Let's see the code

function createExpirablePromise(pr, expirationTime){
		let nP = new Promise((resolve, reject) => {
			let timeout = setTimeout(() => {
				reject("timed out");
			}, expirationTime);
			pr.then((result) => {
				clearTimeout(timeout);
				resolve(result);
			});
		});
		return nP;
}

If we are given a function that returns a promise we can create a function that returns an expirable promise like this:

//fn is a function that returns a promise
//we return a function that retuns an "expirable promise"
function createExpirableFunction(fn, expirationTime){
	let expirableFn = (val) => {
		let pr = fn(val);
		return createExpirablePromise(pr, expirationTime);
	}
	return expirableFn;
}

With the joyful addition of async/await to the javascript arsenal, we can write a cute sample like this:

//example of a long running async operation
//function that returns a Promise
function formatter1Promisified(st){
	return new Promise((res, rej) => {
		console.log("formatter1 running");
		st = st.toUpperCase();
		setTimeout(() => {
			res(st);
		}, 3000);
	});
}


async function testUsingAsync(){
	let expirationTimes = [1000, 4000];
	for (let i=0; i < expirationTimes.length; i++){
		let timeout = expirationTimes[i];
		try{
			let res = await (createExpirableFunction(formatter1Promisified, timeout))("Hi"); //timeout expires("Hi"); 
			console.log(`succeeded with timeout: ${timeout}, result ${res}`);
			break;
		}
		catch (ex){
			console.log(`failed with timeout: ${timeout}`);
		}
	}
}



testUsingAsync();

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):


asyncFunc1()
.then(function (value1) {
    asyncFunc2()
    .then(function (value2) {
        ···
    });
})


The flat version looks like this:


asyncFunc1()
.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

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.