Amit’s Codebase

June 22, 2009

Ssh without password

Filed under: How To, Linux — amitcodes @ 6:56 am
  1. Run the following command on the client
    • -> ssh-keygen -t dsa
  2. File id_dsa and id_dsa.pub will be created inside $HOME/.ssh
  3. Copy the id_dsa.pub to the server’s .ssh directory
    • -> ssh-copy-id -i ~/.ssh/id_dsa.pub user@server
  4. You can try ssh to the server from the client and no password will be needed
    • -> ssh user@server

Source:  http://linuxwave.blogspot.com/2007/07/ssh-without-password.html

June 16, 2009

Why do we write any servlet initialization code in init() and not in servlet’s constructor ?

Filed under: Java — Tags: — amitcodes @ 11:53 am

I was asked this question and I found this here when I googled for the same:

The init() method is typically used to perform servlet initialization–creating or loading objects that are used by the servlet in the handling of its requests. Why not use a constructor instead? Well, in JDK 1.0 (for which servlets were originally written), constructors for dynamically loaded Java classes (such as servlets) couldn’t accept arguments. So, in order to provide a new servlet any information about itself and its environment, a server had to call a servlet’s init() method and pass along an object that implements the ServletConfig interface. Also, Java doesn’t allow interfaces to declare constructors. This means that the javax.servlet.Servlet interface cannot declare a constructor that accepts a ServletConfig parameter. It has to declare another method, like init(). It’s still possible, of course, for you to define constructors for your servlets, but in the constructor you don’t have access to the ServletConfig object or the ability to throw a ServletException.

I started digging deep into java code where Servlet classes are loaded and found the code in org.apache.catalina.core.StandardWrapper.loadServlet().
It goes like this:

  • A servlet class is loaded
  • An instance of the the servlet class is created using default (zero argument) constructor of the class by reflection
  • The method init(ServletConfig config) is called on this instance which passes all context related configuration to the servlet
  • The method init(ServletConfig config) then calls method init()
  • The servlet is now loaded and the instance created !

So if you put in any servlet initialization code in servlet’s default constructor, it should not use ServletConfig and ServletContext objects. This will throw NullpointerException, since ServerConfig information is not initialized the Servlet till this point. However, if you want to perform any initialization which does not refer to ServletContext / ServletConfig, you can safely do so in the default constructor.

Note: Any constructor other than the default constructor is useless as it is never called by the servlet-container.

June 5, 2009

Write a function to remove the duplicate items in-place

Filed under: Programming Problems — Tags: — amitcodes @ 10:04 am

Write a function to remove the duplicate items in-place (return the new size of the array)

Solution:

  1. Sort the array, complexity of this step depends on algo used.
  2. loop over array till index < len(array)-1
  3. check if current element == next element
  4. if true, delete next element, else increment index

Complexity:
Complexity = complexity(sort()) + Complexity(remove_duplicates())
= O(N) + Complexity(remove_duplicates())
Hence depending on whether you use Bubble Sort or Merge Sort (?) the
overall complexity is going to be O(N^2) or O(NlogN)

Python Code:

#!/usr/bin/python

# Simple bubble sort for demo, O(N^2)
# You can use a better sorting algo
def sort( arr ):
    L=len(arr)-1
    for i in range(L,0,-1):
        for j in range (0,i):
           if arr[j] > arr[j+1]:
                t = arr[j]
                arr[j] = arr[j+1]
                arr[j+1] = t
    return arr

# Complexity O(N)
def remove_duplicates( arr ):
    length = len(arr)
    i=0;

    while i < (length-1):

        # check if two consequtive
        # elements are equal ...
        if arr[i] == arr[i+1] :
            #delete next element
            arr.pop(i+1)
            #get new size of array
            length = len(arr)
        else:
            # else move on to next
            # element
            i = i + 1
    return arr

# Execute
a = [1,3,6,1,5,5,0,9,6,8,9,7]
arr = remove_duplicates(sort(a))
print arr

How to multiply a number by 7 most efficiently

Filed under: Programming Problems — Tags: , — amitcodes @ 8:13 am

This is an easy one.
For machines it is always simpler to do bit-shifting than multiply.

What is bit-shifting one place to left, physically ?
Bit shifting one place right means multiplication by 2.
Example:

0010 << 1 = 0100, ( 2 * 2 = 4 )
0100 << 1 = 1000, ( 4 * 2 = 8 )
0011 << 1 = 0110, ( 3 * 2 = 6 )

Similarly, bit-shifting one place right means diuvision by 2.

