Friday, September 12, 2014

Something about DICOM


Modality Look up table (MLUT) - When a CT image is acquired the data present in the image is manufacturer dependent values, in order to convert this data to Hounsfield values Modality LUT is applied.

MLUT is applied using rescale intercept & rescale slope values present in the DICOM image. Following is the equation for it:

data[pixelIndex] = data[pixelIndex] * rescale_slope + rescale_intercept

rescale slope is represented by DICOM tag (0028, 1052)
rescale intercept is represented by DICOM tag (0028,1053)

 

Saturday, June 21, 2014

HTTP Authentication mechanisms

HTTP Basic Authentication:  The username and password are sent to the server without any encryption.

HTTP Digest Authentication: A hash function is applied to the password before it is sent. So more secure than Basi

HTTPS: HTTP + SSL. SSL encrypts all information going over network.

Do I need Digest authentication if already using SSL?
No, following explaination on stack overflow explains
http://stackoverflow.com/questions/11923607/do-you-still-need-to-use-digest-authentication-if-you-are-on-ssl


Other SSL resources
http://tomcat.apache.org/tomcat-6.0-doc/ssl-howto.html#Introduction_to_SSL

Friday, June 6, 2014

Visual Studio 2010: No symbol loaded for this document


If visual studio 2010 shows the above issue, then go to project properties & try  following steps:

  1. Ensure Linker -> Debugging -> Generate program database file properties is set
  2. Ensure Linker -> Debugging -> Generate debug info is set
  3. C/C++ -> General ->  Debug information is set to Program Database for edit and continue (/ZI)




 

Thursday, May 1, 2014

Program to filter values not in range from BST

Problem Statement: Remove the values from the Binary search tree which are out of the given range

Ex: Input tree



 Input Range: 10 to 16

Output Values:  10, 12, 13, 14, 16

Code:

class LocalTree2{
     public int val;
  public LocalTree2 leftTree;
  public LocalTree2 rightTree;
  static int MIN = 9;
  static int MAX = 11;
  static public LocalTree2 init;
  public LocalTree2(int i) {
   val = i;
  }
  public void add(int i){
   LocalTree2 temp = this;
   LocalTree2 parent = this;
   while (temp != null){
    parent = temp;
    if ( i > temp.val){
     temp = temp.rightTree;
 
    }else{
     temp = temp.leftTree;
    }
   }
   temp  = new LocalTree2(i);
   if ( i > parent.val){
    parent.rightTree = temp;
   }else{
    parent.leftTree = temp;
   }
  }


  public LocalTree2 deleteFromTree(LocalTree2 tree, int value){
   if (tree == null)
    return tree;

   if (tree.val < value){
       tree.rightTree = deleteFromTree(tree.rightTree, value);
   }else{
    if (tree.val > value){
     tree.leftTree = deleteFromTree(tree.leftTree, value);
    }else{
     LocalTree2 successorNode = getInOrderSucessor2(tree);
     if (successorNode != null){
      tree.val = successorNode.val;
      tree.rightTree = deleteFromTree(tree.rightTree, tree.val);
     }else{
      tree = tree.leftTree;
     }
    }

   }
   return tree;
  }


  private int getInOrderSucessor(LocalTree2 node) {
   if (node.rightTree != null){
    node = node.rightTree;
   }
    while (node.leftTree != null ){
     node = node.leftTree;
    }
   return node.val;

  }
  private LocalTree2 getInOrderSucessor2(LocalTree2 node) {
   if (node == null || node.rightTree == null){
    return null;
   }
   node = node.rightTree;
    while (node.leftTree != null ){
     node = node.leftTree;
    }
   return node;

  }

  public void printTree(LocalTree2 root){
   if (root == null)
    return;
   printTree(root.leftTree);
   System.out.println(root.val);
   printTree(root.rightTree);
  }

  public LocalTree2 findNode(LocalTree2 root, int val){
   if (root == null)
    return null;

   LocalTree2 node = findNode(root.leftTree, val);
   if ( node != null)
    return node;
   if (root.val == val)
    return root;
   node = findNode(root.rightTree, val);
   if ( node != null)
    return node;
   return null;
  }

