Archive

Archive for the ‘Technology’ Category

Yahoo! Open Hack 5 – The Experience

August 25, 2012 Leave a comment

Before we even start, here’s the idea which we hacked up during the 24 hour contest timeline. Brand horizon – When all the social media focuses on the count of re-tweets or share (or whatever they’d like to call it) None of it actually gives you the count of people your product update reached out to. That particular missing link is what addressed in Brand Horizon is. It’s not actually how many shared your update, rather it is who shared your update. The most influential person’s share would spread the word faster. You hit the right nerve, you get the information across faster.

Well before the event:

After Yahoo! Open Hack 4, the expectations were really high for the next edition. The two day weekend at The Lalit Ashok Palace Bangalore during July 2011 hiked up the anticipation for this one. The date was fixed for August second weekend at The Sheraton Bangalore. Two weeks prior to the event, me and my co-hacker came up with countless suggestions for the hack we were about to build. Some of it were: Rupyaa++ – a social media based money management tool which would help you split up the costs of a group hangout or a trip. TwitVote – a voting system with crowd sourced data from twitter. A sentiment analysis based system which gives you a pulse of the crowd’s thought over a given subject. We even came up with some fun hack ideas – A guy-bot who changes his emotions based on tweets he receives and a Guess-the-movie-based-on-its-quote site.

Just before the event:

As the event neared, the official categories for the hacks were published as: Digital Communications, Digital Media & Advertising, Multi-media Experiences and a wide bucket category called “Surprise Us”.  The last one was quite tempting. Although we chose to take the defined category of Digital Media & Advertising and that’s when we brought the idea of Brand Horizons to the fore.

The event:

Like any of its precedents, fifth edition had all the usual elements: Swanky hotel, Yahoos, A huge crowd of eager developers and none other than Anil. He’s Yahoo’s secret sauce when it comes to YDN and developer engagement. After the usual sessions from Murray, Saurabh, Jai – we drove straight into the hack and started with our product. We learnt a lot from our mistakes at YOH 4 which we vowed not to repeat this edition.

The Issues:

Well for starters, the WiFi gave away and we lost precious time after the 24 hour countdown started ticking down. Those wonderful Yahoos wracked their brain to help us connect, but our laptops just wouldn’t give up and connect. Next, once we started querying Twitter through YQL console we never got what we wanted. Turned out, due to multiple pings to Twitter APIs through YQL, Twitter blocked YQL. So our original idea of mashing up data from Twitter and Facebook was given up and the product specifically focussed on brands based out of Twitter. The last one was, neither of our team members, knew in-depth PHP. So we had to struggle overnight to complete the app which required a good use of OAuth.

Panel Evaluation:

The 24 hours counted down to 00:00:00 and we wrapped up our hack with a good description, a screencast on youtube. We were given the first slot for presentation, yay! And We were ready for the panel evaluation.  Our panel was of 3 judges with one extra time-keeper. We were offered strictly 2 minutes with 90 seconds for the demo and 30 seconds for any Questions from the judges. The key person on our panel was Shouvick and was indeed a pleasure to see our product examined by an industry leader.

The presentation went well although sadly for a remark that the prototype was constrained just to Twitter and there were other competitors like TweetReach with similar ideas. This gave a clear idea that our prototype didn’t make the cut, Nevertheless we were satisfied we could come up with a complete working prototype in under 24 hours.

The actual winners:

The final few hours of the event were made of the very popular open bar, and the presentations from the selected hacks. As remarked by one of the judges, not all ideas were worth selling but only a few were. And those were the ones which made the cut. Later that day, saurabh announced the winning hacks through the YDN website Brock, vibration reduction, pictrends, i am bored, bookmafia, beamOS. All deserved the accolades. It was a real experience into the world of startups where in a simple idea turns into something worth making money out of!

 

Creating a smoke using Particle System in Silverlight


Here’s what we’re trying to achieve: demo

One of a fellow programmer came up with a question of “How do you create Smoke effect using Silverlight?” Well there may be plenty of code, third-party tools and plug-ins strewn over the internet for this, but out of a professional curiosity I got into the business of creating one out of my own hands.

