Saturday, June 23, 2012

Alan Turing - Google Doodle Solved

Google, breaking the pragmatism of creating artistic doodles, has showed up a geeky doodle which is a gate way to Google search results for the greatest mathematician, natural code breaker Alan Mathison Turing who with his inventions laid the strong foundation for modern computing world. The " Alan Turning Doodle " which is showed  up on Google's home page today is a tribute this ingenious.

I didn't care much to solve this doodle for the first couple of Google searches that I made today, but each time I opened Google's home page, it was be-knocking at me by tacitly asking to be solved. I began and It took little time to understand the problem to be solved and here it is.

Problem to be solved
  • User is expected to, match the pattern displayed at the right top corner of the doodle.
  • To match patterns it is required to shift bits, either 0 or 1 which can be set explicitly.
  • Each time the bits are set , doodle starts matching the modified pattern with the target pattern.
  • And if the match is successful, each letter of the word "GOOGLE" is decoded, i.e each character's color changes from gray scale to colored.
  • Once all the characters of the world "Google" is decoded, Google redirects you to page displaying search results for Alan Turning

Approach
This is more of a permutation problem combined with need to set or unset the bits appropriately.
each time a character is decoded, the level and hence the complexity of the problem increases.

Decoding Patters for each character

G = 01011
O = 00011
O = 00011
G = 01011
L = 01001
E = 10000 

And Here is how I did it.
Though I could capture most, but few screenshots are missed.

Decoding G

Decoding O
 
Decoding O


Decoding G
Decoding L
Decoding E
Google

It took a little time for me to solve, but it was worth of it.

Friday, June 22, 2012

Windows 8 - From a Consumer And a Developer Perspective

Microsoft Surface an unexpected surprise to the computing world, a menacing competitor for those who thought they had touchstone devices in the digital realm, and an adjunct to the joy of consumers and developers, Microsoft Surface running Windows 8 has formally made its pitch to bring-in  wave of change to the way we interact with computers superseding traditional flashy, jazzy, banal user interface.

That is not all, the release of Surface has now personally given me a strong reason to start posting articles on windows 8  which I was postponing for last few months, and this article being harbinger to the series of windows 8 articles, presents a brief introduction to windows 8 from a consumer and a developer perspective.

Windows 8 Home Page
Consumer Perspective
Perceiving windows 8 from a consumer perspective gives raise to innumerable questions which are very common, and to list a few.
What is Metro UI ?
What was the need of Metro UI ?
What learning efforts it takes to start working with Windows 8 ?
Can I run all those applications on Windows 8 which I used to run on Windows 7 ?

Now, let me try to answer these.
Windows 8 isn't just, an another operating system, because by considering it so, we would be reflecting our own ignorance. Yes for the sake of definition Windows 8 is yet another operating system, but beyond everything at the crux of it Windows 8 is a new design concept distinctly unique and discrete from the rest of converging design concepts.

Windows 8 Metro UI is a new way of perceiving things to build a sense of familiarity which gets imbibed in our conscious without even we could realize it. To exemplify this consider a scenario. Say, for the first time you are about to drive from a source to destination location, and as you hit the road your eyes start searching for sign boards, and you will be unknowingly trembling in a state of ambivalence until you find a signboard, with an arrow mark directing you to the destination location.

Once you are assured of the way to the destination location as indicated by sign boards, your conscious will feel back at home. This is because our brain is already being tuned to be familiar with such sign boards since the day our brain started learning and perceiving things around us. Windows 8 metro UI is all about this, making our conscious feel comfortable, feel always be at home, encounter with less surprises, a minimal computing work for brain and ultimately bridging the gap between humans and machines.

Windows 8 isn't Metro UI or Metro UI isn't Windows 8 either, in its original and in the most Ingenuous form Metro itself is a insular design concept with unquestioned approbation, since Metro design can be easily interpreted and perceived by human beings.

And lastly the key point, "Backward Compatibility" which is the main requirement of any newly built software product, and this isn't different for Windows 8. Having said that users can be assured that all of the  applications running on windows 7 should flawlessly run on windows 8 with or without minor modifications.

Developer Perspective
From a developer perspective, Windows 8 has opened a new and also a huge window of opportunities to developers to showcase their skills, expertise, design erudite,  and ability to make a difference. Now it is the responsibility of the developers across the world to build windows app store from the scratch since Windows 8 has brought in the concept of  Metro UI and a more strict and restrained life cycle of applications. Below are the few common concerns of the developers who are novice to windows 8.

Snap Shot of  Windows 8 Metro UI - Twitter app
Metro UI or Desktop Application.
Developers are not fettered to be developing only Metro applications for Windows 8, because some applications are more appealing and friendly to be used in windowed mode than as a Metro application. To support windowed applications, Windows 8 runs "Windows Desktop Environment" as an application inside Windows 8, enabling it to run native windowed applications.

Tablet PC or Desktop Computer.
Developers can develop Metro applications without bothering anything about target devices. This is because Metro applications are inherently device agnostic. it just needs WinRT framework to run. However desktop applications, aka windowed applications built for windows 8 will only run on Windows 8 Desktop edition and these windowed applications can't be run on tablet PCs since tablets running Windows 8 lacks desktop environment.

Programming Languages.
Windows 8 makes every developer feel at home, since there isn't any new language to be learnt to code for windows 8. Developers can build both Metro and Desktop applications using the same languages C, C++, C#, VB, JavaScript, HTML which they have been using ever since.

