搜尋此網誌

2013年1月29日 星期二

Linked List implementation in C

#include <stdlib.h>
#include <stdio.h>

struct Node{
    int value;
    struct Node* nextNode ;
};

typedef struct Node* NodePtr;

void insert(NodePtr  , int value);
void display(NodePtr );

int main (void){

    NodePtr start = (NodePtr)malloc (sizeof(NodePtr));
    start->value = 0;
    start->nextNode = NULL;
    insert(start , 1);
    insert(start , 2);
    insert(start , 3);
    display(start);
    return 0;
}

void insert(NodePtr node , int value){
    NodePtr temp = node;
    while(temp->nextNode != NULL){
        temp = temp->nextNode;
    }
    NodePtr new = (NodePtr)malloc (sizeof(NodePtr));
    new->value = value;
    new->nextNode = NULL;
    temp->nextNode = new;
}

void display(NodePtr node){
    NodePtr temp = node;
    while(temp != NULL){
        printf("%d\n", temp->value);
        temp= temp->nextNode;
    }
}

2013年1月28日 星期一

Sizeof a c structure. C結構的大小.

Structure 會把char不足的部分, 補足到4 bytes .
#include <stdlib.h>
#include <stdio.h>

struct people{
    char name;
    int id;
};

int main(void ){

     printf("%d\n" , sizeof(struct people));
    printf("%d\n" , sizeof(char));
    printf("%d\n" , sizeof(int));
    return 0;
}

2013年1月22日 星期二

Create spring datasource in code not in xml (用程式創建spring的data source, 而非xml的方法)

1. DatasourceCreateDemo.java
import javax.sql.DataSource;

import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DriverManagerDataSource;


public class DatasourceCreateDemo {
    
    public static void main(String[] args){
    
        new Tester().testJdbcTemplate();
        
    }
}

class DataSourceFactory {
    
     public DataSource createDataSource() {
        DriverManagerDataSource dataSource = new DriverManagerDataSource();
        dataSource.setDriverClassName("driver.class.name");
        dataSource.setUrl("sqlurl");
        dataSource.setUsername("username");
        dataSource.setPassword("password");
        return dataSource;
     }
    
}

class Tester{
    private JdbcTemplate jdbcTemplateObject;
    
    public void setDataSource(DataSource dataSource) {
        this.jdbcTemplateObject = new JdbcTemplate(dataSource);
    }
    
    public void testJdbcTemplate(){
        System.out.println(jdbcTemplateObject==null);
    }
}
2. spring config
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.0.xsd">

   <bean id = "dataSourceFactory" class = "xxx.xxx.DataSourceFactory" />    
   
   <bean id = "dataSource" factory-bean = "dataSourceFactory" factory-method = "createDataSource" />
   
   <bean id="Tester" 
      class="xxx.xxx.Tester">
      <property name="dataSource"  ref="dataSource" />    
   </bean>
   
</beans>

2013年1月18日 星期五

2013年1月17日 星期四

Set tomcat default encodeing (設定tomcat預設的編碼)

1. 到conf/server.xml   

2. 找到connector port = 8080的tag, 加上URIEncoding="UTF-8"  這個屬性

3. restart tomcat

2013年1月16日 星期三

JQuery getJson 用法

getJsonLoad.html
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<script src="../jquery-1.8.3.min.js"></script>
<script type="text/javascript">
function getFruits() {

    $.getJSON('../jsp/load_json.jsp', function(data) {

        $.each(data, function(key, val) {
            $("#fruitsBox").append('<option id="' + key + '">' + val + '</option>');
        });

    });
}
</script>
</head>
<body>
<select id = "fruitsBox"></select>

<button onclick ="getFruits()">get fruits</button> 
</body>
</html>
load_json.jsp
<%@ page contentType="text/html" import="org.json.* , java.io.*"%>
<%

    JSONObject obj = new JSONObject();
    obj.put("1", "apple");
    obj.put("2", "orange");
    obj.put("3", "pineapple");
    
    PrintWriter pw = response.getWriter();
    pw.print(obj.toString());
    
%>

Reference:JQuery getJson

用JQuery 或是 DOM 建立element

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
</head>
<body>
<script src="../jquery-1.8.3.min.js"></script>
<script type="text/javascript">

function addOption(){
    
    var myComboBox = document.getElementById("myComboBox");
    var myOption = document.createElement("option"); 
    myOption.innerHTML = " Hello ";
    myComboBox.appendChild(myOption);
    
}

function addOptionByJq(){
    var myOption = document.createElement("option"); 
    myOption.innerHTML = " Hello by JQ ";
    $("#myComboBox").append(myOption)
    
    
}

</script>



<select id="myComboBox"></select>

<br>

<button onclick="addOption()">add a new option by dom manipulation</button>

<br>

<button onclick="addOptionByJq()"> add a new option by Jquery</button>

</body>
</html>
ReferenceJQuery append

