Sunday, 10 April 2016

Expect script to ssh server and do stuff, scp files to server

 #!/usr/bin/expect  
   
 set server [lindex $argv 0];  
 set folder [lindex $argv 1];  
 spawn ssh $server  
 expect "msun@$server's password:"  
 send "$env(MY_PASSWORD)\r"  
 send "mkdir -p /home/$folder\r"  
 send "exit\r"  
 interact  
 spawn bash -c "sudo scp ~/sound/*.* msun@$server:/home/$folder"  
   
 expect {  
  "Password:" {  
   send "$env(MY_PASSWORD)\r"  
   exp_continue  
  }  
  "msun@$server's password:" {  
   send "$env(MY_PASSWORD)\r"  
   exp_continue  
  }  
 }  
 sleep 1  
 exit  

In .bash_profile

 export MY_PASSWORD = "12345"  

File name is sshscp.exp
Usage: ./sshscp.exp serverName folderName

Effective Java Item 41: Overload String.valueOf(char[]) and String.valueOf(Object)

Overloading methods can hurt a lot...

 public class MyOverload {  
   public static void main(String[] args){  
     char[] a = new char[]{'a','b','c'};  
     System.out.println(String.valueOf(a));  
     Object o = new char[]{'a','b','c'};  
     System.out.println(String.valueOf(o));  
   }  
 }  

The result is

 abc  
 [C@194fa3e  

Saturday, 9 April 2016

Effective Java Item 11: Cloneable interface

Cloneable determines the behavior of Object's protected clone implementation: if a class implements Cloneable, Object's clone method returns a field-by-field copy of the object; otherwise it throws CloneNotSupportedException.

What does this sentence mean? Let's look at an example.

 class Dog implements Cloneable{  
   private String name;  
   private int age;  
   
   public Dog(String name, int age) {  
     this.name = name;  
     this.age = age;  
   }  
   
   @Override  
   public String toString() {  
     return "Dog{" +  
         "name='" + name + '\'' +  
         ", age=" + age +  
         '}';  
   }  
   
   @Override  
   public Dog clone() {  
     try {  
       return (Dog) super.clone();  
     } catch (CloneNotSupportedException e) {  
       e.printStackTrace();  
     }  
     return null;  
   }  
 }  
   
 public class MyClone {  
   public static void main(String[] args){  
     Dog dog = new Dog("dog",1);  
     System.out.println(dog.clone());  
   }  
 }  

It runs fine. Now take out the cloneable interface

The result is

 java.lang.CloneNotSupportedException: clone.Dog  
      at java.lang.Object.clone(Native Method)  
      at clone.Dog.clone(MyClone.java:22)  
      at clone.MyClone.main(MyClone.java:33)  
      at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)  
      at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)  
      at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)  
      at java.lang.reflect.Method.invoke(Method.java:498)  
      at com.intellij.rt.execution.application.AppMain.main(AppMain.java:144)  
 null  

This says clone() method does not work without the Cloneable interface.

Effective Java Item 34 Generic T multiple extend

   interface IOperation{}  
   enum Operation implements IOperation{...}    
   private static <T extends Enum<T> & IOperation> void test(Class<T> opSet){  
     for (IOperation op : opSet.getEnumConstants()){  
       System.out.println(op);  
     }  
   }  

Friday, 8 April 2016

Effective Java Item 30,32,33 fromString(), EnumSet and EnumMap

Correct way to implement enum's fromString. We should always use EnumSet and EnumMap because they are faster than HashMap.


 import java.util.*;  
 enum Operation {  
   PLUS("+"), MINUS("-"), TIMES("*"), DIVIDE("/");  
   private static final Map<String, Operation> stringToEnum = new HashMap<>();  
   static {  
     for (Operation op : values()){  
       stringToEnum.put(op.toString(), op);  
     }  
   }  
   private String symbol;  
   Operation(String symbol){  
     this.symbol = symbol;  
   }  
   public String toString(){  
     return symbol;  
   }  
   public static Operation fromString(String symbol){  
     return stringToEnum.get(symbol);  
   }  
 }  
 public class EnumSetMap {  
   public static void main(String[] args){  
     Set<Operation> enumSet = EnumSet.of(Operation.PLUS, Operation.MINUS);  
     Map<Operation, String> enumMap = new EnumMap<>(Operation.class);  
     System.out.println(Operation.fromString("+"));  
   }  
 }  

Effective Java Item 30: Strategy enum pattern

 enum PayrollDay {  
   MONDAY(PayType.WEEKDAY),  
   TUESDAY(PayType.WEEKDAY),  
   WEDNESDAY(PayType.WEEKDAY),  
   THURSDAY(PayType.WEEKDAY),  
   FRIDAY(PayType.WEEKDAY),  
   SATURDAY(PayType.WEEKEND),  
   SUNDAY(PayType.WEEKEND);  
   private final PayType payType;  
   PayrollDay(PayType payType){  
     this.payType = payType;  
   }  
   double pay (double hoursWorked, double payRate){  
     return payType.pay(hoursWorked, payRate);  
   }  
   private enum PayType {  
     WEEKDAY {  
       double overtimePay(double hours, double payRate){  
         return hours <= HOURS_PER_SHIFT ? 0 : (hours - HOURS_PER_SHIFT) * payRate / 2;  
       }  
     },  
     WEEKEND {  
       double overtimePay(double hours, double payRate){  
         return hours * payRate / 2;  
       }  
     };  
     private static final int HOURS_PER_SHIFT = 8;  
     abstract double overtimePay(double hours, double payRate);  
     double pay(double hoursWorked, double payRate){  
       double basePay = hoursWorked * payRate;  
       return basePay + overtimePay(hoursWorked, payRate);  
     }  
   }  
 }  
 public class StrategyEnumPattern{  
   public static void main(String[] args){  
     for (PayrollDay payrollDay : PayrollDay.values()){  
       System.out.println(payrollDay + " pays " + payrollDay.pay(9, 100));  
     }  
   }  
 }  

Effective Java Item 28: Generics Comparable

What's the benefit of using Comparable<? super T>?

   public static <T extends Comparable<T>> T max1 (List<T> list){  
     //implementation not import  
     return null;  
   }  
   public static <T extends Comparable<? super T>> T max2 (List<T> list){  
     //implementation not import  
     return null;  
   }  

The code below compiles fine.

 class Cat implements Comparable<Cat>{  
   @Override  
   public int compareTo(Cat o) {return 0;}  
   public static void main(String[] args){  
     List<Cat> cats = new ArrayList<>();  
     max1(cats);  
     max2(cats);  
   }  
 }  
However, if we make Cat extend Animal and allow it to compare with other animals....

 class Animal{}  
 class Cat extends Animal implements Comparable<Animal>{  
   @Override  
   public int compareTo(Animal o) {  
     return 0;  
   }  
 }  

max1() doesn't compile any more. Clearly, Comparable<? super T> is more flexible.