Total Pageviews

2016/04/03

[Python] Install Python IDE for Eclipse


PyDev is a plugin that enables Eclipse to be used as a Python IDE (supporting also Jython and IronPython).

It uses advanced type inference techniques to provide features such code completion and code analysis, while still providing many others such as a debugger, interactive console, refactoring, etc.
- See more at: https://marketplace.eclipse.org/content/pydev-python-ide-eclipse#sthash.0052eVTc.dpuf

Here is the installation steps:
1. Open Eclipse
2. Help => Install new software


3. Click Add button


4. Fill in name and location, then click OK button


5. Check PyDev and click Next button


6. Click Next


7. Choose I accept option and click Next button




After install PyDev plugin, you need to restart your Eclipse

8. Configure Intercepter in preference


9. Choose the interpreter you have installed in your computer



Create a PyDev Module
1. create a new PyDevProject


2. Fill in project name, and choose Grammar version & intercepter


3. Create a utility module which name myUtils


The python code is as bellows:
'''
Created on 2016年1月24日

@author: albert
'''
def printHelloMessage(name):
    print('Hello! ' + name)
    
def addTwoNumbers(num1, num2):    
    return num1 + num2

4. Create another test client module to call myUtils





The python code is as following:
'''
Created on 2016年1月24日

@author: albert
'''
from utils import myUtils

if __name__ == '__main__':
    myUtils.printHelloMessage("Albert")
    
    print(myUtils.addTwoNumbers(10, 20))

Here is the test result:

2016/04/02

[閱讀筆記] 圖解國富論 Part 1



  1. 自利(self-love)原則:經濟人活動的主要動力是個人利益 (自利),而要滿足個人利益,只能透過和別人交換服務 (滿足自己也滿足他人)。人的自利行為就是個人對自身利益的追求過程,在『看不見的手』的指引下,經濟人追求自身利益的最大化的過程中,也促進社會公共利益的增長
  2. 承認自利,尊重他利,發展互利,建構了整個西方經濟學經濟發展原則的基礎
  3. Adam Smith認為,一切特惠或限制的制度,一經完全廢除,最單純的自然自由制度就會建立起來。
  4. 所謂的自由,是指不損害他人自由的所有人的自由,才是具有真正意義的自由主義。
  5. 財產權是一種具有排他性的所有權,它規定了對於物質財富的私人所有權。經濟學家認為,窮人一直佔多數的原因在於窮人的財產權沒有受到保護,故到20世紀,由於窮人的私有財產權受到嚴格的保護,歐美國家才出現數量占絕對優勢的中產階級
  6. 財富分配不均乃是政府產生的真正原因,為了保護財產權,有必要成立政府,建立公正的法律
  7. 哪裡有大宗財產存在,哪裡就有大量不平等存在。因此,大宗財產的獲得,必然要有公民政府的建立
  8. 社會有責任為窮人提供能夠據以『改善它們現況』的社會福利制度
  9. 社會要保證,每個人的致富機會是均等的,競爭的規則是公平的
  10. 由於每個人的地位、財富、社會關係、所受的教育不盡相同,就算處於公平的制度下,每個人追求自我利益的社會必定是弱肉強食的社會,並產生階級的對立。假如社會制度不公平,那麼弱肉強食的狀況會更嚴重
  11. 馬太效應,用來形容貧者越貧,富者越富的現象,又比喻為滾雪球,如果你是幸運的人,你的雪球會越滾越大
  12. 看不見的手:只有在完全自由市場才會出現。在自由市場中,買賣雙方的活動都在自動自發地將市場價格推向均衡價格,讓買賣雙方獲得最大滿足
  13. 自由競爭的市場能夠在無意中促進經濟福利與發展。競爭創造了低價、高需求、更多的就業和經濟發展,進而提高工資與充分就業,這一切都是看不見的手所推動,一切是無意識的
  14. 人只有在社會中才能生存,他生來就是和在塑造他的環境中生活。人類社會的所有成員都需要互相幫助,但也面臨彼此互相傷害
  15. 企業生產什麼產品或提供什麼服務,取決於消費的需求及其利潤
  16. 市場競爭必然促使企業提高生產力,使社會生產力不斷地向前發展
  17. 工作經過分工後,生產率比原來沒有分工時提高了數十倍。故凡生產力程度較高的國家,其分工程度也達到了一定的高度
  18. 勞動是衡量實質價格的唯一標準;商品的名目價格則是用貨幣衡量的
  19. 分工的產生是由交換而引起的,所以分工的範圍必然是受到交換能力的限制
  20. 一個人是富有還是貧窮,必然根據他所能支配或購買得起它們的勞動數量來決定
  21. 商品的實質價格以勞動價值來表示,它是一切商品交換價值的實質尺度,但由於商品更多是用來和其他商品進行交換,所以貨幣表示的名目價格則更為常見
  22. 世界上物價和工資總是在持續增長,溫和的物價和工資上漲是經濟常態
  23. 土地私有化後,商品價格多半由地租、工資、利潤三者組成,如穀物價格中,一部分用來支出給地主的地租,一部分用來支出勞動者的公司,另外一部分就是農場業主的利潤
  24. 商品的自然價格等於地租+勞動工資+資本利潤。商品的自然價格是固定的,而其市場價格則受到供應量的影響而左右其價格變動。
  25. 市場像水一樣,使生產流向具有低成本優勢的企業,淘汰生產成本太高的企業;市場又像火一樣,把物品送到對它評價最高的消費者面前(願意花比較多錢購買的消費者),忽略對他評價較低的消費者
  26. 在既定的市場價格下,工資的高低必定受制於資本利潤和地租
  27. 只有當國家的收入和資本存量增加時,對勞動力的需求才會增加,工資才能增長
  28. 最高的勞動工資不是出現在最富有的地區,而是出現在發展最快的地區,因為人力供不應求
  29. 當國家的經濟出現停滯或衰退,工資就很難增長,甚至會衰退
  30. 工資與物價的比例一旦失衡,生育、醫療、教育等諸多問題也會接踵而至

