Pages

Showing posts with label Programming. Show all posts
Showing posts with label Programming. Show all posts

Friday, January 25, 2013

Mysql Insert From Cross Join

Think of a scenario like this, we have a database of Doctors and Patients. All the doctors have access to all the patients information and all the patients can visit any doctor.
-- ----------------------------------------
-- Table `Doctors`
-- ----------------------------------------
CREATE TABLE IF NOT EXISTS `Doctors` (
  `doc_id` int(10) unsigned NOT NULL,
  `doc_first_name` VARCHAR(104) NOT NULL,
  `doc_last_name` VARCHAR(104) NOT NULL,
  `doc_discipline` VARCHAR(104) NOT NULL,
  PRIMARY KEY (`doc_id`)
) 
ENGINE=InnoDB DEFAULT CHARSET=utf8;
INSERT INTO `Doctors` VALUES(1,'Sintu', 'Kumar', 'otholaringology');
INSERT INTO `Doctors` VALUES(2,'R', 'Chinch', 'dentistry');
-- ----------------------------------------
-- Table `Patients`
-- ----------------------------------------
CREATE TABLE IF NOT EXISTS `Patients` (
  `p_id` int(10) unsigned NOT NULL,
  `p_first_name` VARCHAR(104) NOT NULL,
  `p_last_name` VARCHAR(104) NOT NULL,
  PRIMARY KEY (`p_id`)
) 
ENGINE=InnoDB DEFAULT CHARSET=utf8;
INSERT INTO `Patients` VALUES(1,'Jim','Cary');
INSERT INTO `Patients` VALUES(2,'John','Cook');
-- ----------------------------------------
-- Table `Doctors_Patients`
-- ----------------------------------------
CREATE TABLE IF NOT EXISTS `Doctors_Patients` (
  `id` int(10) unsigned NOT NULL auto_increment,
  `doctor_id` int(10) unsigned NOT NULL,
  `patient_id` int(10) unsigned NOT NULL,
  PRIMARY KEY (`id`),
  FOREIGN KEY (`doctor_id`) REFERENCES `Doctors` (`doc_id`) ON DELETE NO ACTION ON UPDATE NO ACTION,
  FOREIGN KEY (`patient_id`) REFERENCES `Patients` (`p_id`) ON DELETE NO ACTION ON UPDATE NO ACTION

) 
ENGINE=InnoDB DEFAULT CHARSET=utf8;
Now we want to populate the table `Doctors_Patients` with the Cartesian  product of the other two tables. For this we can simply use cross join as listed below.

INSERT INTO `Doctors_Patients`(doctor_id,patient_id) SELECT `doc_id`, `p_id` FROM `Doctors`  CROSS JOIN `Patients`;

And this is what it did.
select * from Doctors_Patients;

+----+-----------+------------+
| id | doctor_id | patient_id |
+----+-----------+------------+
|  1 |         1 |          1 |
|  2 |         2 |          1 |
|  3 |         1 |          2 |
|  4 |         2 |          2 |
+----+-----------+------------+
4 rows in set (0.08 sec)

Wednesday, December 19, 2012

Current epoch time

Perl                    time
PHP                     time()
Java                  long epoch = System.currentTimeMillis()/1000;
MySQL                 SELECT unix_timestamp(now())
Oracle PL/SQL         SELECT (SYSDATE - TO_DATE('01-01-1970 00:00:00','DD-MM-YYY HH24:MI:SS')) * 24 * 60 * 60 FROM DUAL
JavaScript           Math.round(new Date().getTime()/1000.0) getTime() returns time in milliseconds.
Unix/Linux Shell     date +%s

Tuesday, December 18, 2012

Character count problem

You have a string of small letters a-e, which can be represented as a regular expression in the form of [a-e]*

Example: abcdef, eafdceeafe, etc etc

Problem: Write a program that counts maximum continuous occurrence of a character and their indexes. For example, if the string is "abbbbdcdef", it will be "b" : 4, starting at index 1 to 4.

public class TestStringCharCount {

