Sunday, 3 April 2022

The Hamidian Massacres

I have a profound affection for the Armenian people. It comes down to a long time ago when I first knew about the Armenian Genocide of the early XX century. Over the years this feeling has not done but to increase. Since the day I admitted that regardless of not being a believer and still considering that there are some dubious elements in Christianity, I belong to a civilization deeply shaped by Christianity, a civilization I'm proud of, the story of resistence and survival of this people feels deeply inspiring to me. A Christian nation (the first one) partially surrounded by the eternal enemy of the Western world, Turkey (Azerbijan is populated by the same Turkish people and hence it's just the same enemy).

When many Armenians had to flee their land to avoid being completely annihilated by the Turks in 1917, many of them arrived to Marseille and settled in France. Since them, they have been an important contributor to France. They embraced the French culture and assimilated into the French nation, a nation defined by culture, values and the acceptance of being the continuation of the history that defined all that, not by genes or phenotypes. It's the same that most Polish, Portuguese, Italians, Spaniards, East Asians... and some Africans have done. At the same time, they have kept the links with the land of their ancestors and the pride of descending from a people of survivors.

In spite of the important contributions of the Armenian diaspora in countries like the USA and France, being a small country means being left apart in the Geopolitical game. That's why when Turkey-Azerbaijan invaded Armenian territory in october 2020, slaughtering the population helped by their ISIS mercenaries, nobody seemed to care. Moreover, we all know that when Muslims kill Christians (or atheists, or yazidis, or whatever), reacting to that is a clear sign (and sin) of Islamophobia... Also, when Turkish ultra-nationalists living in France attack French people of Armenian descent, that's not a big deal either... after all that's part of their culture and we have to respect it, right?

With the above and with the fact that many countries (among them Spain and UK!!!!) have not recognized yet the Armenian Genocide, it's not strange that previous massacres perpetrated by the Turks against the Armenians are hardly known. Indeed, I have to admit that I did not know about it until recently, when I watched this excellent video in Le Figaro (it tries to explain why the Turkish-Azeri invasion of Armenia did not prompt the same reactions as the Russian invasion of Ukraine).

So already at the end of the XIX century, the Turks, guided by ultra-nationalism and Islamism (as usual) decided to massacre quite a few thousands (between 100.000 and 300.000) Armenians during the Hamidian Massacres. As they would do 20 years later, they turned their hatred into pure anti-Christian violence, killing an additional 25.000 Assyrians (seems this time the Greeks were excluded, the Turkish would wait 2 decades to show their feelings of "respect, love and peace" to them, during the Greek Genocide). I have not much to say about this unknown massacres, just read the wikipedia article and remember it each time the neo-sultan Erdogan threatens us with his desire to join the European Union (to further destroy us from inside).

Saturday, 26 March 2022

Self-Referencing function in JavaScript

Long time ago it was possible for a function in JavaScript to reference itself by means of arguments.callee. As you can read here, this is not allowed in strict mode and should be avoided in general. You can read in that same url the explanation of why arguments.callee is no longer considered necessary. OK, I agree for the most part, but I still think that there are situations where a function should be able to reference itself in some way.

The obvious case is when you want to print in your logs the function name without hardcoding that function name (either the string or the "function.name" access). Also, in recursive functions it can be useful to call the function using a self-reference rather than the function name. Let's see an example


function recursivePrint(txt, times){
    if (times > 0){
        console.log(`v1: ${txt}`);
        recursivePrint(txt, --times);
    }
    else{
        console.log("------------");
    }
}

recursivePrint("Francoisi", 3);


p1 = recursivePrint;
p1("Francois", 3);
// v1: Francois
// v1: Francois
// v1: Francois
// ------------



//modify recursivePrint to print v2
recursivePrint = function (txt, times) {
    if (times > 0){
        console.log(`v2: ${txt}`);
        recursivePrint(txt, --times);
    }
    else{
        console.log("------------");
    }

};

p1("Francois", 3);
// v1: Francois
// v2: Francois
// v2: Francois
// ------------


In the above example p1 references to recursivePrint. Then we redefine recursivePrint. p1 continues to point to the initial recursivePrint, but in the recursion, as we are calling the function through the global reference, the ensuing calls use the redefined function. So we have a mix of v1 and v2.

