Thursday, December 19, 2013

Use package members in Java

Summarize what is at http://docs.oracle.com/javase/tutorial/java/package/usepkgs.html to make it simple.

Referring to a Package Member by Its Qualified Name
eg: 
   graphics.Rectangle myRect = new graphics.Rectangle();

Importing a Package Member
eg: 
   import graphics.Rectangle;
   Rectangle myRectangle = new Rectangle();

Importing an Entire Package
eg: 
   import graphics.*;
   Rectangle myRectangle = new Rectangle();

Apparent Hierarchies of Packages
At first, packages appear to be hierarchical, but they are not.
eg:
  java.awt package,
  java.awt.color package,
  java.awt.font package,
   and many others that begin with java.awt.xxxx

However, the java.awt.color package, the java.awt.font package, and other java.awt.xxxx packages are not included in the java.awt package.

The prefix java.awt (the Java Abstract Window Toolkit) is used for a number of related packages to make the relationship evident, but not to show inclusion.


Name Ambiguities
Have to use the member's fully qualified name to indicate which you want.
eg: 
    pkgA.Rectangle rect1;
    pkgB.Rectangle rect2;

The Static Import Statement
Wen to access to static final fields (constants) and static methods from classes, the static import statement gives you a way to import the constants and static methods that you want to use so that you do not need to prefix the name of their class. In short, it's to make static stuff of a class available, it's kind of away from package include we are talking about above.
eg:
   import static java.lang.Math.PI;   //Math is a class & we use its static stuff.
       or as a group:
   import static java.lang.Math.*;

   double r = cos(PI * theta);     // cos() and PI are static stuff of class Math. 




how JDBC works


Sunday, December 15, 2013

static keyword

Basic information about static: 
1. In general, the static keyword means that the entity to which it is applied is available outside any particular instance of the class in which the entity is declared.
2. A static field (member variable of a class) exists once across all instances of the class.
3. A static method may be called from outside the class without first instantiating the class. Such a reference always includes the class name as a qualifier of the method call.
In java, MyClass.f1()
In c++, MyClass::f1()

Here is the understanding about what static means from another angle:
It's used to create utility tools that are ONLY related to the class to which they're applied to. Basically it's a relationship between these static member functions/utility tools and the class.
In theory, you can create these static member variable / member functions anywhere outside the class. However, since those member functions/variables that are declared as static have no use to other components, so it's better to declare them within the class to which they are useful.

One of advantages to doing so is that these static member functions/utility tools have access to the private/protected member variables via entities of the class. Pay attention to "via entities of the class", the reason is these static member functions can only access static member variables. However, they can access private/protected member variables via entities of the class. In contrast, utility tools that are declared outside the class can't.

For example in c++,

static void MyClass::statc_utility_func(MyClass a)
{
  // access private member variable via entity of class. 
   cout << a.data << endl;   // assuming a.data is a private member variable .
}

void outside_utility_func(MyClass a)
{
   cout << a.data << endl;     //  It will be a compile error 'cause it can't access private members.
}

Wednesday, December 11, 2013

vtable : virtual method table

Words from wikipedia about virtual method table: 

A virtual method table, virtual function table, virtual call table, dispatch table, or vtable, is a mechanism used in a programming language to support dynamic dispatch (or run-time method binding).

Suppose a program contains several classes in an inheritance hierarchy: a superclass, Cat, and two subclasses, HouseCat and Lion. Class Cat defines a virtual function named speak, so its subclasses may provide an appropriate implementation (e.g. either meow or roar).

When the program calls the speak method on a Cat pointer (which can point to a Cat class, or any subclass of Cat), the calling code must be able to determine which implementation to call, depending on the actual type of object that is pointed to. Because the type of object pointed to by the Cat pointer is not determined at compile-time, the decision as to which branch to take cannot be decided at compile-time.