The whole concept of creating smoke (without fire ;)) can be done through what they call as Particle System. It’s a technique where in you employ very small graphical objects in large numbers to simulate effects like say Smoke, Fire, Snow, Dust, etc…

We need the smoke to be moving freely, so a canvas would be a best bet for the layout.

<Canvas x:Name="myCanvas" Background="White">
</Canvas>

From this point on the rest of the Smoke effect would be programmed in code behind file (C-Sharp in my case)

Let’s think a minute about smoke, shall we? Smoke starts at a point, very concentrated (Generation Point). According to the complex laws of physics, it simply rises up becoming dilute all the way. Finally blending well with the air where it seems to disappear (Vanishing Point).

Smoke

Understanding the dynamics of smoke

Our approach would be to consider smoke as made up of small particles, which would originate at the Generation Point. These particles as time passes would simply rise up, becoming transparent by smaller percentages as it goes and finally becoming invisible at the Vanishing Point.

These particles are going to be ellipses. Let’s have a method which does just that.

public static Ellipse createEllipse()
{
Ellipse objEllipse = new Ellipse();
//Smaller sized particles
objEllipse.Width = 1;
objEllipse.Height = 1;

//Giving the particles a Smokey look
RadialGradientBrush rgbObj = new RadialGradientBrush();

GradientStop gsObj1 = new GradientStop();
gsObj1.Color = Colors.Transparent;
gsObj1.Offset = 2;
GradientStop gsObj2 = new GradientStop();
gsObj2.Color = Colors.DarkGray;
gsObj2.Offset = 0.5;
GradientStop gsObj3 = new GradientStop();
gsObj3.Color = Colors.Black;
gsObj3.Offset = 0.001;

rgbObj.GradientStops.Add(gsObj1);
rgbObj.GradientStops.Add(gsObj2);
rgbObj.GradientStops.Add(gsObj3);

objEllipse.Fill = rgbObj;

//Set the position of the ellipses to the Generation Point
Canvas.SetTop(objEllipse, 300);
Canvas.SetLeft(objEllipse, 150);
return objEllipse;
}

While the Silverlight application initializes, we’d simply call the following line to add a new smoke particle:

myCanvas.Children.Add(createEllipse());

Well, this is just one particle. By every tick of the clock, new particles should be generated to give the effect of the smoke billowing. This calls for a DispatcherTimer instance which would give me an event for say every 2 millisecond.

System.Windows.Threading.DispatcherTimer timer = new System.Windows.Threading.DispatcherTimer();
timer.Interval = new TimeSpan(2);
timer.Tick += timer_Tick;
timer.Start();

At every tick, we need to be doing a set of tasks based on a few decisions.

Firstly, we cannot afford to overload the memory/screen with infinite number of particles. When a smoke particle simply disappears beyond the vanishing point, we can move them down to the generation point and reuse them. For this purpose, let’s have a limit of 1000 particles that can be freshly generated. If the screen has less than 1000 of them, we can go ahead and generate a new one.

if (myCanvas.Children.Count < 1000){
generateFireParticles();
}

Secondly, at every instant – *all* the smoke particles should perform the following tasks:

  • Rise up
Canvas.SetTop(item, Canvas.GetTop(item) - 1.25);
  • Grow and become lighter in visibility
item.Opacity = item.Opacity - 0.009;
item.Width = item.Width + 0.075;
item.Height = item.Height + 0.075;
  • And take a wavy path up. Smoke particles take a simply chaotic path up, they just don’t go up in a straight line.
Random randObj = new Random(10);
Canvas.SetLeft(item, Canvas.GetLeft(item) - (Math.Pow(-1, randObj.Next(5)) * randObj.Next(2)));

Thirdly, Move every vanished particle back to its original point.

if (item.Opacity < 0.0001){
item.Opacity = 1;
item.Width = item.Height = 1;
Canvas.SetTop(item, 150);
Canvas.SetLeft(item, 300);
}

So, considering all above, my timer tick event would look like this:

