Friday, 17 August 2018

Paris Futur

I love cities and architecture and though I have to admit that I have a rather particular taste, the fact that I consider Paris as the most beautiful place on earth does not deviate so much from standard liking. Anyway, apart from my obvious fascination with historical Paris, I find also an enormous delight in modern Paris. One could think it boils down just to La Defense, but there are quite a few more interesting planned, new, recent or relatively recent, modern developments in Paris. For example I pretty much appreciate the Biblioteque Francois Mitterrand, the modern, mid-rise buildings in the Rive Gauche and Batignoles ZACS (notice also that both ZACs are crowned up with one/two skyscrappers) and of course, the so disliked Tour Montparnasse (it seems like years ago it ranked second in a web poll about the ugliest buildings in the world). I absolutely love how majestic it looks isolated in the middle of classic, Hausmannian Paris, a reference point visible from anywhere in the city. I admit that its dark, "sad" exterior is not its strong point, so finding out that the tour is going to be fully revamped has been pretty nice news (moreover considering that in the last decade several conservative candidates to the mayor's office had proposed to demolish it...). You can read here that Montparnasse will get a vegetalized, transparent facade, and will even grow 18 meters thanks to a greenhouse on its top!

Searching more information about it I've come across an excellent site referencing some of the main new architectural projects in Paris, Paris Futur. I already knew about many of the projects shown there, but it's really nice and convenient to have them listed together in the same place. La Defense continues to thrive, with the construction of 2 new skyscrappers already started (Tour Hekla and Jardins de l'Arche), and other 2 projects almost ready to start (tours Sisters and the new headquarters for Total). On the other side, high rise buildings in Paris intramuros continue to be controversial to say the least, and the opposition of different groups of rednecks continues to hinder the construction of the amazing Tour Triangle. There's one project that is not mentioned in ParisFutur but that has managed to defeat the "Anti-Tour" opposition and is well under construction, Les Tours Duo by Jean Nouvelle. Right in the border with Ivry sur Seine, but still inside the Peripherique!

Monday, 6 August 2018

Task.Run in JavaScript

Web Workers have been for sure a great addition to Javascript, but its usage has always seemed a bit odd to me. So you create an "execution unit" (the spec does not say if it'll be implemented as a threat or a process) from a js file that contains the code for that execution unit, and communicate with it via messages. So these messages should prompt the worker to run some action which result will be returned to you via a message. Comparing it to other environments, one could think of this as if each Web Worker were a ThreadPool of a single thread to which I send actions. This is fine, but I felt as if there was an scenario that was missing.

My first experiences with threads (in C#, like 15 years ago) involved creating a Thread object and passing to it a function object (a delegate). That code would be run by the thread and the thread would finish. This is quite close to how things work at the OS level with the CreateThread Win32 API. Creating Threads on your own this way is no longer recommended in the .Net world, as thread creation is expensive and we should leverage the Thread Pool. Task.Run provides us with a familiar "interface" (we pass it a delegate to be run), leverages the thread pool and furthermore returns a Task, so we can easily chain the next code to run (via ContinueWith or even better with await).

Let's say that I don't care that much about the code running in the ThreadPool or in a new one, what I really like is the "interface" provided by Task.Run: pass the code to run as a function and await for its result. So, could I somehow replicate it in Javascript? A web worker receiving a function to be run and returning a Promise on which I could await. Hopefully yes, we can do it

There are some ingredients that we have to mix to make this possible:

  • We have to create a Promise
  • We have to create a Web Worker and pass it a function via postMessage. The Web Worker should run this function. We can not directly post a function to the worker, so we'll pass it serialized into a string, and then the Web Worker will run it via eval
  • Once the function is finished, the Web Worker has to resolve (or reject) the Promise

The code for the Web Worker itself is pretty simple, in principle we'll put it in a separate "WebWorkerCode.js" file and pass its url to the Worker constructor

//e is an array with 2 elements: the function in string format and an array with the arguments to the function
onmessage = function(e){
    let fnSt = e.data[0];
    let args = e.data[1];
    
    //we need the () trick for eval to return the function
    let fn = eval("(" + fnSt + ")");
    let workerResult = fn(...args);
    console.log('Posting result back to main script: ' + workerResult);
    postMessage(workerResult);

}

Then we have a class (PromiseWorkerHelper) with a run method. The "constructor" creates a worker that waits for us to post it the function to execute. The "run" method creates a Promise, gets hold of the resolve/reject handlers of the Promise and posts the function to the worker. Once the worker finished with running the function will post a message with the result, that will be received by PromiseWorkerHelper that at this point will resolve the promise.

class PromiseWorkerHelper{
    constructor(){
        //one shot object, we create it and invoke its run method just once
        this.alreadyCalled = false;

        //this.worker = new Worker("WebWorkerCode.js");
        this.worker = this._createWorkerFromString();

        //this is executed when the worker posts a message
        this.worker.onmessage = (msg) => this.resolveFunc(msg.data);
        this.worker.onerror = (msg) => this.rejectFunc(msg); 
        this.resolveFunc = undefined;
        this.rejectFunc = undefined;
    }

   

    run(fn, ...args){
        if (this.alreadyCalled){
            throw "already used once";
        }
        this.alreadyCalled = true;

        let pr = new Promise((resolve, reject) => {
            this.resolveFunc = resolve;
            this.rejectFunc = reject;
        });

        this.worker.postMessage([fn.toString(), args]);
        return pr;

    }

   _createWorkerFromString(){
        let workerOnmessageHandler = function(e){
            let fnSt = e.data[0];
            let args = e.data[1];
            
            //we need the () trick for eval to return the function
            let fn = eval("(" + fnSt + ")");
            let workerResult = fn(...args);
            console.log('Posting result back to main script: ' + workerResult);
            postMessage(workerResult);
        
        };

        let str = "onmessage = " + workerOnmessageHandler.toString() + ";";
        let blob = new Blob([str], {type: 'application/javascript'});
        return new Worker(URL.createObjectURL(blob));

    }
}

The "_createWorkerFromString" private method is a nice addition. Rather than having the worker code in a separate file, we can have it here, create a Blob, create a URL for that in memory object and pass it to the Worker constructor. I learned this trick here

We can run it as easily like this:

function longFormatting(txt, formatCharacter){
    console.log("starting longFormatting");
    let res = formatCharacter + txt + formatCharacter;
    start = Date.now();
    while(Date.now() - start < 1000){}
    console.log("finishing longFormatting");
    return res;
}

function main(){
    document.getElementById("launchCalculationBt").addEventListener("click", async () => {
        console.log("Main.js, inside button handler");

        let txt = "hello";
        let formatCharacter = "---";

        let promise = new PromiseWorkerHelper().run(longFormatting, txt, formatCharacter);
        
        let res = await promise;

        console.log("Main.js, result: " + res);

    });
}

window.addEventListener("load", main, false);

I've put the code in a gist, and you can run it from here (check the debug console for the output).

Notice that we are passing to the run method the function and the parameters to that function, while Net Task.Run receives just the function. In .net if our original function expects parameters we have to create a closure to trap those parameters and invoke the original function with them. In JavaScript, as in the end we have to pass the function as a string to the Worker, the closure is not an option.

Wednesday, 1 August 2018

Well Done Denmark

It seems like there's still some hope for those resisting islamisation. Today, August 1st, a law that forbids wearing the burqa or niqab in public spaces has come into force in Denmark. The Scandinavian country joins France, Belgium, Austria, Latvia, Bulgaria... (you can read a listing here) in the fight against intolerance and communitarism.

There are many reasons for banning those disgusting face veils from the public space (security, women's rights, religious neutrality...) but the fundamental reason for me is that the burqa and niquab represent a declaration of war against our Western freedoms and lifestyle. A man forcing a woman to wear the full face veil, or a woman that decides to do so on her own accord, are following a fundamentalist vision of Islam where those who are not Muslims, the infidels, are their enemies, that must be converted, avoided or murdered. Such an interpretation of Islam is not compatible with our Western values, and as such, can not be allowed here. Furthermore, as such a symbol of hatred, they must not just be forbidden from being worn, their sale must be forbidden also. Wearing a burqa or niqab is just the same as sporting a swastika, it must be banned and punished.

For those radical Muslims that consider that not being allowed to hide their faces is discriminatory and "Islamophobic", I have a simple solution, EMIGRATE to a Fundamentalist Muslim country, unfortunately there's a broad list of destinations for your choice... Of course, you can also take with you all those "left-wing feminists" that support you right to wear the full veil, sure they will appreciate the freedom that as infidel women they will enjoy in such countries...

Thursday, 26 July 2018

View Independent Animations

For some simple animations (squares moving through a scenario for example) one could hesitate between drawing these squares to a canvas or using DOM divs. The animation logic should be independent of the Canvas/Divs, which would be just 2 different views. I've adapted the TweenJS sample that I posted some days ago so that now it can either draw on a Canvas or move divs around. The new sample is here. The top animation is using the Canvas, and the one at the bottom is using Divs.

The idea is simple. I keep the animation logic in an AnimationSystem class that holds a list of the items to animate. requestAnimationFrame will ask AnimationSystem to get updated, which means that it will call to the differen AnimationItems to update its position and draw to the screen. I have an AnimationItem base class and a derived TweenJSAnimationItem that contain all the animation logic, they correspond to the "Model-Controller". They delegate the drawing logic to a View object, so we have a Canvas View and a DOM View. As these View objects have a single function, drawing, I've opted for directly using functions for them, rather than classes. As these functions need state (the canvas context or the DIV being animated) I'm wrapping them in closures. Let's see their code:

//callable interface
interface DrawItemFunc{
    (currentPosition:Vector, size:Number, color:string, alpha:number):void
}


class ViewFunctions{
    //Factory function returning a closure that traps the context, height and width
    static SystemCanvasViewFactory(height:number, width:number, ctx:CanvasRenderingContext2D):()=>void{
        return function SystemCanvasView(){
            ctx.clearRect(0,0, width, height);
        };
    }

    static SystemDOMView(){
        //nothing to do here, only at the ItemView level
    }

    //------------------------------------------

    //Factory function returning a closure trapping the canvas context
    static ItemCanvasViewFactory(ctx:CanvasRenderingContext2D):DrawItemFunc{
        return function ItemCanvasView(currentPosition:Vector, size:Number, color:string, alpha:number){
            ctx.beginPath();
            ctx.rect(currentPosition.x, currentPosition.y, size, size);
            ctx.closePath();
            ctx.fillStyle = color;
            ctx.globalAlpha = alpha;
            ctx.fill();
        };
    }

    //Factory function returning a closure trapping the DOM item
    static ItemDOMViewFactory(domDiv):DrawItemFunc{
        return function ItemDOMView(currentPosition:Vector, size:Number, color:string, alpha:number){
            Object.assign(domDiv.style,{
                //position: "absolute",
                //border: "0.1px solid red",
                backgroundColor: color,
                opacity: alpha,
                left: currentPosition.x + "px",
                top: currentPosition.y + "px",
                width: size + "px",
                height: size + "px"
            });
        };
    }
}

Notice that for the transparency, in the Canvas world we talk about context.globalAlpha, while for DOM items we use the style.opacity property.

For the canvas case, before drawing each AnimationItem via the ItemCanvasView closure, I need to clear up the canvas, this is done by the view associated to the AnimationSystem itself. For the DOM case, as we move items rather than redrawing them, there's nothing to do at the AnimationSystem level.

The AnimationItem and TweenJSAnimationItem contain the animation logic and end up invoking the View closures (pointed by the drawingFunc field).

abstract class AnimationItem{
 currentPosition:Vector;
 size:number;
 color:string;
 alpha:number;
    
 moving:boolean;
 drawingFunc:DrawItemFunc;
 resolveCurrentAnimationFunc:any;

 public abstract update():void;
 
 public draw():void{
  this.drawingFunc(this.currentPosition, this.size, this.color, this.alpha); 
 }
 
 public animate():Promise{
  this.moving = true;
        return new Promise((res, rej) => {
            this.resolveCurrentAnimationFunc = res;
        });
    }
}

class TweenJSAnimationItem extends AnimationItem{
    tweenGroup: any;
    movementTween: TWEEN.Tween;
    tweenStep:number;

    constructor(currentPosition:Vector, size:number=5, color:string="red", 
        alpha:number=1, drawingFunc:DrawItemFunc, logger)
        {
        
        super();
        this.drawingFunc = drawingFunc;
        this.currentPosition = currentPosition;
        this.size = size;
        this.color = color;
        this.alpha = alpha;
        this.moving = false;
        this.tweenStep = 0;
        this.logger = logger;
    }

    public animateDiagonal(endPosition:Vector):Promise{
        this.tweenStep = 0;
        this.tweenGroup = new TWEEN.Group();
        this.movementTween = new TWEEN.Tween(this.currentPosition, this.tweenGroup) // Create a new tween that modifies 'coords'.
            .to({ x: endPosition.x, y: endPosition.y }, 40) // Move to (300, 200) in 1 second.
            .easing(TWEEN.Easing.Quadratic.Out)
            .onComplete(() => {
                console.log("movementTween completed");
                this.moving = false;
                //cleaning up
                this.tweenGroup = null;
                this.movementTween = null;
                //I think this is not necessary, the engine itself takes care of it once the Tween is finished
                //TWEEN.remove(this.movementTween);
                this.resolveCurrentAnimationFunc();
            });
        
        let growTween = new TWEEN.Tween(this, this.tweenGroup) // Create a new tween that modifies 'coords'.
            .to({ size: this.size * 3, alpha: 0.4}, 20)
            //.easing(TWEEN.Easing.Quadratic.Out)
            .onComplete(() => console.log("growTween completed, " + this.size)); 

        let shrinkTween = new TWEEN.Tween(this, this.tweenGroup) // Create a new tween that modifies 'coords'.
            .to({ size: this.size, alpha: 1}, 20)
            //.easing(TWEEN.Easing.Quadratic.Out)
            .onComplete(() => console.log("shrinkTween completed, " + this.size)); 

        growTween.chain(shrinkTween);

        this.movementTween.start(0); // Start the tween immediately.
        growTween.start(0)
        
        return this.animate();
    }

    public animateFall(endY:number):Promise{
        this.tweenStep = 0;
        this.tweenGroup = new TWEEN.Group();
        this.movementTween = new TWEEN.Tween(this.currentPosition, this.tweenGroup) // Create a new tween that modifies 'coords'.
            .to({ x: this.currentPosition.x, y: endY }, 40) // Move to (300, 200) in 1 second.
            .easing(TWEEN.Easing.Quadratic.Out)
            .onComplete(() => {
                console.log("movementTween completed");
                this.moving = false;
                this.resolveCurrentAnimationFunc();
            });
        
        

        this.movementTween.start(0); // Start the tween immediately.

        return this.animate();
    }

    public update():void{
        if(!this.moving){
            return;
        }

        this.tweenGroup.update(this.tweenStep++);
    }

    //implemente in the base class
 // public draw():void{
    // }

   
}

Notice also that for drawing on the canvas we'll invoke ItemCanvasViewFactory just once, as the same instance of the view closure (trapping the canvas context) will be used by all the AnimationItem's. On the contrary, for the divs animation, each AnimationItem will use a different view closure that traps a different div, so we'll invoke ItemDOMViewFactory once for each AnimationItem in the system.

Sunday, 22 July 2018

Energy Dependence

Even the most stupid person in the world can on occasion say something that is correct. That's what happened last week when the Trump shitbrain said that it was ridiculous that Germany was increasing even more its dependence on Russian Gas. For sure that's a very correct statement, though one could wonder why a Putin lover and Europe hater like the Trump asshole would care about such undesirable dependence. For the biggest enemy of Europe (along with Russia and the Islamists) the weaker Europe is the better... Well, Trump is just a psychopathic megalomaniac piece of shit that can say one thing and its contrary with just the seconds difference needed to tweet his brain farts...

This increased German dependence (that unfortunately applies to other Western European countries) on Russian gas is related to the construction of the Nord Stream 2 gas pipeline that will go under the Baltic Sea directly from Russia to Germany. There's already a Nord Stream gas pipeline doing the same, so this will further increase the already worrying European reliance on Russian gas. Depending on Russia is as castastrophic as depending on Islamist countries, indeed, it's even worse. Golf countries are invading Europe by educating and funding Islamists that live or will live here, but this is a relatively slow invasion that we still could easily fight if we had the bollocks to do it (massive deportation of binational Islamists, for life incarceration for the others, and capital punishment for those with links to terrorism). On the other side, if Russia decides to military invade the Baltic or Nordic countries, fighting back would be quite more complicated. Russia is our enemy both in a geopolitical sense and in a cultural sense (while Western Europe is supposed to represent freedom, equality and opennes, Russia stands for ultra-nationalism, conservadurism, racism, homophobia...) and being fully aware of this is essential for the survival of Europe as we know it.

This article gives a pretty good insight of how dangerous this new pipeline is:

If it is built, the EU would become extremely dependent on a single gas supplier - Gazprom, an entity under the full control of Russian leader Vladimir Putin.

Europe already imports 39 percent of its gas from Russia. After NS2, 80 percent of Russian gas imports would be concentrated in one route. In Germany itself, the share of Russian gas would increase from 40 percent to 60 percent.

Beyond Germany, 12 EU member states depend on Russia for 75 percent or more of their gas. After NS2, the level of their dependence would also go up.

Natural gas is supposed to be a bit cleaner than other fossil fuels, but does its slightly smaller environmental effect justify to keep us as slaves of Fascist or Islamo-Fascist states like Russia or Qatar???
The answer is a big NO for me, so:

For sure Europe needs to continue to invest on renovable energies (which clearly involves the somehow despised and forgotten HydroElectric power) but until the illusory day when they can fullfill all our needs, we'll have to continue to burn Polish cheap coal and leverage nuclear power.

By the way, you can watch this documentary about the damned new pipeline

Wednesday, 18 July 2018

Equipe de France

If 20 years ago someone had told me how obsessed with race our world would be in 2018 I would have rejected to believe it, but sadly, part of this world is as obsessed with race and ancestry now as it was in the worst times of history. One could think that it's just the fault of the White far-right (Russia, Eastern Europe, Trump, and their satellites in Western Europe), but "Blacks", "Latinos" and the far-left have contributed to this mess in equal doses.

The kind of comments that have been stir up by the victory of the French football team in the World Cup are sickening. It's not just the Far-Right who considers the French team an "African team", but also African and Afro-American "personalities", or the Nicolas Maduro idiot. So some of the African people that complain about racism are as obsessed with race and ancestry as any of the very white "official racists". So for these people a Human being is not free to decide to what society he wants to belong, it's just his skin color or the birth place of his ancestors who determines that, that's all, the individual has no rights, it's only the "race", who has rights... This is revolting.

For the most part I don't give a shit about football, and I have little idea of the feelings of identity of the players of African descent in the French team. Maybe some of them love France with all their heart, maybe others are anarchists and don't care about nations, and yes, unfortunately it could happen that some of them is an "anticolonial racaille" that identifies himself with the country of his ancestors (from which they fled due to poverty) rather than with the country that has provided him with food and education... I honestly don't know, and hence I apply my general rule, if you are born and/or have lived most of your life in one country, and you give no signs of disrespecting that country, you are a citizen of that country, regardless of your physical traits or those of your ancestors. That's quite simple.

Additionally, these "African nationalists" that want to appropriate the victory of the French team based on race and ancestry are missing a huge point. Would these guys have become good players if they had lived in Africa, rather than in France, with the Western welfare state and being trained by French (of whatever color) trainers?

Hopefully, all this crap has brought up some excellent reactions. Benjamin Mendy, from the French football team, came across a stupid tweet from some sport magazine that associated to different players the flag of their alleged "country of origin", he fixed it by assigning the French flag to all of them.


The (born and raised) French Basketball player (born to a Cameroonian father) Nicolas Batum went even further (sorry for my bad translation).

Sorry for my language, but those that say "Bravo Africa for your victory", go fuck yourself!. I proudly wear the blue t-shirt with "France" written on it, I've won several trophies and medals with the French team since I was 15, I sing La Marseillaise, when I am in the USA I cry high and strong that I am French. Then, yes, I have a Cameroonian father and a Cameroonian name, but we all have fought and played for France because we have been born here, we have grown here, we have learnt our sport here, we are proud of having the French nationality. We have won for France, for the French youth that looks at us and aspire to do the same and bear high the French colors. Let's be proud of that. Vive la république et vive la France!

When one sees this growing and deviated obsession with race, the move from the French National Assembly to remove the word race from the French constitution seems particularly appropriate.

Sunday, 15 July 2018

TweenJS and Canvas Basic Sample

I've been playing around a bit more with animations on the HTML5 Canvas. While in this previous sample I was doing the basic movement logic myself, for this new experiment I wanted to use some library that would allow me to use easing equations. After some basic investigation I've opted for tweenJS. I'm not animating DOM elements, but shapes that I draw on the canvas, so I needed a library that would accept any object and update its values on request based on the selected movement/evolution logic, and then I would take care of drawing it. TweenJS fits perfectly into this mindset.

As in the previous sample, I'm leveraging the power of async/await to make it simple to launch my animations in sequence. There is not much to explain, just launch your debugger to see the typescript code.

while (true){
        for (let y=0; y<itemsMatrix.length; y++){
            for (let x=0; x<itemsMatrix[y].length; x++){
                let item:TweenJSSquare = itemsMatrix[y][x];
                await item.animateDiagonal(new Vector(canvas.width - ((x + 1) * size), size * y )); //endPosition:Vector,);
            }
        }

        for (let y=0; y<itemsMatrix.length; y++){
            for (let x=0; x<itemsMatrix[y].length; x++){
                let item:TweenJSSquare = itemsMatrix[y][x];
                await item.animateFall(canvas.height - (size * (y + 1)));
            }
        }

        for (let y=0; y<itemsMatrix.length; y++){
            for (let x=0; x<itemsMatrix[y].length; x++){
                let item:TweenJSSquare = itemsMatrix[y][x];
                await item.animateDiagonal(new Vector((x * size), size * y )); //endPosition:Vector,);
            }
        }
    
        for (let y=0; y<itemsMatrix.length; y++){
            for (let x=0; x<itemsMatrix[y].length; x++){
                let item:TweenJSSquare = itemsMatrix[y][x];
                await item.animateFall(canvas.height - (size * (y + 1)));
            }
        }
    }