   public static void main(String[] args) {

        int start = 0;
        int count = 0;
        int maxCount = 0;
        char maxChar = 'a';
        String str = "abcdefabbbbbbbbcdaeff";
        char[] chars = str.toCharArray();

        for (int i = 0; i < chars.length; i++) {
            count = 0;
            for (int j = i; j < chars.length; j++) {

                if (chars[i] == chars[j]) {
                    count++;
                } else {
                    break;
                }
                i = j;
            }

            if (count > maxCount) {
                maxCount = count;
                maxChar = chars[i];
                start = i;
            }

        }
        System.out.println("string = "+ str + ", length = "+ str.length());
        
        System.out.println(maxChar + ":" + maxCount + " starting at "
                + (start - maxCount) + " to " + start);
    }
}

Output: 
string = abcdefabbbbbbbbcdaeff, length = 21
b:8 starting at 6 to 14

Friday, December 14, 2012

Get current time in perl

#!/usr/bin/perl -w

print "current time in epoch is : ". time(). "\n";
print "current time is : ". localtime(time()). "\n";

my ($sec,$min,$hour,$day,$month,$yr19,@rest) =   localtime(time);

print "----------------------------------------\n";
print "Sec : ". $sec . "\n";
print "Min : ". $min . "\n";
print "Hour : ". $hour . "\n";
print "Day : ". $day . "\n";
print "Month : ". $month . "\n";
print "Year : ". $yr19 . "\n";
Output
current time in epoch is : 1355483046
current time is : Fri Dec 14 16:34:06 2012
-------------------------------------------
Sec : 6
Min : 34
Hour : 16
Day : 14
Month : 11
Year : 112

Monday, November 19, 2012

Hello World! Perl Example

My first PERL program. Create a new file

vi hello_world.pl

#!/usr/bin/perl -w
#
#
print "Hello World!\n";

exit;


Execute the above script with the command below.

perl hello_world.pl

Tuesday, July 3, 2012

Function in JavaScript


Passing functions to another function
    function invoke_and_add(a,b){
        return a() + b();
    }

    function one(){
        return 1;
    }

    function two(){
        return 2;
    }

    invoke_and_add(one,two);

Callback function
    function multiplyByTwo(a,b,c, callback){
        var i, array = [];
        for(i=0;i<3; i++){
        array[i] = callback(arguments[i] * 2);
        }
        return array;
    }

    function addOne(a){
        return a+1;
    }

    myarr = multiplyByTwo(1,2,3,addOne);

Self-invoking function
    (
        function(){
            alert('this is a self invoking function');
        }
    )()

Inner (Private) function
    function a(param){
        function b(input){
        return input * 2;
        };
        
        return 'the result is ' + b(param);
    };

    a(2);

Functions that return function
    function a(){
        alert('a');
        return function(){
        alert('b');
        };
    }

    var newFn = a();
    newFn();

    // also the above 2 lines can be replaced with this one liner

    a()();


Function rewriting itself
    function a(){
        alert('a');
        a = function(){
        alert('b');
        };
    }

    a();
    a();

JavaScript Quiz

Here are some of the questions that I found in a book titled "Object-Oriented JavaScript" by Stoyan Stefanov.


    var a; typeof a;
    var s = 'ls'; s++;
    !!false;
    !!undefined;
    typeof -Infinity;
    10 % "0";
    undefined == null;
    false  === "";
    typeof "2E+2";
    a = 3e+3; a++;
    var v = v || 10;
    typeof NaN;

Thursday, June 7, 2012

Java program to find host name and IP address of local and remote machine

Problem Statement: Many times we need to find the host name and IP address of local and the remote machines. Most importantly I want to do this with a Java program.

Solution: Here is the main class, I have named it as HostNameFinder and to test these methods I've another class called as HostNameFinderTest.