Another use for self-referencing functions is if we want to attach data to the function as properties in the function, and use them from inside the function. It's similar to having a closure, in both cases we have a function with state, the main difference is that in a closure accessing to that state from outside is not possible (unless you use some odd technique like the one that that I describe here). So, I'm talking about this:


function formatter(txt){
    console.log(`v1: ${formatter.pre}txt${formatter.post}`);
}
formatter.pre = "[";
formatter.post = "]";

f = formatter;
f("hi");
//v1: [txt]
formatter = (txt) => {
    console.log(`v2: ${formatter.char}txt${formatter.char}`);
}
formatter.char = "|"

//It's a mess here, we continue to point to the original function, but it tries to get the state from the new function
f("hi");
//v1: undefinedtxtundefined

A solution for me would be having a variable inside the function that points to the function itself. We could use the name self for that variable. We can use closures for that, something like this:


function createSelfReferencingFormatterFunction(){
    let self = function formatter(txt){
        console.log(`my name is: ${self.name}`);
        console.log(`${self.pre}txt${self.post}`);
    };
    return self;
}

let formatter = createSelfReferencingFormatterFunction();
formatter.pre = "[";
formatter.post = "]";
formatter("hi");

// my name is: formatter
// [txt]

That looks pretty nice to me, but having to define a factory function for each function that we want to do self-referencing is not nice. How could we generalize it to have a generic function that receives a function and returns a self-referencing funtion?

I've come up with a solution that leverages the unfamous eval function. You can check this post from some years ago where I explain how eval has access to the scope of the function where it's invoked, in such a way that if we define a new function in the string passed to eval, that new function adds that scope to its scope chain.




function createSelfReferencingFunction(fn){
    //we have to use var, not let
    code = "var self = " + fn.toString() + ";"
    eval(code);
    return self;
}

function formatter2(txt){
    console.log(`my name is: ${self.name}`);
    console.log(`${self.pre}txt${self.post}`);
}

f1 = createSelfReferencingFunction(formatter2);
f1.pre = "[";
f1.post = "]";
f1("hi");

// my name is: formatter2
// [txt] 

Notice the comment in createSelfReferencingFunction where I indicate that let does not work and we have to use var. The reason for this is that eval creates a block, so the scope of let is restricted to that block, while var's scope is the whole function. There's an answer in stackoverflow explaining it.

Because eval introduces a new block of code. The declaration using var will declare a variable outside of this block of code, since var declares a variable in the function scope.

let, on the other hand, declares a variable in a block scope. So, your b variable will only be visible in your eval block. It's not visible in your function's scope.

Sunday, 20 March 2022

Python Strictness

I really like JavaScript and Python a lot, both being so profoundly dynamic, and very similar in many aspects, but there are some points where Python is a bit "strict" when compared to JavaScript, and you have to be more careful, let me explain.

Access to non existing items
In JavaScript, access to an index beyond the array length, or to a non existing key in an object or a map, just returns undefined


> let ar = [];
undefined
> ar[2];
undefined

> let ob = {name: "Francois"}
undefined
> ob.city;
undefined


> let m = new Map();
undefined
> m.set("a", "aa");

> m.get("b");
undefined


In python we have to be much more careful, as that kind of access will throw exceptions. So we'll have to check for the array length, the existence of a field via the hasattr() function, and the existence of a dictionary key via "if key in dict" (the has_key() function is deprecated)


>>> ar = []
>>> ar[1]
Traceback (most recent call last):
  File "", line 1, in 
IndexError: list index out of range

>>> d1 = {"name": "Francois"}
>>> d1["city"]
Traceback (most recent call last):
  File "", line 1, in 
KeyError: 'city'

>>> if "city" in d1:
...     print("key exists")
... else:
...     print("key does not exist")
key does not exist

>>> class Person:
...     pass
... 
>>> p1 = Person()
>>> p1.name
Traceback (most recent call last):
  File "", line 1, in 
AttributeError: 'Person' object has no attribute 'name'

>>> hasattr(p1,"name")
False
>>> 


Function parameters/arguments

In JavaScript you can invoke a function with whatever arguments you want, regardless of the parameters defined in the function signature (obviously, the function code will work or not depending on how those arguments are used)


