2010年12月30日 星期四

[Python] Threading Sample - 執行緒範例

每一秒加一個Thread

每一個Thread Sleep 10 seconds

Result:
sleeping 10 sec from thread 0
sleeping 10 sec from thread 1
sleeping 10 sec from thread 2
sleeping 10 sec from thread 3
sleeping 10 sec from thread 4
sleeping 10 sec from thread 5
sleeping 10 sec from thread 6
sleeping 10 sec from thread 7
sleeping 10 sec from thread 8
sleeping 10 sec from thread 9

[Python] 將List 內的項目轉換型態

>>> a = ['1', '2', '3', '4']
>>> a
['1', '2', '3', '4']

>>> a[:] = [int(x) for x in a]
>>> a
[1, 2, 3, 4]

See Also:
http://stackoverflow.com/questions/4561113/python-list-conversion

2010年12月29日 星期三

[Django] Don't use field_id to named your field 別用_id命名資料庫爛位

class Car(models.Model):
    manufacturer = models.ForeignKey('production.Manufacturer')

Django 會自動加個 manufacturer_id 所以你不用自己去處理他
如果自己定義一個 xxx_id Django會confuse
除非你想自己處理SQL

官網原文

DATABASE REPRESENTATION
Behind the scenes, Django appends "_id" to the field name to create its database column name. In the above example, the database table for the Car model will have a manufacturer_id column. (You can change this explicitly by specifying db_column) However, your code should never have to deal with the database column name, unless you write custom SQL. You'll always deal with the field names of your model object.


See Also
http://docs.djangoproject.com/en/dev/ref/models/fields/#database-representation

2010年12月28日 星期二

[Python] Convert String to List 字串轉串列

我把一個List ['aaa', 'bbb'] 存到資料庫

讀出來時會變成 "['aaa', 'bbb']" 字串

所以如果要一一列出時

l = "['aaa', 'bbb']" # 從資料庫讀出的

for v in l:
  print v

會變
[
'
a
a
a
'
,
b
b
b
'
]

所以要先用eval() 把 String 轉回 List即可

for v in eval(l):
  print v

aaa
bbb


See Also:
http://docs.python.org/library/functions.html#eval

[Django] Model中的null 和 blank 設定與差異



models.CharField(max_length=200, null=False, blank=True)

Django的驗證, 預設每個攔位都是為必要的(required)

所以如果你想要將欄位設為空值, 必須再另外設定

在Django的Field有兩種值可以設定: blank and null

blank 只是用於Django自己的input欄位驗證 (Django’s input validation)

Null 是否允許讓你在Database裡插入NULL, 就是空值 (whether the database accepted NULL)

Null = Python的None = 不存在

blank = True 欄位檢查允許為空值
blank = False 欄位檢查不允許為空值
null = True 寫入資料庫允許為NULL (Python 為 None)
null = False 寫入資料庫不允許為NULL (Python 為 None)

See Also:
http://www.b-list.org/weblog/2006/jun/28/django-tips-difference-between-blank-and-null/

2010年12月27日 星期一

[Django] list all Session

for k in request.session.keys():
    print ' key = ', k
    print request.session.__getitem__(k)

See Also:
django - How to use sessions

2010年12月25日 星期六

[Music] MC Hot Dog 2010 - MC來了

MC Hot Dog真的很棒!!  聖誕節應景一下吧^^

MC = Microphone Controller
MC = Menstrual Cycle
MC = Merry Christmas

===========



歌詞:

[CSS] 改變反白顏色 Change Selection Color

測試後只有IE沒效果


<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<style type="text/css">
body {
 background: black;
 color: white;
}

::selection {
        background: red; /* Safari */
        }
::-moz-selection {
        background: red; /* Firefox */
}
</style>

12345678910
abcdefghijklmnopqrstuvwxyz
ABCDEFGHIJKLMNOPQRSTUVWXYZ
あいうえお
かきくけこ
さしすせそ
たちつてと
なにぬねの
はひふへほ
まみむめも
やゆよ
らりるれろ
わをん

[Python] 逐行顯示檔案內容 read file line by line

f = open('C:\test.txt')
for l in f:
    print(l.strip())

Reference:

http://docs.python.org/library/stdtypes.html#str.strip
http://maestric.com/doc/python/misc

2010年12月13日 星期一

[Django] Getting Started part 2 - 設置與同步資料庫

Step 1: 編輯setting.py

設置DATABASE的ENGINE and NAME, 在這我用sqlite

such as:

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3', # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.
        'NAME': 'mysite.sqlite',                      # Or path to database file if using sqlite3.
        'USER': '',                      # Not used with sqlite3.
        'PASSWORD': '',                  # Not used with sqlite3.
        'HOST': '',                      # Set to empty string for localhost. Not used with sqlite3.
        'PORT': '',                      # Set to empty string for default. Not used with sqlite3.
    }
}


Step 2: 同步資料庫

python manage.py syncdb

syncdb會根據setting.py裡INSTALLED_APPS的內容來建立需要的資料庫


你可以透過SQLite Manager來查看建立了哪些資料表
http://code.google.com/p/sqlite-manager/

[JavaScript] 將JSON data寫入新開的視窗

例如我要把產生的JSON Code, 顯示在新開的視窗中


<script type="text/javascript" src="http://www.json.org/json.js"></script> 
<script type="text/javascript"> 
 
var Beatles = new Object();
Beatles.Country = "England";
Beatles.YearFormed = 1959;
Beatles.Style = "Rock'n'Roll";
 
function prevJSON() {
  var win = window.open(" ", "_new");
  win.document.open();
  win.document.write("<pre>" + JSON.stringify(Beatles, null, '\t') + "</pre>"); }