void timer_Tick(object sender, EventArgs e)
{
if (myCanvas.Children.Count < 1000)
{
generateFireParticles();
}
foreach (Ellipse item in myCanvas.Children)
{
if (item.Opacity < 0.0001)
{
item.Opacity = 1;
item.Width = item.Height = 1;
Canvas.SetTop(item, Y);
Canvas.SetLeft(item, X);
}
else
{
item.Opacity = item.Opacity - 0.009;
item.Width = item.Width + 0.075;
item.Height = item.Height + 0.075;
Canvas.SetTop(item, Canvas.GetTop(item) - 1.25);
Canvas.SetLeft(item, Canvas.GetLeft(item) - (Math.Pow(-1, randObj.Next(5)) * randObj.Next(2)));
}
}
}

Thus, was how we can generate a smoke effect in Silverlight using Particle System. With a minor change in the color and nature of the ellipse, you can create Fire or other similiar effects.

Suggestions welcome from expert readers on alternate or even better ways!

Online Identity Explosion – Securing your identities

March 4, 2012 2 comments

Firstly, be it a tech-savvy or be it a normal person, everyone has a life online. Here online, I refer to the internet and the myriads of websites there in. Programming forums, healthcare, lifestyle, romance, banking, travel, blogging, electronic mail, ecommerce; these are just few of the categories that pop in my head when I think of what we do online.

Let’s do the math. Each of these categories has at least n different websites/vendors associated with it. Say, electronic mail – you have Gmail, Hotmail, and MSN and so on. Take for instance ecommerce, you have Amazon, e-bay, or may be even the flip kart. Each of these require you to register and have an identity (username and password) associated with them.

Normally you choose to have the same username with all of them. But the rules vary with many, some allowing symbols, some disallowing numbers – you are forced to vary your usernames with the websites. And same is true for passwords – One of your comfortable passwords might be unacceptable by some accounts. Some websites have to be associated with email identities. If you took to internet after Gmail came in, then chances are you’ve associated all your email accounts with it. If otherwise, you might have had a host of other email accounts like, yahoo.com or live.com.

Now each identity needs a password. Let’s see.

1.       You can use the same password for all your accounts.

      Great choice. Allows you to remember a single password for all your identities. But this leaves you at a risk. One of your accounts gets hacked into, and you lose across the board.


2.       You use a new password for each of your accounts.

      This reduces your vulnerability to a hack. Even if one of your accounts gets compromised, you can save all your rest. But that gives you N passwords for n accounts you hold. Mighty hard to remember isn’t it?

Good online behaviour states, you cycle your passwords at least every 45 days to prevent your accounts from getting compromised. Now how do you do that, without having to go through the trouble of remembering the new sets of passwords again?

This discussion did not mention, ghost accounts (which you have probably false identities), intranet accounts (which are not under the internet category – but still requires a username/password and hence a necessary payload on your brain)

IMO, this seems to be a pretty interesting and wide area for research. If necessity is the mother of invention, this is the right time to invent, discover or re-discover a cost-effective solution that is within reach for a normal internet user. A normal user is right now juggling with at least 10 online accounts in his hands, forgetting passwords every 10 days, clicking on that seemingly helpful “Forgot your password” link. Or an unassuming user is in a false-sense of assurance having a same password for all his online accounts, screaming to be hacked and compromised.

The solution being proposed for curbing online identity explosion should provide, a way to access all your online accounts in an easier manner, while ensuring that:

  1. Safety of the identities are secure against any forms of hack
  2. Solution is accessible to nay web user – with minimal or zero-overhead
  3. Various modes of access are addressed – Mobile, single point of access, multiple point of access

Extending Internet Explorer – Scenario based overview

February 6, 2012 Leave a comment

For one of my projects, I was working on a minor enhancement. The project was web-based and as per client’s requirement, run only on Internet Explorer. The enhancement was related some data input page but access to any part of the site was restricted by a Login page.

The login page, as like any, consisted of a very minimal input – the username and password. But any change or recompiling on the site made me go from the login screen. Since it was a pretty old (almost a decade), it never had or no one bothered to put a “Remember me” check box. So logging in through the main screen was pretty customary.

I quickly considered the other alternative of hardcoding the values into the code, or at least till the release was made. But the idea of making temporary fixes to code for my pleasure nauseated me immediately.

What I was looking for, was a very efficient way to give me a quick form fill feature on the browser without having to mutilate the project in any possible way. May be Internet explorer had an option of extending itself! Fortunately it did and I finally figured out a way to do exactly that.

