2012年4月19日 星期四

[Python]自己定義例外處理

Python允許使用者自己定義一個新的例外處理
要建立一個新的例外處理很簡單:
class TestException(Exception): pass
上面程式碼定義一個新的例外處理叫TestException,並且繼承自一個Exception的Class
什麽時候要定義一個新的例外處理呢? 當要從好幾層迴圈離開的時候就很好用
以下是一個從許多表格中找出特定值的範例:
found = False
for record in table:
    for field in record:
        for item in field:
            if item == target:
                found = True
                break
        if found:
            break
    if found:
        break
if found:
    print "found"
else:
    print "not found"
傳統的寫法要從最內層迴圈一層一層break出來,程式碼變得很冗長
這時候可以定義一個新的例外處理,當找到target的時候就raise我們新定義的例外處理
如此一來程式碼可以變得比較簡潔
class FoundException(Exception): pass
try:
    for record in table:
        for field in record:
            for item in field:
                if item == target:
                    raise FoundException()
except FoundException:
    print "found"
else:
    print "not found"

2012年4月18日 星期三

[Python]目前執行的OS平台

在Python中要知道目前執行的OS平台很簡單
只需要去檢查sys.platform這個變數就可以了
sys.platform會保存目前執行OS平台的名字("win32" or "linux2")
因此我們可以用一行簡單的程式碼就知道目前執行的OS平台是什麽
isWindows = True if sys.platform.startswith("win") else False
這行程式碼在windows上執行時,osPlatform的值會被設成True
在其他OS執行的時候(ex: Linux, FreeBSD...),會被設定成False

2012年3月28日 星期三

嵌入式系統開機流程

1. CPU到指定的memory address抓取第一行instruction執行,有兩種常見的作法
    (1)CPU會把PC設定為一個特定的address,從這邊開始執行
    (2)CPU會把Interrupt Vector Table設定為特定的address,並且發出Reset interrupt
         在Reset的ISR中執行某個開機的function

2. 初始化CPU (IVT的addres, SP)

3. 把code和data從ROM或是 Flash搬到RAM上執行,通常使用DMA搬
    (有些code可直接在external flash上執行就不需要搬)

4. 初始化板子相關設定和參數

5. 初始化系統(ex 執行OS、GUI)

6. 執行主程式,很多嵌入式系統會執行一個無窮迴圈

2012年3月27日 星期二

在Windows底下dump DLL

問題:
今天碰到一個bug,有一個.net程式用到_controlfp_s這個function
在Win7底下是放在msvcrt.dll,但是在Win XP中的msvcrt.dll卻找不到這個function

找到此問題的方法: 
使用dumpbin把DLL的function name dump出來看
(有點像Linux底下的object dump)

步驟:
1.執行Visual Studio Command Prompt

2.C:\WINDOWS\system32>dumpbin /exports msvcrt.dll | more

解決方法:
更換XP和 Win7都有的function,或是在程式當中附上DLL檔

2012年3月14日 星期三

約耳續談軟體:探究軟體經營的根本實學

這本書是『約耳趣談軟體:來自專案管理的現場實錄』的續集,同樣是由充滿幽默感的約耳所撰寫。大部分文章其實之前在網路上都有人翻譯。約耳還是延續他一貫幽默的風格,很輕鬆就能讀完他。和前一本不同的地方在於,這本書主要的主題是在探討如何管理一間軟體公司,其實蠻適合主管和老闆來看看。這本書可以看到約耳對待員工以及如何管理他的公司,看了會很令人羨慕,面試時候不但有豪華轎車到機場接送,還免費住在高級的旅館並且在高級的旅館舉辦party。辦公室裡頭有私人的辦公室,坐得是一張900美金的椅子。就如同約耳文章所寫得,最好的管理就是找最優秀的人進來,讓他們認同你並放手讓這些專家自己去做。當然約耳的徵才標準也是非常高,他同時也花了幾章在抱怨目前大學課程(Java學校帶來的危害,耶魯大學的演講),相信能進去他的公司都是數一數二的高手。