  public LocalTree2 filterNode(LocalTree2 tree, int minFilter, int maxFilter){
   if (tree == null)
    return tree;

   tree.leftTree = filterNode(tree.leftTree, minFilter, maxFilter);
   while (tree != null &&  ((tree.val < minFilter) || (tree.val > maxFilter) )){
    tree = deleteFromTree(tree, tree.val);
   }
   if (tree != null)
    tree.rightTree = filterNode(tree.rightTree, minFilter, maxFilter);


   return tree;

  }

}

public class BST {
 public static void main(String[] args) {
  LocalTree2 l = new LocalTree2(8);
  l.add(3);
  l.add(1);
  l.add(6);
  l.add(4);
  l.add(7);
  l.add(10);
  l.add(14);
  l.add(13);
  l.add(12);
  l.add(16);
  l.printTree(l);
  l = l.filterNode(l, 10, 16);
  System.out.println("************** Post Filtering ********************");
  l.printTree(l);
 }
}

Print nth smallest number in tree

import java.util.Vector;

class LocalTree{
 public int val;
 public LocalTree leftTree;
 public LocalTree rightTree;

 /**
  Enter the index here
*/
 public static int NTHSMALLEST = 3;
 public LocalTree(int i) {
  val = i;
 }
 public void add(int i){
  LocalTree temp = this;
  LocalTree parent = this;
  while (temp != null){
   parent = temp;
   if ( i > temp.val){
    temp = temp.rightTree;
   
   }else{
    temp = temp.leftTree;
   }
  }
  temp  = new LocalTree(i);
  if ( i > parent.val){
   parent.rightTree = temp;
  }else{
   parent.leftTree = temp;
  }
 }

 public static void normalTraverse(LocalTree root){
  if (root == null)
   return;
  normalTraverse (root.leftTree);
  System.out.println(root.val);
  normalTraverse (root.rightTree);
 }



 public static int nthSmallest(LocalTree root, int count){
  if (root == null){
   return count;
  }
 
  count = nthSmallest(root.leftTree, count) + 1;
 
 
  if (count == NTHSMALLEST){
   System.out.println("nth smalles element " + root.val);
   System.exit(0);
  }
 
  count =  nthSmallest(root.rightTree, count) ;
 
 
  return count;
 }
}

public class TreePrint {

 public static void main(String[] args) {
       
  LocalTree l = new LocalTree(100);
  l.add(150);
  l.add(125);l.add(124);l.add(126);l.add(175);l.add(170);l.add(180);

  StringBuffer s1 = new StringBuffer();
  StringBuffer s2 = new StringBuffer();
  LocalTree.nthSmallest(l, 0);
 }

}

Print Tree elements in zig-zag order

Ex: if tree is
                         100
                80                 150
                            125                175
                    124          126    170     180        

For the above tree following should be the output
100
150  80
125   175
180   170  126 124

Code:

import java.util.Vector;

class LocalTree{
    public int val;
    public LocalTree leftTree;
    public LocalTree rightTree;

    public int leftChildCount = -1;
    public int rightChildCount = -1;
    public static int maxDistance = -1;
    public static LocalTree maxDistanceRoot = null;

   public static int NTHSMALLEST = 4;
   public LocalTree(int i) {
       val = i;
   }

   public void add(int i){
      LocalTree temp = this;
      LocalTree parent = this;
      while (temp != null){
           parent = temp;
           if ( i > temp.val){
             temp = temp.rightTree;
           }else{
             temp = temp.leftTree;
          }
      }
      temp  = new LocalTree(i);
      if ( i > parent.val){
         parent.rightTree = temp;
      }else{
        parent.leftTree = temp;
     }
 }
 public static void zigZagPrint(LocalTree root){
  if (root == null)
   return;
 // System.out.println(root.val);
  Vector stack1 = new Vector();
  Vector stack2 = new Vector();
 
  //stack1.add(root.rightTree);
  stack2.add(root);
  boolean condition = true;
  while (condition ){
   while (stack1.size() != 0){
      LocalTree currentElem = (LocalTree)stack1.remove(stack1.size()-1);
      System.out.print(currentElem.val + " ");
    
      if (currentElem.rightTree != null)
             stack2.add(currentElem.rightTree);
      if (currentElem.leftTree != null)
            stack2.add(currentElem.leftTree);
   }

   System.out.println();
   while(stack2.size() != 0){
     LocalTree currentElem = (LocalTree)stack2.remove(stack2.size()-1);
    System.out.print(currentElem.val + " ");
     if (currentElem.leftTree != null)
        stack1.add(currentElem.leftTree);
    if (currentElem.rightTree != null)
       stack1.add(currentElem.rightTree);
   }

   System.out.println();
   if (stack1.size() == 0 && stack2.size() == 0)
    condition = false;
  }
 
 }



}

