Pages

Wednesday, August 10, 2022

Count Frequency of Elements in a list using Set, Map and Streams

      List<Integer> list = Arrays.asList(1,2,2,6,7,8,4,3);  
                //Using a Set  
                Set<Integer> distict = new HashSet<>(list);  
                System.out.println("Using a Set =================>");  
                for(int i : distict) {  
                     System.out.println( i + ":" + Collections.frequency(list, i));  
                }  
                System.out.println("Using a Set =================>");  
                //Using a Set  
                //Using a Map  
                Map<Integer, Integer> frequencyMap = new HashMap<>();  
                for(int i: list) {  
                     Integer count = frequencyMap.get(i);  
                     if (count == null) {  
                          count = 0;  
                     }       
                     frequencyMap.put(i, count + 1);  
                }  
                System.out.println("Using a Map =================>");  
                for(Map.Entry<Integer, Integer> entry: frequencyMap.entrySet()) {  
                     System.out.println(entry.getKey() + ": " + entry.getValue());  
                }  
                System.out.println("Using a Map =================>");  
                //Using a Map  
                //Using Streams  
                Map<Integer, Long> streamFrequencyMap = list.stream().collect(Collectors.groupingBy(Function.identity(),Collectors.counting()));  
                for (Map.Entry<Integer,Long> entry: streamFrequencyMap.entrySet()) {  
                     System.out.println(entry.getKey() +": "+entry.getValue());  
                }  
                //Using Streams  

Friday, January 10, 2020

Write a function to get the intersection point of two Linked Lists

 package programmers.choice.linkedlist;  
 import java.util.HashSet;  
 class LinkedListIntersect {   
   public static void main(String[] args)   
   {   
     // list 1   
     Node n1 = new Node(1);   
     n1.next = new Node(2);   
     n1.next.next = new Node(3);   
     n1.next.next.next = new Node(4);   
     n1.next.next.next.next = new Node(5);   
     n1.next.next.next.next.next = new Node(6);   
     n1.next.next.next.next.next.next = new Node(7);   
     // list 2   
     Node n2 = new Node(10);   
     n2.next = new Node(9);   
     n2.next.next = new Node(8);   
     n2.next.next.next = n1.next.next.next;   
     Print(n1);   
     Print(n2);   
     System.out.println(MegeNode(n1, n2).data);   
   }   
   // function to print the list   
   public static void Print(Node n)   
   {   
     Node cur = n;   
     while (cur != null) {   
       System.out.print(cur.data + " ");   
       cur = cur.next;   
     }   
     System.out.println();   
   }   
   // function to find the intersection of two node   
   public static Node MegeNode(Node n1, Node n2)   
   {   
     // define hashset   
     HashSet<Node> hs = new HashSet<Node>();   
     while (n1 != null) {   
       hs.add(n1);   
       n1 = n1.next;   
     }   
     while (n2 != null) {   
       if (hs.contains(n2)) {   
         return n2;   
       }   
       n2 = n2.next;   
     }   
     return null;   
   }   
 }  

Tuesday, June 16, 2015

Difference between Bitwise OR and Exclusive OR

Difference between Bitwise OR and Exclusive OR

Bitwise Or
  1. Takes 2 patterns of equal length and performs the logical inclusive OR operation
  2. forces a bit to be set ON in a sequence where corresponding mask bit is one
  3. Example
    1. 0101(5)
    2. 0011(3)
    3. 0111(7) // Output
Exclusive OR
  1. Returns XOR logical Exclusive OR outputs true when both inputs differ
  2. Truth Table
    1. 0 0 0
    2. 0 1 1
    3. 1 0 1
    4. 1 1 1

Swap 2 Numbers with Exclusive Or

Here is a simple program to swap to numbers with Exclusive OR

 public class Swap {  
   public static void main(String args[])  
   {  
     int a=4;  
     int b=5;  
     a^=b;  
     b^=a;  
     a^=b;  
     System.out.println(a);  
     System.out.println(b);  
   }  
 }  

Output :

5
4

Java - Division by Floating Zero

An amazing result of Java Program on Division by 0.0

 public class Fruits {  
   public static void main(String args[])  
   {  
     int numOranges=5;  
     int numApples=10;  
     double averageFruit=0.0;  
     double fruitTypes=0.0;  
     averageFruit=(numOranges+numApples)/fruitTypes;  
     System.out.println("Average fruit is "+averageFruit);  
   }  
 }  
 Output : Average fruit is Infinity  


