Total Pageviews

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


2016/03/02

[Python] Set Up Python Environment

Step 1. Download Python from https://www.python.org/downloads/windows/


Step 2. Install Python














Step 3. If you are Windows users, you need to configure Python installation path and Scripts path to path (environment variables)
i.e. C:\Python35-32\ and C:\Python35-32\Scripts


If you are Mac user, you can ignore this step.

Step 4. Open command prompt, and type in python3 -V to do verification. 



Write a first and simple Python program
1
2
3
4
# encoding: utf-8

print("Hello, Python")
print("哈囉,派森")




Then you can use IDLE to help you learn Python


IDLE knows all about Python syntax
Ex1. Use terminal


Ex2. Use IDLE


IDEL also offers "code completion" when you use build-in functions, ex. print()

2016/03/01

[閱讀筆記] 富爸爸,窮爸爸 (Part 2)


  1. 風險無所不在,要學會駕馭風險,而不是一昧低迴避風險
  2. 工人付出最高限度的努力工作以避免被解雇,而雇主提供最低額度的工資以防止工人辭職
  3. 麥當勞擁有一套出色的商務體系。許多才華洋溢的人之所以貧窮,是因為他們只專心做好漢堡,而對如何運作商務體系卻所知甚少。
  4. 成功所必要的管理素質包括:
    1. 對現金流的管理
    2. 對系統(包括你本人、時間及家庭)的管理
    3. 對人員的管理
  5. 人們即便是經過學習,掌握財務知,但是在通往財務自由的道路上人面臨許多困難,包含:恐懼心理、憤世嫉俗、懶惰、不良習慣、自負
  6. 在投資活動中,從沒遇過從未損失的富人,但常遇到從未損失過一毛的窮人
  7. 如果你討厭冒險,對金錢損失感到擔心,那就早點動手累積屬於妳的金錢
  8. 在財務上不能獲得成功的最大原因是大部份的人的作法太安全。人們因為太害怕失敗,所以才會失敗
  9. 人人都想上天堂,卻沒有人想死。可是不死怎麼上天堂。這就如同大部份人夢想發財,但卻害怕在投資過程損失金錢,所以她們永遠進不了天堂
  10. 洛克斐洛曾說:我總是試圖將每一次災難轉換成機會
  11. 90%的美國公民財務困難的主要原因在於他們是為了避免損失而理財,而不是為了營利而理財
  12. 失敗會激勵勝利者,也會撃垮失敗者。勝利意味著不害怕失敗,他們了解自己,也討厭失敗,但失敗會激勵他們做的更好
  13. 如果妳沒有什麼資金又有致富的願望,妳就必須集中精力,把妳僅有的雞蛋放在較少的籃子(當然你還要確信籃子的結實程度),不要把很少的雞蛋放在許多籃子裡
  14. 如果妳不願失敗,那就安全的投資;如果損失會讓你元氣大傷,那就安妥一點,去做一個平衡的投資。但以安全的方式進行投資,就要儘早起步,儘早開始累積妳的雞蛋,因為以這種方式需要大量的時間
  15. 未經證實的懷疑和恐懼會產生憤世嫉俗者。憤世嫉俗者抱怨現實,從來不會贏;成功者分析現實,想辦法贏
  16. 我們用錢的習慣決定我們是什麼類型的人,有的人之所以貧窮是因為他們有著不良的用錢習慣
  17. 聰明 + 傲慢 = 無知
  18. 如果你想駕駛飛機,你應該去聽有關飛行原理的課程,而不是直接坐進駕駛艙。妳買了一兩套房地產,不會讓你成為房地產專家。你應該花時間投資你最重要的資產 - 頭腦
  19. 累積財富的過程,最困難的事情莫過於堅持自己的選擇而不盲目從眾
  20. 是否缺乏自律,是將富人與窮人區分開來的首要因素。生活之所以推著你轉,不是因為驅使你的人很厲害,而是因為你個人缺乏自我控制和紀律
  21. 開創你自己的事業需具備三個重要的管理技能:現金流量管理、人事管理、個人時間管理
  22. 不要背負數額過大的債務包袱,要使自己的支出保持低水平。先增加自己的資產,然後再用自己的資產中產生的現金流購買大房子、大車子
  23. 當你資金短缺時,去承受外在壓力而不要動用你的儲蓄或投資,利用這種壓力去激發你的財務天賦,想辦法掙出更多的錢,然後再支付帳單
  24. 窮人有個不好的習慣,就是隨便動用儲蓄,富人知道儲蓄只能用於創造更多的錢,而不是用來支付帳單
  25. 人事管理是要能夠管理在某些技術領域比你聰明的人,而不是只會管理沒有自己聰明的人或能力沒有自己強的人
  26. 最容易的道路往往會越走越艱難,而艱難的道路往往會越走越輕鬆
  27. 如果你的財務智商很低,金錢就會比你更精明,他會從你身上溜走。如果你沒有金錢精明,你將為他工作一生。要成為金錢的主人,你要比金錢更精明,讓金錢為你工作,而不是成為它的奴隸,這就是財務智商
  28. 行動吧!行動者總會擊敗不行動者
  29. 思考是一種思想,你應該思考致富,而不是努力工作致富。讓金錢為你辛勤工作,你的生活將會變得更輕鬆、更幸福
  30. 上天賜與每個人兩樣禮物:思想與時間。隨著每一張鈔票流入你的手中,愚蠢地用掉它,你就選擇了貧困;把錢用在負債專案上,你就會進入中產階級;投資於你的頭腦,學習如何獲得資產,財富將成為你的目標和你的未來
  31. 為你的財務負起責任或一生只聽從別人的命令,你要嘛是金錢的主人,亦或是金錢的奴隸

