Customizing Highcharts – Tooltip Positioning

The Highcharts API Reference for tooltip.positioner reads

A callback function to place the tooltip in a default position. The callback receives three parameters: labelWidth, labelHeight and point, where point contains values for plotX and plotY telling where the reference point is in the plot area. Add chart.plotLeft and chart.plotTop to get the full coordinates. The return should be an object containing x and y values, for example { x: 100, y: 100 }.

However, positioner is much more than just the default position of the tooltip. It takes the following syntax

Note the three arguments labelWidth, labelHeight & point at your disposal, these seem to be sufficient for most of the use cases to calculate a desired tooltip position. labelWidth and labelHeight are the width and height that your tooltip requires, hence you can use them for edge cases to adjust your tooltip and prevent it from spilling out of the chart or even worse getting clipped. Let us see an example of positioning the tooltip to the right of the point.

Keen eyes would have noticed a problem while hovering over the December points, the tooltip goes outside the chart area. Let’s fix this using the labelWidth, this tells us how much space would the tooltip need. Using the labelWidth along side pointX we can find the far right of the tooltip and compare that with the plot’s width, if it goes outta bounds, we position the tooltip to the left instead. Try fiddling with the rightmost points on the series.

Sometimes, all we may want is a static location for the tooltip, like one of the corners of the chart. At the same time, we might not want the tooltip to eclipse any datapoints. We could simply assign the bottom left corner (chart.plotLeft,chart.plotTop + chart.plotHeight – labelHeight) as the tooltip’s position, and make use of the all the three parameters to determine if the current point falls behind the tooltip’s default location, if so, move the tooltip to the top right of the point. Hover over any point and observe the tooltip stays at the corner, now hover over the point at the bottom left and see the tooltip give way to the point.

For further reading, the default tooltip positioner that comes with highcharts is interesting. One should be able to adapt this to the appropriate requirement (Source).

Read further about customizing the visibility of the tooltip @ Customizing Highcharts – Tooltip Visibility

Reference Links


Exceptions aren’t problems but symptoms, let them show up

When we design an application we are the ones to govern the rules, it’s like a country having its own laws which everyone inside has to abide to and obviously, we don’t want people who won’t follow our jurisdiction. Assuming people keep the same persona both in and outside the country. There are several ways to ensure this, you can have a check-post to ensure whom you wish to allow inside, or you can allow everybody in & have cops to catch intruders when they disobey some laws, or you can simply have enough trust in the outside world to only send good people to your country. I am a big time believer of peace and hence strongly recommend the last. Rest of the blog is for people who simply cannot follow the crappie-big-time-believer-of-peace-ethic

Trust brings with it expectations. Since we programmers, unlike managers, don’t expect impossible things and hence we can say expectations are a small subset of possibilities. All code that you write, should be against expectations and not possibilities, with just one exception which we shall see later in the post. What this means is, your code should be free of try...catch blocks, unless one of the use case is expected to produce some exception, and even in such cases your catch block should be against that particular expected type of exception and not against all subclasses of Exception. Assume our acceptance criteria says, Divide should return Double.Infinity if we encounter division by zero.

A way to do this would be

The above code is sure to return Double.Infinity if num2.Value were to be zero. Here even if we pass num1 or num2 as null, we will be returned Double.Infinity, since num1.Value / num2.Value will throw a NullReferenceException exception, which will be caught. As we are not expecting num1 or num2 to be null, we should be alerted when this happens. By catching it we will never know something unexpected even happened.

Right way to do it would be to only catch the expected DivideByZeroException & not others

Another thing to keep in mind is your try block should have as few statements & operators as possible. More the number of statements, less likely the exception occurred at the expected place.

So what happens to all the exceptions that we did not catch? Any unhandled exception will crash your application. Let our application crash!! Are you crazy? you may say, well craziness is a relative term 🙂 When an exception that we were not prepared for occurs, its better to let your app sink, than to let it continue in an unknown and possibly inconsistent state. But the same can be done gracefully.

All applications/processes/threads have start points, like main() is a start point, so if anything inside fails it cascades back to these start points, this is one place where we use a generic try...catch(Exception e) and in the catch, we should log the exception, and let the user know that the ship is sinking. It gets a bit tricky with multi-threaded applications but most of these do have some event to subscribe to unhandled exceptions, in case of threads one can create a utility method that creates threads, and hence this utility becomes the start point of all user-created threads, and the try...catch can be deployed here. Note that, in case of unhandled exceptions in threads, only that thread will die and not necessarily entire application, some special care may be needed