JQuery load usage (JQuery load的使用方式)

load.html:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<script src="../jquery-1.8.3.min.js"></script>
<script type="text/javascript">

function getServerResponse(){
    $("#respone").load("../jsp/load.jsp");
}


</script>
</head>
<body>
<span id="respone"></span>
<button onclick ="getServerResponse()">get server response</button> 
</body>
</html>
load.jsp
<%@ page contentType="text/html" import="java.io.*"%>
<%
    PrintWriter pw = response.getWriter();
    pw.print("Hello");
%>

Reference jQuery - AJAX load() Method

Div and span introduction (介紹Div 和 span )

Div : 常常被使用在把一整個group的元件(elements), 套用到同一個css .:
Span: 則是使用在內部小部分元件上, 套用個別的css, 以下的例子結合div和span使用的方式 Reference :w3schools

2013年1月14日 星期一

JQuery 的type種類介紹

  1. String :  " hello " , ' hello' , '  "hello"  ' , "  \" 跳脫字元 \" "
  2. Number : 12 , 3.14 , 0.1 + 0.5 
  3. Boolean: 在Javascript 可以直接使用true or false, 例如:

  4. if ( true ) console.log( "always!" );
    if ( false ) console.log( "never!" );

  5. Object: 在javascript每件東西都是物件, 最簡單創造物件的方法,是使用物件實字,例如:
  6. 1.var x = {};
    2.var y = { name: "Pete", age: 15 };
  7. Array , 在javascript的array 是可變動長度的list, ex: var x = [];
    var y = [ 1, 2, 3 ];
  8. Plain object , 可包含零或多個key-value pairs , ex:
  9. var o = {};
    jQuery.isPlainObject( o ); // true
  10. Function ,
  11. javascript的函式可以有名字或者是匿名 任何函式都可以assign value給變數 或傳給另一個method,
    但要注意這麼做的話, 這個函式很有可能在另一個object裡被呼叫到. ex:
    function named() {}
    var handler = function() {}
全文參考自JQuery官方文件

2013年1月12日 星期六

Using Json in Java demo

import java.util.LinkedList;

import org.json.JSONArray;

public class JavaJsonDemo {

    public static void main(String[] args) {
        LinkedList<JSONArray> list = new LinkedList<JSONArray>();

        JSONArray obj = new JSONArray();
        JSONArray obj1 = new JSONArray();
        JSONArray obj2 = new JSONArray();
        obj.put("1");
        obj.put("2");
        obj.put("3");
        obj1.put("1");
        obj1.put("2");
        obj1.put("3");
        obj2.put("1");
        obj2.put("2");
        obj2.put("3");

        list.add(obj);
        list.add(obj1);
        list.add(obj2);
        System.out.print(list.toString());

    }

}

2013年1月8日 星期二

Observer pattern demo (觀察者模式)

import java.util.LinkedList;
import java.util.List;

public class ObserverPatternDemo {
    
    public static void main(String [] args){
        
    Novelist novelist = new Novelist();
    novelist.addReader(new Reader());
    novelist.addReader(new Reader());
    novelist.addReader(new Reader());
    novelist.addReader(new Reader());
    novelist.addReader(new Reader());
    novelist.notifyReaders();
        
    }

}

class Novelist  {
    
    List<InfoReceiver> readerList = new LinkedList();
    
    public void addReader(InfoReceiver reader){
        readerList.add(reader);
    }
    
    public void notifyReaders(){
        
        for(int i = 0 ; i < readerList.size() ; i++){
            Info info = new Info(i);
            readerList.get(i).readInfo(info);
        }
    }
}

class Info{
    
    int id;
    
    Info(int id){
        this.id = id;
    }
    
    public void printInfo(){
        System.out.println("reader " + this.id + " will receiver my newest book");
    }
}

interface InfoReceiver {
    
    public void readInfo(Info info);
}

class Reader implements InfoReceiver{

    @Override
    public void readInfo(Info info) {
        info.printInfo();
    }
    
}


2013年1月7日 星期一

BST with Java implementation

The removal part is all from Algorithms and Data Structures with implementations in Java and C++ . I just add some comments.


public class BST {

    public static void main(String[] args) {
        Tree myBst = new Tree();
        Node one = new Node(1);
        Node six = new Node(6);
        Node three = new Node(3);
        Node five = new Node(5);
        Node two = new Node(2);

        myBst.insert(one);
        myBst.insert(six);
        myBst.insert(three);
        myBst.insert(five);
        myBst.insert(two);
        myBst.preOrderTraversal(myBst.root);
        System.out.println("-----------------");
        myBst.remove(3);
        myBst.preOrderTraversal(myBst.root);

    }

}

class Node {
    Node leftChild;
    Node rightChild;
    int value;

    Node(int i) {
        this.value = i;
    }

