How to get output of multiple asynchronous calls in one callback


Javascript IO is asynchronous, which is awesome but sometime you might land into a situation where you wanted to call several asynchronous function and when all of them are ready you have to perform some action. Obviously you can not nest each other with anonymous functions in all situations.

so intead of doing this (assume u need to call several asyncCalls 1,2,3 etc,)


         asyncCall1(param1,function (output1){
           asyncCall2(param2,function(output2){
              asyncCall3(....)
           })
         })



You might like to do this

    function finalCallback(alloutput){
       //here is your final output
    }
    cbGenerator=getGroupCallBackGenerator(timeout,finalcallback);
    asyncCall1(param1,cbGenerator.getCallback('asyncCall1'))
    asyncCall2(param2,cbGenerator.getCallback('asyncCall2'))
    asyncCall3(param3,cbGenerator.getCallback('asyncCall3'))
    asyncCall4(param4,cbGenerator.getCallback('asyncCall4'))
    cbGenerator.start();



Well You can do it if you want to use my utility function here.


Codefoo Plugin for Sublime Text 2

Hi,

I developed a Sublime Text 2 Plugin, named codefoo which does some magic for you.
This plugin helps you in retrieving code snippet from web.

Do not leave the browser simply get code in 3 easy steps 
 1. type the query
 2. select
 3. press `ctrl+alt+r`

Try with these query 

 * email validation regex
 * URL validation in javascript
 * reversing a string in javascript
 * slide To unlock css

Demo 




Githubhttps://github.com/markandey/codefoo


How it works


It works by searching you query in a list of popular web pages where you find code. Then it scrapes the page to get just the code snippet.

Install Via Sublime Package Control

  1. You should use sublime package manager
  2. Use cmd+shift+P then Package Control: Install Package
  3. Look for CodeFo and install it.
This is all powered by Yahoo! BOSS Search API and YQL.

Javascript Language Sugar (one liners)


Here are some good one liners in javascript

//Hello World Program Which is Palindrome

(alert)('Hello, World') && ('dlroW ,olleH')(trela)


//Reverse a string

"this is a string".split("").reverse().join("");


//Trim a string

" Hello World ".replace(/^\s*|\s*$/g,'')


//HTML escape

"<b>Hello HTML</b>".replace(/([&<>])/g,function (c) {return "&" + {"&": "amp","<": "lt",">": "gt"}[c] + ";";});


//Shuffle an array

[1,2,3,4,5].sort(function(){return (4*Math.random()>2)?1:-1})


//Detect IE

isIE='\v'=='v';


//Force String to be a Number (multiply or divide by 1)

"100"*1


//Force to be boolean

!!"some value"


//Converting string to Leet

"Hello Hacker".replace(/[a-z]/g,function f(a){return "4BCD3F6H1JKLMN0PQR57"[parseInt(a, 36)-10] || a.replace(/[a-t]/gi,f)});


//Clone an array

var clone = [1,2,4,5,6,9].slice(0);

YUI DateTime Chooser

I just created YUI3 DateTime Chooser Module.

What is it?


At some time in a webform you have to capture date and time together with timezone. This YUI3 module is to help you in progressively enhance "date-time form input" to popup (calendar and slider based) UI to input date and time with TimeZone.

How to Use?



<script src="http://yui.yahooapis.com/3.7.3/build/yui/yui-min.js"></script>
<link rel="stylesheet" type="text/css" href="http://yui.yahooapis.com/combo?gallery-2012.12.12-21-11/build/gallery-datetime-input/assets/gallery-datetime-input/gallery-datetime-input-core.css">
<script>
YUI({
gallery: 'gallery-2012.12.12-21-11'
}).use('gallery-datetime-input', function (Y) {
  new Y.DateTimeInput({
    inputBox:"#datetime-input"
   });
});
</script>

Introduction To Yahoo Mojito and Its Client and Server Seamlessness [screencast]

Hi There,