2016/04/01

[閱讀筆記] 你還在努力省錢來投資理財嗎? Part1


  1. 如果某樣商品複雜又難以理解,你很可能根本不該投資
  2. 儲蓄和投資的基本原則很容易學,但不代表我們就學會了
  3. 人生無常,不會永遠照我們想像的方式運作
  4. 超級富豪與平凡人的鴻溝越來越大,你根本無法靠投資來縮小差距。撇開少數福星高照的dot com百萬富豪不談,股市和房市並非許願池,並沒有點石成金的能力
  5. 幾乎沒有人注意到,我們在指望靠個人理財、房地產和股市來修正長期經濟弊病。促使我們欣然接受用自助理財的方法來解決社會問題。然而,這種自助不求人的理財中心思想是:I can do it
  6. 上電視的理專需要建立權威性來吸引我們注意,讓我們相信唯有他們真的握有正確解答。如果他們真的知道答案,我們會不再需要他們,進而終止與他們的業務往來。所以,我們獲得的建議大多不可信與不可行
  7. 我不是主張所有財務建議都沒有用,重點是理解及掌控我們的財富,從事自主性的理財活動
  8. 金融業不斷售予一個夢想給大眾:個人理財具有魔力,可以補救停滯的薪水、貧富所得不均,和一年不如一年的社會福利
  9. 我們絕大多數人的薪資跟不上經濟趨勢,先是遭逢通貨膨脹的重擊,再面臨所得M型化,所得最高階層與普羅大眾的差距越拉越遠,我們完全陷入停滯
  10. 從1979到2007年,美國經濟前1%所得者的稅後收入暴增281%,前20%的人所得增加95%,正中間的1/5僅僅增加25%
  11. 小心諸如財星、財智、華爾街日報、紐約時報等等出版品的內文和廣告,其內文吹捧了哪些共同基金的場,就找得到那些基金的廣告
  12. 人必須先找到錢,才能投資,然而這對一般美國人而言,都成問題
  13. 美國的階級流動性明顯低於社會階級分明的歐洲,根據研究顯示,生於美國資產底層1/5家庭的小孩,成年後擠身前40%的機會不到20%
  14. 花錢的問題在於會減少我們的儲備金,但他並非財務不幸的根本原因。長久而言,花兩塊美金買拿鐵會積少成多。但那不是直接因素,主因結合了昂貴的醫療費用、失業等
  15. 財務不幸的真正問題在於固定成本,也就是難以削減的事物,2000年代,住屋、醫療和教育費用佔了一般家庭可自由支配所得的75%,在1973年是50%
  16. 以美國為例,醫療服務的成本繼續以高於通膨率的速度增加,健保的價格在2001至2011年之間漲了一倍。21世紀的第一個十年,養小孩的成本增加40%。上大學的成本也大增,加州大學2010~2011年一學期的學費,較上學期增加302%,但是這段期間的通貨膨脹率微乎其微
  17. 研究證實,如果你要上破產法庭,最快的辦法不是買台最新款的蘋果電腦,而是透過醫療支出
  18. 把破產描繪成道德敗壞,並不符合美國的真實生活,公司倒閉、健保費用漲翻天,社會安全網有等於沒有。
  19. 退休試算公式的侷限是:他無法幫你存錢。你為什麼不能存錢不重要,你可能沒有未雨綢繆,你可能出錢讓孩子唸大學,你可能環遊世界把錢花光,你可能生病或失業。當你需要付帳時,什麼都不成理由
  20. 我們每一個人,無論是年輕的、中年或年長的美國人,都必須應付在滿足今日與明日需求之間,持續不斷的掙扎。該買電腦或省下來存第一棟房屋的頭期款。不幸的,隨著這十年實質薪資長期減少,這種掙扎又變得更加困難