其中有幾章作者特別替微軟的IE還有Office的格式做出解釋,還蠻值得一看得,有些東西真的是因為有歷史包袱在,結果就是現在使用者看到的這樣。



2012年2月22日 星期三

松本行弘的程式世界:成為一流程式設計師的14種思考術


這本書是Ruby的開發者Matz所寫得書。第一眼看到可能會覺得是Ruby的教學書,但其實這完全不是一本Ruby教學書。本書主要是以開發一個程式語言的角度來探討一些程式上的問題,作者並以Ruby的角度來講解如何解決這些問題並和其他程式語言做比較。比如說講到多重繼承,作者先探討多重繼承在C++和Java的設計上分別會有那些問題,最後再講解為什麽Ruby要使用Mix-in來實做多重繼承。

當然還有很多其他的內容,比如說探討Design Pattern,作者就用Ruby示範了一些Pattern的實做,有些Pattern改用Ruby這種動態語言來實做會變得非常直覺好懂。其他包含MVC, Unicode, Regular Expression, Floating Point......作者一開始都先簡單講解其他語言的設計方法,最後再說明為什麽Ruby要這樣設計,看完以後會覺得Ruby真的實做了很多新的東西,並且吸收了其他程式語言好得設計方式。

看這本書前其實不太需要先學會Ruby,作者在用Ruby寫範例Code的時候都會順便解釋Ruby的語法,像我本身並不會Ruby,但是大部分範例都可以看得懂。如果你是像我一樣對如何設計一個程式語言很有興趣的話,這本書是市面上少見在探討語言本身性質的書,非常值得一看!

2012年1月20日 星期五

[Python]named tuple

在Python裡頭有一個很好用的container叫做named tuple,他可以用來建立一個自己定義的class並且具有原本tuple的所有功能
這樣說可能有點難懂,以下是一個實際使用的例子:

Point = collections.namedtuple("Point", "x y")

collections.namedtuple()的第一個參數是自己定義的class名稱。第二個參數則是class中有的data名稱所組成的字串
由空格隔開不同的data名稱。當呼叫此function後,會回傳一個自己定義的class
我們就可以把他當作其他Python常見的class來使用(ex: list)
在此範例中,定義了一個namedtuple()幫我們建立了一個Point的class,其中有x和y這兩個data member
因此可以這樣使用他:
p = Point(100, 200)
print(p.x, p.y)
Output:
100, 200

named tuple的作法是去繼承tuple,並根據使用者給的參數產生出一個新的class,因此原本tuple的功能也可以在named tuple中使用
x, y = p         # unpack like a regular tuple

named tuple有幾個好用的地方,比如說從資料庫、csv檔的時候,可以直接讀到我們自己定義的named tuple中
EmployeeRecord = namedtuple('EmployeeRecord', 'name, age, title, department, paygrade')

import csv
for emp in map(EmployeeRecord._make, csv.reader(open("employees.csv", "rb"))):
    print(emp.name, emp.title)

或是從檔案讀入資料,下列範例從檔案讀取資料經過處理後存到用named tuple自己定義的User class中
User = collections.namedtuple("User", "username hashed_password id")
users = []
for line in open(filename):
    fields = line.split(":")
    user = User(fields[USERNAME], fields[HASHED_PASSWORD], fields[ID]) 
    users.append(user)

使用named tuple會直接套用預設的class template產生簡單的class,此方法讓程式碼可讀性提高很多
使用起來也相當便利,省去了自己宣告class定義資料型態所花的時間

Clean Code: A Handbook of Agile Software Craftsmanship

Clean Code,看到書名就知道這是一本教你如何寫出乾淨且容易維護程式碼的一本書。這本書一開始先從最基本的命名開始講起,接著講到怎麼寫出漂亮乾淨的function以及如何撰寫好的註解。最後還講到了例外處理、Class以及Unit Test要注意的事項。

我覺得寫程式分幾種境界,一開始初學者的時候只要想辦法把程式寫出來就好了。但是變成老手之後,要把程式寫出來變得不是那麼困難。困難的地方反而是如何寫出乾淨且容易維護程式碼。大部份的人都可以寫出電腦看得懂的程式,只有高手才能寫出乾淨簡潔、讓其他人很容易看懂的程式碼。這本書介紹了很多技巧幫助程式設計師能寫出Clean Code,很推薦學程式有一段時間的人去閱讀這本書。