eg: Catching unhandled exception in main

eg: Catching unhandled exception in multi-threaded applications.
This is the simplest way of achieving a streamlined thread creation mechanism and hence handling any exceptions in the new threads, we just need to make sure that any new thread should only be spawned using this method

So what does all this give us? This helps us track down all unexpected behaviors a.k.a defects which may have been hidden due to the improper exception handling. These exceptions in the generic catch blocks are your symptoms to a bigger problem which is waiting to be solved by you, so go and gear up with your debugging hat and get started…

IMagic – The power of interfaces

This one talks about the power of Interfaces, and how polymorphism can make things highly flexible and decoupled. Interface is a simple view of your class-to-be to the outside world, a perfect form of abstraction. Wikipedia says

A protocol or interface is a common means for unrelated objects to communicate with each other. These are definitions of methods and values which the objects agree upon in order to cooperate.

Lets take an example for better understanding. Assume, I am creating my good old calculator again.

Being poor, I can’t afford any staff to work on my jazzy calculator. I have come up with all my classes and stuff, but can’t start working on my calculators logic, as my Calculator has an object of type DisplayPanel, and I will have to complete the implementation of this class in order to use it in Calculator otherwise my compiler will simply keep complaining and won’t let me proceed. But Calculator seems far more interesting to start with than DisplayPanel. So what do I do? You may say, I will write the DisplayPanel class and leave all the functions blank!! Smart 🙂 What about the non-void functions if any? You would return some random value based on the type of the return type of the function. Well, why do all this? I would simply go ahead and replace the type of UserDisplay from DisplayPanel with its interface (say IDisplayPanel).

Now, I can bindass go ahead and keep calling UserDisplay.Show(), without the trouble of keeping my compiler happy. This code will build with no compile errors, but will fail at run time since you can only call a function on a solid class instance, not interfaces. So how do I know if what I have written so far works or not? Well unit tests with mocking is the answer, I would like to defer this topic for a post in the near future.

After showing my Calculator idea to some biggy investors in the silicon valley, I manage to get funding to hire 2 assistants. Yippee, now I can get some work on the DisplayPanel started with their help. I assign this task to Bluto, one of my assistants. While my other assistant, Popeye, has no work for the time being and is enjoying spinach with Olive 🙂 Brutus thinks he has come up with an exciting implementation and even I have finished working on my Calculator

Time to merge the code gentlemen!

Scary??? No, all that we need to do is assign the UserDisplay to a concrete class, the one Brutus wrote, before I make any call to any of its methods. Best place is in the constructor.

Great !!! All works fine, but….. Brutus, as dumb as he is, came up with a very lame and irritating implementation of the IDisplayPanel, this one throws a big message box (IE Style) to the user with the content to display, that too every time I press any button on the calculator :'( !! Popeye, meanwhile knew how pissed I would be, and had already prepared another implementation that he was ready to show me. Better than I thought, a sleek panel on top of all my calculator buttons to immediately show what key the user presses and the result too. Yes, the windows calculator is a complete rip off of Popeye’s version. Wow!!! Totally wanted to get this into my production code. But code change again!!! Well this time it’s just a one line change, in fact half a line.

Hope the IMagic got through to you by now. Interfaces allow us to decouple our implementations. You are not bound to someone’s speed of coding. Before you get working on your code that uses someone’s code all you need to do now is just sit together, analyze and agree upon an interface that you both are comfortable with, and both can proceed peacefully and independently. Also, this allows easy migration from one implementation to the other, imagine if you had to change the implementation in case of concrete classes, you would change the body of all your functions, and if the new implementation turned out to be worse, you don’t even have the old code to rollback to, unless you have taken some backup, which again would be tedious to some extent. Here all you do is just change the constructor, and still both the implementations co-exist, this gives the user a choice as well.

Another, in my opinion more powerful, advantage that interfaces give, is when we are actually dealing with enterprise software that depend on third party pluggable code. (You may want to skip to the end, if you are an absolute beginner). In a more complex aka real-world application, you may not have all the code in the same file, in fact not even in same project. Here all you would have is the interface, which would generally be shared across projects. In such cases, your Calculator class won’t even know there is something called AwesomeDisplayPanelByPopeye, only the classes using this calculator may know about it. Hence your statement

