Thursday, February 22, 2007

Introducing tvHtmlHelper and TagCreator

I just saw this helper class called pQuery on ajaxian today .written by vikas from delhi ,that offers a very modest way of generating your html code with the necessary attributes for the html elements ,etc .

The good news is that its nice to see someone featured on ajaxian . (both vikas and myself are 23 btw...cheers to that ! ). The bad news ,i knew he could do better .

The API needed a little bit more extensibility and scalability . And thats how i got on a hacking marathon to show how to integrate this class ive made to make ...say a tag creator .Here is vika's code usage :

PHP implementation of pQuery:

  1. =$pquery->form_remote_tag(array('url'=>'index.php?task=ajax','update'=>'#idtoupdate'));?>
  2. Field : "field"
  3. < type = "submit">

My first comments ? Very shabby !

Here my custom built html helper , i write - that would not only go with jQuery ,but heck i use it for spitting out everything from body tags with onload 's , to hr tags , and tables -tr's running in reccursive loops .

Demo of tvhtmlHelper.php:

/**
* @description - A simple Tag creator written in php that uses tvHTMLHelper
* @author Bhasker V Kode
* @date Feb23,2007
* @copyright Some Rights Reserved
*/

class TagCreator extends tvHTMLHelper{
public function
addTag($type=NULL , $tag=NULL){
switch(
$type){
case
'technorati':
/*OUTPUT :will output the html for a tag .
return $this->insert('a','start',array("href"=> "http://www.technorati.com/tags/$tag" ,"rel"=>"tag")) . $tag . $this->insert('a','end') ;
break;
/*
case 'youtubeVideoLink':
// follow similiar style to embed a youtube video , or so on for other widgets of your choice .
*/
}
}


$myInstant = new TagCreator;
echo $myInstant->addTag('html','start');
echo $myInstant->addTag('body','start',array("onload"=>"init();" , "class"="bC");
echo $myInstant->addTag('technorati','tvhtmlhelper');
echo $myInstant->addTag('technorati','bosky101');
echo $myInstant->addTag('technorati','php');
echo $myInstant->addTag('body','end');
echo $myInstant->addTag('html','end');

Notice the following design differences pQuery and tvHTMLHelper:
  1. Inheritance is good for you !
    Primary usage pattern would be to extend this class where you deal with html a lot.
  2. To echo or not to echo !
    If youve noticed ,in pQuery it prints instead of returning . Mine does not echo on its own .but return the html string instead ! .This can be used when you need to generate html to be used later ,like writing concatenating to a string /or sending mail /etc . Being generic never does any harm in helper classes. This i feel is a big pitfall in pQuery .
  3. Clear cut definition boundaries of beginning and ending .
    The API has a startEnd for obvious reasons. This might be a major fallout in pQuery . If you do attempt to seperate presentation from logic , then why make it half way ? do it well or its better off not to do it at all .
  4. Scalability.
    Now tvHtmlHelper does not limit you to jQuery but basically every web page . Heck ,i even use it for a custom build stringToXML class ive written where i could use the API in loops like this :
    • $myInstant->insert('channels','start',array("length"=>1,"foo"=>"bar") );
    • OR links
    • $myInstant->insert('a','start',array("href"=>$link1,"id"=>"foo","class"=>"fadeClass") );
  5. Useful across file types : xml ,html , tagging ,and link generation !
    You could even extend tvHtmlHelper to replace the < > symbols with custom ones or words .like ,what ever you pass through the API will come out as a technorati tag !
Ive put a demo page ,which you can check out . Ive ported tvHTMLHelper to both php4 as well as php5 . Have a look at the sourcecode ( rar file) !

I'd love to get any feedback on this ,or places where you might be able to use this .

Keep Clicking,
Bhasker V Kode



Technorati Tags: , , , , , , , , , ,

Thursday, February 15, 2007

Adding Idempotent Event Handling to your Javascript Toolkit

Idempotent transactions are ones which may be repeated without affecting anything. You may have heard of this term when it comes to online banking ,where idempotent transactions are required ,and basically care needs to be taken to rollback , and not accidently charge twice for the same purchase .

So im trying to extend this to a javascript scenario ,where clicking on a button twice in quick succession will be ignored . This may well be used in a registration / payment / complex timed ui / or any other critical operation . Or basically to add a bit of fun to anything event driven !

Explanation

Let us assume that you dynamically add an event to an object . Now with Reusable.DeferredEvent , it throws a similiar api , gives you an option to specify your existing addEvent code -.Popular version of which are :
So basically what i have is a plug'n play support for handling idempotent events , using your existing javascript toolkits corresponding dynamic event handling capabilities . In the demo page , I have shown how to integrate with these frameworks by uncommenting the suitable line of code as needed.

Which means for configure listenEvent event for every listenTill seconds , for any listenObj object .


In the demos , you will find two scenarios :
  • Only unique button click's on Button1 in the range of 1 seconds will be recognised !
  • Only unique mouseouts on Button2 in the range of 3 second will be be recognised.




//@param name of instance
//instantName = new Reusable.IdempotentEvent(instantName);
// Step 1 : Instantiation
responsive = new Reusable.IdempotentEvent('responsive');


//@param listenObj - DOM listenTillelement or element id
//@param listenEvent string - Event name (as per your toolkit nomenclature )
//@param listenTill int / string - how frequency to accept event triggers
//@param callBack string - What function to callback eventually

// Step 2 : Exeuction
//responsive.register( listenObj , listenEvent , listenTill , callBack );
responsive.register( btn1, 'click' , btn1.getAttribute('onclickwhen'), 'clicked' );
responsive.register( btn1, 'mouseout' , 1000, 'hovered' );






Demo and Code here .


Technorati Tags: , , , , , , ,

Monday, January 29, 2007

A Profile of TechEnclave


So, I've also always wondered if the portal a handful of '20-something year old' geeks and myself have built over the years totally in our spare time - would figure as being part of the Indian web innovation revolution .

It's called TechEnclave , famed for its forums ... ( http://www.techenclave.com/forums ) Being a moderator for the forum , we're all excited that the member base that Team TechEnclave have been really building the community from 2002-03 onwards with experience gained from a temporary hosted forums ,to other experiements through '04, - 05 and finally fixed on the TechEnclave brand ,and have stuck to it ever since the end of 2005 .

The reason why i 'm talking about it now - is also to highlight the transition we've seen with the web 2.0 revolution hitting the indian plains . Sure , we did implement ajax based forum search options before it became cool , and we do have some forum regulars like a calendar that the 10k displaying birthdays ,user meets ,and so on . We've even had our TE user meets where we get to interact with the members dating to early 2005 . And with over 25- 30 of them across the country over the years - its not really tough to see why the unconferencing theme dint take too long to pick up in India. Today TechEnclave has over 25 forum sections covering hardware overclocking to gaming , portable devices and Tech News from across the world .If TechEnclave as become what it is today , it has been off the strength ,quality and relevence of its Forums - be it for the tech noobie , geek gurus or the persistent troubleshooter .

Some other statistics TechEnclave as of Nov 3 , 2006
Members: 13,500 +
Threads: 27,229
Posts: 292,544,
Most users ever online was 1,363, 28 Nov 05 2005 at 01:18 PM.

So ...coming back to how TechEnclave fits in as a interesting collage of user-feedback inspired product innovation built inhouse...

1 ) TE Spy
an inhouse clone of digg spy ,developed in ajaxian ishtyle , and shows in real time when new posts made at techenclave ... currently for premium members only . But the amount of content we throughout the day ensure that the TE spy functions like a charm . If you are registering at TechEnclave , we'll be happy to upgrade you to a premium membership .Just let me know your user id ,and then you can check out TE Spy for yourself .









2 ) TechEnclave Addons & Initiatives
The TechEnclave ToolBar , A nifty little addon for Firefox helps our users search and naviagate across the site better . We also have an exclusive download manager apart from the recently added hardware benchmarking software located at http://www.techenclave.com/forums/superprime/ as well as numerous other nifty utilities like bookmarklets , feed aggregator widgets ,newletters , rss feeds , and so on .


