Friday, December 28, 2012

keyboard shortcut netbeans php go to symbol

ctrl alt shift O

Find command find latest files

 find . -printf '%T+ %p\n' | sort -r | head

Wednesday, December 26, 2012

Monday, December 24, 2012

Mysql Setting Indian TimeZone (Asia/Calcutta)

Problem : 
The following query : 
select count(1) cnt,date_format(from_unixtime(absoluteTime),'%D-%M-%Y') as date1 from a,b where = b.fid and b.col2 = 'xyz' group by date1 order by absoluteTime asc

Gave different results on my local machine as compared to the server hosted on EC2.

When I did : 
mysql> show variables like '%time_zone%

I got : 

| Variable_name    | Value         |
| system_time_zone | EST           |
| time_zone        | SYSTEM |

Which means that mysql is picking the system time zone which is EST(some US time zone).

Solution : 
1. I checked time_zone* tables in mysql db - they were empty. So I did 2.
2. mysql_tzinfo_to_sql /usr/share/zoneinfo | mysql -u root mysql (Source)
3. I edited /etc/my.cnf file and put this line there : default_time_zone=Asia/Calcutta   

now service mysqld restart

Friday, December 21, 2012

installing apc

 yum install pcre-devel
yum -y install php-devel
 pecl install apc

add to php.ini

Friday, December 14, 2012

php catching fatal errors