Infinity means a positive but effectively infinite result that is greater than the largest number that can be stored in double

Tuesday, November 18, 2014

Mysql Puzzle(Left Join)-Take out those department who have no employees assigned to it

EMP
EMPNO   ENAME    DEPTNO

DEPT
DEPTNO   DNAME
 
 
1st Way using Subquery
 
SELECT D.DNAME
FROM DEPT D
WHERE 
NOT EXISTS (SELECT * FROM EMP E WHERE D.DEPTNO = E.DEPTNO) 

2nd way using Left Join
 
SELECT D.DNAME
FROM DEPT D
LEFT JOIN EMP E ON D.DEPTNO = E.DEPTNO
WHERE E.DEPTNO IS NULL 

Sunday, November 16, 2014

HTML - HTTP Request Types

1) GET:- Used when the client is requesting a resource on the Web server.

2) HEAD:- Used when the client is requesting some information about a resource but not requesting the resource itself.

3) POST:- Used when the client is sending information or data to the server—for example, filling out an online form (i.e. Sends a large amount of complex data to the Web Server).
POST sends data to a specific URI and expects the resource at that URI to handle the request. The web server at this point can determine what to do with the data in the context of the specified resource.

Example can be
obj.set_attribute(value)


4) PUT:- Used when the client is sending a replacement document or uploading a new document to the Web server under the request URL.
PUT puts a file or resource at a specific URI, and exactly at that URI. If there's already a file or resource at that URI, PUT replaces that file or resource. If there is no file or resource there, PUT creates one.

Example Can be
obj.attribute = value


5) DELETE:- Used when the client is trying to delete a document from the Web server, identified by the request URL.

6) TRACE:- Used when the client is asking the available proxies or intermediate servers changing the request to announce themselves.

7) OPTIONS:- Used when the client wants to determine other available methods to retrieve or process a document on the Web server.

8) CONNECT:- Used when the client wants to establish a transparent connection to a remote host, usually to facilitate SSL-encrypted communication (HTTPS) through an HTTP proxy.

Friday, September 5, 2014

Cakephp-Overview of Programming Patterns

Active Record Pattern

Active Record Pattern is for those application's which use relational databases.
The interface of an object conforming to this pattern would include functions such as Insert, Update, and Delete, plus properties that correspond more or less directly to the columns in the underlying database table.

Association Data Mapping

An Association data mapping pattern allows Relational object to associate with other Relational Objects the way they are associated in Relational Databases.

Front Controller

The Front Controller Pattern allows handling of all requests to be at a centralized location from where they are redirected specified Request Processors.

MVC

MVC expended as Model View Controller is a pattern where

Model's act as a wrapper classes for Database Table's
Controller's act as wrapper classes for Business Logic
and View act's as file for User Interface
 

Saturday, July 19, 2014

Set up htaccess permissions in ubuntu 14.04

We need to enable mod_rewrite

sudo a2enmod rewrite 

Then we need to restart Apache using following command

 
sudo service apache2 restart 

Then add following lines to /etc/apache2/sites-available/000-default.conf

<Directory "/var/www">
   Options FollowSymLinks 
   AllowOverride All
</Directory>

My apache directory is "/var/www" if yours is different change it to taste

Restart Apache again

sudo service apache2 restart 

Sunday, January 26, 2014

Debian/Linux/Ubuntu-Configure Postfix to use Gmail

Configure Postfix to use Gmail

Install necessary packages first

 sudo apt-get install postfix mailutils libsasl2-2 ca-certificates libsasl2-modules  

 Configure Postfix using


 sudo dpkg-reconfigure postfix  


Navigate to Postfix Directory

 cd /etc/postfix  

Open Postfix config file using following command

 sudo gedit main.cf  

Add following lines to it


 relayhost = [smtp.gmail.com]:587  
 smtp_sasl_auth_enable = yes  
 smtp_sasl_password_maps = hash:/etc/postfix/sasl_passwd  
 smtp_sasl_security_options = noanonymous  
 smtp_tls_CAfile = /etc/postfix/cacert.pem  
 smtp_use_tls = yes  

Now we need to create a file called sasl_passwd


 sudo vi /etc/postfix/sasl_passwd  

Add the following line to the same


 [smtp.gmail.com]:587  USERNAME@gmail.com:PASSWORD  

Configure permissions for sasl_passwd


 sudo chmod 400 /etc/postfix/sasl_passwd  
 sudo postmap /etc/postfix/sasl_passwd  