Will give a compile error as the class AwesomeDisplayPanelByPopeye is not present in any of the referenced libraries. In such cases, or even otherwise, a concept named Dependency Injection comes into play. In our case, the Calculator is dependent on IDisplayPanel, we don’t want the calculator to decide which implementation of this interface to use, but let the user of the Calculator decide it instead. This is done in various ways, one of them is through the constructor. We remove the default parameter-less constructor, and instead use a constructor that takes an object of type IDisplayPanel, and assign this object to our UserPanel as follows.

Now, your code is truly agnostic of the implementation of IDisplayPanel that it will use. You can now have n different Calculators from the single Calculator that you wrote. Today’s world is all about choices, more choice you give, more people will use it 🙂

There are many more benefits of interfaces than what I tried demonstrating above. Hoping this helps you in writing better, reusable, efficient and beautiful code =D

OOPs………… !!!!

Most of us have gone through books with various definitions/introductions on Object Oriented Programming, these contain then-jargon like abstraction, polymorphism, inheritance, encapsulation, etc. in the very first chapter. How to easily understand all that when we are just starting? To some, it’s too much of spices when they don’t know what common salt is.

To begin with, all we need to know is a class. Class, in simple words is Kind or Family. Let’s say I have a calculator, I like to call it Jugal's Calculator giving a sense of possession. So now, we ask Jugal's Calculator is of what kind? The simplest kind we can identify without knowing the brand or functionality this calculator gives, would be of kind Calculator. It so happens that John Doe also has a calculator, which he calls JDC. From what we know, JDC also belongs to the family of Calculator. So here, Calculator is our Class and Jugal's Calculator & JDC, which are things of those kind, are called objects or instances of the class Calculator.

Object Oriented Programming, as name suggests, revolves around these things or objects that we just defined.

  • What (but not how) this object can do? (encapsulation)
  • What families does the object belong to? (abstraction)
  • What it is made up of? (composition)
  • Does another object already do a part of what I am supposed to? (inheritance)
  • And more complex (yet interesting) things like Polymorphism, etc

We have very loosely defined these terms for understanding purposes, the real meanings will be clearer as we get a better hang of their usages. I also like to call it Real-World Programming. RWP??? We create data structures/classes with the aim of having an analogy to the real world.

With all that said, let’s see how to create a neat class. Things we need to keep in mind are,

  • What will be the primary objective of the objects of this class?
  • What data will they need to have, in order to do these actions efficiently?

These two questions would allow us to define the public part of the class. I would love to use interfaces here, but want to keep things simple till we make them complex ;). If you think you know the answers to these two questions, think again =D.

So, if we have to design a very simple calculator, which even our great grandfathers might not use, what would be our class(es)? Let’s say, this calculator can only perform add and subtract.

And we are all happy? Not me. This wouldn’t be wrong or not serve the purpose, just that it doesn’t translate into the real world analogy concept. How many of you have a calculator that asks for the operator first (Add) and then the two numbers and gives the answer back to you? The way calculators work is to give first operand, give operator and then second operand and get the result.

Lets answer the first question.
Add? Subtract? Add & Subtract? I would say, the primary objective of the calculator is to simply Calculate!! Add & Subtract are merely types of calculations.

Now the second question.
It just needs two operands and an operator.

So now are we happy? I ain’t yet. This still isn’t real world. A calculator consists of buttons and a display. This is now real world. So we introduce two more types of objects, Button & Display. This is how OOP is supposed to work. Breaking down responsibilities and delegating them so you only do what is your primary role.

In this new approach, the user doesn’t actually interact with Calculator directly, it uses the buttons, which are part of the calculator. The user can press a button. In fact that is all the user can actually do 🙂 Making all the above class members (Operand1, Operand2, Operator, Calculate()) not directly accessible to the user. Thus, they would all become private and an array of Buttons would be the only thing public to the user. Each button would merely expose a method (say, Press()) for the user to interact. Also there would be DisplayPanel that user can view.

I will refrain from going into the implementation details and aim to highlight the process of coming up with the right classes and not implementing them.

