2012年12月23日 星期日

Javascript detect browser type

1. Problem:
Sometimes there are different present in the different browser, especially in IE and firefox-like. In this we should get the browser type and do the different method


2. Solution
/* To get the browser type */
function detectIsIEBrowser(){
    var isIE = false;
    var val = navigator.userAgent.toLowerCase();
   
    if(val.indexOf("msie") > -1) {
        isIE = true;
    }
    return isIE;
   
}




Reference
Basic
Advance_PPK

2012年12月22日 星期六

YUM Repository


1.The YUM path
 YUM is a easy management software tools, and mostly the
repository  files will in /etc/yum.repos.d/ and the config file in /etc/yum.conf



2. Useful yum commands
  • yum search tools-name
  • yum install tools-name
  • yum info tools-name
  • yum list installed
  • yum clean


3.  Useful yum repository
in my CentoOS 6.2, I use the following repo
  • CentOS-Base.repo
  • CentOS-Debuginfo.repo
  • CentOS-Media.repo
  • mirrors-rpmforge
  • mirrors-rpmforge-extras
  • mirrors-rpmforge-testing
  • rpmforge.repo

4.  Advance isuuses

2012年12月11日 星期二

CLC Bio about NGS develop



RNA Ploy A tail

From: Ploy(A) Tail

The Poly(A) Tail


As illustrated in the following figure, a generic messenger RNA (mRNA) consists of a number of distinct features, each of which has different functions. The very 5’-end* of the mRNA has a so-called cap (the chemical structure of which is shown in the figure). The most recognizable part of the mRNA is the open-reading frame; this is the series of nucleotides that are “read” by ribosomes to yield the polypeptide that is coded by the mRNA. The open reading frame begins (almost always) with the nucleotide triplet AUG, and ends (after a number of nucleotides that is a multiple of three) with one of the three “stop codons” (UAA, UAG, UGA). At the 3’-end* lies a tract of adenosines – between 90 and 300 or so, at the outset of the life of an mRNA. Finally, the regions of the mRNA between the cap and open reading frame, and between the open reading frame and poly(A) tail, are designated as the 5’- and 3’- untranslated regions, or UTRs.




These different features all interact with other cellular factors; the complete story fills large review volumes, and I won’t bother to try and describe everything. However, it is important for this overview to note that the cap is bound by a so-called cap-binding complex, and the poly(A) tail by a poly(A)-specific RNA binding protein (the poly(A)-binding protein, or PAB). As a single PAB binds only 12 or so nucleotides, the poly(A) tail is “coated” with a number of PAB subunits.

The poly(A) tail functions in two ways. It promotes translation of the mRNA by ribosomes, via a process that is briefly sketched in the following figure. The poly(A) tail, via PAB, actually is “connected” with the cap of the mRNA, via interactions of PAB and the cap-binding complex with other translation initiation factors. This serves to circularize the mRNA-protein complex as shown, and to stabilize the interactions at the 5’-end of the mRNA. The cap-binding complex and other translation initiation factors eventually recruit the small (40S) ribosomal subunit to the vicinity of the cap; this subunit and some of the initiation factors then scan along the mRNA until it finds a suitable AUG triplet, whereupon the 60S ribosomal subunit, initiator tRNAs, and other factors come into play to begin the process of translation.






Remove or unlink the symbolic link

1. What ??
General I often to use the unlink to remove the symbolic links,
but when there are many links file in a folder,
is there any of quick method to do that ??



2. Solution:
A. Write a batch to unlink the symbolic link.

B. Use rm when there are no any physical files in this
rm reference
      If file is a symbolic link, then only the symbolic link is removed.
      The file or directory pointed to by the symbolic link is not affected.
      If any of the intermediate path components of file happens to be a
      symbolic link, then rm follows the symbolic link and removes the file.
Reference: How to Unlink all files in a directory?

2012年12月10日 星期一

illumina experiment

www.perkinelmer.com/pdfs/downloads/CST_RGHS_UK_NGS_Magrini.pdf
1. We sholud the data content Reference: NGS Sample Prep Challenges






















2012年12月8日 星期六

Transcription factor


1. What Transcription factor  ??

In molecular biology and genetics, a transcription factor (sometimes called a sequence-specific DNA-binding factor) is a protein that binds to specific DNA sequences, thereby controlling the flow (or transcription) of genetic information from DNA to mRNA.Transcription factors perform this function alone or with other proteins in a complex, by promoting (as an activator), or blocking (as a repressor) the recruitment of RNA polymerase (the enzyme that performs the transcription of genetic information from DNA to RNA) to specific genes


Referencee:
wiki
Advance

2012年12月6日 星期四

illumin read and phred 33


