Saturday, 19 December 2015

YellowKorner

I think YellowKorner is an absolutely amazing place for anyone that is into photography, or just into beauty. I first came across one store of this publisher of Artistic Photography here in Toulouse and I was just delighted by the exquisite pieces of photography that I found there. In a city that sports a pretty good offer of Museums and galleries, YellowKorner ranks at the highest position in my podium of cultural references.

Talking about the art centres of "ma ville", Toulouse features one of the oldest public places in the world dedicated to photography, Le château d’eau. They usually have on display 2 different exhibitions for around 2 months. So far I've been in some of these exhibitions and they were OK, but not particularly interesting. However, this spring I attended to a really good one taking place in the cute, imposing (the exterior is rather reminiscent of Albi's Sainte Cécile) and just revamped Couvent des Jacobins. It was a selection of works in the château d’eau collection, intendend to celebrate its 40th anniversary, and some of the pieces were really remarkable.

Over time, I've come across YellowKorner branches in many other French cities: Paris, Montpellier, Aix en Provence... and today checking their web site I've found that they have shops in many other countres, even in Asia. I really recommend you to take a look at their list of locations, so that next time you visit a city hosting one, you don't miss to pay a visit. The works on sale change enough to make it well worth to pay a visit to a YellowKorner establishment at least once every 2 months.

Thursday, 10 December 2015

ES6 Constructors

I've previously said here that I'm not particularly excited about the addition of classes to ES6, though well, as they are mainly syntactic sugar all the magic of Prototype based programming (or OLOO, Objects Linked to Other Objects) remains. Anyway, regardless of our predisposition to it, as they will become mainstream we'll have to end up using them, so I thought it was good to get used to them.

One feature in "classic JavaScript" that I pretty like is that we can decide in our "constructor functions" (those that we designed to be invoked with new) to return a different object, rather than the one that has been passed to it as "this". The main use that I see for it is for having a pool of objects, or an "implicit/transparent" singleton (that is indeed a particular case of an Object Pool). With this in mind I was wondering if ES6 class constructors would allow that. Hopefully yes. It's well explained in this post by Dr Rauschmayer. He calls it "Overriding the result of a constructor". I had not thought that the [Prototype] of a "class" points to the Parent "class", but it makes pretty sense in order to inherit static methods. This diagram shows the whole picture of how objects the class inheritance sugar is translated into the prototypal world.

The whole article is pretty interesting. Reading it I found out that classes are not just compile time sugar, but that their inclusion has indeed modified the way the runtime works, as the creation of the object passed as this to a (constructor) function is done differently:

The instance object is created in different locations in ES6 and ES5:

In ES6, it is created in the base constructor, the last in a chain of constructor calls.
In ES5, it is created in the operand of new, the first in a chain of constructor calls.