/**
 * 
 * Classname : HostNameFinder.java
 * <b>HostNameFinder<b><br> 
 * <p>
 *     This class helps to get the host name and the IP addresses of the local machine and 
 *     remote machines. It provides static methods that can be used to get the very specific
 *     information such as host name or the IP address.
 * </p>
 * 
 * @author Manohar Negi
 * @version 1.0
 * @since 1.0
 * @see
 * Copyright notice
 *
 * Revision History: 
 *
 * Date            By              Version        Comments
 * ---------------------------------------------------------------------------------
 * Aug 31, 2011    Manohar Negi    1.0            Initial Draft
 * Sep 01, 2011    Manohar Negi    1.1            Modified to include more methods
 *
 **/

package com.mani.util;

import java.net.InetAddress;
import java.net.UnknownHostException;

/**
 * <p>
 * <b>Functional Description:</b>
 * <p>
 * Some Description of the file
 * 
 * Created: Month, Day ,YYYY
 * 
 * @author
 * @version
 */
public class HostNameFinder {

    public static String getMyHostName() {
        String hostname = null;
        try {
            InetAddress addr = InetAddress.getLocalHost();
            hostname = addr.getHostName();
            System.out.println("Host Name = " + hostname);

        } catch (UnknownHostException e) {
            e.printStackTrace();
        }

        return hostname;
    }

    public static String getMyIPAddress() {
        String ipAddress = null;
        try {
            InetAddress addr = InetAddress.getLocalHost();
            String ipAddr = addr.getHostAddress();
            System.out.println("IP Address = " + ipAddr.toString());

        } catch (UnknownHostException e) {
            e.printStackTrace();
        }

        return ipAddress;
    }

    public static String getIPByAddress(String address) {
        String ipAddress = null;
        try {
            InetAddress addr = InetAddress.getByName(address);
            String ipAddr = addr.getHostAddress();
            System.out.println("IP Address = " + ipAddr.toString());

        } catch (UnknownHostException e) {
            e.printStackTrace();
        }

        return ipAddress;
    }

    public static String getHostNameByAdress(String address) {
        String hostname = null;
        try {
            InetAddress addr = InetAddress.getByName(address);
            hostname = addr.getHostName();
            System.out.println("Host Name = " + hostname);

        } catch (UnknownHostException e) {
            e.printStackTrace();
        }

        return hostname;
    }

}


Here is the test class.

/**
 * 
 * Classname : HostNameFinderTest.java
 * <b>HostNameFinderTest<b><br> 
 * <p>
 *     This class is to test the methods of HostNameFinder.class
 * </p>
 * 
 * @author Manohar Negi
 * @version 1.0
 * @since 1.0
 * @see
 * Copyright notice
 *
 * Revision History: 
 *
 * Date            By              Version        Comments
 * ---------------------------------------------------------------------------------
 * Aug 31, 2011    Manohar Negi    1.0            Initial Draft
 * Sep 01, 2011    Manohar Negi    1.1            Modified to include more methods
 *
 **/
package com.mani.util;

public class HotmNameFinderTest {

    public static void main(String[] args) {

        /* get the host name for local machine */
        HostNameFinder.getMyHostName();

        /* get the IP for local machine */
        HostNameFinder.getMyIPAddress();

        /* get the host name for localhost */
        HostNameFinder.getHostNameByAdress("localhost");

        /* get the IP for localhost */
        HostNameFinder.getIPByAddress("localhost");

        /* get the host name for www.google.com */
        HostNameFinder.getHostNameByAdress("www.google.com");

        /* get the IP for www.google.com */
        HostNameFinder.getIPByAddress("www.google.com");

    }

}


And here is the output that I got.

Host Name = mani-mac
IP Address = 192.168.2.4
Host Name = localhost
IP Address = 127.0.0.1
Host Name = www.google.com
IP Address = 74.125.236.83

Friday, May 18, 2012

Transaction management in Hibernate

A transaction is an atomic unit of work. There are only two outcomes, either success or failure. In hibernate one way to manage transactions is as given below.

Session session = null;
Transaction tx = null;
try {
    session = sessionFactory.openSession();
    tx = session.beginTransaction();
    //perform the transactions here
    // some more transactions
    tx.commit();
} catch (RuntimeException ex) {
    tx.rollback();

} finally {
    session.close();
}

Handling window close or hide event in ExtJS 3.2.1