2016/03/31

2016/03 Travel

台大杜鵑花節







2016/03/09

[Python] File I/O example

Example 1: Read file and print its content

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
import os

""" 列印檔案內容 (print file content) """
def printFileContent(file):
    try:
        if(isFileExists("D:\\python\\txt\\" + file)==True):
            """ r stands for read """
            data = open("D:\\python\\txt\\" + file, "r", encoding="utf-8")
            for each_line in data:
                print(each_line)
        
        else:
            print("查無檔案 : "+file)
    except IOError as err:
        print('IOError! ' + err.args[0])
    finally:
       data.close()

"""" 檢查檔案是否存在 """
def isFileExists(file):
 if os.path.exists(file):
  return True
 else:
  return False

Execution result:
1
2
3
4
5
6
7
>>> import myUtil
>>> myUtil.printFileContent("AJokeADay.txt")
A rancher asked his veterinarian for some free advice. 

I have a horse that walks normally sometimes, and sometimes he limps. What shall I do?

The Vet replied, The next time he walks normally, sell him.


Example 2: append some words at the end of file

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
import os

""" 在檔案內容末端增加文字 (add words at the end of file content) """
def appendString(file, content):
    try:
        if(isFileExists("D:\\python\\txt\\" + file) == True):
            """ a stands for append """
            data = open("D:\\python\\txt\\" + file, "a", encoding="utf-8")
            data.write("\n" + content)
        else:
            print("查無檔案:"+file)
    except IOError as err:
        print('IOError! ' + err.args[0])
    finally:
       data.close()  


""" 列印檔案內容 (print file content) """
def printFileContent(file):
    try:
        if(isFileExists("D:\\python\\txt\\" + file)==True):
            """ r stands for read """
            data = open("D:\\python\\txt\\" + file, "r", encoding="utf-8")
            for each_line in data:
                print(each_line)
        
        else:
            print("查無檔案 : "+file)
    except IOError as err:
        print('IOError! ' + err.args[0])
    finally:
       data.close()


"""" 檢查檔案是否存在 """
def isFileExists(file):
 if os.path.exists(file):
  return True
 else:
  return False

Execution result:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
>>> import time
>>> addedContent = time.strftime("%Y/%m/%d")+" edited"
>>> myUtil.appendString("AJokeADay.txt", addedContent)
>>> 
>>> myUtil.printFileContent("AJokeADay.txt")
A rancher asked his veterinarian for some free advice. 

I have a horse that walks normally sometimes, and sometimes he limps. What shall I do?

The Vet replied, The next time he walks normally, sell him.

2015/12/23 edited
>>> 

Example 3. Apply with statement to open file

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
def printFileContent2(fileName):
    try:
        if(isFileExists("D:\\python\\txt\\" + fileName)==True):
            """ r stands for read """
            with open("D:\\python\\txt\\" + fileName, "r", encoding="utf-8") as data:
                for each_line in data:
                    print(each_line)
        
        else:
            print("查無檔案 : "+fileName)
    except IOError as err:
        print('IOError! ' + str(err))
    finally:
       if 'data' in locals():
        data.close()
    







2016/03/08

[Python] IF...ELIF...ELSE Statements

