Wednesday, March 14, 2012

Russian Ark - *****

OK, I was a bit late to see this movie. Well, by almost 10 years. But that is what I like: discovering when the hype is completely gone.

If you do not know anything about it, here is what you would commonly hear about it: "The whole film is just one shot, and it spans the whole 96 minutes of the film".

Second is that in the course of the film, you would see stunning pictures, I am saying stunning - you got to see it.

But, but.

This is not really what the film is about. For starter, Russian Ark is not the first single-shot movie (first being Hitchcock's). It is not even the second one. So no novelty here. There was a huge logistics to make this happen but yet again that is not what makes a film a memorable one.

Also, I have seen films with stunning pictures and I did not like them. Movies of the late Theo Angelopoulos were among them - he may rest in peace but I would not withhold my view. Weeping Meadow was weak, really weak - and I cannot understand why the Cannes prize. Anyhow - enough talking behind the passed away.

The film is about history. Well, that was obvious, wasn't? Covering three centuries of Russian Monarchy history in an hour and half with location being Hermitage museum. And showing so many historical artefacts, painting, people, costumes... Yet this obviousness transpires towards the end of the film into something greater. It is a celebration of us mortal beings and our vague yet eternal legacy. Story so many dead people narrated by the spirits of two dead strangers - yet it is a celebration of life.

Finale is worth watching the whole thing if you get bored halfway. Stick with it and you will be graciously awarded for your patience.

This is 5 stars and immediately among my top 100 movies of all time.

Thursday, February 02, 2012

Introducing conditional.js, a jquery plugin for clean predicate-action separation

These days javascript space is full of newly developed and emerging frameworks. It is still early to speculate which ones will make it and can become par to jquery's unique status, but some have already made it into quite a few production projects and are gaining momentum and popularity by the day.

Depending on your background - be it Open Source Java/Ruby/Python or Microsoft's .NET - examples could be different but one is the MVVM Framework for javascript - aka knockout. I have been and am a fan of all the possibilities this framework brings to the client-side code but sometimes all you need is a simple tool to organise your code and make it more readable - you do not need a full-fledged MVVM library.

Let's bring an example.

Consider we have a form where depending on the answer to one question, answering some other questions become mandatory. We have a form asking for our detail and if the answer to marital status from a dropdown is "married", then detail of the spouse needs to be provided.

If we were to build this in HTML/javascript, we would put the fields for spouse detail in a container and then hide/show based on the value selected from the dropdown.

Here we have a predicate: "whether marital status of married is selected" and we have an action which is "show or hide a container". Here the action is parameterised with a boolean which happens to be the return value of the predicate.


Coding this is almost trivial: use jquery (or plain old DOM events) to subscribe to changes of the dropdown value and hide/show accordingly. And none of that predicate/action nonsense!


But as the requirements gets more complex, the code gets more and more complex to the point where the intention of the code is buried underneath many lines of code. For example, what if the logic depends on the value of multiple fields? The complexity will increase exponentially with the number of fields involved. Also one common problems - those of you who have implemented such scenario would immediately remember - is that when the value is served by the server, the event is not triggered so the visibility of the container is not affected. For example, if we edit a saved form for a married person, server will send the HTML with the value of married status dropdown to "married", however, since the change event is not triggered, spouse detail container stays hidden. To combat this, we have to raise the change (or call the callback code) so that the logic is executed.

One solution is to use a framework such as knockout to wire the event with the logic as a client-side binding. One problem with such approach is that the binding to multiple fields is cumbersome, especially if they are involved in more than one such logic. Also, implementing custom action requires adding custom binding which is fine with one or two cases but not great when there are more custom action to be executed.

The solution conditional.js presents here is to a separation of predicate and action by:

  1. Subscribe to change events of one or multiple elements by providing one or more jquery selectors
  2. Accepting a predicate (a javascript callback function) that will receive the value of the elements
  3. A set of standard actions (hide/show and enable/disable) that will react to the value returned by the predicate. Alternatively registering a custom action, or simply just providing a callback action that will be called passing the return value of the predicate.

This probably sounds more complex than it is so let's bring the example - example above but this time with code.


        $("#spouseContainer").conditional({
            selectors: "#marst",
            predicate: function (maritalStatus) { return maritalStatus==="Married"; }
        });

As can be seen above, container with id of "spouseContainer" is used to start create the jquery object. We pass selectors (here a single string and it can be a string array too) that is for the marital status dropdown with id of "spouseContainer" and then a predicate defining our desirable condition which by default is visibility - i.e. whenever value of "marst" is equal to "Married", spouseContainer will be visible. Since we have passed a single selector, our predicate needs to accept a single parameter.

So I believe this 3 lines of code are really expressive and readable. This also take care of the problem of setting the status when the page is loaded with the desirable value.

In the next blog, I will delve into all options and possibilities of conditional.js.

Friday, December 09, 2011

Review: Nader and Simin, A separation

I watched the movie A Separation in a friend's house last night. This was a movie that I had heard about and planning to watch but when it comes to popular films, I let the dust settle so I can have clear view, without any prejudgement. I must confess it is one of the better films I have seen lately.

A Separation is a tense and gripping movie. Takes you through a rollercoaster of emotions and in the end, it lands you safely but shaken while letting you digest the intense drama. It sucks you in: you cannot be a bystander watching this, either you are full in or full out. For a family film, as it were, this is a surprisingly intense experience with a suspense, drama and complex story-line that is not a hallmark of such genre.

Apart from a stunning performances from every single actor, transparent and true cinematography (which as far as I can remember not quite the style Kelari is known for) and precise editing, this is a layered movie: the one on the surface is the story of the characters and the one deeper, which is the story of chasm and confusion of today's Iran society. It cuts deep to the bone, where the separation is that of social fabrics.

After finishing watching it, I could understand why this became so popular in France. It immediately reminds of Dardenne Brothers films where realism meets intense and personal drama: no long shots, camera is so close to the characters that you can almost smell them.

[SPOILER ALERT: There will be references to the ending and events within the film from here on]

After the first scene, we get to think that perhaps separation was just a fluke, a spin-off so that the real story can begin. Nader does not make any efforts to stop Simin. He seems to be merely interested in his father and daghter. Not only he does not show any affection towards her, but also he does not even make an eye contact - cannot remember even one scene that he makes an eye contact. After watching the movie till the end, I feel that Nader avoids Simin as he knows that Simin's love will destroy him, as he would be torn apart between her and his father -  a choice that he would not be able to make. Simin is completely shaken by the separation but she sees no option other than choosing a future that will spare his daughter from the increasingly unbearable conditions of the society.

On the other hand, Razieh is torn between the interest of her family versus her religious beliefs. He calls Fatwa line's and asks for religious guidance for difficult choices she has to make. Hojjat has been stung once by the society and he is after his right. He is in a desperate and hopeless situation where his religious believes can cost him repayment of his debts. He is torn between playing the victim and perpetrator. And Termeh is torn between choosing her father or her mum.

This is pretty much how every Iranian feels. They are torn inside having to make difficult choices while the fabrics of the society are being torn outside by the shearing power of conflicting and even paradoxic powers. Nader is representative of the part of the middle class who sticks to his father (the traditions) while his father does not even recognise him - and he acknowledges it. Simin is the part of the middle class who had enough and wants a modern contemporary life (and since she cannot have it in Iran she has to emigrate). And for the working class (Razieh and Hojjat), there is no hope. It is interesting that the upper class has no representative here, it completely lives in its own world with no connecting to the realities of the street.

Now here, it is for the new generation (Termeh) to decide which one to choose: as Kiosk very well puts it, modernity or tradition [I strongly recommend watching this video, illustrates the paradox very well]. Separation is final, it is past the point of no return and Iran's new generation has to choose - which one? I think Farhadi has left the history to tell us the rest of the story.

Monday, December 05, 2011

Upgrading your jquery to 1.6+ is safe, really?

Upgrading dependencies are always a risk. A risk that sometimes can be qualified but from my personal experience when things go wrong, they are usually where you least expect them. While performing a thorough "impact analysis" is helpful, this is easier said than done. And usually just a tick in the box, meaning yes we did it (technically covering our back). In my case, we planned our upgrade from 1.4 to 1.5 but this time, we had to use a jquery plugin which we realised in the middle of the sprint that it used 1.6 features.

We all love jquery, not only because it has made working with DOM easier but also because it is such a forgiving framework, tries to guess your intentions and return you what you intended and not necessarily what you asked for. Well, we will see how this could affect the risk of upgrading to jquery 1.6+ (currently at 1.7). But to be honest out of all libraries, jquery was the one I would least to expect a breaking change - it is a library that hides breaking differences of browsers so knows the pain of a breaking change!

According to jquery release note, upgrading to jquery 1.6.1 should not require any change:

With the introduction of the new .prop() method and the changes to the .attr() method, jQuery 1.6 sparked a discussion about the difference between attributes and properties and how they relate to each other. It also came with some backwards compatibility issues that have been fixed in 1.6.1. When updating from 1.5.2 to 1.6.1, you should not have to change any code.
 OK, I am relieved! So I can happily upgrade our jquery 1.5 to 1.6.1 (and even better 1.7). Is it really safe? Well, the answer depends on how you have used (or abused) the method attr() on previous versions.

attr() vs. prop()

All the difference between v 1.5 vs. 1.6 boils down to introduction of prop() and change of the semantics of the existing attr() that can break your code, well it did ours - unfortunately I believe due to our bad jquery code. prop() will represent the semantic of the property which could have been stored as an attribute while the attr() will return literal (string) value of the attribute.

Confused? Well, I believe origin of the confusion was the poor HTML attribute definition - let's blame W3C here, they always get blamed anyway! To explain it further, if I have a checkbox that is checked, its "checked" property will be true but its "checked" attribute will be "checked".

In code terms, let's imagine this scenario:

<button name="chip" id="chap" disabled="disabled">happy chappy</button
<input type="checkbox" id="chk" checked="checked">Hello</input>


As you can see we have to elements, a checked checkbox and a disabled button.
This is how this is going to look in jquery 1.5 (jsfiddle line here)

console.log("disabled attr: "$("#chap").attr("disabled")); //outputs "disabled attr: true"
console.log("checked attr: " $("#chk").attr("checked"))//outputs "checked attr: true"

This is how this is going to look in jquery 1.6 (jsfiddle link here)


console.log("diabled attr:"$("#chap").attr("disabled"))// disabled attr: disabled
console.log("checked attr: " $("#chk").attr("checked"))// checked attr: checked
console.log("diabled prop: "$("#chap").prop("disabled"))// diabled prop:  true
console.log("checked prop: " $("#chk").prop("checked"))// checked prop: true


Will attr() always return the literal value of the attribute? No, and that is what confuses me but again I think it is partly due to inconsistencies of HTML attributes. For example, value of the disabled attribute does not have to be "disabled" to be effective, its mere existence signifies "disabledness" of the element. For example, if the attribute has no value, element is still disabled (or checked) and attr() will return element's implied value and not the literal one (which I believe should not be so and attr() should just stick to the literal value):

<button name="chip" id="chap" disabled>happy chappy</button
<input type="checkbox" id="chk" checked>Hello</input>

console.log("diabled attr:"$("#chap").attr("disabled"))// disabled attr: disabled
console.log("checked attr: " $("#chk").attr("checked"))// checked attr: checked

Where can it cause problems


We experienced two types of problems:
  1. Calling  $("#chap").attr("disabled", ""will totally remove the attribute (enable the element) in jquery 1.5, while in jquery 1.6 it will just set the value to empty string. So my colleagues have been conveniently using attr("disabled", "") to enable the element while they should have just used removeAttr() which has been there since v1.0. Semantically, attr("disabled", ""should set the attribute to empty string but jquery used to gracefully interpret that as the same as setting property to false - not anymore.
  2. If you use the literal value of the attr() since it would return false/true but now it will return "disabled"/undefined. In our case the value was being passed to the server, hence server was expecting a boolean (false/true) and it broke when it saw "disabled"/undefined!

Conclusion

Upgrading your code from jquery 1.5 to 1.6 can break your code around the attr() function. So be careful and plan a full regression testing after the upgrade.

Sunday, September 18, 2011

Performance comparison of .NET method calls

In this post I will try to compare performance of various method call types in .NET including IL's call, virtual call, reflection method call, delegates, compiled lambda expressions and Action/Func.

It is not too rare for me to pick up and say something about the internals of .NET framework or just general Microsoft stack only later to realise I was wrong - not in this case because I was wrong although that happens too but because things have changed since I last checked up or read upon them. This happens a lot on Stackoverflow where it is even more crucial to be right - don't wanna give false information to others.

With the advent of lambda expressions and introduction of generic delegates aka Action<T>, Func<T>, etc in .NET 3.0 things have certainly got funkier - pun intended! Now in .NET 4.0, we have the dynamic stuff which is even better, certainly solving many difficult problems we were facing in a statically typed environment. Best example is Simple.Data which I just love for its simplicity and would be impossible without it.

Now this is all well and good but it does come with a price tag - performance hit here - which we all know exists but its kinda like banking direct debit, you know you have set it up and it goes out of your pocket but since you do not see a bill, you do not realise how much you are paying. On the other hand, sometimes you might drop off the other end of spectrum and start micro-optimising by not using any reflection or dynamic hence loose the opportunity to make your code more maintainable by not using more expensive but much more elegant approach which involves dynamic or lambda expressions.

I remember from the old VB6 days when we were talking about late binding and how evil they were and we were to avoid them like plague. Now 10-12 years later and things have changed a lot: we are trying to solve much more complex problems and we need new tools and new languages hence the popularity of functional languages. On the other hand, our hardware have got noticeably better so what would be deemed to be a no-no back then, it has become commonplace to use. But I certainly see a new wave of awareness to the performance, thanks to the popularity of mobile and tablet platforms where memory and CPU just cannot be taken for granted.

Anyway, from whatever angle you look at it, it is useful to have a comparison.

I have created different scenarios where the same piece of code (which does a simple calculation) is called in a various ways. Here


As can be seen, calling DynamicInvoke on a delegate has the worst performance. Of notice, is relatively good performance of Dynamic objects compared to reflection.

In the next post we will discuss the detail and code for the test.

Thursday, February 10, 2011

New blog days

It seems that I have now managed to get back to my blog - fiddle with a new design, new title and basically renovated the blog. Not sure if it looks OK but perhaps you never know until you get people's feedback.

These days have been very busy with quite a few things on my mind: events in Egypt, my load testing framework at work, my Android app which I have published but has not yet made it to version 1 (still version 0.9.6) - what if it does not make it version 1.0, I keep making versions until 0.9.9 and then I suppose there is no limit you can go up to 0.9.9.9.9.9.... Reminds me of the famous mathematical paradox: everything is still and there is no movement since let's say you are moving from A to B. In order to do that, you need to do the half and then the next half. With the second half also, you need to do the first quarter and second quarter, so on. At the end, it concludes that movement is just an illusion, we are all still!

OK, I look forward to my next post. I had a couple of posts which I preferred to disable since I felt they are old - well, they were 3.5 years old - what a hiatus!