Validate Certificates


 cat /etc/ssl/certs/Thawte_Premium_Server_CA.pem | sudo tee -a /etc/postfix/cacert.pem  

Reload Postfix


 sudo /etc/init.d/postfix reload  

Test Mail from Terminal


 echo "Test mail from postfix" | mail -s "Test Postfix" you@example.com  

Copy of my php.ini mail section


 SMTP = ssl://smtp.gmail.com  
 smtp_port = 587  
 auth_username = usrname  
 auth_password = pwd  
 sendmail_from = from_mail  

Monday, December 16, 2013

PHP-Arrays-Get the occurance of each value in numeric array

Like as always we have a problem we have some prerequisites we will have a function and we will draw some results


Problem and Prerequisites :

We have an array let us suppose array(1,2,1,3,4,5,4,6,3,2,1,2,8,9,3,4,5,3,2,4,6,2) and we want to create a function that checks for number of times value repeats in the array.

So we need and output like

1 repeats 3 times
2 repeats 5 times etc.

Function and Solution :

 <?php
 function get_modes($numarray)  
 {  
   if(!(is_array($numarray)))  
     throw new Exception ('Parameter Not an array');  
   $revarray=array();  
   foreach($numarray as $key=>$value)  
   {  
     if(array_key_exists($value,$revarray))  
     {  
       $revarray[$value]++;  
     }  
     else   
     {  
       $revarray[$value]=1;  
     }  
   }  
   return $revarray;  
 }  
 $myarray=array(1,2,1,3,4,5,4,6,3,2,1,2,8,9,3,4,5,3,2,4,6,2);  
 $navarray=get_modes($myarray);  
 foreach($navarray as $key=>$value)  
 {  
   echo $key." repeats ".$value." times<br/>";  
 }  
 ?>  

Output:

1 repeats 3 times
2 repeats 5 times
3 repeats 4 times
4 repeats 4 times
5 repeats 2 times
6 repeats 2 times
8 repeats 1 times
9 repeats 1 times

Sunday, December 15, 2013

PHP-Image functions

//size of image
getimagesize()
http://www.php.net/getimagesize

//image width
imagesx()
http://www.php.net/manual/en/function.imagesx.php


//image height
imagesy()
http://www.php.net/manual/en/function.imagesy.php

//determine type of an image
exif_imagetype()
http://www.php.net/manual/en/function.exif-imagetype.php

Encrypt data using PHP

Encryption Decryption
AES_ENCRYPT() AES_DECRYPT()
ENCODE() DECODE()
DES_ENCRYPT() DES_DECRYPT()
ENCRYPT() N/A
ENCRYPT() N/A
MD5() N/A
OLD_PASSWORD() N/A
PASSWORD() N/A
SHA() N/A
SHA1() N/A
N/A UNCOMPRESSED_LENGTH()

Saturday, December 14, 2013

HTML->Difference between GET and POST methods

POST Method
In Post method we can send unlimited data(This limit is defined by server for example "post_max_size=20M" in Apache)

Data is not shown in URL so it is good for sensitive data

GET Method

In GET method this depends on browser for example IE8 can take about 2048 bytes of data i.e about 2KB

Data is shown in URL so not appropriate for sensitive data

PHP-Database connectivity function's

One of the main aspects of PHP is database connectivity.Though it supports variety of databases we will talk about mysql in particular here.

All the functions which are of concern are present in file mysqli.php which contains class "mysqli_sql_exception" which in turn extends "RuntimeException"

The very first functions that we encounter while working with databases with PHP are the "connect functions".

Let's see what we get when we execute these functions in order

As a software development flows we will have some prerequisites,a function which will process them and then we will have some results.

Prerequiaites :

A dbhost : "localhost"
A username : "uroot"
A password : "proot"
Also

That's it and all we need is a php setup LAMP/WAMP/MAMP/XAMPP package

Our first function :
 $con= mysqli_connect('localhost1','puroot','pproot','test1');  
Reference :
/**
 * (PHP 5)<br/>
 * Alias of <b>mysqli::__construct</b>
 * @link http://php.net/manual/en/function.mysqli-connect.php
 * @param $host [optional]
 * @param $user [optional]
 * @param $password [optional]
 * @param $database [optional]
 * @param $port [optional]
 * @param $socket [optional]
 */
function mysqli_connect ($host, $user, $password, $database, $port, $socket) {}

This function tries to connect to the database with given credentials. We have created a negative mutant to test the same as you can see from what credentials we have passed above.