> function fn(a, b){}
undefined
> fn();
undefined
> fn(1,2,3);
undefined


In python you have call the function with a number of arguments that matches the parameters defined in the function (save if you've defined them as *args, **kwargs)


>>> def fn(a,b):
...     pass
... 
>>> fn()
Traceback (most recent call last):
  File "", line 1, in 
TypeError: fn() missing 2 required positional arguments: 'a' and 'b'
>>> fn(1,2,3)
Traceback (most recent call last):
  File "", line 1, in 
TypeError: fn() takes 2 positional arguments but 3 were given
>>> 


strings and null/None
In JavaScript you can print (console.log) a null or undefined value, same as in Python you can print None. But in Python you have to be careful when using "+" for string concatenation (but well, most likely you're using f-strings, right?)


>>> a = "Hi"
>>> b = None

>>> st = a + b
Traceback (most recent call last):
  File "", line 1, in 
TypeError: can only concatenate str (not "NoneType") to str


>>> st = f"{a} - {b}"
>>> st
'Hi - None'

Sunday, 6 March 2022

The Reports on Sarah and Saleem

The Israeli-Palestinian conflict is a difficult topic. It's a mess on which my position has fluctuated a bit over the years, but in a greater or lesser degree I've always been quite supportive of normal Israli people that just want to have a state (of course I profoundly distaste orthodox jews and new settlers) and though I have never cared too much about Palestinians (because of Hamas and even worse groups, because of how Palestinian groups were crucial to unleash the bloody Lebanese civil war). That said, I think for sure that Palestinians deserve to have their own state, particularly the ones living in Cisjordania, and I think Israel, as a wealthy country would have to help a normal Palestinian state (one state that should annihilate the Islamist groups) to develop (a way of paying for the land they've taken from them).

Quite often one can find some form of beauty in pain and madness, and we could say that's the case here. All the suffering caused by this conflict has given us some of the best films ever produced: Le fils de l'autre, Capharnaum and Incendies (as I've said, without the Palestinian conflict probably we would have never witnessed the Lebanese Civil war), and now The Reports on Sarah and Saleem.

I've recently watched this excellent film on TVE2. If you watch it you'll probably wonder how could someone come up with such a crazy story, and well, reallity did, as the film seems to be based on real facts.

We have a married Israeli woman (married to an army high rank) and a married Palestinian guy that are having an affair. When you add to this unfrequent (I guess) situation something that could seem harmless, taking a drink together in Bethlehem (Belén), where nobody knows her, you're setting the ground for some crazy developments. In the end the guy ends up accused of seducing her (the wife of a soldier) to gain knowldge about Israeli military actions. The adulterous man becomes an imprisoned hero for Palestinians, and she becomes a traitor, not just to her husband, but to her nation.

It's really good for me to watch films like this, not just because of how instructive and entertaining they are, but because they remind me that not all Palestinians are crazy Hamas islamists. Many of them are normal guys that undergoing a brutally unfair and harsh existence, try to get by, and try to enjoy life, taking a drink, a dance and flirting with girls (event with Israeli ones).

One of the sequences in this film that I think I'll particularly remember in the future is this dialog between the desperate Israli woman and her work colleague, another young, normal, Israeli woman (I mean that she does not look like a religious or nationalist fanatic). I'm not reproducing the original dialog, just the main sense of what they say:

  • It's horrible, I've cheated on my husband
  • Oh, pour girl. Well, it's not that bad, these things sometimes happen
  • But furthermore he (my lover) is a Palestinian
  • What!!?? You are crazy. There are millions of Jewish men in this world and you have an affair with an Arab! How desperate you are!!!

Probably I would have said those same "racists" (yes, "Arabs" are not a race, but you understand) words. I admit that because of the conflict betwen our civilization and that other civilization, sometimes I tend to generalize and consider almost all Arabs, all Maghrebians and all Turks as our enemies. I know this is unfair, I know not all of them are crazy Islamists, crazy nationalists or crazy criminals, but it's easy to generalize, and when I do so, I'm ashamed about it.

Sunday, 20 February 2022

itertools.tee implemented in JavaScript

Generator functions and Generator objects, iterators and iterables work in a quite similar way in Pyhton and JavaScript, though there are some differences that maybe I will address in a separate post. Both in JavaScript and Python generator functions return generator objects that are both iterables and iterators (so the generator object iterates itself). Because of this, you can iterate a generator object only once. Notice that I explained time ago that this works differently in C#.

Looking into the functionality provided by the Python itertools module I came across an intereting function, tee, that allows creating multiple independent iterators over the same iterable. These iterators point to a buffer around the original iterator. It's a nice idea and I've implemented it in JavaScript



function tee(iterable, num){
    let internalIterator = iterable[Symbol.iterator]();
    let buffer = [];

    //it's very interesting that a generator function can trap the outer variables in a closure, though
    //in the end what is being generated by the compiler is an object with a next() method, not a function that traps the activation object
    function* generatorFn(){
        let pos = 0;
        let finished = false;
        while (!finished){
            if (pos %lt; buffer.length){
                yield buffer[pos];
            }
            else{
                it = internalIterator.next();
                if (it.done){
                    finished = true;
                }
                else{
                    buffer.push(it.value);
                    yield it.value;
                }
            }
            pos++;
        }
    };
    
    let generatorObjs = []
    for (let i=0; i%lt;num; i++){
        generatorObjs.push(generatorFn());
    }
    return generatorObjs;
}


let generatorObj = (function*(){
    yield "a";
    yield "b";
    yield "c";
})()

let [iter1, iter2, iter3, iter4] = tee(generatorObj, 4);

console.log(iter1.next().value);

console.log(iter2.next().value);
console.log(iter2.next().value);
console.log(iter2.next().value);
console.log(iter2.next().value);

console.log(iter1.next().value);
console.log(iter1.next().value);
console.log(iter1.next().value);
for (it of iter3){
    console.log(it);
}

for (it of iter4){
    console.log(it);
}
/*
a
a
b
c
undefined
b
c
undefined
a
b
c
a
b
c
*/

After coding it (and uploading it to a gist) I realized of how the generators and closures machinery is even more impressive than I already knew. In the above code we have a generator function that captures in a closure the "internalIterator" and "buffer" variables in its lexical scope (well, it'll get them through the [[scope]] property...). The amazing thing is that as we know that "generator function" will create "generator objects" on which we will invoke the .next() method, and is really that .next() method who will be accessing the captured variables, so somehow the compiler has to translate the "closure behaviour" (that in this case is a sort of "virtual closure") to a normal object, adding I guess references to the trapped variables to each of the generator objects that it creates. Evenly impressive is the fact that the node.js debugger will show us everything at runtime as if we were just dealing with a normal closure.

Sunday, 13 February 2022

async for vs for await

There's an important difference between how the async iteration constructs work in JavaScript (for await) and Python (async for), the ability (or lack of) to use it also to iterate a synchronous iterable/iterator.

Based on the idea that I mentioned in my previous post, the sloppy promise semantics, in JavaScript a for await loop can iterate both an asynchronous and a synchronous iterable. This is pretty coherent with the fact that we can also await for a non Promise value. The Iteration Protocols dictate that an Iterable object must have a method available with the Symbol.iterator key, that returns an Iterator object. This Iterator object must have a next method. For an Async Iterable we must have a Symbol.asyncIterator method, and the returned Async Iterator must have also a next method that returns a Promise.

A for await tries first to obtain an Async iterable checking if the object has a Symbol.asyncIterable, if that's not the case, it'll try to obtain a normal Iterator checking if the object has a Symbol.iterator. Then, as both iterables and asyncIterables have a next method, and as we know awaiting for a non awaitable value is perfectly fine, the Polymorphic behaviour is all set. Beautiful!.


let cities = ["Toulouse", "Lyon", "Xixon"];

async function* asyncCities(){
		for (let city of cities){
			yield await new Promise(res => setTimeout(() => res(city), 700));
		}
}


async function print(items){
	for await (let it of items){
		console.log(it.toUpperCase());
	}
}

(async () => {
	await print(cities);
	console.log("------");
	await print(asyncCities());
})();


That's not the case in Python. An async for will try to obtain an async iterator through the aiter() function (that invokes the __aiter__ method in the object). If the object lacks that __aiter__ method, we get a:
#TypeError: 'async for' requires an object with an __aiter__ method.
No attempt is done to invoke iter/__iter__. So writing code that supports both sync and async iterables is not so elegant:



import asyncio
import time

async def getCitiesAsync():
    print('getCitiesAsync')
    await asyncio.sleep(0.5)
    yield "Xixon"
    await asyncio.sleep(0.5)
    yield "Toulouse"
    await asyncio.sleep(0.5)
    yield "Paris"

def getCities():
    print('getCities')
    yield "Xixon"
    yield "Toulouse"
    yield "Paris"



async def printCities(cities):
    if hasattr(cities, "__aiter__"):
        async for city in cities:
            print(city)
    else:
        for city in cities:
            print(city)


async def main():
    await printCities(getCitiesAsync())



Sunday, 6 February 2022

async/await JavaScript - Python differences

I've been working a bit with async/await in Python lately, and there are some slight differences with JavaScript that I will document here.

Python's asynchronous machinery is provided by the asyncio module. We have coroutines, Tasks and Futures, I already talked about it, and I won't copy/paste the documentation, I'll just say that most of the time you will just work with coroutines (coroutine functions are those declared with async and they return a coroutine object. We can think of coroutine objects as JavaScript Promises.

JavaScript runtimes start an event loop on their own (nothing runs in JavaScript without an event loop), but in Python you have to start it yourself by calling asyncio.run(). Python's event-loop and coroutines are based on generators, and it does not use a ThreadPool like .Net does. This is well explained here and here

OK, so let's go now to the practical stuff, those minor differences with JavaScript

The most important difference is that coroutines are Lazy. Invoking a coroutine function returns a coroutine object, but the code that we wrote inside the function won't be executed until an await is done on that coroutine. In Javascript the code inside an async function starts to run as soon as we invoke the function.


import asyncio
import time

async def test():
    print("inside test")
    aux = await asyncio.sleep(1)
    return "test result"

async def main():
    print('inside main')
    aux = asyncio.sleep(1)
    print(type(aux)) #<class 'coroutine'>
    await aux
    print('next')
    aux = test()
    print(type(aux)) #<class 'coroutine'>
    #if we don't do an await aux, "test" is never executed
    #and we get a warning:
    #RuntimeWarning: coroutine 'test' was never awaited


#very interesting, the code in the "main" coroutine is not started until we call asyncio.run
#(I assume inside asyncio.run there is an await)
#it's different from javascript
cr = main()
print(type(cr))
time.sleep(3)
asyncio.run(cr)

In Javascript we can await for a non promise value. I mean, we can do:
let a = await "yyy";.
What happens here is that the JavaScript engine does a call to Promise.resolve(x) for each "await x;" sentence that it finds. If "x" is a Promise, it just returns that Promise, else, it returns a Promise that resolves to x.
This is not like that in Python. Awaiting for a non awaitable (coroutine, Task or Future) value throws an exception:


a = await "a"
#TypeError: object str can't be used in 'await' expression

In JavaScript when we await for a Promise that resolves to another Promise, the await will await for that internal promise, and so on...


(async () => {
	let pr = new Promise(resFn => setTimeout(() => {
		console.log("resolving first Promise");
		resFn(new Promise(resFn2 => setTimeout(() => {
				console.log("resolving second Promise");
				resFn2("Bonjour!");
		}, 3000)));
	}, 2000));
	let txt = await pr;
	console.log(txt);
	//after 5 seconds Bonjour gets printed
})();

This is not like that in Python. If a coroutine resolves to another coroutine, it's that second coroutine what await will "return"


import asyncio

async def __getCity__():
    await asyncio.sleep(1)
    return "Paris"


async def getCity():
    await asyncio.sleep(0.5)
    print("after first sleep")
    #if the coroutine resolves to another coroutine, the "await" in "main" calling "getCity" does not wait for the internal one (contrary to JavaScript)
    return __getCity__()
    
    #so we should write this line rather than the one above
    #return await __getCity__()


async def main():
    
    city = await getCity()
    print(city)

asyncio.run(main())

#after first sleep
#<coroutine object __getCity__ at 0x7fad74b34540>


We can say that for the 2 previous cases JavaScript works differently because of what seems to be known as the sloppy promise semantics