2014年12月29日

Gradle(1) -- 介紹

image_thumb5

歷史介紹


當我們發展軟體過程由需求訪談、編寫程式、編譯、測試、打包,發佈,我們希望可以自動化將這些重複繁雜的步驟,這些工具幫我們完成自動化任務,可以稱為建構語言。建構語言必須由make腳本開始說起,在早期C語言,當專案發展到一定的大小,會漸漸出現瓶頸,這時make工具的誕生解決的這些大專案的問題,主要他解決的一個專案的編譯規則,定義哪些文件需要編譯、哪先不需要編譯等等。在Java程式語言Ant編譯工具想必很多人不陌生,在2000年所誕生,主要是使用XML去定義編譯編譯規則,但是發展一段時間,會發現他無法檢查系統模組相依性。這時為了解決相依問題才發展Ivy來輔助Ant編譯工具。Maven也是常耳聞的編譯工具之一,主要的優點透過一定的約定形式去撰寫編譯規則,但是缺點是當專案太大會使您的pom.xml過於忙亂,而無法正常工作。

專案自動化優點


     (1) 防止人為錯誤
     (2) 更容易建構專案
     (3) 維持軟體品質

Gradle誕生原因


Gradle主要結合Ant和Maven的優點而誕生,主要有下列的優點
(1) 使用動態語言(Domain Specific Language,DSL)代替靜態語言,支援Groovy語言。
(2) 可以準確的編譯每個程式
(3) 解決編譯時的相依問題,富有彈性
(4) 支援多個專案建製,可以解決各專案之間的相依性
(5) gradle支援Ant和Maven的腳本

Gradle 安裝


(1) Gradle安裝需要的套件
     A. Java JDK 6.0以上 :   http://www.oracle.com/technetwork/java/javase/downloads/index.html
     B. Gradle安裝檔: http://gradle.org/gradle-download/

(2) Gradle安裝套件
     A. gradle-[version]-all.zip : 包含原始檔,執行檔和手冊
     B. gradle-[version]-bin.zip : 執行檔

    C.
gradle-[version]-src.zip : 原始檔,你可以客制企業特定的功能

Windows 安裝
第一步: 下載ZIP檔  http://gradle.org/gradle-download/第二步: 設定環境變數 :
        變數名稱: GRADLE_HOME
        變數值:    C:\gradle-2.2  (解壓後,gralde的目錄)



          image

第三步: 設定PATH路徑
設定GRADLE_HOME到PAHT變數

        image    


第四步: 測試
如果有出現gradle版本訊息,就表示設定成功

image

Gradle 常用的指令


格式 : gradle [option...] [task...]
-?, -h, --help Shows this help message.
-a, --no-rebuild Do not rebuild project dependencies.
-b, --build-file Specifies the build file.
-d, --debug Log in debug mode (includes normal stacktrace).
-i, --info Set log level to info.
-m, --dry-run Runs the builds with all task actions disabled.
-q, --quiet Log errors only
-s, --stacktrace Print out the stacktrace for all exceptions.
--stop Stops the Gradle daemon if it is running.
-v, --version Print version info.

Linux安裝
   

第一步: 下載ZIP檔  http://gradle.org/gradle-download/
第二步: 編輯個人設定檔(~/.profile)
加入:
       GRADLE_HOME  = 安裝位置
       PATH=$PATH:$GRADLE_HOME/bin

Logging Options

日誌設定: --quiet (or -q),-debug (or -d), --info (or -i), --stacktrace (or -s),
                  --full-stacktrace(or -S)


Gradle JVM


Gradle的JVM設定選項跟JAVA的JVM相同,例如在 JAVA_OPTS=512MB你想要增加,
例如:GRADLE_OPTS="-Xmx1024m"

建構生命流程

(1) 編譯程式,將原始檔編譯成二進位檔
(2) 打包(環境檔與二進制檔)並
壓縮
(3) 單元測試與整合測試
(4) 發佈artifacts檔(jar, war)
(5) 佈署程式到正式機
(6) 增量建置
(7) 產出報表