Illumina reads:
@ + [Read Name] + [Paried_Direction(1/2)]
@HWI-ST688:211:C0F02ACXX:6:1101:12568:67545 2:N:0:AGTCAA
GGGAGGAAGGTGCAGGTCCCTCTGCCCTTTCTGCCAAGGTGCAGAATAGCGCCCGGGCGTGTGTTTTGGCTCCAGAGCAGTTCCACGTGGAGCAACTTCGT
+
BCCFFFFFHHFHHJJJHIJJJJJJJJJIJJJJJJJJIJJ?FGHJGIGIHIGGHIIJHHD>@;AACDDDD:ACDDDDDDDDCDDDEDDBDDBDDBDDDDD@#
@HWI-ST688:211:C0F02ACXX:6:1101:12568:67545 1:N:0:AGTCAA
CCTCCTCACAGATCAAGTACACAACACACACACACACACACACACACACACACGAAGTTGCTCCACGTGGAACTGCTCTGGAACCAAAACACACGCCCGGG
+
CC@FFFFFHHHHHJJJJGIJJJJJIJJJJJIJJJJJJJJJJJIJJJJJJJJIHFEFF?>ACACDCDD?ABDDDCC>ACDCDC(9<ABBBDDDBB>>BB<55

[From http://en.wikipedia.org/wiki/FASTQ_format]

--------------------------------
TruSeq / Quality 101 / Quality Scores Overview
Quality Scores
Quality scores measure the probability that a base is called incorrectly. With SBS technology, each base in a read is assigned a quality score by a phred-like algorithm1,2, similar to that originally developed for Sanger sequencing experiments. The quality score of a given base, Q, is defined by the equation
Q = -10log10(e)
where e is the estimated probability of the base call being wrong. Thus, a higher quality score indicates a smaller probability of error. In the table below, a quality score of 20 represents an error rate of 1 in 100, with a corresponding call accuracy of 99%.
The Relationship Between Quality Score and Base Call Accuracy Quality Score Probability of Incorrect Base Call Inferred Base Call Accuracy
10 (Q10) 1 in 10 90%
20 (Q20) 1 in 100 99%
30 (Q30) 1 in 1000 99.9%
From [http://www.illumina.com/truseq/quality_101/quality_scores.ilmn]

Phred 33:
How are qualities scaled?
Q = ord(q) - 33
q = chr(Q+33)
Q  integer quality
q  character representation
[From http://www.google.com/url?q=http://faculty.washington.edu/jht/GS373_2010/lectures/G373_Shendure_Wk9_Monday_lec24.pdf&sa=U&ei=-4fBULi5DM6WmQWc9YCgDA&ved=0CBcQFjAA&sig2=cLOTAx1vQje5eSYCseyaOg&usg=AFQjCNFWi32peUKA4MaYr6_dEEGgGDD7WA]

2012年12月5日 星期三

Primer and random primer

1. What is a primer?

A primer is a short synthetic oligonucleotide which is used in many molecular techniques from PCR to DNA sequencing.  These primers are designed to have a sequence which is the reverse complement of a region of template or target DNA to which we wish the primer to anneal.   






Reference: What is a primer



2. What is a random primer?? 
Random primers are short segments of single-stranded DNA (ssDNA) called oligonucleotides, or oligos for short. These oligos are only 8 nucleotides long (octamers) and they consist of every possible combination of bases which means there must be 48 = 65,536 different combinations in the mixture. Because every possible hexamer is present, these primers can bind to any section of DNA.


 Reference: random primer




3. More about primer

The only issue worth mentioning now is that three different types of primers can be used (figure 3). 1) 

  • If the mRNA has a poly-A 3' tail, then an oligo-dT primer can be used to prime all mRNAs simultaneously. 2) 
  • If you only wanted to produce cDNA from a subset of all mRNA, then a sequence-specific primer could be used that wil only bind to one mRNA sequence. 3) 
  • If you wanted to produce pieces of cDNA that were scattered all over the mRNA, then you could use a random primer cocktail that would produce cDNA from all mRNAs but the cDNAs would not be full length. 


The major benefits to random priming are the production of shorter cDNA fragments and increasing the probability that 5' ends of the mRNA would be converted to cDNA. Because reverse transcriptase does not usually reach the 5' end of long mRNAs, random primers can be beneficial



Reference: primer and CDNA







CDS and exon relationship

1. what is cds?

the gene coding sequence. and is composed of many exon.




Refernece:
What's the difference between CDS and ORF?

Sensitive and specific Reference

1. 究的實驗分析:敏感性、特殊性

2. P-value 的 Multiple test correction

2012年12月3日 星期一

SAM file format

1. About SAM format
SAM is (Sequence Alignment/Map) format

2. Field introduction
Office File



3. Flag expalin
  read paired
  read mapped in proper pair
  read unmapped
  mate unmapped
  read reverse strand
  mate reverse strand
  first in pair
  second in pair
  not primary alignment
  read fails platform/vendor quality checks
  read is PCR or optical duplicate
Reference: Web SAM Flag



3. Example
 Reference: Detail Example



4. Paired-End Flag
  • 163: read paired, read mapped in proper, mate reverse, second in pair
  • 83  : rad paired, read mapped in proper, read reverse, first in pair
  • 67: read paired, read mapped in proper, fist in parir
  • 131: read paired, read mapped in proper, second in pair 
  • 99: read pair, read mapped in proper, mate reverse, fist in pair
  • 147: read pair, read mapped in proper, read reverse, second in pair


5. Paired insert length calculation
 Reference: Paired insert length





2012年11月29日 星期四

Top Field


1.

VIRT: Total amount of virtual memory used by the process
RES: physical memory which the process has used 
S - Process status - Possible values:
  • R - Running
  • S - Sleeping (may be interrupted)



Reference:
Top_field

2012年11月28日 星期三

illumina rna-seq insert size discussion

1. illumina say insert using 200-500 bp insert. Reference: illumina office

2. Someone say the peak of 180~190bp and (means the inserts shall be 60~70bp, Pair-End). Reference: Seq_Answer

3. a simple clear answer: Reference Biostart

2012年11月27日 星期二

Human sequence reference

1. Current there a human project hg19 and mean the grch37

2. As I found in google the hg19 is equal the grch37,
    but the hg19 is develop in UCSC
    Reference: UCSC hg19, UCSC_hg19_Statistic

3. And grch37 is develop in the genome reference consortium
    Reference: GRCH37

4.  Ensembl is a European project, but the version I didn't clear
        *Ensembl_Human_Annotation Genbank
        *EnsemblJ_Human_Annotation_GTF
        *Ensembl_FTP_Download_include_FASTA

2012年11月26日 星期一

How to set Java memory size

1.  What is the heap function in java ?
Java heap is the heap size allocated to JVM applications which takes care of the new objects being created. If the objects being created exceed the heap size, it will throw an error saying memoryOutof Boun.


2. Problem:
How to set the java memory? to avoid the OutOfMemoryException.
and how much is fit?


3. Solution:
A.How to set java memory
Memory usage = Stack Size + Heap Size + Code Size
  
-Xmsinitial java heap size
-Xmxmaximum java heap size


-Xssset thread stack size




B. How much is fit on your application?
IBM technical report say about head size

Size your Java heap so that your application runs with a minimum heap usage of 40%, and a maximum heap usage of 70%.


Reference:
IBM heap size advice
How to set java memory and debug
Java Memory Talk
what_is_java_heap_size

2012年11月21日 星期三

Boost Error boost/thread/detail/thread.hpp:43: undefined reference to `boost::detail::thread_data_base::~thread_data_base()'

1. Problem:
My boost version is boost_1_49_0, and System is Centos6.3
its build step is following and
it will auto create the library in the /usr/local/lib,
and the include files in /usr/local/include/boost:
  • su -
  • ./bootstrap.sh
  • ./b2
  • ./b2 link=static runtime-link=static stage install

But when I use this information to compile my project,
it is happen the following error
/home/Andy/IBMS/Software/tophat/develop/tophat-2.0.4/src/segment_juncs.cpp:4926: undefined reference to `boost::thread::join()'
/home/Andy/IBMS/Software/tophat/develop/tophat-2.0.4/src/segment_juncs.cpp:4927: undefined reference to `boost::thread::~thread()'
/home/Andy/IBMS/Software/tophat/develop/tophat-2.0.4/src/segment_juncs.cpp:5003: undefined reference to `boost::thread::join()'
/home/Andy/IBMS/Software/tophat/develop/tophat-2.0.4/src/segment_juncs.cpp:5004: undefined reference to `boost::thread::~thread()'


It seems like the thread error.



2. Solution:
I find the google and the key point is
add the
 -lboost_thread-mt
to my gcc,
and then it will pass the problem.



Reference:
Boost Error Undefined


2012年11月16日 星期五

Struts 1.3 redirect function in login page

1. Problem: 

In my application,
I have a login.jsp and
authorize page need the user to login through this login,
then he will get the content of authorize page.

A general method
in struts-config.xml  file
<action path="/login" type="struts.action.LoginAction" scope="session" name="loginForm">

            <forward name="login" path="/login" />   
            <forward name="success" path="/loginSuccessPage" />
</action>
<action path="/anyAuthorizePage" type="struts.action.AuthorizeAction" scope="request" >
            <forward name="login" path="/login" />
            <forward name="anyAuthorizePageSuccess" path="/anyAuthorizePageSuccessPage" />
 </action>


And long as you type following page, and assuming session is timeout
                     http://localhost/anyAuthorizePage
the action is AuthorizeAction and because not login,
user will receive the login.jsp.

But when the user login,
according to the login action,
user will receive the loginSuccessPage,
not user expected the anyAuthorizePageSucccessPage.



2. Solution:

My solution conception is
let client way provide redirect url to LoginAction, 
and LoginAction use this redirect url to perform the redirection page.

The key point in my solution is client way, therefore I don't handle any session  this in anyAuthorizeAction. I only focus on the client way and LoginAction.
Another reason why I solve in client way is me observe that the



3. Example:

The technique contains the javascript to get the browseURL, struts action of redirect attribute. The following simple step is following:

A. Adding the webbrowse url filed on login.jsp

 
<script type="text/javascript">

/*將 user browserID */
function loginOnload() {
    writeBrowseUrlToForms();
}


/* 寫入 browse URL 到欄位中 */
function writeBrowseUrlToForms() {
   
    // 取得所有表單的 form, 因為 tagname 會回傳 array 
    elementsForms = document.getElementsByTagName("form");
   
    // 進入個別 form 取得個別欄位
    for (var intCounter = 0; intCounter < elementsForms.length; intCounter++)
    {
           writeBrowseUrlToForm(elementsForms[intCounter]);
    }
}

/*單一 URL */
function writeBrowseUrlToForm(currentForm) {

     var elementsInputs;
     var browseurl = document.location.href;
    
     // 取得所有輸入欄位 input, 但只在意 formposition 與 endPosition 兩個欄位
     elementsInputs = currentForm.getElementsByTagName("input");

     for (var intCounter = 0; intCounter < elementsInputs.length; intCounter++)
     {
           var inputFieldName = elementsInputs[intCounter].name;
           var inputFieldValue = elementsInputs[intCounter].value;
          
           if (inputFieldName == "browseurl")
           {
              elementsInputs[intCounter].value = browseurl;
           }
     }

}

/* 加入 Layout Onload 到事件中*/
// Namespace of login content
var login;

if (!login) {
    login = {};
}

login.oldOnload = window.onload || function() {};
window.onload = function () {
    login.oldOnload();
    loginOnload();
};

</script>
<html:form action="/login" >

<%-- hidden the url redirect, and on submit send to user --%>
<table id="login_table" style="border-collapse: collapse">
      
    <tr>
    <td>User Name</td>
    <td><html:text name="loginForm" property="name" size="20" /></td>
    </tr>
    
    <tr>
    <td>Password</td>
    <td> <html:password name="loginForm" property="password" size="21" /></td>
    </tr>
    
        
    <%-- Hiden redirect page --%>
    <tr>
     <html:hidden property="browseurl" value=""/>
    </tr>
    
    <tr> <td colspan="2" align="right">    <html:submit value="login"/></td>
    </tr>
    
    
    
</table>

</html:form>



 B. And LoginAction adding sendRedirect() method in LoginAction

public ActionForward execute(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response) {
 
if (verifyUser(username, password)) {
           
          ....
       
            // 如果需要重導入功能
            ActionRedirect redirect = null;
            if ( (redirect = sendRedirect(request, loginForm.getBrowseurl(), mapping)) != null) {
                return redirect;
            }else {
                return mapping.findForward("success");
            }
        } 

}

}


    protected ActionRedirect sendRedirect(HttpServletRequest req, String needLoginPageURL, ActionMapping mapping) {
        ActionRedirect redirect = null;
       
        if (req == null || needLoginPageURL == null || needLoginPageURL.equals("")) {
            return redirect;
        }
        logger.info(needLoginPageURL);
       
        // 比對是否相同 host not by hack
         if (equalsHost(getThisFormUrl(req), needLoginPageURL)) {
           
             String contextPath = getContextPath(needLoginPageURL);
           
             if (contextPath != null) {
               
                 // 手動加入想要 login 內容
                 if (contextPath.contains("/authorizePage.do")) {
                     redirect = new ActionRedirect(mapping.findForward("
authorizePage"));
                 }
               
             } // end if path
         }
        return redirect;
    }



/** 需要 URL 網址 */
    protected String getThisFormUrl(HttpServletRequest req) {
        String reqUrl = req.getRequestURL().toString();
        String queryString = req.getQueryString();  
        if (queryString != null) {
            reqUrl += "?"+queryString;
        }
        return reqUrl;
    }



C. LoginForm.class add the browseurl

public class LoginForm extends ActionForm{
    private static final long serialVersionUID = 1L;
    private String name;
    private String password;
    private String browseurl;        // 如果需要從新導入可以使用
   
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }
    public String getBrowseurl() {
        return browseurl;
    }
    public void setBrowseurl(String browseurl) {
        this.browseurl = browseurl;
    }
     
}

D. Setting the struts.xml Action
<action path="/login" type="struts.action.LoginAction" scope="session" name="loginForm">
            <forward name="login" path="/login" />   
            <forward name="success" path="/successLogin" />           
           <forward name="authorizePage" path="/authorizePaget.do" redirect="true" />
</action>



Reference
Struts_Action_Redirct
GET_Browse_URL
web_GET_URL

2012年11月13日 星期二

JSP or Struts simply show error page and exception inforamtion

1. Problem
In develop the web application by struts or jsp,
it has the requirement to show the error message,
but use the struts default exception handler method is complex to show data,
because it involve the bean, action setting for exception type.

I study the inline error page show and share it.


2. Solution
I use simple jsp handle object,
pageContext.exception and
pageContext.errorData


3. Example

Notice: if you use struts,
don't write the <global-exceptions> tag,
we will transfer the exception to the tomcat handle

A. in web.xml write
=============================================
<error-page>
        <error-code>404</error-code>
        <location>/error.jsp</location>
</error-page>
 
<error-page>
     <exception-type>java.lang.Throwable</exception-type>
      <location>/error.jsp</location>
</error-page>
=============================================



B. error.jsp
=============================================

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@page isErrorPage="true" %>
<html>
<head>
<title>Error Page</title>

 <style type="text/css">
h2{background:darkblue;color:white}
h3{background:darkblue;color:white}
.style1 {
    color: #66CCFF;
    font-size: x-large;
    font-weight: bold;
}
</style>


</head>
<body>
<span class="style1">Oops...</span><br>
<div>
A system error has occured. <br>
If the
problem persists, please report this information to the System Administrator.
</div>

<br/>
[<a href="./index.jsp">GoGack to index</a>]
[<a href="javascript:showDetails()">Show details</a> ]
[<a href="javascript:hideDetails()">Hide details</a> ]
<br/>


<table id="showDetailsLinkDiv" style="{display:none}"   cellspacing="0" width="100%" border="1">
 
    <tr valign="top">
        <td width="40%"><b>Error:</b></td>
        <td>${pageContext.exception}</td>
    </tr>
 
    <tr valign="top">
        <td><b>URI:</b></td>
        <td>${pageContext.errorData.requestURI}</td>
    </tr>
 
    <tr valign="top">
        <td><b>Status code:</b></td>
        <td>${pageContext.errorData.statusCode}</td>
    </tr>
 
    <tr valign="top">
    <td><b>Stack trace:</b></td>
    <td>
        <c:forEach var="trace"
                 items="${pageContext.exception.stackTrace}">
        <p>${trace}</p>
    </c:forEach>
    </td>
    </tr>

</table>

<script language="javascript">
   function showDetails() {
     document.getElementById("showDetailsLinkDiv").style.display = "inline";
   }
   function hideDetails() {
     document.getElementById("showDetailsLinkDiv").style.display = "none";
   }
</script>
</body>
</html>


=============================================


Reference:
http://geekexplains.blogspot.tw/2008/06/errorexception-handling-in-jsp-using.html

2012年11月12日 星期一

Eclipse problem: import ClassName cannot be resolved.

1. Problem:
  When I write a java web project a long times, and use the subversion case,
  It appear the import ClassName cannot be resolved. problem

2. Solution:
    I don't know the real reason. But I solve it by
    choose the project item of menu -> Clean function


Reference:
Many other solution
May be the reason

Javascript search string

1. Problem:
   There are kind of search string function in javascript. At first
   we can attract by  search() method, but when we use it to search dot "."  
   information such as judge the upload file is ".jpeg" suffix,  it will return 0.


2. Why:
   Because argument of search()  is regular expression, I avoid it and use
   indexOf() method replace it. And it will work correct


3. Example:
strA = "myPic.jpeg"
strA.search(".");
result: 0
strA.indexOf(".");
result: 5



Reference:
Like problem
string method

2012年11月8日 星期四

Eclispe change webapp name

Motivation. There are some step you can change your web app in eclispe

Step:
 1. open project
 2. click the mouse right button and choose the properties in the finally button
 3. choose  web project setting
 4. type the new in context root
 5. stop the server and remove the old project
 6. because the eclipse will change the web.xml file, and add the tag in   web.xml, so 1. you can copy old web.xml to this.  2. or delete this tag 


Encourage problem but can solve by my step especially the step 6 is important:
a. problem {java.lang.IllegalArgumentException: Can't convert}
b. 404 not find new appname


Eclipse store your  web application position:
/home/${yourname}/workspace2/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps


Reference:
How to change eclipse webapp name?
How to fix the error of java.lang.IllegalArgumentException: Can't convert






2012年11月6日 星期二

Get DIV Height

1 Problem:
   Sometimes you should make the layout in html using the css,
   and first should get the height from two div,
   the often use js code offsetHeight property,
   but it can't the real the height??


2. Reason:
    Because the offsetHeight didn't contain the margin height
     [offsetHeight property useage]
  Returns the height of the visible area for an object, in pixels. The value   contains the height with the padding, scrollBar, and the border, but does not include the margin.


3. solution:
    add the maring, but you should reference how to get margin top value

/* Get the div offsetHeight value*/
function getDivHeight(divIdName) {
    var div = document.getElementById(divIdName);
    var divHeight = 0;
   
    if (div){
        divHeight =  div.offsetHeight;
    }
     
    return divHeight;
}

/* I didn't know now to get the css top margin */
function getMainTopMarginHeight() {
    return 70;  /* Fix the content values*/
}


var mainBlockHeightTopMargin =  getDivHeight("main") +  getMainTopMarginHeight();


Reference





2012年11月4日 星期日

GNOME panel restart in centos

GNOME panel restart
1. problem:
sometimes you will unfortunately to close the gnome panel, may be it disappear or delete by you

2. solution:
a. remove the setting files
mv ~/.gnome2 /tmp
mv ~/.gconf /tmp /tmp
b. restart the pc
reboot

Iimage align text bottom

1. Problem: when you bind the text and image, the image can effect the line-height such that the image bottom is high the text bottom.

2. solution: setting the imge css property
 img { vertical-align: middle; }

Refereence:
http://stackoverflow.com/questions/5021676/vertical-align-img-and-text-within-li

Get rid of iframe boarder

1. problem: Although the iframe is not support in future, but some time you can see it. And in IE the iframe will have the border in white color,
you can eliminate it by

2. solution::
frameborder="0"

Multiple method on onload

1. Problem:
we can do something in window.load position such as arrange the layout,
but there are only one method in this window.onload function.


2. Solution
we can store the previous onload method,
and build a new anomyous function which put the old_onload_method,
adding the new load_method.

var oldOnload = window.onload || function () {};
window.onload = function ()
{
    oldOnload();
    // Do Something...
}

Reference:
http://www.jaceju.net/blog/archives/160/

CSS span width

CSS span width

1. problem:
span didn't support the width property in span, or inine tag

2. solution:

span {
  background-color:#ffcc00;
  display:-moz-inline-box;
  display:inline-block;
  width:150px;
}



refrence:
http://www.blabla.cn/css_kb/html_span_width_kb.html

CSS table align

1.  This is a simple solution, but in IE didn't work, you can see the reference for
more technique.

2. Solution::
  .center {
    margin-left:auto; 
    margin-right:auto;
  }


Reference:
http://www.granneman.com/webdev/coding/css/centertables/

2012年11月1日 星期四

Unicode and 全形字元 在 html

1. What is Unicode HTML ?
when you type the other nature characte, you can use unicode in html


2. How to use ?
you type a set of &#AABB;  in this AABB is the unice code number, and &#; is the encolse around the char.


3. Example
,  is the , symbol

Reference:



2012年10月26日 星期五

Bash shell string Manual and simple usage

Introduction:
It is often use the shell variable to do something.


1. Count the length
stringZ=abcABC
${#stringZ}


2. Substring
${stringZ:0}





Reference:
linux_String_Manual





2012年10月25日 星期四

Executable Ant with other other jar in on jar with java.lang.NoClassDefFoundError.

1. Problem:
   How do you execute a jar file, and the other jar as the library in this executable jar? If you execute this executable jar with java -jar this.jar , it will appear a exception with java.lang.NoClassDefFoundError. But Why? it is also happened when you write down the Class-Path property with this reference library's jar in the manifest.mf file.

2. Why:
  Because JVM didn't execute a jar with loadding it's classpath in this jar,
it means even your jar has the lib folder with necessary jar, it didn't work.


3. Solution:
  (A) The simple way is to unzip the lib in jar, and then execute the jar. Because it extract the lib folder in the executable Jar, and use java to execute it, the classpath will reference lib/*, then all class will find in your executeaJar. The condition is you need wirte the reference lib in the manifest.mf.
        unzip canExecute.jar  lib/*;
        java -jar canExecute.jar;

  (B) Eclipse provide a exporting the executable jar function. Its method is include a classloader called JarRsrcLoader, and firstly jvm will load this loader which can load other jar. then load you class. But this method is depends on your IDE.

  (C) A package called One-Jar is support some solution. But it need modify your source call to load other jar file and your manifest.


Reference:
JVM with classloader
JVM with classloader written by caterpillar
JVM with claspath
One-JAR_intro
One_Jar_Office
ClasLoader with third-part
Manifest Intro 
Ant with manifest
Ant with manifest having lib
Ant with manifest_3_relavent the jar_other jar


2012年10月23日 星期二

getResource() function with classpath

1. Why use getResource() function ? 
    Sometimes there is a need for you to get file, but in java the constructor of File class need the absolute path, but it is depends on the machine, it will be a problem when you didn't know the actual parent path in other computer.
    Therefore, you need a method supporting defining the different root staring path, and can get the file. That is the answer of the  getResource function.


2. where is the relevant searching path in getResource()?
  1.  package as the staring path
  2.  classpath as the staring path

3. Example
File file3 = new File(Test.class.getResource("file3.txt").getFile())



Reference:
http://gavin-chen.iteye.com/blog/261151
 

2012年10月12日 星期五

記憶體漏失 Memory Leak

記憶體漏失 Memory Leak


Memory Leak造成的原因是某個被配置(allocated)的記憶體無法在被參照(referenced),也無法被釋放(released);那塊被配置的 記憶體就有如記憶體孤兒般,無法被系統再使用,所以要看一個程式有否Memory Leak,很簡單的方法就是去看作業系統(For standalone application)或是Application Server(如果是Web Application)的實體記憶體使用圖,如果隨著時間增加,記憶體的使用量呈現明顯增加的趨勢,這個程式就極有可能有潛在的Memory Leak問題。
 
Memory Leak在C/C++語言中是很常見的人為過失,因為C/C++並沒有自動Garbage Collector (垃圾收集器)的機制,程式設計師必需在使用完資源後,人為釋放資源。雖然在Java、C#有自動Garbage Collector的機制,Memory Leak的機會大幅下降,但仍然不能完全倖免,只要程式設計師不小心仍然會造成Memory Leak

Reference
 Memory Leak








rhino for print and readln function

1. what is rhino ??


Rhino is a javascript interpreter which use java language to develop.
In rhino you can import java package and call java package.

2. rhino shell

you can enter js, and type help() to view the function.

3. rhino print

can use print("expression") function;

4. rhino input





var readln = (typeof readline === 'function') ? (readline) : (function() {
     importPackage(java.io);
     importPackage(java.lang);
     var stdin = new BufferedReader(new InputStreamReader(System['in']));

     return function() {
         return String(stdin.readLine());  // Read line, 
     };                                    // force to JavaScript String
 }());
 
 
 
Reference:
 input
 output



2012年10月2日 星期二

Newline thransform Linux \n to \r\n



Command:
sed -e 's/$/\r/'



Reference:
http://superuser.com/questions/419865/how-can-i-replace-all-r-n-with-n-using-either-komodo-edit-on-osx-snow-leopard

2012年9月19日 星期三

Program Design and develop

1.  Version control
  • use date to build a version
  • write a version files


2.  Error message
  • use log4j to record different error message


3. Properties files
  • we can set different files such as project or test




log4j


Writing step:

a. write a log4j.properties in your package
{code}
log4j.rootLogger=Info, A1


# A1 is set to be a ConsoleAppender
log4j.appender.A1=org.apache.log4j.ConsoleAppender
log4j.appender.A1.layout=org.apache.log4j.PatternLayout
# %d is date and it's format
# %p is output the log priority info DEBUG INFO WARN ERROR FATAL
# %c is class name
# %l is line position
# %m is the message in contents
# %n is new line
# output format
#[12/09/20 09:26:10][DEBUG][HelloWorld-14] Sample debug message
#[12/09/20 09:26:10][INFO][HelloWorld-15] Sample info message
#[12/09/20 09:26:10][WARN][HelloWorld-16] Sample warn message
log4j.appender.A1.layout.ConversionPattern=[%d{yy/MM/dd HH:mm:ss}][%p][%C-%L] %m%n
{code}

b. write a class call hello word
{code}
import org.apache.log4j.BasicConfigurator;
import org.apache.log4j.Logger;


public class HelloWorld {
   
    static final Logger logger = Logger.getLogger(HelloWorld.class);

    // Reference http://werdna1222coldcodes.blogspot.tw/2009/11/javalog4j.html
    public static void main(String[] args) {
            // 會自動設定
            //BasicConfigurator.configure();
            System.out.println("Start Log4j test");
            logger.debug("Sample debug message");
            logger.info("Sample info message");
            logger.warn("Sample warn message");
            logger.error("Sample error message");
            logger.fatal("Sample fatal message");
    }
    
}

{code}

c. Reference
http://werdna1222coldcodes.blogspot.tw/2009/11/javalog4j.html

AJP Introduction

AJP is the apache and tomcat community method.


English:
http://www.mulesoft.com/tomcat-connector

Chinese:
http://tc.itkee.com/sysapp/detail-16d3.html
http://puremonkey2010.blogspot.tw/2010/09/linux-apachetomcat-tomcat-worker.html

Office:

http://tomcat.apache.org/tomcat-4.0-doc/config/ajp.html

2012年9月13日 星期四

validate From

There we introduce an article which use javascript to check the form field,
it use the tradition methods to get form field elements, and introduce some register event content.

you can see:
http://www.webcredible.co.uk/user-friendly-resources/dom-scripting/validate-forms-javascript.shtml

2012年9月12日 星期三

Javascript interpter in rhino

There are  a javascript interpter on local machine.
It is the rhino, it is written by java, and you can download it, then

type
[]java -jar js.jar JSFileName

will show the result,

js.sh
{code}
#!/bin/bash
RLWRAP='rlwrap -C js';
exec $RLWRAP java -jar ~/IBMS/Program/java/lib/js.jar "$@";

{code}


Rhino Download:
https://developer.mozilla.org/en-US/docs/Rhino/Download_Rhino?redirectlocale=en-US&redirectslug=RhinoDownload


rlwrap download: http://utopia.knoware.nl/~hlub/uck/rlwrap/

reference:
http://workingrhino.blogspot.tw/2007/10/getting-started.html











2012年9月10日 星期一

極光行動 (Operation Aurora)

http://tw.trendmicro.com/tw/support/tech-support/board/tech/article/20120430133619.html

2012年9月4日 星期二

Java regular express

1. It is a good content in this to explain the java regular express you can reference it

http://www.vogella.com/articles/JavaRegularExpressions/article.html

2012年8月29日 星期三

Strust

 You can see the struts contetnt
1. http://strutstestcase.sourceforge.net/

2012年8月28日 星期二

Struts 1.3 document

 there is the struts document about description the action attribute, 

you can link it to the office document, such as 

<action path="/somepath" 
        type="SomeAction" 
        name="SomeForm" 
        scope="session"
        input="someinput.jsp">

 

struts-config_1_3.dtd

http://struts.apache.org/1.x/struts-core/dtddoc/struts-config_1_3.dtd.html#action-mappings

2012年8月21日 星期二

Hibernate Query Language (HQL)



1. Reference

Sample {{{

Query query = session.createQuery("from Stock where stockCode = :code ");
query.setParameter("code", "7277");
List list = query.list();

}}}
http://www.mkyong.com/hibernate/hibernate-query-examples-hql/



2. office
http://docs.jboss.org/hibernate/orm/3.3/reference/en/html/queryhql.html

FirstHibernateExample

1. You should modify the code
    a. using





Reference:
tutorial in http://www.laliluna.de/articles/java-persistence-hibernate/first-hibernate-example-tutorial.html

Libray in http://www.java4s.com/hibernate/jars-required-for-hibernate-annotations/

and the cglib.jar




2012年8月9日 星期四

Eclispe Folder, source folder


http://www.cnblogs.com/slowly-keeping/archive/2012/04/23/2466054.html

2012年8月8日 星期三

myEclispe Setting memroy

set the MyEclipse memory for -vmargs
-Xmx768m
-XX:MaxPermSize=384m
-XX:ReservedCodeCacheSize=64m



Reference :http://www.myeclipseide.com/PNphpBB2-printview-t-26337-start-0.html








2012年7月27日 星期五

Python print exception message

        try:
                mainFUN()
        except :
                print 'Exception occur.. '
                #-- MyDebug
                import sys
                import traceback
                print "Unexpected error:", sys.exc_info()[0], sys.exc_info()[1], sys.exc_info()[2]

2012年7月26日 星期四

Python Debug


 Execute command:

python -m pdb foo.py


A. next line
n

B. Set the break point
 b 3


C. run to break line
r










Reference:
http://fcamel-life.blogspot.tw/2011/07/python-debug.html

2012年7月25日 星期三

Python uninstall

python setup.py install --record files.txt And when you find out the list is complete: cat files.txt | xargs rm -rf


Reference: http://stackoverflow.com/questions/1550226/python-setup-py-uninstall

2012年7月23日 星期一

Eclispe HightLight Pattern

ATL + SHIFT + O

Reference: http://stackoverflow.com/questions/6148481/eclipse-with-java-wont-display-matching-variables

2012年7月19日 星期四

Move File Name By Speceial Format

mv $file ${file%.snp}_snp.txt

Zip Include your wante file

zip -r xxx . -i xxx/*.snp;

2012年7月16日 星期一

awk print thousand format

export TK_USE_CURRENT_LOCALE=1
awk 'BEGIN { printf("%'\''10d\n",123456)}'

reference http://www.mkssoftware.com/docs/man1/awk.1.asp

2012年7月2日 星期一

Distinct

SELECT DISTINCT table_column1, table_column2···
FROM table_name;
可以將資料只有一筆,
避免重複,


distinct column




Group By Having

Group By: is seperating the  data query condtion,
having: is the filter condition after the group,
Aggregation function: using in group query


-- 使用 group 找出相同內容
select i.sample  ||  '.' || i.chr || '.' || i.pos || '.' || i.type as mykey,
count(i.sample  ||  '.' || i.chr || '.' || i.pos || '.' || i.type) as counts
from gra.gra_indels_het_homo_target_testDel as i
group by i.sample  ||  '.' || i.chr || '.' || i.pos || '.' || i.type
having  count(i.sample  ||  '.' || i.chr || '.' || i.pos || '.' || i.type) > 1



reference:
http://news.csdn.net/n/20061123/98120.html
http://tomkuo139.blogspot.tw/2008/11/group-by-having.html

2012年6月6日 星期三

Perl 學習

Reference: http://ind.ntou.edu.tw/~dada/cgi/Perlsynx.htm
這篇文章是轉自此網站,  寫簡潔明瞭, 希望在此轉貼



Perl的基本語法
前言:
這篇文章是花了我很多時間、費了我很多心血才完成的,雖然連我自己都覺得無法達到盡善盡美的境界,但希望能幫助大家入門,稍微了解到Perl到底是個什麼樣的東西,Perl到底有那些強大的功能,那麼這篇文章的目的就達到了。 我分做資料型態控制敘述副程式I/O和檔案處理Regular ExpressionsSpectial VariablesHelp 這幾部分來講解,但只是敘述了一些Perl的基本語法而已,Perl活潑的特性和程式的技巧就無法一一詳述了,甚為缺憾。
(1) 資料型態(Data type):
Perl的資料型態大致分為四種:
ScalarScalar ArrayHash ArrayReferences, 看起來雖少但用起來卻綽綽有餘。尤其在寫Perl程式時可以不必事先宣告變數,這一點對剛學程式語言的人甚為方便, 不過為了以後程式除錯和維護方便,我建議你還是養成事先宣告變數的習慣比較好。
(a) Scalar:
純量變數是Perl裡最基本的一種資料型態,它可以代表一個字元、字串、整數、甚至浮點數,而Perl把它們都看成是一樣的東東! 你甚至可以混著用,不可思議吧。例如:

# 井字號開頭的後面都是註解。
# 純量變數以$開頭。
# my 是一種宣告變數的方式,它可以使變數區域化。
# 宣告變數時若不加 my 或 local 則Perl會把它當作全域變數使用。
# 習慣上,我們會將字串用雙引號括起來,而數值就不用加引號。
my $x="abc";
my $x=123;
my $x=4.56;

那麼程式怎麼判斷這是數值還是字串呢? 其實不是程式判斷,而是你自己要判斷。Perl分別提供了一堆運算子來處理數字和字串,你必須知道這個變數是數值或字串,才能使用個別的運算子來對變數做運算。我分別列出字串運算子和數值運算子,好讓大家能區分它們的不同。


◎字串運算子
String OperatorPurpose
xReturns a string consisting of the string on the left of the operand, repeated the number of times of the right operand.
Concatenates the two strings on both sides of the operator.
eqReturns True if the two operands are equivalent, False otherwise.
neReturns True if the two operands are not equal, False otherwise.
leReturns True if the operand on the left is stringwise less than the operand on the right of the operator. Returns False otherwise.
ltReturns True if the operand on the left is stringwise less than or equal to the operand on the right of the operator. Returns False otherwise.
geReturns True if the operand on the left is stringwise greater than or equal to the operand on the right of the operator. Returns False otherwise.
gtReturns True if the operand on the left is stringwise greater than the operand on the right of the operator. Returns False otherwise.
cmpReturns -1, 0, or 1 if the left operand is stringwise less than, equal to, or greater than the right operand.
,Evaluates the left operand, the evaluates the right operand. It returns the result of the right operand.
++Increments the string by one alphabetic value.


◎數值運算子
Value OperatorPurpose
+Computes the additive value of the two operands.
-Computes the difference between the two operands.
*Computes the multiplication of the two operands.
/Computes the division between the two operands.
%Computes the modulus(remainder) of the two operands.
= =Returns Ture if the two operands are equivalent, False otherwise.
!=Returns Ture if the two operands are not equal, False otherwise.
<=Returns Ture if the operand on the left is numerically less than or equal to the operand on the right of the operator. Returns False otherwise.
=>Returns Ture if the operand on the left is numerically greater than or equal to the operand on the right of the operator. Returns False otherwise.
<Returns Ture if the operand on the left is numerically less than the operand on the right of the operator. Returns False otherwise.
>Returns Ture if the operand on the left is numerically greater than the operand on the right of the operator. Returns False otherwise.
< = >Returns -1 if the left operand is less than the right, +1 if is it greater than, and 0(False) otherwise.
&&Performs a logical AND operation. If the left operand is True m then the right operator is not evaluated.
||Performs a logical OR operation. If the left operand is True m then the right operator is not evaluated.
&Returns the valueof the two operators bitwise ANDed.
|Returns the valueof the two operators bitwise ORed.
^Returns the valueof the two operators bitwise XORed.
++Increment operator. Increments the variable's value by 1.
--Decrement operator. Decrements the variable's value by 1.
**Computes the power of the left-hand value to the power of the rihght-hand value.
+=Adds the value of the right-hand operand to the value of the left-hand operand.
-+Subtracts the value of the right-hand operand to the value of the left-hand operand.
*=Mlutiplies the value of the left-hand operand to the value of the right-hand operand.
>>Shifts the left operand right by the number of bits that is specified by the right operand.
<<Shifts the left operand left by the number of bits that is specified by the right operand.
~Performs a 1s complement of the operator. This is a unary operator.

(b) Scalar Array:
純量陣列,陣列內的每一個元素都是Scalar variable。宣告及使用方式如下:

# 純量陣列以 @ 開頭。
my @array;
my @array=qw(a b c d);

# qw 函數會將其後的每個元素用逗點隔開,效果就像下面這行。
my @array=("a","b","c","d");

# 當然你也可以一個個元素宣告,下面就是存取每一個元素的方法。
# 因為陣列中的每一個元素都是純量變數,所以要以 $ 開頭,
# 剛開始容易搞混,請注意。
$array[0]="a"; $array[1]="b"; $array[2]="c"; $array[3]="d";

# 使用for loop印出陣列內每個元素的值。
for($i=0; $i<=$#array; $i++) {
print "$array[$i]\n";
}

看到$#array這個奇怪的東東沒? 這是Perl的一個特殊用法,代表這個陣列最後一個元素的註標。 由於Perl不必事先宣告變數,也不必預先宣告陣列的大小,甚至可以隨時增加新元素,那我們怎麼知道這個陣列到底有多大呢? 透過這個特殊變數我們可以得知這個這個陣列最後一個元素的註標,自然而然也就知道這個陣列究竟有多大了。 另外Perl只定義了一維陣列的語法,二維以上只能用指標間接來達成。


(c) Hash Array(Associative Array):
雜湊陣列也叫做相關陣列,它和一般陣列沒什麼不同,差別只是在它的索引值用的是字串,而非一般陣列所用的整數值, 因此相關陣列不像一般陣列一樣有次序的概念,它沒有所謂的第一項資料這種說法。它就相當於把一堆變數組合成一個group,然後我們可以透過索引字串存取這個group每一個元素的值。 相關陣列的宣告及使用方式如下:

# 相關陣列是以 % 符號開頭的。
my %hash;

# => 這個符號是Perl5新增的,是為了相關陣列量身定做的,
# 因為索引和元素值都是純量,若使用 => 這個符號,
# (索引=>元素值) 兩兩對應,就不容易發生失誤。
my %hash=("i1"=>"aaa","i2"=>"bbb","i3"=>"ccc");

# 上面這行的效果和下面這行是一樣的。
my %hash=("i1","aaa","i2","bbb","i3","ccc");

# 下面是存取每個元素的方法,注意是用大括號把索引括起來哦。
# 習慣上索引值用單引號、元素值用雙引號括起來。
$hash{'i1'}="aaa"; $hash{'i2'}="bbb"; $hash{'i3'}="ccc";

# 下面是使用相關陣列的三個例子:
foreach $key (keys %hash) {
print "$hash{$key}\n";
}
foreach $value (values %hash)
while(($key,$value)=each %hash)


Perl有上述三個函數可對相關陣列做運算:keys函數可取出相關變數的索引值,組成一純量陣列,注意這些由keys函數取出的索引值沒有次序性;values函數可取出相關變數的元素值;each函數則會取出(索引、元素)對。使用者可視情況而用。


(d) References(Pointer):
Perl 5新增了參考指標的資料型態,使Perl和C一樣可借由指標建立一些複雜的資料結構。 普通程式是用不到指標這玩意的,下面也只是簡單介紹一下,看不懂的人可不必深究。
⊙如何取得變數的位址?
$scalarRef=\$scalarVar;
$arrayRef=\@arrayVar;
$hashRef=\%hashVar;
$funcRef=\&funcName;
⊙如何使用指標? print $$scalarRef;
print "@$arrayRef";
print $hashRef->{$key};
&$funcRef;
⊙Anonymous Array References:(二維陣列) $arrayRef=[[1,2,3,4],a,b,[x,y,z],c];
print "$arrayRef->[0][0]\t$arrayRef->[2]\t$arrayRef->[3][2]\n";
⊙Anonymous Hash References: $hashRef={a=>aa,b=>bb,c=>cc};
print "$hashRef->{a}\t$hashRef->{b}\t$hashRef->{c}\n";


(2) 控制敘述(Control Statements) (a) Conditional Control Statements: Perl的條件控制敘述和C語言很像,讓使用者很快就能掌握它。不過Perl比C語言又另外多了些實用的語法,我用底線標出來,大家一看便知:

# Expression 就是條件敘述式,Perl和C一樣沒有定義布林資料型態(Boolean data type),
# 因此 0 是false、非0 是ture。另外要注意字串運算子和數值運算子要分清楚哦。
# Code Segment 就是用大括號括起來的一堆指令,也就是一個Block。
if (Expression) {Code Segment}
if (Expression) {Code Segment} else {Code Segment}
if (Expression) {Code Segment} elsif (Expression) {Code Segment} else {Code Segment}
# elsif 就是 else if

# 如果指令(statement)只有一項,我們可以使用倒裝句法,看起來比較簡潔。
statement if (Expression);
# unless 就是if not
statement unless (Expression);
例:
print "HELLO!\n" if ($name eq "friend");
$x-=10 if ($x == 100);

看吧! C 語言有的Perl大部分都有,學過 C 的人可以毫不費力的學會Perl。


(b) Loop Control Statements: Perl的迴圈控制敘述也和C語言很像,當然,照例Perl也另外多了些實用的語法:

# 注意:純量變數前面要加個 $ 字號,這一點和C語言不一樣哦。
for($i=0; $i<=10; $i++) {Code Segment}

# foreach 是承襲UNIX的shell script來的,
# 第一個引數是純量變數,第二個引數要用括號括起來,裡面是一個純量陣列,
# 顧名思義它就是把陣列中的每個元素依序傳給第一個引數,直到全部傳完。
# 它和 for($i=0; $i<=$#array; $i++) 用法雖然不同,但目的都是要取出陣列的每個元素。
foreach $i (@array) {Code Segment}

# 其實在Perl中,for和foreach是可以混著用的,就看個的人習慣了。
# 下面這行就等於上面第一個敘述,不過簡潔多了,大家可以試著用用看。
for $i (0..10) {Code Segment}

# while控制迴圈和後置迴圈。
while($i<=10) {Code Segment}
do {Code Segment} while(Expression);

# Perl也有和C語言的break和continue一樣的指令,Perl叫它做 last 和 next (較口語化)。
# last是跳出現在所在的迴圈,next則是跳過下面的指令直接執行下一次的迴圈。
while(chomp($i=)) {
next if ($i == 5);
last unless ($i > 10);
}
Perl還有提供label(標記)的語法,也就是 goto 指令,不過有經驗的programer並不喜歡用它,我也不建議大家使用,所以就此按下不講。有興趣的人請自行查閱。 還有一點值得注意的是Perl沒有提供像C語言一樣的 switch 敘述,不過Perl的pattern match的功能非常強,所以我建議你直接用 if else 敘述來做就好了。



(3) 副程式(Subroutines)

(a) Syntax: sub NAME {Code}

(b) 呼叫副程式: &NAME(para1, para2,...)

(c) 參數傳遞: @_ Perl和C一樣是採用Call by value的方式,不過因為Perl不用事先宣告變數,所以建立副程式的時候也不用宣告要傳遞什麼參數。 當主程式在傳遞參數給副程式時,Perl會把括號括起來的參數按順序放在一個特殊的全域變數 @_ 陣列中,然後副程式就可以隨意使用陣列 @_ 裡的參數,例如 $_[0] 是第一個參數, $_[1] 是第二個,或是用 my ($a1,$a2,$a3,...) = @_;來取出各個參數,當然 my @arg=@_;my %arg=@_; 也是可以的。 由於Perl的語法非常活潑,使得程式在維護時特別棘手,因此寫註解成為一項很重要的工作。 我建議你最好在每個副程式前面加上對這段副程式的描述,特別是需要傳遞的參數要註明清楚。

(d) Variable Localization:my or local 通常我們在程式中定義的變數都是全域變數,所以在副程式中若要把變數區域化則要加上 my 或 local 關鍵字,例如: my $x=3;,若副程式所用的變數名不小心和主程相同,Perl會以目前正在執行的副程式裡的變數為優先。

(4) I/O和檔案處理

(a) Syntax: open(FILEHANDLE,"Expression");
close(FILEHANDLE);
這裡的Expression是一個敘述加上檔案名稱,若Expression只有檔案名稱沒有加上敘述,則預設是唯讀。Expressions敘述如下:

ExpressionEffect
open(FH, "Opens filename for reading.
open(FH, "+Opens filename for both reading and writing.
open(FH, ">filename") Opens filename for writing.
open(FH, "+>filename") Opens filename for both reading and writing.
open(FH, ">>filename") Appends to filename.
open(FH, "command|") Runs the command and pipes its output to the filehandle.
open(FH, "command|") Pipes the output along the filehandle to the command.
open(FH, "-") Opens STDIN.
open(FH, ">-") Opens STDOUT.
open(FH, "<&=N") Where N is a number, this performs the equivalent of C's fdopen for reading.
open(FH, ">&=N") Where N is a number, this performs the equivalent of C's fdopen for writing.

例:
# 開啟$filename這個檔案,若開啟失敗則印出die後面的訊息,並結束程式。
open(FILE, $filename) || die "Can't open file $filename : $!\n";
# 下面是一個十分精簡的寫法,和 while($_=){print "$_";} 是等效的。
print while();
# 檔案開啟後要記得隨手關閉,這才是寫程式的好習慣。
close(FILE);
# $!和$_都是Perl的特殊變數,下面會介紹的。


(b) Input: Perl沒有特別用來輸入的函數,因為Perl在執行程式時,會自動開啟標準輸入裝置,其filehandle定為STDIN,所以在Perl中要輸入資料的方法就是使用 # Perl不會自動去掉結尾的CR/LF,跟C語言不同,所以要用chomp函數幫你去掉它。
# 大家常常會忘記這個動作,導致結果跟你想的不一樣,要特別注意一下。
$input=; chomp $input;
# 下面是較簡潔的寫法。
chomp($input=);



(c) Output: print "variables or 字串"; Perl也有printf()函數,語法和C語言一模一樣,我就不多做介紹了。Perl另外有個print函數,比printf()更方便、更好用,包你愛不釋手。 Output不外乎是輸出到螢幕或檔案,用例子來說明比較容易了解。 # 不用再指定變數的data type,這樣不是比printf()方便多了嗎?
print "Scalar value is $x\n";
# . 是字串加法的運算子,上下這兩行是等效的。
print "Scalar value is " . $x . "\n";

# 輸出到檔案的方法。
print FILE "print $x to a file.";

# 下面是print的特殊用法,學自shell script的用法:
print<

這招叫做 here document,XXX可以是你取的任何識別字,
在識別字之間的字都會按照你所寫的樣子輸出,就像
標籤一樣。
而當一行的開頭是XXX你取的這個識別字時,才會停止輸出。
XXX Perl 也有和 C 一樣以 "\" 開頭的特殊字元:
      \t    tab
      \n    newline
      \r    return
      \f    form feed
      \b    backspace
      \a    alarm(bell)
      \e    escape
      \033  octalchar
      \x1b  hex char
      \c[   control char
      \l    lowercase next char
      \u    uppercase next char
      \L    lowercase till \E
      \U    uppercase till \E
      \E    end case modification
      \Q    quoteregexp metacharacters till \E
另外需要說明的是 Perl 融合了 unix shell script 的使用慣例,以雙引號("")括起來的字串會先經過展開,但反斜線(\)後面的字元則不展開,當作一般字元看待。 而以單引號('')括起來的字串完全不會展開,以反單引號(``)括起來的字串會把它當作命令列指令一樣執行,等於system()一樣。 初學者常常會搞混,但習慣之後就會覺得不這樣分清楚反而不行哩。舉個例吧:
$x="ls -l";
print "$x";             # Output ls -l
print "\$x";            # Output $x
print '$x';             # Output $x
print `$x`;             # Output files in this directory
(5) Regular Expressions
Regular Expression通常是用來尋找特定的字串樣式(pattern),也就是所謂格式辨認(pattern-matching)的功能。 它的運算子是『=~』和『!~』,可以把它念做match和not match。
Syntax: $string =~ /regular expression/expression modifier
例:$sentence =~ /Hello/

(a) Modifiers:修飾選項可有可無,它是用來對整個敘述作修正的。
g Match globally, i.e. find all occurrences.
i Makes the search case-insensitive.
m If the string has new-line characters embedded within it, the metacharacters ^ and $ will not work correctly. This modifier tells Perl to treat this line as a multiple line.
o Only compile pattern once.
s The character . matches any character except a new line. This modifier treats this line as a single line, which allows . to match a new-line character.
x Allows white space in the expression.

(b) Metacharacter:下面這些字元都具有特殊意義,可以讓你建立更複雜的搜尋樣式(searching pattern)。
\Tells Perl to accept the following characters as a regular character; this removes special meanings from any metacharacter.
^ Matches the beginning of the string, unless /m is used.
. Matches any character except a new line character, unless /s is used.
$ Matches the end of the string, unless /m is used.
| Expresses alternation. This means the expressions will search for multiple patterns in the same string.
( ) Groups expressions to assist in alternation and back referencing.
[ ] Looks for a set of characters.

(c) Pattern Quantifier:用來表示字元的數量關係。
* Matchs 0 or more times.
+ Matchs 1 or more times.
? Matchs 0 or 1 times.
{n} Matches exactly n times.
{n,} Matches at least n times.
{n,m} Matches at least n times but no more than m times.

(d) Character Patterns:下列的sequence用來match一些特定格式的字元:
\r Carriage return(CR), ASCII 13(十進位)
\n New line, UNIX中代表ASCII 10(十進位), DOS(Windows)系統中則是ASCII 13 + ASCII 10(十進位).
\t Tab, ASCII 9(十進位)
\w Matches an alphanumeric character. Alphanumeric also includes _. 即 [A-Za-z0-9_].
\W Matches a nonalphanumeric character. 即 [^A-Za-z0-9_].
\s Matches a white space character. This includes space, tab, FormFeed and CR/LF. 即 [\ \t\f\r\n].
\S Matches a non-whote space character. 即 [^\ \t\f\r\n].
\d Matches a digit. 即 [0-9].
\D Matches a nondigit character. 即 [^0-9].
\b Matches a word boundary.
\B Matches a nonword boundary.
\033 octal char
\x1B hex char

(e) Examples: Regular Expression這個東東非常強大、非常重要,但是對初學者來說簡直是個惡夢,記得我當初剛接觸時也是霧煞煞的,就算現在的我也不敢說全懂了:p 但你若了解了它的基本技巧後,包你愛不釋手,每每為它強大的功能讚歎。上面那些表格相信你也是有看沒有懂,這種東西要借由範例入門比較快,下面我列出一些基本範例,希望能幫助你了解它的基本技巧。 /abc/
找到含有abc的字串 /^abc/ 找到開頭是abc的字串 /abc$/ 找到結尾是abc的字串 /a|b/ 找到有a或b的字串,也可以用來找整個字(word) /ab{2,4}c/ 找到a後面跟著2-4個b,再跟著c的字串,若只有/ab{2,}c/則會找二個以上的b /ab*c/ 找到a後面跟著0個或多個b,再跟著c的字串,如同/ab{0,}c/ /ab+c/ 找到a後面跟著一個以上的b,再跟著c的字串,如同/ab{1,}c/ /a.c/ .可以代表任何字元,除了new line字元(\n)外。 /[abc]/ 找到含有這三個字元中任何一個的字串 /\d/ 找到含有數字的字串,如同/[0-9]/ /\w/ 找到含有字母的字串,如同/[a-zA-Z0-9_]/ /\s/ 找到含有white space的字串,如同/[ \t\r\n\f]/ /[^abc]/ 找到沒有abc任一字元的字串 /\*/ 找到含有字元*的字串,在反斜線"\"後面的字元Perl會把它當作普通字元看待。若你不確定這個符號是否為特殊字元,乾脆全加上\以策安全。 /abc/i 忽略abc的大小寫 /(\d+)\.(\d+)\.(\d+)\.(\d+)/ 找到類似IP的字串,並將IP的四個數字分別存在$1,$2,$3,$4四個特殊變數中,以便在其後加以利用。例: if ($x =~ /(\d+\.\d+)\.\d+\.\d+/) { print "海洋大學" if ($1 eq "140.121"); } m//gimosx m命令可以讓你自訂pattern的分隔符號,而gimosx則是它的修飾選項,請參看(a)Modifiers。例如: $url="my.machine.tw:8080/cgi-bin/test.pl"; ($host, $port, $file)=($url=~m|http://([^/:]+):{0,1}(\d*)(\S*)$|);
這個Regular Expression相當複雜,主要目的是分析指定的URL,然後取得host名稱、port號碼及對應的檔案。我一項項慢慢解釋:
$url=~m|| m後面跟著的就是分隔符號,| |裡面的就是pattern。
([^/:]+) match一個字串,裡面沒有/和:字元。找到的字串存在$1中。
:{0,1}(\d*) match 0或1個:,後面跟著一串數字或nothing。找到的字串存在$2中,若找不到,$2就是空的。
(\S*)$ match一串非空白字元,並以找到的字串為結尾。找到的字串存在$3中。
()=() ($host, $port, $file)=($1, $2, $3) 即$host="my.machine.tw" $port=8080 $file="/cgi-bin/test.pl"
s/PATTERN/REPLACEMENT/egimox 沒錯,這就是取代的命令。它會尋找符合PATTERN的字串,並取代成REPLACEMENT字串。它的修飾選項多了e選項,其他的和上面都一樣,我將它列表如下:
e Evaluate the right side as an expression.
g Replace globally, i.e. all occurrences.
i Do case-insensitive pattern matching.
m Treat string as multiple lines.
o Only compile pattern once.
s Treat string as single line.
x Use extended regular expressions.
例: $x =~ s/\s+//g 把所有的white space全部去除掉
$x =~ s/([^ ]*):*([^ ]*)/$2:$1/ 把用":"分開的兩個欄位互相對調
$path =~ s|/usr/bin|/usr/local/bin| 它也可以讓你自訂分隔符號哦
tr/SEARCHLIST/REPLACEMENTLIST/cds
這是也是取代的命令,和上一個不同的是SEARCHLIST和REPLACEMENTLIST只能是普通字串,而不是Regular Expression,所以速度比較快。它的修飾選項也比較少:
c Complement the SEARCHLIST.
d Delete found but unreplaced characters.
s Squash duplicate replaced characters.
例: $x =~ tr/this/that/ 把"this"替換成"that"
$x =~ tr/a-z/A-Z/ 把小寫字母全部替換成大寫字母
$count = $x =~ tr/*/*/ 計算$x中有幾個"*"
(6) Spectial Variables
Perl的特色之一就是有超過50個以上的特殊變數,這些變數都是全域變數,用來設定程式的執行環境和其它細節。 若你想深入了解Perl程式設計,那麼這些東西是不可或缺的。在這裡我只列幾個常用的特殊變數以供參考,有興趣的人請自行查閱。
$_ The default input and pattern-searching space.
$digit Contains the subpattern from a successful parentheses pattern match.
$. The current input line number of last filehandle read.
$! Contains the current value of errno.
$0 The name of the file of the Perl script.
@ARGV The command line arguments issued when the script was started.
@_ The parameter array for subroutines.
%ENV This associative array contains your current environment.
(7) Help
目前市面上有關Perl語言的書並不多,就算是原文書也只有那幾本聖經本。不過只要是有關CGI的書,其內容大都會提到Perl,但卻很少教到基本語法,常常使人一頭霧水。 所以我建議:如果你真的想學好Perl語言,真得想拿Perl來寫程式,那我建議你最好去買一本書來看,在觀念上會比較清楚,在實際應用上也會比較有幫助; 如果你只是想寫一些簡單的CGI程式,或只想看得懂別人所寫的CGI程式,那在網路上的資料就綽綽有餘了。 首先你可以到各大BBS站的WWW板或program板的精華區找找,不過資料不會很多,而且有點雜亂。 再不然你可以到蕃薯藤輸入perl或cgi關鍵字找找,有不少人的homepage上有教人如何用Perl寫CGI程式,還有一堆別人已經寫好的CGI程式可以抓來用用。 說到這裡順便打一下廣告,在http://ind.ntou.edu.tw/documents下有Perl的說明文件,做得相當不錯,不過全是英文的就是了,而我這份講義打好後也會放在IND的homepage上,大家可以抓回去參考參考。 第三種資源就是Perl本身的man pages,你在IND帳號下鍵入 man perl 就可以查閱了,這份文件做得不錯,還根據Perl的各個部分寫了man pages,如Perl syntax, builtin function, regular expression, data structure等, 大家可以用man指令一一查詢,有時候在寫程式時一時忘了某個函數怎麼用,這倒是個方便又快速的查詢方法。我會把這些man pages轉成html格式,放在WWW上讓大家參考。