Skip to content

Commit 86bfcd2

Browse files
committed
Merge pull request Show-Me-the-Code#33 from ddkangfu/master
ddkangfu's code
2 parents 17f110a + aaf9b72 commit 86bfcd2

9 files changed

Lines changed: 231 additions & 0 deletions

File tree

ddkangfu/0000/0000.py

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
# coding=utf-8
2+
3+
from PIL import Image, ImageDraw, ImageFont
4+
5+
6+
def draw_number(file_name, number):
7+
image = Image.open(file_name)
8+
pos = (image.size[0] - 90, 0)
9+
font = ImageFont.truetype('Arial.ttf', 140)
10+
11+
draw = ImageDraw.Draw(image)
12+
draw.text(pos, number, fill=(255,0,0), font=font)
13+
14+
image.show()
15+
16+
17+
if __name__ == '__main__':
18+
draw_number("507583.jpeg", "2")

ddkangfu/0000/507583.jpeg

39.4 KB
Loading

ddkangfu/0000/Arial.ttf

756 KB
Binary file not shown.

ddkangfu/0001/0001.py

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
#coding=utf-8
2+
3+
import uuid
4+
5+
"""
6+
做为 Apple Store App 独立开发者,你要搞限时促销,为你的应用**生成激活码**(或者优惠券),使用 Python 如何生成 200 个激活码(或者优惠券)?
7+
"""
8+
9+
def generate_activation_code(count):
10+
code_list = []
11+
for i in xrange(count):
12+
code = str(uuid.uuid4()).replace('-', '').upper()
13+
if not code in code_list:
14+
code_list.append(code)
15+
16+
return code_list
17+
18+
19+
if __name__ == "__main__":
20+
code_list = generate_activation_code(200)
21+
for code in code_list:
22+
print code

ddkangfu/0002/0002.py

Lines changed: 88 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,88 @@
1+
#coding=utf-8
2+
3+
import uuid
4+
5+
import MySQLdb
6+
7+
"""
8+
002, 将 0001 题生成的 200 个激活码(或者优惠券)保存到 **MySQL** 关系型数据库中
9+
"""
10+
11+
12+
class ActivationCode(object):
13+
def __init__(self, code_count, database, username, host='localhost', port=3306, password=''):
14+
self._host = host
15+
self._username = username
16+
self._password = password
17+
self._database = database
18+
self._port = port
19+
20+
self.codes = self._generate_activation_code(code_count)
21+
#print self.codes
22+
23+
24+
def _get_mysql_instance(self):
25+
params = {
26+
'host': self._host,
27+
'user': self._username,
28+
'passwd': self._password,
29+
'db': self._database,
30+
'port': self._port,
31+
}
32+
return MySQLdb.connect(**params)
33+
34+
35+
def _generate_activation_code(self, count):
36+
code_list = []
37+
for i in xrange(count):
38+
code = str(uuid.uuid4()).replace('-', '').upper()
39+
if not code in code_list:
40+
code_list.append(code)
41+
42+
return code_list
43+
44+
45+
def store_to_mysql(self):
46+
if self.codes:
47+
conn = self._get_mysql_instance()
48+
49+
try:
50+
cur = conn.cursor()
51+
52+
# clear old datas
53+
cur.execute('delete from code')
54+
55+
# insert mutilple code
56+
for code in self.codes:
57+
cur.execute("insert into code(code) values('%s')" % code)
58+
59+
conn.commit()
60+
cur.close()
61+
conn.close()
62+
63+
return True
64+
except MySQLdb.Error,e:
65+
conn.rollback()
66+
print "Mysql Error %d: %s" % (e.args[0], e.args[1])
67+
68+
return False
69+
70+
71+
def print_activation_code(self):
72+
conn = self._get_mysql_instance()
73+
74+
try:
75+
cur = conn.cursor()
76+
cur.execute('select code from code')
77+
78+
results = cur.fetchall()
79+
for row in results:
80+
print row[0]
81+
except MySQLdb.Error,e:
82+
print "Mysql Error %d: %s" % (e.args[0], e.args[1])
83+
84+
85+
if __name__ == "__main__":
86+
active_code = ActivationCode(200, database='Test', username='root')
87+
if active_code.store_to_mysql():
88+
active_code.print_activation_code()

