Pages

Thursday, December 27, 2012

mvn jetty:run port

To start the jetty server in a different port than 8080 we can use this command.

mvn -Djetty.port=9999 jetty:run

Thursday, December 20, 2012

MySQL and Epoch Time

While working on MySQL, I found some useful functions to work with epoch time. They are well documented in the MySQL reference manual. Here is a list of few that I have used for my piece of work.
  • UNIX_TIMESTAMP() : Return a UNIX timestamp i.e. current time in epoch. See some examples below.
mysql> SELECT UNIX_TIMESTAMP() as cuurent_epoch_time;
       ->1355992290
  • UNIX_TIMESTAMP(DATE: Return a UNIX timestamp i.e. current time in epoch. See some examples below.
mysql> SELECT UNIX_TIMESTAMP(NOW()) as cuurent_epoch_time;
       ->1355993021
mysql> SELECT UNIX_TIMESTAMP('2012-12-20 10:30:19');
       ->1355979619
  • FROM_UNIXTIME(UNIX_TIMESTAMP: Format UNIX timestamp as a date. See some examples below.
mysql> SELECT FROM_UNIXTIME(1355993021);
       ->2012-12-20 14:13:41
mysql> SELECT FROM_UNIXTIME(UNIX_TIMESTAMP());
       ->2012-12-20 14:22:19
  • FROM_UNIXTIME(UNIX_TIMESTAMP , format: Format UNIX timestamp as per the format specified. See some examples below.
mysql> SELECT FROM_UNIXTIME(1355993021, "%Y");
       ->2012
mysql> SELECT FROM_UNIXTIME(UNIX_TIMESTAMP(), "%M");
       ->December
mysql> SELECT FROM_UNIXTIME(UNIX_TIMESTAMP(),'%Y %D %M %h:%i:%s %x');
       ->2012 20th December 02:35:53 2012

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

Saturday, November 17, 2012

MySQL Performance Tuning



SHOW VARIABLES LIKE 'have_query_cache';
SHOW VARIABLES LIKE 'query_cache_size';
SET GLOBAL query_cache_size = 256000000;

Gradle jettyRun debug

To start gradle jettyRun in debug mode, follow the steps below.

Set the GRADLE_OPTS as shown in the screen

$ export GRADLE_OPTS="-Xdebug -Xrunjdwp:transport=dt_socket,address=9999,server=y,suspend=n"
$ gradle jettyRun

Start the jetty server

Jetty server started

Open the debug configuration settings in Eclipse
Click on the debug button to start debugger

Set the breakpoints
Call the methods and debug


Set the debug points in your code and open the URL

http://localhost:9999/komliprime-trafficking-service/api/strategi?authtoken=6991a70eb121f3f623ebc2567927fef5


Truncating log files in UNIX/Linux

Most of the time we need log files to be truncated for many reasons. We can use the below command to truncate the file contents.


sudo cp /dev/null trafficking.log

Friday, August 3, 2012

Mounting exFAT in Ubuntu

Recently, I was trying to access NTFS based partitions in Mac OSX Snow Leopard, which always shows them as "read only" partitions. I got to understand that OSX by default only supports NTFS read only. I have had an option of using FAT with OSX and that too have its own limitation, one I know is the max file size less than 4gb.

So, I decided to partition my drive as exFAT, which is supported in both Windows and Mac. But when I tried accessing the same from my Ubuntu machine, it failed. So here is what I did to fix the problem in Ubuntu.
sudo su -
add-apt-repository ppa:relan/exfat
apt-get update
apt-get install fuse-exfat
With the above setting you will be able to manually mount the drives. In order to make this process automated this is what  I followed.
apt-get install build-essential
apt-get install ncurses-dev
apt-get install util-linux

With this it worked in all the operating systems I work on. 

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;

Wednesday, June 27, 2012

Check / Un-check ExtJS Grid header check box

Problem Statement: I have an ExtJS Grid with check boxes a shown in the figure below. The header check box toggles the selections of all the records in the grid. But many times I want to manually check and un-check the header check box and also I need a way to identify whether it's already checked or not.


Problem Solution: Here is a way out to find whether the header check box is selected or not.
/*
 * This function tells whether grid header checkbox is checked or not
 * 
 */
function isHeaderchecked(gridId){
    var view   = Ext.getCmp(gridId).getView();
    var chkdiv = Ext.fly(view.innerHd).child(".x-grid3-hd-checker");
    if(chkdiv.getAttribute('class') === 'x-grid3-hd-inner x-grid3-hd-checker'){
        return false;
    }else{
        return true;
    }
}

The methods to check and uncheck the header check box are as below.
/*
 * This function checks grid's header checkbox
 * 
 */
function checkHeader(gridId){
    var view   = Ext.getCmp(gridId).getView();
    var chkdiv = Ext.fly(view.innerHd).child(".x-grid3-hd-checker")
    chkdiv.addClass('x-grid3-hd-checker-on');
}
/*
 * This function un-checks grid's header checkbox
 * 
 */
function uncheckHeader(gridId){
    var view   = Ext.getCmp(gridId).getView();
    var chkdiv = Ext.fly(view.innerHd).child(".x-grid3-hd-checker")
    chkdiv.removeClass('x-grid3-hd-checker-on');
}

Installing RPM's In CentOS

Problem Statement: I have a web application that runs on Tomcat server 7. I have created RPM for the same. How do I deploy the RPM and restart the web application and Tomcat 7.

Problem Solution:

wget "rpm location"
Example:  wget http://192.168.0.59:8080/mywebapp_01_may_2012.rpm

yum localinstall "rpm file name"

Example:  yum localinstall mywebapp_01_may_2012.rpm
service tomcat7 restart

Thursday, June 7, 2012

Default selection in ExtJS combo boxes

Problem Statement: I have a combo box and the options are populated from a data store. In my case the date store is local data store. Only thing that I want is to make some option selected by default.


This is what my code looks like.

var statusStore = new Ext.data.ArrayStore({
    id: 0,
    fields: [
        'status',
        'label'
    ],
    data: [
           ["", 'All'],
           [true, 'Active'], 
           [false, 'Inactive']
          
    ]
});

items: [{                        
    mode:'local',
    hideLabel:true,    
    xtype: 'combo',
    id: 'filterStatus',
    editable:false,
    typeAhead: true,
    triggerAction: 'all',
    forceSelection: true,
    store: statusStore,
    displayField: 'label',
    width: 110,
    ctCls: 'MB'
}]

Problem Solution: One of the solution lies around using listeners. After the combo box is rendered, make the default selection. The one that works for me is as given in the code below.


var statusStore = new Ext.data.ArrayStore({
    id: 0,
    fields: [
        'status',
        'label'
    ],
    data: [
           ["", 'All'],
           [true, 'Active'], 
           [false, 'Inactive']
          
    ]
});

items: [{                        
    mode:'local',
    hideLabel:true,    
    xtype: 'combo',
    id: 'filterStatus',
    editable:false,
    typeAhead: true,
    triggerAction: 'all',
    forceSelection: true,
    store: statusStore,
    displayField: 'label',
    width: 110,
    ctCls: 'MB',
    listeners:{
        afterrender:function(){
            this.setValue(true);
            this.setRawValue('All');
        }
    }
}]

What I have done here is added a listener i.e. afterrender to make the default selection. The code above is self explanatory.

Enable/Disable button in ExtJS 3.2.1

Problem Statement: How to enable disable buttons in ExtJS 3.2.1?

Problem Solution:  ExtJs button is basically instance of Ext.Button class. There are two ways we can enable/disable
  1. Using config option
  2. Programmatically enabling & disabling
USING CONFIG OPTIONS
In order to set any button enabled or disabled, config option disabled can be set as true or false.


Ext.Button({
    text: 'Edit',
    id: 'edit',
    cls: 'edit_class',
    diasabled: 'true', // button is disabled
    listeners: {
    'click': function () {}                
    }
})

Ext.Button({
    text: 'Edit',
    id: 'edit',
    cls: 'edit_class',
    diasabled: 'false', // button is enabled
    listeners: {
    'click': function () {}                
    }
})

PROGRAMMATICALLY
Ext.getCmp('edit').setDisabled(true);

Ext.getCmp('edit').setDisabled(false);

Read more : Ext JS 3.2.1 API DOCS (http://extjs.cachefly.net/ext-3.2.1/docs/)

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

Monday, April 30, 2012

Object Oriented Analysis & Design

Why object orientation ?
  1. Higher level of abstraction
  2. Seamless transition among different phases of software development
  3. Encouragement of good programming techniques
  4. Promotion of reusability


Unified Approach (UA)
Based on the Booch, Rumbaugh and Jacobson methodologies.
  1. Use case driven development
  2. Utilize the unified modeling language (UML) for modeling
  3. Object-oriented analysis
  4. Object-oriented design
  5. Repositories of reusable classes and maximum reuse
  6. The layered approach
  7. Incremental development and prototyping
  8. Continuous testing 


Objects
  1. The term object was first formally used in the Simula language.
  2. Object have properties or attributes and behaviors.
  3. Objects respond to messages. Messages essentially are nonspecific functional calls. For example, we would send a draw to a chart  when we want the chart to draw itself. A message is different from a subroutine call, since different objects can respond to same message in different ways.
Objects respond to messages according to methods defined in its class. Message is the instruction and method is implementation.


Object relationships
Association: Represents the relationship between objects and classes.
  1. Associations are bidirectional - that means they can be traversed in both directions, perhaps with different connotations.
  2. Cardinality - specifies how many instances of one class may relate to a single instance of an associated class.
Dependency: One class is dependent on other.

Generalization: One class is generalized from other. This is typically known as class inheritance in object oriented programming terms.

Realization: This brings interfaces into consideration.

Sunday, April 29, 2012

Web 3.0

The future of web is going to be lot more powerful then we see today. People already started calling it as Web 3.0. Web 3.0 is all about building the semantic web and the future of web apps is termed as "Semantic Web Applications".

There are two possible aspects to the future of Web. The first is Social networking and people centric web and the second would be Semantic nature of the web. Today's web has got hell lot of information but web by itself do not understand the relationship between the data it has got. The web technology of today focuses more on how web pages are displayed and what content is displayed, rather than on the content itself. So whatever web does today, it does with the help of human intervention, it needs someone to provide ample guidance on what to do. Web is not smart enough to predict something and react to it.

The key features of Web 3.0 will be
  1. Semantic web (meaning of data)
  2. Personalization
  3. Intelligent search
  4. Behavioral advertising
  5. Metadata
More on Web 3.0
http://www.labnol.org/internet/web-3-concepts-explained/8908/
http://computer.howstuffworks.com/web-30.htm
http://en.wikipedia.org/wiki/Web_2.0#Web_3.0

Saturday, April 28, 2012

Google Drive


Finally, Google Drive is out there in market for use and  I got it configured for myself. Currently it gives 5GB of free space. 

Note! As of now Google Drive client is not available for GNU/Linux.  After setting up all this in Mac, I gave it a try in Ubuntu also. When I login to Google Drive web application, there is no option to download client, as it's now available yet :) 

Here we go, setting up Google Drive and client in Mac.

Read more about Google Drive on their official blog.

Get started with Google Drive at drive.google.com/start
Download the Google Drive (In my case it's for Mac)
I got the .DMG file
Double click .DMG file. You will see "Install Google Drive" icon
Double click
To install it, drag Google Drive.app to Applications
Verify Google Drive in applications and click it to launch
Might get this message, allow forever
Enter userid password

You will see this icon, on click below menu pops

Sign in with your google email id / password


Click Next

Start sync

You will see this message

Google Drive is created and synched

After logging in menus does change.

Friday, April 27, 2012

Take screen shot of iPhone & iPod Touch

To capture iPhone screen as an image, press Home and Sleep button at the same time. You can see the captured image in Photos.

Press Home and Sleep button together


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.

Shrink and extend disk partitions in Windows 7

Its been a long time since I played with partitioning hard drives and creating and deleting volumes. Way back in Windows era, there was no way to shrink and extend disk partitions. Recently I installed Ubuntu in my machine hosting Windows 7 and found one very useful option in Disk Utility i.e. to shrink and extend volumes. Here we go.

 Here is how we can shrink a volume. This will create an empty partition or unallocated space in your disk. Inn the similar way you can extend a volume where in you can assign extra space from unallocated disk space.

My Computer → Right Click → Manage

Select Disk Management → Select the partition

Right Click → Shrink Volume

You might see this message

Enter the amount of space to shrink in MB

ExtJS 3.2 Grid and jQGrid performance

ExtJS Grid and jQGrid are really nice to have kind of UI components. Based on the preference of ExtJS or jQuery framework one can choose which one to use. As I was assigned a task of improving performance of existing web application created in ExtJS 3.2, I got to evaluate grids in ExtJS and jQuery.

To evaluate ExtJS and jQuery grids and their performance, I created separate projects for them. And of course I am using server side pagination. No server side caching, client side caching for this evaluation. 

ExtJS performance 
Data Set
Page Size
Initial Load
Avg Next
Avg Prev
Avg Last
Avg First
853
100
1.06 s
100 ms
90 ms
30 ms
30 ms
853
200
1 s
250 ms
200 ms
250 ms
250 ms
853
500
1.48 s
350 ms
350 ms
250 ms
250 ms
853
800
976ms
350 ms
350 ms
400 ms
500 ms

jQuery performance 
Data Set
Page Size
Initial Load
Avg Next
Avg Prev
Avg Last
Avg First
853
100
200 ms
50 ms
50 ms
40 ms
40 ms
853
200
3 s
150 ms
130 ms
150 ms
150 ms
853
500
913 ms
200 ms
200 ms
250 ms
250 ms
853
800
938 ms
200 ms
200 ms
40 ms
100 ms


So, with my tests I found jQuery little faster compared to ExtJS. There could be n-number of reasons for this. 

Summary: 
Finally for the shake of maintainability of existing code base, I have chosen ExtJS over jQuery. However I have also experimented plugging in jQGrid in place of ExtJS Grid and that too worked for me. Initially I was not sure whether both can work together or not but they did.