function handleShutdown() {
        $error = error_get_last();
        if($error !== NULL){
            $info = "[SHUTDOWN] file:".$error['file']." | ln:".$error['line']." | msg:".$error['message'] .PHP_EOL;

Monday, December 10, 2012

FD RD Computation for LIC policy

$premium = 1000;
$rate = 0.05;
$years = 20;

echo "RD = ".rd($premium,$rate,$years)."\n";
$fd1 = fd(3000,0.05,15);
$fd2 = fd(3000,0.05,10);
$fd3 = fd(3000,0.05,5);

$fd4 = 22000;
echo "FD = ".($fd1+$fd2+$fd3+$fd4)."\n";

function fd($amt,$rate,$years) {
        for($i=0; $i<$years;++$i) {
                $amt = $amt*(1+$rate);
        return $amt;

function rd($amt,$rate,$years) {

        $final = 0;
        for($i=0; $i<$years;++$i) {
                $final = ($final + $amt)*(1+$rate);
        return $final;

Friday, November 23, 2012

dropbox centos sync

Dropbox CLI for CentOS 5 the easy way

Alan Ivey's picture

Dropbox hardly needs any introduction; put files in your Dropbox and they show up everywhere else you have Dropbox installed and A feature about Dropbox that is probably not as widely known is that free accounts come with 30 days of undo history and Pro accounts can get "Pack Rat" that keeps unlimited history of changes. The history of files, including reverting deleted files, was particularly interesting to me, since I could hook in my latest daily MySQL dumps from AutoMySQLBackup to Dropbox and have 30 days of backups for free available from anywhere is accessible.

The problem is that we use CentOS for our servers and the Dropbox Linux builds are geared for distributions like Ubuntu and Debian that have updated versions of required software like Python, libc, and others, that I did not want to upgrade by hand on my systems and risk the integrity of the system packages. But, I got it to work anyway, read on for how I got Dropbox CLI installed on CentOS without replacing any system files.

  1. Download or (Ref)
  2. Extract tar.gz file downloaded and leave in ~ of desired user
  3. Run ~/.dropbox-dist/dropboxd to get Dropbox to provide a URL to go to in your browser to link this computer to your Dropbox account
    $ ./dropboxd
    This client is not linked to any account...
    Please visit https: // to link this machine.
  4. After visiting the URL in a browser to which you've logged into, you'll see the following output:
    cannot open display:
    Run 'nautilus --help' to see a full list of available command line options.
  5. If you cannot quit the app, open another a shell, get the PID by running $ ps -ef|grep dropbox, and kill PID. The output on your other shell should say:
  6. Download the official Dropbox CLI: (Ref)
  7. won't work without Python 2.6, but let's not risk messing up our official RHEL packages. Download ActivePython 2.6 (AS Package) from (Ref)
  8. As mentioned in the AP documentation (Ref), run the installer with ./ and install where desired. It defaults to /opt/ActivePython-2.6, which is fine because it does not conflcit with the system default python 2.4 install. For my purposes, I had created a user called dropbox that did not have root privileges, so I installed to /home/dropbox/ActivePython-2.6.
  9. Edit and change #!/usr/bin/python to the path you just installed AP to. For my installation, it's set to #!/home/dropbox/bin/ActivePython-2.6/bin/python
  10. Run without commands to see your available options.

Monday, November 19, 2012

Generating html drop down options with vim

:1,$ s:\(.*\):<option value="\1">\1</option>:g  

If the file contains 


This command will result in 
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>

Friday, November 16, 2012

installing pecl_http on centos

yum install php-pear
yum install gcc
yum install curl-devel
yum install php-devel
pecl channel-update
/usr/bin/pecl install pecl_http

installing apache and php on centos

yum install httpd mod_ssl
yum install php-common php-gd php-mcrypt php-pear php-pecl-memcache php-mhash php-mysql php-xml
yum install mod_php

Friday, September 28, 2012

JQuery in place editing with autocomplete (with dummy data)

Pick the corresponding libraries from here : 

Then edit the file named : jquery.editinplace.js like this ; 

(Modify) createEditorElement: function() {
if (-1 === $.inArray(this.settings.field_type, ['autocomplete','text', 'textarea', 'select']))
throw "Unknown field_type <fnord>, supported are 'text', 'autocomplete','textarea' and 'select'";
var editor = null;
if ("select" === this.settings.field_type)
editor = this.createSelectEditor();
else if ("autocomplete" === this.settings.field_type)
editor = this.createAutoCompleteEditor();
else if ("text" === this.settings.field_type)
editor = $('<input type="text" ' + this.inputNameAndClass() 
+ ' size="' + this.settings.text_size  + '" />');
else if ("textarea" === this.settings.field_type)
editor = $('<textarea ' + this.inputNameAndClass() 
+ ' rows="' + this.settings.textarea_rows + '" '
+ ' cols="' + this.settings.textarea_cols + '" />');
return editor;

(Add) createAutoCompleteEditor: function() {
var editor = $("<input "+this.inputNameAndClass()+" type=\"text\"/>");
        minChars: 1,data: [
            ['apple', 1],
            ['apricot', 2],
            ['pear', 3],
            ['prume', 4],
            ['Doyenné du Comice', 5]
return editor;

Now, modify the dummy data with real data and specify field_type as autocomplete when creating an inPlaceEdit element.

Monday, September 10, 2012

Websockets deployment on a dedicated server

I was able to test a websockets based application perfectly on my localhost but when I tried to deploy it on the production server there were problems.

Here is what I did : 

1. Edit the file : /etc/sysconfig/iptables
and add this line : 
-A RH-Firewall-1-INPUT -m state --state NEW -m tcp -p tcp --dport 8123 -j ACCEPT
assuming that you want to run your websocket server on port 8123.

2. service iptables restart

3. When you start your websocket server, start it on It will ensure that it's open to connection on all interfaces - be it LAN or external IPs.

4. To test whether it's accepting connection on the above port, do telnet IP Port. If it's successful then you can proceed with your websocket related stuff.

Wednesday, August 29, 2012

Articles with tags queries : HQL/JPQL/MySql
Java MySQL Hibernate
Lets review basic many-to-many relationship between tables and build common search queries in MySQL and Hibernate HQL. We will take this site's database schema which has article-tag many-to-many relationship as an example and will try to build search queries to find articles by specific tags.
Here is our database schema that implements many-to-many relationship using intermediate "article_tag" table:
Table Schema
Corresponding Hibernate mappings:
      <class name=ca.sergiy.model.Tag" table="tag">
          <cache usage="read-write"/>
          <id name="id" column="id" type="long">
              <generator class="native"/>
        <property name="name" column="name"/>
    <class name="ca.sergiy.model.Article" table="article">
          <cache usage="read-write" />
          <id name="id" column="id" type="long">
              <generator class="native" />
        <property name="title" column="title" />
          <set name="tags" table="article_tag" lazy="false">
              <key column="articleid" />
              <many-to-many class="ca.sergiy.model.Tag" column="tagid" />

#1. Find all articles that are tagged with any of tag1, tag2, ..., tagn

MySQL query to select all articles that have "Java" or "Hibernate" among their assigned tags:
  FROM   `article` a
         INNER JOIN article_tag at
           ON at.articleid =
         INNER JOIN tag t
           ON = at.tagid
  WHERE IN ("Java", "Hibernate")
Corresponding Hibernate HQL:
  String[] tags = {"Java", "Hibernate"};
  String hql = "select distinct a from Article a " +
                  "join a.tags t " +
                  "where in (:tags)";
  Query query = session.createQuery(hql);
  query.setParameterList("tags", tags);
  List<Article> articles = query.list();
This query will also work for a single tag (find all articles tagged with "Java")

#2. Find all articles that have no tags assigned

MySQL query:
  SELECT   a.*
  FROM     `article` a
           LEFT JOIN article_tag at
             ON at.articleid =
  HAVING   Count(at.tagid) = 0
Corresponding Hibernate HQL:
  String hql = "select a from Article a " +
                  "left join a.tags t " +
                  "group by a " +
                  "having count(t)=0";
Query query = session.createQuery(hql);
  List<Article> articles = query.list();
Note that this query uses LEFT JOIN.

#3. Find all articles that are tagged with at least tag1, tag2, ..., tagn

MySQL query to select all articles that have at least both "Java" and "Hibernate" among their assigned tags:
  SELECT a.*
  FROM   article a
       INNER JOIN (SELECT   at.articleid
                     FROM     article_tag at
                            INNER JOIN article a
                                ON = at.articleid
                              INNER JOIN tag t
                                ON = at.tagid
                     WHERE IN ("Java","Hibernate")
                     GROUP BY at.articleid
                     HAVING   Count(at.articleid) = 2) aa
           ON = aa.articleid
Hibernate HQL, looks much cleaner:
  String[] tags = {"Java", "Hibernate"};
  String hql = "select a from Article a " +
                  "join a.tags t " +
                  "where in (:tags) " +
                  "group by a " +
                  "having count(t)=:tag_count";
Query query = session.createQuery(hql);
  query.setParameterList("tags", tags);
  query.setInteger("tag_count", tags.length);
  List<Article> articles = query.list();

#4. Find all articles that are tagged with exactly tag1, tag2, ..., tagn

MySQL query to select all articles that are tagged with exactly "Java" and "Hibernate" tags (no other tags assigned):
  SELECT a.*
  FROM   article a
       INNER JOIN (SELECT   at.articleid
                     FROM     article_tag at
                   WHERE    at.articleid IN (SELECT   at2.articleid
                                               FROM     article_tag at2
                                                      INNER JOIN article a2
                                                          ON = at2.articleid
                                               GROUP BY at2.articleid
                                               HAVING   Count(at2.articleid) = 2)
                              AND at.tagid IN (SELECT id
                                               FROM   tag t
                                             WHERE IN ("Java","Hibernate"))
                     GROUP BY at.articleid
                     HAVING   Count(at.articleid) = 2) aa
           ON = aa.articleid
Hibernate HQL:
  String[] tags = {"Java", "Hibernate"};
  String hql = "select a from Article a " +
                  "join a.tags t " +
                  "where in (:tags) " +
                  "and in (" +
                      "select " +
                      "from Article a2 " +
                      "join a2.tags t2 " +
                      "group by a2 " +
                      "having count(t2)=:tag_count) " +
                  "group by a " +
                  "having count(t)=:tag_count";
Query query = session.createQuery(hql);
  query.setParameterList("tags", tags);
  query.setInteger("tag_count", tags.length);
  List<Article> articles = query.list();
Basically it is query #3 with extra condition applied: total number of tags should be n.
Aug 21, 2009

Saturday, July 21, 2012

Saturday, July 14, 2012

New features in PHP I didn't know about

Type hinting
Short array syntax
Function array dereferencing
Instance method call
objects as functions
Session Handler Interface
JSON Serializable interface

PHP Dev/Debug Tools


Benchmark your webserver with : siege
System calls made by apache(httpd) with : strace
Check inclued hierarchy
callgrind xdebug xhprof
hiphop  for static analysis

Others : 
replace time() with $_SERVER['REQUEST_TIME']
prefer require/include over require_once/include_once

Monday, July 9, 2012

accessing properties file in jsp/jstl using spring

<spring:eval var="itemsPerPage" expression="@browsePageProperties.getProperty('itemsPerPage')" scope="request"/> 

where browsePageProperties is defined in (Application Conext Xml) root-context.xml like this : 

    <util:properties id="browsePageProperties" location=""/>  

Thursday, July 5, 2012

vim for eclipse

hibernate many to many query

Thanks Dude !

1. JPA Sucks.

2. HQL works : 
Session session = (Session) entityManager.getDelegate();
Criteria criteria = session.createCriteria(Design.class);
Query query = session.createQuery("select d from Design d join d.tags t where in (:tags) group by d having count(t) =:tag_count");
   List<Design> list = query.list();

3. Hibernate without HQL doesn't work : 
/* int i=0;
   for ( String tagName : tags ) {
       String aliasName = "alias_" + i;
       criteria.createAlias("tags", aliasName, Criteria.INNER_JOIN);
       criteria.add( Restrictions.eq(aliasName+".name",tagName) );
  // List<Design> list = criteria.list();

4. PHP and MySql Rock.

Tuesday, June 19, 2012

apache access log images average object size, total requests, total B/W used

cat 19_jun | grep -iE '(.gif|.jpg|.png|.jpeg)' | awk '{SUM += $10;COUNT +=1;} END {print SUM/(1024*1024*1024);print COUNT;print SUM/COUNT;}'

Monday, May 21, 2012

clear recent project list in netbeans

get hold of user directory from Help->About (menu)
for me it's : C:\Users\admin\.netbeans\7.1.1

 Then go to : c/Users/admin/.netbeans/7.1.1/config/Preferences/org/netbeans/modules

edit file :

remove all lines starting with 'recent'

Thursday, May 10, 2012

NetBeans jvi :w problem (colon w)

Tools -> Options -> jVi Config -> Platform

uncheck : ":" Command completion Auto Popup

Tuesday, May 8, 2012

Vim : replacing text with matched text

For e.g. If my input is : 

and I want to make it : 

then : 
:1,$ s/$this->Lang(\(.*\))/\1/

\1 denotes the text matched between first \( \)

Thursday, May 3, 2012

C program for printing all permutations

#include <stdio.h>
void swap(int* a,int i,int j) {
        int tmp = a[i];
        a[i] = a[j];
        a[j] = tmp;

void print_array(int* a,int n) {
        int i;
        for(i = 0; i<= n; ++i) {
                printf("%d ",a[i]);

void permute(int* a, int i, int n) {
        int j;
        if(i == n) print_array(a,n);
        else {
                for(j = i;j <= n; j++) {

void main() {
        int a[4] = {1,2,3,4};

Wednesday, May 2, 2012

rough sketch for generating all permutations

permute(arrayCollection) {

if has only 2 :

for ( ith elem in collection) {
 otherThanIth = elems other than ith;
 otherThanIthPermed = permute(otherThanIth);
 prepend(ith, otherThanIthPermed);


Printing a BST in level order


while(queue.hasElems() && currNode = queue.popFront()) {\
if(currNode != stopper) {
   print currNode;
   queue.addAtEnd(left) if left not null;
   queue.addAtEnd(right) if right not null;
} else {
  print new line;
  if queue.hasElems()

other solutions from leetcode :

With two queues :

void printLevelOrder(BinaryTree *root) {
  if (!root) return;
  queue<BinaryTree*> currentLevel, nextLevel;
  while (!currentLevel.empty()) {
    BinaryTree *currNode = currentLevel.front();
    if (currNode) {
      cout << currNode->data << " ";
    if (currentLevel.empty()) {
      cout << endl;
      swap(currentLevel, nextLevel);

With one queue but counters :
void printLevelOrder(BinaryTree *root) {
 if (!root) return;
 queue<BinaryTree*> nodesQueue;
 int nodesInCurrentLevel = 1;
 int nodesInNextLevel = 0;
 while (!nodesQueue.empty()) {
   BinaryTree *currNode = nodesQueue.front();
   if (currNode) {
     cout << currNode->data << " ";
     nodesInNextLevel += 2;
   if (nodesInCurrentLevel == 0) {
     cout << endl;
     nodesInCurrentLevel = nodesInNextLevel;
     nodesInNextLevel = 0;

Tuesday, February 28, 2012

Clearing AutoFill Form data from Google Chrome

Delete all Autofill entries and saved text

Click the wrench icon on the browser toolbar.
Select Tools.
Select Clear browsing data.
In the dialog that appears, select the "Clear saved Autofill form
data" checkbox.
Use the menu on the top to select the amount of data you want to
delete. Select the beginning of time to clear everything.
Click Clear browsing data.

Wednesday, February 1, 2012

pig sorting a tuple

grp = foreach recs generate (($0 lt $1) ? $0 : $1), (($0 lt $1) ? $1 : $0); 

Blog Archive