Thursday, 31 October 2013

Of Systems and Designs (Non Technical)

Swami Gulagulaananda said:
"The ability to handle rejection is an important quality to have"

[I started reading this fantastic book called "Design Of Everyday Things" by Donald A. Norman. The book is highly recommended by the way. This post is inspired by the book. Let me start off by saying I am no expert - these are my opinions only]

Systems and Designs seem to be very technical words. But, to me, they are more like common sense. These days, that is... Actually, from yesterday, because I started reading this book and now I have suddenly become an expert in the area.

Driving in Bangalore is a pain, which most of you are aware of. But driving a car can get a little more annoying because of all the motorcycles that swarm around you. Motorcycles are inherently unstable and tend to move in unpredictable paths in excessive traffic. So a driver of a car has to be extra careful when he drives because he has to concentrate on a number of haphazardly moving vehicles on both sides. The following is a scenario I encounter almost everyday.

I am on the left because I want to turn to the left. However, there are motorcycles that want to go straight but don't find enough space on the right side. So they creep in the space between my car and the pavement and go ahead. This is particularly annoying when I am turning to the left because it is idiotic of him to come in that space.

But it happens. Invariably... Every single day...

How do you fix this? Simple, educate everyone. This is not really as simple as it sounds. One, because it is an extremely time consuming task. Two, there are always idiots who will do it. To rely on the intelligence of people, therefore, becomes difficult. To fix this, we need to come up with systems.

A good system, according to me, is something that is idiot-proof. Something that should become impossible to break. My solution to this particular problem, that I have been effectively using everyday, is to drive very close to the pavement, so close that all hopes of finding subatomic spaces between my car and the pavement are completely eliminated. I have seen motorcyclists trying to sneak into small spaces and I cover even that area till they give up and wait. As you can notice, it is sheer impossibility that prevents any attempts.

One of  the nicest things I like is the Sim card design - If you observe a sim card, it has a small inclined cut on one of the corners. This makes it possible to insert a Sim card in only one way. Any other way, the card simply gets rejected. Norman gives the example of the floppy disk which also follows a similar principle. There can be only one way to do it - therefore, it becomes impossible to screw things up. Now think how many times you have messed up inserting your pen drive into the USB slot - I hate putting it in the wrong way, flipping it around and trying again. And think how your laptop charging points are designed and your mobile phones... Either universal or only one way.

