How to filter records in postgreys table with bytea field ?

Before telling about solution please avoid storing data in postgrey bytea field if you need a filter on stored data, instead store it in jsonb data type.

Yes but we don’t have all time a luxury to change the data type if we are working on a legacy system. hence if you are in the same boat you can write the queries as mentioned below.

Take example of following json stored in bytea data type of events table and field name is event_payload.

{
  "id": 10,
  "globalID": 112,
  "time": "2020-05-28T23:30:39.265688+05:30",
  "type": "LocalIndexUpdated",
  "data": {
    "filenames": [
      "kk.txt"
    ],
    "folder": "vutuy-aeecb",
    "items": 1,
    "version": 1
  }
}

And let say want to filter out the event on the bases of event type

SELECT convert_from(event_payload, 'UTF-8')::json as event 
FROM events
WHERE convert_from(payload, 'UTF-8')::json->>'type' = 'LocalIndexUpdated'

So idea is to convert the bytea to json format and then filter out the result set on the bases of json field.

such queries can be slow because there is no indexing on filtered field and json type conversion.

Posted in Database, Postgreys | Leave a comment

Create custom session handler in php using mysql database

class mySession implements SessionHandlerInterface {

    private  $dbConnection;
    private  $sessionLifeTime;

    function  __construct(){

        //set session handler
        session_set_save_handler(array(&$this,"open"),
            array(&$this,"close"),
            array(&$this,"read"),
            array(&$this,"write"),
            array(&$this,"destroy"),
            array(&$this,"gc"));
    }

    //function to create session
    function open($savePath,$sessionName){

        //get the db connection
        $this->dbConnection = new PDO('mysql:dbname=db_based_session;host:localhost', 'XXX', 'XXX');

//set the default session expiration time
$this->sessionLifeTime = get_cfg_var('session.gc_maxlifetime');

if ($this->dbConnection)
return true;
else
return false;
//if it was a file based then we have to create file for all session and have to store in specified path

}

function close()
{

//expire time for this session
$this->gc(get_cfg_var('session.gc_maxlifetime'));

//destroy db connection
$this->dbConnection = null;

}

function read($sessionId)
{

//read data
$query = "SELECT session_data FROM my_sessions WHERE session_id = :session_id AND session_expires > :session_expires";
$preparedQuery = $this->dbConnection->prepare($query);
$resultSet = $preparedQuery->execute(array(":session_id" => $sessionId, ":session_expires" => time()));
if ($resultSet)
return $resultSet->session_data;
else
return "";
}

function write($sessionId, $sessionData)
{

echo $sessionId;
//set expiration time
$newExpirationTime = time() + $this->sessionLifeTime;

//check if session is already there with specified id
$query = "SELECT * FROM my_sessions WHERE session_id = :session_id";
$preparedQuery = $this->dbConnection->prepare($query);
$preparedQuery->execute(array(":session_id" => $sessionId));
$output = $preparedQuery->fetch(PDO::FETCH_COLUMN, 0);

if ($output) {
$result = $output->fetch(PDO::FETCH_COLUMN, 0);
//yes there is session with specified id then increase then update the session expiration time
if ($result) {
$updateQuery = "UPDATE my_sessions SET session_expires = ?, session_data = ? WHERE session_id = ?";
$preparedQuery = $this->dbConnection->prepare($updateQuery);
$preparedQuery->execute(array($newExpirationTime, $sessionData, $sessionId));
if ($updateQuery)
return true;
else
return false;
}

}

//new session
$insertQuery = " INSERT INTO my_sessions (session_id,session_expires,session_data) VALUES(:session_id,:session_expires,:session_data)";
$preparedQuery = $this->dbConnection->prepare($insertQuery);

$result = $preparedQuery->execute(array(
":session_id" => $sessionId,
":session_expires" => $newExpirationTime,
":session_data" => $sessionData));

if ($result)
return true;

//at the end if there is any issue
return false;

}

//session destroy function

function  destroy($sessionId)
{
$deleteQuery = "DELETE FROM my_sessions WHERE session_id =?";
$deleteQueryResult = $this->dbConnection->prepare($deleteQuery);
$deleteQueryResult->execute(array($sessionId));
if ($deleteQueryResult)
return true;
else
return false;
}

function gc($sessMaxLifeTime)
{

$deleteQuery = "DELETE FROM my_sessions WHERE session_expires dbConnection->prepare($deleteQuery);
$result = $preparedQuery->execute(array(time()));
if ($result)
return true;
else
return false;
}

}