Our Second function and third function :
 if (mysqli_connect_errno())  
 {  
   echo "Failed to connect to MySQL: " . mysqli_connect_error();  
 }
Reference:
/**
 * (PHP 5)<br/>
 * Returns the error code from last connect call
 * @link http://php.net/manual/en/mysqli.connect-errno.php
 * @return int An error code value for the last call to <b>mysqli_connect</b>, if it failed.
 * zero means no error occurred.
 */
function mysqli_connect_errno () {}

/**
 * (PHP 5)<br/>
 * Returns a string description of the last connect error
 * @link http://php.net/manual/en/mysqli.connect-error.php
 * @return string A string that describes the error. <b>NULL</b> is returned if no error occurred.
 */
function mysqli_connect_error () {}

Now when we execute the above pieces of code we get an error

Failed to connect to MySQL: Unknown MySQL server host 'localhost1' (2)Error creating database:

When we set host right we get following error
Failed to connect to MySQL: Access denied for user 'puroot'@'localhost' (using password: YES)Error creating database: 

Similarly when we set username and password right we get
Failed to connect to MySQL: Unknown database 'test1'

Now that we are done with the set of connection functions we will try to create a database on success.Now since we have already created a database "test" we will test with a negative mutant.

Our fourth and fifth function
 $sql="CREATE DATABASE test";  
 if (mysqli_query($con,$sql))  
 {  
   echo "Database test created successfully";  
 }  
 else  
 {  
   echo "Error creating database: " . mysqli_error($con);  
 }  
Reference:

 /**  
  * (PHP 5)<br/>  
  * Performs a query on the database  
  * @link http://php.net/manual/en/mysqli.query.php  
  * @param mysqli $link  
  * @param string $query <p>  
  * The query string.  
  * </p>  
  * <p>  
  * Data inside the query should be properly escaped.  
  * </p>  
  * @param int $resultmode [optional] <p>  
  * Either the constant <b>MYSQLI_USE_RESULT</b> or  
  * <b>MYSQLI_STORE_RESULT</b> depending on the desired  
  * behavior. By default, <b>MYSQLI_STORE_RESULT</b> is used.  
  * </p>  
  * <p>  
  * If you use <b>MYSQLI_USE_RESULT</b> all subsequent calls  
  * will return error Commands out of sync unless you  
  * call <b>mysqli_free_result</b>  
  * </p>  
  * <p>  
  * With <b>MYSQLI_ASYNC</b> (available with mysqlnd), it is  
  * possible to perform query asynchronously.  
  * <b>mysqli_poll</b> is then used to get results from such  
  * queries.  
  * </p>  
  * @return mixed <b>FALSE</b> on failure. For successful SELECT, SHOW, DESCRIBE or  
  * EXPLAIN queries <b>mysqli_query</b> will return  
  * a <b>mysqli_result</b> object. For other successful queries <b>mysqli_query</b> will  
  * return <b>TRUE</b>.  
  */  
 function mysqli_query (mysqli $link, $query, $resultmode = 'MYSQLI_STORE_RESULT') {}  
 /**  
  * (PHP 5)<br/>  
  * Returns a string description of the last error  
  * @link http://php.net/manual/en/mysqli.error.php  
  * @param mysqli $link  
  * @return string A string that describes the error. An empty string if no error occurred.  
  */  
 function mysqli_error (mysqli $link) {}  


Error creating database: Can't create database 'test'; database exists

because we have already created one

similarly mysql_query() is used for create table,insert

Our sixth function

 $result= mysqli_query($con,"SELECT * FROM Persons");  
 while($row= mysqli_fetch_array($result))  
 {  
   echo "<pre>";  
   print_r($row);  
   echo "</pre>";  
 }  
 $result= mysqli_query($con,"SELECT * FROM Persons");  
 while($row= mysqli_fetch_row($result))  
 {  
   echo "<pre>";  
   print_r($row);  
   echo "</pre>";  
 }  
 $result= mysqli_query($con,"SELECT * FROM Persons");  
 while($row= mysqli_fetch_object($result))  
 {  
   echo "<pre>";  
   print_r($row);  
   echo "</pre>";  
 }  
 $result= mysqli_query($con,"SELECT * FROM Persons");  
 while($row= mysqli_fetch_assoc($result))  
 {  
   echo "<pre>";  
   print_r($row);  
   echo "</pre>";  
 }  