Start Coding.
Download Windows 8 release preview
Download tools and SDK for development of Metro apps.
Self help Documentation

That is all for now. I will be writing posts, mainly developer centric on building metro applications. I hope this article could help you understand the essence and need of Metro UI and hence Windows 8.
Kindly write to me if you have any comments or suggestions

Friday, May 25, 2012

Why Every Developer Needs to Learn Web Programming and What it Takes

Be a web programmer in less than four hours, yes that is my claim and I am assertive on that. learning web programming isn't rocket science, but people often get lost on their way as they start learning web programming since they are deluged with many technologies targeting the web platform.


OK, don't be deceived, this article isn't a tutorial on how to do web programming, because there is already opulent self explanatory resources on web, and adding any single line further will be redundant.

So, What is this article about ?
This article is basically intended to give an heads up to developers starting with web programming by delineating a systematic approach to learn basic web programming and explaining them why is it inevitable to learn web programming.
First part of the article speaks about the growing significance of web technologies which is leaving every programmer no choice but to learn web programming. And the second part unravels a step by step approach towards learning web programming and few links to free web resources available, making learning quick and easy.

Why every developer needs to learn web programming ?
Couple of reason, but to quote a few prominent ones.
  • Windows 8 and an increasing popularity of metro style applications.
  • Introduction of chrome OS and the popularity of chrome app store.
  • Re-engineered and elegant HTML5 UI
  • Bestowing browser with complex capabilities of native Multimedia playback, Canvas drawing, Geo positioning etc.
You like it or not, web technologies would be the most  hot and happening technologies of the future and it is coming in a big way. Developers working on OS components and other crucial system modules always had a misconception that web programming, which is basically mistaken as scripting is not for geeks like us. But in reality these misconceptions have become defunct.

To shed light on the facts mentioned above, significant number of metro apps will be coded in javascript by developers across the world, since it is quick and not a onerous task unlike other technologies like C++ and C#. Though the metro apps can be built using well known VB, C#, C++ no one would really acclaim this until there is something which can't be achieved by javascript. To quote an example metro style gaming apps using DirectX must be coded in C++ and there is no alternative for it.
With the release of Chrome OS which is complemented by chrome web store, and increasing number of web apps are built everyday. and if a developer is not there already, it leaves with very less opportunities to catch up with expedited technological growth.

With HTML5, the UI is revamped making web look more elegant and less cluttered. Browsers supporting HTML5 are fettered under the rules of W3C HTML working group to support native Video playback, Canvas drawing, Geo positioning and many other signification features. Once HTML5 and in turn Web Runtime can support these features it encourages significant number of app development with HTML5 UI and back end being built using other languages like C++, C#, VB.
Considering all the facts mentioned above, it makes it inevitable for every developer to learn and start programming for the web to be in concomitant with technological advancements.

Let's move on to the second part, 

What it take to be a web programmer ?
As mentioned earlier web programming is lucid, and not a painstaking task like other technologies. All which is needed is a proper guidance for a developer about what to start with and how to take it forward. This is very crucial since, when we speak about web technologies developers are deluged with hundreds of languages, frameworks, third party components  etc. Just to name a few we have HTML, XSLT, XML, XHTML, DHTML,CSS, JavaScript, PHP, DOM, Jason, JQuery, AJAX, ASP .. The list just goes on leaving developer confused about where to start with.

Below is my own experience when I started learning programming for web. Even I followed the well accepted approach of starting  with HTML, JavaScript, CSS before moving on to advanced topics, believe me it had its returns. Building a web page is basically an amalgamation of three technologies which results in an elegant web page. and they are,

HTML - Defines the basic structure of a web page.
HTML is an acronym for HyperText Markup Language. and it is basically a "Markup" language rather a programming language. A markup language, is collection of stylistic instructions, issuing the target rendering engine three basic instructions on,
  • What needs to be painted, 
  • Where it needs to be painted and 
  • How. it needs to be printed.
HTML is built on DOM architecture, where each HTML element is nothing but a DOM node. instructing web browser about the content to be rendered and its attributes.
CSS - Makes web pages look elegant with less work
By now you have a basic structure of web page which can convey the intended information, but let's present it in an eye catching way, use CSS, an acronym for Cascading Style Sheets.
CSS constitutes styling information to be used for different elements, and the reason it reduces significant amount of work is, once a CSS style is defined for an element it is applicable to all the occurrences of that elements hence avoiding specifying the styling information redundantly.
JavaScript - Makes web pages come alive by adding interactivity
Few people have a misconception that JavaScript is a variant of JAVA programming language, but the truth is far from reality. JavaScript and Java programming language share no resemblances and neither of them is derived from the other.
JavaScript adds intelligence to webpages so that, pages can talk back to the user. Rich web applications can be easily built using JavaScripts. Introspecting JavaScript it can be found that JS is in turn made up of two technologies, and they are,
  • ECMAScript - which defines the core language constructs, and
  • DOM elements - on which script acts on
And there needs an interface between these two technologies to work in synchronization and this is provided by WebIDL specifications. WebIDL is an interface definition language which prominently defines  javascript constructs for web runtime.

I hope this article, could elicit the intensity of need to start with web programming, and how to take it up further. for more resources kindly refer,
Happy Coding...

Sunday, May 13, 2012

Compiler's Optimization Techniques - Virtual Inheritance - Part 2

This post is continuation to Part -1 of this article, hence kindly skim through the first part if not already, before you  begin with part - 2 for better understanding.