$session = new mySession();
session_start();
echo session_id();
$_SESSION['abc'] = "whats up";
$_SESSION['kk'] = "hello";

echo $_SESSION['kk'];

//session_destroy();
Posted in Architecture, Framework, PHP, Programming, Uncategorized | Tagged , , , | Leave a comment

Find second highest number in an integer Array

package dsProblem;

/**
* Created by gyaneshwar on 26/11/2016.
*/
public class SecondLargestNumber {

int[] a;

public int[] getA() {
return a;
}

public void setA(int[] a) {
this.a = a;
}

public int findSecondLargestNumber() {
int largestEle = 0;
int secondLargestEle = 0;

for (int aa : a) {
if (largestEle < aa) {
secondLargestEle = largestEle;
largestEle = aa;
} else if (secondLargestEle < aa) {
secondLargestEle = aa;
}

}
return secondLargestEle;
}

public static void main(String[] args) {

int[] a = new int[20];
a[0] = 3;
a[1] = 2;
a[2] = 5;
a[3] = 8;
a[4] = 10;
a[5] = 7;
a[6] = 1;
SecondLargestNumber secondLargestNumber = new SecondLargestNumber();
secondLargestNumber.setA(a);
int sl = secondLargestNumber.findSecondLargestNumber();
System.out.println(sl);
}

}
Posted in Algorithm, Data Structure, java, Programming, Uncategorized | Tagged | Leave a comment

Given a dictionary and a list of letters find all valid words that can be built with the letters

package dsProblem;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by gyaneshwar on 26/11/2016.
 */
public class DictionaryWithChar {
    List<String> dictionary;
    char[] characters;
    Map<Character, Integer> alphabet;

    public DictionaryWithChar(List<String> dictionary, char[] ch) {
        this.dictionary = dictionary;
        this.characters = ch;
        this.alphabet = new HashMap<Character, Integer>();
        getAlphabetHashMap();
    }

    public List<String> findString() {
        List<String> output = new ArrayList<String>();
        //loop to iterate the dictionary
        for (String s : dictionary) {
            Map<Character, Integer> characterIntegerMap = this.alphabet;
            int k = 0;
            while (k < s.length()) {
                char c = s.charAt(k);
                if (characterIntegerMap.get(c) > 0) {
                    Integer integer = characterIntegerMap.get(c);
                    characterIntegerMap.put(c, --integer);
                } else {
                    break;
                }
                output.add(s);
            }
        }
        return output;
    }

    private void getAlphabetHashMap() {
        for (int i = 0; i < 26; i++) {
            char i1 = (char) (97 + (i));
            this.alphabet.put(i1, 0);
            char i2 = (char) (65 + (i));
            this.alphabet.put(i2, 0);
        }
        //set the count for alphabet
        for (int j = 0; j < characters.length; j++) {
            Integer integer = this.alphabet.get(characters[j]);
            this.alphabet.put(characters[j], ++integer);
        }
    }

    public List<String> getDictionary() {
        return dictionary;
    }

    public Map<Character, Integer> getAlphabet() {
        return alphabet;
    }

    public char[] getCharacters() {
        return characters;
    }

    public static void main(String[] args) {

        char[] chars = new char[4];
        chars[0] = 't';
        chars[1] = 'a';
        chars[2] = 'b';
        chars[3] = 'c';
        List<String> dictionary = new ArrayList<String>();
        dictionary.add("Rat");
        dictionary.add("mat");
        dictionary.add("bat");
        dictionary.add("chat");
        dictionary.add("cat");
        dictionary.add("tab");
        dictionary.add("fab");
        dictionary.add("batt");
        DictionaryWithChar dictionaryWithChar = new DictionaryWithChar(dictionary, chars);
        System.out.println(dictionaryWithChar.findString().toString());
    }
}</pre>
<pre>
Posted in Algorithm, Data Structure, java, Uncategorized | Tagged , , | Leave a comment

How to write bold and italic text in whatsApp message