預設專案架構

Gradle是繼承Maven的架構,使用Gradle建構Java專案必須遵照下列的架構,才可以正常使用。

src /
       ----main/
                     ….java/
                     ---resources
        ---- test
                     ….java/
                     ---resources

2014年11月23日

Python Study (8) – Function


Introduction

Function is a Python’s basic structure. Function often is used to reuse code. you can repeat task that define a function for code reuse.

Function Advantage 

(1) Maximizing code reuse and minimizing redundancy
     In developing software,  don't repeat yourself is a a principle . We use function to achieve the goal in Python.A section code is adopted many times or offer other to use. We need to package to a function and offer many time for reuse .

(2) Procedural decomposition
A flow program is combined from



Function component 

(1) def

  • Syntax
def name(arg1, arg2….) :
    statements …
  • Example

def add(a, b):
           print(a+b)
>>>add(1,2)
3

(2) return

  • Syntax
def name(arg1, arg2….) :
    statements …
return result
  • Example

def add(a, b):
return a+b

>>>print(add(1,2))
3

(3) lambda
     lambda is keyword in python, It mainly is used to create anonymous function.

  • Syntax
lambda arg1, arg2, ....: statments # lambda is equal to follow as :
def fun(arg1, arg2,….) :   
return result
  • Example

>>> add = lambda a, b : a+b
>>> add
<function <lambda> at 0x0000000003327D08>

>>> add(1,2)
3

(3)lambda

Variable Scope 

>>> k=1
>>> def add(a,b):
    k=10
    print(k)

>>>k
1
>>>add(1,2)
10

Why k value is different in add function and outside add function ? 
1.Local variable : In a function , A variable is declared  and the variable only use in function
2. nested variable: In nested functions, A variable is declared in enclosing function.
3. global variable : A variable is declared  and the variable is hold  in file
4. nonlocal variable: In Python3.x  it introduce a new nonlocal statment , It only define in a function.

Example

>>> counter = 1
>>> def increament():
         global counter
         counter = 10
         counter = counter +1
         print(counter)

>>> increament()
11
>>> counter
11

 



 








Build-in Scope :
    Servial variable is builed-in python’s library.

>>> import builtins
>>> dir(builtins)
['ArithmeticError', 'AssertionError', 'AttributeError', 'BaseException',
'BlockingIOError', 'BrokenPipeError', 'BufferError', 'BytesWarning',
'ord', 'pow', 'print', 'property', 'quit', 'range', 'repr', 'reversed',
'round', 'set', 'setattr', 'slice', 'sorted', 'staticmethod', 'str', 'sum',
'super', 'tuple', 'type', 'vars', 'zip']


 















 

2014年11月13日

Python Study (7) – Statements


Introduction

Programming statements are used to expresse action or assign a variable in program.Each statement  has own syntax and purpose. We can combine these statements to achieve specific purpose.

Assignment Statements

Assingment statement is used to set reference of object or value stored in monery address by a variable name.

(1) normal assignment : fruit = “apple”

(2) sequence assignment:  a,b = 'Jack', 'John'

(3) List assignment :

(4) Augmented assignment:
     >>>a =1
     >>>a+=1

(5) Sequence assignment

  • Sequence one to one
>>>seq = [1, 2, 3, 4]
>>> a,b,c,d = seq
>>> a,b = seq  #seq have 4 elements, but assignemnt elements just have 2
Traceback (most recent call last):
  File "<pyshell#9>", line 1, in <module>
    a,b = seq
ValueError: too many values to unpack (expected 2)

>>> a,b,c,d = seq
>>>a
1
  • Sequence one and rest
>>>seq = [1, 2, 3, 4]
>>> e, *f = seq[0:3]    #e get first element, other element assign f
>>> e
1
>>> f
[2, 3]

>>> *g, h = seq[0:3]  #
>>> g
[1, 2]
>>> h
3