As mentioned in the earlier part, in this post we get more insight into object layout , implicit pointer conversions,  pointer offsetting and virtual base class pointers in the case of multiple inheritance. And in the process we get good understanding of Virtual Inheritance. And a disclaimer before we proceed, the examples considered here are just hypothetical cases and not to disparage anyone.

Further extending the inheritance hierarchy mentioned in part -1, consider that now the company has decided to introduce an open source mobile OS, based on existing "Mobile_OS" of the company but enhancing it further to favor open source development with a strong eco-system of contributors and names it "Android".
 class Mobile_OS   
 {   
   public:   
    float iKernalVersion;   
    float iReleaseVersion;   
    char* strVendor ;
    virtual float GetKernalVersion();   
    virtual float GetReleaseVerison();   
    Mobile_OS();   
    ~ Mobile_OS();   
 };  
 class Android : public Mobile_OS   
  {   
   private:   
     char* strVendor;   
     char* strProjectCode ;    
   public:   
     int iAndroidCustomRomVersion ;   
     float GetKernalVersion();   
     float GetReleaseVerison();   
     Android ();   
     ~ Android ();   
  };   

The memory layout of Android class will be exactly same as of "WindowsPhone" class mentioned earlier, since both of these two classes are derived from the same base "Mobile_OS"

The design looks good till this point, with reusable modules and well defined class hierarchy. Now consider, the same company which had produced Windows and Android phones has now plans to come up with "Tablet" devices, with a hybrid operating system, based on superior features of both windows and android phones and making itself a unique OS by adding exclusive unique features and calls it " Hybrid_Tablet "

Do you foresee any problems with this design ?
Yes, we run into issues of data redundancy and inconsistency by deriving a " Hybrid_Tablet " from " WindowsPhone" and "Android" classes.

What caused issues of data redundancy and inconsistency ?
The cause of these issues is rooted in the fact that, both "WindowsPhone" and "Android" classes are derived from a common base "Mobile_OS" and hence both of these two classes persist its own instance of  "Mobile_OS" class leading to issues of data redundancy and inconsistency.

How expensive is this fault ?
It depends on size of the base class, in our case it is the size of "Mobile_OS" class. Even if the developer cautiously resolves issues of data inconsistency by object reference for class data access,  there is no solution to curb data redundancy. And if the base class is huge with many data members this design decision proves expensive.

What is the solution ?
The only solution to problems like above is to use Virtual Inheritance.

In a system of classes, belonging to a single hierarchy, if a class is derived from multiple base classes which are in-turn derived from a single base class, the concept of Virtual Inheritance is used to ensure that there is only a single copy of the common base class in the most derived class.

Deploying virtual inheritance in the current issue, we can ensure that the "Hybrid_Tablet" will have only a single instance of "Mobile_OS" which is commonly shared between "WindowsPhone" and "Android".

To inform the compiler to use single instance of "Mobile_OS" in " Hybrid_Tablet" the two base classes of " Hybrid_Tablet" which are "WindowsPhone" and "Android" should be derived virtually from "Mobile_OS" as shown below.

 class Mobile_OS   
 {   
  public:   
   float iKernalVersion;   
   float iReleaseVersion;   
   char* strVendor ;   
   virtual float GetKernalVersion();   
   virtual float GetReleaseVerison();   
   Mobile_OS();   
   ~ Mobile_OS();   
 };   
 class WindowsPhone : public virtual Mobile_OS     
 {   
  private:   
   char* strCodeName ;   
   char* iHardwarePlatform ;    
  public:   
   int iCustomRomVersion ;   
   float GetKernalVersion();   
   float GetReleaseVerison();   
   WindowsPhone();   
   ~ WindowsPhone();   
 };   
 class Android : public virtual Mobile_OS    
  {    
   private:    
    char* strVendor;    
    char* strProjectCode ;    
   public:    
    int iAndroidCustomRomVersion ;    
    float GetKernalVersion();    
    float GetReleaseVerison();    
    Android ();    
    ~ Android ();    
  };   

Memory Layout of an object in case of Virtual Inheritance
In the case of non virtual inheritance, it is most certainly accepted design practice that both base class and derived class will have the same starting address since in a derived class the base instance is placed first. For more details please refer Part -1

In the case of virtual inheritance, embedded base virtually floats within the derived object without having a definite fixed displacement. Hence there is an overhead of maintaining this information within the derived virtual object. and this is achieved by maintaining "Virtual Base Table Pointer" and  "Virtual Base Pointer Table" as shown in the diagram below.

Click on the image for high resolution version
The instance of each virtually derived class will have a hidden pointer "vbptr" which is an acronym for " Virtual Base Table Pointer" which points to "Virtual Base Pointers Table" of a class. The Virtual Base Pointers Table contains displacement of the virtual base within the derived class from the address point of "vbptr" in number of bytes.

In the above example "Android::vbptr" points to "Virtual Base Pointers Table" which has two entries. which are displacement values for virtual base, and the acronyms stand for,

 And_Dt_And_vbptr_And = In Android Instance Distance of Android vbptr to Android  
 And_Dt_And_vbptr_Mos = In Android Instance Distance of Android vbptr to Mobile_OS  

Memory Layout of Most Derived class in virtual inheritance.
Now, coming back to our original issue of  designing a " Hybrid_Tablet" by deriving from multiple base classes which are derived from common base class, can be addressed using virtual inheritance. And this is achieved by,