I have a similar watch. It shows time (Du'h). It also shows the date, day and has a stop watch feature. So naturally all of these are settable. A frequent problem that analogue watches have is the 30-31 day problem. When a month has 30 days, on the first of the next month, the watch still shows 31. So I need to increment the date. Alright... We understand the problem. Now, how do I do that?

I know I can set the time, the date, day, start and stop the stop watch, reset the stop watch and also tweak the starting position of the stop watch. It has 3 controls on the right side - 2 buttons and a standard screw. The button on the top is used to start and stop the stop watch. The other button is used to reset the stopped stopwatch. Everybody knows that the screw is used to set the time. How? Well, obviously you pull it and turn it and push it back. Great! But how do I set the date and day? The screw can be pulled a little and all the way. Pulling it a little bit and turning it around sets the the time and pulling it all the way is for setting dates... Or vice versa, I can't remember. But which way should it be turned for the date? And which for the day? I can't remember. Does it mean I am an idiot? How do I manage it? You might have guessed it because you think it is obvious - Trial and Error. You pull it half and turn the screw a little bit and see what happened. Did the minute hand move? Ok, wrong level. Pull it all the way and slowly turn it. Did the date change? Great!! If you didn't want to change the date but you did it anyway, you have to rotate it 30 more times!!

You see, the system is allowing me to do as I wish - and so mistakes happen. And that happens because of an improper design. Which direction to turn to change the date or how much to pull to change the time, are not based on anything logical or natural. They are completely arbitrary. Arbitrary things are naturally difficult to remember... That's why people come up with mnemonics and associative memory techniques to remember arbitrary things. Another fantastic book to read is 'Thinking Fast and Slow'. So, to summarise, in this case, this watch is a flawed design. Anything arbitrary is wrong.

I had another funny experience - My friend Mayur got a new fancy pen. I asked him to show it, and I tried to pull what appeared to be the cap to see it. The moment I began, he said "Hang on, hang on, that's not the way..." and pressed it. Think about it - How difficult is it to use a pen? :P But you have gone through this before too. The classic Reynolds 045 ball point pen, for example, is impossible to mess up. Some fancy pens look like you have to do something else, but actually you have to do something else. Which is weird... and flawed.

This is a technical paragraph - feel free to skip... Amod and I had a bad experience when we started learning jQuery. On click of a button, we would clear a div, make an ajax call and create a table html structure and populate the div by using jQuery append. Okay, we know it's wrong to do such things now and use more elegant ways, but we were beginners then. If a person pressed the button once, the code worked fine. But what happens if a person presses the button twice? Ajax being asynchronous resulted in the div getting cleared for each click once, ajax calls being made and the responses of both getting appended, which means, two tables got appended. Clearly wrong. You can argue and say - Don't press  twice. But that's not the point. The design is flawed and  the system is wrong. To avoid it, either fill entire html (use html instead of append) or disable the button till the callback is completed...

To summarise, designs and systems should inherently avoid mistakes from being made. I am no expert in the field, I was just excited to share these views and recommend the two books to everyone.

Saturday, 26 October 2013

Of Random Seeds and Other Random Bits

Baba Gyani Triviani said:
"If you believe in fate and destiny, then the randomness in this world is pseudo-randomness"

Random Number Seed
I am sure most of you would have used a Random number generating piece of code in your program at some point of  time or another. And when you were looking up code, you would have noticed the word 'seed' but would have ignored it. Some of you would have even noticed a word called pseudo-random number generator. Well, I did. And I didn't know what this seed was until a few days back.

Let's try out an experiment. I will use Python in this post, but you can use any other language - Java, Ruby and they will all behave in the exact same way.
>>> import random
>>> random.random()
0.23108685984562283
>>> random.random()
0.017276293409835386
If you try this piece of code on your machine, your results will be different from mine. Isn't that obvious? It IS a random number generator after all, you might say. Now let's do something a little different. Try out the following code...
>>> import random
>>> random.seed(5)
>>> random.random()
0.6229016948897019
>>> random.random()
0.7417869892607294
The only difference is  that I have written an extra line with seed and I am passing 5 as the parameter. If you try out this piece of code now, you will see that the random numbers that you are getting is the same as what I am getting. ! So that means that random numbers are not as random as we think they are. You can try by opening another terminal and issuing same commands and your results will match.

Variable arguments in Javascript
Most of you are familiar with varargs - If you want a function to accept variable number of arguments,  you use the standard ellipsis notation - works in C, Java... But does it work in Javascript? No. So how do you do it? I was browsing through Coffeescript and I noticed the varargs ellipsis notation. On checking the generated Javascript code, I noticed something interesting.

So this is what you should try. Fire up your console in Google Chrome and type the following:

function test() {
   console.log(arguments);
}

test('hey');
test('hi', 'hello', 'howdy');
test();

And the outputs are:
["hey"]
["hi", "hello", "howdy"]
[]

As you can see, though the function test doesn't look like it is accepting any arguments, arguments can be passed and accessed using a special 'arguments' variable. It is basically an array and you can use it to check if arguments were passed or not, how many were passed and which argument is what. Fancy, huh?

Closures in Javascript
Apparently, to be called some kind of an expert in Javascript, you should be able to talk intelligently about Closures. For a long time, I used to stare blankly at the word. Eventually I decided to see what all the fuss was about. 

But before I tell you what closures are, I wanted you to know this simple piece of code. If you know it, go ahead. Otherwise try it out. Functions in Javascript can be written in two ways:

function sayHello(name) {
   console.log("Hello " + name);
}

sayHello = function(name) {
   console.log("Hello " + name);
};

Both work - The difference is that, the first one is available the moment your scripts begins to execute, the second one is available only after that line gets executed. What it means is that, I can call sayHello in a line that precedes the actual function definition in the first case. However, if I write it in the second way, it is available only after that line. An attempt to call it before will make your program to crash out - You are attempting to use it before defining it.

The advantage of the second style is that you can change the entire function behaviour but retaining the same name. Here's an example:
chameleon = function() {   console.log("I am green in colour");}; 
chameleon(); 
chameleon = function() {   console.log("I am brown in colour");} 
chameleon();
As you can see, the functions entire behaviour changes. This happens if you define it in the other style as well, but since this is like a variable, you can use this style to accept functions that get returned from other functions. The following example clarifies this point while also explaining closures.

So here's a simple example for closure.
function outer(x) {
    this.x = x;
    return function(y) {
        console.log(x + y);   
    }
} 

a = outer(5);
b = outer(10);

a(10);
b(10);


So essentially, we have a function called outer that accepts one parameter - x, and it returns a function (That's one feature I love about JS - the ability to pass functions around like any other variable). So, a and b will store the returned functions. But these two functions are not exactly identical. Since the 'x' parameter was different, the 'x' inside the returned functions are different too. To clarify, the 'x' inside the console.log gets hard-coded to whatever was passed - 5 for the a, 10 for b.

So when we call a and b with 10 as argument, the sum becomes 5 + 10 = 15 for a  and 10 + 10 = 20 for b. That's how you can a single function to behave differently depending on arguments.

Object oriented programming in Javascript
I thought of writing a bit about prototypes here - but then I thought that, rather than doing that, you should give CoffeeScript a chance. It's very easy to learn and you can do things in a better way. Like class definition is much cleaner in it and it takes care of the dirty work behind the scenes for you. It eventually generates Javascript and you don't have to worry about it.

Sunday, 20 October 2013

The (fake) Quest To Eradicate AIDS with Mythical Mystical Indian roots

Swami Gulagulaananda said:
"When in a game, play..."

I have won several lotteries organised by Shell, Coca Cola and other companies. Each prize was no less than 500,000 GBP. And I have also been fortunate to share my surname with super rich heirless millionaires, facilitating unscrupulous lawyers to wire their enormous funds into my account so that I can send them their share for making it happen. Considering the number of lotteries I have won and number of inheritances in my name, I am richer than Bill Gates ten times over.

But alas, we are aware of how scams work. Some of us, at least. So I continue to be penniless as before.

Recently, I got an email - The brevity of which prompted me to reply, and then began an interesting conversation.
from: Robert Adair
to: r-adair@hotmail.co.ukdate: 17 October 2013 21:29subject: Your revert awaited
having a proposal to discuss with you
To which I replied, with equal conciseness...
Regarding what
And I got a reply to that...
from: Robert Adair
to: Nikhil Baliga
date: 18 October 2013 13:42subject: RE: Your revert awaited
I am Robert Adair from the United Kingdom.There is huge demand for Indian herbal roots in my company
presently. My Boss is desperate in need of the roots for Pharmaceutical productions even
willing to buy at a higher rate. He is ready to send a purchase officer to meet the seller in
India,to receive this product and pay instantly.
But due to my interest in the business,i don't wish to reveal the real seller's contact to my
boss. Hence,I am soliciting your help to stand as a middleman to do this business on my behalf
and the profit would be shared between us. Profit will be healthy in this deal.
For further detail about the business,kindly reply
Sincerely,Robert Adair
Healthy profits. Time to pretend to be a sucker... but a cautious one. We don't want to set off any alarm bells. So I replied...
Sure, it sounds interesting. It'd be great if you can provide more information.
So he sent me his business proposal. It might be a little long to read, but I think you should quickly go through it. Just for kicks... (There's a tl;dr at the end of the mail for the lazy ones)
PURCHASE OF ANTI HIV/AIDS RAW MATERIAL EDUIN SALVE  ROOTSAttn. Sir,I am a foreign purchasing Manager/Pharmacist to the above mentioned company; a subsidiary of Shire Pharmaceutical Limited UK.I got your contact from the internationalbusiness directory out of desperate search for a reliable and abusiness minded person in your country for a mutual and urgentbusiness transaction requiring maximum confidentiality and trust,hence I am contacting you. I and my Regional director use to visit your country India for the purchase of the above mentioned HIV EDUIN SALVE ROOTS . The botanical name of this Raw Material is  Eduin Salve Herbal Roots This Eduin Salve Herbal Roots raw materials used for the preparation/manufacturing of ANTI HIV/AIDS drugs in the United Kingdom . I wish to seek your cooperation in having an alliance with you in the outright purchase of these raw materials from the original seller in your country, and resell to our company. This seeds is sold at the rate of ($1,800.00) per packet. The seller of this seeds is a citizen of your country India .We have come to purchase these raw materials from him in several occasions. I will want you to be the middle man between the original seller of this products and my company. Where by you will purchase these products from the original seller at the rate of ($1,800.00) per a packet and resell to our company at the rate of ($3,150.00) as against($2,400.00) per a packet which we normally buy the products from the former middle man who has never kept to our sharing agreement. The over inflated profit that is added to it will be shared by both of us. That’s you will have 60% while 40% will be for me. This over inflated profit shall be calculated on the basis of the number of packets that you are able to supply us for purchase in any of our trip to India . I shall give to you my bank account details where you will send in my entitlement.Please NOTE that my regional director will not make any payment to you without seeing the products with you due to past experience. That’s you are going to make the out right purchase of these products from the original seller and resell to us when we must have finish discussion with you on our arrival in India. The payment is usually done on Bank to Bank transaction or cash in hand. That’s after seeing the number of packets supplied by you and the total amount calculated; we shall immediately proceed with you to our nearest correspondent Bankers trust here in India for instant payment into your account. We will be able to make any payment to the tone of the number of packets supplied to us on our arrival. I shall give to you the direct contact of the original seller for you to make enquiries about these raw materials after you must have given me your consent in this proposal. I will also give you details on how to contact my company officially over these raw materials and the new price of $3,150.00 per a packet after you must have concluded with the original seller. Because my company also serves as a distributing company of this products to some other companies in United Kingdom . All other information shall be given to you when you must have agreed to handle this proposal with utmost confidentialityFor your fullest cooperation, hoping to hear from you in a soonest possible time.Contact Number +448719746257   Regards,Mr Robert Adair
tl;dr: Guy says there're some roots that he wants me to purchase for $1800 and sell it at $3150. The profit is divided between me and him in 60:40 ratio. I have to pay upfront. His boss is clever to not pay upfront.

I am a poor average person from a third world developing country. Can you expect me to have $1800? So I ventured...
Hi Robert,

Thanks for the explanation. The deal certainly looks exciting and I am interested to pursue this offer.

However, $1800 is a lot in Indian Rupees and I don't have that much liquid cash to purchase the packets. I understand from your mail that your regional manager is not willing to pay the money upfront. However, since you and I are going to be business partners, I'd like you to transfer the money to my account. In return of the trust that you display, I am willing to share 50% of my profit, thereby giving you 70% of the total money. So rather than a 60-40 arrangement, it becomes a 30-70 arrangement.

I am really looking forward to hearing from you.

Thanks and Regards,Nikhil Baliga
I tried to be smart, huh? I wanted to see how he would evade it. But the tenacious little bugger played the sick card (What's next, dog ate my homework?) He replied thus, and in all caps:
THANKS FOR YOUR RESPOND I HAVE TO ENLIGHTEN YOU MORE ABOUT THIS BUSINESS TRANSACTION, THIS BUSINESS IS BUYING AND SELLING BUSINESS. YOU ARE TO BUY FROM THE INDIA DEALER AND RE-SELL TO THE COMPANY. SHIRE PHARMACEUTICAL LIMITED UK . THE COMPANY WILL BE SENDING THEIR SALES REPRESENTATIVE TO INDIA TO PURCHASE THIS PRODUCT,MIND YOU I HAVE A PARTNER IN INDIA BEFORE HIS NAME IS MR. PRADEEP GUPTA , HE BETRAYED ME IN THE BUSINESS AFTER SOME TRANSACTION, THAT IS WHY I REALLY NEED A GENUINE AND RELIABLE PERSON. MR. PRADEEP GUPTA , AFTER THE TRANSACTION HE DID NOT SEND MY OWN PERCENTAGE TO ME ACCORDING TO OUR ARRANGEMENT. NOW THE COMPANY HAS TOLD ME TO SUPPLY THE SAME PRODUCT AGAIN, I NEED SOMEONE WHO IS TRUTH WORTHY SO IF YOU KNOW YOU CAN HANDLE THIS TRANSACTION FOR ME WITHOUT ANY DOUBLE MIND I WE BE GLAD TO RECEIVE YOU AS A PARTNER. (2) I AM BRINGING THIS TO YOUR KNOWLEDGE THAT I DON'T WANT THE COMPANY TO KNOW THE DEALER OF THIS PRODUCT TO ENABLE US REMAIN AS THE SUPPLIER OF THE MATERIAL. BECAUSE IF THEY KNOW THE DEALER OF THE PRODUCT THEY WILL BEING GOING DIRECTLY TO THE DEALER TO BUY THE PRODUCT. I SUPPOSE TO COME DOWN TO INDIA BY MYSELF TO BUY THE PRODUCT BUT BECAUSE OF THE ACCIDENT THAT KEEP ME IN THE HOSPITAL BED. THIS THE REASON WHY I NEED SOMEONE IN INDIA WHO CAN HANDLE IT FOR ME. (3)AND ALSO YOU DO NOT NEED ANY LICENSE TO DEAL ON THIS RAW MATERIAL.BECAUSE A LOT OF ORGANIZATIONS ARE LOOKING FOR GOOD WAYS OF ERADICATING THE EPIDEMIC OUT OF THE GLOBE WORLD BECAUSE OF ITS DEADLY NATURE. SO PEOPLE THAT DEAL ON THIS MATERIAL ARE RESPECTED PEOPLE IN THE HEALTH WORLD.THAT MEANS THE BUSINESS DID NOT REQUIRE LICENSE BECAUSE THE COMPANY SALES REPRESENTATIVE IS COMING TO INDIA TO BUY IT FROM YOU. AND THEY ARE COMING WITH CASH MONEY. YOUR COMMISSION SINCE YOU ARE THE EXECUTOR YOU WILL TAKE 60% FROM THE PROFIT AND I THAT INTRODUCE YOU TO THE BUSINESS WILL TAKE 40%.SO ACCORDING TO YOUR QUERRY IN YOUR PREVIOUS MAIL, ONE PACKET CONTAINS 10SATCHETS AND ONE SATCHET IS 5GRAM SO 1PACKET IS 50GRAMS SO PLEASE DO LET ME KNOW IF YOU CAN HANDLE IT. TO ENABLE ME TO GIVE YOU THE INDIA DEALER CONTACT. PLEASE YOU ARE TO PROVIDE ME YOUR DETAILS. FULL NAME:PARTNER NAME IF ANY. NACOMPANY NAME:HOUSE ADDRESS:A COPY OF YOUR I.D CARD OR DRIVING LICENSE.CONTACT NUMBERREGARD.ROBERT ADAIR

Somehow the mail made me scroll to the bottom looking for "I agree with terms of license" button. So I have now decided  to reward his efforts. I played the fool card thus...
Hi Robert, 
   Thanks for the explanation. I understand from your mail that you are looking for a trustworthy and reliable business associate. I can assure you that I will not betray you like Pradeep Gupta. Please send me the details of the supplier from whom I have to purchase the boxes and number of boxes that you would like me to purchase. Once I have purchased the boxes, I will get in touch with you. Can I use my credit card to make the purchases? 
Thanks and Regards,
Nikhil Baliga
The reply came as expected.
SO PLEASE DO LET ME KNOW IF YOU CAN HANDLE IT. TO ENABLE ME TO GIVE YOU THE INDIA DEALER CONTACT. PLEASE YOU ARE TO PROVIDE ME YOUR DETAILS.
FULL NAME: 
PARTNER NAME IF ANY. NA 
COMPANY NAME: 
HOUSE ADDRESS: 
A COPY OF YOUR I.D CARD OR DRIVING LICENSE. 
CONTACT NUMBER 
REGARD ROBERT ADAIR
What do I do next? Any suggestions? I was thinking of creating a fake profile and sending all this fake information to him with a well photoshopped fake license or something.

Some salient points to observe:
  • The plant that he mentions is not the scientific name of anything. Google searches resulted in nothing relevant. In fact, it sounds like a Marathi surname :P
  • For a Brit, the quality of his English is dropping like crazy with every other mail.
  • Replies look like standard templates. There is a disconnect between my mails and his replies
  • Identity thief, drug dealer or plain scamster?
  • And no, I am not jobless. I am just trying to get some kicks and also understand the modus operandi. But it's mostly for the kicks