Showing posts with label hack. Show all posts
Showing posts with label hack. Show all posts

Monday, July 26, 2010

Chrome Extension to do YQL page scraping. (quickest way to create a YQL mashup)

Hello ,
This weekend I was in Bangalore to attend "Yahoo Hack Day", Where I wrote a hack, which is a Chrome Extension to make your life really easy when you are trying to do some page scraping using YQL. My hack is also the "winning hack".

Name of the extension is ChromYQLip, which you can install from here.

Here is demo video



Yahoo hack days are great event, this time in India total participants were more that 450 and a total of 142 Hacks submitted and 108 hacks presented.

Thanks for reading My blog

Sunday, June 13, 2010

HindiTransliteration (c# and JavaScript implementation, works offline)

When I was in college, I wrote a quick and dirty code to transliterate in Hindi (DevNagari Script). Much before Google's Implementation.
{This code was kept on my old desktop PC,I Thought, its a good idea to share with the rest of the world}



Though my implementation is not very robust, but Its very simple and small. It does not require any Internet connection and can work offline.

Note: code was originally written in C#.net and converted to javascript latter.
Here is C#.net Code(solution zipped)

You need to call function
DoTransLitrate(str)
Where str(as input): Phonetically typed (in English) Hindi .
Returns: Hindi in Devnagari script.


Using JavaScript Code
Get the JavaScript File from here include in your html page and call function
DoTransLitrate()
  DEMO  

Wednesday, May 19, 2010

Twenital: Determines gender from a twitter handle

Twitter never stores the gender of their users. It makes the life of analytic engines very difficult to find that what is the ratio of men vs women on twitter.
Here I have created quick and dirty mash-up to get  gender of the twitter user.


How It Works?
Thanks to face.com API, they have recently released face recognition API. I am simply using their face recognition API to do this.


Here is AJAX code

function getusergender(imageurl) {
var url = 'http://api.face.com/faces/detect.json?api_key=1ce92a4c5e60f04c37bedf86c2d19387&urls=' + imageurl + '&callback=?';
$.getJSON(url, function (data) {
if (data.status == "success") {
if (data.photos[0].tags.length == 0) {
$("#resdiv").html('<div class="errormsg">hmmm..Let him/her put better profile picture. </b>TIP: put high resolution profile picture, facing front.</div>');
}
else if (data.photos[0].tags.length > 1) {
showerror('This user is multifaceted, Let him/her put better profile picture..');
}
else {
if (data.photos[0].tags[0].attributes.gender.value) {
var gender = data.photos[0].tags[0].attributes.gender.value;
if (data.photos[0].tags[0].attributes.gender.confidence > 40) {
if (gender == 'male') {
$("#resdiv").text('100% Male');
}
else {
$("#resdiv").text('Gorgeous Female');
}

}
else {
if (gender == 'male') {
$("#resdiv").text('Male');
}
else {
$("#resdiv").text('Female');
}
}
}
else {
showerror('hmmm... not sure!!');
}

}
}
else {
if (data.usage.used > 197) {
showerror('Sorry!! Application Overloaded!!');
}
else {
showerror('Processing failed!! Can not determine gender!!');
}
}
});

}

   DEMO  

Monday, April 19, 2010

Create quick and dirty YQL Mash-up in 10 seconds (using MashupBuilder)


Sometime, you might have experienced that  you have to wait till whole website is downloaded just to see a stock-quote, game score, or league points table(etc.). Mostly these kind of websites are poorly managed, and they are very slow or contains too many annoying ads. I have created a Mash-up-builder that will help you in creating YQL based mash-up, very quickly. These mash-ups will be capable of showing just a small portion of the original web page. Mash-up will be dynamic and content will be pulled from original page every-time you will visit the mash-up. Additionally mash-up will be hosted on my website, so you need not to bother about hosting, though you can copy HTML code anytime if you want to host on your own.(these mashups are pure JavaScript, no server side coding).

Advantage is getting a faster & neat web page.

It was very easy to create mash-up-builder. I used YQL's html table.

How it works?
As you see that YQL's HTML table gives you output if you provide the URL and xpath of the content. Similarly Mash-up builder take 2 parameters as input, a URL of the web page and an XPATH of the content. Once these 2 things are ready, I cleverly used JSONP to render the content on page.

I recommend you to see the source {view-source} to understand the working of the mash-up.


Warning
Since mash-up builder injects HTML content directly from external source, its  prone to CrossSite Scripting attack. My website is not hosting any private content , so to me its fine because no security can be breached, do not try to replicate this functionality on your website if your website is hosting some private content.

  LIVE DEMO  




Feel free to share on twitter, Facebook & other social networking sites. 

Saturday, April 3, 2010

IPL Tables made sortable

Ever since I visited the official IPL website, I hated those static points table.

So I used YQL to grab that data and place in very sortable fashion here.




To create this I am using,
YQL 
Google visualization API  (optionally one can use YUI)
Jquery tabs

Tuesday, March 16, 2010

Chrome Extension to analyse tweeter (Twitter User) Behavior

Recently I was looking on various sites that shows some statistics about tweeters (twitter user). They are great but they often focus on one thing, there is no single place where we can see all these analysis. So i closely analysed these websites to come-up with YQL hack to bring all of them on a single page. Mainly I focused myself on these websites.

  1. http://twitterholic.com/
  2. http://web.forret.com/tools/twitter-tq.asp
  3. http://tweeps.info/
  4. http://happytweets.com/
  5. http://tweeteffect.com/
TweetChrome

[I am also trying to pull information from http://tweetstats.com]

Well if I would have hosted this functionality something like this (actually hosted ).  No one will use it, because people are very lazy. So I have created a chrome extension here.

If you use chrome then you can simple see source code here.

Thanks for reading my blog.

Saturday, February 13, 2010

Playing with Javascript Closure, JSON, & YQL to Visualize upcoming Android Version Names

Hi There,
As you know that First version of android was named "cupcake" and then it was "Donut" and current version is "Éclair".
People found a pattern in naming; they are alphabetical names of cake. Now many people on internet came up with the names up to the Z.
Here they are

  • Cupcake
  • Donut
  • Eclair Cake
  • Frosting
  • Gelato
  • Honey
  • Icing cake
  • Jelly
  • Kiwi
  • Lemon
  • Marshmellow
  • Noodle
  • Orange
  • Pudding
  • Quince
  • RockyRoad
  • Sundae
  • Taffee
  • upside-down-cake
  • Vanilla
  • Waffle
  • Xmas Cookies
  • Yogurt
  • Zebra Cake


I am completely unaware of some of these names; I really don’t know how they look like. So here i made a small YQL hack to get images with these names to visualize them.


Here is the YQL Bing table query to images





function get_images_from_bing(query,callback){
var yql_url="http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20microsoft.bing.image%20where%20query%3D%22"+query+"%22&format=json&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys&callback=callbacks."+callback;
var div_ele=document.getElementById("myscrpts");
var scrpt=document.createElement("SCRIPT");
scrpt.src=yql_url;
div_ele.appendChild(scrpt);
}

Here I am using closure to get a call-back function which will render the my images.




function GetCallbackFunction(element){
/*
element will be accessible to inner returned function
even after outer function has returned
*/
return function(data){
/*Get randomely from top 3 images*/
var index=get_random(3);
index=index%data.query.results.ImageResult.length;
element.src=data.query.results.ImageResult[index].MediaUrl;
};
}

Saturday, January 30, 2010

I know what you read on dzone last summer

You should know that depending upon how CSS is coloring your links; I can figure out that what are the links you visited already.
This is a nice hack, many people use it for knowing user interests e.g
  • What social networking site you use.
  • What banking site you use.
  • And many more what you can think of.
I have created a hack to show all popular links from dzone, I am sorting the links based what you have read already. Before you read further Check This, (will not work in IE8)

Here is how you can inspect CSS color of a link in your browser


document.write('<style>');
document.write('
#linkID:visited {color: #FF0000;}");
document.write('
</style>');

/* quickly add and remove the link from the DOM with enough time to save the visible computed color. */
document.body.appendChild(link);
var color = document.defaultView.getComputedStyle(
link,null).getPropertyValue("color");
document.body.removeChild(link);

/* check to see if the link has been visited if the computed color is red */
if (
color == "rgb(255, 0, 0)") {

/*visited do something*/

}
else {

/*not visited, do something else*/

}




Read More about How I brought All Dzone links on 1 page

Read More About How This CSS hack works?

Read Rest of My Hacks


Thursday, January 28, 2010

Understanding C#.net Border-less Form, when you maximize it

Hi There,
Have you ever created, a borderless window in C#.net?
There is problem with borderless window, if you maximize it, it goes FullScreen (over the taskbar).

Here is an analyis of how to achieve maximized borderless window.




If  you first set the border(anything other than FormBorderStyle.None) for the window and then set WindowState to maximize, You will get a standard maximized window, you can make it border-less there after.





private void btMaximize_Click(object sender, EventArgs e)
{
this.FormBorderStyle = FormBorderStyle.FixedSingle;

if (this.WindowState != FormWindowState.Maximized)
{
this.WindowState = FormWindowState.Maximized;
}
else
{
this.WindowState = FormWindowState.Normal;

}

this.FormBorderStyle = FormBorderStyle.None;
}





If you maximize a window after making it borderless it goes beyond the task-bar. You will get complete full-screen.



private void btFullscreen_Click(object sender, EventArgs e)
{
this.FormBorderStyle = FormBorderStyle.None;
if (this.WindowState != FormWindowState.Maximized)
{

this.WindowState = FormWindowState.Maximized;
}
else
{
this.WindowState = FormWindowState.Normal;
}

}





Sunday, January 17, 2010

Hacking Google maps AJAX API to use in C#.Net

Hi,
As you know “Google Maps API” is available only for AJAX developers. Using it in C#.net is not possible. One of the great things about Google maps API is it gives you turn by turn direction almost anywhere on earth. I wanted to exploit this feature of turn by turn navigation on my mobile, that too offline, because when i go to remote places its highly probable that i will not be having connectivity on my phone. Or connectivity will be so poor that using maps is highly impractical.

So I have created a pair of application.
1. A Desktop app to retrieve turn by turn navigation data + static images.
2. A Mobile app to read this data and to give me turn by turn navigation on phone (offline).

Certainly this is something not allowed in TOU of Google, so i cannot release this app commercially.

How to Mix AJAX and C#.net??
1. I created a web page (html+JavaScript), which dumps the direction info data in DOM.
2.In C#.Net Form, I kept a web-browser control, which loads this page.
3.When page is loaded, using webBrowser1.Document.GetElementById stuff I extracted the direction info.
4.Then I downloaded Static Images using "Google Static Maps API", & hacked to get the latitude and longitude positions on the static images. see code for detail.


How I exported data on mobile??
1. Serialized whole object in an XML file, including direction info and static images.
2. De-serialized on mobile to get that data back.


Source Code
http://code.google.com/p/pocketnavigator/


Screen-shot Of Mobile Version.



Demo of Desktop App (6 minute).

Thanks, Feel free to ask question, & share on twitter + digg & blah blah.

Thursday, December 24, 2009

How to Use TextToSpeech Feature of Google

Here is how you can make your own TextToSpeech App, using Google's un-documented API.

Google Has an undocumented REST API to get TextToSpeech

http://translate.google.com/translate_tts?q=your+text+goes+here
Here is the HTML Code. Do not miss to see the screen-cast.

<html>
<head>
<title>
Text To Speech Demo
</title>
<script>
function GetSpeech()
{
var framehtml="<iframe src=\"http://translate.google.com/translate_tts?q=";
framehtml+=escape(document.getElementById("mytext").value);
framehtml+="\" </iframe>";

document.getElementById("myframe").innerHTML=framehtml;
/*we are done!!!!!*/
/* we will test now*/
/*wow!!!!! its working :) */

}
</script>
</head>
<body>
Enter your text Here
<textarea id="mytext">
</textarea>
<button id="mybutton" onclick="GetSpeech();">
Click me to get the text
</button>
<div id="myframe">
</div>
</body>
</html>

Here is a screen-cast


Thanks Guys
Happy Christmas

Sunday, December 20, 2009

Jump into 3D maps by calculating orientation

Lets make a VirtualDrive MashUp today. As you know that Google maps API has Street view feature and Live maps has Bird’s Eye view feature. We will mix these 2 things in our mash-up.
Feature of This MashUp will be
  • To Take input as source and destination address.
  • Animate the street view & Bird’s Eye from source to destination.
To get this done you will need direction API to know the path between source and Destination. Eventually Google’s Direction API will do this for us. Direction API returns a PolyLine from source to destination. We will use GDirections.getPolyline() Function. Once you have all the points (Latitude and Longitude) along the path you are all set to go. But wait street-view and Bird’s Eye view are 3D Maps they also have something called orientation .
Bird’sEye View requires only one extra parameter "orientation" which can be
  • North
  • East
  • South or
  • West
Where as Google Street View is more complicated , its requires Yaw and Pitch (i am ignoring zoom level which applies to all kind of maps)
image
Since we will concentrate on driving , we will keep the pitch horizontal i.e. pitch will be zero.
Yaw can be calculated by using 2 points along the path. Yaw is the angle of your driving direction from North, in degrees.
Here is a JavaScript code to calculate Yaw with given 2 values of GLatLng.
(Note that Yaw & Bearing is closely related terms and they are having same value here.)
function GetBearing(GLatLng1, GLatLng2) {

var lat1 = GLatLng1.lat();
var lon1 = GLatLng1.lng();
var lat2 = GLatLng2.lat();
var lon2 = GLatLng2.lng();
lat1 = lat1.toRad();
lat2 = lat2.toRad();
var dLon = (lon2 - lon1).toRad();

var y = Math.sin(dLon) * Math.cos(lat2);
var x = Math.cos(lat1) * Math.sin(lat2) - Math.sin(lat1) * Math.cos(lat2) * Math.cos(dLon);
return Math.atan2(y, x).toBrng();
}
One feedback about street-view API though, function setLocationAndPOV is very mysterious and I could not make it work.
Individual Code snippets I picked from here
  1. Google AJAX Playground
  2. Live Map APIs Sample
  3. movable-type
Now Jump To Demo

And Do ViewSource to see the code.

Wednesday, November 11, 2009

Phonetic Translation For Hindi

Hello!! I am an Indian, and for obvious reasons I have many friends on twitter who are also Indian and  we communicate in Hindi very often. Wait!! We don't type Hindi on twitter, because Hindi typing requires a special keyboard (or at least special Input Method), which we typically don't keep with us. Its because we Indian officially work in English Language.

So if you are a foreigner and You see this phonetically typed Hindi, No way you can get it translated to your own language.

So For you I have created a small JavaScript hack so that you can translate Phonetic Hindi into your own language.

This is not for only who are foreigners, If you are Indian & still you have problem in understanding Hindi, here is Tool for you.

Demo

How to develop on your own??

This is a Mashup. I am using 3 different service.

1.Script Convertor

2.Google Translate API

3.YQL (a very useful platform for creating mashup)

To see the source code open the demo page and view source.

I have written only few lines of  of JavaScript to do this.

Sunday, November 8, 2009

Coding Bullshit Meter (Outlook Addin)

I thought this will be fun. We developers often get some mail from corporate management, which are completely bullshit to us. How much bullshit it has?? Lets calculate? To calculate I have created a small outlook Add-in (plug-in) which will Display the bullshit percentage on the ToolBar when you select the mail item.


Some of the keywords its uses to calculate the bullshit is this


synergy,strategic fit,gap analysis,revisit,bandwidth,best practice,bottom line,hardball,out of the loop,benchmark,value added,proactive,win-win,think outside the box,fast track,result driven,empower,knowledge base,total quality,quality driven,touch base,mindset,client focus

This is the first time i am developing any kind of Add-In for any application. I used Visual Studio 2010 (beta) 2010 for developing.

You will get many problems,  when you will develop an outlook plug-in. One of the biggest problem I faced was that "Event of 'Item selection change' was not firing".
this.Application.ActiveExplorer().SelectionChange
I finally come to know that you need to keep a reference of the ActiveExplorer all the time in the class.

Ok, this trick worked!!!

Download Source Code Here

I am not creating installer for this (or any kind of set-up). If at all you want to use this, please download the source code and compile on your machine. You might need Visual studio 2010 for this.

Thursday, August 27, 2009

YQL hack to get DZone popular articles on 1 page

Problem with DZone feed is, it contains the link to DZone page. No way i can jump to article, skipping the DZone page. At the end of this article You will be getting a simple YQL based hack to get a DZone popular links on 1 page linked to original blog page.
Note: if you are not interested in how i got it Jump to Demo.
STEP-1
Using YQL first get the popular links.  using feed table (use YQL console).
URL to popular link feed is http://feeds.dzone.com/dzone/frontpage
So my YQL query will be.
select * from feed where url='http://feeds.dzone.com/dzone/frontpage'

You will get the details of all popular articles linked to Dzone’s page (same as in feed).
I am just interested in links so my YQL will be (replace * by link).
select link from feed where url='http://feeds.dzone.com/dzone/frontpage'
STEP-2
With all those link retrieved in the step-1, get the HTML page out of it. get the title node using an XPath query .
First by simple DOM inspection i can figure out that title node is wrapped in a DIV element  whose class name is ‘ldTitle’.
select * from html where url in (select link from feed where url='http://feeds.dzone.com/dzone/frontpage') and xpath='//div[@class="ldTitle"]/a'
Select format as XML and grab the REST URL
which will look like this
http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20html%20where%20url%20in%20(select%20link%20from%20feed%20where%20url%3D'http%3A%2F%2Ffeeds.dzone.com%2Fdzone%2Ffrontpage')%20and%0A%20%20%20%20%20%20xpath%3D'%2F%2Fdiv%5B%40class%3D%22ldTitle%22%5D%2Fa'&format=xml

STEP-3
Now Time to do some tweaking. if i get this data in XML i have to parse it. if i will get it in JSON, JavaScript will do all the parsing for me. That's why i love JSON.
Now if i get everything in JSON i have to regenerate DOM via a JavaScript code. I am lazy to do even that. So i want result formatted in JSON and DOM section as it is(i.e. in XML).
I can do this by putting a call-back as argument in above REST URL.
so my REST URL will be

http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20html%20where%20url%20in%20(select%20link%20from%20feed%20where%20url%3D'http%3A%2F%2Ffeeds.dzone.com%2Fdzone%2Ffrontpage')%20and%0A%20%20%20%20%20%20xpath%3D'%2F%2Fdiv%5B%40class%3D%22ldTitle%22%5D%2Fa'%0A%0A&format=xml&callback=loadlist

My call back name is ‘loadlist’. so lets implement this call-back.
which is like this.
function loadlist(data)
{
var content_div=document.getElementById('content');
if(!data.query)
{

content_div.innerHTML="error.. failed to load"
}
else
{
var i=0;
var html="";
for(i=0;i<data.query.count;i++)
{
html= html+data.results[i]+"<br/>";
}
content_div.innerHTML=html;
}
}


To see the full source code, visit this page and view source code. I have implemented extra function ‘track’ for some purpose. .


Sunday, August 23, 2009

7 things I did on my blog, to make it a better place to read

Readability & accessibility for a blog is very important.  You need to give few good reasons to your reader to bring them on your blog site. Today, when technology is really advanced we need to re-look our blog website & think of few additional things.  This blog has all those 7 things, which I am going to discuss. I consider my blog most accessible in all forms. Good theme for readability, easy to share, optimized for speed, accessible on mobile, user can choose to translate in his language & last but not the least user can choose to listen its content.

1. Choose better theme.
This is most basic thing. Clean and neat theme on a blog is very important. White background with black colour text is most appropriate theme.  Do not put too much of flashy advertisements or flashy content, they not only distract & confuse your readers; they also slow down the loading time. This article might help you to choose better theme.

2. Make it easy to share & comment.
Blogging is a form of social media. It’s very important to have better interactivity with your readers.  Comment form must be having various options; user should not be forced to login to put comment. Yes, if don't want any unwanted content to be posted by your readers, your can go for “comment approval” option.
These days’ people love to share blogs on various channels. Add buttons like addthis, dzone, tweetmeme(blogger, wordpress) digg(blogger, wordpress) etc to make it easy to share.

3. Optimize for speed.
Adding to much of buttons, poor theme and gadgets might slow down loading time of your blog site. Here are 3 things you can do to improve performance.

i. Put all unobtrusive scripts at the bottom of page.
As you know most of the gadgets and buttons are based on JavaScript. Adding too much of buttons and gadgets might slow down loading time of your blog.

Any JavaScript block, freezes the loading of rest of the content till complete JavaScript code is not loaded. So you can effectively bring readable content much early, by putting most of the JavaScript blocks at the bottom of the page. Question is how can you decide, what can be kept at the bottom of the page? Any script which only executes when entire webpage is loaded can be brought the bottom of the page. In more technical terms any unobtrusive code can be kept at the bottom of the page.

ii. Use CDN (for better loading time) .
One way to get free CDN is “Google’ App Engine”. Read this article.

iii. Run tests like Yslow or Page Speed.
YSlow and PageSpeed are a plug-ins for Firefox (on top of Firebug). These plug-ins can run a test on websites and can tell you what can be optimized.  They will provide huge list, though you can not achieve all of them easily but if you even achieve 50% of them your website will be much faster than any webpage. If you really want to see most optimized web page see yahoo home page. They have lots of content on the website but still loading surprisingly low.

4. Automated podcast (sometime listening is better).
If you are kind of guy, who write long descriptive content, automated podcasting feature might help your reader to have an option to “listen” rather reading it. Odiogo gives free automated way to get podcast of your blog text. It has built-in text-2-speech feature, which will narrate your blog.

5. Automatically Translatable.
Automated translation might not help a lot, but can be really handy for foreign users. Use Google Translate widget on your blog so that user can easily translate.

6. Mobile readable.
Many people prefer to do blog reading on their mobile. There is an easy way to create mobile version of your website. You can use Mobify, to get mobile version of your blog. Getting mobile version is easy; you can get it in 3 easy steps.

7. Add some fun.
On my blog you can drag those sidebar gadgets, such kind of functionality can help reader to play with your blog.

Thanks for reading, Love to see your comments.

Sunday, August 9, 2009

Top 11 Language Concepts That Every Developer Should Know

There are a few fundamental things we have invented in programming languages,
which was invented at various point of time, particularly by one language and they were later adapted by many other languages.
I am going to list some of them, which have bigger impacts.


DataType
The first and foremost thing which we have ever invented is the data type. Computers were  just a dumb machine, which could only understand the binary sequence. Binary sequence made no sense till it was grouped to form a DataType.
As you know a DataType, is something which groups the binary sequence together and represents some entity in mathematical word OR real word. All depends on its interpretation.
DataType is not just a grouping of binary sequence but also a set of operations which it posses. I mean a DataType definition just don't end with its binary  grouping but also the operation which can be performed on those entities.
Later we have evolved these DataTypes into more complex form. We used mathematics to bring various complex data structures like List, Stack, Queue etc.
Today almost every programming language directly or indirectly have concept of data type.


Pointers
With the invention of computers, we've   also invented the concept of loading and storing data from Hardware. Computers accesses memory by toggling special bit patterns in the  wires (which was called data bus).  This  led to the invention of Pointers in our high level programming languages.
Pointers specially became popular in C programming language. Pointer is one of the most popular programming concepts ever invented.  Other than C language, pointers are supported by languages like C++,C#, Fortran, Pascal. Few dialects of BASIC also supports pointer.


Structured Programming
Most of the programs in the early days were completely relying on GOTO statements, which was a real mess and was making programmers life real hell. Now that's where we have invented the "structured programming " another fundamental programming concept. Through this concept we have brought something called functions, and subsequently we realized the power of abstraction.


OOPs
I think OOPs (Object Oriented Programming) is one of the most popular and ever lasting fundamental concept we have invented in history of programming languages. OOps is an umbrella concept. We have brought many concepts under this.Concepts like Data hiding, Inheritance, abstraction, polymorphisms (static & dynamic) were just the beginning of OOps. OOps is available directly or indirectly in almost all modern languages. Languages like C++, java & c# have brought it a long way.


Regular Expression
Regular expressions provide a concise and flexible means for identifying patterns in string. This is used for searching and replacing special pattern in a string.If your favourite programming language is supporting Regular Expressions, and you are still thinking of learning,then this is the time to go and learn. Regular Expressions are now supported by many languages (almost all popular programming languages). Additionally Regular expression became standard language for many find and replace system utilities. Unix command (utility) Grep is one of the most popularly known Regular Expression based utility. Regular Expressions became so popular concept that many programming languages made it as the part of there language syntax (construct).Languages like  Perl, Ruby and TCL embraced regular expression as their primary language construct.


SQL
With the invention of Relational database, where everything is stored in the form of Tables, SQL type of languages evolved. This was mainly developed for  data query, data update, schema creation & schema modification. They became so popular that it was extended to make procedural SQL.
With the popularity of SQL, recently Google has brought GQL to abstract their Big Table ( a non relational data base). SQL like syntax is also borrowed by yahoo in YQL, to query data from anywhere on internet. LINQ in C#.net, is also inspired from SQL.


Managed Heap
Managed Heap OR Smart pointers, was another revolutionary concept which was invented as a hack of OOps concept (classes ) in C++. This was invented by Microsoft in a concept called COM. Smart Pointer, solved the problem of memory leak .
This concept was later adapted as default language semantic in programming languages like Java & C#. Later this was adapted by many programming languages like VB.net and Managed C++.


XPATH
XPath is another programming concept which was developed to access DOM tree, and became a preferred way to access the XML formatted data. This is another programming paradigm which you should be aware of, If by any chance you work with XML.



Duck Typing
The Term “Duck Typing” is invented by Python, though the concept of duck typing is old and was there in few languages earlier than Python.In duck typing, programmer is concerned with just those aspects of an object that are used, rather than with the type of the object itself.
Let's understand this. Let us say we have a real life object Shape, which knows how to draw itself (with a method draw).  Now in OOps, We enforce this by creating an interface something like IDraw, any anything which can be drawn on the screen must be of type IDraw(i.e It should be inheriting IDraw). I Duck Typing, object can be drawn on the screen as long as object holds the draw method,irrespective of the type of object. DuckTyping removed the dependency of common interface definition, which are typically shared by client and server modules in OOps languages.  Disadvantage of such thing is, programmer will not be able to know at the compile time, that the object is not having the draw method in it. But wait, python does not have compile time, its interpreted language, so all the problem can only be identified during the runtime.
One thing i am sure about DuckTyping is that it is very risky deal when you are building a big (cathedral like) software. But it is very good when you are writing  very small quick and dirty lines of code.
Duck Typing is supported by Python, JavaScript(and similar languages) & C# (for your surprise, read this nice example).
Duck Typing helps a lot in JavaScript, in fact the concept of “JSON based AJAX” is completely based of duck typing.
Duck typing is a very controversial concept, many OOPs lovers hate this concept.


Closure
Some languages (e.g. JavaScript) allows you to define a function inside another function. Closure is the scope, which inner function is having.  Coolest part of closure is, scope remains valid even after outer function have returned.
One of the nice example of closure is this (in JavaScript), Inner function dofading will still be having access to ‘Div_InClosureScope’ even after the Fade have returned.
function Fade(id)
{
var Div_InClosureScope= document.getElementById(id);
var level=0;
function dofading()
{
var hex=level.toString(16);
Div_InClosureScope.style.backgroundColor='#ff'+hex+hex+hex+hex;
if(level<15)
{
level++;
setTimeout(dofading,100);
}
}
setTimeout(dofading,10);
}
In more general term, closure is a special scope, provided to a special instance of a function. In OPPs the member function enjoys closure (data members are in closure scope). Programming language C does not have closure concept at all. Its a most simple and straight language.

Yield
I found this technique first in python.This was not something new, but can confuse most the programmers from c/c++ background. This technique somehow stores state of iterator (I will explain latter), and returns different result at different time, and this is something c/c++ programmers are not used to. Any C/C++ programmer assumes a function is a stateless machine, which can return only one result for given set of argument, no matter how many time you going call that function.


A Python function stack can be unwrapped( retuned) in 2 ways, by a return statement or by a yield statement. A return statement stops the execution of a function (same as in c/c++ ). On the other hand an yield statement halts the execution of a function and store the state, so that when it will be invoked later, execution will start from the same point.


Lets take an example of typical Fibonacci number generator.

#An endless generator
def fibonacci():
i = j = 1
while True:
r, i, j = i, j, i + j #respective assignment
yield r

for rabbits in fibonacci():
print rabbits,
if rabbits > 100: break

Output
1 1 2 3 5 8 13 21 34 55 89 144

Python certainly support, C++ like return statement, but using yield is most efficient for this such generators. All those recursive way of writing Fibonacci number generators are really inefficient( though they look simple).
Yield statement is also supported by C#.net.  Here is one of the nice post about yield in c#. Do not miss!

I love this article, "Life after loops". somehow, its connected to this blog post

Monday, July 6, 2009

2 Steps to make your (blogger based) blog translatable.

Here are the 2 step to make you blog translatable, Like this.

STEP-1
Grab This code
<script src='http://www.google.com/jsapi' type='text/javascript'></script>
<script type='text/javascript'>
google.load("jquery", "1.3.2");
google.load("language", "1");
</script>
<script src='http://jugad.googlecode.com/files/translate.js' type='text/javascript'> </script>

STEP-2
Go to blogger, and "Edit Layout" Section, and choose "Edit HTML".
In Head Section just paste the above code, Save and exit.

Optionally You can also add a title less Gadget of type "HTML/JavaScript" and paste the above code. But it might not work all the time.


Please feel free to leave comment if its not working with you.

For the advanced Users:
I have created a Unobtrusive JavaScript code, Here
This requires Google Language API & jQuery.
First two script block above is to bring jQuery in your blog and then my script to produce a translate "combo box", which can be used to translate your blog.

Demo: Click Here
Source: Click Here

Thursday, July 2, 2009

Quick and Dirty Way of Buffer Serialization in C#

This article will tell you to get raw buffer from the c# structure. Basically C# is a TypeSafe language, it never lets you to access byte-stream of any managed object. But You can still make a raw buffer using Marshal.StructureToPtr Method . Today, In this article I will introduce you to new serialization format called QP-Encoding(Quoted-Printable Encoding). QP-Encoding is old encoding style, but known to very little people. Its very simple to understand.
Its a string formed from Raw buffer, whose every byte is represented by '=XX' way. In QP every byte is represented by =and followed by the 2 character of Hex which tells you the value of that byte. BUT if byte is printable it will be printed as it is.

For Example: a buffer whose byte sequence is 41,4A,4F,08 Then QP could be =41=4A=4F=08 but since 41 4A and 4F is printable character you can also write as ")JO=08" (as a better QP)

Using marshalling technique here you can transform any(almost any) c# managed object into QP string using following function
static public string SerializeBuffer(object obj, ref int size)
{
size = Marshal.SizeOf(obj.GetType());
IntPtr ptr = Marshal.AllocHGlobal(size);
Marshal.StructureToPtr(obj, ptr, true);
byte[] byteArray = new byte[size];
string encode_qp = "";
for (int i = 0; i < size; ++i)
{
byte b = (byte)Marshal.ReadByte(ptr, i);
encode_qp += "=" + b.ToString("X2");
}
Marshal.FreeHGlobal(ptr);
return encode_qp;
}
This is How you can DeSerialize
static public void GetDeSerializedBuffer(ref object Obj, ref string QPData)
{
int size = Marshal.SizeOf(Obj.GetType());
IntPtr ptr = Marshal.AllocHGlobal(size);
for (int i = 0; i < size; i++)
{
Marshal.WriteByte(ptr, i, ReadByteFromQPString(ref QPData));
}
Obj = Marshal.PtrToStructure(ptr, Obj.GetType());
Marshal.FreeHGlobal(ptr);
}

Thursday, June 25, 2009

How to add Tabs on blogger?

[This is old post, you can follow easy steps , with new blogger template designer here]
Here is a step by step procedure to add tabs for your blogger.

STEP-1 Go to Blogger Dash board

STEP-2 Go to layout section of your blog, and go to edit HTML
[Save your template, to make sure that if anything will go wrong, you can restore the things back]
STEP-3: Grab this code
#tabsB {
float:left;
width:100%;
background:#F4F4F4;
font-size:93%;
line-height:normal;
}
#tabsB ul {
margin:0;
padding:10px 10px 0 50px;
list-style:none;
}
#tabsB li {
display:inline;
margin:0;
padding:0;
}
#tabsB a {
float:left;
background:url("http://sites.google.com/site/hackbit/tableftB.gif") no-repeat left top;
margin:0;
padding:0 0 0 4px;
text-decoration:none;
}
#tabsB a span {
float:left;
display:block;
background:url("http://sites.google.com/site/hackbit/tabrightB.gif") no-repeat right top;
padding:5px 15px 4px 6px;
color:#666;
}
/* Commented Backslash Hack hides rule from IE5-Mac \*/
#tabsB a span {float:none;}
/* End IE5-Mac hack */
#tabsB a:hover span {
color:#000;
}
#tabsB a:hover {
background-position:0% -42px;
}
#tabsB a:hover span {
background-position:100% -42px;
}

STEP-4 Paste this code(above code) just after body CSS which will look like this
body { 
background:$bgcolor; margin:0;
color:$textcolor;
font:x-small Georgia Serif;
font-size/* */:/**/small; font-size: /**/small;
text-align: center;
}

STEP-5 Grab following code (customize the link as per your need)
<div id="tabsB"> 
<ul>
<li><a href="#" title="Link 1"><span>Link 1</span></a></li>
<li><a href="#" title="Link 2"><span>Link 2</span></a></li>
<li><a href="#" title="Link 3"><span>Link 3</span></a></li>
<li><a href="#" title="Longer Link Text"><span>Longer Link Text</span></a></li>
<li><a href="#" title="Link 5"><span>Link 5</span></a></li>
<li><a href="#" title="Link 6"><span>Link 6</span></a></li>
<li><a href="#" title="Link 7"><span>Link 7</span></a></li>
</ul>
</div>

STEP-6 Paste the above code in you HTML template after header section (the line which will look like this)
<b:widget id="Header1" locked="true" title="Experimenting Blogger (Header)" type="Header">
</b:widget>

STEP-6 Done!!, save the template and view your blog
You can get some different kind of tab design here