Now what if you shit each bit 2 places ? It is simply bitshiting each bit by 1, 2 times – right ? Which is nothing but multiplying by 2 twice!
Hence, bit-shifting a number 2 places left multiplies it by 4.

That’s ok, but how is it related to multiplication by 7 ?
Elementary Watson!
For any given number N,

N*7 = N*( 1 + 2 + 4)
    = N + N*2 + N*4
    = N + N<<1 + N<<2

Where << is the bitwise left shift operator.

Here is example python code:

>>> def multiply_by_seven( n ):
...     return (n<<1) + (n<<2) +n;
...
>>> multiply_by_seven(2)
14
>>> multiply_by_seven(3)
21
>>> multiply_by_seven(7)
49
>>>

Similarly you can break multiplication by any number into powers of 2 and perform an efficient multiplication.

NOTE: Akshay just walked past me and said “Well, just multiply by 8 and subtract 1″ ;-)

June 4, 2009

How do you efficiently right-shift an array with the least memory usage?

Filed under: Programming Problems — Tags: , , — amitcodes @ 4:42 pm

How do you efficiently right-shift an array with the least memory usage?
For example, the original array could be 2 3 4 5 6. after right-shift two positions, it should be 5 6 2 3 4. The function prototype is shift_right (int[] arret, int shiftCount).
OR
Algorithm to right-shift an array M places, where M < length(array)

Solution 1:

Here is the exact solution as given in “Programming Pearls, 2nd Edition” :
“Swap all the numbers M times”
For example: Say you have an array[1,2,3,4] and you have to shift
it right 2 places. The

---   Start    ---
[1,2,3,4]
--- First Pass ---
[1,2,3,4]
 ^ ^
[2,1,3,4]
   ^ ^
[2,3,1,4]
     ^ ^
[2,3,4,1]

--- Second Pass ---
[2,3,4,1]
 ^ ^
[3,2,4,1]
   ^ ^
[3,4,2,1]
     ^ ^
[3,4,1,2]

---   Result   ---
[3,4,1,2]

Complexity:
Not good! Take the worstcase. Say you have an array of length `n` and you have to shift all elements `n-1` places.
The complexity becomes `O(N*(N-1)) ≈ O(N^2)` as `n -> ∞`.
In average case it will be O(mN), where `m` is the number of places to shift.

Solution 2:
Yet another solution.
Step 1: reverse the array by swapping all the elements (single pass, O(N))
Step 2: reverse all the elements from 0 to `M-1`
Step 3: reverse all the elements from `M` to `L-1` (where L is the length of the array)

Array       : [1,2,3,4,5], M=3
First pass  : [5,4,3,2,1] (all elements swapped reversing the array)

Second pass : [3,4,5,2,1] (reverse array from 0 to 3-1=2)
               ^ ^ ^
Third Pass  : [3,4,5,1,2] (reverse elements 3 to 5)
                     ^ ^
Result      : [4,5,1,2,3]

As simple as that !!

Java Code: [ source: sun java fourums ]

int[] reverse(int[] a, int i, int j) { // reverse elements i, i+1 ... j-1
   for (; --j > i; i++) {
      int t= a[i]; a[i]= a[j]; a[j]= t;
   }
   return a; // convenience.
}

int[] shiftRight(int[] a, int i) {
   return reverse(reverse(reverse(a, 0, a.length), 0, i), i, a.length);
}