WhatsApp world best text messaging app I am fond of the way they maintain the simplicity of app with some of the greater features.  Recently I got some interesting update on Android app.

  1. Make text bold in the message : you just need to surround the text with star(*).                 Example : *hello world I am bold text in WhatsApp*
  2. Make text Italic in the message : you just need to surround your text with the underscores (_) Example : _hello world I am italic text in whatsapp_ . But where is the underscore in the default android keyboard ? Below screenshot will help you to find out the hidden underscore.                                                                                                                 a. open second page of keyboard by pressing bottom left ?1:)                                                  b. open  next keyboard screen by pressing  =\<

     

    3.Here is example screen for italic text

     

     

     

Posted in Uncategorized | Leave a comment

Install Laravel in Mac OS X and Linux

Laravel has awesome documentation but still I Faced problem while installation.Below are the Just three commands which can help you to run Laravel in your mac book or Linux systems like ubuntu and any other distribution.


$ cd ~
$ curl -sS https://getcomposer.org/installer | php
$ ./composer.phar global require "laravel/installer=~1.1"
$ ./composer.phar create-project laravel/laravel --prefer-dist projectDirectoryName

A Developer
Gy@n

Posted in Framework, Laravel, PHP, Uncategorized | Tagged , , | Leave a comment

Implementation of Golang routines

Now the development of software is an easy task but scaling things for millions of users and performing things in the millisecond are the most challenging and interesting task.

Parallel processing is the first thing comes in mind when we think about scaling and performance. Java is the best in terms of concurrency and threading, but java threading is heavy and needs lots of attention during implementation.

Golang routines are very light weight and easy to implement if you want to do things concurrently like multiple APIS calls.

Here is example of multiple APIs calls with Golang (I wrote this application to fetch Flickr images. you can check multiple things over here like how to store details in mongo using Golang etc.)

package main

import (
	"encoding/json"
	"fmt"
	"io/ioutil"
	"net/http"
	"strconv"
	"sync"
	"time"

	"gopkg.in/mgo.v2"
)

//some global const

const perPagePhoto int = 50
const flickerApiUrl string = "https://api.flickr.com/services/rest/?method=flickr.photos.getRecent&api_key=00b8e8a000238defd8704f7c6bdbe130&format=json&nojsoncallback=1&text=puppies"

//struct for api response
type payload struct {
	Photos photos `json:photos`
	Stat   string `json:state`
}

//struct for photos listing
type photos struct {
	Page    int     `json:page`
	Pages   int     `json:pages`
	Perpage int     `json:perpage`
	Total   int     `json:total`
	Photo   []photo `json:photo`
}

//struct for individual photo
type photo struct {
	Id             string `json: id`
	Owner          string `json:owner`
	Secret         string `json:secret`
	Server         string `json:server`
	Farm           int    `json:farm`
	Title          string `json:title`
	Ispublic       int    `json:ispublic`
	Isfriend       int    `json:isfriend`
	Isfmaily       int    `json:isfmaily`
	Url            string `json:url`
	ThumbUrl       string `json:thumbUrl`
	UpVotesCount   int    `json:upVotesCount`
	DownVotesCount int    `json:downVotesCount`
}

// this will return photos list per page
func getFlickrPhotos(pageNumber int) {

	// fmt.Println(pageNumber)

	url := flickerApiUrl + "&page=" + strconv.Itoa(pageNumber) + "&per_page=" + strconv.Itoa(perPagePhoto)

	// fmt.Println(url)
	res, err := http.Get(url)

	if err != nil {
		panic(err)
	}
	defer res.Body.Close()

	body, err := ioutil.ReadAll(res.Body)

	if err != nil {
		panic(err)
	}

	// fmt.Println(body)

	var p payload

	err = json.Unmarshal([]byte(body), &p)

	if err != nil {
		panic(err)
	}
	addPhotosToDb(p.Photos.Photo)
}

//to store photos details in mongoDB
func addPhotosToDb(Photos []photo) {

	session, err := mgo.Dial("localhost")

	if err != nil {
		panic(err)
	}
	defer session.Close()

	uc := session.DB("explorePhotos").C("photos")

	for _, photo := range Photos {

		photo.Url = "https://farm" + strconv.Itoa(photo.Farm) + ".staticflickr.com/" + photo.Server + "/" + photo.Id + "_" + photo.Secret + "_b.jpg"
		photo.ThumbUrl = "https://farm" + strconv.Itoa(photo.Farm) + ".staticflickr.com/" + photo.Server + "/" + photo.Id + "_" + photo.Secret + "_n.jpg"
		photo.UpVotesCount = 0
		photo.DownVotesCount = 0

		err = uc.Insert(photo)
		if err != nil {
			panic(err)
		}
		// fmt.Println(photo)
	}

}

