Tuesday, April 26, 2011

StudyNote--X--JAVA--I

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package trans;
import java.io.*;
import java.util.regex.*;
import java.util.LinkedList;
import java.lang.Thread.*;
import java.util.concurrent.locks.ReentrantLock;
/**
 *
 * @author sc
 */
//this is a stack which length is only 2
 class ProductTable {
//define a LinkedList and then will be used as the stac
    public LinkedList <String>products = new LinkedList<String>();
//this is the function to add data into LinkedList,synchronized is the key word used with lock
    public synchronized void addProduct(String context){
      //if the stack is full,the producer should wait until there is a space
        while(this.products.size()>=2){
            try {
                wait();
            }
            catch(InterruptedException e){
                e.printStackTrace();
            }
        }
        this.products.addLast(context);
       //tell other producer thread they can use this stack now
        this.notifyAll();
    }
//this function is to get data from the stack
    public synchronized String getProduct() {
     //if this stack is empty,consumer should wait until some producer filled it
        while(this.products.size()<= 0){
            try {
                wait();
            }
            catch(InterruptedException e){
                e.printStackTrace();
            }
        }
        String context =this.products.removeFirst();
        this.notifyAll();//tell other consumer thread they can use this stack now
        return context;
    }
}
//this is producer function that implement Runnable function
 class Producer implements Runnable {
    private ProductTable productTable;
    private String context;
    private File file;
    private BufferedReader input;
    //initialize this producer thread 
    public Producer(ProductTable productTable,String filename) {
        this.productTable = productTable;
        this.file=new File(filename);//bind the file with filename
        if(this.file.exists()){
            try{
                this.input = new BufferedReader(new FileReader(this.file));
            }
           //this is required to catch IOException
            catch(IOException ioException){
                ioException.printStackTrace();
            }
        }
        else{
            System.err.println("Does not exist!");
        }
    }
    @Override//override the Runnable run() function
    public void run(){
        try{
        //each time read one line from the file
             while((this.context = this.input.readLine())!=null){
                this.productTable.addProduct(context);
            }
        }catch(Exception e){
            e.printStackTrace();
        }finally{
            try{
                this.input.close();//when all data is read,close the file
               //send a signal to consumer to tell it the producer is terminated 
                this.productTable.addProduct("OVER");
            }
            catch(IOException ioException){
                ioException.printStackTrace();
            }
        }
    }
}
//this is the consumer thread class
class consumerDoc implements Runnable{
    private ProductTable productTable;
    public StringBuffer[] buffer;
    private String str;
    private String regex;
    private Pattern p;
    private Matcher m;
    public int count=0;
    public consumerDoc(ProductTable productTable){
        this.productTable = productTable;
        this.str=null;
       //this is the pattern match,regression
        this.regex="(.*?)(, size)\\ (.+?)\\ [(^](.*?)\\ words(.*?)\\:\\ (.*)";
        this.p= Pattern.compile(this.regex);
    }
    @Override
    public void run(){
        try{
            while(true){
                try{
                    Thread.sleep(1);//thread sleep
                    this.str=productTable.getProduct();//get a data line from the stack
                   //if meets "OVER" means producer is terminated and this is the end of the stack,consumer can terminated itself
                    if(this.str.equals("OVER")){
                        productTable.addProduct("OVER");//put back to end other threads
                       return;
                    }
                    this.m=this.p.matcher(this.str);
                    while(m.find()){
                         //invoke another method and add the filtered information into output data structure 
                        setValue(m.group(1),m.group(4),m.group(6));
                    }
              //must catch InterruptedException in Runnable run() function
                }catch(InterruptedException e){
                    e.printStackTrace();
                }
            }
        }catch(Exception e){
            e.printStackTrace();
        }
    }
    public void setValue(String A,String B,String C){
    //this is Main static variable to be invoked here
    // not use append twice because of the multi-threads issue
        Main.docBuffer[0].append(m.group(1)+"\n");//size
        Main.docBuffer[1].append(m.group(4)+"\n");//words
        Main.docBuffer[2].append(m.group(6)+"\n");//name
    }
}
//this is main class
public class Main {
   //three static variables to be invoked, as Runnable has no return method,use this way to get Runnable results
    public static LinkedList<String> list = new LinkedList<String>();
    public static StringBuffer[] docBuffer=new StringBuffer[3];
    public static StringBuffer[] featureBuffer=new StringBuffer[2];
    /**
     * @param args the command line arguments
     */
     public static void main(String[] args) throws Exception{
        // TODO code application logic here
        //Use currentTimeMillis() to read current time to measure program proformance
        long s=System.currentTimeMillis();
        for(int i=0;i<3;i++){
            docBuffer[i]=new StringBuffer();
        }
        featureBuffer[0]=new StringBuffer();
        featureBuffer[1]=new StringBuffer();
        ProductTable queueA=new ProductTable();
        Producer producerA=new Producer(queueA, "C:\\DocInfo.txt");
       //start 20 consumer threads to handle the data 
       consumerDoc[] consumerA=new consumerDoc[20];
       for(int i=0;i<20;i++){
            consumerA[i]=new consumerDoc(queueA);//initialize the threads
        }
        Thread threadRQA1=new Thread(producerA);
        Thread[] threadRQA2=new Thread[20];
        for(int i=0;i<20;i++){
            threadRQA2[i]=new Thread(consumerA[i]);
        }
        threadRQA1.start();//start the thread
        for(int i=0;i<20;i++){
            threadRQA2[i].start();
        }
        threadRQA1.join();//only threadRQA1 complete can the rest runs
       for(int i=0;i<20;i++){
            threadRQA2[i].join();
        }//wait for all threads ends
        long f=System.currentTimeMillis();
        System.out.println("Running time is :"+(f-s));
    }
}
**Note to end producer and consumer thread,one should have signal transferred and end according to the signal.Sometimes,multi-threads performance not much better than single thread as frequently access IO would possibly reduce the speed and when use multi-threads, the data order is a big issue that should be considered.