ES6 involves many more runtime changes, like the new Internal properties featured by functions: [[ConstructorKind]], [[Construct]] and [[HomeObject]], and as the conclusion of the article states, one main point is that now we have different kinds of functions:

  • On one side we have Constructible functions, that I understand are those that can be called with new (as they have [[Construct]]), these are our "normal" functions and the ones created by a constructor definition.
  • Then we have Arrow functions, which have 2 main features: not being constructable, and capturing the lexical this (so for the latter it's as if you had called Function.bind)
  • And then functions created by method definitions, that are not constructable, use dynamic this and can use super.

Classes in ES6 follow a similar approach to other languages regarding missing constructors. If you don't provide a explicit constructor in your class definition, the compiler will add one. This one for a base class: constructor() {}, and this one for a derived class: constructor(...args) {super(...args);} .

As a JavaScript function can receive a different number of parameters, the idea of function overloading that we have in static languages does not exist, and hence a class can have only one constructor function. As a consequence we don't have the minor "problem" that can happen in static languages if a base class misses a parameterless constructor. It's described here

The article mentions something that is missing in ES6 classes and that even deserved an entry on its own, calling a constructor without new. The importance given to something like this really puzzles me. I've never understood the "effort" taken by some libraries (for example underscore.js) in pre ES6 times to allow you to call a fuction that is going to be used to create objects (what in pre-ES6 times we used to call a "constructor function") both with and without new. I'm referring to code like this:

function Person() {
    if (!(this instanceof Person)) return new Person();
    //normal initialization code here 
    //this.property = val;
  };

The idea that this is in case someone forgets to use new seems senseless to me. You have to know the rules... is as if you try to call a method with "->" rather than with "."... Reading the comments Rauschmayer explains that the use case is this :

The use case is if you want to remain flexible w.r.t. implementing something via a class or via a factory function. For my own code, I wouldn’t mind this kind of minor refactoring. For libraries, this becomes more important.

I assume he refers to having a function that receives as parameter another function that will be used to create one object. Your code does not know if that function is a simple one or a "constructor" one, it will just invoke it without new. The designer of that function wants to allow 2 use cases: the one I have just described, where the caller does not really know what function this is, and the normal one where the caller calls this function with new.

function Person() {
    if (!(this instanceof Person)) return new Person();
    //normal initialization code here 
    //this.property = val;
  };

function test(objectCreatorFunc){
   var o1 = objectCreatorFunc();
}

//normal use:
new Person();

//pass it as a factory to the test method
test(Person);

Well, the idea seems useful, but not having it in the language is pretty simple to circunvent, just do the extra step of creating the factory:

class Person() {
    constructor(){
     //this.property = val;
 }
  };

function test(objectCreatorFunc){
   var o1 = objectCreatorFunc();
}

test(function(){
 return new Person();
});

Searching a bit about other people thoughts on this topic I've found articles like this. The guy is really against the use of "new", saying:

The `new` keyword violates both the substitution principle and the open / closed principle. It’s also destructive because it adds zero value to the language, and it couples all callers to the details of object instantiation.

If you start with a class that requires `new` (all classes in ES6) and you later decide you need to use a factory instead of a class, you can’t make the change without refactoring all callers. Take a look at this example gist.

At first thought the idea of discouraging "new" and just using factories can sound odd, but on second thought it makes sense, cause as he says it causes huge coupling. But giving it another thought, we've already heard about avoiding "new" and using Dependency Injection for that. So yes, the idea of being able to call a function (contructor/factory) with or without new is meaningless, what you need is to inject those objects. Indeed, linking this to the feature that I mentioned at the start that in principle I liked (returning a different object from a contructor), it should not be a class itself that decides that it uses a pool of instances of itself, that's something should be managed externally, by the IoC.

Reading that whole post has been a pretty good thought exercise. He mentions that "super" should be deprecated, as it causes heavy coupling. Well, sure, because as he mentions earlier in the article, "extends", that is, inheritance, causes heavy coupling and should be avoided. Well, this is nothing new, it's just the "favor composition over inheritance" principle. In that sense, reading this answer in StackOverflow about why inheritance is heavily coupled has been a more that welcome reminder of why we should do so.

http://js-bits.blogspot.fr/2010/08/constructors-without-using-new.html ------------- https://medium.com/javascript-scene/the-two-pillars-of-javascript-ee6f3281e7f3#.g3ynqbd4j http://martinfowler.com/bliki/CallSuper.html Dependency Injection

Sunday, 6 December 2015

Hotel Descas

Already in my first incursion to Bordeaux 2 years ago I came across with one impressive building that was not mentioned in the guides that I had been reading, the Hotel Descas or Chateaus Descas. I've had pending a short post about it ever since, so given that today I've passed by it, marvelled again, and taken some fresh pics, it's about time to cross it off my ToDo list.

It's one more sample of that astonishing kind of French building that almost obsesses me, like the Hotels de Ville of Paris and Lyon, the Louvre... but you'll find them everywhere in France. The feature that I appreciate the most are those incredible slate roofs so huge and complex. For sure Chateau Descas is a great example of that kind of roofs, and it also boasts beautiful sculptures and mascarons on its facade. This kind of buildings exist since the French Renaissance, but the so intricate roofs are probably a more baroque element. The facade itself I assume fits into the Beaux Arts style. I'm a pretty ignorant person regarding architecture (I just like it), so probably what I'm saying is rather wrong.

I just leave you with some poor pictures to whet your appetite.

Imposing:

Facade details:

The roofs:

In English:

En français:

Wednesday, 18 November 2015

ES6 proxies part II

I already wrote about ES6 proxies in the past.. Reading this post by Dr Rauschmayer I've realised of an interesting and subtle difference depending on how we create our proxy for method interception.

In "classic" languages (C#, Java...) there are 2 strategies used by the different Proxy creation libraries. One is to use composition (the proxy class will reference the target class), and the other one is to use inheritance (the proxy class inherits from the target class). Based on the "favor composition over inheritance" principle most libraries tend to use composition. There's an interesting difference in the results of both approaches.

When using composition, if the initial method calls into another method in the object, this second call will not go through the proxy. It's normal, the proxy intercepts the first call, does its stuff, and then invokes the method through the target object. Once you are in the invokation done through the target object, the proxy has no way to intercept any ensuing code.
On the other side, when using inheritance, any secondary call goes also through the Proxy, cause indeed there is not this separation between target and proxy, your proxy is the target.

ES6 proxies are based on composition, as you have a target object and you create a proxy that points to it and intercepts actions on it. The big difference is how methods are called. A method in javascript is a property of the object, and calling a method entails 2 steps: getting it, and then invoking it. As explained in the article, ES6 proxies give you 2 traps for method calls, the get trap and the apply trap. When you use the get trap you return a function that will be later on invoked. In this returned function you put the "decorating" code, and the call to the original method. Here comes the cool part, in this function you have both the target object and the proxy (and the name of the property being intercepted), so you can invoke the property (method) either via the target (so it would be like in the composition case, no more interception happens):

//other method calls done from the first intercepted method are NOT intercepted
var entryCallProxied = new Proxy(cat, {
 //target is the object being proxied, receiver is the proxy
 get: function(target, propKey, receiver){
  //I only want to intercept method calls, not property access
  var propValue = target[propKey];
  if (typeof propValue != "function"){
   return propValue;
  }
  else{
   return function(){
    console.log("intercepting call to " + propKey + " in cat " + target.name);
    //target is the object being proxied
    return propValue.apply(target, arguments);
   }
  }
 }
});

or via the proxy itself (either using "this" or "receiver" as both point to the proxy). In this case the interception continues for other method calls performed from this returned function

//other method calls done from the first intercepted method are ALSO intercepted
var allCallsProxied = new Proxy(cat, {
 get: function(target, propKey, receiver){
  //I only want to intercept method calls, not property access
  var propValue = target[propKey];
  if (typeof propValue != "function"){
   return propValue;
  }
  else{
   return function(){
    console.log("intercepting call to " + propKey + " in cat " + target.name);
    //"this" points to the proxy, is like using the "receiver" that the proxy has captured
    return propValue.apply(this, arguments);
   }
  }
 }
});

Given the cat object below, you can see the difference between using one or another type of proxy. In the first case the call from method1 to method2 is not intercepted, while in the second case it is:

var cat = {
 name: "Kitty",
 method1: function(msg){
  console.log("cat: " + this.name + ", method1 invoked with msg: " + msg);
  this.method2(msg);
 },
 
 method2: function(msg){
  console.log("cat: " + this.name + ", method2 invoked with msg: " + msg);
 }
};

entryCallProxied.method1("Francois");

//Output:
// ------------------------------
// intercepting call to method1 in cat Kitty
// cat: Kitty, method1 invoked with msg: Francois
// cat: Kitty, method2 invoked with msg: Francois
// ------------------------------

allCallsProxied.method1("Francois");

//Output:
------------------------------
// intercepting call to method1 in cat Kitty
// cat: Kitty, method1 invoked with msg: Francois
// intercepting call to method2 in cat Kitty
// cat: Kitty, method2 invoked with msg: Francois

At the time of this writing you can run the above code in Firefox. Oddly enought, it does not work in node.js, even if we pass the --harmony_proxies flag. You can get the whole code here.

Saturday, 14 November 2015

Je Suis Humain

Je suis Charlie. Je suis Humain. Je suis choqué. Je suis tellement en colère. J'ai mal à la tête et à l'ame. Je me sens plein de haine, de tristesse... Je ne sai pas quoi dire, mais je vais essayer de l'écrire ici.

I am Charlie. I am a Human Being. I'm shocked. I'm so angry. My head and my soul hurt. I'm filled with hate and sadness. I don't know what to say, but I'll try to write it down here.

Last night I was going to bed after doing some hobbyist programming when I read the shocking news, the terror attacks in Paris. I was so shocked, angry and in pain. It took me time to fall asleep. This morning I ran to my laptop to read the news as soon as I woke up, but indeed I don't know why. I mean, I know enough. Some monsters blinded by a sickening perversion of the Muslim faith decided to kill as many innocents as they could. That's all what matters. In the next days we'll read about how they got radicalised, if they came from a Muslim family or they had converted. If their ancestors had been born here or there, or maybe these beasts had just crossed the border. We'll probably read that some of them had grown up in a quartier sensible, and in such case maybe some idiot will tell us how the French society had marginalized them... Maybe some other idiot (considering himself a leftist) will say that fundamentalist Islam exists because of capitalism an inequality. Bullshit, I don't care (and I don't buy it). Radical Islam exists mainly because Saudi Arabia, Qatar and Kuwait want it to exist, that's why they fund it with millions of petrodollars.

Right now all what matters to me is that they are bloodthirsty beasts that hate anyone that does not fit into their perverted vision of the world. They hate me, they hate you, they hate us, they are our sworn enemies and as such they must be treated. Today, more than ever, we are at war, a very difficult war, but in the moral sense it's a really simple one. Usually there are millions of geopolitical factors to account for when thinking about this kind of conflicts (how a past of colonisation, exploitation or previous wars project into the present...) but this case is pretty simple. This is just a war of Good vs Evil, Humanity vs Horror. It's like the war against fascist regimes in the last century, they are just scum that must be destroyed, for good and forever.

I've been seriously touched by these events. Previous terror attacks in New York, Madrid or London seemed very far to me (even when Madrid is geographically slightly closer to Xixon than Paris is to Toulouse). I don't have an emotional connection with those cities (well, I have it now with London, but in 2005 I had been there just once), but I have a strong connection with Paris. In part it's because I've been there quite a few times (and I think in all those occasions I've been around the area where the slaughter has been perpetrated). In part it's because it's the most beautiful city in the world. And in part it is because as it happens with other big French urban areas (Toulouse is a great example), it represents for me the biggest example of how people of different cultures, "races", ethnicities and religions can live together and share a present and a future (yes, for sure it's not perfect and there are problems, but the overall result so far is beautiful and inspiring). So an attack like this is not an attack to a city or a country, it's an attack to the whole of humanity and our shared existence.

Of course the French government has hurried up to state that serious measures will be taken, but which measures? Which real measures were taken after the Charlie Hebdo tragedy? Ah, yes, they put some troops on the streets, watching large train and Metro stations, synagogues... it's quite visible, but it's nothing. I'm not aware of the state watching seriously what is said in mosques and deporting radical clerics. I'm not aware of massive operations against salafist scum, I'm not aware of new policies of assimilation being put in place and replacing the dreadful "communitarism". When is this kind of measures going to be carried out???

The biggst measure that the French government seems to have launched is taking part in the air strikes against Daesh in Syria. Of course I support these actions, but it's not enough and furthermore it's pretty hypocritical. Basically the French government is trying to kill yihadist of French origin that are "fighting" (i.e.raping and enslaving women, torturing and murdering civilians...) in Syria. That's good, for sure, but why the same policy is not applied when they return to France? Yes, sure, this is the Politically Incorrect part of this post. I'm saying that when yihadist return to France they should be executed. They return here after having committed crimes against Humanity (I don't care how many women they have raped or how many people they have killed, if they went there it's because they wanted to do that), and come back with the intent of committing crimes and doing proselytism here. Honestly, and I'm not overdoing, this is right what I think, I'd like them to be shot on the spot as soon as they set foot in Europe. No detention, no trial, just shoot them dead on the spot as they get off the plane. You can call it revenge and brutality, I call it justice.

Thursday, 12 November 2015

Typed Serialization in Perl

After writing this post about deserialization of a type known at runtime, I remembered how out of the box it is achieving the same in perl.

If you've ever written some perl code you'll probably know about Data::Dumper and eval. So well, basically that's all you need for serializing an object and then deserializing it back without having to pass the type as parameter or anything of the sorts. Let's see.

When Dumper serializes a type, it will write the data in the object (your blessed reference or whatever) to a "perl code string", and furthermore, it will wrap it in a call to bless, passing it the type of the object!. I mean:

$VAR1 = bless( {
                 'places' => {
                               'Asturies' => 'Uvieu',
                               'France' => 'Toulouse',
                               'Germany' => 'Berlin'
                             },
                 'name' => 'Francois',
                 'lastName' => undef,
                 'city' => bless( {
                                    'name' => 'Paris'
                                  }, 'City' )
               }, 'Person' );

So we have there perfectly valid code to create a perl object of the right type with the right data. Obviously to dinamically run a string of perl code in our script all we need is calling the almighty eval. Well, just one minor quirk. We have to get rid of the $VAR1 = assignment. Oddly enough perl does not have replace function out of the box to do something like replace(mySerializedObject, '$VAR1 = ', ''), so you either use a regex, or substr

I've put the few lines of code needed for this serialization/deserialization into a class, in case one day I need to change the serialization strategy.

package TypedSerializer;

use strict;
#Data::Dumper::Dump stringifies the content of the object and wraps it in a call to bless with the corresponding type, 
#the main problem is that it adds this assignment " $VAR1 = bless(" ,
#if we pass this string directly to eval, it will fail because of that "$VAR1 = ", so we just need to remove "$VAR1 = " from the string
#so we either use Terse to directly prevent it from going to the string, or we just remove it with substr or a regex

use Data::Dumper;

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

sub Serialize{
 my ($self, $item) = @_;
 my $str = Dumper($item);
 return substr($str, length('$VAR1 = '));
}

#bear in mind that when the object is deserialized, the "constructor", New, is not called
sub Deserialize{
 my ($self, $str) = @_;
 return eval $str;
}
1;

I've put it up in a gist along with some testing code here

Sunday, 8 November 2015

Top vs Rownum

I guess talking about Sql queries these days, when Non Relational DBs are all the rage, is quite "uncool", but anyway...

For someone that has mainly worked with SqlServer, that fact that Oracle misses the TOP clause is quite shocking. You have to resort to using the ROWNUM pseudocolumn.

So a query like this:

SELECT TOP 10 * FROM cities

has to be written like this for Oracle:

SELECT * FROM cities WHERE ROWNUM <= 10;

It's odd, as I would say almost any other RDBMS out there implements TOP, but well, it's not a big deal. However, there is a huge difference when combined with ORDER By. If you rewrite this query:

SELECT TOP 10 * FROM cities ORDER BY population

like this:

SELECT * FROM cities WHERE ROWNUM <= 10 ORDER By population

You'll have a problem. In the first query the TOP clause to limit the number of results is executed after the ORDER BY, but in the second query, the WHERE ROWNUM condition is executed before the ORDER BY. This means that you will get whatever first 10 rows you have in your table, and then you'll order only those restricted rows, so obviously that is not what we want.

Hopefully the solution is pretty simple. In order to execute first the ORDER BY and then the filtering, you can use a composed query like this:

SELECT * FROM (
SELECT * FROM cities ORDER By population
)
WHERE ROWNUM <= 10

I came to this simple solution on my own, and doing some search to see if there is another better option, it seems like it's the common solution.