func main() {

	url := flickerApiUrl + "&page=1&per_page=" + strconv.Itoa(perPagePhoto)

	res, err := http.Get(url)

	if err != nil {
		panic(err)
	}
	defer res.Body.Close()

	body, err := ioutil.ReadAll(res.Body)

	if err != nil {
		panic(err)
	}

	// fmt.Println(body)

	var p payload

	err = json.Unmarshal([]byte(body), &p)

	if err != nil {
		panic(err)
	}
	// add first page photos to db
	addPhotosToDb(p.Photos.Photo)

	totalPages := p.Photos.Pages
	//first page photos we already got lets call go routins for other pages

	fmt.Println(totalPages)

        //bench marking lets see how much time its take 
	t1 := time.Now()

	//  with go routines
	var wg sync.WaitGroup
	
	for i := 2; i <= totalPages; i++ { //execute this for all pages
		println(i, "page number")
		wg.Add(1)
		go func(page int) {
			println(page)
			defer wg.Done()
			getFlickrPhotos(page) //these functions will execute concurrently 
		}(i)
	}
	wg.Wait()

	/*
		//without go routines to check how much time it takes 
		for i := 2; i <= totalPages; i++ { //execute this for all pages
			getFlickrPhotos(i)
		}
	*/
	t2 := time.Now()
	fmt.Println("time taken: ", t2.Sub(t1))
}

A Developer
Gy@n

Posted in golang, parallel programming, Programming, Uncategorized | Tagged , , | Leave a comment

Solo trip is not a fun. It’s just a time when you explore yourself and world together.

Heard a lot about solo trip so thought to let’s experience it. After resigning from one job, I want to take a break. Time after resignation is the best to do such things no deadlines, no coding, no programming, no urgent calls, no job just me with myself.

IMG_20150822_185245

I booked bus ticket for Gokarna and just moved on for three days holiday without knowing how’s the weather, whether it’s good time to go or not, I love travelling like this. I just wanted to talk to myself for sometime. (when I talk like this, people always tell me, are you drunk or mad? But who bother). I just wanted to experience sound of sea, ocean waves touching to my feet while sitting alone and I found Gokarna is the best place. I stayed in a wooden cottage, which is very far from main city and very near to beach even I can see sea from window.

I have travelled a lot, places like coorg, wayanad, ooty, mysore, chennai, chikmagalur, but in a group of good friends. I realize so many new things and thought to share with people and this blog post came in my mind.

1. Solo trip is not a fun. It’s just a time when you explore yourself and world together.
2. You will realize how important friends to enjoy life.
3. Sitting alone means you will start remembering your past, that’s not good, but flash back will start automatically, like a movie.
4. You will start realizing how far you came from your Home.
5. Might be you won’t speak single word for a long duration (more than 24 hours).
6. Might be you aren’t going to sleep whole night because of new place and other obstacle. In my case I was in wooden cottage and it was raining heavily whole night and sea’s waves were sounding like anything.
7. If you are trying to know what you love, solo trip is best for it.
8. There will be flood of so many new ideas in your mind about what to do in the future? How to improve yourself? How can you improve life of human beings? Blah blah….
9. Might be you will meet so many people for first and last time. I met couple from France, they discussed a lot about India. They were asking me about guest house, I told them to stay in resort or hotel, but don’t know why they were insisting to know more about guest house and wasn’t comfort with hotels and resorts.
10. Some people will laugh on you whenever you will tell about your solo trip, But as I told who cares.

So plan your solo trip, have fun, see the world while travelling alone it looks more beautiful. Might be your solo trip tells you your sole purpose in the world.

Happy Journey!
Gy@n!

Posted in experience, travel | Tagged , , | Leave a comment

Print all nodes of binary tree at distance k from a given node

#include<iostream>
using namespace std;

class Node
{
public:

	Node *leftChild;
	Node *rightChild;
	Node *parent;
	int value;
	int visited;

	Node(int val) {
		this->value = val;
		this->leftChild = NULL;
		this->rightChild = NULL;
		this->parent = NULL;
		this->visited=0;
	}
	~Node();

};

