Friday, 6 December 2013

One more Programming Mashup

It's been a while since my last "list of interesting programming stuff" kind of entry, so here it goes a new installment.

  • JavaScript is already very well packed with reflective features: Introspection, Object Expansion, Runtime Code Evaluation (eval is not evil), so it called my attention to find Reflect API planned for ES6. As the document says, it does not provide new functionality, but is a convenient way to place this already existing functionality (I've always considered Object as an odd location for functions like: freeze, seal, getOwnPropertyDescriptor). It's also interesting to see how nicely it plays with proxies.
  • Talking of proxies, it's clear that it's one of the hottest and more expected additions to JavaScript, and we'll see all sort of interesting uses of it, one that I pretty much like is this one, adding negative indexes to arrays. If you take a look at the code you'll see it's just a couple of lines!
  • I pretty much like the usage (and the code) for this Dependency Injection library for JavaScript
  • With my love for Prototype based languages, I've never been much keen to use any of the many class emulation libraries for JavaScript, and indeed I don't like the idea of adding Classes syntactic sugar (internally it'll continue to be based on prototypes chains) to ES6. But when one comes across so many discussions about different approaches to inheritance, with names like "parasitic inheritance":
    • http://www.benlakey.com/2013/05/javascript-prototypal-inheritance-done.html
    • http://helephant.com/2009/08/17/javascript-prototype-chaining/
    • http://stackoverflow.com/questions/7250423/javascript-parasitic-inheritance?rq=1
    • http://javascriptissexy.com/oop-in-javascript-what-you-need-to-know/http://stackoverflow.com/questions/2800964/benefits-of-prototypal-inheritance-over-classical?lq=1
    • http://stackoverflow.com/questions/16929353/parasitic-combination-inheritance-in-professional-javascript-for-web-developer
    • http://ericleads.com/2013/02/fluent-javascript-three-different-kinds-of-prototypal-oo/">
    one can end up changing his mind and thinking that the homogeneity that the class construct will bring to most developments, can be indeed a promising prospective.
  • I've found interesting this entry about how a bad design it is when a class requires its inheritors to call some of the parent methods. There's no way to force that an inheritor will do that, so if he skips that call, this new Child class will be wrong. As the article mentions, we should change the design to use the Template Method Pattern (one of my favorite ones)
  • I've always felt quite happy using normal objects when I need a Dictionary in JavaScript, so this post has been a real eye opener.

Wednesday, 27 November 2013

Exberliner, refugees in Germany

Exberliner is a really inspiring publication (it already prompted this post last year). The base idea (an in English lifestyle magazine for expats in Berlin) should not be particularly appealing to a scarcely social, not cool in the slightest individual like me... but it's crystal clear that Berlin is a different place, and what in other cities would be a hipsters oriented magazine, in Berlin involves articles about social issues, historical background and so on. For example, the April number contained great articles about the urban (gentrification) plans for the city and the wipe out of part of the socialist architectural heritage.

November's issue made a non stop reading session in my flight back, and helped me understand things I'd seen the previous days both in Berlin and Hamburg. Already in October 2012 I had come across a refugees support camp in OranienPlatz (O-Platz), and information about demonstrations and a march in solidarity with refugees. The same landscape has been present in my ensuing visits to the world capital (it's very funny to see how to me Berlin has turned into the Welthaupstadt that the nazi scum dreamt about, but just for all the contrary reasons: freedom, art, dynamism, convergence of ideas, alternative thinking...) This November, apart from the camp, I found many stickers, posters, flags hanging from autonomous centers and alternative book shops... reading: Refugees Welcome and Lampedusa in Berlin/Hamburg.

Also, when paying a visit to one of my favorite Berlin spots, the desolated site between the Spree and Kopenickerstrasse with its abandoned factory covered in graffiti and murals, I found a middle east family trying to build a shanty under the shelter of the factory.

Exberliner's november issue is called "Looking for Asylum in Berlin" and nicely explains the current situation through different interviews and articles. In the last years Germany has become one of the top destinations for people seeking asylum in Europe. The reasons for this are not completely clear, but one of them is the false belief that achieving asylum in Germany is easy. Reading the experiences of some refugees it's pretty clear that it's not. Years of stagnation in a Heim (emergency refugee centre), without any idea of whether your request will be accepted or not, whether you'll be moved to another Heim in another city, the inability to work as you lack the permissions needed for that... As more refugees have been arriving into Germany (and primarily Berlin) and no move has been done by the government to speed up the asylum request procedures or to improve the conditions in which they are kept until the final decision is done different support initiatives has emerged, one of them being the protest camp in OranienPlatz. The "Lampedusa in Berlin" phrase comes from the fact that many of those refugees enter Europe through Lampedusa.

It's shocking to see that lately there's been an increase of Russian gays seeking asylum in Germany on the basis of the wave of homophobia that Putin's government and the Orthodox Church have unleashed. It seems like in the last months Russian neonazis and other pieces of human debris have been moving their focus from dark skinned people to gays.

Apart from these sad refugees stories, there's also an interesting column about Die Linke, their last electoral results (unfortunately, not too impressive), their difficulties to get rid of the past and the permanent boycott they're subjected to.

Sunday, 24 November 2013

A slight taste of Perl

Over the last weeks I've been learning some Perl. Yes, I know it sounds like odd, what the hell is doing someone quite obsessed with language evolution learning a dusty 90's language?
Well, let's explain. First, a new project sprang up in my employer involving Perl and relocating for some months to the very beautiful city of Toulouse. Spending some months in Toulouse seemed appealing enough to me to make Perl look as cute as ES6 or even more :-) so I just eagerly jumped into the project.
Second, Perl is way much better than I would have expected. I guess I'll be blogging about it in the nearby future, so I'll just say here that you can do perfectly modern programming with Perl 5. This does not change the fact that the language is riddle with very idiomatic "features" that I frankly consider SHIT (the default variable/parameter thing above all), but well, it's just a matter of avoiding those things (and praying for not having to work with code written by others that consider those features cool and useful).

The thing is that while learning Perl I've come up with some very familiar features that until that moment I used to identify as JavaScript specific. Probably the most obvious are shift, unshift and splice for arrays. While the functionality is common to almost any language/library, the choice of names is not (I guess Append, RemoveFirst... are quite more natural).

A fast search brings up a related entry in the excellent 2ality blog. Well, there are a few more influences not mentioned there that I can think of:

  • Perl's undef is mainly the same as JavaScript's undefined
  • While (contrary to JavaScript) Perl lacks a Boolean type, the coercion rules applied to normal values in if conditions and son on are pretty similar. 0, "", and undef are considered false. Notice though, that "0" and an empty array/list will be considered false in Perl, but true in JavaScript.
  • I would not call this an influence, but an inherited disease... the most basic function to obtain the current datelocaltime, considers months from 0 to 11, rather than 1 to 12... one of the most common JavaScript gotchas.
  • Update, 2013/12/27 Removing a key from a dictionary/hash is pretty similar (and not particularly intuitive, I would prefer a .remove method), use the delete operator in JavaScript:
    delete myObj.key;
    or the delete function in perl:
    delete(myHashRef->{key});

There has also been some more recent influences. JavaScript 1.7 first (implemented by Firefox since quite a few years ago) and ES6 now, implement destructuring assignment, a beauty that Python also drew from Perl. Moose, a modern object system for Perl 5 sprung up a JavaScript equivalent, Joose.

Sunday, 17 November 2013

Stree Crap 2

While being in Hamburg last week, I came across another insult to aesthetics that makes a good follow up to this previous post. I was quite interested in paying a visit to the Bismarck memorial in Hamburg, mainly because its Berlin counterpart makes one of my favorite monuments, though not for the Bismarck statue itself, but for the 4 other statues surrounding it. You can read the wikipedia article for some basic info, I'll just say that they look incredibly imposing and powerful (reminding me in that sense the astonishing 2 statues flanking the entrance to the Altes Museum.

Hamburg's memorial is quite interesting, Bismarck stands sober and serious watching over one of the most affluent cities of the country he managed to unify (specifically over St. Pauli, the most leftist, anarchic, party going district in Hamburg). It's quite remarkable how with his cape and sword he looks more like a Teutonic Knight than like a statesman of the end of the XIX century.

And here you have some pics of the offence, when street art turns into street crap

As for Bismarck, he seems to be a rather interesting personage, and not just for founding the most important country in modern Europe. From my basic understanding of his biography, I have mixed feelings about him. On one side he was deeply anti-socialist, but on the other side he was responsible for creating the concept of Welfare state that civilized people (i.e Europeans, Canadians...) have today, along with trying to avoid war by all means (without him, WWI well might had occurred some decades earlier).

Thursday, 31 October 2013

Generators

It seems like there's been quite excitement lately around one of the new beautiful features with which one day ES6 will delight us, Generators. They've been added to the last version of node.js, and have been available in Firefox since time immemorial (fuck you Chrome), but notice that Firefox will have to update its implementation to the syntax agreed for ES6 (function*...).

I first learnt about Generators back in the days when I was a spare time pythonist. Then the feature was added to C# 2.0, and all my relation with the yield statement has been in the .Net arena. Notice that unfortunately Microsoft decided to use the term Iterator for what most other languages call Generators, same as they decided to use the terms Enumerable-Enumerator for what most other languages call Iterable-Iterator... frankly a quite misleading decision.

I've been quite happy with C# Generators (Iterators) ever since, especially with all the cool black magic that the compiler does under the covers (create aux class implementing IEnumerator (and IEnumerable if needed), __this property pointing to the "original" this...), but reading about JavaScript generators I've found some powerful features that are missing in C# version.

It's no wonder that in JavaScript generator functions (functions with yield statements) and iterator objects (__iterator__) are pretty related. Documentation talks about generator functions creating an generator-iterator object. Let's clarify it, what they mean with generator-iterator object is an iterator object with some additional methods apart from next:
send, throw, and close

These extra methods are quite interesting and are not present in C# implementation. send seems particularly appealing to me. As explained in different samples, basically it allows you to pass a value to the generator object that it can use to determine the next steps in the iteration. You can use it to reset your iterator or to jump to a different stage. I've said reset, well, IEnumerator has a Reset method, but the IEnumerator/IEnumerable classes that the C# compiler generates when we define an Iterator (generator) method lack a functional Reset method (it just throws a NotSupportedException).

Pondering a bit over this, we can sort of add a Send/Reset method to our C# iterators. From the iterator method we have normal access to properties in the class where it's defined (as the generated Enumerator class keeps a __this reference to that class), so we can add the Send/Reset method directly there. This means that if we want to Reset the Enumerator created from an iterator method, we'll have to do it through the class where that iterator method is defined, rather than directly through the Enumerator. Obviously it's not a much appealing solution, but well, it can be useful in some occasions.

public class FibonacciHelper
{
 private bool reset;
 public void Reset()
 {
  this.reset = true;
 }
 public IEnumerator<int> FibonacciGeneratorSendEnabled()
 {
  int prev = -1;
  int cur = 1;
  while (true)
  {
   int aux = cur;
   cur = cur + prev;
   prev = aux;
   yield return cur;
   if (this.reset)
   {
    this.reset = false;
    prev = -1;
    cur = 1;
   }
  }
 }
}

FibonacciHelper fibHelper = new FibonacciHelper();
  IEnumerator<int> fibEnumerator = fibHelper.FibonacciGeneratorSendEnabled();
  for (var i=0; i<10; i++)
  {
   fibEnumerator.MoveNext();
   Console.WriteLine(fibEnumerator.Current);
  }
  Console.WriteLine("- Reset()");
  fibHelper.Reset();
  for (var i=0; i<10; i++)
  {
   fibEnumerator.MoveNext();
   Console.WriteLine(fibEnumerator.Current);
  }

I've got a full sample here

Another difference is that while JavaScript's send will both reposition the iterator and return a value, my implementation above will just reposition the enumerator, but no value will be returned until the following call to Next.

Another interesting feature in JavaScript generators is the additional syntax for composing generators, aka "delegated yield": yield* (seems Python's equivalent is yield from)

function myGenerator1(){
yield* myGenerator2();
yield* myGenerator3();
}

As C# lacks that cutie, we have to write:

IEnumerator<T> MyGenerator1()
{
foreach(var it in MyGenerator2()){
yield it;
foreach(var it in MyGenerator3()){
yield it;
}

Saturday, 26 October 2013

Make me a German

Make me a German is an equally funny and informative BBC documentary. The curiosity for understanding why the German economy is doing so good while the economies of the rest of the European Union are doing so dramatically bad, compels a British family to move to Germany and try to convert themselves in the average German family in an attempt to understand the country from inside.

The experiment is pretty funny, and brings up some interesting points, at least for someone like me, that in spite of having an obsessive fascination for Berlin, having read quite a lot about German history and society and counting some German artists (Caspar David Friedrich) among my all time favorites, has never had a too intense interaction with locals (I've been to Germany quite many times, but as a solitary person with not much significant social skills... I've hardly scratched the surface of the German mind). I'll list below some of their findings:

  • Germans really work less hours than most Europeans (at least British and Asturians), but they work so focused and hard that they are much more productive. It's astonishing how outraged one German lady felt when talking about her experience in U.K. in an office where people where checking their personal emails or talking about their private life during the work day. Quite hilarious.
  • There seems to be a very strong sense of community at work, and also an identification with the company. You are part of a team and as everyone in the team is working hard you can't fail them. I guess most people will appreciate this, but notice that taking to the extreme this feeling of unity and belonging and the denial of individualism helped set the backdrop for the Nazi regime. I'm a very individualist person, so I'm a bit biased on this point.

  • Germans are cautious with money and save more than the rest of Europe. This can be easily traced to the brutal crisis after WWI and WWII. Germans are quite little fond of credit cards (hum, that's a rather Germanic trait of mine). This background also explains something that I pretty enjoy when being there, Supermarkets are cheap, indeed it turns out that German supermarkets have the tightest profit margins in Europe.
  • It's easier to be a mother in Germany. Families with kids get enormous fiscal advantages, Kinder Gartens are really cheap, and there's a sense of pride in being a mother that has left her job to take care of her little kids and the house. It's so common that mothers that decide to carry on with their jobs are generally seen with a certain disapproval. What seems odd to me is that having all these advantages the birthrate continues to be so low.
  • I'd never noticed that Sundays as a rest day were so important to Germans, well probably it's cause they're not that sacred in Anarchist Berlin as they are in Christian southern Germany. Combine this with that almost genetic obsession with abiding by the rules and civic behaviour, and doing some more noise than expected in a Sunday morning can end up with the Polizei paying you a visit and giving you a fine. On a personal note, the unruly Astur-Gallaecian in me can't help enjoying the bad looks I get there each time I cross a red light :-D (and what to say about travelling without a ticket in Berlin's BVG)

It quite caught my attention that a British family were looking at Germany as a better place. For an Asturian like me, that lives in a place with 27% unemployment, where youngsters are much more ignorant now than they were 100 years ago, having as their main aspiration in life to turn into a TV crap celebrity and partying as hard as possible, where politicians are mainly a bunch of thieves, where "picaresca" (that is, getting whatever you want by means of tricks and cheating rather than by effort) is a chronic illness... it's normal to perceive Germany as a better place and look at it with a certain sense of inferiority (though based on culture, history and geography Asturies is NOT Southern Europe, in the end we share and suffer too many traits with the rest of Southern Europeans), but I also perceive UK as a better place/society, so it seemed funny to me seeing the Brits envious of the Germans. Who knows, maybe Swedes are also envious of Norwegians or Danes... but for us, they're all just "first class countries".

Sunday, 20 October 2013

Stalin's Birthday Cakes

My fascination with architecture (I'm talking about buildings today, not about Software) has grown over and over along the years. My main source of fascination are Gothic Cathedrals (and to a lesser extent Baroque structures) and slim sky scrappers (aka "Business Cathedrals"). I'll also leverage this entry to make public my discomfort with simplistic buildings that for some reason "self proclaimed intellectuals" decided to consider "revolutionary". I'm talking about the main current in functionalism and that sort of Bauhaus crap. For me Aesthetic pleasure should be one of the main aims of architecture, indeed, it's one of its basic functions.

This said, is easy to understand my fascination with Stalinist Style sky scrappers (aka Stalin's Birthday Cakes). This wikipedia article gives an excellent introduction to the broader subject of Socialist Realism. Though I've never been to Russia, "the Soviet sphere of influence" after WW II (aka occupation and puppet states) has meant that I've been able to indulge myself with the views of some extraordinary pieces of this style with no need to leave the European Union.

Along with the 2 most well known buildings, Warsaw's Palace of Culture and Science and its little brother (or sister) Latvian Academy of Science in Riga, I've also set my eyes on 3 other beautiful (though obviously not so magnificent) constructions in:

  • Prague (the Crowne Plaza Hotel). I knew about this building through some web research, otherwise it's a bit far from city centre and I don't think I would have come across it just by chance.
  • Tallinn (nice residential building close to city centre). You can read more about Tallinn's "Soviet legacy" here.
  • .
  • and Vilnius. I just came across this building by chance. It's close to the city centre, by the Neris river, just next to the pedestrian bridge crossing to the business district (by the way, that bridge gives you a pretty nice view of that area). I haven't found any additional information about it.

I've created a new Picasa Gallery with some more related pictures.

While I find this "Birthday cakes" style buildings the most noticeable of the genre, the whole Socialist Classicism style seems fascinating to me. My visits to the Soviet War Memorial in Berlin have been sort of spiritual experiences (apart from the imposing architecture it confronts you with the miserable condition of human beings when you think about how the heroes that liberated Europe from fascism turned into the brutal rapists of millions of German women...), and visiting the memorials in Tallinn or Riga, or just strolling along Karl Marx Allee in Berlin or Nowa Huta in Krakow are absolutely recommendable activities.