2016/02/29

2016/02 Travel


嘉義梅山公園
DSC09076

嘉義蘭潭水庫
DSC09106

DSC09117

DSC09122

DSC09123

金瓜石
DSC09186

朱銘美術館
DSC09275

2016/02/27

How to import a git non-Java project into Eclipse

Assume I import a non-Java project from GitHub into Eclipse

1. Import non-Java project from GitHub: File => Import


2. Choose Git => Projects from Git => Next


3. Select Git Repository => Click Next


4. Choose "Import as general project" => Click Next


5. Click Finish


Import project successfully !



Owing to the project which import from GitHub is non-Java project, so I would like to change it to Java Project.

1. Right click on this project => properties


2. Click Project Facelets = > Covert to faceted form


3. Check Java => Apply => click OK


4. Done !



2016/02/24

[Oracle] How to grant privilege and create synonym in Oracle

If I would like to grant two views, dbm200va and dbm400va, to another database user. How do to it?


Syntax for tables/views is as bellows:
GRANT privilege-type ON [TABLE] { table-Name | view-Name } TO grantees



In addition to grant privileges by ap_dbm, ap_psr also need to create synonym on its side.
Create synonym syntax is as following:
CREATE [PUBLIC] SYNONYM [schema .] synonym FOR [schema .] object [@ dblink];



Reference
  1. grant privilege: http://docs.oracle.com/javadb/10.8.1.2/ref/rrefsqljgrant.html
  2. create synonym : http://docs.oracle.com/cd/B19306_01/server.102/b14200/statements_7001.htm

2016/02/07

[Oracle] How to get the date of the last day of the month in Oracle

Problem
If I would like to get the date of the last day of the month, how to do it?

How to
Oracle had build-in function, LAST_DAY, to fulfill this requirement.

Here is the example:
SELECT to_char(sysdate, 'YYYYMMDD') today,
       to_char(LAST_DAY(sysdate), 'YYYYMMDD') last_day_of_month
FROM dual

Query result :


Reference
[1] https://docs.oracle.com/cd/B28359_01/server.111/b28286/functions077.htm

2016/02/06

[Windows] svchost 狂吃 RAM

Problem
某天打開電腦 (OS: Windows 7),發現整台電腦跑得非常慢
打開工作管理員以後,發現我的 RAM 幾乎被 svchost 這個 process 吃光光所導致


How To
執行以下步驟可以解決此問題
1. 打開命令提示字元,執行以下指令,重新註冊 DDL:
REGSVR32 WUAPI.DLL
REGSVR32 WUAUENG.DLL
REGSVR32 ATL.DLL
REGSVR32 WUPS.DLL
REGSVR32 WUPS2.DLL

2. 在命令提示字元中,執行以下指令暫停Automatic Updates服務:
net stop WuAuServ

3. 進入 C:\windowns,rename  SoftwareDistribution 成其他名字

4. 在命令提示字元中,執行以下指令重新啟動Automatic Updates服務:
net start WuAuServ

5. restart computer

打開工作管理員觀察,可以發現 svchost 吃的記憶體下降非常多,整台電腦就不在像調整前卡卡遲鈍了


Reference
[1] http://sungshu.pixnet.net/blog/post/195361068-%5Bwin%5Dsvchost.exe%E7%8B%82%E5%90%83%E8%A8%98%E6%86%B6%E9%AB%94


2016/02/05

[Microsoft SQL Server] Adding Rows by Using INSERT and SELECT

Problem
Assume I have a function, as user click a button it will copy last year's data and insert data into this year. How to use SQL statement to fulfill this requirement?


How To
We can use insert with a select subquery to implement this requirement
By using a SELECT subquery to specify the data values for one or more rows, such as:
INSERT INTO dbm031fa(sta_date, age, fund_id, fund_name, age_type, remark, user_id, update_date)
SELECT DATEADD(YEAR, 1, sta_date) sta_date,
       age,
       fund_id,
       fund_name,
       age_type,
       remark,
       user_id,
       CURRENT_TIMESTAMP update_date
FROM dbm031fa
WHERE year(sta_date) = year(CURRENT_TIMESTAMP)-2

Reference
[1] https://technet.microsoft.com/en-us/library/ms188263(v=sql.105).aspx