Example
Assume I have four exam type, each type has its passing scores. 
I will provide a method, as people fill in exam type and scores, it will you tell you pass the exam or not. 
This example will demonstrate how to use if / elif / else in Python program:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
""" 判斷分數是否通過考試 """
def passExan(examType, scores):
 if examType == '1':
  if scores >= 252.79:
   print("恭喜您通過 專業1→營運職2 升等考試")
  else:
   print("很抱歉,您未通過 專業1→營運職2 升等考試")
 elif examType == '2':
  if scores >= 248.65:
   print("恭喜您通過 專業2→專業1 升等考試")
  else:
   print("很抱歉,您未通過 專業2→專業1 升等考試")
 elif examType == '3':
  if scores >= 260.79:
   print("恭喜您通過 專業3→專業2 升等考試")
  else:
   print("很抱歉,您未通過 專業3→專業2 升等考試")
 elif examType == '4':
  if scores >= 254.88:
   print("恭喜您通過 專業4→專業3 升等考試")
  else:
   print("很抱歉,您未通過 專業4→專業3 升等考試")
 else:
  print("查無此考試項目")

Test:
1
2
3
4
5
6
7
Python 3.5.1 (v3.5.1:37a07cee5969, Dec  6 2015, 01:38:48) [MSC v.1900 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> import myUtil
>>> myUtil.passExam("1", 270)
恭喜您通過 專業1→營運職2 升等考試
>>> myUtil.passExam("3", 180)
很抱歉,您未通過 專業3→專業2 升等考試


Reference
[1] http://www.tutorialspoint.com/python/python_if_else.htm

2016/03/07

[Python] Exception Handling

Problem
Here is my Python program:
1
2
3
4
5
6
def checkNum(num):
  try:
    if(num>0):
        print("* number > 0 ( you input " + str(num) + " ).")
    else:
        print("* num < 0 ( you input " +  str(num) + " ).")

The parameter in checkNum method only accept number data type. If I provide String data type...
1
2
3
4
5
6
7
8
>>> import myUtil
>>> myUtil.checkNum("-20")
Traceback (most recent call last):
  File "<pyshell#5>", line 1, in <module>
    myUtil.checkNum("-20")
  File "C:\Users\albert\AppData\Local\Programs\Python\Python35-32\lib\site-packages\myUtil.py", line 2, in checkNum
    if(num>0):
TypeError: unorderable types: str() > int()

How To
We can use try...except to do exception handling in Python program, and given more friendly exception message:
1
2
3
4
5
6
7
8
def checkNum(num):
  try:
    if(num>0):
        print("* number > 0 ( you input " + str(num) + " ).")
    else:
        print("* num < 0 ( you input " +  str(num) + " ).")
  except TypeError as err:
    print('只接受數字型態(Only Accept Number Data Type)! ' + err.args[0])

Test:
1
2
3
4
>>> import myUtil
>>> myUtil.checkNum("-20")
只接受數字型態(Only Accept Number Data Type)! unorderable types: str() > int()
>>> 









2016/03/06

[Python] TypeError: Can't convert 'int' object to str implicitly

Problem
I have a Python program as bellows:
1
2
3
4
5
def checkNum(num):
    if(num>0):
        print("* number > 0 ( you input " + num + " ).")
    else:
        print("* num < 0 ( you input " +  num + " ).")

As I try to do test, it showed error message as following:
1
2
3
4
5
6
7
8
>>> import myUtil
>>> myUtil.checkNum(10)
Traceback (most recent call last):
  File "<pyshell#3>", line 1, in <module>
    myUtil.checkNum(10)
  File "C:\Users\albert\AppData\Local\Programs\Python\Python35-32\lib\site-packages\myUtil.py", line 3, in checkNum
    print('* number > 0 ( you input ' + num +' )')
TypeError: Can't convert 'int' object to str implicitly


How To
You need to use str function to convert number to String
1
2
3
4
5
def checkNum(num):
    if(num>0):
        print("* number > 0 ( you input " + str(num) + " ).")
    else:
        print("* num < 0 ( you input " +  str(num) + " ).")

Test result:
1
2
3
4
5
6
>>> import myUtil
>>> myUtil.checkNum(89)
* number > 0 ( you input 89 ).
>>> myUtil.checkNum(-20)
* num < 0 ( you input -20 ).
>>> 


Reference
[1] http://stackoverflow.com/questions/13654168/typeerror-cant-convert-int-object-to-str-implicitly

2016/03/05

[Python] File I/O in Python : UnicodeDecodeError

Problem
I would like to open a text file and prints its content
1
2
3
4
5
>>> import os
>>> os.chdir ("D:\python")
>>> data = open("txt\AJokeADay1.txt")
>>> for eachLine in data :
 print(eachLine)

But it throw this exception:
1
2
3
4
Traceback (most recent call last):
  File "<pyshell#7>", line 1, in <module>
    for eachLine in data :
UnicodeDecodeError: 'cp950' codec can't decode byte 0xe2 in position 70: illegal multibyte sequence


How To
Assign encoding to utf-8 as open this file.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
>>> data = open("txt\AJokeADay1.txt", "r", encoding="utf-8")
>>> for eachLine in data :
 print(eachLine)

 
[In Office Jokes]

A guy shows up late for work. 

The boss yells, You shouldve been here at 8.30!’ 

He replies. Why? What happened at 8.30?’ 
>>> data.close()






2016/03/04

[Python] Module your Python Code

In Java, if some source code will be reused by others. We may create a utility class, if someone need this function, he/she can import this class and reuse this function. Do not need to reinvent the wheel.

Assume I have a simple Python code which named printLoop.py, the code is as bellows:
1
2
3
4
""" print movie list"""
def printMovies(movies):
 for movie in movies :
  print(movie)

Supposed that many people may need this function to print the content of array. Therefore, you need to package this Python program as a module.

Step 1. Create a folder for my module which name printLoop


Step 2. Create a setup.py in printLoop folder
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
from distutils.core import setup
setup(
 name = 'printLoop',
 version = '1.0.0',
 py_modules = ['printLoop'],
 author = 'albert',
 author_email = 'xxx@gmail.com',
 url = 'http://xxx.com',
 description = 'simple example for building module',
)

Step 3. Build distribution file
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
D:\python\printLoop>python setup.py sdist
running sdist
running check
warning: sdist: manifest template 'MANIFEST.in' does not exist (using default file list)

warning: sdist: standard file not found: should have one of README, README.txt

writing manifest file 'MANIFEST'
creating printLoop-1.0.0
making hard links in printLoop-1.0.0...
hard linking printLoop.py -> printLoop-1.0.0
hard linking setup.py -> printLoop-1.0.0
creating 'dist\printLoop-1.0.0.zip' and adding 'printLoop-1.0.0' to it
adding 'printLoop-1.0.0\PKG-INFO'
adding 'printLoop-1.0.0\printLoop.py'
adding 'printLoop-1.0.0\setup.py'
removing 'printLoop-1.0.0' (and everything under it)

Step 4. Install the distribution file
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
D:\python\printLoop>python setup.py install
running install
running build
running build_py
creating build
creating build\lib
copying printLoop.py -> build\lib
running install_lib
copying build\lib\printLoop.py -> C:\Users\albert\AppData\Local\Programs\Python\Python35-32\Lib\site-packages
byte-compiling C:\Users\albert\AppData\Local\Programs\Python\Python35-32\Lib\site-packages\printLoop.py to printLoop.cpython-35.pyc
running install_egg_info
Removing C:\Users\albert\AppData\Local\Programs\Python\Python35-32\Lib\site-packages\printLoop-1.0.0-py3.5.egg-info
Writing C:\Users\albert\AppData\Local\Programs\Python\Python35-32\Lib\site-packages\printLoop-1.0.0-py3.5.egg-info

Test.
1. Import printLoop module
2. Create a movie list
3. utilize printLoop.printMovies to print movie list
1
2
3
4
5
6
7
8
9
Python 3.5.1 (v3.5.1:37a07cee5969, Dec  6 2015, 01:38:48) [MSC v.1900 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> import printLoop
>>> movies = ["Inside Out", "The Intern", "Our Brand is Crisis"]
>>> printLoop.printMovies(movies)
Inside Out
The Intern
Our Brand is Crisis
>>> 



2016/03/03

[Python] How to Change Working Directory in IDLE

Problem
As I open IDLE, how do I know my current working directory? And how to change to another working directory?

How To
1. you need to import os module first
2. use os.getcwd() to get current working directory
3. use os.chdir("XXX") to change working directory

1
2
3
4
5
6
7
8
9
Python 3.5.1 (v3.5.1:37a07cee5969, Dec  6 2015, 01:38:48) [MSC v.1900 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> import os
>>> os.getcwd()
'C:\\Users\\albert\\AppData\\Local\\Programs\\Python\\Python35-32'
>>> os.chdir("D:\python")
>>> os.getcwd()
'D:\\python'
>>> 


Reference
[1] http://stackoverflow.com/questions/15821121/whats-the-working-directory-when-using-idle