public class TreePrint {

 public static void main(String[] args) {
  LocalTree l = new LocalTree(100);
  l.add(150);
  l.add(80);
  
  l.add(125);
  l.add(124);
  l.add(126);
  l.add(175);
  l.add(170);
  l.add(180);
  LocalTree.zigZagPrint(l);

 }

}

Check whether subsequence sum is equal to given number


public class SubSeqSum {
    static int arr[] = {1, 4, 10, 20, 34};
   static int elemSum = 25;
   Object o;
   public static void main(String[] args) {
      // SubSeqSum.testDynamicApproach();
       boolean found = SubSeqSum.testUsingRecursiveApproach(0, elemSum);
      if (found){
                 System.out.println("Sum FOund");
       }else{
                System.out.println("sum not found");
       }
 }
 private static boolean testUsingRecursiveApproach(int index,int elemSum) {
    if (elemSum == 0){
        return true;
    }
    if ( ((index+1) > arr.length) || (elemSum <0) )
           return false;
 
 
  if ( testUsingRecursiveApproach((index+1), elemSum - arr[index]) || testUsingRecursiveApproach((index+1), elemSum) )
         return true;
  else
         return false;
 
 }
 private static void testDynamicApproach() {
   int temp[] = new int[arr.length];
 
   for (int i=0;i<arr.length;i++){
       for (int j=0;j<(i+1);j++){
            temp[j] = temp[j] + arr[i];
            if (temp[j] == elemSum){
                 System.out.println("Sum foound");
            }
        }
    }

 
 }
}

 

Print Valid bracket pattern of given length

import java.util.HashSet;
import java.util.Set;

public class Paren {
    static Set<String> h = new HashSet();

   static void generateComb(StringBuffer str, int permToGen){
       if (permToGen == 0){
               h.add(str.toString());
              return;
        }
 
       for (int i=0;i<str.length();i++){
            StringBuffer s = new StringBuffer(str);
            s = s.insert(i, "()");
           generateComb(s, permToGen-1);
       }
 
 }


 public static void main(String[] args) {
     StringBuffer str = new StringBuffer("()");
     int permToGen = 3;
     generateComb(str, permToGen-1);
 
      System.out.println("Set lenght " + h.size());
 }
}

Program of combinations to climb steps

Problem Statement: Suppose a person is climbing stairs with "n" steps and at a time a person can climb "x"steps. So what are the different permutations of climbing this stairs

Ex: If there are 5 steps in stair and at a time person can climb maximum 3 steps. Then following are the different permutations

11111
1112
1121
113
1211
122
131
2111
212
221
23
311
32

Code:

public class Steps {
   
  public void findStep(int steps, String buf){
  
   if (steps == 0){
    System.out.println(buf);
    return;
   }else{
    if (steps == 1){
     findStep(steps-1, buf + "1");
    }
    if (steps == 2){
     findStep(steps-1, buf + "1");
     findStep(steps-2, buf + "2");
    }
   
    if (steps >= 3){
     findStep(steps-1, buf + "1");
     findStep(steps-2, buf + "2");
     findStep(steps-3, buf + "3");
    }
   
   
   }
 
 }
 
  public static void main(String[] args) {
   String buf = new String();
   Steps s = new Steps();
   s.findStep(5, buf);
  }
}

I'll try to improve this program and generalize it in next posts

Arrange number in array such that positive and negative occur alternate

Problem Statement: Arrange number in array such that positive and negative occur alternately. And continuous numbers positive or negative should be summed up


public class Consolidate {
    static int arr[] = {3, -6, 10, 4, 7, -6, -5, 4, -1};

 public static void main(String[] args) {
  int j = 0;
  int ord = (arr[0] > 0)? 0 : 1;
  int sum = 0;
  for (int i=0;i<arr.length;i++){
   if ( (arr[i] >0 && ord == 0) || (arr[i] < 0 && ord == 1)){
    sum = sum + arr[i];
   }else{
    ord = (ord+1)%2;
    arr[j++] = sum;
    sum = arr[i];
   }
  }
  arr[j++]= sum;
  for (int i=0;i<j;i++){
   System.out.println(arr[i] + " ");
  }
 }

}

Wednesday, April 30, 2014

