2018年11月10日 星期六

java 非同步呼叫 callback




public class Ajax_1 {

    Callback callback;

    String name;

    void query(Callback callback) {
        this.callback = callback;
      
        // 非同步
        Thread t = new Thread(() -> {
           
            // 取得查詢
            String name = (new SyncSqlQuery()).query();
            Ajax_1.this.name = name;
            Ajax_1.this.callback.callback();
        });

        t.start();
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        Ajax_1 a = new Ajax_1();
        int x = 5;
       
        a.query(() -> {
            // 及時命令
            out.println(a.name);
        });
       
       
        a.query(new Callback(){
            public void callback(){
                // 及時命令
                out.println(a.name);
            }
        });

    }

}
//-------------------------------------------------------

public interface Callback {
    void callback();
}
//-------------------------------------------------------
public class SyncSqlQuery {
    public static int id = 0;
   
    String query(){
       
        return "SyncSqlQuery_" + id++;
    }
}
//////////////////////////////////////////////////////////////////////////

/**
 *
 * @author xman
 */
public class Ajax_1 {

    String name;

    void query(Callback callback) {       

        Thread t = new Thread(() -> {
           
            // 取得查詢
            String name = (new SyncSqlQuery()).query();
            Ajax_1.this.name = name;
        });

        t.start();
        try {
            t.join();
        } catch (InterruptedException ex) {
            out.println(ex);
        }

        callback.callback();
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        Ajax_1 a = new Ajax_1();
        int x = 5;
       
        a.query(() -> {
            out.println(a.name);
        });
       
       
        a.query(new Callback(){
            public void callback(){
                out.println(a.name);
            }
        });
    }
}

java inner-class 閉包

// 運用 innerClass

public class T_4 {

    String name;

    String getName() {
        return name;
    }
    //----------------------------
    class A {
        public void setName(String name) {
            T_4.this.name = name;
        }
    }
    //----------------------------
    public static void main(String[] args) {
        T_4 t = new T_4();
        T_4.A a = t.new A();

        a.setName("Xman");
        out.println(t.getName());
    }
}
/////////////////////////////////////////////////////////////////////////////////////////////
// 運用 lambda
// 比較方便偷懶

interface Callback {
    // callback 內容隨你寫....讚
    public void callback(String name);
}
//-------------------------------------------
public class T_4 {

    String name;

    String getName() {
        return name;
    }

    // 送出一個 callback
    // 來設定 name
    Callback getCallback() {

        // lambda 生成一個 匿名 class implements Callback
        return ((name) -> {
            T_4.this.name = name;
        }
);
    }

    // ----------------------------
    public static void main(String[] args) {
        T_4 t = new T_4();

        // 藉由 callback 設定 t
        t.getCallback().callback("Xyz");

        out.println(t.getName());
    }
}

2018年11月9日 星期五

java繼承 與變數型態 間的問題

public class T_1 {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        T_1_B b = new T_1_B();
        b.showName();

        T_1_A a = b;

        a.showName();

        try {
            a.getName(); // error
        } catch (Exception e) {
            out.println(e);
        }

    }
}
//--------------------------------
class T_1_A {

    String name = "G";

    void showName() {
        out.printf("A(%s)\n", name);
    }
}
//--------------------------------
class T_1_B extends T_1_A {

    void showName() {
        String _name = this.getName();
        out.printf("B(%s)\n", name);
    }

    String getName() {
        return name;
    }
}

2018年11月3日 星期六

Java中對象的類型判斷

Java中對象的類型判斷


instanceof

判斷一個對象是否是一個類的實例,用Java中自帶的關鍵字instanceof似乎可以做到(僅從關鍵字名稱上可以猜測出),如下面的代碼:

public static void main(String args[]) {
    Object i = new Integer(7);
    if (i instanceof Number) {
        System.out.println("Integer i is a Number");
    } else {
        System.out.println("Integer i isn't a Number");
    }

    if (i instanceof Serializable) {
        System.out.println("Integer i is a Serializable");
    } else {
        System.out.println("Integer i isn't a Serializable");
    }

    if (i instanceof Integer) {
        System.out.println("Integer i is an Integer");
    } else {
        System.out.println("Integer i isn't an Integer");
    }

    if (i instanceof Float) {
        System.out.println("Integer i is a Float");
    } else {
        System.out.println("Integer i isn't a Float");
    }
}



類定義部分為:

public abstract class Number implements java.io.Serializable {}
public final class Integer extends Number implements Comparable<Integer> {}


運行結果:

    Console Output :
    Integer i is a Number
    Integer i is a Serializable
    Integer i is an Integer
    Integer i isn't a Float

