Wednesday, June 23, 2010

Java Script Anonymous functions , Closures

People have doubts about closures and anonymous functions. actually closures are a type of function which allow the creation of functions which have no specified name. they are very useful when you want control over callback or you want use function as the values of variables. every language provide a freedom to create anonymous/closures functions. PHP also provide such feature .. 

$greet = function($name)
printf("Hello %s\r\n"$name);

Back to our discussion. here, i summarized about js anonymous, closures. 

Anonymous functions
  • Any function that is defined as a function expression is technically an anonymous function since there is no definitive way to reference it.
  • With no definitive way to reference a function, recursive functions become more complicated.
  • Recursive functions should always use arguments.callee to call themselves recursively instead of using the function name, which may change.
Closures are created when anonymous functions are defined inside other functions, allowing the closure access to all of the variables inside of the containing function, as follows:-
  • Behind the scenes, the closure ’ s scope chain contains a scope for itself, a scope for the containing function, and the global scope.
  • Typically a function ’ s scope and all of its variables are destroyed when the function has finished executing.
  • When a closure is returned from that function, its scope remains in memory until the closure no longer exists.
Using closures, it ’ s possible to mimic block scoping in JavaScript, which doesn ’ t exist natively, as follows:-
  • A function can be created and called immediately, executing the code within it but never leaving a reference to the function.
  • This results in all of the variables inside the function being destroyed unless they are specifically set to a variable in the containing scope.
Closures can also be used to create private variables in objects, as follows:-
  • Even though JavaScript doesn ’ t have a formal concept of private object properties, anonymous functions can be used to implement public methods that have access to variables defined within the containing scope.
  • Public methods that have access to private variables are called privileged methods.
  • Privileged methods can be implemented on custom types using the constructor or prototype patterns as well as on singletons by using the module or module - augmentation patterns.
  • Anonymous functions and closures are extremely powerful in JavaScript and can be used to accomplish many things. Keep in mind that closures maintain extra scopes in memory, so overusing them may result in increased memory consumption.
original source  from Nicholas C. Zakas (Yahoo's principal front-end engineer) 

Tuesday, June 15, 2010

PHP Session issue

A PHP Session Cookie (mostly defined as PHPSESSID) has a default life time until the browser is closed. Another session-relevant issue is the PHP garbage collector. When a session is created, a flat-file is created on the server - e.g. in /tmp on linux servers. Since the session ID is a unique identifier, those session files will accumulate over time - the garbage collector will take care of these files and delete old files from time to time. PHP has a sort of built-in "load-balancing" feature for this garbage collector, so that old session files are not deleted on each and every session request, but with a certain probability. The default timeout for session files is 1440 seconds or 24 minutes. So a session file can be deleted after that timeout, but it may reside on the server longer, depending on the amount of sessions created - here comes the probability into the game.

So we have a session cookie with a lifetime until the browser is closed, but the garbage collector might delete the session file much earlier. In this case, and if there is a session request after the session file has been deleted, a new session is created and the old session information is lost. This can be very annoying if e.g. the users is writing some message in a web-based interface and this task takes longer than the session file on the server is available.

There are 3 PHP.ini variables, which deal with the garbage collector:PHP ini value name default Changeable
session.gc_maxlifetime 1440 seconds PHP_INI_ALL
session.gc_probability 1 PHP_INI_ALL
session.gc_divisor 100 PHP_INI_ALL

session.gc_probability in conjunction with session.gc_divisor is used to manage probability that the gc (garbage collection) routine is started. The probability is calculated by using gc_probability/gc_divisor, e.g. 1/100 means there is a 1% chance that the GC process starts on each request.

The most important variable is session.gc_maxlifetime:-
As discussed earlier, this variable sets the timeout for session file deletion.
All three variables can be set in the php.ini configuration file, but more important, those can be also set during runtime due the PHP_INI_ALL permission.

we can be also set those 3 PHP.ini variables during runtime due the PHP_INI_ALL permission. so we can create another directory *within* the regular session file directory and set the new path for the session files. Now our session files are stored in the new directory and the regular garbage collector will not see them, so those files will survive at least that long as defined in gc_maxlifetime.

But make sure that all these changes MUST be made before the actual session is opened with session_start() or session_register(). need to include at top of index file.

// path for cookies
$cookie_path = "/";

// timeout value for the cookie
$cookie_timeout = 60 * 30; // in seconds

// timeout value for the garbage collector
//   we add 300 seconds, just in case the user's computer clock
//   was synchronized meanwhile; 600 secs (10 minutes) should be
//   enough - just to ensure there is session data until the
//   cookie expires
$garbage_timeout = $cookie_timeout + 600; // in seconds

// set the PHP session id (PHPSESSID) cookie to a custom value
session_set_cookie_params($cookie_timeout, $cookie_path);

// set the garbage collector - who will clean the session files -
//   to our custom timeout
ini_set('session.gc_maxlifetime', $garbage_timeout);

// we need a distinct directory for the session files,
//   otherwise another garbage collector with a lower gc_maxlifetime
//   will clean our files aswell - but in an own directory, we only
//   clean sessions with our "own" garbage collector (which has a
//   custom timeout/maxlifetime set each time one of our scripts is
//   executed)
strstr(strtoupper(substr($_SERVER["OS"], 0, 3)), "WIN") ?
$sep = "\\" : $sep = "/";
$sessdir = ini_get('session.save_path').$sep."my_sessions";
if (!is_dir($sessdir)) { mkdir($sessdir, 0777); }
ini_set('session.save_path', $sessdir);

// now we're ready to start the session

print "mytest=".$_SESSION['mytest']."

$_SESSION['mytest'] = "captain";

Thursday, June 10, 2010

How to detect a click outside an element to close overlay or modal box ?

function clickedOutsideElement(elemId) {
    var theElem = getEventTarget(window.event);
    while(theElem != null) {
        if( == elemId)
            return false;
        theElem = theElem.offsetParent;
    return true;

function getEventTarget(evt) {
    var targ = ( ? : evt.srcElement;
    if(targ != null) {
        if(targ.nodeType == 3)
            targ = targ.parentNode;
    return targ;

document.onclick = function() {
        alert('Outside the element!');
        alert('Inside the element!');

codeigniter's super object

I hope everybody have seen & get_instance variable while working in codeigniter. I searched and trying
to find out how codeigniter builds super object and how it works internally. Hope we will enjoying it.

CI works by building one 'super-object', it runs  whole program as one big object, in order to eliminate scoping issues. When we start CI, a complex chain of events occurs.  If we set CI installation to create a log, we'll see something like this:-

    1 DEBUG - 2006-10-03 08:56:39 --> Config Class Initialized
    2 DEBUG - 2006-10-03 08:56:39 --> No URI present. Default controller  set.
    3 DEBUG - 2006-10-03 08:56:39 --> Router Class Initialized
    4 DEBUG - 2006-10-03 08:56:39 --> Output Class Initialized
    5 DEBUG - 2006-10-03 08:56:39 --> Input Class Initialized
    6 DEBUG - 2006-10-03 08:56:39 --> Global POST and COOKIE data sanitized
    7 DEBUG - 2006-10-03 08:56:39 --> URI Class Initialized
    8 DEBUG - 2006-10-03 08:56:39 --> Language Class Initialized
    9 DEBUG - 2006-10-03 08:56:39 --> Loader Class Initialized
    10 DEBUG - 2006-10-03 08:56:39 --> Controller Class Initialized
    11 DEBUG - 2006-10-03 08:56:39 --> Helpers loaded: security
    12 DEBUG - 2006-10-03 08:56:40 --> Scripts loaded: errors
    13 DEBUG - 2006-10-03 08:56:40 --> Scripts loaded: boilerplate
    14 DEBUG - 2006-10-03 08:56:40 --> Helpers loaded: url
    15 DEBUG - 2006-10-03 08:56:40 --> Database Driver Class Initialized
    16 DEBUG - 2006-10-03 08:56:40 --> Model Class Initialized

each time a page request is received over the Internet , CI goes through the same procedure.
We can trace the log through the CI files:-

The index.php file receives a page request. The URL may indicate which controller is required, if not, CI has a default controller (line 2). Index.php makes some basic checks and calls the codeigniter.php file.
The codeigniter.php file instantiates the Config, Router, Input, URL, (etc.) classes (lines 1, and 3 to 9). These are called the 'base' classes: we rarely interact directly with them, but they underlie almost everything CI does.
codeigniter.php tests to see which version of PHP it is running on, and calls Base4 or Base5 (/codeigniter/Base4(or 5).php). These create a 'singleton' object: one which ensures that a class has only one instance. Each has a public &get_instance() function. Note the &:, this is assignment by reference. So if we assign to the &get_instance() method, it assigns to the single running instance of the class. In other words, it points we to the same pigeonhole. So, instead of setting up lots of new objects, we are starting to build up one 'super-object', which contains everything related to the framework.
After a security check, codeigniter.php instantiates the controller that was requested, or a default controller (line 10).

The new class is called $CI. The function specified in the URL (or a default) is then called, and life as we know it starts to wake up and happen. Depending on what we wrote in   controller, CI will then initialize any other classes we need, and 'include' functional scripts we asked for. So in the log above, the model class is initialized. (line 16)

    class my_new_class{
var $base;
   $obj =& get_instance();
   // geolocation code here, returning a value through a switch statement
   //this value is assigned to $local_url
   $this->base = $obj->config->item('base_url);
   $this->base .= $local_url;

We've looked at the way CI builds up one 'super-object' to make sure that all the methods and variables we need are automatically available without having to manage them and worry about their scope.

CI makes extensive use of assignment by reference, instantiating one class after another and linking them all together so that we can access them through the 'super-class'. Most of the time, we don't need to know what the 'super-class' is doing, provided that we use CI's 'arrow' notation correctly. We've also looked at how we can write   own classes and still have access to the CI framework.

Saturday, June 5, 2010


Main advantages of DATETIME (DT) compared to TIMESTAMP (TS) :-
DT is human readable (TS is not without using TO_DATE)
DT has a possible timespan of 8999 Years (1000-01-01 00:00:00 to 9999-12-31 23:59:59)
(TS only about 68 years, 1970-01-01 to 2038-01-19)
DT can be used for advanced date calculation (SELECT NOW() + INTERVAL 2 DAY)
Not sure ( DT is faster than TS)

Main advantages of TIMESTAMP (TS) compared to  DATETIME (DT) :-
TS only needs 4 bytes (DT uses 8)
TS are stored as UTC values and changed according to the client's timezone setting
TS columns can serve as a "log" for monitoring when a row has changes
TS helpful to cut down on too much date parsing in PHP

Install reliance broadband+ in ubuntu

In Ubuntu 10.04 , broadband+ device is detected as usb storage.To make it detected as modem we will use usb-modeswitch package. It is a Switching tool for controlling "flip flop" USB devices.

Need to Install follwoing tools.

A. usb-modswitch
B. usb-modswitch-data

Commands to install:-

1. sudo apt-get install -yq usb-modeswitch usb-modeswitch-data

2. wget -c

3. dpkg -i  usb-modeswitch-data_20100127-1_all.deb

For 64 bit :

4. wget  -c

5. dpkg -i usb-modeswitch_1.1.0-2_amd64.deb

For 32 bit

4. wget -c

5. dpkg -i usb-modeswitch_1.1.0-2_i386.deb

Once you install both packages,  you should have the modem detected and then use networkmanager to configure it.