Reverse a string without reversing the words and trim extra space

Input: "   MY NAME IS      ABHINAV   "
Output: "ABHINAV IS NAME MY"

public class ReverseString {
    static String str = "   MY NAME IS      ABHINAV   ";
    static char s[]  = str.toCharArray();

   static void reverse( int startIndex, int endIndex){
 
     for(int i=startIndex;i<(endIndex/2);i++){
       char c = s[i];
       s[i] = s[endIndex-i-1];
       s[endIndex-i-1] = c;
     }
 }

 static int leadingSpaceIndex(){
    int i = 0;
    while (s[i++] == ' ');
    return (i-1);
 }

static int trailingSpaceIndex(){
  int i = s.length;
  while (s[--i] == ' ');
  return i;
}

static int trim(int leadingSpace,int  trailingSpace){
  int place = leadingSpace;
  for (int i=leadingSpace;i<(trailingSpace+1);i++){
   if (s[i] != ' '){
     s[i-place] = s[i];
     s[i] = ' ';
   }else{
    while (s[i+1] == ' '){
      i = i+1;
      place++;
    }
   }
  }
  return 0;
 }
 public static void main(String args[]){
 
  
  int leadingIndex = leadingSpaceIndex();
  int trailingIndex = trailingSpaceIndex();
 
  reverse(0, s.length);
 
 
  int i = 0, index =0;
 
  while ( i < s.length){
   if (s[i] == ' ' || s[i] == '\0'){
    reverse( index, (index+i));
    index = i+1;
   }
   i++;
  
  }
//  int leadingIndex = leadingSpaceIndex();
  System.out.println("pre final string "+ new String(s));
  trim(leadingIndex, trailingIndex);
  System.out.println("final string "+ new String(s));
  
 }
}

Reverse a linked list from a given location

Suppose you have following list
1->2->3->4->5

if add you are asked to reverse the list from 3 node, then output sequence would be
1->2->5->4->3


 if add you are asked to reverse the list from 2 node, then output sequence would be
1->5->4->3->2

Code


class linkedList{
    private linkedList next;
 private int val;

 public linkedList(int x){
  val = x;
 }

 public void addToList(linkedList n){
  linkedList templinkedList = this;
  while (templinkedList.next != null){
   templinkedList = templinkedList.next;
  }
  templinkedList.next = n;
 }

 public void print(){
  linkedList templinkedList = this;
  while (templinkedList != null){
   System.out.println(templinkedList.val);
   templinkedList = templinkedList.next;
  
  }
 }
 public linkedList reverseA(int x) {
  x =x-1;
  boolean firstNode = true;
  linkedList init = this;
  linkedList root = this;
  linkedList current = root;
  linkedList forward;
  linkedList chainList = null;
  int i = 0;
  while ( current.next!= null){
   if ( i == x){
    i =0;
    if (firstNode == true){
     init = root;
     firstNode = false;
    }
    chainList = current;
    root = current.next;
    current = root;
   
   
   }
  
   i++;
   forward = current.next;
  
   current.next = forward.next;
  
   if (firstNode){
    forward.next = root;
    root = forward;
   }
   else{
    forward.next = chainList.next;
    chainList.next = forward;
   }
  
  }
  if ( x== -1)
   return root;
  return init;
 }
 public void reverseFromMid(linkedList root){
 // linkedList init = root.next;
  linkedList current = root.next;
  linkedList forward = current.next;
 
  while (forward.next != null){
   current.next = forward.next;
   forward.next = root.next;
   root.next = forward;
   forward = current.next;
  }
 
  int tempVal = forward.val;
  forward.val = root.val;
  root.val = tempVal;
 }
}
public class RevListInParts {
 public static void main(String[] args) {
  linkedList n = new linkedList(1);
  linkedList n2 = new linkedList(2);
  linkedList n3 = new linkedList(3);
  linkedList n4 = new linkedList(4);
  linkedList n5 = new linkedList(5);
  linkedList n6 = new linkedList(6);
  linkedList n7 = new linkedList(7);
  linkedList n8 = new linkedList(8);
  n.addToList(n2);
  n.addToList(n3);
  n.addToList(n4);
  n.addToList(n5);
  n.addToList(n6);
  n.addToList(n7);
  n.addToList(n8);
  n.print();
 // n = n.reverse(3);
  n.reverseFromMid(n2);
  System.out.println("Post reverse");
  n.print();
 
 }
}
 