1) Deriving "WindowsPhone" and "Android" virtually from "Mobile_OS", and
2) Deriving " Hybrid_Tablet" from "WindowsPhone" and "Mobile_OS".

 class Hybrid_Tablet : public WindowsPhone, public Android  
 {  
  Private:  
        ..................  
        ..................  
  public:  
        ..................  
        ..................  
 };  

As mentioned earlier, in virtual inheritance the position of base class instance is arbitrary within derived class, and in this case, we can see that, instance of  "Hybrid_Tablet" has only a single instance of "Mobile_OS", "WindowsPhone" and "Android" and reference to "Mobile_OS" is maintained with the help of "Virtual Base Table Pointer" one for each class and which points to a single "Virtual Base Pointers Table"of "Hybrid_Tablet" class. as shown below.

Click on the image for high resolution version
 Hbt_Dt_Wnp_vbptr_Wnp = In Hybrid_Tablet Instance Distance of WindowsPhone to WindowsPhone  
 Hbt_Dt_Wnp_vbptr_Mos = In Hybrid_Tablet Instance Distance of WindowsPhone to Mobile_OS  
 Hbt_Dt_And_vbptr_And = In Hybrid_Tablet Instance Distance of Android to Android  
 Hbt_Dt_And_vbptr_Mos = In Hybrid_Tablet Instance Distance of Android to Mobile_OS  

With this, I hope this article delineates moderately deeper insight of virtual inheritance and its implementation details. Kindly mail me if you have any queries or suggestions.
Also, please let me know if you are further interested in digging deeper into virtual inheritance in understanding "Data Access" and "Function Calling" mechanisms, I can write a post on that as well.

E- Mail : mail2vijaydr@gmail.com
References : MSDN, CodeProject, CodeGuru, and other web resources.

Tuesday, April 17, 2012

Compiler's Optimization Techniques - Virtual Inheritance - Part 1

Inheritance is one of the pillars of Object Oriented Programming. Many high level languages have different implementations for inheritance and also they support wider ramification of inheritance. Despite these differences, the core implementation structure of inheritance converges to an accepted design which is common across all languages. The advantage of diving deeper into understanding the implementation details of inheritance is that it imparts greater confidence in you to be able to exactly figure out what compiler is trying to achieve.

The reason behind writing this article is, out of all the high level programming languages C++ stands out by supporting multiple inheritance, which none of the other high lever languages support in it's native form, but rather as interfaces. As a programmer it is always good to understand your compiler and its optimization techniques which ultimately helps you to write efficient code.

The main article will be presented as two separate posts, and this being Part-1 of the article, discusses primitive inheritance technique ie single level inheritance, object layout, memory allocation, implicit class pointer conversion, and pointer offsetting. and Part - 2 of the article provides comprehensive insight into implementation details of multiple and virtual inheritance.

Part - 1
Consider two simple classes, " Mobile_OS " and " WindowsPhone" which is derived from "Mobile_OS" with a public access specifier.

 class Mobile_OS  
 {  
 public:  
   float iKernalVersion;  
   float iReleaseVersion;  
   char* strVendor ;  
   
   virtual float GetKernalVersion();  
   virtual float GetReleaseVerison();  
   Mobile_OS();  
   ~ Mobile_OS();  
 };  
   
 class WindowsPhone : public Mobile_OS  
 {  
 private:  
   char* strCodeName ;  
   char* iHardwarePlatform ;    
   
 public:  
   int iCustomRomVersion ;  
   float GetKernalVersion();  
   float GetReleaseVerison();  
   WindowsPhone();  
   ~ WindowsPhone();  
 };  

The blue print of  "WindowsPhone" class lays out all the non virtual data members in the order of their declaration starting from the base class data members, followed by derived class data members. as shown in the diagram below.
 
Why this object layout is preferred for derived class?
The C++ Standards Committee allows object layout of any ordering of data members each separated by access declarator. But VC++ and most of the other compilers ensures that the objects are laid out in the order of declarations, with derived class data members following the base class data members.

What optimization does compiler achieve with this layout?
Derived class inherits all the public properties and behaviors of base class.  The complete instance of base class's data members are contained within the derived class address space. 
By placing the base class "Mobile_OS" at the starting address of a derived class "WindowsPhone" ensures that the address of the base object  "Mobile_OS" within derived object "WindowsPhone" corresponds to very first byte of  "WindowsPhone".  And hence this layout avoids offset calculations for  base object data access with in derived object.

How does offset calculation is avoided ?
 Mobile_OS* Lumia = new WindowsPhone();  
 Lumia->iKernalVersion;  
Consider the code snippet above, here base class data member "iKernalVersion" is accessed from "Lumia" object pointer whose static type is "Mobile_OS*" but dynamic type is "WindowsPhone*".
Since the implicit upcasting form "WindowPhone" to "Mobile_OS" is succesfull in this case, compiler just extracts value of "iKernalVersion" based on "Mobile_OS" layout, and hence no offset calculations required in this case. So to get to the base class data member compiler just needs to compute

&DataValue = DerivedClass_StartingAddress + Offset_of_DataMember_Within_BaseClass

What if  base class data members followed derived class data members ?
Consider the same code snippet specified above, and if at all base class data members followed derived class data members, accessing any data member of the base class would have been an  overload with offset computation. So to get to the base class data member compiler needs to compute.

&DataValue = DerivedClass_StartingAddress + Offset_To_BaseClassObject_Within_DerivedClass  +Offset_of_DataMember_Within_BaseClass 