Mojito is a model-view-controller (MVC) application framework built on YUI 3 and its open source. Most notable feature of mojito is its capability to give you seamless MVC framework to manage your code on server as well as on client. Applications built on Mojito consists of  small components called Mojits which are independent UI element which can have their own Model,View, Controller and Binders.

Mojito features:
  1. Local Command Line development Tools.
  2. Library for simplifying internationalization & localization.
  3. Integrated unit testing.
  4. Device Specific Presentation.
  5. Single MVC to manage Client and Server code seamlessly.   
Here is screen cast to show you some awesomeness of Yahoo Mojito. Watch the Youtube video.

ScreenCast
How to setup this example
  1. Install Node
  2. Install Mojito

  3. npm install mojito -g

  4. Create App and Mojit

  5. $ mojito create app youtubesearch
    $ cd youtubesearch
    $ mojito create mojit containerMojit
    $ mojito create mojit searchResultMojit
    

  6. Modify application.json
  7. Modify routes.json
  8. Modify mojits MVCs. Get the full code here

  9. Get from github
    git clone https://github.com/markandey/mojito-example-youtube.git
    

HTMLFrameMojit is inbuilt mojit in the Mojito framework which creates basic html layout. In the example we have created a containerMojit, which is a composite mojit. Then In searchResultMojit we have created binder to handle click of search button. We are using mojitProxy to tunnel the request to mojit. We never bothered about the location of searchResultMojit and framework automatically tunnels the request to mojit either it is on server or it is on client. There is a way to lazyLoad a mojit.

I have used YQL to get youtube search result. To Read more about the YQL read here.


Where to Host Mojito Application
You can host mojito on any node.js server, Try Openshift, its free and easy to deploy.
You can also try http://www.nodejitsu.com/

Why text-overflow ellipsis does not work?


Text-overflow is (almost) always required to be used along with white-space: nowrap; property, and this is solution to your problem if you are reading this article.

check this jsFiddle


<style>
.not-working{
    text-overflow: ellipsis;
    width:200px;
    height:40px;
    border:1px solid red;
    overflow:hidden;
}

.working{
    text-overflow: ellipsis;
    width:200px;
    height:40px;
    border:1px solid red;
    overflow:hidden;
    white-space: nowrap;
}

</style>
<div class="not-working">
This is a large text i want this to wrap.
</div>

<div class="working">
This is a large text i want this to wrap.
</div>​


Thank You for reading.. enjoy


How to generate rainbow colors


Hi There,
At times you might have to generate few colors which almost covers entire rainbow (visible spectrum) range.

Here in this article I am giving away a function which generates as many colors as you want but those colors will try to cover the entire (visible light) spectrum. i.e if you just generate 3 colors you will get Green, Red and Blue. If you generate 100 colors you will get multiple tints of Green, Red and Blue.

Function Name is : getColor(count)
Input count: Number of colors to generate.
Returns : li items with color (as style attribute).

<li class="color" style="background-color:rgb(254,64,54);">  </li>

How it works?
I have taken 3 sine waves, all are with different phase. Each of these sine curve generates my RGB values. Each sine wave will swing from 0 to 2pie (360deg). There has been a bit of normalization just to make the colors look good (in final code).





function getColor(noOfColors) {
    html = "";
    frequency = 5 / noOfColors; 
    for (var i = 0; i < noOfColors;++i) {
        r = Math.sin(frequency * i + 0) * (127) + 128;
        g = Math.sin(frequency * i + 1) * (127) + 128;
        b = Math.sin(frequency * i + 3) * (127) + 128;
        li = '<li class="color" style="background-color:rgb({r},{g},{b});">  </li>';
        li = li.replace("{r}", Math.floor(r));
        li = li.replace("{g}", Math.floor(g));
        li = li.replace("{b}", Math.floor(b));
        html = html + li;
    }
    return html;
}

                                                                  Demo jsfiddle 

How to extract people/person names from text? (javascript code)

This is a very simple guide which will answer questions like

1) How to extract people/person names from text?
2) How to extract company names from text?
3) How to extract entities from text?

For all of the above we will use Yahoo's Content Analysis API.

Here is simple code (gist)


function init(){
    var contentanalysisURL="http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20contentanalysis.analyze%20where%20text%3D%22{text}%22&format=json&callback=?";
    //this function will be called on json recieve
    function receiveJSON(data){
        //6. recieve Data

        try{
            //7.get list of all entities
            var et=data.query.results.entities.entity;

            var out=[];
            var len=et.length;
            for(var i=0;i<len;i++){
                var eee=et[i];
                //8.get entity name
                var content=eee.text.content;
                var startChar=eee.text.start;
                var etypes="";
                if(eee.types){
                    //9.get entity type
                    var typ=eee.types.type;
                    for(var j=0;j<typ.length;j++){
                        var ttt=typ[j].content;
                        if(ttt.indexOf('/')>=0){
                          etypes=etypes+" "+ ttt.substring(ttt.lastIndexOf('/')+1); 
                        }
                    }
                }
                //10.Append to dumo array
                out[out.length]={
                    "Entity":content,
                    "startChar":startChar,
                    "etypes":etypes,
                };
                
            }
            //11.update container with output
            $('#imgdiv').html("<pre>"+JSON.stringify(out,null,'\t')+"</pre>");
        }catch(e){
            $('#imgdiv').html("<pre>error</pre>");
        }

    }
    //1. hook click event of btget 
    $('#btget').click(function (){
        //2. Get text, length of text should be less than 512 or less. 
        //Note:when text is too large this will not work
        var text=$('#tu').val();
        //3.Update loding message

        $('#imgdiv').html("<pre>Loading..........</pre>");
        //4.Form a GET request, (YQL table )
        var url=contentanalysisURL.replace("{text}",text);
        //5. inject script block in dom with callback as receiveJSON
        $.getJSON(url,receiveJSON);
    });
}

$(document).ready(init);


  Working Demo  

Limitations with Code

  • Does not work with large data, due to limit of URL size. Get Request fails on large URL size. To Fix this read my this article
  • To Extract location name correctly, use geo.placemaker API of yahoo

Shell Script to Execute commands in parallel

Hi There,
Do you have some kind of {network operation / file operation} to do in parallel? Here is shell script  to help you.


Suppose you have 10 thousand items in a file (one item per line) which requires some parallel processing, you can use this script to get your work done!

Note: if you are doing pure math, do not make it parallel, it will not help much on single core CPU.
But if you are doing some network operation, you can make it parallel, it will help you for sure!!


How to Use?
You need to provide following inputs
cmdParams -->  A file with 1 item per line which requires some processing
maxthread  --> Specify max threads to fork

executeInSerial function will get each item as $1 do some operation with it, Implement it as you want it.

Here is script


Creating Rajinikanth Powered Site (BCB11)


Recently I saw this site , which claims to be working offline, in fact it does but it sucks because it was  built using Flash.

Now since we have HTML5 browsers ready!!, we can have 100% working offline website.

On Feb 11 2012, it was Bar Camp (11th) in Bangalore so I decided to educate people about offline capability of HTML5. BCB11 was really nice and many talks were awesome including a talk from Sameer Panchangam on hypnotism.


Here is Presentation from my talk.






GithHub Code
https://github.com/markandey/markandey.github.com/tree/master/rajani1


Live Demo 
http://markandey.github.com/rajani1/





Sublime Text Editor (screen cast)

Sublime text is really nice editor . Watch the screenshot to see some awesome features of it.







 
Open File Command Window
(type text for file name and @ for function
: for line number)
cmd+p
Open command Window
(Package Controll etc.)
cmd+shift+p
Shortcuts To Remember
Find: cmd+f
Find Selection (quick find) cmd+alt+G
Swap Line ctr+cmd+down
Multi Column Selection ctrl+shift+up/down
Scope Selection cmd+shift+space
Brackets Select ctrl+shit+M
Indentation Select cmd+shift+j
Tag Select cmd+shift+a
Line Select cmd+L