In case you need to do something specific on window close or hide. Here is a way to do so.

var myPopUpWindow = new Ext.Window({
    layout : 'hbox',
    layoutConfig : {
        align : 'stretch',
        pack : 'start',
    },
    width : popUpWindowWidth,
    height : popUpWindowHeight,
    modal : true,
    resizable : true,
    closable : true,
    draggable : true,
    animate : true,
    id : myPopUpWindow,
    shadow : true,
    closeAction : 'hide',
    hideMode : 'visibility',
    title : 'Selection Box Example',
    items : [ my_popUp_grid, my_selections_grid ],
    bbar : new Ext.Toolbar({
        items : [ {
            xtype : 'tbbutton',
            text : 'Cancel',
            handler : function() {
                myPopUpWindow.hide();
            }
        }, {
            xtype : 'tbfill'
        }, {
            xtype : 'tbbutton',
            text : 'Save',
            handler : function() {
                saveData();
                myPopUpWindow.hide();
            }
        } ]
    }),
    listeners:{
         'close':function(win){
                  console.info('bye');
                  saveData();
          },
         'hide':function(win){
                  console.info('just hidden');
                  saveData();
          }
 }
});

In the example above, I'm calling saveDate() on window close and hide.

Thursday, May 3, 2012

Handling exceptions in ExtJS

Problem Statement: I struggled almost for a week to fix exception handling in ExtJS. The problem is when I make an AJAX call or make any asynchronous server side call, I was not able to read exact exception message thrown by server. I saw different ways to implement exception listeners in ExtJS but most of them didn't work for me.

Problem Solution: This is what I am using to handle exceptions in ExtJS.

var reportProxy = new Ext.data.HttpProxy({
    url : 'myReportURL',  // web URL
    method : 'post',      // HTTP method
    timeout : 180000,     // request timeout
    listeners : {         // configure listener
        exception : function(proxy, type, action, options,
                response, arg) {
            // this block is reached on any exception
            if (!response.isTimeout) {
                // check if response didn't timed out
                Ext.Msg.show({
                    title : '',
                    msg : "Oops !! There is some Internal Server Error.",
                    buttons : Ext.Msg.OK,
                    icon : Ext.MessageBox.INFO
                });
            } else {
                // this block is called on response timeout
                Ext.Msg.show({
                    title : '',
                    msg : "Its taking too long. Response timed out.",
                    buttons : Ext.Msg.OK,
                    icon : Ext.MessageBox.INFO
                });
            }
        }
    }
});

Note the syntax for defining exception block, the function signature is important. I have seen different signatures for this function but this is the one that worked for me.

Tuesday, May 1, 2012

Features of Java 7


Initially Java 7 was proposed to have many new features such as
  1. Modularization
  2. Anonymous methods (closures)
  3. Simplifications in generics implementations
  4. Enhanced exception handling
  5. Strings in switch statements
  6. Dynamic languages support
  7. Simplified initialization of collections
  8. Elvis operators
  9. API changes
Out of above listed features a few were dropped from actual release of Java 7 and they are supposed to be released as part of Java 8. And they are 
  1. Anonymous methods (closures)
  2. Simplified initialization of collections
  3. Elvis operators

New features in Java 7
  1. Change in language syntax
    • Constants
      • Binary constants
      • Underscore in numeric constants
    • Strings in switch statement
    • Extended try catch
    • Multi-catch
    • Diamond operator
  2. Better support of dynamic languages
    • New bytecode  instruction
    • New dynamic linkage mechanism
  3. JDBC 4.1
    • try-with-resources statement
    • RowSet 1.1
  4. NIO 2
    • Comes with a set of views
    • New abstract class java.nio.file.Path
    • Notion of metadata
  5. Updates in Swing API
  6. Unicode 6
  7. Updates in concurrency package
  8. Automatic resource closure

Friday, April 27, 2012

JavaScript to get the browser window's height and width

While working on a web application I came across a scenario where in I wanted to adjust height and width of my component as per browser's resolution. And here is the code snippet to do that in JavaScript.