然而好像和預期的不太一樣,能看出,使用該關鍵字不僅可以判斷對象是否是某個類的實例,甚至連該類繼承的基類和實現的接口也都能夠被識別為true,雖然這樣在邏輯上沒有任何問題,是可以把Integer當做一個Number來看來用,也當做一個Serializable來看來用,但是這樣返回的結果就沒有針對性了,太過於模糊,我們如果僅僅需要i instanceof Integer為true該怎麼做呢?
Class.equals

還好在Java有一個叫做Class的類,這是一個用來描述類信息的類,我們如果要精確判斷一個對象是否是具體的一個類的實例,可以這麼做:

public static void main(String args[]) {
    Object i = new Integer(7);
    if (i.getClass().equals(Number.class)) {
        System.out.println("Integer i is a Number");
    } else {
        System.out.println("Integer i isn't a Number");
    }

    if (i.getClass().equals(Serializable.class)) {
        System.out.println("Integer i is a Serializable");
    } else {
        System.out.println("Integer i isn't a Serializable");
    }

    if (i.getClass().equals(Integer.class)) {
        System.out.println("Integer i is an Integer");
    } else {
        System.out.println("Integer i isn't an Integer");
    }

    if (i.getClass().equals(Float.class)) {
        System.out.println("Integer i is a Float");
    } else {
        System.out.println("Integer i isn't a Float");
    }
}

2018年11月2日 星期五

java 區域變數的問題

int[] d = {5, 10, 60};

        int[] t = new int[1];
        int y; // 會有問題
       
        for (int i = 0; i < d.length; i++) {
            t[0] = d[i];
            y = d[i];
        }
       
        System.out.println("(%d, %d)",t[0], y);

2018年10月25日 星期四

java String, char 間的轉換

String str = "abc";
char[] bm;

// String 轉 char[]
bm = str.toCharArray();

// char[] 轉 String
str = String.valueOf(bm);

簡化 java System.out.print.*

import static java.lang.System.out;
//////////////////////////////////////////////////////
package com.xyz.util;

import java.io.*;

/**
 *
 * @author xman
 */
public class Out {

    public static void println(Object obj) {
        System.out.println(obj);
    }
    //--------------------------------------------------------------------------
    // 换行输出
    public static void println() {
        System.out.println();
    }
    //--------------------------------------------------------------------------
    // 不换行输出,
    public static void print(Object obj) {
        System.out.print(obj);
    }
    //--------------------------------------------------------------------------
    public static void printf(String format, Object... args) {
        System.out.printf(format, args);
    }
}

2018年10月17日 星期三

visual studio code debbuger

{
    // 使用 IntelliSense 以得知可用的屬性。
    // 暫留以檢視現有屬性的描述。
    // 如需詳細資訊,請瀏覽: https://go.microsoft.com/fwlink/?linkid=830387
    "version": "0.2.0",
    "configurations": [
        {
            "type": "java",
            "name": "java Debug (Launch)",
            "request": "launch",
            "cwd": "${workspaceFolder}",
            "console": "internalConsole",
            "stopOnEntry": false,
            "mainClass": "",
            "args": ""
        },
        {
            "name": "nodejs Launch Program",
            "type": "node",
            "request": "launch",
            "program": "${workspaceFolder}/app.js"
        },
        {
            "name": "nodejs: Current File",
            "type": "node",
            "request": "launch",
            "program": "${file}"
        },
        {
            "name": "Python: Current File (Integrated Terminal)",
            "type": "python",
            "request": "launch",
            "program": "${file}",
            "console": "integratedTerminal"
        },
        {
            "name": "Python: Attach",
            "type": "python",
            "request": "attach",
            "port": 5678,
            "host": "localhost"
        },
        {
            "name": "Python: Django",
            "type": "python",
            "request": "launch",
            "program": "${workspaceFolder}/manage.py",
            "console": "integratedTerminal",
            "args": [
                "runserver",
                "--noreload",
                "--nothreading"
            ],
            "django": true
        },
        {
            "name": "Python: Flask",
            "type": "python",
            "request": "launch",
            "module": "flask",
            "env": {
                "FLASK_APP": "app.py"
            },
            "args": [
                "run",
                "--no-debugger",
                "--no-reload"
            ],
            "jinja": true
        },
        {
            "name": "Python: Current File (External Terminal)",
            "type": "python",
            "request": "launch",
            "program": "${file}",
            "console": "externalTerminal"
        }
    ]
}

2018年10月2日 星期二

jquery 靜態工具

camelCase: 把 style key 化為駝峰

cleanData: 清除  $.data() 資料