There are a variety of different ways to implement such dynamic dispatch, but the vtable (virtual table) solution is especially common among C++ and related languages (such as D and C#).

Here is a graphic description about what this means.



Tuesday, December 10, 2013

lambda functions in python

Lambda functions are kind of anonymous functions. It creates functions on the fly. Instead of defining an entire method for the sole purpose of using it once, you can simply define the function right in the parameter list.
Syntax: 
    lambda [parameter_list] : expression

Two notes I want to emphasize: 
1. Function must return something, which is expression highlighted. It is similar to a regular function that returns.
2. By bracketing the whole thing, you can use it as normal function name. See examples below.

For example:
# A regular function
def incrementor(x):
  return x + 1    

print incrementor(3)
print (lambda x: x+1)(3)     #note 1 in red, note 2 is bold

#define a function sayhello
sayhello = lambda x: 'hello ' + x
print (lambda x: 'hello ' + x)('world')
print sayhello('world')

ls=['232', '32e23', '23423', '2de2']
#define a function f1
f1=lambda x: x.find('e') > -1
print filter(lambda x: (x.find('e') > -1 ), ls)
print filter(f1, ls)

Monday, December 9, 2013

A simple version of linked list in Python

It's quite simple to convert java code to Python code. Basically it's done by removing declaration of objects/variables/functions and keyword new
But there are two things you need to pay attention to when you do the conversion from java to Python.
1. null in java is replaced by None in Python.
2. Indentation in python. I debugged the python code for a while after converting it from a java code, which is posted in another post,  and found out it's due to a simple indentation issue.

Here goes the code:
#!/bin/python

class Node:
  pass

class LinkList:
  def __init__(self):
    self.head = None

  def isEmpty(self):
    return head == None

  def insert(self, a):
    node = Node()
    node.data = a
    node.next = None
    if self.head is None :
      self.head = node
    else:
      cursor = self.head
      last = self.head
      while (cursor is not None):
        if cursor.next is None:
          last = cursor
        cursor = cursor.next
      last.next = node

  def top(self):
    self.head = self.head.next

  def printList(self):
    cursor = self.head
    print  "List:  "
    while (cursor is not None):
      print cursor.data , " "
      cursor = cursor.next
    print

list = LinkList()
list.insert(1)
list.insert(2)
list.insert(3)
list.printList()
list.top()
list.printList()
list.top()
list.printList()

Sunday, December 8, 2013

multiple threads

1. Basic info about thread:
A thread is a thread of execution in a program. The Java Virtual Machine allows an application to have multiple threads of execution running concurrently.

When code running in some thread creates a new Thread object, the new thread has its priority initially set equal to the priority of the creating thread.




  • All Java threads have a priority and the thread with he highest priority is scheduled to run by the JVM.
  • In case two threads have the same priority a FIFO ordering is followed.


  • What I try to say is about word concurrently. When there are multiple threads running concurrently, but at any given single moment, there is only one single thread running. If the threads all have the same priority, then JVM will take turns to run each of them in a super fast fashion, which tricks human being to think they are all running on the same time. In fact, it's like each of them runs for a super short time, then pauses for a few super short times, and then runs again for a super short time, then pauses for a few super short times, and so on.

    2. Basic information about synchronized keyword:
    The synchronized keyword may be applied to a method or statement block and provides protection for critical sections that should only be executed by one thread at a time, which is the one I highlighted above as "any given single moment. 

    Basically what synchronized means is simply to say "I lock something and only I can modify it, once I'm done with it then it's unlocked and somebody else can modify it. "

    Here is a piece of code that has two threads to increment the information 5000 times. Basically one thread locks the information and increments it 5000 times so it increments it from 1 to 5000 in a try,after it's done it releases the information and another thread does the same.
    Without using synchronized keyword to lock the information, two threads will take turn to increment the information, which is not what I want.

    • When applied to a static method, the entire class is locked while the method is being executed by one thread.
    • When applied to an instance method, the instance is locked while being accessed by one thread
    • When applied to an object or array, the object or array is locked while the associated code block is executed by one thread

    Here goes the code:
    public abstract class Multithread {
        private static Integer info = new Integer(0);
        static Thread t1 = new Thread() {
            public void run() {
                synchronized (info) {
                    for (int i = 0; i <= 5000; ++i) {
                        System.out.println("world " + info++ + " "
                                + this.getPriority());
                    }
                }
            }
        };
        static Runnable t2 = new Runnable() {
            public void run() {
                synchronized (info) {
                    for (int i = 0; i <= 5000; ++i) {
                        System.out.println("hello " + info++ + "  "
                                + Thread.currentThread().getPriority());
                    }
                }
            }
        };

        public static void main(String[] args) throws InterruptedException {
            t1.start();
            new Thread(t2).start();
        }
    }


    Output will be like: 
    world 1       5
    ....
    world 4996 5
    world 4997 5
    world 4998 5
    world 4999 5
    world 5000 5       // thread 1 is done with the information and release it.
    hello 5001  5
            // thread 2 picks up the information and increments it.
    hello 5002  5
    ...
    hello 10001 5

    Saturday, December 7, 2013

    which one is bigger: base or derived???

    Let me ask you a question: between an object of a base class and an object of a child class that is derived from the base class, which one is bigger in terms of information?

    Answer is : derived class object. The reason is derived class object contains base class object. It's like a child gets all his/her parents' genes,but at meanwhile he/she gets his/her own stuff.













    Friday, December 6, 2013

    a simple circular linked list in Java















    class Node {
        public int data;
        public Node next;
    }

    class LinkList {
        private Node head;
        // LinkList constructor
        public LinkList() {        head = null;    }

        // Returns true if list is empty
        public boolean isEmpty() {        return head == null;    }

        // Inserts a new Node at the head of the list
        public void insert(int a) {
            Node node = new Node();
            node.data = a;
            node.next = null;
           
            if (head == null)
            {
                head = node;
                node.next = node;  // a snake bites its tail.
            }   
            else
            {
                Node last = getLastNode();
                // insert node at the end of list.
                last.next = node;
                node.next = head; // bite head again.
            }
        }

        // tops the Node at the head of the list
        public void top() {   
            if (!isEmpty())
            {
                Node last = getLastNode();
                if (head == last)
                    head=null;
                else
                {
                    head = head.next;   
                    last.next = head;
                }   
            }
            else
                System.out.println("empty!!!");
        }

        private Node getLastNode()
        {
            // Find the last node.
            Node cursor = head;
            Node last = head;
            while (cursor != null)
            {
                if (cursor.next == head) { last = cursor; break;}
                cursor = cursor.next;
            }
           
            return last;
        }
       
        // Prints list data
        public void printList() {
            Node cursor = head;
            System.out.print("List:  ");
            while (cursor != null) {
                System.out.print(cursor.data + " ");
                cursor = cursor.next;
                if (cursor == head) break;
            }

            System.out.println("");
        }

        public static void main(String[] args) {
            LinkList list = new LinkList();
            list.insert(1);
            list.insert(2);
            list.insert(3);
           
            list.printList();
            list.top();
            list.top();
            list.top();
            list.top();
            list.printList();
            list.insert(3);
            list.insert(2);
            list.insert(3);
            list.printList();
        }
    }

    a simple double linked list in Java






    class Node {
        public int data;
        public Node prev;
        public Node next;
    }

    class LinkList {
        private Node head;

        // LinkList constructor
        public LinkList() {
            head = null;
        }

        // Returns true if list is empty
        public boolean isEmpty() {
            return head == null;
        }

        // Inserts a new Node at the head of the list
        public void insert(int a) {
            Node node = new Node();
            node.data = a;
            node.prev = null;
            node.next = null;
           
            if (head == null)
                head = node;
            else
            {
                // All below stuff is to find the last node. 
                Node cursor=head;
                Node last = head;
                while(cursor != null)
                {
                    if (cursor.next == null) last = cursor;
                    cursor = cursor.next;
                }

                // Now insert new node at the end of list.
                last.next = node;
                node.prev = last;
            }
        }

        // Top the node at the head of the list
        public void top() {
            head = head.next;
            head.prev = null;
        }

        // Prints list data
        public void printList() {
            Node cursor = head;
            System.out.print("List:  ");
            while (cursor != null) {
                System.out.print(cursor.data + " ");
                cursor = cursor.next;
            }
            System.out.println("");
        }
       
        public void printListBackwards() {
            Node cursor=head;
            Node last = head;
            while(cursor != null)
            {
                // Find the last node.
                if (cursor.next == null) last = cursor;
                cursor = cursor.next;
            }
           
            cursor = last;
            System.out.print("List:  ");
            while (cursor != null) {
                System.out.print(cursor.data + " ");
                cursor = cursor.prev;
            }
            System.out.println("");
        }
       
        public static void main(String[] args) {
            LinkList list = new LinkList();
            list.insert(1);
            list.insert(2);
            list.insert(3);
           
            list.printList();
            list.printListBackwards();
            list.top();
            list.printList();
            list.printListBackwards();
        }
    }

    a simple linked list in java



    class Node {
        public int data;
        public Node next;
    }

    class LinkList {
        private Node head;
        // LinkList constructor
        public LinkList() {        head = null;    }

        // Returns true if list is empty
        public boolean isEmpty() {        return head == null;    }

        // Inserts a new Node at the head of the list
        public void insert(int a) {
            Node node = new Node();
            node.data = a;
            node.next = null;
          
            if (head == null)
                head = node;
            else
            {
               // All stuff below is to find the last node. 
                Node cursor = head;
                Node last = head;
                while (cursor != null)
                {
                    // Find the last node.
                    if (cursor.next == null)
                        last = cursor;
                    cursor = cursor.next;
                }

                // Now insert node at the end of list.
                last.next = node;
            }
        }

        // Top the node at the head of the list
        public void top() {        head = head.next;    }

        // Prints list data
        public void printList() {
            Node cursor = head;
            System.out.print("List:  ");
            while (cursor != null) {
                System.out.print(cursor.data + " ");
                cursor = cursor.next;
            }

            System.out.println("");
        }

        public static void main(String[] args) {
            LinkList list = new LinkList();
            list.insert(1);
            list.insert(2);
            list.insert(3);
          
            list.printList();
            list.top();
            list.top();
            list.printList();
        }
    }

    java inner class

    1. Inner class are helper classes that can access member variables of  something outer (class, function, blocks and expression ) and are for local use only. They are no need to be aware of by outside world. 

    2. Three types of inner classes:
    inner class: inside a class
    local class: inside any block ( expression, statement or block )
    anonymous class: are expressions

    Not matter how you categorize them, basically they are local to something outer.

    I want to talk a little more about anonymous class. Basically it's 2-in-1: implementation + initialization

        interface HelloWorld {
            public void greet();
            public void greetSomeone(String someone);
        }

        HelloWorld frenchGreeting = new HelloWorld() {
            String name = "tout le monde";
            public void greet() {
                greetSomeone("tout le monde");
            }
            public void greetSomeone(String someone) {
               name = someone;
               System.out.println("Salut " + name);
            }
        };
     
    It's the same as 
     class FrenchGreeting implements HelloWorld { same blah above...}
     FrenchGreeting frenchGreeting = new FrenchGreeting();
     
    However, by doing 2-in-1, you not only get rid of creating 
    new class name FrenchGreeting, which is why it's called anonymous 
    class,  but also initialize an object of it. So it's much simpler. 

    java primitive type

    Data Type Default Value (for fields)
    byte  8-bit signed integer 0
    short  16-bit signed integer 0
    int  32-bit signed integer 0
    long 64-bit singed integer 0L
    float 32-bit floating point 0.0f
    double 64-bit floating point 0.0d
    char 16-bit Unicode character '\u0000'
    String (or any object)   null
    boolean  two possible values false




    Literal: To describe something as literal is to say that it is exactly what it seems to be.


    Literals  ( = contants )

    You may have noticed that the new keyword isn't used when initializing a variable of a primitive type. Primitive types are special data types built into the language; they are not objects created from a class. A literal is the source code representation of a fixed value; literals are represented directly in your code without requiring computation. As shown below, it's possible to assign a literal to a variable of a primitive type:
    boolean result = true;
    char capitalC = 'C';
    byte b = 100;
    short s = 10000;
    int i = 100000;
    


    Monday, December 2, 2013

    find with -exec or xargs

    The most basic thing about  find combined with -exec or xargs.


    Basically, find finds a list of something and sends them to a command and let
    the command to deal with them. The point I'm trying to make here is to show you that when find sends these something to a command, it can send them one at a time or all of them at a time. When it does one at a time, it's less efficient but it's safer and more flexible. In the opposite side, when it sends something all at a time, it's more efficient but less flexible.

    Say you have three files: a1,  a2 and a3


    #1.  \; sends parameters to the command following -exec one at a time.
    $ find . -type f -name "a*" -exec echo '{}' \;
    ./a1   -- '{}' represents each of one of them each time echo runs.
    ./a2
    ./a3


    #2.  Both + in -exec and xargs: collects the filenames into groups or sets, and runs the command once per set
    $ find . -type f -name "a*" -exec echo '{}' +
    ./a1 ./a2 ./a3
    $ find . -type f -name "a*" | xargs     
    ./a1 ./a2 ./a3

    Summary: 
    1. -exec normally sends parameters found to command line one at a time with \; at end
    2. -exec can also combine parameters into one line and send it as a whole to command line with + at end, similar to xargs does.
    3. We can add extra parameters to command line when using -exec with \;. However, you are not able to do so using -exec using +, same goes to using xargs.The combined one line parameter is all you got to send to command line when using xargs or -exec with +.
    4. -exec with +   is kind of equal to   xargs

    For example, ~/ is an extra parameter.
    find . -type f -exec cp '{}'  ~/  \;    
    find . -type f -exec cp '{}'  ~/ +      # not working
    find . -type f  | xargs cp ~/              # not working

    Useful tips:
    $ find . -type f   -mmin  -30   # files modified less than 30mins ago.  
    $ find . -type f   -mtime  -3    # files modified less than 3 days ago.