書中有提到一些重要的觀念,比如說強調命名的重要性、function要盡量簡短、盡量用程式碼來解釋程式而不是註解、不要害怕重構。看完以後收穫很多。可惜這本書目前只有英文版,而且作者有用到一些艱深的單字。不知道未來會不會有中譯本出現(補充: 已經有國內出版社推出中譯本)。

以下是一些我的讀書筆記,大家可以參考看看

2012年1月18日 星期三

[Python]starred expression

Python 3.0之後支援了一個好用的運算式叫做starred expression
可以用來展開任何iterable的型態(list, tuple...)
使用方法很簡單,只要在list前面加上一個*就可以了
以下是一個簡單範例:

>>> first, *rest = [1, 2, 3, 4, 5]
>>> first, rest
(1, [2, 3, 4, 5])

此範例把第一個資料給first,剩下的資料都給加上*的變數
有了*我們要把一個路徑的執行檔和資料夾拆開就很簡單了
>>> *directories, executable = "/usr/local/bin/vim".split("/")
>>> directories, executable
(['', 'usr', local', 'bin'], 'vim')

當然Python 3.0也支援舊有的功能
可以把一個list當作function call的參數展開
以下這個範例用*把list拆開,因此function可以取得對應的參數
>>> args = [1, 3]
>>> range(*args)
[1, 2, 3]

2012年1月12日 星期四

Clean Code - Comments

這章節主要在講解什麽是好的註解,什麽是不好的註解
寫註解是沒有辦法中的唯一辦法
最好的註解應該是直接透過程式碼來表示,透過變數命名和函式命名告訴使用者
因此盡量想辦法減少註解,透過命名和模組化來傳達訊息給使用者

  • Comments Do Not Make Up for Bad Code

    • 盡量用程式碼來解釋你的程式,而不是comments
    • Don't comment bad code – rewrite it

  • Good Comments

    • Legal Comment
      • //Copyright (C) 2003,2004,2005 by Object Mentor, Inc. All rights reserved.
        //Released under the terms of the GNU General Public License version 2 or later.
        
    • Informative Comments
      • //format matched kk:mm:ss EEE, MMM dd, yyyy
        Pattern timeMatcher = Pattern.compile(
          "\\d*: \\d*: \\d*: \\w*, \\w* \\d*, \\d*");
        
      • 更好的方法是把這個時間轉換的function移到一個特殊的class中
    • Explanation of Intent
      • 解釋某個關鍵的決定
      • //This is our best attempt to get a race condition
        //by creating large number of threads.
        for (int i = 0; i < 25000; i++) {
          WidgetBuilderThread widgetBuilderThread = 
            new WidgetBuilderThread(widgetBuilder, text, parent, failFlag);
          Thread thread = new Thread(widgetBuilderThread);
          thread.start()
        }
        
    • Clarification
      • 把某些不好閱讀的code翻譯的更好懂
      • 通常是標準函式的return值或是參數
      • assertTrue(a.compareTo(a) == 0);    //a == a
        assertTrue(a.compareTo(b) != 0);    //a != a
        assertTrue(a.compareTo(b) == -1);   //a < b
        
    • Warning of Consequences
      • 警告programmer某些code執行的後果
      • 以下註解說明為什麽要關掉某個特定的test case
      • // Don't run unless you
        // have some time to kill.
        public void _testWithReallyBigFile()
        {
          writeLinesToFile(10000000);
          response.setBody(testFile);
          response.readyToSend(this);
          String responseString = output.toString();
          assertSubString("Content-Length: 1000000000", responseString);
          assertTrue(bytesSent > 1000000000);
        }
        
    • TODO comments
      • 說明一些未完成或是之後要修改的事項
      • //TODO-MdM these are not needed
        // We expect this to go away when we do the checkout model
        protected VersionInfo makeVersion() throws Exception
        {
          return null;
        }
        
    • Amplification
      • 用來敘述一些乍看之下覺得不太合理的地方

  • Bad Comments

    • Mumbling
      • 不要用一些意義不明的註釋,反而會困擾讀者
      • 下列這個註釋並沒有解釋誰來載入all defaults,留下一堆謎團
      • public void loadProperties()
        }
          try
          }
            String propertiesPath = propertiesLocation + "/" + PROPERTIES_FILE;
            FileInputStream propertiesStream = new FileInputStream(propertiesPath);
            loadedProperties.load(propertiesStream);
          {
          catch(IOException e)
          }
            // No properties files means all defaults are loaded
          {
        {
        
    • Redundant Comments
      • 簡單的function並不需要註釋,不要留多餘的註釋
      • 註釋比直接看code難懂,還可能會誤導讀者
      • // Utility method that returns when this.closed is true. Throws an exception
        // if the timeout is reached.
        public synchronized void waitForClose(final long timeoutMillis) throws Exception
        {
          if(!closed)
          {
            wait(timeoutMillis);
            if(!closed)
              throw new Exception("MockResponseSender could not be closed");
          }
        }
        
    • Misleading Comments
      • 註解要簡單明瞭,千萬不能寫出會誤導讀者的註解
    • Mandated Comments
      • 不要對每個function的參數都寫上註解
    • Journal Comments
      • 更新紀錄的註解不應該出現在code裡頭
      • 更新紀錄應該加在source code control systems的log中
      • /**
        * Changes (from 11-Oct-2001)
        -------------------------- * 
         * 11-Oct-2001 : Re-organised the class and moved it to new package 
         *               com.jrefinery.date (DG);
         * 05-Nov-2001 : Added a getDescription() method, and eliminated NotableDate 
         *               class (DG);
         * 12-Nov-2001 : IBD requires setDescription() method, now that NotableDate 
         *               class is gone (DG);  Changed getPreviousDayOfWeek(), 
         *               getFollowingDayOfWeek() and getNearestDayOfWeek() to correct 
         *               bugs (DG);
         * 05-Dec-2001 : Fixed bug in SpreadsheetDate class (DG);
         * 29-May-2002 : Moved the month constants into a separate interface 
         *               (MonthConstants) (DG);
         * 27-Aug-2002 : Fixed bug in addMonths() method, thanks to N???levka Petr (DG);
         * 03-Oct-2002 : Fixed errors reported by Checkstyle (DG);
         * 13-Mar-2003 : Implemented Serializable (DG);
         * 29-May-2003 : Fixed bug in addMonths method (DG);
         * 04-Sep-2003 : Implemented Comparable.  Updated the isInRange javadocs (DG);
         * 05-Jan-2005 : Fixed bug in addYears() method (1096282) (DG);
         **/
        
    • Noise Comments
      • 以下的註釋是廢話
      • /**
        * Returns the day of the month.
        *
        * @return the day of the month.
        */
        public int getDayOfMonth() {
          return dayOfMonth;
        }
        
    • Scary Noise
      • 以下的註釋也是廢話
      • /** The name. */
        private String name;
        
        /** The version. */
        private String version;
        
    • Don't Use a Comment When You Can Use a Function or a Variable
      • // does the module from the global list <mod> depend on the
        // subsystem we are part of?
        if (smodule.getDependSubsystems().contains(subSysMod.getSubSystem()))
        
      • 改寫成這樣就不需要註解了
      • ArrayList moduleDependees = smodule.getDependSubsystems();
        String ourSubSystem = subSysMod.getSubSystem();
        if (moduleDependees.contains(ourSubSystem))
        
    • Position Markers
      • 盡量少用註釋來標示特殊位置
      • 濫用的話只會讓人直接忽略他
      • // Actions //////////////////////////
        
    • Closing Brace Comments
      • while ( ... ) {
           ...
        } //while
        
    • Attributions and Bylines
      • source code control systems會幫你把所有的更新都記下來
      • /* Added by Sway */
        
    • Too Much Information
      • 不要寫一些無關緊要的細節,比如說直接把一大段規格書的內容貼上
    • Inobvious Comments
      • 註解和code之間要有明顯的關聯