void printKthDistanceNode(Node *root, int k) {

    //lets mark root at visited
    root->visited=1;

	if (root == NULL && k > 0) {  //for leaf node
          //don't do anything
	}
	else if (root != NULL && k == 0) {  //got the element
		cout << root->value <<"-->";
	} 

	else { //intermediat node still need to find the elements
		if (root->leftChild && root->leftChild->visited==0){
			printKthDistanceNode(root->leftChild, k - 1);
		}

		if (root->rightChild && root->rightChild->visited==0){
			printKthDistanceNode(root->rightChild, k - 1);
		}

		if (root->parent && root->parent->visited==0){
			printKthDistanceNode(root->parent, k - 1);
		}
	}
}


int main() {

    //form a binary tree

	Node *newNode = new Node(4);

	newNode->leftChild = new Node(5);
	newNode->leftChild->parent = newNode;

	newNode->rightChild = new Node(6);
	newNode->rightChild->parent = newNode;

	newNode->leftChild->leftChild = new Node(8);
	newNode->leftChild->leftChild->parent = newNode->leftChild;

	newNode->leftChild->rightChild = new Node(9);
	newNode->leftChild->rightChild->parent = newNode->leftChild;

	newNode->rightChild->leftChild = new Node(18);
	newNode->rightChild->leftChild->parent = newNode->rightChild;

	newNode->rightChild->rightChild = new Node(19);
	newNode->rightChild->rightChild->parent = newNode->rightChild;

	// cout<<newNode->rightChild->parent->value;
	printKthDistanceNode(newNode->rightChild->rightChild, 2);
	return 0;
}

OutPut: 18–>4–>

A Developer
Gy@n!

Posted in Algorithm, c++, interview Question, Programming | Tagged | Leave a comment

Implementation of Finite State Machine

<?php

//state base class
abstract class States {
	public $stateName;

	function __construct($state) {
		$this->stateName = $state;
	}
	abstract function execute();
}

//transition class
class Transitions {
	public $transitionName;
	public $toState;

	function __construct($transition, $toState) {
		$this->transitionName = $transition;
		$this->toState = $toState;
	}

	function execute() {
		echo "Executing Transition " . $this->transitionName . "\n";
	}
}

/**
 * implementation of fsm
 */
class SimplestFSM {
	public $states;
	public $transitions;
	private $currentState;
	private $currentTransition;

	function __construct() {
		$this->states = array();
		$this->transitions = array();
		$this->currentState = NULL;
		$this->currentTransition = NULL;
	}

	function setState($state) {

		if (isset($this->states[$state])) {
			$this->currentState = $this->states[$state];
		}

	}

	function setTransition($transition) {

		if (isset($this->transitions[$transition])) {
			$this->currentTransition = $this->transitions[$transition];
		}

	}

	function getState() {
		return $this->currentState;
	}

	function getTransition() {
		return $this->currentTransition;
	}

	function execute() {
		if ($this->currentTransition) {
			//execute the transition function
			$this->currentTransition->execute();
			//set the current state
			$this->setState($this->currentTransition->toState);
			//make transition null
			$this->setTransition(NULL);
			//and execute the new state
			$this->currentState->execute();
		}

	}
}

//class for switch on
class On extends States {
	function execute() {
		echo "State: " . $this->stateName . " and machine switched on \n";
	}
}

//class for switch off
class Off extends States {
	function execute() {
		echo "State:" . $this->stateName . " and machine switched off \n";
	}
}

//lets see fsm in action
$fsm = new SimplestFSM();

//set states for fsm
$fsm->states["On"] = new On("On");
$fsm->states["Off"] = new Off("Off");

//set transitions
$fsm->transitions["onToOff"] = new Transitions("onToOff", "Off");
$fsm->transitions["offToOn"] = new Transitions("offToOn", "On");

//set initial values
$fsm->setState("On");
$fsm->setTransition(NULL);

$i = 0;
while ($i < 10) {
	//to show case the transitions
	$randomNumber = rand(0, 1);

	//if number is 1 then only change the state of machine
	if ($randomNumber) {

		//current state is on
		if ($fsm->getState()->stateName == "On") {
			$fsm->setTransition("onToOff");
		} else {
			//current state is off
			$fsm->setTransition("offToOn");
		}
	}
	$fsm->execute(); //alwasy execute machine function
	$i++;
}
?>
Posted in Data Structure, interview Question, PHP, Programming | Tagged , , | 1 Comment