3 ) TE Rig Gallery
TERig was an idea that we at techenclave had for a long time. We wanted to give , the tech enthusiast a medium to showcase your rig to the world. From our feedback on the forums ,we understood that the true potential of your rig can only be shown when your rig details are presented in a well formatted manner and with the all important pictures of your rig. So our admins Safin and QuickFire , went about hacking just that . Not only will you be able to put your rig specs in a well formatted manner, but also will be able to view where your rig stands vis-a-vis other's. Till date ,we are the first forum to have such a versatile system ...check it out at http://www.techenclave.com/forums/RigGallery.html
transcending the role of a forum .












4 ) TE iTrader ( Market )
A custom built environment that provides a better showcase of the product that users put up for sale .










5 ) TE Price Guide
Based on feedback over the years ,we even felt the need for a comprehensive and updated price guide for hardware ,whatever be the city you are in india. So welcome another custom built app . the TE Price Guide located at http://www.techenclave.com/forums/hardware-prices.html which has now attained a sort of lengendary status of sorts over at the "Build Your Own Rig" followers in India . We even have a seperate Market Section where users can swap their new and old stuff .This initiative has gathered a lot of traction for genuine buyers and sellers especially ,for reaching users in the the non metros .


The TE Family
Apart from helping troubleshooting across 20 odd forum sections ,being part of the Techenclave , has helped bridge distance for the indian techie and transcend geekdom !
TechEnclave 's depth of quality in its reviews and experienced members helped it become a source to present demos at hardware branding and launch expos . Infact ,name any piece of hardware or software ,and you can be sure that theres someone from techenclave whos' got it first or swears by their favourite utility . Also of note is the sister forum that we've created called FunEnclave over at www.funenclave.com