</script> 
<input type="button" value="preview JSON code" onClick="prevJSON()"> 


References:
http://www.learn-ajax-tutorial.com/Json.cfm

[Ubuntu 10.10] 如何安裝JDK - How to install Java(JDK)

$ sudo apt-get install openjdk-6-jdk

After installation, you can try to get version information like below

$ java -version
java version "1.6.0_20"
OpenJDK Runtime Environment (IcedTea6 1.9.2) (6b20-1.9.2-0ubuntu1)
OpenJDK 64-Bit Server VM (build 19.0-b09, mixed mode)

2010年12月9日 星期四

[jQuery] Select All Checkbox 選取所有選取框checkbox

Sample Below: (save to html to try this)

<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>

<script type="text/javascript">
$(function() {
/**
 * Select all checkbox
 */
  flag = false;
  $(".selectall").click(function() {
    flag = !flag;
    $("input[name='box[]']").each(function() {
      $(this).attr("checked" , flag);
    });
    $(".selectall").attr("checked", flag);
  });
});
    

</script>

<input type="checkbox" class="selectall"> Select All<br />
<input type="checkbox" name="box[]"><br />
<input type="checkbox" name="box[]"><br />
<input type="checkbox" name="box[]"><br />
<input type="checkbox" name="box[]"><br />
<input type="checkbox" name="box[]"><br />
<input type="checkbox" name="box[]"><br />
<input type="checkbox" name="box[]"><br />
<input type="checkbox" name="box[]"><br />

[jQuery] Select DIV element by ID

It's a sample code below.

<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
  $('div[id*="mydiv"]').append('*');  // containing the a given substring.
  $('div[id|="mydiv"]').append('|');  // mydiv- (string followed by a hyphen (-)
  $('div[id$="mydiv"]').append('$');  // a value ending exactly with a given string.
});

</script>

</script>
<div id="mydiv"></div>
<div id="0mydiv0"></div>
<div id="mydiv-1"></div>
<div id="mydiv1"></div>
<div id="mydiv2"></div>
<div id="3mydiv"></div>


Result:

*$
*
*|
*
*
*$

Reference: http://api.jquery.com/category/selectors/

2010年12月8日 星期三

[Apache] 新增虛擬目錄 Create Virtual Directory

因為有時候一些在家寫的小程式, 會想要在工作或是別的地方拿出來用或測試, 所以我都是放在dropbox裡, 但是每次都要copy出來放到網頁目錄覺得很麻煩, 所以我新增了一個虛擬目錄到My Dropbox裡的www資料夾, 這樣就不用每次都要複製了, 可以直接修改, 直接測試。

Open the Apache configuration : httpd.conf
打開Apache的設定檔httpd.conf

Add code on below, save then restart Apache Server
設定如下, 存檔後重啟Apache

Alias /www/ "C:/My Dropbox/www/"

<Directory "C:/My Dropbox/www/">
    Options FollowSymLinks MultiViews
    AllowOverride None
    Order allow,deny
    Allow from all
</Directory>

2010年12月7日 星期二

[Django] Getting Started part 1 -建立專案和應用程式

在開始之前, 你的系統必須安裝好Python及Django

我的作業系統是Ubuntu, 所以如果你是用Fedoa或其他系統, 你得用其他方式來安裝
My OS is Ubuntu, so if you use Fedora or CentOS, maybe you have to use yum install to do.

Step 1. Install Python 安裝Python
# apt-get install python


Step 2. Install Django 安裝Django
# apt-get install python-django

你可以試著執行python, 然後打入以下語法來測試是否成功安裝Django
Then you can try to see Django version from above command line:

# python
>>> import django
>>> print django.get_version()
1.2.3


[Python] String 字串 速記

>>> s = 'Hank'
>>> len(s)  # 字串長度
4

>>> s[0]
'H'

>>> s[1]
'a'

>>> s[-1]
'k'

>>> s
'Hank'

>>> s[1:3]
'an'

[Python] Math and Random 速記

>>> import math
>>> math.pi
3.141592653589793
>>> math.sqrt(85)
9.219544457292887
>>> import random
>>> random.random()
0.7685885105411999
>>> random.choice([1,2,3,4])
2
>>>

Reference:
math — Mathematical functions
random — Generate pseudo-random numbers
Learning Python, 3e

2010年12月2日 星期四

[Tools] Zen Coding : Generating HTML from selectors 使用選擇器產生HTML

顧名思義就是用來自動產生HTML, 第一次用也是覺得超酷, 用習慣真的能增加工作效率

直接看範例, 我是用Aptana, 打下面的selectors

html:xt>div#header>div#logo+ul#nav>li.item-$*5>a

按下Ctrl+Alt+E後會自動產生成下列的HTML

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
 <meta http-equiv="Content-Type" content="text/html;charset=UTF-8" />
 <title></title>
</head>
<body>
 <div id="header">
  <div id="logo"></div>
  <ul id="nav">
   <li class="item-1"><a href=""></a></li>
   <li class="item-2"><a href=""></a></li>
   <li class="item-3"><a href=""></a></li>
   <li class="item-4"><a href=""></a></li>
   <li class="item-5"><a href=""></a></li>
  </ul>
 </div>
</body>
</html>

Reference:
Zen Coding: Generating HTML from selectors
Zen Coding: A Speedy Way To Write HTML/CSS Code

2010年12月1日 星期三

[Moodle] 解決圖表顯示中文變成框框

隨便選一個中文字體複製修改成default.ttf

然後複製到moodledata資料夾下的 lang//zh_tw_utf8/fonts即可
Related Posts Plugin for WordPress, Blogger...