Complexity: O(N)
Basically you traverse over the array twice, hence the complexity turns out to be O(2N) ≈ O(N)` as `n -> ∞`.

June 2, 2009

Given an unsorted array of integers, find all integer pairs in array which add up to 200.

Filed under: Programming Problems — amitcodes @ 12:58 pm

Problem : Given an unsorted array of integers, find all integer pairs in array which add up to 200.

Solution:

  • First of all sort the array so that the largest number is on top
  • There should be two pointers – initialize both by letting one
    point to the head of array and another to the tail.
  • add head and tail
  • if (head + tail ) > 200, then increment head
  • if (head+tail ) < 200, then decrement tail
  • if (head + tail ) == 200, then decrement tail, increment head
  • break if head and tail meet

The fundamental is you have the greatest number in the lot in `head`. Now you start adding increments to it (starting from the smallest increment). If the result is smaller than the target number, you need to increase the increment and vice-versa.

Complexity:

  • The complexity method findNumbers is O(N) [single pass]
  • The complexity of method bubble Sort is O(N^2)

Since assymptotically O(N^2) dominates O(N), the complexity of this solution is O(N^2) [ BAD! BAD!! BAD!!! ]
One good trick is to implement quikSort instead of bubbleSort. In that case the complexity becomes :
O(N) + O(NlogN) = O(NlogN)

I implemented bubble sort just for demonstration purposes. The optimized way is to sort it with quick sort.

My Tip: If you still don’t understand the fundamentals of this solution, use this text as a hint and try to do it on a piece of paper. It’s hard to explain but easier to realize :)

package org.simplesoft.programmingproblems;

/**
 * @author Amit Kumar Sharma
 */
public class Arrays {

    /**
     * Method to find all numbers in a sorted array
     * of integers which add up to number `N`.
     * For example "find all numbers in an array
     * of integers which add up to 200"
     * @param arr: Sorted array of integers
     * @param n: number to which add up to
     */
    public static void findNumbers(int[] arr, int n) {
        // array is assumed to be sorted in descending order
        int head = 0;
        int tail = arr.length - 1;

        int num1, num2;

        while (tail != head - 1) {

            num1 = arr[head];
            num2 = arr[tail];

            if (num1 + num2 > n) {
                head++;
            } else if (num1 + num2 < n) {
                tail--;
            } else if (num1 + num2 == n) {
                System.out.println(num1 + " + " + num2 + " = " + n);
                head++;
                tail--;
            }
        }

    }

    /*
     * Bubble sort of complexity O(n^2)
     * If you push in quick sort here - the complexity of
     * the overall problem becomes O(NlogN)
     */
    public static void bubbleSort(int[] arr) {

        for (int i = (arr.length - 1); i > 1; i--) {

            for (int j = 0; j < i; j++) {

                if (arr[j] < arr[j + 1]) {

                    // swap
                    int tmp = arr[j];
                    arr[j] = arr[j + 1];
                    arr[j + 1] = tmp;
                }
            }
        }
    }

    /**
     * Utility method to print integer arrays
     */
    public static void echoArray(int[] arr) {
        for (int i : arr) {
            System.out.print(i + ", ");
        }
        System.out.println();
    }

    public static void main(String[] args) {
        int[] arr = {
                       1,  8,  9,
                      23, 32, 16,
                      44, 83, 92,
                      62, 51, 12,
                      48, 50, 10,
                      22, 38, 15
                    };

        echoArray(arr);

        bubbleSort(arr);
        findNumbers(arr, 60);

    }
}

April 8, 2009

WSDLException: faultCode=OTHER_ERROR: Can’t find prefix

Filed under: Java — amitcodes @ 11:58 am

damn! damn!! damn!!!

I was developing a webservice using Apache-CXF (2.1.1) and Spring (2.5.5) using wsdl-first-approach.

All went well, wsdl validation passed, code compiled, war created, webservice hosted on apache-tomcat 6. And then as I tried to access the wsdl url, I got this error :

Apr 8, 2009 4:37:15 AM org.apache.catalina.core.StandardWrapperValve invoke
---- 8< ------------------------------------------------------
SEVERE: Servlet.service() for servlet CXFServlet threw exception
javax.wsdl.WSDLException: WSDLException: faultCode=OTHER_ERROR: Can't find prefix for 'http://prediction.simplesoft.org/2009/xsd'. Namespace prefixes must be set on the Definition object using the addNamespace(...) method.
    at com.ibm.wsdl.util.xml.DOMUtils.getPrefix(Unknown Source)
    at com.ibm.wsdl.util.xml.DOMUtils.getQualifiedValue(Unknown Source)
    at com.ibm.wsdl.util.xml.DOMUtils.printQualifiedAttribute(Unknown Source)
    at com.ibm.wsdl.xml.WSDLWriterImpl.printParts(Unknown Source)
    at com.ibm.wsdl.xml.WSDLWriterImpl.printMessages(Unknown Source)
    at com.ibm.wsdl.xml.WSDLWriterImpl.printDefinition(Unknown Source)
    at com.ibm.wsdl.xml.WSDLWriterImpl.writeWSDL(Unknown Source)
    at com.ibm.wsdl.xml.WSDLWriterImpl.getDocument(Unknown Source)
    at org.apache.cxf.transport.http.WSDLQueryHandler.writeResponse(WSDLQueryHandler.java:168)
    at org.apache.cxf.transport.servlet.ServletController.invoke(ServletController.java:147)
    at org.apache.cxf.transport.servlet.AbstractCXFServlet.invoke(AbstractCXFServlet.java:174)
    at org.apache.cxf.transport.servlet.AbstractCXFServlet.doGet(AbstractCXFServlet.java:156)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:617)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at org.springframework.orm.hibernate3.support.OpenSessionInViewFilter.doFilterInternal(OpenSessionInViewFilter.java:198)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:76)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:128)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:286)
    at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:845)
    at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:583)
    at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:447)
    at java.lang.Thread.run(Thread.java:619)
---- 8< ------------------------------------------------------

I searched and searched through google and internet, found nothing that could fix this issue.
I finally found the silly bug : pretty improbable, but true:
The targetNamespace annotations for my endpoint (interface) and implementation class were different. This can not be, so I simply made them same and it all worked like cake-walk! :)

I am pasting the erred source below for all to see ( Don’t laugh :P )

The Endpoint >>

/**
 * This class was generated by Apache CXF 2.1.1
 * Fri Apr 03 17:22:14 IST 2009
 * Generated source version: 2.1.1
 *
 */

@WebService(targetNamespace = "http://prediction.simplesoft.org/ws", name = "PredictionPortType")
@XmlSeeAlso({org.simplesoft.prediction._2009.xsd.ObjectFactory.class})
@SOAPBinding(parameterStyle = SOAPBinding.ParameterStyle.BARE)
public interface PredictionPortType {

// And the rest of class definition ...
// ...
// ...

The Implementation >>

@WebService(serviceName = "PredictionService", portName = "PredictionPort",
targetNamespace = "http://prediction.simplesoft.org/2009/xsd", /*namespace is wrong, i.e, different from endpoint*/
endpointInterface = "org.simplesoft.prediction.ws.PredictionPortType")
public class PredictionServiceImpl implements PredictionPortType {

// And the rest of class definition ...
// ...
// ...

October 2, 2008

sendmail jumpstart

Filed under: How To — Tags: — amitcodes @ 9:17 pm

This little tutorial tells you how to send email using a server on which sendmail is installed.

STEP 1:
telnet to mail server

telnet mail.example.net 25

STEP 2: Type the text starting with ‘#‘ [without # ofcourse ] when you see the following and press Enter

220 local ESMTP Sendmail 8.13.5/8.13.5; Wed, 15 Mar 2006 01:51:21 -0800 (PST)
#HELO host.example.com
250 mail.example.net Hello host.example.com [192.0.2.1], pleased to meet you
#MAIL FROM:<user@example.com>
250 2.1.0 <user@example.com>... Sender ok
#RCPT TO:<postmaster@example.net>
250 2.1.5 <postmaster@example.net>... Recipient ok
#DATA
354 Enter mail, end with "." on a line by itself
#This is a test message
#.
250 2.0.0 k2FApLlB020139 Message accepted for delivery
#QUIT
221 2.0.0 mail.example.net closing connection

Step 3: Check status
Sendmail uses the mail facility of syslog for logging. The mail log is usually written to /var/log/maillog. You can test the status by tailing the log file.

Simple :)

September 22, 2008

Hello world!

Filed under: Uncategorized — amitcodes @ 9:20 pm

public class Hello {
    public static void main ( String[] args ) {
        System.out.println("Hello World :) ");
    }
}

August 10, 2008

Are static methods safe to be invoked by multiple threads simultaneously ?

Filed under: Programming Problems — amitcodes @ 3:01 pm

Are static methods safe to be invoked by multiple threads simultaneously ?
Ok. So it goes like this. Picture this :

  • the instruction sequence for a method is stored in memory
  • the calling method stores data (arguments) at a particular memory location
  • instruction counter starts executing instructions for the given method on parameter data and storing results
  • when end of method instructions is reached, result is returned and the parameter data is cleared.

Now of in this process, the called method does not store the resulting value at a memory location which will not be cleared after the instruction sequence is completed then this method can be accessed by multiple threads at the same time without any problem. This can be so because each thread comes with it’s own data and these instructions are executed on the given data. This can be be true for both – instance methods as well as static methods.

Can Data Access Objects be Singleton ? If so, when ?
DAOs can be singleton provided none of the methods store state in any way. All the methods of the DAOs should just :

  • take data
  • execute set of instructions
  • return the result

If so happens – even the following scenario will not result in a dicey result :

  • Thread A calls method X to insert a record in database and at the same time
  • Thread B also calls method X for the same operation.
  • What happens in such a case is – two different database connections try to insert data into database. Which is same as calling the same method on two different instances of the given DAO class.
  • In fact – it’s safer to use singleton DAOs in case of server applications where 1000 users trying to query database may result in 1000 DAO objects which is not a very elegant design!
Older Posts »

Blog at WordPress.com.