>>> i, *j, k = seq[0:4]
>>> i
1
>>> j
[2, 3]
>>> k
4

  • Boundary cases
>>>seq = [1, 2, 3, 4]
>>>

 

(6) Mulitple-target assignment
     There has many assignment variable.

>>> a = b =0
>>> b = b + 1
>>> a,b
(0, 1)

>>> a =b =[]
>>> b.append(10)
([10], [10])

>>> a=[]
>>> b= []
>>> a.append(21)
([],[42])




 

Control Statements

1.if/elif/else statment

  • Syntax

if expression :
      statement1
elif:
       statement2
else:
      statement3


  • Example
    (1) There are a fruit list , we check apple if it is in the list.
fruit = ["apple","banana"]
if "apple" in fruit:
    print("found it!)
else:
    print("don’t found it!")
--------------------------------------
found it !

       (2) Jack

grade = {"Jack":90, "Joe":60, "Bryant":50,  "Hacker":30}
if grade["Hacker"]>=90:
    print("perfect!")
elif grade["Hacker"]<=90 and grade["Hacker"] >=60 :
    print("great")
elif grade["Hacker"]<60:
    print("hard")

--------------------------------------
hard

2. for/else

  • Syntax

for var inm sequence:
    statment1

       (1) 

list1 = {1,2,3,4,5}
for a in list1 :
    print(a)

--------------------------------------
1
2
3
4
5

3.while/else

  • Syntax

while( expression):
     statment1

  • Exception

while True:
    inputNumebr = input("Enter a numebr:")
    if inputNumebr== "stop":break
        print(int(inputNumebr))
-----------------------------------------------------------------------------------------Enter a numebr:1234
1234
Enter a numebr:stop

Note : you input a number 


Handling Errors


In python when the programe is executed how to handle it and throw message to notify operator.

  • Syntax

try:
    statement01
except:
    statement02

  • Exception

while True:
    inputNumebr = input("Enter a numebr:")
    if inputNumebr== "stop":break
    try:
        print(int(inputNumebr))
    except:
        print("Please input a number!")
-----------------------------------------------------------------------------------------Enter a numebr:1234
1234
Enter a numebr:stop

Note : When  input is not a  number , it will enter into except section and    show “Please input a number”
 




 

 

2014年11月9日

Python Study (4)– Dynamic type


Introduction

In many programs, You need to declare data type to tell compiler, but  you don’t do it  in Python. It are determined automatically at runtime. 

>>> a = “hellow ”    # without delcaring data type
          

Assigning variable 
1. Create an object
2. Create an variable
3. Create reference variable to object


Example :
The example create a variable and named “a”, then assign enough space to the object. the variable link to the object as reference.

>>> a = “hellow ”    
          
image


Example:
The float object is value 1.2 and tell python the object is a float-point-number at first assignment.

>>> a =  1.2          # first assign
>>> a =  2             # second reassign
>>> a =  ”apple”  # third reassign
          

Python Study (5)– String Type


Introduce to string type 


ASCII is a sample form of Unicode text, but many text may be not non-English-text source.File working in two modes are  text and bytes ,We need to understand differnt of String of object type in Python3.X and Python 2.X. 

Python3.X :
    (1) str           : handle text of Unicode form
    (2) bytes       : handle binary data
    (3) bytearray : handle mutable variant of bytes
Python2.x:
   (1) str           :  handle 8-bits text and binary data
   (2) unicode    :  hanlde Unicode text
   (3) bytearray  : handle mutable variant of bytes. ( support 2.6 or later)


1.String Basics 
Everything is string.String can be used to represent informations of all kinds(e.g. profile, song…), these informations can be encoded as text or bytes.  


2.String Literals

In python, String function handle various data types.
quote mark description
single quote
‘temp’s’
double quote
“temp’s”
triple quotes “”” mutiline…  ”””
  ‘’’mutilne… ‘’’
raw string r”data”
escape sequences “s\tdat\n”
bytes b’sp\x01’
unicode u’eggs\u001’

Problem 1. single and double-quoted string are the same ?
       In python, single- and double-quote  characters are interchangeable. string
       literals is written enclosed in either two single or two double quotes.

Example:


>>> 'apple',"apple"
('apple', 'apple')

>>> 'Tom"s apple',"Tom's apple"  //embed a quote
('Tom"s apple', "Tom's apple")

>>> 'Tom\'s apple',"Tom\'s apple" //use escape quote
("Tom's apple", "Tom's apple")




Escape  


Escape Description
\n
Newline
\t
tab
\xhh
hex value
\o
octal value
\’
single quote
\”
double quote
\\
backslash(\)
\0
null: binary 0 character
\N{id}
Unicode database ID
\uhhhh
Unicode character with 16-bit hex value
\uhhhhhhhh
Unicode character with 32-bit hex value

Example:

>>> “abc\ndef\t ghi ”
'abc\ndef\t ghi'
>>> print(“abc\ndef\t ghi ”)
’abc
   def    ghi



Basic Operations 

Operation Description
len(str) return the length of a string or size of the string in the memory
str + str return concatenate two string to create new string
str * n return  adding a string to itself a number of times
[start:end] return slicing the string
image
[start:end:step] return slicing the string by step
Example:
             s = “abcdefghijklmnopqrstuvwxyz”


>>> s = "abcdefghijklmnopqrstuvwxyz"
>>> len(s)
26

>>> s+"1234567890"
'abcdefghijklmnopqrstuvwxyz1234567890'

>>> s*2    
'abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz'
>>> s[0]
'a'
>>> s[-2]
'y'

#slicing>>> s[0]
'a'
>>> s[-1]
'z'
>>> s[1:]         #get all elements beyond the first
'bcdefghijklmnopqrstuvwxy'
>>> s[3:6]
'def'
>>> s[:-1]   # get all elements unitl the last

Note: s[0] fetches the string at offset 0 from the left and return “a”;s[-1] gets the string at offset 1 back from the end.
String conversion 

In python, if the string looks like number and you want to add a number and the string together. it will happe a error(TypeError) so you need to convert the string to integer.


>>> "30"+1
Traceback (most recent call last):
  File "<pyshell#79>", line 1, in <module>
    "30"+1
TypeError: Can't convert 'int' object to str implicitly




These are String conversion tools

conversion Description
int(str) return converted integer
int(str, base=10) return converted integer by base
str(obj) return converted string
repr(obj) return code string,
float(text) return  floating-point-number
ord(str) it only convert a single character to integer
chr(int) an integer code convert to the correspanding character
bin(int) return binary
Example:
(1) A number and a string add together, the string is converted to integer.

(2) A number and a string add together, the number is converted to string.
(3) A string looks like a  float-point-number, the string is conveted to float.

   a = 1, b = ”2”, c = “3.14”


>>> a = 1
>>> b = "2"
>>> c = “3.14”
>>> a + int(b)      # (1) convert to integer
3

>>> str(a) + b     # (2) convert to string
'12'


>>> float(c)
3.14

Example :
    (1) single character convert to integer code
    (2) integer convert to single character




Example:
   (1) binary to integer
   (2) integer to binary



>>> int('1111',2)
15

>>> bin(15)
'0b1111'


String function 



function Description
capitalize() retrun the first character of the string is  capitalized
casefold() return the string is lowercased
center(int width)
encode(encoding=”utf8”) Return an encoded version of the string as a bytes object.
find(str) return index in the string where substring is found
index(str) like find()
isalpha() return true if all characters are alphabestic in the string
isdecimal() return true if all characters are decimal in the string
isdigit() return true if all characters are digits in the string
lower() like casefold()
split() return a list of the words in the stirng by sep as the delimiter string.
zfill(int width) return the string filled with ‘0’













2014年11月6日

JAVA 字串格式化

應 用 時 機 

在日常生活中,常看到文字的格式為日期、時間、貨幣或是特定格式輸出等等,在Java中可以使用formatter來自訂字串的格式。我們可以分為這五種轉換形態

1. 常規 : 一般文字格式
2. 字元 : 顯示字元的型態,char、byte、short
3. 日期/時間 : 用來輸出date、time、calendar等等
4. 百分比: 輸出百分比型態,以百分比表示”%”
5. 換行符號: 換行符號(\n)
6. 數字: 用來可以輸出數字

1.常 規 格 式 化 

格式符號 說明

-

最小寬度內左對齊,不可0使用

#

用在8進位與16進位的表式

+

空白

正號加空格,負號加-

0

不足填零補足

,

每三位數字,加上,

(

參數為負,以括號把數字刮起來


以下實例可以指定輸出的對象,這種特殊格式以%index$來做指定,下列範例是將a和b對調顯示

public static void main(String[] args) {
      //宣告變數
      int a = 10 ;
      int b = 20 ;
      int c = 30 ;
     
      System.out.printf("%d %d %d \n",a,b,c);   //正常顯示
     
      //使用format物件
      Formatter format = new Formatter() ;
      System.out.println(format.format("%2$d %1$d %3$d", a, b, c)) ;
      format.close();

      System.out.printf("%2$d %1$d %3$d \n",a,b,c);  //使用printf
    }

===================
10 20 30
20 10 30
20 10 30

 

2.字 元 格 式 化

格式符號 說明
b 或 B
如果是null,為false; 如果是boolean型態,則輸出String
h 或 H
輸出為16進位
s或 S
輸出為字串
c 或 C
輸出為Unicode字元
d
輸出為數字

o

輸出為八進制

x 或 X

輸出為16進制

e 或 E

輸出為科學符號表示

f

輸出為浮點數
g 或 G
設定精準度去顯示數字的表示

a 或 A

輸出以十進位或是科學符號表示

t 或 T

日期或時間輸出表示


程 式 案 例 

public static void main(String[] args) {
    
       System.out.printf("16進制 : %h \n",20);
       System.out.printf("科學符號: %e", new BigDecimal("10000"));
 
    }
===================
16進制 : 14
科學符號: 1.000000e+04

 

3.日期與時間格式化

在JAVA中比較常用的來顯示日期與時間格式為java.text.DateFormat 和 java.text.SimpleDateFormat 兩種:

(1). DateFormate:不需要用建立實例,利用getDateInstance()函式來建立日期格式物件,它根據Locale不同語系和區域來顯示當地的日期與時間。
(2). SimpleDateFormate : 常用於解析和格式化日期時間字串,它也有支援Locale的設定。

時間 說明

H

以24小時格式呈現,00~23

I

以12小時格式呈現,00-12

k

以24小時呈現,0-23

l

12小時格式,0-12

M

顯示分鐘,00~59

S

顯示秒,00~60

p

依照locale設定顯示上午或是下午

z

GMT標準也可以稱為格林威治標準時間,台灣+8小時

Z

配合Formatter使用,顯示GMT

R

以24小時格式顯示,格式為"%tH:%tM"

T

以24小時格式顯示,格式為"%tH:%tM:%tS"

 

日期 說明

B

月份全稱,Fanuary,May

b

月份簡稱,Fan,May

A

星期全稱,Sunday, Mondday

Y

以四位數顯示年份,例如: YYYY

y

以兩位數顯示年份,例如: yy

m

以兩位數顯示月份

d

顯示一個月中第幾天,01-31

e

兩位數

D

日期,格式化: %tm/%td/%ty

c

日期與時間,格式化:%ta %tb %td %tT %tZ %tY

F

ISO 8601 日期格式,格式化: "%tY-%tm-%td"。

d

顯示日,00-31


程 式 案 例


範例一、
顯示今天日期西元年-月-日 小時:分:秒,使用格式


public static void main(String[] args) {
       Date date = new Date()  ;
       System.out.println(date.toString());             //預設date的日期輸出格式
       System.out.println(date.toGMTString());     //格林威治標準時間
    
      //自訂輸出模式
       DateFormat dateFormat = new SimpleDateFormat(
                                              "YYYY-MM-dd hh:mm:ss") ;
       System.out.println( dateFormat.format(date)); 
}

===================
Sat Nov 08 09:52:34 CST 2014
8 Nov 2014 01:49:58 GMT
2014-11-08 09:52:34


範例二、顯示今天的日期,英國區域的英文語系,


public static void main(String[] args) {
  
          Locale locale = new Locale("cy", "GB");
          DateFormat cyDateFormat = DateFormat.getDateInstance(
                            DateFormat.DEFAULT, locale);
          DateFormat cyTimeFormat = DateFormat.getTimeInstance(
                            DateFormat.DEFAULT, locale) ;
         String cyDate = cyDateFormat.format(new Date()) ;
         String cyTime = cyTimeFormat.format(new Date()) ;

         System.out.println(cyDate+" "+cyTime);

//SimpleDateFormate
           Locale locale2 = new Locale("cy", "GB");
           String formatePattern = "YYYY-MM-dd  HH:mm:ss EEEEEZ" ;
           DateFormat cySimpleDateFormate = new SimpleDateFormat
                             (formatePattern, locale2) ;

          String cyDateTime = cySimpleDateFormate.format(new Date()) ;
          System.out.println(cyDateTime);
}

===================
Nov 8, 2014 12:57:17 PM
2014-11-08  13:00:48 Saturday+0800


範例三、解析日期或是時間,假設某公司的人資員工生日為20141101,但是在網頁上希望可以加上/符號,方便人員瀏覽

public static void main(String[] args) {
  
         String pattern = "yyyyMMdd";
        String inputDate = "20140101" ;
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat(pattern);

        try {
            Date date = simpleDateFormat.parse(inputDate);
            DateFormat birthDateFormat = new SimpleDateFormat("YYYY-MM-DD");
           
            System.out.println(birthDateFormat.format(date));
           
        } catch (ParseException e) {
            System.out.println(e.toString());
        }

}

===================
2014-01-01




4.百 分 比

如果在畫面上我們希望可以輸出百分比符號,要如何達到,我們可以知道「%」已經是一個特殊符號,需要利用轉義字符去完成,但是在format的轉義字元並不是「\」,而是「%」來完成

public static void main(String[] args) {
  
        System.out.println(String.format("%f%%", ((10f/100f)*100f) ));
        System.out.println(String.format("%d%%", 12 ));
}

===================
10.000000%
12%

5.換 行 符 號

public static void main(String[] args) {
        
         System.out.printf("\n");
        
        //字串物件本身提供格式化功能
         System.out.print(String.format("%d %n", 111));    
}
==============

111

6. 數字/貨幣

Java語言在現今已經支援各式各樣的商業應用,在企業中報表金額部分,可以顯示多國的幣值符號與各種數字。我們可以利用NmberFormat物件來完成

public static void main(String[] args) {
        
        int num =10 ;
         NumberFormat format01 =  NumberFormat.getCurrencyInstance(new Locale("",Locale.CANADA.getCountry()));
         System.out.println(format01.format(10.01));

         BigDecimal b1 = new BigDecimal("10.50") ;
         NumberFormat format02 = new DecimalFormat("#,###.00") ;
         System.out.println(format02.format(b1);

         BigDecimal b2 = new BigDecimal(0.3) ;
         NumberFormat format03 = NumberFormat.getPercentInstance() ;
         System.out.println(format03.format(b2));
        
}
==============

CAD 10.01
10.50
30%



字 串 格 式 化

字串本身的物件中,也有提供靜態格式化的方法


public static void main(String[] args) {
   
    int no = 2 ;
    String strNo = String.format("%02d", no) ;
    System.out.println(strNo);
   
}
==============
02