Multiple Inheritance (Horizontal) in php

<?php
/**
* Created by gyaneshwar
* Date: 6/4/15
* Time: 10:11 PM
* multiple Inheritance  is not possible in php but we can implement using
* interface but still interface is build only for
* blue print we can't create concrete methods in interface.
* php we can't extend class horizontally.trait is concept in
* php using this we can support horizontally inheritance like multiple inheritance
*/
trait hello {
function hello(){    echo "say hello to trait a \n"; }
}
trait bye{
function bye(){ echo "say bye to train b \n"; }
}
trait whatsup{     function whatsup(){} }
class ItsMyClass{     use hello, bye,whatsup;
function whatsup(){
echo "whats up dude i am overriding trait function any problem  \n";
}
}
$myClass = new ItsMyClass(); echo $myClass->hello();
 echo $myClass->bye();
 echo $myClass->whatsup();

A Developer
Gy@n!

Posted in PHP, Programming | Tagged | Leave a comment

Implementation of array iterator in php


<?php
/**
 * Created by gyaneshwar
 * Date: 28/3/15
 * Time: 4:44 PM
 * To change this template use File | Settings | File Templates.
 */

class MyArrayIterator implements  Iterator {

    private $Arr;

    /**
     * (PHP 5 &gt;= 5.0.0)
* Return the current element
     * @link http://php.net/manual/en/iterator.current.php
     * @return mixed Can return any type.
     */

    public function __construct($array){
        $this->Arr=$array;
    }

    public function current()
    {
        return current($this->Arr);
    }

    /**
     * (PHP 5 &gt;= 5.0.0)
* Move forward to next element
     * @link http://php.net/manual/en/iterator.next.php
     * @return void Any returned value is ignored.
     */
    public function next()
    {
        next($this->Arr);
    }

    /**
     * (PHP 5 &gt;= 5.0.0)
* Return the key of the current element
     * @link http://php.net/manual/en/iterator.key.php
     * @return mixed scalar on success, or null on failure.
     */
    public function key()
    {
        return key($this->Arr);
    }

    /**
     * (PHP 5 &gt;= 5.0.0)
* Checks if current position is valid
     * @link http://php.net/manual/en/iterator.valid.php
     * @return boolean The return value will be casted to boolean and then evaluated.
     * Returns true on success or false on failure.
     */
    public function valid()
    {
        return $this->key() !== null;
    }

    /**
     * (PHP 5 &gt;= 5.0.0)
* Rewind the Iterator to the first element
     * @link http://php.net/manual/en/iterator.rewind.php
     * @return void Any returned value is ignored.
     */
    public function rewind()
    {
        return reset($this->Arr);
    }
}

//lets play with iterator

$myArray= array();

for($i=0;$i<=23;$i++)
    $myArray[]=$i+2;

//display values using iterator
$ArrayIterator = new MyArrayIterator($myArray);
while($ArrayIterator->valid()){
    echo $ArrayIterator->key().":".$ArrayIterator->current()."\n";
     $ArrayIterator->next();
}

A Developer
Gy@n!

Posted in PHP, Programming | Tagged | Leave a comment

Singleton design pattern in php

<?php
/**
 * Created by gyaneshwar
 * Date: 28/3/15
 * Time: 5:22 PM
 */

class SingletonDesignPattern {

    //just for demo there will be only one instance
    private static $instanceCount =0;

    //create the private instance variable
    private static $myInstance=null;

    //make constructor private so no one create object using new Keyword
    private function  __construct(){}

    //no one clone the object
    private function  __clone(){}

    //avoid serialazation
    public function __wakeup(){}

    //ony one way to create  object
    public static  function  getInstance(){

        if(self::$myInstance==null){
            self::$myInstance=new SingletonDesignPattern();
            self::$instanceCount++;
        }
        return self::$myInstance;
    }

    public static function getInstanceCount(){
        return self::$instanceCount;
    }

}

//now lets play with singleton design pattern

$instance = SingletonDesignPattern::getInstance();
$instance = SingletonDesignPattern::getInstance();
$instance = SingletonDesignPattern::getInstance();
$instance = SingletonDesignPattern::getInstance();

echo "number of instances: ".SingletonDesignPattern::getInstanceCount();

A Developer
Gy@n!

Posted in design patterns, PHP, Programming | Tagged | Leave a comment

My Phone screen with google awesome :)