I hope this provides convincing explanation about object layout and its advantages in case of single inheritance. And as mentioned earlier Multiple and Virtual Inheritance implementations will be discussed in Part-2 of the article. Kindly revert back if any comments or suggestions.

Thursday, March 22, 2012

Why a C++ Developer May Find it Uneasy to Work With C#

Let me put up disclaimer first, since the title of article may contradict with the views of C# developer community. This article is based on my own experience working on both C++ and C# languages for more than 4 years. And this article is intended to developers migrating from any flavors of C++ technology to C#. Also a C# developer may look upon this article to get a picture of how distinct and abstract is C# language design when compared to other programming languages which runs natively on hardware.

This article is highly abstract, which looks only into syntax and semantics of the languages, and doesn't really dig deeper into design considerations of the language.

So, let's quickly get to the point. How C# is highly distinct from C++ ?

 
  •  Absence of Pointers
    One of the prime goals of C# language design is to get rid of ugly pointers and make coding easy, quick, clean which finally conduces " Rapid Application Development " . But believe me a C++ developer feels at home working with pointers, it's no real fun coding in the absence of pointers. In fact a matured C++ developer finds it really hard to write programs a deprived of pointers .

    Not to be demotivated , Microsoft bequeathed every single responsibly of  'pointers'  in the hands of  " References " which basically alludes pointers. The message is clear Microsoft  doesn't expect or allow developers to mess around by having direct memory access.

    • Memory Management
      The .Net framework further makes developers life easy or rather I say lazy by, completely managing the memory allocations and deallocations in the name of  "Garbage Collection" and branding the resultant code as " Managed Code ". What I really don't understand is that when an experienced developer can write complex algorithms, can design systems involving multilevel difficulties, is it really hard be responsible for memory management.

      By delegating memory management to framework, a developer really loses flexibility on design and functioning of the system. If developer had the luxury of memory management as in C++ he could clearly circumscribe on the target hardware capabilities and limitations on which the program will be run. And could also customize applications to be run on platforms constrained by hardware limitations.

      • Member Value Assignment Inside Class Definition
        The basic principle of Object Oriented Programming conveys that " Class represents a generic blueprint of an instance " and values of data members are specific to an instance, but 'static' is an exemption here. Contrary to this, C# language design allows developers to assign initial value to data members of a class as shown below.

        public class Student
        {
           public string Name = " James Frank " ;
        }
        ANSI standards for Object Oriented language implementation ensures initialization of data members of a class to default values through default constructor. If we already have a default constructor which is clean, and serving the main purpose , C# feature of member value assignment inside class definition is "Redundant" and affects code readability. Any feature of a language unless it serves a signification purpose is redundant or burden.

        • Boxing and Un-Boxing 
        C# developers must be aware of the fact that, it is possible to explicitly convert a value type variable to reference type, and a reference type variable to value type through a feature called Boxing and Unboxing respectively.
         
        Boxing
        short S = 20 ;
        object ShortObject  = S ;
         
        UnBoxing
        short S = (short) ShortObject ;
         
        C# provided this feature to have a unified type system in place which allows value type to represent the underlying data altogether wrapped in a new representation called " reference " and vice versa. Unless there is a flaw in design, how the polymorphic classes are built this feature is of no worth, and if at all one is using this feature it necessitates the need to trace back derivation hierarchy of polymorphic classes.
         
        • Static Constructors
        This is an odd feature of C# , it breaks the basic understandings of Object Oriented Programming in being developer friendly. Below is an example of static constructor

        public class employer
        {
              private static string CompanyName ;
              static employer()
             {
                 CompanyName = "Nokia" ;
             }
        }
         
        Static constructor ensures that, static data members are always assigned to an initial value. And it is called, when an instance of class is created or a static member function is invoked.
        I mentioned this is an odd feature because, this is a work around for C# language design which doesn't allow anything to be defined outside of a class. In the absence of this constraint static data members could have been defined and initialised outside class definition as in C++
         
        string employer :: CompanyName = "Nokia" ;
         
        • Redundant Out and Reference Parameters
        C# has introduced couple of enhancements in parameter passing mechanisms, to cut short developer efforts from writing lengthy code. Out of which "Out" and "Ref" are the two parameter decorators. Value for "Out" parameter is assigned by the called member, as shown below.

        public static void Add ( int x, int y, out int ans )
        {
             ans = x + y ;
        }

        Usage :
        public static void calculate()
        {
             int ans ;
             add ( 1, 2, ans ) ;
        }
         
        The sum is stored in 'ans' variable by callee " Add " .
        Now consider "Ref" decorator, the only difference is "Ref" parameter must be initialized before being sent to callee. So if this is the only constraint we don't really need "Out" parameter at all, all which is required is to use "Ref", ensuring that the variable is assigned to initial value.

        These are the couple of features of C# which I found redundant, ugly,  which leads to confusion, and mystifies clarity of  the language rather assisting a developer. However these are my own views but not conclusions.


        Friday, March 2, 2012

        Nokia Pulse, Your Freedom of Expression

        Privacy, Privacy, and Privacy .. Yes you heard it right, the most concerned, researched, and discussed topic of internet community of all the time is Privacy.  As internet has grown into integral parts of our lives the loquacious couldn't stop themselves from being very expressive on internet. And finally there arose the problem of  " Individual Privacy ".

        Now a days with more and more incidents of breach of individuals' privacy, people are very watchful in what they share on internet. But with the unparalleled excellence of Facebook in social networking and Google+ in bringing the like minded people together individual privacy has again taken a backseat as people are becoming liberal in what they share. But if you observe keenly the breach of individuals' privacy really isn't due to sharing things with others but due to " What you share " and " With whom ".

        So, what is the solution ?
        Social networking giants like Facebook, and Google+ provide features to create closed groups, but people hardly use it due to usability issues, very confusing settings, and credibility measures. Even when a person with technical background finds it difficult to play around with these setting one can't expect a layman to use those.
        This was the time when Nokia pitched into development of a unique social networking product " Nokia Pulse "

        What is Nokia Pulse ?
        Nokia Pulse is a unique product which gives life to your day to day conversations, It is as intuitive as you verbally interact with your loved ones. 
        Wishing your friends good morning, asking about their whereabouts, letting them know where you are, calling them for a coffee at your favorite hangout place, letting them know how to reach the venue, etc.. all these are just a few taps on Nokia Pulse.

        Let me explain how...

        Create your closed user groups
        Segregate your friends, colleagues, relatives, and the people you care most, across different user groups. This is basically the first step of achieving individuals' privacy by deciding who gets to know what. You don't intend to share everything with everyone.



        Tell your friends about how you freaked out at weekend party, Discuss technical things with your office colleagues,  share your trip photos and experience with your family and relatives. And what not, the possibilities are boundless, but at any point of time you have the supreme control of who views what.

        Propose your plans and let your friends comment


        Are you fanatical about going on trips, let your friends know about it, propose your plans with the destination info, some photos and share it with your intended group. Your friends from that group would revert back with their opinions about the plan, discuss on it, prepare a concrete plan and you are ready to drive, and of course Nokia maps will guide you to destination.
        Invite your friends for events, help them with navigation details .
        Would you plan to hangout at a cafe with your friends, or call them for a cricket match. Say it with Nokia pulse, type in your message, add a picture which speaks your mind, add the destination info with Nokia maps and just share it.



        Nokia pulse makes all these possible with the tap of a finger, in epitome pulse assures an Intuitive, highly secured, private, credible, social networking solution that we envision of.

        Tuesday, January 31, 2012

        Compiler's implementation of New and Delete operators

        Digging deeper into the implementation of New and Delete operators,  raises couple of question as listed below.
        • Under what circumstances a bad_alloc exception is thrown.
        • What if there is an exception thrown inside a constructor.
        • Who releases the heap memory allocated for the object, when constructor fails.
        • Is it possible to reuse a chunk of memory on the heap to reconstruct the object.
        • How to distinguish whether the exception is due to heap allocation error or due to a failing constructor.



        Rather trying to answer these questions individually, it's better to explore compiler implementation of  " new " and " delete " operators which eventually answers the above questions.











         Consider CellPhone,a class declaration below

             class CellPhone
             {
                 long IMEI ;
                 char* DeviceName ;
              public:
                 CellPhone(int ID, char* Name)
                 {
                     IMEI = ID ;
                     strcpy(DeviceName,(char*)malloc(sizeof(strlen(Name)+1)));
                 }
                 void* operator new ( size_t size );
                 void operator delete (void* buffer);
             };

        The below instruction creates an instance of this class on the heap through " new " operator.

          CellPhone* PhoneObject = new CellPhone(900,"NOKIALUMIA") ;

        New Operator
        The "new" operator instantiates an object on the heap in two steps.

        1) Allocate the required amount of  memory for the object, on heap
        2) Call constructor of the class to initialize the object.

        Instantiating the object on heap
        To allocate memory on the heap "new" operator uses a function " operator new " as shown in the class declaration. This function allocates memory specified by " size_t " parameter on heap for the object and returns a " void* " pointer. And if the memory allocation fails, run-time will throw a " bad_alloc " exception.

              void* CellPhone::operator new(size_t size) throw (const char*)
              {
                void* buffer = malloc(size);    
                if(buffer = NULL) throw "Not enough memory to allocate for the object";
                return buffer ;
              }

        The above function can be overloaded by the developer to provide custom implementations and excemption details.

        Initializing the object by calling constructor 
        Run-time achieves this functionality through " Placement new " operator which basically receives  " void* " pointer returned by " operator new " function, allocated on the heap and calls constructor of the  class to initialize the object as shown below.

        Calling operator new function.
            void* buffer = operator new(sizeof(CellPhone)); // ----------->1

        Typecast void* pointer to class specific pointer.
          CellPhone* PhoneObject = dynamic_cast<CellPhon*>(buffer);//Simple  static cast also would do.

        Constructing the object at the allocated space using " placement new " operator.
            try
            {
               new(PhoneObject)CellPhone(900,"NOKIA LUMIA"); //------------> 2
            }
            catch(exception& e)
            {
                cout << e.what();
                operator delete( PhoneObject );
                throw "Exception inside constructor";
            }
            
            void CellPhon::operator delete (void* buffer)
            {
               free(buffer);
               buffer = NULL ;    
            }

        The above programming structure clearly explains, how the exceptions from constructor is handled. The " placement new " operator shown in instruction #2 receives pointer to the buffer allocated as shown in instruction #1 and tries to construct the object at that location.
        During this process if there is any exception thrown inside the constructor it is caught and the allocated memory is released back to heap using " operator delete ( ) " function, which is a compliment of " operator new ( ) " function.
        With the above implementation user would be clearly able to distinguish whether the " new " operator failed due to "heap allocation error " or due to " exception thrown " inside the constructor.

        I hope this article was helpful in demystify obscure implementation details of  "New" and "Delete" operators. Suggestions and comments if any is appreciated.

        Thursday, January 19, 2012

        Code Sprint - 2 , Algorithmic Problems

        This post is for all the self proclaimed geeks who love resolving complex algorithmic problems. Below are the questions  from  code sprint 2 an online coding contest. Time to overclock your brains. Happy coding.

        The Living History
        Coin toss
        You have an unbiased coin which you want to keep tossing until you get N consecutive heads. You've tossed the coin M times and surprisingly, all tosses resulted in heads. What is the expected number of additional tosses needed until you get N consecutive heads? Input: The first line contains the number of cases T. Each of the next T lines contains two numbers N and M. Output: Output T lines containing the answer for the corresponding test case. Print the answer rounded to exactly 2 decimal places. Sample Input : 4 2 0 2 1 3 3 3 2 
        Sample Output : 6.00 4.00 0.00 8.00

        Permutation
        This is an approximation solution type problem. Please read about this type of problem at the bottom before attempting. Given n, print a permutation(p) of (0,1,2...n-1) From the permutation p, you can create n-1 (x,y) coordinates, where x and y are consecutive pairs in the permutation. You are also given the n x n square matrix V. For each coordinate, you can find an associated value in the matrix V. (x and y are 0-indexed) 
        Task : Given n and V, find the permutation p that maximizes the sum of the associated values of the consecutive pair coordinates Constraints: n <= 50 Input: First line contains n Next n lines contains n integers, forming the matrix V 
        Output : Space separated permutation of (0,1,2....n-1)

        Polygon
        There are N points on X-Y plane with integer coordinates (x i , y i ). You are given a set of polygons with all of its edges parallel to the axes (in other words, all angles of the polygons are 90 degree angles and all lines are in the cardinal directions. There are no diagonals). For each polygon your program should find the number of points lying inside it (A point located on the border of polygon is also considered to be inside the polygon). Input: First line two integers N and Q. Next line contains N space separated integer coordinates (x i ,y i ). Q queries follow. Each query consists of a single integer M i in the first line, followed by M i space separated integer coordinates (x[i][j],y[i][j]) specifying the boundary of the query polygon in clock-wise order. Polygon is an alternating sequence of vertical line segments and horizontal line segments.
        Polygon has M i edges, where (x[i][j],y[i][j]) is connected to (x[i][(j+1)%M i ], y[i][(j+1)%M i ].
        For each 0 <= j < M i , either x[i][(j+1)%M i ] == x[i][j] or y[i][(j+1)%M i ] == y[i][j] but not both.
        It is also guaranteed that the polygon is not self-intersecting.
        Output : For each query output the number of points inside the query polygon in a separate line.

        Sub-sequence Weighting
        A sub-sequence of a sequence is a sequence which is obtained by deleting zero or more elements from the sequence. You are given a sequence A in which every element is a pair of integers i.e A = [ (a 1 , w 1 ) , (a 2 , w 2 ) ,...,(a N , w N )]. For a sub-sequence B = [ (b 1 , v 1 ) , (b 2 , v 2 ) , .... ,(b M , v M ) ] of the given sequence : We call it increasing if for every i ( 1 <= i < M ) , b i < b i+1 .
        Weight(B) = v1 + v2 + ... + vM .
        Task : Given a sequence, output the maximum weight formed by an increasing sub-sequence 
        Input : First line of input contains a single integer C. C test-cases follow. First line of each test-case contains an integer N. Next line contains a 1 , ... , a N separated by a single space. Next line contains w 1 , ... , w N separated by a single space. 
        Output : For each test-case output a single integer number: Maximum weight of increasing subsequences of the given sequence.

        Crab Graphs
        A crab is an undirected graph which has two kinds of vertices: 1 head, and K feet , and exactly K edges which join the head to each of the legs.( 1 <= K <= T, where T is given) Given an undirected graph, you have to find in it some vertex-disjoint sub-graphs each one of which is a crab . The goal is to select those crabs in such a way that the total number of vertices covered by them is maximized. Note: two graphs are vertex-disjoint if they do not have any vertex in common. 
        Input : First line of input contains a single integer C. C test-cases follow. First line of each test-case contains three integers N, T, and M (the number of nodes, max number of feet in the crab graph, and number of edges, respectively). Each of next M lines contains two space separated v 1i , v 2i meaning that the there is an edge between vertexes v 1i and v 2i . Note that the graph doesn't have parallel edges or loops. 
        Output : For each test-case, output a single integer indicating the maximum number vertices which can be covered by some vertex disjoint sub-graphs of graph which are crabs

        Picking Cards
        There are N cards on the table and each has a number between 0 and N. Let us denote the number on the ith card by c i . You want to pick up all the cards. The ith card can be picked up only if at least c i cards have been picked up before it. (As an example, if a card has a value of 3 on it, you can't pick that card up unless you've already picked up 3 cards previously) In how many ways can all the cards be picked up? Input: The first line contains the number of test cases T. T test cases follow. Each case contains an integer N on the first line, followed by integers c i ,...,c N on the second line. Output: Output T lines one corresponding to each test case containing the required answer for the corresponding test case. As the answers can be very big, output them modulo 1000000007. 

        Count strings
        A regular expression is used to describe a set of strings. For this problem the alphabet is limited to 'a' and 'b'.
        We define R to be a valid regular expression if: 1) R is "a" or "b" 2) R is of the form "(R1R2)" where R1 and R2 are regular expressions 3) R is of the form "(R1|R2)" where R1 and R2 are regular expressions 4) R is of the form "(R1*)" where R1 is a regular expression.
        Regular expressions can be nested, and will always have two elements in the parenthesis. ('*' is an element, '|' is not; basically, there will always be pairwise evaluation) Additionally, '*' will always be the second element; '(*a)' is invalid.
        The set of strings recognised by R are as follows: 1) If R is "a", then the set of strings recognised = {a} 2) If R is "b", then the set of strings recognised = {b} 3) if R is of the form "(R1R2)" then the set of strings recognised = all strings which can be obtained by a concatenation of strings s1 and s2 where s1 is recognised by R1 and s2 by R2. 4) if R is of the form "(R1|R2)" then the set of strings recognised = union of the set of strings recognised by R1 and R2. 5) If R is of the form "(R1*)" then the the strings recognised are the empty string and the concatenation of an arbitrary number of copies of any string recognised by R1.
        Task : Given a regular expression and an integer L, count how many strings of length L are recognized by it. Input: The first line contains the number of test cases T. T test cases follow. Each test case contains a regular expression R and an integer L. Output: Output T lines one corresponding to each test case containing the required answer for the corresponding test case. As the answers can be very big, output them modulo 1000000007.
         

        Monday, January 9, 2012

        Backup Your Life , Before it Dies...

        I am very delighted as I started writing my first blog article of 2012. Happy new year to one and all. I thought for a while on what is going to be the topic for this article, as I wanted it to be quite unique, non technical, informative to readers. So, there strikes a question which always haunted me... 

        Is It Possible to Backup Life ?

         

        Days, months, years are passing by as quick as 5 minutes snooze of morning alarm, which you never feel. Hundreds of people that we meet, hangouts with friends, events that we participate in, numerous social engagements, the places that we visit, images that we capture, sports that we play, seminar that we present, innovations that we make, heights that we achieve and the list just goes on.
        But we tend to forget all these very quickly, people are lost in day-today engagements, an aggressive life style where things change very drastically.

        I always thought, how good it will if I could remember or document all those things which I do everyday, and could exactly recount what I was doing on a particular day of the year when asked.. and the list just doesn't end here , it grows even further with many more wishes like,
        • Whom all I met in the years passed.
        • What problems I worked on.
        • What all the topics which grabbed my attention.
        • Which all the places that I have visited.
        • The sports that I played.
        • Images that I captured.
        • Parties that I attended. 
        How can I backup all these information in a structured way ?
        If I were thrown this question a couple of years back probably I would have had no answer. But now certainly we can address these questions by leveraging the power of web services. In the recent days web has evolved beyond our expectations, with could computing and easy access to internet one could reap the benefits of web services without any hassle.

        Below is the brief description of how we can make use of free web services and applications to address all the issues mentioned above, and precisely " How can be backup our lives ".

        People whom I met. 
        Social networking sites like Twitter, Facebook, LinkedIn will fit the bill in addressing this concern. With the boom in social networking one can keep in touch his friends effortlessly. Now a days people from internet community are found at-least on one of the social networking site, and this is enough to keep in touch with the person of interest.

        Building circles based on my profession and interests.
        " Google Plus " is the answer. As most people say Google Plus is for geeks, being a networking site, G+ is heading in right direction in bringing like minded people from every corner of the world. And it  doesn't even expect that the participating members to be friend of each other.
        Google Plus is a huge stream of free flowing information source which anyone can listen to. You just need to circle all the people, pages which you are interested in and they will keep you updated about latest technological innovations as you listen to their streams.

        Articles which grabbed my interest.
        A simple one word answer " Tweet " , tweet more, tweet all those articles which you found interesting. Unknowingly you are backing up all those articles of your interest and in future if you look back you end up having a well structured catalog of articles which you can refer back to.

        Places that I have visited.
        "Google Latitude" is the perfect application which you can use to keep record of all the places that you visit. Each time you visit a new place, mark it on Google latitude with the help of GPS, that's all. The records are saved in your Google account, ready to be referred back at any point in future.

        Pictures that I have captured.
        Online photo stores like Picasa, Flicker, Tumblr, will assist in keeping your pictures safe and lets you share your photographs with your friends, and get feedback on them. With the help of these applications you can let the world know that hidden artist within you. 

        I want to keep my articles and notes safe for future reference.
        Use " Evernote ", a quick note taking and documenting application which is platform and device agnostic, which can be used from anywhere and you are ensured that always you get the most updated data. No matter from whichever device you have edited the information it is all there synched on all the devices.

        I want a Document repository which I could share with others.
        " Dropbox " is the perfect application for you. Dropbox allows users to backup documents online which is ready to be extracted from anywhere and on any device. Dropbox also allows you to share some selected documents with your friends and hence helps in synchronizing between multiple people working on same documents.

        Where can I backup my hobby projects.
        "GitHub" a web hosting service for software projects. You can create your repository on this server and backup your code. You can also share repository with team members and it assists in combined efforts of a software development team.

        And lastly....

        I'm interested in knowing what is happening in others life
        After all this is a basic instinct of human race. I don't need to mention the web service for this purpose, but this article would be incomplete if I don't mention it. Use " Facebook ", to be connected with people. That's all and the rest you only know.

        With this, we have come to the end of this article. I hope following these would certainly help in backing up ones Social engagements, interests, views, skills, facts, desires, hopes, memories and what not. and hence you can " BACKUP YOUR LIFE".

        ShareThis