The people behind TechEnclave ( http://www.techenclave.com/forums/staff.html ) are dedicated enthusiasts who came together because of their expertise and being identified as uber geeks and experts by their peers ,combined with a blend of effective management , marketing and creative abilities - to make things happen . We take pride in building one of India's Biggest Technology Forums from scratch without any commercial backing or investment by putting back all ad generate revenue back into getting better servers , bandwidth and so on .( You can see a brief history and evolution of techenclave over at http://www.techenclave.com/forums/techenclave-history-and-evolution-720.html ) And we hope to keep the quality and members right up there ,to take TechEnclave to greater heights ! 8 )


If TechEnclave does not fit into the realm of indian innovations - we will understand . But If you think that this community has evolved ,then do let us know ,and drop in at the forums and find out for yourself . See you there...


Keep Clicking,
Bhasker V Kode ,

PS : If you do want to explore advertising options ,feel free to go through the page at http://www.techenclave.com/forums/advertisewithus.html .

This is a post meant to act as Profile of TechEnclave . So while it very well would be in the public domain,i'd appreciate the linkback .

Technorati Tags: , , , , , ,

Saturday, January 27, 2007

Good to be back in Chennai

Me in chennai for a few days...after a long break ,and the weekends been gr8 so far.

Attended the alumni meet and committed to helping out in the alumni site setting up as well .those guys are really stepping on the networking ,and the urgency is more so to gear up fto celebrate SVCE's 25th year of graduation to be in 2010 .

Showed off my new black dual-core 120 gb sata with dvd writer hp laptop to everyone at home here . its damn mobile and very sleek . am absolutely in love with it,and still think it was a better option that going for a mac ! (incidenly we just got another acbook ,bring the total to two now in our -10 odd strong develoepr & testing army at tutorvista's only office ( stpi ,electronic city,bangalore )

good news continues with my bro getting into Georgia tech, TAMU ,and Duke for his industrial engineering as well . Hes still waiting for stanford ,yale and darthmouth . All the best Bhargav !

Wrote a nice piece that i think a lot of my juniors at SVCE could use , and i think spend some time thinking about ,especially if your in a CS / IT department and contemplating a career in web based development.

Speaking of TE, the member base at TechEnclave has passed 13,500 geeks and looking good , We just completed a deal with Reliance Webworld for a banner display,and completed a small announcement deal with Rashmi Bansal - Editor, Jammag as well .

on the work front ,tutorvista just celebrated its first year anniversay at HINT, in bangalore central .a disc /pub that we booked all for ourselves and EVERYthing on the house !!! : ) . that was a freaking awesome party ! Getting into some new projects in office as well with the newsletter, feed syndication,apart from the now deployed googlish Calendar utility released live to our 2500+ paid customers. We're expanding on the hiring front as well - tutors,operations , developers ... conducted my first phone interview myself ;) ,plus its exciting that after our secodn round of funding of 10mln ,we're now going from the incubated unit at stpi to a full fledged 33 story byulding of our in the heart of Bangalore's corporate zone off the airport road.


went for a nice long move - salame ishq ,entertaining , india Vs west indies cricket match happening live here in chennai . and so is the cult fest saarang here at iit-madras campus.met up with my old buddies from school , called a few more . had a nice day out with my family and nrought my gf to my house for the first time to my mom and grand mom. spoke to my dad who's sailing after a long time . Madhu will continue to be in Biocon,bangalore till she leaves for her MS. And i think its time i thought about my plans for the near and distant future as well -education wise, health wise , personal life, wise in all respects ... Salsa classes have been doing me good as well....

Cheers to a rocking start to 2007 ....life is beautiful .... 8 )

Keep Clicking,
Bhasker V Kode


Technorati Tags: , , , , , , , , ,

Wednesday, January 03, 2007

Live Blogging a Javascript hackers first dive into Erlang

There comes a time in every developers life ,when you want to find out for himself ,what ,how and why the hell people swear by their languages .Especially when its not one that youve ever worked with . For me ,it started off with Paul Graham godfathering Lisp . No i havnt Lisp/scheme land yet .But i have instead gone into another one , inspired by the one paradigm that has got everyone from languages all over the place going gaga.

Functional Programming . And the language im talking about ........is Erlang.

Now being a javascript 'n DOM hacker myself, Ive always wanted to take on any claim that other framework combinations (read django,ruby on rails , pylon ,and the rest) have to well...claim as far as im concerned by quoting improved performance , rapid prototyping , and ease .