References for ways we can fetch row:
 /**  
  * (PHP 5)<br/>  
  * Fetch a result row as an associative, a numeric array, or both  
  * @link http://php.net/manual/en/mysqli-result.fetch-array.php  
  * @param mysqli_result $result  
  * @param int $resulttype [optional] <p>  
  * This optional parameter is a constant indicating what type of array  
  * should be produced from the current row data. The possible values for  
  * this parameter are the constants <b>MYSQLI_ASSOC</b>,  
  * <b>MYSQLI_NUM</b>, or <b>MYSQLI_BOTH</b>.  
  * </p>  
  * <p>  
  * By using the <b>MYSQLI_ASSOC</b> constant this function  
  * will behave identically to the <b>mysqli_fetch_assoc</b>,  
  * while <b>MYSQLI_NUM</b> will behave identically to the  
  * <b>mysqli_fetch_row</b> function. The final option  
  * <b>MYSQLI_BOTH</b> will create a single array with the  
  * attributes of both.  
  * </p>  
  * @return mixed an array of strings that corresponds to the fetched row or <b>NULL</b> if there  
  * are no more rows in resultset.  
  */  
 function mysqli_fetch_array (mysqli_result $result, $resulttype = 'MYSQLI_BOTH') {}
/**
 * (PHP 5)<br/>
 * Get a result row as an enumerated array
 * @link http://php.net/manual/en/mysqli-result.fetch-row.php
 * @param mysqli_result $result
 * @return mixed <b>mysqli_fetch_row</b> returns an array of strings that corresponds to the fetched row
 * or <b>NULL</b> if there are no more rows in result set.
 */
function mysqli_fetch_row (mysqli_result $result) {}
/**
 * (PHP 5)<br/>
 * Fetch a result row as an associative array
 * @link http://php.net/manual/en/mysqli-result.fetch-assoc.php
 * @param mysqli_result $result
 * @return array an associative array of strings representing the fetched row in the result
 * set, where each key in the array represents the name of one of the result
 * set's columns or <b>NULL</b> if there are no more rows in resultset.
 * </p>
 * <p>
 * If two or more columns of the result have the same field names, the last
 * column will take precedence. To access the other column(s) of the same
 * name, you either need to access the result with numeric indices by using
 * <b>mysqli_fetch_row</b> or add alias names.
 */
function mysqli_fetch_assoc (mysqli_result $result) {}
/**
 * (PHP 5)<br/>
 * Returns the current row of a result set as an object
 * @link http://php.net/manual/en/mysqli-result.fetch-object.php
 * @param mysqli_result $result
 * @param string $class_name [optional] <p>
 * The name of the class to instantiate, set the properties of and return.
 * If not specified, a <b>stdClass</b> object is returned.
 * </p>
 * @param array $params [optional] <p>
 * An optional array of parameters to pass to the constructor
 * for <i>class_name</i> objects.
 * </p>
 * @return object an object with string properties that corresponds to the fetched
 * row or <b>NULL</b> if there are no more rows in resultset.
 */
function mysqli_fetch_object (mysqli_result $result, $class_name = null, array $params = null) {}

PHP-Reference Variable

Reference variable are those that have a reference to the value stored in them for example

 $name = 'fruit'; //Generic Varible  
 $$name='banana'; //Reference Variable  
 echo $fruit;   
 //Outputs Banana  


Here $name is a variable which stores name 'fruit' and in turn there is a memory location in your system when you run this program which is labelled as 'fruit' in which value is stored as $$name or $fruit.

Saturday, December 7, 2013

Static function,Variable accesibility

Recently one of my co-friends regarding  a programme which made my concepts clear for a static function, variable accessibility outside a class

 <?php  
 final class Hello  
 {  
      private static $greeting='Hello';  
      private static $initialized=false;  
      private static function initialize()  
      {  
           if(self::$initialized)  
           return;  
         self::$greeting='There';  
         self::$initialized=true;  
      }  
     public static function greet()  
     {  
       self::initialize();  
       echo self::$greeting;  
     }  
     public function hello1()  
     {  
       return 'hi';  
     }  
 }  
 echo Hello::hello1();  
 $obj=new Hello();  
 echo "==>";  
 echo $obj->greet();  
 ?>  


this outputs "hi==>There"

A static function though can be called with scope resolution operator via class name directly or from object.

A static variable can only be called from a static function or from a class name via scope resolution operator

And since we can call a static function directly we cannot use $this in the same

for example in static function greet we are calling the
echo self::$greeting;
and not
echo $this->$greeting;

Sunday, September 15, 2013