What would be the outcome? The outcome of this simple hack procedure would provide me with a new item on the Right click menu on Internet Explorer. On clicking upon such menu item, the fields on my form (website) would be auto filled with pre-set values.

Where all can I apply this hack? This procedure would specifically suit Internet Explorer browsers of versions anywhere in 6, 7 or 8. Although this has not been tested on very recent releases of Internet Explorer. If you’re using browsers like Chrome you have other ways of extending the browser functionality, this is just for my fellow developers like me who have no other browser to turn to except IE.

Can we get on to the hack already? Yeah sure.

All I need for this hack would be:

  • A registry entry
  • A simple javascript function

Registry entry: The whole purpose of the registry entry is to add the menu item to Internet Explorer’s context sensitive menu. As far as my knowledge goes, there isn’t a straight way of doing this than to go for a registry edit.

Warning: This section involves a registry edit. Altering registry settings without proper care might render the operating system useless. Kindly ensure necessary precautions before proceeding. Hazmat suits advised. Alternatively, you can visit this link to back up your registry settings.

  1. Enter regedit in your run command prompt.
  2. In the registry editor, navigate to the following tree-child.
  3. HKEY_CURRENT_USER\Software\Microsoft\Internet Explorer\MenuExt\
  4. Create a new key under this tree element, by any name “XYZ” of your choice.
  5. Under the registry item “XYZ”, add the following String Values as below:
  • String Value: CLSID
    • Value: A guid like {1FBA04EE-3024-11D2-8F1F-0000F87ABD16}
    • PS: You may use any GUID generator to get such a string
  • String Value: Menu Text
    • Value: My Menu Extension
    • PS: This text would appear on your Internet Explorer context sensitive menu.
  • String Value: Exec
    • Value: Path to the HTML file, you’ll be coding in the next section.
    • Example – C:\MyFolder\MyFile.html

JavaScript function:

  1. Place a simple javascript code to do the job of the form filling in a html file.
  2. Copy the location to this html file and place in the above registry item’s, Exec value.
  3. Restart your internet explorer
  4. Navigate to your page, a right click on it – you must see “My Menu Extension” on the right click menu.
  5. Click on it to perform the tasks you’ve coded in the javascript function. Or in this case, it would fill two textboxes txtUserId and txtPassword with corresponding values.
<Script language="JavaScript">
var parentwin = external.menuArguments;
parentwin.document.forms.txtUserId.value ="UserName";
parentwin.document.forms.txtPassword.value ="Password";
</Script>

Well, that’s how I solved my requirement with a simple concept of extending Internet Explorer. The possible areas of further work I looked into were

  • Filling huge web-forms (repetitive tasks) for let’s say testing purposes with the ease of a right-click menu item
  • Automating using a excel macro to create the registry entries and their corresponding javascript function for different sets of values provided. Basically abstracting the user from the nitty gritties and allowing him just the final piece of cake.

For a very detailed look into various customizations on Internet Explorer, check this link

Regular Expressions – String manipulation simplified

February 1, 2012 Leave a comment

Regular Expressions are an amazing way to go. A regular expression (regex or regexp for short) is a special text string for describing a search pattern. You can think of regular expressions as wildcards on steroids. Almost all languages support them and with a little understanding, you can ace at them. What more, they condense tens and thousands of lines of logic into just a couple of simple lines. I’ve used regular expressions both through .NET framework and in JavaScript and found them to be immensely helpful. This blog post focuses majorly on them and here’s a little outline on how I’ll be approaching the concept on hand.

  • A problem –  We engineers are problem solvers, so a simple problem followed by how regular expressions solved it in an even simpler way
  • Dissecting the solution – An understanding of the above simpler solution
  • Link to raw regular expression resources – Unless you can make up some of those regular expressions, you can never make it easier to use this language feature
  • RegEx class – The power of RegEx in .NET framework, what all you can achieve

Starting with this, followed by that, then this and then a dozen of that – A Problem!

I was given, the below problem statement and a laptop to code and solve. Developer instincts are hard to ignore and eventually I started scribbling off an elegant algorithm, or so I thought.