    public boolean remove(int value, Node parent) {
        if (value < this.value) {//not found, keep left search
            if (leftChild != null)
                return leftChild.remove(value, this);
            else
                return false;
        } else if (value > this.value) {//not found , keep right search.
            if (rightChild != null)
                return rightChild.remove(value, this);
            else
                return false;
        } else {//found
            if (leftChild != null && rightChild != null) {//two leafs case
                this.value = rightChild.minValue();
                rightChild.remove(this.value, this);
            } else if (parent.leftChild == this) {//left node is the only one child node
                parent.leftChild = (leftChild != null) ? leftChild : rightChild;
            } else if (parent.rightChild == this) {//right node is the only one child node
                parent.rightChild = (leftChild != null) ? leftChild    : rightChild;
            }
            return true;
        }
    }

    /*
     * The minimum value of a tree is always located in the left sub tree,
     * so recursively search from left subtree. 
     */
    public int minValue() {
        if (leftChild == null)
            return value;
        else
            return leftChild.minValue();
    }

}

class Tree {

    Node root;

    public void insert(Node node) {
        if (root == null) {
            root = node;
        } else {
            Node temp = root;
            while (temp != null) {
                if (node.value >= temp.value) {
                    if (temp.rightChild == null) {
                        temp.rightChild = node;
                        break;
                    } else {
                        temp = temp.rightChild;
                    }
                } else {
                    if (temp.leftChild == null) {
                        temp.leftChild = node;
                        break;
                    } else {
                        temp = temp.leftChild;
                    }

                }
            }

        }
    }

    public boolean remove(int value) {
        if (root == null)
            return false;
        else {
            if (root.value == value) {
                Node auxRoot = new Node(0);
                auxRoot.leftChild = root;
                boolean result = root.remove(value, auxRoot);
                root = auxRoot.leftChild;
                return result;
            } else {
                return root.remove(value, null);
            }
        }
    }

    public void preOrderTraversal(Node root) {
        System.out.println(root.value);
        if (root.leftChild != null) {
            preOrderTraversal(root.leftChild);
        }
        if (root.rightChild != null) {
            preOrderTraversal(root.rightChild);
        }
    }

}

BST with c++

2013年1月5日 星期六

Java 物件equals method 的用法

Generally speaking , you must override the equals method of your own class. Otherwise , the jvm will treat two objects with the same memory address as the same.

多型介紹 (polymorphism introduction)

package helloWorld;

public class PolymorphismDemo {
    
    public static void main(String [] args){
        
        callMan(new SuperMan());
        callMan(new SpiderMan());
        callMan(new IronMan());
        callMan((IMan)new MixedHero(){});
    }
    
    private static void callMan(Man man){
        man.weapon();
    }
    
    private static void callMan(IMan man){
        man.weapon();
    }

}

abstract class MixedHero extends Man implements IMan{
    public void weapon(){
        System.out.println("I am a mixed hero");
    }
}

abstract class Man{
    protected void weapon(){
        System.out.println("Normal man is using a hammer");
    }
}

class SuperMan extends Man{
    
    public void weapon(){
        System.out.println("Superman can use his leaser eye");
    }
}

class SpiderMan extends Man{
    
    public void weapon(){
        System.out.println("Spiderman can use many high-tech stuffs");
    }
}

interface IMan{
    void weapon();
}

class IronMan implements IMan{

    @Override
    public void weapon() {
        System.out.println("Ironman (Sorry , I really don't know how to write descriptions for this character)");
    }
}

2013年1月4日 星期五

property change support demo

import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeSupport;
import java.beans.PropertyChangeListener;

public class PropertyChangeSupportDemo {

    public static void main(String[] args) {

        MyBean mBean = new MyBean();
        
        PropertyChangeSupport myBean = new PropertyChangeSupport(mBean);
        
        myBean.addPropertyChangeListener(new PropertyChangeListener(){

            @Override
            public void propertyChange(PropertyChangeEvent evt) {
                
                //Do something when property change
                System.out.println("property changed , ");
                System.out.println("new value : " + evt.getNewValue());
                System.out.println("old value : " + evt.getOldValue());

            }
            
        });
        
        myBean.firePropertyChange("name", "old", "new");
        
    }

    static class MyBean {
        String name = "old";

    }

}

2013年1月2日 星期三

創建目錄 (create folders)

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;

/**
 * Reading folder names from a text file (temp.txt) , then create them under template folder.
 * 
 * temp.txt looks like following:
 * 
 * folder1
 * folder2
 * folder3
 * 
 * 
 * @author Steven
 *
 */
public class CreateFolder {

    public static void main(String [] args) throws IOException{
        
        String outPutFolder = "template/";
        FileReader fis = new FileReader(new File("src/temp.txt"));
        BufferedReader br = new BufferedReader(fis);
        String folderName = br.readLine();
        while( folderName != null){
            File tmp = new File(outPutFolder + String.valueOf(folderName));
            tmp.mkdirs();
            folderName = br.readLine();
        }
    }
}