Screenshot_2014-10-09-11-53-51-ANIMATION

Posted in Uncategorized | Leave a comment

Cloning the Javascript object

Javascript keep the same reference for original and cloned objects, so when you change anything in original object it will change in cloned object also and vice versa. So we can’t simply copy one object to another. Below i have copied each property of original object to cloned using recursive approach.

/**
 * Created by gyaneshwar
 * Date: 29/3/15
 * Time: 11:38 AM
 * To change this template use File | Settings | File Templates.
 */

var jsonObj = {
    "name":"gyani",
    "address":"Bangalore India",
    "occupation":"Software Engineer",
    "url":"gyaneshwarpardhi.wordpress.com",
    "friends":[
        {
            "name":"gyani",
            "address":"bangalore",
            "occupation":"Software Engineer",
            "url":"gyaneshwarpardhi.wordpress.com"

        },

        {
            "name":"gyani",
            "address":"Bangalore India",
            "occupation":"Software Engineer",
            "url":"gyaneshwarpardhi.wordpress.com"

        }
    ],
   "contacts":{
      'email':"gyaan1334@gmail.com",
       "skype":"gyaan1334"

   }
}

var jsonObj2={};

copyFromOneJsonToAnotherJson(jsonObj,jsonObj2);

jsonObj.name="hello changed name";

console.log(jsonObj);

//dude this is not assigned by reference  so jsonObj2 will be as it is
console.log(jsonObj2);

//function to copy one json object to anther
function copyFromOneJsonToAnotherJson(fromJson,toJson){

    for(var key in fromJson){

        if(fromJson.hasOwnProperty(key)){

            if(Array.isArray(fromJson[key])){

                if(fromJson[key] instanceof Array){
                    toJson[key]=[];
                }
                else{
                    toJson[key]={};
                }

                toJson[key]=copyFromOneJsonToAnotherJson(fromJson[key],toJson[key]);

            }
            else{
                toJson[key]=fromJson[key];
            }
        }
    }

    return toJson;
}

A Developer
Gy@n!

Posted in interview Question, javascript, Programming | Tagged , | Leave a comment

Program to display bottom view of binary tree

#include<iostream>
#include<climits>
#include<queue>
#include<map>
using namespace std;
class Node {

public:

	int horizontalHeight;
	int data;
	Node * leftChild;
	Node * rightChild;
	Node(int value) {
		this->data = value;
		this->leftChild = NULL;
		this->rightChild = NULL;
		this->horizontalHeight=INT_MAX;
	}

};

class MyTree {

private:Node * root;

public:

	MyTree(Node * myNode) {
		this->root = myNode;
		this->root->horizontalHeight=0;
	}

    void printBottomViewOfBinaryTree(){

         map<int, int>myTrackMap;
         queue<Node*>Q1,Q2;
         Q1.push(this->root);
         myTrackMap[this->root->horizontalHeight]=this->root->data;

         while(!Q1.empty()){

        	 Node *temp = Q1.front();
        	 Q1.pop();
        	 if(temp->leftChild){
        		 myTrackMap[temp->horizontalHeight-1]=temp->leftChild->data;
                 temp->leftChild->horizontalHeight=temp->horizontalHeight-1;
        		 Q2.push(temp->leftChild);
        	 }

        	 if(temp->rightChild){
        		 myTrackMap[temp->horizontalHeight+1]=temp->rightChild->data;
        		 temp->rightChild->horizontalHeight=temp->horizontalHeight+1;
        		 Q2.push(temp->rightChild);
        	 }

        	 if(Q1.empty())
        		 swap(Q1,Q2);

         }

         //print the map elements
         //iterator of a map
         map<int, int>::iterator dis;

         	//display all elements
         	for (dis = myTrackMap.begin(); dis != myTrackMap.end(); dis++) {
         		cout << dis->first<<"-->"<<dis->second<<"\n";
         	}

    }

};

int main(){

    Node * rootNode = new Node(3);
    rootNode->leftChild=new Node(4);
    rootNode->rightChild=new Node(5);

    rootNode->leftChild->leftChild=new Node(6);
    rootNode->leftChild->rightChild=new Node(7);

    rootNode->rightChild->leftChild=new Node(8);
    rootNode->rightChild->rightChild=new Node(9);

    MyTree * t = new MyTree(rootNode);
    t->printBottomViewOfBinaryTree();

	return 0;
}