PHP-Loop Queston's

1. for($i=1;$i++;$i<100)
echo $i;

2. for($i=0;$i++;$i<100)
echo $i;

How many times will the loop execute in both the cases.

Answers:

1. Infinite why?
We know that for loop has 3 blocks 1st is assignment 2nd is condition and 3rd is increment.

Now in first block we have assignment $i=1 We are fine with it
In second block we are having $i++ which means that it will check for value of $i as condition before incrementing so $i=1 and increment $i to 2 and again in next pass we have $i=2 which is again true value>0 results in true.
and it will go on until falls short of memory.

2. 0 Why?

$i=0 initially checked that condition before increment $i=0 which returns false and as such loop halts.


OOPS-PHP-Magic Methods

1. __get($property)

Get value for a property set in a class foe example

 function __get($property)  
 {  
 return $this->properties[$property];  
 }  


Usage: echo $st->name;

2. __set($property,$value) Set value for a property
 function __set($property, $value)  
 {  
 $this->properties[$property]="AutoSet {$property} as: ".$value;  
 }  


Usage: $st->roll=16;

3. __call()
overloads any undefined function in a class.Thus we can also call an undefined function and show custom error message.

 function __call($method, $arguments)  
 {  
 echo "You called a method named {$method} with the following  
 arguments <br/>";  
 print_r($arguments);  
 echo "<br/>";  
 }  

Usage: $ol->notAnyMethod("boo");

OOPS-Static keyword,Singleton Design Pattern and its implementation

Static keyword is useful in creating Singleton design pattern because in such a scenario changes made by 1 object to a variable is reflected in all the objects of that class in that request.

Here is my example code with Singleton Design Pattern.

What I was trying to do is I was trying a singleton object over different request's and was trying to see whether it maintains its state or not. And it doesn't I tried running this page from different browser's and I failed to retrieve data of previous request's or session's.

Singleton Pattern is just needed so that only one object access at a time a resource to avoid conflict's

Singleton's are used to write log's and database access,maintain configuration variable's.

And that is when I realized the importance of an Application Server over a Web Server where we can create application object's.

 <?php  
 session_start();  
 //Singleton class example  
 error_reporting(E_ALL);  
 final class UserInfo  
 {  
   static $user=null;  
   static $instance=NULL;  
   public static function Instance()  
   {  
     if (self::$instance === null) {  
       self::$instance = new UserInfo();  
     }  
     return self::$instance;  
   }  
   /*  
    * Shows the array  
    */  
   public static function showUser()  
   {  
     if(self::$user!=null)  
     {  
       foreach(self::$user as $key=>$value)  
       {  
         echo "<br/>Sessionid ".$key." is assigned to ".$value."<br/>";  
       }  
     }  
   }  
   /*  
    * Adds session Id and user to the array  
    */  
   public static function AddUser()  
   {  
     echo "<br/>";  
     echo "Object count is ==>";  
     echo $ucount=count(self::$user);  
     echo "<br/>";  
     if(self::$user===null)  
     {  
       self::$user=array();  
       self::$user[session_id()]="User ".($ucount+1);  
       //print_r(self::$user);  
     }  
     else   
     {  
       if(!(array_key_exists(session_id(),self::$user)))  
       {  
         self::$user[session_id()]="User ".$ucount+1;  
       }  
     }  
   }  
   private function __construct()  
   {  
   }  
 }  
 echo "My Session Id is :". session_id();  
 UserInfo::Instance()->AddUser();  
 $fact1= UserInfo::Instance();  
 $fact= UserInfo::Instance();  
 $fact1->AddUser();  
 $fact->showUser();  
 UserInfo::Instance()->showUser();  
 if($fact1===$fact)  
   echo "Matches";  
 /*  
  * ERROR LINE  
  */  
 //$fact3= new UserInfo();  
 ?>  

Output is:
 My Session Id is :p15snn5ebgn52ftsj0eb43e4n0  
 Object count is ==>0  
 Object count is ==>1  
 Sessionid p15snn5ebgn52ftsj0eb43e4n0 is assigned to User 1  
 Sessionid p15snn5ebgn52ftsj0eb43e4n0 is assigned to User 1  
 Matches  

As you can see above is mine singleton class with a private constructor.I have 2 static methods one to store data and other to show data

In first case I have added user name as value and corresponding session id as key to the array.
I have called my method in 2 way's directly via class and by an object.

In the second call count goes 1

Finally I call show user in 2 way's and the 2 object's matches as per the condition