Do i think a well informed programmer javascript /DOM hacker is any less equipped to implement ANYTHING that a ruby on rails coder can ?

my answer is No. not yet anyway . Either that or i havent seen anything so exclusive to a ruby on rails that cannot be implemented otherwise .( Let the rants begin ..he he ... 8 P )


Coming back to Erlang .What im going to attempt to do is :
  • show the erlang example from the nice folks at erlang.org
  • rewrite the same in javascript ,
  • rewrite the same in javascript ,attempting a FP style.
erlang code for factorial
-module(tut1).
-export([fac/1]).

fac(1) ->
1;
fac(N) ->
N * fac(N - 1).

Execution
tut1:fac(4).
a modest javascript equivalent of erlang code
/**
* @author Bhasker V Kode
* @description a modest javascript equivalend of the erlang factorial example.
* @date Jan3 ,2007
*/
function fac1(number){
var total = 1;
for(var N=0 ; N <>


Execution:
alert(fac(4));
javascript equivalent of erlang code with a modest Functional Programming Style
/**
* @author Bhasker V Kode
* @description a modest javascript equivalend of the erlang factorial example.
* @note : oh erlang gods ! please let me know if this could have been more erlangish.
* @date Jan3 ,2007
*/
function fac(total,number){
if(number >1 ){
fac(total+number,number-1);
}else{
return total;
}
}


Execution:
alert(fac(1,4));

Now as the nice documentation said - what ive atttempted to do with this erlang program OR rather the highlight of functional style would be the limited need/scope of variables and instead the fact that the argument to a function can be the result of another function. Pretty wicked huh!

Now i know ive gone wrong somewhere . So if any erlanger / FP guru happened to see this ,they might know ?
  • if you cud make the js above with just one argument ?
  • if you should rather keep increasing the arguments being sent instead of increasing the sum
Lets move on to a more cryptic example of embedding functional style of programming into predominantly OOPs based javascript.

XmlWriter : a Javascritpt Class that uses minimalistic Functional Programming Styles

/**
* @author Bhasker V Kode
* @date Jan 4 ,2006
* @description Uused to create xml structures as a string ,and get a string form at any node level ,easily add nodes ,attributes and values.
*/

function XmlWriter(root){
this.totalNodes=new Number(0) ;

this.addNode = function(parent,nodeName,value){
if(nodeName!=undefined){
this.totalNodes++ ;
var len = this.index.length - 1 ;
this.index[this.totalNodes] = new Object() ;
if(value!=undefined){
this.index[this.totalNodes][nodeName] = new Node(nodeName,this.getDepth(parent)+1,value,this.totalNodes) ;
}else{
this.index[this.totalNodes][nodeName] = new Node(nodeName,this.getDepth(parent)+1,this.totalNodes) ;
}
this.index[this.getIndex(parent)][parent].array.push(nodeName) ;
}
}

this.getRoot = function(){
return this.root ;
}

this.getNode = function(parent){
var len = this.index.length ;
return this.index[len - 1 ][parent] ;
}
this.getIndexElem = function(id,assoc){
if(id < 0){
id=0 ;
}
return this.index[id][assoc] ;
}

this.printXML = function (node,str){
if(str==undefined){
var str = new String('') ;
}
var tempArrElem = this.getIndexElem(this.tempIndex,node) , tempArr = tempArrElem.array ;
// this.jsAlert('going to call start tag for this.index['+this.tempIndex +'having name '+ tempArrElem.name+' and attribs '+ tempArrElem.attribs) ;
str+= this.startTag(node,tempArrElem.attribs) + tempArrElem.value ;

if(tempArr.length > 0 ){
for(var j=0 ; j < tempArr.length ; j++){
//this.jsAlert('j='+j+',node :'+node+',this.tempIdex is '+this.tempIndex+'so tempArr is : this.index['+this.tempIndex+']['+node+'] = '+tempArr[j]) ;
this.tempIndex++ ;
// this.jsAlert('going to call printXML with node:'+tempArr[j]+',cuurent str is '+str) ;
str = this.printXML(tempArr[j],str) ;
}
// this.jsAlert('done with filled'+ node+'this.printed = ' + str) ;
str+= this.endTag(node) ;
return str ;
}else{
// this.jsAlert('done with empty'+ node+'this.printed = ' + str + this.endTag(node)) ;
str+= this.endTag(node) ;
return str ;

}

}

this.startTag = function(nodeName,attribs){
if(attribs==undefined){var attribs='' ; }
return ' < '+nodeName+attribs+'>'
}
this.endTag = function(nodeName){
return ' < /'+nodeName+'>'
}

this.getDepth = function(nodeName){
for(var i =0 ; i < this.index.length ; i++){
for(var node in this.index[i]){
if( this.index[i][node].name==nodeName){
return this.index[i][node].depth ;
}
}
}
}

this.getIndex = function(nodeName){
var tempRet=0 ;
for(var i =0 ; i < this.index.length ; i++){
for(var node in this.index[i]){
if( this.index[i][node].name==nodeName){
tempRet = i ;
}
}
}
return tempRet ;
}

this.getXML = function(nodeName){
if(nodeName==undefined){
var nodeName = this.root ;
}
this.tempIndex=0 ;
return(this.printXML(nodeName)) ;
}
//constructor
//adding root node
this.printed = new String() ;
this.index = new Array() ;
this.index[0] = new Object() ;
this.index[0][root] = new Node(root,0) ;
this.root = root ;

}

function Node(nodeName,depth,params,index){
this.array = new Array() ;
this.depth = depth ;
this.name = nodeName ;
this.index = index ;
if(params!=undefined){
if(params.value!=undefined){this.value=new String(params.value) ; }else{this.value=new String('') ; }
if(params.attribs!=undefined){
this.attribs=new String(' '+params.attribs) ;
}
}else{
this.value=new String('') ;
this.attribs=new String('') ;
}
return this ;
}

Execution:
var x = new XmlWriter('channels');
x.addNode(x.getRoot(),'channel',{attribs:'preferred="ndtv"'});
x.addNode('channel','shows');
x.addNode('shows','show',{attribs:'date="05:01:2006" title="waynes world"',value:'21:00:00'});
x.addNode('shows','show',{attribs:'date="05:01:2006" title="cnn news"',value:'22:00:00'});
alert ( x.getXML('channels') );
As you can see with the above example . This class can generate a consistent xml file from any particular node, handle attributes (although i need to add better error checking / escape character into the system) .The interesting part comes in the printXML function where ive implemented a minimalistic function style of programming where . Now ofcourse ive put in plenty of Object oriented javascript as evident with the use of the this keyword generously . But what ive also done is make the final printing of xml darn simple !

In essence my recursive function printXML does the following:

(XmlWriter.printXML in pseudoCode)

  1. write the start tag of this node .
  2. add the attributes
  3. if this node has a child node ? goto 1 , else goto 4
  4. write the end tag of this node

So now ....im convinced that javascript has done a good job in imbibing some tips from the erlang examples. The beauty of javascript is that since its pretty native as far as the browser is concerned ,you can write anything or implement any paradigm that isnt native to the langauge yourself . But as many wise ones have echoed over the years that the very fact that you code in a functional programming language style, could change the way you think about programming .

Cheers to my erlang and like my first experiment with functional programming ,the javascript hacker in me is up to the challenge as well 8 ) .

Keep Clicking,
Bhasker V Kode

PS : special thanks to Ricky Clarkson for hinting me to check the code again . i was coding the sum of N numbers although i started out wanting to do the factorial of N numbers ! d 'oH ! : P .... thanks ! I hate bloggers code formatting as well !

Technorati Tags: , , , , , , , , ,

Thursday, November 16, 2006

Presenting - Proto.in Widget

I hacked this scriptlet today for proto.in ...

To add the following widget into your blog or webpage ,simply add the following line scriptlet into your html code , to get your own proto.in widget...
<script id="protoWidget" src="http://proto.in/protoWidget/protoWidget.js" type="text/javascript" language="'javascript"></script>

Developer Notes:
I used the following 4 files...
protoWidget.css , protoWidget.js , protoWidget.gif, protoLoad.php


I Initially used iframes and the xmlhttp to read cross domain ,but even though i could get around the infamous ' cross domain same origin ' policy ,couldnt pass the data between the iframe and the parent window . SO ,decided to shift to a dynamic script tag and json format where i spit out the feed xml using php into javascript which was dynamically appended to the dom .A word of caution if you are planning to make your own feed reader ! Dont fall for the unterminated string error .xml as you know will be nicely formatted with elements in different lines ,et cetera . But once you pass this into javascript ,line breaks are a strict NO NO .

Then again ,there 's a hack against this as well. Heres my version of how to retrive cross -domain feed/data without NO hassles of security ,NO browser prompts ,and NO script signing needed. Here you go.(PS: sorry for the code not being aligned properly,but hope u can get a gist of it )

protoLoad.php
var fullXML={bosky:101};

/* reading feed as string into json form */
var _xml={data:'/* pass any site / feed here as querystring. */
if($site){
$fp = fopen($site, "r");
$buffer = "";
// get output in buffer variable
if ($fp) {
while(!feof($fp)) {
$buffer .= fread($fp, 1076);
}
}
$buffer = str_replace("\n","", $buffer);
$buffer = str_replace("\r","", $buffer);
$buffer = str_replace("\t","", $buffer);
$buffer = str_replace("'};

/* ok so now we have the xml string in xml.data . Now to DOM ify it ! */
getXMLTree(_xml.data,'item');

function getXMLTree(xmlStr,nodeName)
{
var xml;
this.load = function (nodeName){
if (window.ActiveXObject)
{
xml = new ActiveXObject("Microsoft.XMLDOM");
xml.async="false";
xml.loadXML(xmlStr);
}
// code for Mozilla, etc.
else if (document.implementation && document.implementation.createDocument)
{
var vParser = new DOMParser();
xml= vParser.parseFromString(xmlStr,"text/xml");
}

if(nodeName!=undefined){
fullXML = xml.getElementsByTagName(nodeName);
}else{
return (xml);
}
}
this.load(nodeName);
}

/* ok so now we have the xml node in fullXML . Now to send it back to client */
parent.window.readData(fullXML);

protoWidget.js
./* client side that initiates the script tag to call protoLoad.php*/

/** METHOD 1 */
** @description This method uses hidden iframe and xmlhttp to read the feed.But it is limited since you cannnot reference data from a child iframe of url location A to the parent window of url location B. You can do this only if you set document.domain explicitly , or the are in the same domain . not very useful !
*/
protoWidget.prototype.readCrossDomain = function(){
this.iF = document.createElement('iframe');
this.iF.id='protoWidgetHost';
var iS = this.iF.style;
iS.border='0px';
iS.width='0px';
iS.height='0px';
this.iF.type='hidden';
this.iF.src = this.crossDomainSrc;
this.add('insert',this.script,this.iF);
}

/** METHOD 2 */
** @description This method uses a dynamically added script tag , which is actually a php file that splits out the feed and puts that into a javascript variable. no securty violations ,no issues . very useful !!!
*/

protoWidget.prototype.readJSON = function(){
var head = document.getElementsByTagName("head").item(0);
var oScript = document.createElement("script");
oScript.setAttribute("src",this.remoteURL);
oScript.setAttribute("id","src1");
this.add('append',head,oScript);
/* makes a call to protoLoad.php here */
}

protoWidget.prototype.add = function(type,addTo,obj){
if(type=='insert'){
addTo.parentNode.insertBefore(obj,addTo);
}else{
addTo.appendChild(obj);
}
}
.
.
.
/* this is called when reading feed is done .in otherwords this is the callback.*/
function readData(_fullXML){
/* thats it ._fullXML is the xml node of the feed ,carry on with the parsing,et cetera . cross browser issue solved . 8 )*/
}

For the full version of the protoWidget.js check it out here .

Oh ,theres no feeling for a geek to substitute writing beautiful code..... 8 )

Keep Clicking,
Bhasker V Kode

Technorati Tags:, , , , , , , , ,

Wednesday, October 25, 2006

How to get hired as a Tutor at TutorVista

Well ,to be quite frank - I intend to try my hand at teaching ,after im done with my stints with software at a later point of time . And heres how you can become a tutor too .

There are three kinds of people that we are looking for for the position of a Tutor , here at Tutorvista . Being a new age company you could be sitting in any part of the world and still be part of the Tutorvista family ,but Id like to explain the options a bit further .

1. Have u always wanted to teach, at some point in your life ?
If you are qualified to train students and have the passion to teach and interact with students from all over the World - from Iran to Egypt to the United States and the UK . Choose the grades and Subjects you are comfortable with and get started with Training that we provide before you handle the students . We take the quality of work, and dedication to time seriously. Both your time as well as those of the students from across the world . And once the training period is completed succesfully -you will certified by TutorVista , and ready to begin .

2 . Are you a school or college Tutor ,looking for part time work ?
Part time Tutors from across India and other countries have found that serving as a part time Tutor at TutorVista have helped them with extra earnings , but provided them with a chance to teach students what you love ....be it Trigonometry , Economics , Classical Music Reading or Japanese ! If you have a skill that you want to share ,then help us extend that satisfaction further by rewarding you for your dedication .

3 . Are you looking for Tutoring as a full time profession ?

TutorVista , is always looking for dedicated personnel to join its growing family worldwide . If you are looking for a full time career in the teaching field or want to shift to the rewarding world of the Tutoring , then look no further . Join now ,as a part time Tutor to get started or if it cant wait - you can always go for our Full Time Tutor positions .

If you feel you come under any one of the above categories , mail in your resume at careers@tutorvista.com with the subject " careers - Tutor#101".

If you on the other hand are a php programmer with 2-3 years of experience with server side programming particularly with extensive database expertise , send your resumes to careers@tutorvista.com with the subject as 'careers - dev#101' .

I can go on and on about the atmosphere here at TutorVista .From the bean bag infested office here in Bangalore, to the Saturday Intra- Office Cricket matches ,to the Celebration parties and the versatile singers that we have to ....uhmmm tolerate :P ...

But its a revolution best experienced than explained. So ,tell your friends & spread the word . TutorVista ......World Class Tutoring,A Click Away .... 8 )

Keep Clicking,
Bhasker V Kode
TutorVista

Technorati Tags:, , , , , , , , , ,

Monday, October 16, 2006

EDITED : Currying in Javascript - a Stress Test

The recent post on the recently established but relevent blog on Datastructures and Algorithms titled "What Arays are for " caught my attention the moment he brought the issue of sending multiple parameters over to functions ,and having a function call instead . Hmmm , interesting point but ...does that ring a bell ...Oh yes ! Sriram Krishnan on Functional programming and currying in C# way back at his msdn blog . Right ,so a quick info at what the wikipedia had to say about currying brought to the table some insightful information ...

"the technique of transforming a function that takes multiple arguments into a function that takes a single argument (the first of the arguments to the original function) and returns a new function that takes the remainder of the arguments and returns the result." - (source -wikipedia )

But honestly , i was a little reserved for even contemplating a " iterative function call VS simple array loops" challenge...however i did test it out ... thanks to the interest "What Arays are for" instilled into me early this morning...

After some time testing the awesome capabilities of the "apply" and "arguments" arguments in javascript ... by which you could generate an inheritance sort of capability by which you could forward all arguments in a present to another just by using the targetFunction.apply(this,arguments) ! wow !!! that should definitley save some time for me in the future (apart from seeing if i can port currying to actionscript ! )

So heres the code .... ive adopted it in relation to the simple example from the nice blog Mr.sanjay maintains , and ported a Currying solution as well.... the results are impressive ,and i feel well worth the interrogation !

The specification is simple ...just tryign to find an average from the total calcualted .
/* EXHIBIT A */ does this with without currying , /* EXHIBIT B*/ is what i hacked for WITH CURRYING...

/* javascript code
* @author Bhasker V Kode
* @date 16th October 2006
*/
/* EXHIBIT A - WITHOUT CURRYING */
var timer1 ,timer2;var ar= new Array();
var noOfStudents = 1000; // tested for 1000,10000,etc
function callAverage()
{
var agesOfStudents = new Array();
var i;
for(i=0;i <>
agesOfStudents[i] = i;
}
var avgAge=0;
timer1 =new Date().getTime();
avgAge = calcAverageAge(agesOfStudents, noOfStudents);
timer2 =new Date().getTime();
alert(avgAge +'found in '+(timer2- timer1) +'ms');
window.clearTimeout(timer2);
}
function calcAverageAge (ages, noOfPeople)
{
var sumOfAges = 0;
var averageAge = 0;
var i;
for ( i = 0; i < noOfPeople; i++)
{
sumOfAges += parseInt(ages[i]);
averageAge = sumOfAges/noOfPeople;
}
return averageAge ;
}


/* EXHIBIT B - WITHOUT CURRYING */
function calcAverageAgeWITHCURRYING(f,x){
return function(){
x = [x].concat(Array.prototype.slice.apply(arguments));
return f.apply(this,x);
}
}

function fn1(){
ar[ar.length] = timer1+','+timer2
}
function add(a,b){
return a+b;
}
function callAverageWITHCURRYING(){
var agesOfStudents = new Array();
var i;
/* filling array from DB /etc */
for(i=0;i < noOfStudents;i++){
agesOfStudents[i] = i;
}

/* starting excecution to find avg */
var sum=0;
timer2 =new Date().getTime();
var div = (noOfStudents%2==0)?0:1;
for(i=0;i < style="color: rgb(0, 0, 0); font-style: italic;">sum += calcAverageAgeWITHCURRYING(add,agesOfStudents[i])(agesOfStudents[i+1]);
}
timer2 =new Date().getTime();
alert(avgAge +'found in '+(timer2- timer1) +'ms');
}

************STATISCTICS************
for 100 students :
with currying : 0milli seconds
without currying :0milli seconds

for 1,000 students
with currying : 31 ms
without currying : 15ms

for 10,000 students
with currying : 481 ms
without currying : 31ms

for 100,000 students
with currying : 5812 ms ( and buttons hanged !! )
without currying : 875ms


So there you have it ...To check it out for youself ...add two buttons on your page ,and call the two functions as follows .... 8 )
<input type="button" onclick="callAverageWITHCURRYING();" value="callAverage with currying">
<input type="button" onclick="callAverage();" value="callAverage without currying">

Keep Clicking,
Bhasker V Kode

Technorati Tags:, , , , , , , , ,

Friday, October 06, 2006

Joel Spolsky heading Dojo ?!?!

I was checking out where I could submit my concept of ajacss ,and speech recognition with ajax,when i stumbled upon The 11th Internationall SOA Web Services Edge 2007 East - International Web Services Conference & Expo, to be held June, 2007, which announces that its Call for Papers is now open.

But what really grabbed by attention was the list of keynotes and panels on the right side of the page . Call it a typo or perhaps some news that I dont know but the page clearly read showed Spolsky,with the word Dojo under the last name .

Heres even a screenshot . screenie1 shows the top of the page that shows Joel Spolsky ,founder Fog Creek . While a little on the right side of the page (couldnt get both in one screenshot ) shows ,soive put that in screenie2

Free Image Hosting at www.ImageShack.usand heres the stealer... Spolsky , Dojo =>Free Image Hosting at www.ImageShack.us

check it out yourself ! Someone 's got some explaining to do :P

Keep Clicking,

Bhasker V Kode

Technorati Tags: news,dojo, spolsky, , bhasker, kode,

Wednesday, September 13, 2006

Proposal for a local Javascript Developers User Group

So your city has its own linux or bloggers user group ...cool . But off late ive been wondering about the need ,or rather the lack of a group dedicated to 'the big J' of scripting languages.

So where do i see this going ? Well ,first up - maybe form a Javascript UserGroup Bangalore Chapter or Chennai Chapter to start off with to come up with an indian Script.aculo.us or Dojo toolkit . Why not !

Ideally it would start off in a small way, and gradually like any other user group - with time mature into a sound and active forum for javascript developers dealing with a number of inherent fields like asynchronous data retreival , DOM and window handling reusable functions , or cross browser issues ,to other problems like making javascript loading more effiecient , dealing with cookies and security , and eventually even come up with suggestions and comments on ECMA scripting .

What do you think are required ..to name a few
=> website / wiki
=> spreading the word
=> ?

I think we can make this work... interested,just post your comments ?

Keep Clicking,
Bhasker V K

Technorati Tags: , , , , , , , ,, , ,

Sunday, September 10, 2006

AJAXifying Your Blog: 3 Ways to Enrich Your Blog

For those missed out , heres a overview of what my session at BlogCamp on Day-1 was about .

Since the unConference was indeed catered to bloggers , i decided to explain how asynchronous methodologies could help in the productivity of blogs in particular ......through 3 methods .


3 Ways that will enrich Blogs in the Future


1. From Content related 'Ads' to content related 'Content'
Traditionally people always took to adding a smart ad -aka adsnese /other text ads to insert ads that are in vibe with the rest of your blog posts /site content . This offers viewers more customized content . But why stop at that . The reason why the best bloggers prosper is because they do most home-work . Take that extra effort to push your own content. I know most people can relate to the fact that they might have made a lot of good posts over the years/months. So how do you get productive and make the most of your own creative content ? By simply reusing it smartly . Clever use of past creative content would give users visibility to explore your older pages . How ? By moving from Content related 'Ads' to content related 'Content'. Gapp in his nice tut yesterday at blogCamp titled "wordress hacks", explained that Wordpress offers the option of having an rss feed of your own categories,which can be placed in a widget /sidebar. Same theory holds for other providers . You not have a neat column of your favourite posts or posts from the blogs you read or feeds from your fav tech hud RIGHT on your blog. Personally i dont see the move towards ajaxy desktops. Instead what people develop is ways to bring content to your own blog.Why go after it . I dont need to go through N feeds ,if i have a neat sidebar with posts from my fav feeds or a list of my friends whove updated their blogs offlate . You get the Picture right .... make your blog all the more content wise with interesting 'content related content '.

2. Better use of your Archives.
Ive always wondered if I could make a better use of the gibberish numbers that take up considerable amount of space . Whats the alternative .Where do I see the future of Blog Archives heading - that pushes the frequency imformation of your posts with dates AS WELL AS inspire people to check out the blogs ?

Check out the demo for yourself .

3. Widgets , Widgets , Widgets
One line of Code . Thats all a bloggers need to have ,and need to get functional widgets. We are going to see more need for develoers to creat ewdigets for blogs ,rather than a site with widgets that you have to go to. Just stay where you are ,and plug them in .From blog statistics and pinkers , to flikr rolls and your favourite quotes . Here are a couple of widgets i showcased - best seen on Firefox.

- BlogCamperKode => a widget i developed for blogCamp
- TechEnclave News Ticker => one line of code (script tag) that adds an ajax forum ticker that reads from the site i help running - TechEnclave.com
- PineFeeds => something i amade sometime in 005 .

So there you have it... It was fun to be at blogCamp , looking forward for more events like this one ,and more geeky garage innovations from yours truly ... 8)

Keep Clicking,
Bhasker V Kode

Technorati Tags: ,,, ,, , , , , ,,,,