Code: What are the various combinations of quarters, dimes, fives and cents to make x cents

Suppose one has 35 cents then what are the various combinations of quarters, dimes, cents and fives which can make  this amount.

For ex:
1 quarter, 1 dimes
1 quarter, 2 fives
1 quarter, 1 fives, 5 cents
.......

Following is the program which generates these combinations:


import java.util.HashSet;
import java.util.Set;

public class Cents {
   public Set<String> s = new HashSet<String>();
   public void getChange(int nos, int qua, int dimes, int fives, int cents){
         if ( nos == 0){
            s.add("" + qua + "," + dimes + "," + fives + "," + cents);
           return;
         }
         if (nos < 0){
               return;
         }

         if ( (nos-25) >= 0)
               getChange((nos-25), (qua+1), dimes, fives, cents);

          if ( (nos-10) >= 0)
              getChange((nos-10), qua, (dimes+1), fives, cents);

         if ( (nos-5) >= 0)
               getChange((nos-5), qua, dimes, (fives+ 1), cents);

         if ( (nos-1) > 0)
              getChange((nos-1), qua, dimes, fives, (cents+ 1));

   }


 public static void main(String[] args) {
   Cents c = new Cents();
  c.getChange(35, 0, 0 , 0 , 0);

  for (String s : c.s){
   System.out.println(s);
  }

 }
}

Java Program to generate permutations of a string

If one wants to generate various possible permutations ( order  matters) from a string.
Ex:
For input {'a','b'},  output would be 'a','b','ab','ba'
For input {'a','b','c'} , output would be 'a','b','c','ac','ab','bc','ac', 'abc'


import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.Vector;

public class AllPerm {
        static String originalString = "abc";
        static Vector<String> stringSet = new Vector<String>();
        static void addCharAt(int index){
             int vecSize = stringSet.size();
              for (int i=0;i<vecSize;i++){
                 StringBuffer element = new StringBuffer(stringSet.get(i));
                 for (int j=0;j<(element.length()+1);j++){
                       element.insert(j, originalString.charAt(index));
                       stringSet.add(element.toString());
                        element.deleteCharAt(j);
               }
             }
       }

      public static void main(String[] args) {
 
              stringSet.add("");
 
              for (int i=0;i<originalString.length();i++){
                 addCharAt(i);
              }
 
              for (int i=0;i<stringSet.size() ;i++){
                  System.out.println(i + " " +  stringSet.get(i));
              }
 }
    }

Java Program to generate combination

If one wants to generate various possible combinations ( order doesn't matter) from char array.
Ex:
For input {'a','b'},  output would be 'a','b','ab'
For input {'a','b','c'} , output would be 'a','b','c','ac','ab','bc','ac', 'abc'

import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import java.util.Vector;

public class AllComb {
          static char arr[] = {'a','b','c','d'};
          public static void main(String args[]) {
                Vector<String> wordSet = new Vector<String>();
                wordSet.add("");
                for (int i=0;i<arr.length;i++){
                        int vectorSize = wordSet.size();
                        for (int index=0;index<vectorSize;index++){
                                String str = wordSet.get(index) + arr[i];
                                wordSet.add(str);
                        }
  
                   }
 
               int vectorSize = wordSet.size();
              for (int index=0;index<vectorSize;index++){
                   System.out.println( wordSet.get(index));
              }
        }
}

Thursday, April 24, 2014

How to back up & restore postgres database?

pg_dump is the functionality  provided by Postgres to take the backup of database

Usage:
If the intent is create database while restoring 
pg_dump -f <fileName> -U <user name> --create <databaseName>

Tuesday, April 22, 2014

Design Implication: Class with static methods VS Singleton

Question: Functionality of a singleton can also by having a class in which all methods are static, then why should one choose singleton?

Answer:  When choosing any approach one should see the impact this design has in terms on maintainability.

Following are the reasons for which one should not choose a class with static methods:

1. Encapsulation: When one uses a class with static methods then encapsulation is broken.
2. Inheritance: A class with static method though can be inherited but parent class reference cannot be used to invoke child class methods
3. Extensibility: If one wants to change the behavior and move away from the singleton behavior, it is a problem if one has the class with static methods

When use class with static methods:
1. Utility class: When a class is a utility class and doesn't need any instance variables
2. Design evolution: If the design is fixed and there is no room for improvement by inheritance

Some of the common classes with static methods in java are:
1. Math