ddkangfu/0003/0003.py

Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
#coding=utf-8
2+
3+
import uuid
4+
5+
import redis
6+
7+
"""
8+
003, 将 0001 题生成的 200 个激活码(或者优惠券)保存到 **Redis** 非关系型数据库中.
9+
"""
10+
11+
12+
def get_redis_instance(host='localhost', port=6379):
13+
return redis.StrictRedis(host=host, port=port)
14+
15+
16+
def generate_activation_code(count):
17+
code_list = []
18+
for i in xrange(count):
19+
code = str(uuid.uuid4()).replace('-', '').upper()
20+
if not code in code_list:
21+
code_list.append(code)
22+
23+
return code_list
24+
25+
26+
def store_to_redise(codes):
27+
if codes:
28+
cache = get_redis_instance()
29+
30+
try:
31+
cache.set('code:count', len(codes))
32+
33+
for i in xrange(len(codes)):
34+
cache.set('code:{0}'.format(i), codes[i])
35+
36+
cache.save()
37+
return True
38+
except:
39+
print 'Can not connect to redis server !!!'
40+
41+
return False
42+
43+
44+
def print_activation_code():
45+
cache = get_redis_instance()
46+
47+
try:
48+
count = cache.get('code:count')
49+
50+
count = 0 if count is None else int(count)
51+
52+
for i in xrange(count):
53+
print cache.get('code:%d'%i)
54+
except:
55+
print 'Can not connect to redis server !!!'
56+
57+
58+
if __name__ == "__main__":
59+
code_list = generate_activation_code(200)
60+
if store_to_redise(code_list):
61+
print_activation_code()

ddkangfu/0004/0004.py

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
#coding=utf-8
2+
3+
import collections
4+
import re
5+
6+
"""
7+
0004, 任一个英文的纯文本文件,统计其中的单词出现的个数。
8+
"""
9+
10+
11+
def count_word(file_name):
12+
f = open(file_name)
13+
14+
line = f.readline()
15+
word_counter = collections.Counter()
16+
17+
while line:
18+
words = re.findall("\w+", line.lower())
19+
word_counter.update(words)
20+
21+
line = f.readline()
22+
23+
f.close()
24+
25+
return word_counter
26+
27+
28+
if __name__ == '__main__':
29+
print count_word('english.txt')

ddkangfu/0004/english.txt

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
In English, that means start with any non-'defaults' keyword argument that doesn’t contain a double underscore (which would indicate a non-exact lookup). Then add the contents of defaults, overriding any keys if necessary, and use the result as the keyword arguments to the model class. As hinted at above, this is a simplification of the algorithm that is used, but it contains all the pertinent details. The internal implementation has some more error-checking than this and handles some extra edge-conditions; if you’re interested, read the code.
2+
3+
If you have a field named defaults and want to use it as an exact lookup in get_or_create(), just use 'defaults__exact', like so:
4+
5+
The get_or_create() method has similar error behavior to create() when you’re using manually specified primary keys. If an object needs to be created and the key already exists in the database, an IntegrityError will be raised.
6+
7+
This method is atomic assuming correct usage, correct database configuration, and correct behavior of the underlying database. However, if uniqueness is not enforced at the database level for the kwargs used in a get_or_create call (see unique or unique_together), this method is prone to a race-condition which can result in multiple rows with the same parameters being inserted simultaneously.
8+
9+
If you are using MySQL, be sure to use the READ COMMITTED isolation level rather than REPEATABLE READ (the default), otherwise you may see cases where get_or_create will raise an IntegrityError but the object won’t appear in a subsequent get() call.
10+
11+
Finally, a word on using get_or_create() in Django views. Please make sure to use it only in POST requests unless you have a good reason not to. GET requests shouldn’t have any effect on data. Instead, use POST whenever a request to a page has a side effect on your data. For more, see Safe methods in the HTTP spec.

ddkangfu/requirements.txt

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
redis==2.10.3
2+
wsgiref==0.1.2

0 commit comments

Comments
 (0)