Labels: ,

Wednesday, April 06, 2011

StudyNote--IX--LaTex--III

% THIS IS SIGPROC-SP.TEX - VERSION 3.1
% WORKS WITH V3.2SP OF ACM_PROC_ARTICLE-SP.CLS
% APRIL 2009
%
% It is an example file showing how to use the 'acm_proc_article-sp.cls' V3.2SP
% LaTeX2e document class file for Conference Proceedings submissions.
% ----------------------------------------------------------------------------------------------------------------
% This .tex file (and associated .cls V3.2SP) *DOES NOT* produce:
%       1) The Permission Statement
%       2) The Conference (location) Info information
%       3) The Copyright Line with ACM data
%       4) Page numbering
% ---------------------------------------------------------------------------------------------------------------
% It is an example which *does* use the .bib file (from which the .bbl file
% is produced).
% REMEMBER HOWEVER: After having produced the .bbl file,
% and prior to final submission,
% you need to 'insert'  your .bbl file into your source .tex file so as to provide
% ONE 'self-contained' source file.
%
% Questions regarding SIGS should be sent to
% Adrienne Griscti ---> griscti@acm.org
%
% Questions/suggestions regarding the guidelines, .tex and .cls files, etc. to
% Gerald Murray ---> murray@hq.acm.org
%
% For tracking purposes - this is V3.1SP - APRIL 2009

\documentclass{acm_proc_article-sp}
#use acm_proc_article-sp template
\usepackage[timestamp,first]{draftcopy}
#this package enable a draft watermark on the background of the first page.Also we can use [timestamp,all]
\usepackage{hyperref}
#enable url used as a reference 
\usepackage{natbib}
#enable reference label marked in an order
\draftcopyVersion{Draft}
# use the draft watermark
\begin{document}
\bibliographystyle{unsrt}
#Entries are not ordered alphabetically, but in the order they are first referenced
\title{Active learning for biased training data\titlenote{ This is an honours thesis.}}
#titlenote
\numberofauthors{1}
#The number of authors share the affiliation
\author{
\alignauthor
SKSC\
\affaddr{School}\\
\affaddr{Australia}\\
\email{somewhere@somewhere.com}\\
}
\date{6 April 2011}
\maketitle
\begin{abstract}
This is the abstract
\end{abstract}

\terms{Honours thesis,Algorithms,Machine Learning}
# This is how to use the terms
\keywords{Active Learning,Similarity}
# How to generate the keyword section
\section{Introduction}
A training set is a set of data used in various areas of information science to discover potentially predictive relationships. Training sets are used in artificial intelligence, machine learning, genetic programming, intelligent systems, and statistics.\cite{wikiTraingSet}\\
\begin{itemize}
  \item 
       First Item
  \item
      Second Item
  \item
      Three Item
\end{itemize}
\newpage
#generate a new page manually
\section{background}
\subsection{Active Learning Scenarios}
\subsubsection{Membership query synthesis\cite{angluin1988queries}}
\subsubsection{stream-based selective sampling}
#several subsections and subsubsections inside.
\section{My Work}
   \subsection{Description}
      This is my description.
   \subsection{Evaluation}
      This is my evalution section
   \section{Conclusions}
      This is my conclusion part

\bibliography{reference}
# This should be .bib file name, no extension required
\balancecolumns
# ensure balanced column heights on the last page
\end{document}

Labels: ,

Tuesday, April 05, 2011

StudyNote-VIII--LaTex II

\documentclass[a4paper,12pt]{article}
\usepackage[top=1in, bottom=1in, left=1.25in, right=1.25in]{geometry}
\usepackage{graphicx}
\usepackage{multicol}

\begin{document}
\title{the title}
\date{}
\author{SKSC}
\maketitle

\begin{abstract}
\small{}
This is the abstract of this article.
\end{abstract}
\section{CAFFEINE}
This is the general structure of a CAFFEINE canonical form basis function. 
\begin{figure}[htp]
  \centering #put the image in the center
  \includegraphics[width=0.45\textwidth]{test.eps}
\end{figure}
#This is the way to present picture in LaTex. Latex can receive jpg,png and some other extension files.However the best is always the eps.To convert from jpg/png or other image file into eps, we can use bmeps command. bmeps file.jpg file.eps
\begin{figure}[h]
\begin{minipage}[t]{0.45\linewidth}
\centering
\includegraphics[width=\textwidth]{SRG.eps}
\caption{SR system used context-free grammar}
\end{minipage}
\hfill
\begin{minipage}[t]{0.45\linewidth}
\centering
\includegraphics[width=\textwidth]{gr.eps}
\caption{CAFFEINE used grammar}
\end{minipage}
\end{figure}
# this is a way to insert reference
\begin{thebibliography}{Reference}
\bibitem 
JJ Page and William B. Langdon and Riccardo Poli,Smooth Uniform Crossover with Smooth Point Mutation in Genetic Programming: A Preliminary Study,1999,Proceedings of the Second European Workshop on Genetic Programming
\end{thebibliography}
\end{document}

Labels: ,