cssHooks:  css 設定提取所需要的特殊處理

cssNumber:  哪些 css 是數值類

attrHooks:  處理頑疾 attr

support:  檢測瀏覽器的支援

valHooks:  針對 table value

contains(context, elem):  context 是否包含 elem

easing:  動畫用的運動函式

$.css:

$.style:

parseHTML(內文, context, option): context 通常指 document, option 若內文含 script 是否要執行

2018年9月26日 星期三

jq 偌多個組件需要統一使用 queue

// queue 的統一者
            const queue_1 = {
                name: "queue"
            };
            function t_1() {
                $(queue_1).queue(function (next) {
                    $("#box_1").animate({
                        left: "+=5%"
                    }, {
                        duration: 1000,
                        queue: false,
                        complete: function () {
                            next();
                        }
                    })
                });
            }

2018年8月29日 星期三

php 正則易碰到的問題

$s = '/a/b';

printf('<p>%s</p>', $s);
var_dump($s);

$res = preg_replace('/\//', '@', $s);

printf('<p>%s</p><hr>', $res);

//----------------------------

$s = '\\a\\b';
printf('<p>%s</p>', $s);
var_dump($s);

$res = preg_replace('/\\\\/', '@', $s);

printf('<p>%s</p><hr>', $res);
//----------------------------

$s = '\a\b';
printf('<p>%s</p>', $s);
var_dump($s);

$res = preg_replace('/\\\\/', '@', $s);

printf('<p>%s</p><hr>', $res);
----------------------------------------------------------

'/\\\\/' => php string = /\\/ => reg = /\/(匹配 '\')
'///' => php string = /// =>  reg = error
'/\//' => php string = /\// => reg = ///(匹配 '/')

----------------------------------------------------------
對 php preg來說  (/) 也屬於保留字
 ----------------------------------------------------------

PHP的跳脫字元



 對 "" 來說,對''無用
\$    顯示金錢符號 $
\"    顯示雙引號符號 "
\'    顯示單引號符號 '
\\    顯示倒斜線符號 \
\b    Backspace鍵
\n    換行符號<br>
\r    Return 歸位字元
\t    Tab鍵
\000 ~ \377    以16進位表示某一個字元
\x00 ~ \xFF    以8進位表示某一個字元

單引號 ' ' 是連跳脫字元都不處理,也就是 \n 會當成 \ 和 n ,而不是換行!這點要特別注意!很多 bug 就是由此而來,例如 str_replace \n 沒有作用之類的。
附帶一提,雖然單引號 ' ' 裡面不處理跳脫字元,但在單引號 ' ' 裡面要寫 (') 或 (\) 還是要記得跳脫一下,不然 PHP 會無法判斷字串結尾︰
<?php
  echo '\''; // 會印 '
  echo '\\'; // 會印 \
?> 
 

PHP preg_quote() 函數

PHP 正則表達式(PCRE)PHP 正則表達式(PCRE)
preg_last_error 函數用於轉義正則表達式字符。

語法

string preg_quote ( string $str [, string $delimiter = NULL ] ) preg_quote() 需要參數 str 並向其中 每個正則表達式語法中的字符前增加一個反斜線。 這通常用於你有一些運行時字符串 需要作為正則表達式進行匹配的時候。
正則表達式特殊字符有: . \ + * ? [ ^ ] $ ( ) { } = ! < > | : -
參數說明:
  • $str: 輸入字符串。
  • $delimiter: 如果指定了可選參數 delimiter,它也會被轉義。這通常用於 轉義 PCRE 函數使用的分隔符。 / 是最通用的分隔符。

返回值

返回轉義後的字符串。

實例

實例 1

<?php  
    $keywords = '$40 for a g3/400';
    $keywords = preg_quote($keywords, '/')
    echo $keywords
?>
執行結果轉義了 $ 和 / 特殊字符,如下所示:
返回 \$40 for a g3\/400

將文本中的單詞替換為斜體

<?php //在這個例子中,preg_quote($word) 用於保持星號原文涵義,使其不使用正則表達式中的特殊語義。 $textbody = "This book is *very* difficult to find."; $word = "*very*"; $textbody = preg_replace ("/" . preg_quote($word) . "/", "<i>" . $word . "</i>", $textbody); echo $textbody; ?>
執行結果如下所示:
This book is <i>*very*</i> difficult to find.
 



2018年8月21日 星期二

php 一些取得 object 資訊的 API


get_class(): 取得物件的 className

get_parent_class(): 取得物件繼承者的 className

get_object_vars():  返回類中所有的非靜態屬性

get_class_methods(): 函數的作用是返回由類的方法名組成的數組