Domestic passport numbers either begin with the letter TW followed by 12 digits, or begin with 6 digits followed by 4 other characters and ending with the letters OFTW.

Pseudo logic:

  1. Is Starting With TW?
    1. Are the remaining 12 characters – digits?

i.      Return “Domestic”

  1. Is Ending with OFTW?
    1. Does it begin with 6 digits?

i.      Return “Domestic”

  1. If all above fails
    1. Return “Foreigner”

So with all the code logic and intricacies figured out, I exactly translate the pseudo code to C# code:

public bool IsDomestic(string PassportNumber)
{
if (PassportNumber.StartsWith("TW"))
{
string Rest=PassportNumber.Substring(2,12);
Int64 Result;
if (Int64.TryParse(Rest,out Result))
{
return true;
}
}
else if(PassportNumber.EndsWith("OFTW"))
{
string First6 = PassportNumber.Substring(0, 6);
Int64 Result;
if (Int64.TryParse(First6, out Result))
{
return true;
}
}
return false;
}

That’s when I was told; don’t you follow all the language features? Especially something called Regular Expressions?

Well, not to be an all knowing buff but yet, I knew what Regular Expression was and I perfectly knew how to use it. But surprisingly it never struck me. Given a problem, my initial mode of tackling it was to analytically approach it and solve. Although regular Expression’s way of doing it was straight opposite – it was elegant; and I hit myself why my mind didn’t think of it.

The Solution – Simpler one

So here’s the code, if I had used RegEx

public bool IsDomestic(string PassportNumber)
{
return Regex.Match(PassportNumber, "(TW)(\\d{12})($)|(\\d{6})([A-Za-z0-9]{4})(OFTW)($)").Success;
}

Surprisingly less lines of code, isn’t it?

Let’s dissect the solution

Without going into much deep, let me explain what the pattern (yes, I called it a pattern) means:

(TW)(\\d{12})($)|(\\d{6})([A-Za-z0-9]{4})(OFTW)($)

You see the pipe (|) symbol in the middle? Let me split the pattern at that part.

Left part: (TW)(\\d{12})($)

(TW) – Simply means that the two initial characters are TW

(\\d{12}) – tries to say that there are 12 digits following

($)– The string should end at the point, no more characters

Right part: (\\d{6})([A-Za-z0-9]{4})(OFTW)($)

(\\d{6}) – The first 6 characters are digits

([A-Za-z0-9]{4}) –  4 alphanumeric (A-Z or a-z or 0-9) characters would follow

(OFTW) – The next four characters would be OFTW

($)– The string should end at the point, no more characters – as we saw earlier

Did I miss the pipe (|)? You know what it is, it’s just an OR condition. The string in question, say TW012345678901 can choose to match with either the left part pattern or the right part pattern.

Some links before we proceed

This should have given you a basic idea into formulating a simple RegEx pattern; if you need further help you can visit http://www.regular-expressions.info/reference.html. It gives you a good glimpse on RegEx.

Or if you want a quick stop solution/pattern, visit Mark’s http://txt2re.com/, it’s an amazing site.

The almighty RegEx class of .NET

Let’s step back a bit and focus on the RegEx class in .NET framework, and see how better we can use it!

Check if a string is looking as it should

The above solution simply does that. The Match, IsMatch methods of the RegEx class tries to fits the given string into a pattern and says True, the string matches the pattern or False, the string looks nothing like the pattern! The simplest form of the method asks only for the pattern and the string.

Replace a questionable part in a string

Take for instance, the exclaimer. He gets too excited for nothing and you just need to dial his excitement down. How?


string SampleText = "This is Outrageous!!!!!!!! Regex can't solve all my problems!!!! What if it can!!!!!";

You can never track the count of the exclamations he has used (!) nor does he use a specific number all the time. The Replace method of Regex would help you there.

SampleText = Regex.Replace(SampleText, "(!)+", "!");
Console.WriteLine(SampleText);

PS: The plus (+), here in the pattern says that the (!) can appear once or more in the string. And the last part is the replace with part. All questionable parts matching the pattern would be replaced with the input to the method.

This would give me an elegant output like thus:

This is Outrageous! Regex can’t solve all my problems! What if it can!

Pattern matching, only simpler:

Imagine how hard it was to match patterns or find the count of substrings actually matching a pattern you’re looking for. RegEx offers you an elegant way to the same, using RegEx.Matches. Let’s take the below statement.

“Are you working on any special projects at work? I am not reading any books right now. Aren’t you teaching at the university now?”

I need to fish out all the present-continuous forms verbs in them, i.e. the words ending with “ing”. Normally this would be a heavy code. But with RegEx we can do it faster and simpler using the pattern string “(\\b)(\\w+)(ing)(\\b)”

This says – in sequence,

\\b blank space
\\w+ [one or more] word character
ing The specific set of characters “ing”
\\b blank space
MatchCollection collObj=Regex.Matches(TestString, "(\\b)(\\w+)(ing)(\\b)");
foreach (var item in collObj)
{
Console.WriteLine(item);
}

Would print me out, all occurrences of the pattern, which are:

Working

Reading

Teaching

Summary

Through this post, I’ve summarized most of the key uses of RegEx with special emphasis on .NET code. Beyond a particular point, it depends on your creativity how you take it further to tailor the RegEx solution based on your problem. You can do away with ugly for loops or unnecessary if-else constructs in code.

The woes of a maintenance developer

January 30, 2012 Leave a comment

Call it a bad choice, fate or ill luck. Or all together – I’m struck. It has been almost a year since. I’ve learnt to live with it but the developer inside me keeps hurting. A huge code base of unmaintainable and stinking code (talk about code smells!) it’s like your nose itch when you’re hands are tied. What irritates me the most; I’ve borne the brunt, bitten the bullet and patiently made a little list:

Foul stench: Martin Fowler talks about Code Smell. It is a kind of a surface indication that is related to a bigger problem in the system. If you’re working on a maintenance project and your luck is at odds, then chances are it’s more than just a smell – It’s a stench! From ill-written [or no] comments, to insanely long method with ridiculous names it has everything. Let me quote a couple of examples, any idea what this method does?

public String ReturnString(String input)

It accepts a string input, opens an xml file, and loops through each tag, returns value of the tag matching the input. This goes on for almost all the tags in the xml file, i.e. the method is called a pretty 200 times each for each of the tag in the xml file. Didn’t expect that eh? Me neither, until I assumed it to be a piece of junk string to string conversion method and tried to chuck it off! This is just not it. As part of an optimization drive (I never learn from my mistakes), I fumbled upon the code below:

public void Method()     {
if(condition1) {
//1000 lines of code
}
if (condition2){
//exactly the same 1000 lines of code
}
else{
//again, the same 1000 LOC
}
}

My heart cringed at the site of this and I refactored it into something very pretty and efficient. What happened next? Check the next section.

The Karma called Bug: Turns out that the 1000 lines of code had just one line (actually one variable) altered in each of the conditional blocks. And what’s worse, none of the tests covered and it was from the customer from whom the defect came.  Believe me; it took a good couple of days of code digging to figure out the source of a weird error.

So that’s the curse of an ill developed maintenance project. You are not to indulge in any refactoring unless you are ready to take full responsibility for any weird defect that may crop up, few minutes from now or few years from now or something that will never crop up.

Paralysis by Analysis: This is my favourite part. All through four years of graduate engineering study, you learn all tricks of the trade. From object oriented analysis design till may be even Artificial Intelligence. You learn all your skills and finally wind up as a maintenance developer filling scores of word documents and spreadsheets. I still vividly remember all those Impact analysis documents I filled out, none of which truly gauged the actual impact my two lines of code were going to make. Here’s a rough estimate of the whole saga of the release:

Requirements elicitation and clarification 3 days
Design – Detailed level with Impact analysis 10 days
Test plan preparation 5 days
Coding and Testing 10 days
Net number of LOC added – 5, just freakin’ 5

Hilarious isn’t it?

To sum up, here’s few points if you’re a maintenance developer – maintaining an ill-developed application:

  1. Thou shall not optimise
  2. Thou shall bear in mind that bug is inevitable
  3. When thy smells stinking code, remember rule 1
  4. Thou shall blame any defect on the developer or the previous maintainer whomsoever has left the organization
  5. Thou shall not crib

%d bloggers like this: