Tuesday, December 27, 2011

HTML Input Place Holder

A Simple way to implement placeholder in a Input Field. Although HTML 5 by default provides placeholders[placeholder attribute], it falls short in Cross Browser Compatibility

Construct A Simple Form

Username:

Let's Implement Placeholders Now [With jQuery]

Change the HTML To
HTML:
Username
Result
Username

Apply CSS and Overlay placeholder over Input Element
CSS:
.place-holder {
 position:relative;
 left:-245px;
 color:#AAA;
 z-index:1; 
}
.name-field {
 width:250px;
 background:#FFF;
 z-index:0;
}
Result
Username

Handle Focus and Blur Event :)
jQuery:
$().ready(function () {
 function hideHolder() {
  $('.place-holder').hide();
 }
 function showHolder() {
  if($('.name-field').val() == '') {
   $('.place-holder').show() 
  }
 }
 $('.name-field').focus(hideHolder);
 $('.name-field').blur(showHolder);
 $('.place-holder').click(function () {
  $('.name-field').trigger('focus');
 });
});

Result
Username

We are Done. Also You Can extend this upto 'N' number of Elements. You can also play with z-index value instead show()&hide() jQuery functions :)

Pros over playing around input's value attribute
  • Styling for placeholder is decoupled from input element and vice versa
  • The value of input element will be '' always if it is left empty
  • Simple

Cons
Just leave a comment if there is any :)

Wednesday, November 30, 2011

JS Automatic Semicolon Insertion

Semicolon; Why should I care?

"Javascript is the only language which people dare to use before learning"
- Crockford

Actually I, myself belong to that category of people whom crockford mentions :)
But trying to be out..

So, What's new today?
Just a informative writeup about ASI

ASI?
Ya, Javascript Automatic Semicolon Insertion

What is a legal statement in Javascript?
Following are some
var a=10;
a;
b++;
b+=1;
;;; // 3 Empty Statements
+a
var a = function() { };
{
  a
  b
  c    
};

Lets start
Try the following
var a=10;
function test() {
    var b;
    b = a;
    b+=1
}
console.log(a)

Even though I didn't insert any semicolon [Statement Terminator] in line 5 and 7, the JS engine never throws an syntax error.
Reason: ASI Construct

Rules to remember:
    ** ASI will insert one for you, if you specify a line terminator @ [no line terminator] mentioned
       in the grammar specification
    ** Whenever a statement misses a semicolon and if the statement following it makes sense along with the former.
       Then JS engine will not place a semicolon. Perhaps it parse them as a single statement
    ** If the statement is the last one inside a scope then you might consider missing semicolons. ASI will take care of

Where ASI will mislead?
There are 6 places
1 return
2 break
3 continue
4 Post ++
5 throw
6 Anywhere :P

Let's see the grammar for the first five
1. Return Statement             ->    return [no line terminator] (space expression)
2. Break Statement              ->    break [no line terminator] (space label)
3. Continue Statement         ->    continue [no line terminator] (space label)
4. Post Increment Statement ->    [operand] [no line terminator] ++
5. Throw Statements             ->    throw [no line terminator] [space expression]

Try it yourselves:
function test() { //Sample 1 Fails Silently
    var a =10;
    return 
    {
        avalue: a
    };
}
console.log(test().avalue);

function test() { //Sample 2 Throws Syntax Error
    var a =10, b = 10;
    return 
    {
        avalue: a,
        bvalue: b
    };
}
console.log(test().avalue);

Transformation:
function test() { //Sample 1 Fails Silently
    var a =10;
    return; --ASI rule 1-- Returns Undefined
    {
        avalue: a
    };
}
console.log(test().avalue);

function test() { //Sample 2 Throws Syntax Error
    var a =10, b = 10;
    return; // --ASI rule 1-- Returns Undefined 
    {    //Considered as a Block Statement            
        avalue: a,  //Considers avalue as label and 'a' as the statement under it
        bvalue: b   //Considers bvalue as label and 'b' as the statement under it
    };
}

According to ASI rule 1, there should not be any line terminator between return keyword and optional value.
If there is line terminator then JS parser inserts one ';' for you and makes your life difficult in case 2 and even more in case 1 [fails silently]

Try it yourselves:
These things likely won't happen but...
outer:for(j=0;j<3;j++) //Sample 1
{
    test:for(var i = 0;i < 3; i+=1) {
            if(i === 2) {
                break     // JS Engine Inserts a ; and 'outer' becomes a reference to outer loop
                    outer;
            }
           console.log(j);    
    }
}
console.log(i);

var a = -10;        //Sample 2
var b = 10        
+a;        // Rule 2
console.log(a+' '+b);

var a, b = 10, c = 10, d = 1, e = 3;  //Sample 3
a = b + c
(d + e).toString(2);    //Rule 2

var a = 10;    //Sample 4
a
++;

var b = 1; //Sample 5
++
b;

var a = 10, b = 10; //Sample 6
if(true)
{
    a++;
    b++        // Rule 3
}

Tidy programming always helps and will keep javascript good :)

Monday, November 21, 2011

Making Javascript Good :)

Somethings I learnt from Crockford :)
Keep it right always :)
function a()  //Seems to be working but not :)
{
    return
    {
        name: 'a'
    };    
}
console.log(a().name);

function a() {  //Keep braces always right. It works :)
    return {
        name: 'a'
    };    
}
console.log(a().name);

There is no concept of block level scoping in javascript but the syntax exists. So, the former falls in that block hole and returns undefined.

It's not c or c++
var i = 'tamil';
for(var i = 0;i < 10;i++){
    
}
console.log(i);

This is misleading because declaring 'var i' @ initialization of for-loop doesn't mean 'i' has the scope of the loop & it doesn't interfere with the one out.
There is no other scope than function scope in javascript. All our declarations are hoisted up to function scope no matter where ever they are. So, don't get misleaded :)

All you spend is 0 but you get a lot :)
function sample() {
    ....do something
    var j = 10;
    ....do something
}

As I mentioned earlier there are no other scopes other than functions. So, what happens here is
function sample() {
    var j = undefined; // Hoisted to the top always. Better we do it meaningfully as var j = 10;
    ....do something
    j = 10;
    ....do something
}

Keep the declarations @ the beginning always. It costs you nothing but it might save your time in future :)

You might know what you are doing :)
if(a = b) { //1
    
}

if(a == b) a(); c(); //2

You might know what you are doing, but don't expect others
I might think for 1, It as either
if(a == b) { //typo
    
}
//or 
a = b;
if(a) {
    
}

For 2
if(a == b) {
    a();
    c();
}
//or
if(a == b) {
    a();
}
c();

Be clear for others too :) It helps

ALL is always bigger than LOT :) U gotta believe :P
0 == false //true
'0'==false //true
'false'==false //false

These might not affect in lots of places but lot !== all :P So, Always use
0 === false //false
'0' === false //false
'false' === false //false


Without with
var test = {    //1
             name: 'xxx',
             age: 12
}
var age = 100;
with(test) {
    age = 200;
} 
console.log(test.age);
console.log(age);

var test = {    //2
             name: 'xxx',
}
var age = 100;
with(test) {
    age = 200;
} 
console.log(test.age);
console.log(age);

1 & 2 are not the same. So, don't rely on unreliable things out there :)

I think I'm becoming Crockford's fan :)

Thursday, November 17, 2011

A Javascript Introduction

Had a chance to read a nice javascript tutorial on variables and data types :)
Let's share :)

Q: How will I declare a variable?
var variablename;

Q: I don't like variablename I wish to have $$$$$, Is it possible?
A: Ya you can there is no restriction on varible names except
1. It should start with either a alphabet or $ or _
2. It should not use any reserve words like function, break, var, etc.,
3. It should not use any of the operators [!@#%^&*()-+=]

Q: Is there any javascript practise to declare variables?
A: The answers is upto you. But most common practise is using CamelCase [Inherited from java]
 var testvariable;
 const TEST_CONSTANT;
 function testFunction() {
    
 }
 testObject = new Object();
 
Another way is Hungarian Notation - appending type of the field/variable to its name
var intAge = 19; //Interger
var strName = "xxxx"; //String
var bSet = false; //Boolean
var fpRate = 12.22; //Floating Point
var fMember = true; //Flag
Advantage:
Following such conventions would increase the readability factor of the code.

Q: What are the primitive types available?
A: numeric, string, boolean are the 3 primitive types available in JavaScript.
All these 3 Primitive types are wrapped by in-built Number, String and Boolean objects

Q: Wrapped by - means?
A: Number, String and Boolean are in-built objects, that support predefined methods for its instances.
Applying such methods over primitive types will also work, though they are not an instance of any of the above mentioned in-built objects.

Q: How is it possible?
A: On applying those methods over primitive types an anonymous instance of respective in-buit object is created and destroyed once the process is completed
Ex:
var age = 12;
var hexAge = age.toString(16);
Here, a Number object is created and it wraps primitive type of 'age', then toString is applied. Once the result is assigned, the instance created is destroyed

Q: What about case sensitiveness?
A: Javascript is Case Sensitive
Ex:
var age = 12;
var Age = 22; //Valid and Different from age

Q: What is this var? Why not int, float, String?
A: Javascript supports loose typing. Type of the variable is defined based on its content
Ex:
var age; //Type undefined
var intAge = 12;  //Type numeric
var fpAge = 12.12; //Type numeric
var bAge = true; //Type boolean
var strAge = '12'; //Type string
var arMarks = new Array() //Type Array object
intAge = true; //Changes type to boolean
Note:
Every Un Initialized variable either declared or not will be initialized with undefined;
Every variable has a boolean value associated with it, to mention whether it is set or not

Q: How does String work?
A: Strings are array of characters quoted either using '' or "" [Either make no difference].
Ex:
var strName = 'xxxx'; //valid
var strCity = "zz";  //valid
var strHobby = "I'm writing a blog"; //valid
var strMe = 'This is my number "12345"'; //valid
var strIV = 'I'm single'//Invalid
var strValid = 'I\'m single' //valid
Escaping characters is allowed and meaning is the same as other languages
Ex: \n, \t, \\, \'

Q: Guess the value of vars
var a = 1+2+3+'4';
var b = '4'+3+2+1;
 
A: a = 64 & b = 4321
Reason:
+ -> Means Concatenation over strings and Addition over numerics
This is the only operator which converts numeric to string implicitly
Others convert the other way round

Q: Guess the value of vars
var a =  12/'4';
var b = '12'/'4';
var c = '12' > '4';
var d = '12' > 4;
A: a = 3 , b = 3 , c = false & d = true
Reason for c:
Both the operands are string so, it is equal to strcmp

Q: Guess the value of vars
var test = new Array('1',{"sample":'2'},'3',4,5,1.2,3.4);
var a =  test[0];
var b = test[1].sample;
var c = test[7];
var d = test['element'];
 
A: a = '1' ,b = 2 & c = undefined & d =undefined
Reason:
Array in javascript itself is an in-built object. It is just a heterogenous collection.
It is always a hash where key for the hash is the index
key---value
'0'---1
'1'---object
'2'---'3'
....
So referencing an outof bound index [7] or not even an index ['element'] will never throw an error instead returns undefined

Some Typeconversion Facts
Number
Conversion:
  Explicit:
    Integer.parseInt()
    Integer.parseFloat()
  Implicit:
    Any arithmetic expression does implicit conversion [except + as mentioned earlier]
undefined----Nan
null---------Nan or 0 [Browser Dependent]
true---------1
false--------0
string-------corresponding value 
object-------Nan 
String
Conversion:
  Explicit:
    toString
  Implicit:
    + operator
undefined---'undefined'
null--------'null'
true--------'true'
false-------'false'
number------'value'
object------[ObjectType object]
Boolean
undefined---false
null--------false
number------false if value is 0 or NAN, true other wise
string------true if not empty [empty is not equal to null]

What ever might be the type while outputting to the browser everything is converted to string :)

If we use some undeclared variable a prototype chain is followed to figure out its value.
Say
var test = {
      'hai':'sample',
      'testFunc':function sampleFunc(){}
    };

alert(test.hai);
Chain:test->object [object is parent of all & end of prototype chain]

Here object test has its own prototype. On executing test.hai JS engine checks for hai in test's prototype. If not defined, it follows the prototype chain of test which is followed by object. If it couldn't find it in it's prototype it returns undefined instead any error.

You cannot access undefined of undefined, Means
var hai;
var sample = hai.test;//Invalid Will throw Type Error since base is undefined
bar.foo; // Invalid Will throw Referrence Error. Since bar is not even declared

Try all these yourself
false == 'false'
false == null
false == ''
false == undefined
false == 0
false == Nan
false == 'false'
true == 'true'
true == '1'
false == '0'
''==0
And wonder :)

I hope I'm Done :)

Tuesday, November 15, 2011

CQL(Cassandra Query Language) Reference

Hi,
I think now I'm eligible to publish a blog post regd CQL. I wish this blog to be a tutorial rather a Syntax provider for various CQL queries

Points to remember
1. CQL doesn't support Composite Types[likely to chage]
2. CQL doesn't support Super columns
3. Counter values are returned in native format [atleast in php/using cqlsh]

Why should I prefer CQL?

1. Readability
2. Ease of use
3. SQL like
4. Stable

Support:
PHP => My Posts using PHPCassa
Python => Refer Here and Download it here
Java => JDBC Driver and Example is here
Ruby => This might help

Creating a Keyspace:
cqlsh> CREATE KEYSPACE sample WITH strategy_class = 'org.apache.cassandra.locator.SimpleStrategy' 
    ... AND strategy_options:replication_factor = 2;
 
Note:
: => Option Specifier

Use a Keyspace:
cqlsh> USE sample;
 
Note:
Don't forget to USE before use
'Sample' and 'sample' are different.

Create Column Family:
cqlsh> CREATE COLUMNFAMILY Test (date ascii PRIMARY KEY, name ascii, age int) WITH default_validation=ascii
    ... AND comparator=ascii
    ... AND replicate_on_write=true;
 

Insert Row:
cqlsh> INSERT INTO Test ('date', 'name', 'age') VALUES ('123', 'tamil', 12)
    ... USING CONSISTENCY ONE
    ... AND TTL 20;
 

Update Counter Row:
cqlsh> UPDATE COUNTERTEST SET 'samplecounter' = 'samplecounter'+5 WHERE KEY='testkey';
 

Update Standard Row:
cqlsh> UPDATE Test SET 'name'='Tamil' WHERE 'date'='123'
 
Note:
We have named row key as 'date'
If you specify KEY instead 'date' your terminal might knock with
Bad Request: Expected key 'KEY' to be present in WHERE clause for 'Test'


Select:
cqlsh> SELECT * FROM Test WHERE 'date'='123';
date | age | dept | desc |  name | rollno |
 123 |  12 |  yyy |  zzz | tamil |    xxx |

cqlsh> SELECT 'a'..'f' FROM Test WHERE 'date'='123';
age | dept | desc |
 12 |  yyy |  zzz |

cqlsh> SELECT FIRST 2 'a'..'z' FROM Test WHERE 'date'='123';
age | dept |
 12 |  yyy |
 
cqlsh> SELECT REVERSED 'z'..'a' FROM Test WHERE 'date'='123';
rollno |  name | desc | dept | age |
   xxx | tamil |  zzz |  yyy |  12 |
 
cqlsh> SELECT FIRST 2 REVERSED 'z'..'a' FROM Test WHERE 'date'='123';
rollno |  name |
   xxx | tamil |

cqlsh> SELECT * FROM Test;
date | age |  name |
 123 |  12 |  yyy |  zzz | tamil |    xxx |
 345 |  12 | pamil |
 234 |  12 | camil |
 
cqlsh> SELECT * FROM Test LIMIT 2; 
date | age |  name |
 123 |  12 |  yyy |  zzz | tamil |    xxx |
 345 |  12 | pamil |

--After some random insertions
cqlsh> SELECT * FROM Test where 'date' in ('123', '124', '125');
date | age |  name |
 123 |  12 | tamil |
 124 |  12 | tamil |
 125 |  12 | tamil |
 

Truncate:

cqlsh> TRUNCATE Test;
 

Drop:

cqlsh> DROP COLUMNFAMILY Test;
cqlsh> DROP KEYSPACE sample;
 

Using Secondary Indexes we can query columns based on values rather by their names.
Creating Index
cqlsh> CREATE INDEX name_test_key ON Test (name);

Using the index
cqlsh> SELECT * FROM Test where name = 'tamil';
 date | age |  name |
  127 |  13 | tamil |
  123 |  12 | tamil |
  124 |  12 | tamil |

cqlsh> SELECT * FROM Test where name = 'tamil' and age > 12;
 date | age |  name |
  127 |  13 | tamil |

Note: I'm able to query based on age's value too as there is an index existing on name
So, I'm done :) Just refer this guy's blog for all constants, arguments and options

Friday, November 4, 2011

Cassandra CQL PHP Part 2

I have explained the way to execute CQL Queries from PHP via PHPCassa in my previous blogpost here and tutorial on cql queries here

It was difficult for me to remember the syntax of update and select CQL queries for Cassandra. Hence I wrote wrappers for them which are listed below

Update Counter Query:
/*
  * $counterMap => Associative array of CounterColumn names and corresponding value for given $key
  * Ex: UPDATE TestCounterFamily SET 'counter'='counter'+1, 'counter2'='counter2'+3 WHERE KEY='test'
*/ 
function generateUpdateCounterQuery($columnFamily, $counterMap, $key) 
{
  $colArgs = "";
  foreach($counterMap as $counter => $value)
  {
      $colArgs=$colArgs."'".$counter."'='".$counter."'+".$value.", ";
  }
  $colArgs = rtrim($colArgs,", ");
  return "UPDATE ".$columnFamily." SET ".$colArgs." WHERE KEY='".$key."'";
}

Update Standard Column Query
/*
  * $columnMap => Associative array of Column names and corresponding value for given $key
  * Ex: UPDATE TestColumnFamily SET 'name'='abc', 'country'='IN' WHERE KEY='test'
*/ 
function generateUpdateStandardColumnQuery($columnFamily, $columnMap, $rowKey) 
{
  $colArgs = "";
  foreach($columnMap as $columnKey => $value)
  {
     $colArgs=$colArgs."'".$columnKey."'='".$value."', ";
  }
  $colArgs = rtrim($colArgs,", ");
  return "UPDATE ".$columnFamily." SET ".$colArgs." WHERE KEY='".$rowKey."'";  
}

Select Column Query
/*
 * $column = Column to be selected from Cassandra $columnFamily
 * Ex: SELECT 'name' FROM TestColumnFamily WHERE KEY='test'(Updated)
 */ 
function generateSelectQuery($columnFamily, $column, $key, $limit='-1', $reversed='0', $range=false) 
{
  if($limit=='-1')
  {
     if($reversed == '1' && $range)
     {
       return "SELECT REVERSED '".$column."' FROM ".$columnFamily." WHERE KEY = '".$key."'";
     }
     return "SELECT '".$column."' FROM ".$columnFamily." WHERE KEY = '".$key."'";
  }
  if($reversed=='0')
  { 
    return "SELECT FIRST ".$limit." '".$column."' FROM ".$columnFamily." WHERE KEY = '".$key."'";
  }
  return "SELECT FIRST ".$limit." REVERSED '".$column."' FROM ".$columnFamily." WHERE KEY = '".$key."'";
}

Generate Range Queries
function selectColumnRange($columnFamily, $from, $to, $key, $limit='-1', $reversed='0') 
{
 return $this->generateSelectQuery($columnFamily ,$from."'".".."."'".$to, $key, $limit, $reversed, $range=true);
}

Execute Selects and Updates
function executeCQLSelect($query, $compression=cassandra_Compression::NONE) 
{
  $resultSet = $raw->client->execute_cql_query($query, $compression);
  return $resultSet;
}

function executeCQLUpdate($query, $compression=cassandra_Compression::NONE) 
{
  $raw->client->execute_cql_query($query, $compression);
}

Sample ColumnMap array would be like
$columnMap = array("name"=>"test", "country"=>"IN")

My solution to test ResultSet returned by Select Query
function isResultNull($resultSet)
{
      return (isset($resultSet->rows[0]) && $resultSet->rows[0] instanceof cassandra_CqlRow && count($resultSet->rows[0]->columns) > 0);
}

Hope this helps :)

Tuesday, November 1, 2011

Auto-Complete in Eclipse&Zend

[Try right click on project and see if there is Configure > Add PHP Support, If it is there use it]

This is a inference of mine while using Eclipse/Zend as IDE for PHP in linux [Not sure abt windows]

I was able to notice that PHP perspective over a SVN checked out PHP project didn't function as it was doing for a regular PHP project created via eclipse.
For Ex:
1. No syntax errors where highlighted/notified
2. CTRL press over a variable or a class or a function didn't give the option to navigate to the point its declaration
3. Autocompletion was completely disabled

After lots of searching, I figured out that whenever we create a project via eclipse, it will create two configuration files along with it

.project

.buildpath


SVN projects might have these files not being configured properly or might even miss them

So, inorder to overcome this, either you can create one by hand or create a new PHP project and export the files you checked out in to the newly created project.

Following are the sample configuration files. You can use them to create one by hand. Place the files in your project's root directory

.project
<?xml version="1.0" encoding="UTF-8"?>
  
    Your Project Name
    
    
    
    
        
            org.eclipse.wst.validation.validationbuilder
            
            
        
        
            org.eclipse.dltk.core.scriptbuilder
            
            
        
    
    
        org.eclipse.php.core.PHPNature
    
Including the previous file itself should fix the issue. If not then go on with this too. Select the correct path for the following file
.buildpath
<?xml version="1.0" encoding="UTF-8"?>

    
    

In linux these file will be by default hidden. Use CTRL+h to unhide them. If they don't exist then create new ones and restart your eclipse
Hope this helps :)

Monday, October 24, 2011

Abt Some Linux Commands

Interesting Linux Terminal Commands

Notation => | - Cursor

CTRL + w
= Delete a word of the command typed
Ex:
$ echo this is a line|
$ echo this is a |[After ^w]

CTRL + b = Move the cursor one character left[Backward]
Ex:
$ cat filename|
$ cat filenam|e

CTRL + a = Move to the start of the command [Equivalent to Home]
Ex:
$ cat filename|
$ |cat filename

CTRL + u = Clear the command from the cursor's point
Ex:
$ cat file1 |file2
$ file2

CTRL + r
= Reversed search, Searchs for the pattern in the commands entered in the past and displays one after another continuously [Last entered command first]


CTRL + e
= Move to the end of the command
Ex:
$ cat |file1 file2
$ cat file1 file2|

!! = Executes the last entered commmand

!$ = Returns the last argument of previously entered command
Ex:
$ mkdir /home/user/temp
$ cd !$

!pattern = Executes the last command with this pattern

!pattern:p = Prints the last command with this pattern instead executing
 

_whatever = Never stores the command in history[_ = space character]
Ex:
$  echo hai
 

Interesting things in vim

:earlier n[Sec 's'|Min 'm'|Hour 'h'|changes '']
:later n[Sec 's'|Min 'm'|Hour 'h'|changes '']

Ex:
:earlier 10s

Switches from current to n[Sec|Min|Hour|changes] before[earlier] or after[later]

:w !sudo tee %
Write even in non-sudo user mode without exiting.
 

gg=G
Indent the entire file

:set tabstop=n
Sets tab characters to n length

:set smartindent|autoindent|cindent
Sets the appropriate indentation

VU = Uppercase the current line

Vu = Lowecase the current line


VEU = Uppercase the word

g~~ = Invert case of the current line [~ - tilde]
In visual mode you can select the text and use tilde to invert case


CTRL + x = Decrements the number under the cursor by 1
CTRL + a = Increments the number under the cursor by 1

:split filename = Opens another file in the same window, split happens horizontally
:vsplit filename = Opens another file in the same window, split happens vertically
CTRL + w
[twice] = Move around the opened files

:hide = Hide current window
CTRL + g = Details of the file[Total no. of lines and % to go from current line]
H = Start of Screen 
M = Middle of Screen
L = Last of Screen
zt = Bring the line to the top [Kind of page up]
zz = Bring the line to the middle
zb = Bring the line to the bottom [Kind of page down]
G = End of file
gg = Start of file 
q: = Command History
q/ = Search History
$ = End of line
b = Beginning of non white space word in  backword direction
B = Beggining of non white space word in forward direction
* = Moves to next occurence [highlights all matches if enabled] of current word in forward direction
#Moves to next occurence of current word in backward direction
^ = Start of line
$ = End of line
<aB || >aB = Intend a Block
c% = Cut the current block
. = Repeat the previous action
CTRL+SHIFT+R+" = Paste the clip board content in insert mode
:set paste = Preserve Indentation
:set ignorecase = ignores case on file search 
All above mentioned commands are useful only if you find the use of them :) For example See the Ex. mentioned for !$ mentioned in the list.

Monday, October 10, 2011

Cassandra CQL PHP

After lots of googling I figured out how to access counter columns value via PHPCassa + CQL. Though it might not be efficient, this is all I was able to figure out after a long struggle :)

First Connecting to and Selection from Cassandra Instance via PHP using PHPCassa
$pool = new ConnectionPool("Stats",$servers);
$raw = $pool->get();
$rows = $raw->client->execute_cql_query("SELECT 'a' FROM Impressions WHERE KEY='xxx'", cassandra_Compression::NONE);
To Return Connection
$pool->return_connection($this->raw);
To Update Counter value via PHPCassa
$pool = new ConnectionPool("Stats",$servers);
$raw = $pool->get();
$rows = $raw->client->execute_cql_query("UPDATE TestCounter SET 'counter'='counter'+1 WHERE KEY='xxx'", cassandra_Compression::NONE);
You can find a wrapper here

So, once you are done with fetch successfully. This is the result you may get
object(cassandra_CqlResult)#17 (3) {
  ["type"]=>
  int(1)
  ["rows"]=>
  array(1) {
    [0]=>
    object(cassandra_CqlRow)#18 (2) {
      ["key"]=>
      string(4) "xxx"
      ["columns"]=>
      array(1) {
        [0]=>
        object(cassandra_Column)#19 (4) {
          ["name"]=>
          string(11) "a"
          ["value"]=>
          string(8) " "                       // Actually there is the value between the quotes
          ["timestamp"]=>
          int(1318230159648)
          ["ttl"]=>
          NULL
        }
      }
    }
  }
  ["num"]=>
  NULL
} 
The problem is CQL returns counter value as string rather int.

So, one general solution everyone would consider is hexdec($rows->rows[0]->columns[0]->value)

But the encoding of string returned is not a hex string. So, hexdec won't help.

So, I figured out a function to convert the string returned to a hex string
function strToHex($string)
{
$hex='';
for ($i=0; $i < strlen($string); $i++)
     {
         $hex .= dechex(ord($string[$i]));  //ord returns the ascii equivalent of given char
     }
     return $hex;
}
Now u have the hex string. Final step
$val = hexdec(strToHex($rows->rows[0]->columns[0]->value))
One more solution for the same
$data = unpack("H*",$rows->rows[0]->columns[0]->value);
$val = hexdec($data["1"]);

Reference: https://gist.github.com/1024060 Hope it helps :)




Sunday, September 18, 2011

Crisps abt scalability Part 3

New to this post?? Go on with Crisps abt Scalablity Part 1 and Part 2
So are you convinced with Master Slave. Let us move on to Sharding or Shared Nothing Architecture
What is it?
 Before this I'll answer a different question.
For Whom is it??
 If the application you built can be partitioned. A scenario, You have 1 billion customers and all the customers are currently being maintained by only one data store. And they are being served from the only available data store. But the beauty of your application is there is nothing being shared between two customers. So, what is the use of it?? Just split them. Because they all are going to read data about them and they are going to write to data about them. Put up in another way, No one is going to read or write to your data except you. So, what you can do is just split your billion customers in to half a billion and make another data store to handle them. I hope now you understood what it is. 
That is awesome :)  
 Ya really, provided your application is of such a kind :)
Final touch on Consistency, Availability and Partition tolerance [CAP]
Why these three?
 According to Brewer's theorem on distributed systems. Any well designed distributed system can achieve only any two of these verticals. It is a tradeoff. And the best thing is, this theorem has a proof as well. 
Cool, what are they?
 Nice delayed question. Consistency - It can be broadly explained as read and write consistency. Read consistency -> Assurance to the user that he/she reads the most recent data. Means once there is an update that should be immediately reflected back to the user who sends the next request after the update. Write consistency -> A scenario, let X be a global variable P1 and P2 both wishes to write to it. By timeline P1 should be able to do the first write and P2 the second one. So, Finally P2's data should be available. If this doesn't happen then write consistency is said to be failed. As per the needs the system integrates a desired level of consistency like Strict, Causal and Weak. Causal only looks odd. It is nothing but event based consistency. Like if e2 is the effect of e1 then we can say e1->e2. So, this is the way the reads are write will be performed. But the problem is, if the events occur with in a single system everything is fine we can determine causal relationship based on time and process execution. Here everything happens across system. So, we need to implement a kind of global clock or use protocol like NTP. Here I'm discussing abt distributed systems. So, reads and write I mention can happen @ any point in the system but it should be reflected properly in all points :)
Availability - This is simple but difficult :P What if one of the machines of yours failed. Means either network unavailability, floods blah, blah  n all. The data contained by that machine is lost. So, how do we handle this?? The solution is replica management. Instead of writing data to a single server write it to other complement servers and that would help atleast to retain data after loss. This n is mostly called as replication factor.
Partition Tolerance - Consider you have 5 nodes and are arranged in a ring what if node 2 and 4 goes down. 3 becomes unreachable now to 1 and 5 and this is called as network partitioning. Your application should be able to handle this.  

As I said earlier choose two go good :) Cassandra choses AP, Google Big table choses CP, MYSQL choses CA. And hence they are performing well :)

Crisps abt Scalability Part 2

If you are reading this part for the first time. First go on with the previous post Crisps abt Scalability Part 1 of mine.
So what are the two alien terms I mentioned earlier. 
WT* is Master and Slave Architecture??
Simple as it name depicts. There ll be one master and the slaves ll listen to him. Soooorrry :P. Let me be clear. One of the implementations of master slave architecture is all writes will go only to the master and reads can be done from any of the master or slave. Ex: Redis Cache. And another way of implementation [I Hope] is master will act as a place holder of metadata about the location of data in its slaves. Ex: HBase (But this is totally different from the former, will be explained soon).
What is the advantage of this??? 
Consistency -> [Conditions apply]
How??
Simple, consider the same scenario of shopping cart. The problem was not about reading the data but writing.. right?? So, we converge all the writes to one common location so that the conflicts in consistency will be resolved at one point. Now the application looks almost like a usual single server model if u consider writes. Problem solved?? Yesssss :) But the answer is no :P 
WhyyyyyyT*?
Now comes the concept of Single point failure :) 
WT* is that?
Ha ha he he, Im there. Means your application has only one entry point for writes. So what if the entry point fails :( Everything is gone :( So, there are many other mechanisms which handles such fail overs. Like hardware, software and information redundancy blah blah n all :) 
OOPs So now all done??
You want me to say yes?? The answer again is no :P There is one more simple thing. 
What is that?? Is that really simple??
Ha ha :) You have got me right :P It is seemingly simple. The problem of write consistency is over. But read consistency??? The thing is How ll master update its slave. And when should it?? There are two ways push based and pull based. Push based is like when ever there is an update master sends an update to all its slaves to maintain consistency. Else the slave can ask for an update from master for a piece of data. Next when?? Periodically or Trigger based, based on the level of consistency application needs.
Atleast Now is it done??
Sorry to say this again the answer is no. Because there is one more issue with the previous issue :P It is, Will the master r slave will be able to respond to requests if they are getting or sending updates?? It is once againg based on the factor availability. In redis the Master side is non blocking but the slave part it is a blocking process. God should help :P So, there is a special care that needs to be taken if there is a update cycle running.

So, I'm done for Master Slave Architecture

Lets list the overheads and [de-merits may be] now
1.SPF
2.Master might get overloaded on write heavy apps
3.Update cycle
4.Availability

Did You see any of these overheads in ur single server implementation?????
1, 2 and 4 are still a problem of in that model too. 3 alone is an overhead. But that makes the big difference. If 3 is not handled properly read consistency will not be achieved. Then all is gone.

I hope now you understand why scalability might even degrade your performance instead enhancing, if you choose a perfectly wrong architecture. I have highlighted it because they ll not always degrade provided if u understand what you are implementing is appropriate for your application. Because Google and facebook are able to serve requests in n*billions using appropriate distributed architecture for them. 

In part3 I'll deal with the other one sharding or shared nothing architecture too. And let us see how it helps :)

Saturday, September 17, 2011

Crisps abt Scalability

Hi all, It was a great day with "Cassandra - Definitive Guide". The best thing i liked abt that book is the way they explained scalability(ofcourse abt Cassandra too :P). 
So, 
What is scalability?
It is nothing but yet another performance measure. To be clear, it is the measure on how well the application you built performs, if you add more resource to the environment it operates on. Ex. Adding more cores to processor, Increasing main memory's size, etc.,
Why should I care abt it?
Because it is not true that if you add more resource, performance of your system(ur app) should increase. Also there is a probability that performance of your system to decrease.
Can You Explain more in detail?
Yes, For sure. Actually there are two ways you can scale the processing environment.Horizontally and Vertically. Horizontally refers to adding more systems instead enhancing the existing system. Ex: Adding more web servers to serve the requests and using a load balancer ahead. Vertically refers to enhancing the existing system. Ex: Moving from 2GB ram to 64 GB ram, 16 core processor etc. 
What are the limitations?
Perfect question. The problem with vertical scalability is limitation and cost. Means how much can u extend the cores and main memory?? There is a limit for that always. And also cost is directly proportional to the square of configuration you expect. So, next horizontal scaling. The only issue with horizontal scaling[Distributed Systems] is maintenance. I'll explain with a scenario. Assume before scaling u had only one web server handling all the requests hitting your system. So, U need not worry abt consistency of data. Coz every one is going to read from the same. Now You had replicated your content and hosted one more web server to handle the traffic. So, part of your traffic reads from server 1 and another from server 2. So, now comes the problem. If you update one letter in a word in one of the pages of your web application you need to sync the same across all the web servers. There is a mega issue if the server you replicated is a database server instead a web server. I hope you understand the seriousness of the latter(database server).
Seriousness?? What Seriousness??
 Cool. Im there again :) Regarding your web server it serves static or dynamic content. Where does this dynamicity comes from?? It is because of  the data store behind it. So, once again a scenario. You have a system implements a shopping cart. Now you have 2 customers viewing the status of a same product. The best part of it is, when C1 gets data from DB Server 1 and C2 gets data from DB Server 2. Now comes the question what is the issue in that?? Let us make it more serious, the product they wish to buy has only one piece left. So, If both gets access from same server there is no issue. Who ever ordered first, based on the timestamp the conflict of their order ll be resolved and the other ll be given proper status of unavailability. But here the issue is different they both contact two different servers. Sooooooooooooooo how ll consistency be achieved :(
OOOOOOOPs what should we do then?
 There are two different solutions based on the application. One is master slave architecture and another is sharding or shared nothing architecture. 
What are they? 
 Wait for part 2.

Sunday, September 4, 2011

Abt jquery drilldown

It was a boring weekend once again and I wished to author a jquery plugin for drilldown operation. Atlast I did it and commited in GIT Link to Git Repo
Really awesome job by jquery team. I never felt that it is difficult to create a plugin. It was full of fun and my day passed by in a useful way :)


Abt my plugin,
This is a plugin which helps to implement drill down in jquery.
To start working on it u need jquery latest version
U need to include either jquery.drilldown.min.js/jquery.drilldown.js in your javascript src


Usage:

$(selector).drillDown({ 

animate: true; // Default 'true' *Not required

container : ".divname|#spanName" //No Default values *Required 

listParam : "list" // Default 'list', see the demo for explanation

direction : 0 // Default 0->vertical, 1->horizontal

callBack  : test // Default 'null', Call back function to be used on selection

});


Styles:
Elements inside Drill Down are li elements with class name drillItem. You can write a customized style for it
Container is the element specified by the user. So, Sytling is upto the user

Tuesday, July 5, 2011

Something abt PoLymOrphISM

A most prominent interview question regd OOPs


I: What is Polymorphism?
S: (Ha ha ;D) Polymorphism is of two types runtime and compile time.
Methods of Compile time polymorphism are Function Overloading and Operator Overloading
Methods of Runtime polymorphism are virtual functions
I: Kool....What is virtual functions or Method Over riding?
S: (Super :D :D)It is possible that we can assign reference of a derived class object to base class
In Such a case if derived class implements a function with same signature as its base then an ambiguity will be arised on resolving function call
So, inorder to overcome that we use virtual functions.
I: Good... Why are they refered as runtime polymorphism? What do u mean by runtime??
S: (Pochu da :( :( ) "Actually" the resolution of function call takes place at runtime. "That is" Compiler don't know which function to call ... Blah Blah ....
I: Why should the resolution take place at runtime? Why not at compile time??
S: (Nammala inniki pottaanga :( :( :( ) new operator allocates memory dynamically so ........
I: K U can leave for the day :D :D


So, Finally a interview seemed to go good :) failed :(


I'm jus going to blaber something which might help u in this particular situation


Virtual functions are referred to Runtime polymorphism bcoz
public class animal // Abstract Class
{
    public void eat()
}
public class cat extends animal
{
    public void eat() { } // Implements eat
}
public class dog extends animal
{
    public void eat() // Implements eat
}
----------------
Some where in the code

animal a=null;
if(i==true)
{
    a=new cat();
}
else
{
    a=new dog();
}
a->eat();
So in the above example the value of a is determined by i which can be determined only at runtime.
IFF the value of a is determined a->eat can be resolved hence they are called as runtime polymorphism


Anyother explanations are welcome :)

Sunday, June 19, 2011

It's abt Brain F**K


It was a Boring Saturday again :P
So jus started exploring Brain F**K an awesome weird programming language 
It has got just 8 alphabets + - < > , . [ ] that's it :) 
This is like Maagi of programming languages :D

. - Prints the current byte
+ - Increments the byte pointed to
- - Decrements the byte pointed to
< - Moves to previous byte
> - Moves to the next byte
[ - Executes the instructions until ]
] - Executes the instructions from [ until the current byte carries 0
, - getchar()
U wanna know the C representation of Brain F**K char array[30000]; char *pointer; That's it :) It has a global array of size 30000 with a pointer pointing to it :) So I'm curious and tried this one
+++++ +++++ [>+>+++++++ >+++++++>++ ++++++<<<<-]>>>+++.<<. >>+++.+++.>++++++.<< -.<.>>>+++.<.>---- .<<<.>>>>+[[-] ,.------- --- ]
So now UR curious? Jus Click the link to Execute this 1. Copy paste the code 2. Type some Name r the One u like in the input Eg. xxx'\n' ('\n' - For clarity it is actually Enter in ur keyboard.) Don't forget to hit an enter at the end of the name else the code ll stuck in infinite loop 3. And Execute it :) 4. Don't laugh you are a culprit :P :P Who is that guy r girl? :D I'm done :) U also wanna explore? U have one link ahead Brain F**K

Friday, June 17, 2011

Crisps abt Design Patterns

Problems are hard solve more than that, our solution should not make our appln disobey OCP (Open to extensions and Closed to Modifications) but what if they have a quality solution pre-existing :)
That's what design patterns are :P They are generic reusable solutions for commonly occuring problems in S/W Design
Design patterns are of various categories if u wanna know them in detail follow the link below 
 Design Patterns  :)
I was just going thro some of the most commonly used Design Patterns in PHP and I wish to give them all a small introduction

Singleton:  
A common scenario for this is a LOG BOOK.

We might be recording various events at various times. So, whenever we need to record 
something we ll be declaring an object for the log book class and will be WRITING using some member functions of it. 
But what if we want a "GLOBAL LOG BOOK" for entire appln? Then choose singleton patterns. 
This pattern allows instantiation of object for a class only once. 
For Further instantiations, reference of the previously created object ll be returned. 
(Now Logbook is updated not created and written everytime)
One more appln is single player(only object of the whole app) gaming 

Google can find U PHP implementation of Singleton easily but i'll plot one for u here
class LogBook
{
  private static $LogBookObject;
  private function __construct(){...}
  public static function createInstance()
  {
     if(self::$LogBookObject==null)
     {
        self::$LogBookObject=new LogBook();
     }
     return self::$LogBookObject;
  }

  public function updateLog($msg){...}
}
$LogBookObject = LogBook::createInstance();
$LogBookObject->updateLog("This Works");
Factory: Huh!!! Its like ordering food to a waiter in a hotel :P Here waiter is an abstract object but the concrete object is the chef :) U might order Veg/Non-Veg the waiter decides to whom the order should be placed. The main advantage of it is the customer never knows even the hotel changes the chef :D Let us design a hotel appln in the sameway :)
class VegChef
{
  public function __construct() {}
  public function makeVegFood($foodName){}
}
class NonvegChef
{
  public function __construct() {}
  public function makeNonvegFood($foodName) {}
}
class Waiter
{
  private function __construct(){}
  public static placeOrder($foodType)
  {
    if($foodType=="Nonveg")
        return new NonVegChef();
    else if($foodType=="Veg")
       return new VegChef();
  }
}

$orderFood=Waiter::placeOrder("Veg");

$orderFood->makeVegFood("Gobi");
Strategy: This is like a music player that chooses songs based on our mood :P Here our behaviour like happy, romantic, sad are implemented as different classes hence any changes in happy never mess up with sad :D User ll also be able to change his mind with no intervention Lets go for implementation now
class ImHappy
{
  public function playSongs(){Algo to choose songs}
}
class ImSad
{
  public function playSongs(){Algo to choose songs}
}
class IfeelRomantic
{
  public function playSongs(){Algo to choose songs}
}
class musicPlayer
{
  private $Choice;
  public function setMyChoice($Choice)
  {
    $this->Choice=$Choice;
  } 
  public function Play()
  { 
   $this->Choice.playSongs()
  }
}

$user=new musicPlayer();
$user->setMyChoice(new ImHappy());
$user->Play();
// Ha I feel Romantic :P
$user->setMyChoice(new IfeelRomantic());
$user->Play();
There are two more Observer and Chain of command out of five I read :) Will soon comeup with nice illustrations for them :)

Thursday, June 16, 2011

all* abt PHP OO :P *conditions apply :D

Hi Folks spent a day with PHP in action Book
An awesome book for developers :)
Wanna share some useful tips out of it
0. When ISA (Inheritance)? When HASA (Composition)?
Only way to decide it is relationship if it is going to be 1:1 go for ISA 1:Many go for HASA :) Cool but true :)

1. Predict what would happen
$object1 = new base();
$object2 = $object1;
in PHP 4 a photocopy of present appearance of the object1 is copied to object2, any changes in object1 later ll not affect the latter :D
in PHP 5 it means shallow copy :) jus the reference is returned to object2 so changes on former or latter ll reflect on latter or former too :D
wanna do the PHP 5 way in PHP 4 then do
$object2 = &$object1; Explicit way :)
But this has the difference with the PHP5 way, in this jus the symbol table is adjusted (Clever no) :)

2. Can abstract functions be private?
Don't scold me if u know the meaning of abstract class :D
The answer is NOOOOOOOOO obviously :) Because abstract methods are need to be implemented by the class inherits it :) so it can't be private
So, what abt protected? It can be :D try it


3. FACT: A class with abstract method should be declared abstract :)
4. What would happen if the class inheriting an abstract class doesn't implement all the abstract methods?
Nothing the compiler will knock ur screen saying that declare the class that derives abstract :) else implement the rest :)


5. FACT: Interface is an abstract class with all methods declared abstract :)
6. Then why do we have both?
A class can inherit only one (abstract) class but can implement many interfaces :) This is how they implement multiple inheritance in java :)
Interfaces are pure abstract classes :P that is, all methods declared are abstract and public by default. So, no method defn can be there. But in abstract class there can be non-abstract methods(implemented with in the class itself) and private members are allowed too :)


7. FACT: Class is a virtual home for an object. The home will exist even if there is no habitants :D So U can loot static members and methods
8. FACT: Diff between die() and exception thrown with no catch is, stack trace is printed in the latter
9. FACT: Class constants won't accept complex expressions :) even string concatenation
10. FACT: PHP is a (statically-incomplete) dynamically typed language :D PHP 5 alows typehints :) function add(integer $a,integer $b) is valid, in the book they have specified that compiler ll generate a warning but im getting a fatal error :D
11. FACT: Method overloading is done through __CALL and by the way this is not same as function overloading :) this is a life saver at the verge of death of execution because of undefined methods :)
12. FACT: In the same way we have __autoload for classes :)

Read some design prinicples like
OCP (Open to extension and Closed to modification)
SRP (Single Responsiblity Policy) - Don't be good at many things :D
DIP (Dependency Inversion Principle) - Program for interface not for implementation :) Believe in abstraction :D

Monday, June 13, 2011

Google Facebook Fun

Jus a funny fact to start with

Jus Search for "Google" @ http://www.google/com and "Facebook" in the same :)

Search results found for Google 10,490,000,000

But for facebook 13,410,000,000

:D