A question may arise, that why not break up the Button or the DisplayPanel into smaller classes too? Yes, sure go ahead, but for the purpose of creating the class Calculator, we are only concerned about the Button and the DisplayPanel, that’s the beauty of abstraction. You are least bothered of the implementation. Calculator doesn’t care if the DisplayPanel consists of LEDs or Printer or whatever, it only knows that it can call on the method Show() with the string it wants to display.

This process may appear to be inundating at first but would come naturally, like any spoken language that you know, once put into practice. Also the real life correlation helps others to quickly understand your code and approach.

Mumbai Fighters v/s Devils of Terror

Nothing till now had made an impact as fierce as this one on me that finally forced me to punch in my first logical ( read not-bragging ) blog.
Yes, once again the financial hub of the country, the town where Bollywood resides, the city that never sleeps and my hometown – MUMBAI – has been targeted by the people who for some reason think that they can do anything they want and to whomsoever they want. It’s like not-so-hopefully an ever lasting battle of MUMBAIAITES v/s TERRORISTS in our home ground, which BTW Mumbai leads 3-0, yet they never seem to accept their fate. The first being the not-easy-to-forget “BLACK FRIDAY” 12th March 1993 where there were these series of bombings in Mumbai, that’s were it all started and these M****RFU*KING-TERROR-A**H***s got their morale from. Yet we, the citizens of Mumbai, managed to forget all that and continued living a peaceful life for a few years since then. But unfortunately just like us they also didn’t give up. And then a few years back again they struck back when a bus (I ain’t sure but I guess it was Route 340 ) was bombed in Ghatkopar and then later a train in Mulund and then another huge one. like the ’93 serial blasts, remembered as the Terror Tuesday or 7/11, yes it was 11th July 2006. its been branded on the minds of all the Mumbaikars those existed then, be it a 5 year-kid or a 90 year gr8-gr8-granpa of many kids.
All this being said and done, nothing has improved in Mumbai, at least not the judiciary or the security. Although as citizens we are more aware but the people who need to be the most aware and lead the city don’t seem to follow suit. The police force did catch hold of most of the criminals but after expectedly taking so many years, yet it turns out that they were not the slowest, the Apex Judicatory of the country handsomely took its time to do whatever it should not and not do whatever it should. All this giving rise to more and more encouragements to miscreants to bajaofay the country, saying come kick our butt and will give you the other cheek to kick as well.
And now today, 26th of November 2008, it is happening all over again … open firings at one of the world’s busiest railway station(CST), the heritage Taj Mahal hotel that Mumbai boasts of, the posh Oberoi(Trident) at Nariman, the Queen’s necklace, Colaba causeway… and so many more places. Imagine the extent of their fearlessness that they get into CST station with so many guns and start firing at innocent people and moreover escaping from there unhurt by all the RPF security on the station. For us to digest that incident they do a braver thing by hijacking a Cop-Qualis and start firing at people on the road including media people and people outside the Metro multiplex. And to top all this they occupy the biggest hotels of the city, the Oberoi and Taj. And take hostage of hundreds of people and put the Taj on fire. All this is continuing since the last 14 hours and still going on as I am writing this.
The basic motive behind this seems to be yet unclear. And this time around the terrorists ain’t any bunch of old guys who have lived their life enough and can take bullets to part from the world, but these are a few dozens of twenty odd year youths! Now just think when would they have started training for such a sure shot road map to death mission, 10 yrs or 14 yrs ?? quite possible.

Everything is not over yet, this will go on and on and on … until either we or they give up, exactly its a game of who gives up first… and looking at our opponents it doesn’t seem they’ll give up ever unless we show they what we can do by first of all avoiding such incidents and secondly in such cases no need of having a trial for them, just get all the info from them and hang them.
Enough of emotions from me for the day, I think have to prepare for my exams now 🙁 ain’t in any mood though. But one thing that’s positive from this is that the English Cricket Team has cancelled their current tour half way, giving our cricketers (may be BCCI won’t agree) a well deserved break.. But yes in the long run India’s situation might become like Pakistan where no one wants to go… Hope that never happens
RIP : All those who have been victims of such cruelties and those martyr policemen

My C Programs

This post is only for historical reasons, the owner of the concerned site, TechBirbal, has taken the site down and is no more operational


Some of My C – Programs [Courtesy WayBack Machine @]