function getScreenHeightWidth() {
    var myWidth = 0, myHeight = 0;
    if (typeof (window.innerWidth) == 'number') {
        // Non-IE
        myWidth = window.innerWidth;
        myHeight = window.innerHeight;
    } else if (document.documentElement
            && (document.documentElement.clientWidth 
                        || document.documentElement.clientHeight)) {
        // IE 6+ in 'standards compliant mode'
        myWidth = document.documentElement.clientWidth;
        myHeight = document.documentElement.clientHeight;
    } else if (document.body
            && (document.body.clientWidth 
                        || document.body.clientHeight)) {
        // IE 4 compatible
        myWidth = document.body.clientWidth;
        myHeight = document.body.clientHeight;
    }
    window.alert('Width = ' + myWidth);
    window.alert('Height = ' + myHeight);
}

I have tested this in latest versions of all modern browsers including Chrome, Firefox, Safari and Internet Explorer. Also I have tested it in Windows 7, Ubuntu 11.10 and Mac Snow Leopard.

HTML Codes for arrow keys

In order to display left, right, up and down arrow keys in HTML we have the following codes.

Key
Code
Output
Left Arrow
&larr;
Right Arrow
&rarr;
Up Arrow
&uarr;
Down Arrow
&darr;

More HTML codes here.

Thursday, April 26, 2012

Modify parameters from ExtJS 3.2 Grid Paging next button

Problem Statement: I have a data store define in ExtJS 3.2 as given below. The problem is when clicking next button in paging bar, the agencyStatus is not passed in.

var agncGridStore = new Ext.data.Store({
    url : '/webui/advertiser/agenciesList.json',
    method : 'GET',
    autoLoad : false,
    reader : new Ext.data.JsonReader({
        root : 'agencies',
        totalProperty : 'agencyCount',
        fields : [ 'id', {
            name : 'name',
            type : 'string',
            sortType : Ext.data.SortTypes.acUCString
        }, 'address', 'status', 'currency' ]
    }),
    listeners : {
        load : function() {
            resizeGridHeight('agncGridID', 200, 300);
        }
    },
    remoteSort : true,
    sortInfo : {
        field : 'name',
        direction : 'asc' | 'desc'
    },
    baseParams : {
        'firstResult' : 0,
        'fetchSize' : pageSize,
        'searchStr' : searchText,
        'agencyStatus' : searchFilter
    }
});
agncGridStore.load();

Problem Solution: After trying different possibilities, finally I got done with the help of beforeload event.
var agncGridStore = new Ext.data.Store({
    url : '/webui/advertiser/agenciesList.json',
    method : 'GET',
    autoLoad : false,
    reader : new Ext.data.JsonReader({
        root : 'agencies',
        totalProperty : 'agencyCount',
        fields : [ 'id', {
            name : 'name',
            type : 'string',
            sortType : Ext.data.SortTypes.acUCString
        }, 'address', 'status', 'currency' ]
    }),
    listeners : {
        load : function() {
            resizeGridHeight('agncGridID', 200, 300);
        },
        beforeload : function(store) {    
            store.baseParams.agencyStatus = searchFilter;
            store.baseParams.searchStr = searchText;
        }
    },
    remoteSort : true,
    sortInfo : {
        field : 'name',
        direction : 'asc' | 'desc'
    },
    baseParams : {
        'firstResult' : 0,
        'fetchSize' : pageSize,
        'searchStr' : searchText,
        'agencyStatus' : searchFilter
    }
});
agncGridStore.load();

Use Hibernate Criteria API to Order By based on Association

Problem Statement: I am working with Hibernate to read database table. Not able to apply order by on associated object's attributes.

Problem Solution: Solution is to use criteria alias.

Sort by Cat.name.

List cats = sess.createCriteria(Cat.class)
    .addOrder( Order.asc("name") )
    .list();
In the statement below associated objects's name property is used for sorting. In this case sort will be on Cat.kittens.name
List cats = sess.createCriteria(Cat.class)
    .createAlias("kittens", "kt")
    .addOrder( Order.asc("kt.name") )
    .list();

Read more