A Developer
Gy@n!

Posted in Algorithm, c++, Data Structure, interview Question | Tagged , | Leave a comment

google calc

I really really big fan of google innovations and creativity . google google calc and here is your  calculator . really its awesome.

image

Gy@n!
A Developer

Posted in tricks | Tagged | Leave a comment

Upload images through REST API

I was writing write apis for android and i-phone app and found some interesting things.

How to upload a file in REST API ?? there are two ways to upload file in rest api.

1. Using usual methods content-type multipart/form-data with POST HTTP method. This is working fine for simple curl api call or other web application but found not suitable for android and iphone app REST API.

2. Converting image in base64 string format and do api call. This is very easy for android and iphone developer to convert a image in base64 format and send through api.

Here is simple implementation.

/**
     * convert base64 encoded image to image
     * @param  $base64String,$writeFolder,$outputFile
     * @return name of new image
     */

  function base64StringToImage($base64String, $writeFolder, $outputFile)
    {
        //open  file
        $file = fopen($writeFolder . "/" . $outputFile, "wb");

        //problem with open a file
        if (!$file)
            throw new \Exception('can able to open file');

        //write file from base64 string
        $writeStatus = fwrite($file, base64_decode($base64String));

        //problem with write
        if (!$writeStatus)
            throw new \Exception('file is not writable');

        //close the file
        fclose($file);

        //return file name
        return ($outputFile);
    }

$base64ImageString="your image base64 encoding string";
$targetPath=="folder name where you want to create file";
$outputFile="new file name";</p>
$fileName = base64StringToImage($base64ImageString, $targetPath, $outputFile);

//display the new created file name
echo $fileName;


check in gist

A developer
Gy@N!

Posted in PHP, REST | Tagged , , | Leave a comment

Why I chooses Zend apigility over frapi and other REST API framework

I was doing research to build a awesome and well structured REST API for a huge very huge DATABASE base web application.

I worked with frapi for REST API and have looked other framework, then I decided to choose Zend apigilty for My REST API application.

Here some of the points which i noted down while choosing zend apigility as a REST API framwork.

1.whenever I start working on any open source project first i look at how active that project and people behind the project. frapi don’t have update for long time all most 1 year before commit in git repository while Zend apigility have lots of work going on check in git.

2.How active community behind open source i found awesome and well active google group for Zend apigility. whenever i post a question i got frequent response and i solved my issue with in very short time.

3.Zend apigility provide awesome admin kind of interface where you can create easily REST API without bother about project structure it will automatically create files and folder for you only you need to put final touch to each entity, resource and collection classes.

4.Zend apigility have API version system which helps you to create REST API in different version and all works well together.

5.Zend apigility divide API in two categories a) REST Service b)RPC(Remote procedure call) which give fair idea about when should we use REST Service and when should we use RPC.

6.Zend apigility REST service divided in two parts a)Entity b) Collections
Entity corporate with individual object while collection mainly used for listing, pagination of objects and interlinking between objects.

7.Zend apigility have all kind of authentication system HTTP Basic Authentication, HTTP Digest Authentication, OAuth2 Authentication.

8.Zend apigility have all feature of Zend Frame work which makes easy to validate things and other stuff.

9.Zend apigility have nice documentation which is very useful while development.

10.Zend apigility works on two modes development and deployment mode which makes development and deployment easy.

There are other features also available in Zend apigility above mention are main.
And at the end I decided to go with Zend Apigility.

Zend apigility still in early stage but this works great for my project.

Gy@n!
A Developer

Posted in PHP, REST | Tagged , , | Leave a comment

Determine given binary search tree is avl (Adelson-velskii and Landis) Tree or not

A binary search tree is called AVL tree when for any node x, the height of left subtree of x and height of right subtree of x differ by at most 1.

Here function which check whether a given BST is a AVL Tree or not

 
static int isAVL(treeNode * rootNode) {
		int left, right;
		if (!rootNode)
			return 0;
		left = isAVL(rootNode->leftChild);

		if (left == -1)
			return left;
		right = isAVL(rootNode->rightChild);

		if (right == -1)
			return right;

		if (abs(left - right) > 1)
			return -1;

		return (left > right ? left : right) + 1;

	}

A Developer
Gy@n!

Posted in Algorithm, c++, Data Structure, interview Question, Programming | Tagged , | Leave a comment