Skip to content

Commit 42e2842

Browse files
committed
Merge pull request Show-Me-the-Code#56 from illuz/master
solve 0000~0002
2 parents 1b63362 + 1d33c1b commit 42e2842

File tree

5 files changed

+296
-0
lines changed

5 files changed

+296
-0
lines changed
Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
1+
# Author: illuz <iilluzen[at]gmail.com>
2+
# File: add_number_to_image.py
3+
# Create Date: 2015-02-08 23:52:01
4+
# Descripton: Add a number to right top corner of images.
5+
# Will backup the image in ./[file]_bak.[ext]
6+
# Usage: add_number_to_image.py [image] [number]
7+
8+
'''
9+
第 0000 题:
10+
将你的 QQ 头像(或者微博头像)右上角加上红色的数字,
11+
类似于微信未读信息数量那种提示效果.
12+
'''
13+
14+
from PIL import Image, ImageDraw, ImageFont
15+
import sys, shutil
16+
17+
18+
# backup file
19+
# @return nothing
20+
def back_file(filename):
21+
p = filename.rfind('.')
22+
shutil.copyfile(filename, filename[:p] + '_bak' + filename[p:])
23+
24+
25+
# add number to right top corner
26+
# @return nothing
27+
def add_number_to_image(im, num):
28+
xsize, ysize = im.size
29+
left, top = int(xsize / 20.0 * 13), int(xsize / 20.0)
30+
right, bottom = int(xsize / 20.0 * 19), int(xsize / 20.0 * 7)
31+
draw = ImageDraw.Draw(im)
32+
draw.ellipse([left, top, right, bottom], (255, 0, 0))
33+
font=ImageFont.truetype("DroidSansMono.ttf", int(xsize / 20 * 4))
34+
draw.text((left + xsize / 10.0, top + xsize / 30), str(num), (0, 0, 0), font=font)
35+
del draw
36+
37+
38+
# open image and deal font and get Draw
39+
# @return a ImageDraw
40+
def deal(f, num):
41+
if (num == None):
42+
num = 0
43+
if (num > '9'):
44+
num = '9+'
45+
im = Image.open(f)
46+
add_number_to_image(im, num)
47+
im.save(f)
48+
49+
50+
def main():
51+
if len(sys.argv) <= 1:
52+
print "Need at least 1 parameter."
53+
return
54+
for i in range(1, len(sys.argv), 2):
55+
f = sys.argv[i]
56+
n = sys.argv[i + 1] if i + 1 < len(sys.argv) else None
57+
try:
58+
back_file(f)
59+
deal(f, n)
60+
print "Success add number to image file", f
61+
except IOError:
62+
print "Cannot open image", f, '!'
63+
pass
64+
65+
66+
if __name__ == '__main__':
67+
main()
68+

illuz/0001/key_generator.py

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
#!/usr/bin/python
2+
# -*- coding: utf-8 -*-
3+
# Author: illuz <iilluzen[at]gmail.com>
4+
# File: key_generator.py
5+
# Create Date: 2015-02-09 10:43:36
6+
# Descripton: Use uuid module to generate 200 register keys.
7+
# Usage: key_generator.py
8+
9+
"""
10+
第 0001 题:
11+
做为 Apple Store App 独立开发者,你要搞限时促销,为你的应用生成激活码(或者优惠券),使用 Python 如何生成 200 个激活码(或者优惠券)?
12+
"""
13+
14+
from uuid import uuid4
15+
16+
def generate_key(num):
17+
key_list = [str(uuid4()) for i in range(num)]
18+
return key_list
19+
20+
21+
def main():
22+
print generate_key(200)
23+
24+
25+
if __name__ == '__main__':
26+
main()
27+
Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
#!/usr/bin/python
2+
# -*- coding: utf-8 -*-
3+
# Author: illuz <iilluzen[at]gmail.com>
4+
# File: create_a_table_and_put_keys.py
5+
# Create Date: 2015-02-09 12:12:43
6+
# Usage: create_a_table_and_put_keys.py
7+
# Descripton: create a table in mysql and put keys into it
8+
9+
"""
10+
第 0002 题:
11+
将 0001 题生成的 200 个激活码(或者优惠券)保存到 MySQL 关系型数据库中。
12+
"""
13+
14+
from uuid import uuid4
15+
import MySQLdb as mdb
16+
17+
18+
def generate_key(num):
19+
key_list = [str(uuid4()) for i in range(num)]
20+
return key_list
21+
22+
23+
def create_a_table_and_put_keys(key_list):
24+
with mdb.connect('localhost', 'test', '123', 'testdb') as cur:
25+
26+
# create table
27+
cur.execute("DROP TABLE IF EXISTS rkeys")
28+
cur.execute("CREATE TABLE rkeys(\
29+
key_value CHAR(40) NOT NULL\
30+
)")
31+
32+
# insert data
33+
# I want to use executemany, but there is a library bug...
34+
# It seems that executemany cannot match single-string list
35+
# cur.executemany("INSERT INTO rkeys VALUES(%s)", key_list)
36+
for i in key_list:
37+
cur.execute("INSERT INTO rkeys(key_value)\
38+
VALUES('%s')" % i)
39+
40+
41+
def main():
42+
create_a_table_and_put_keys(generate_key(200))
43+
44+
45+
if __name__ == '__main__':
46+
main()
Lines changed: 144 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,144 @@
1+
# Python Databases Note - MySQL
2+
3+
4+
### install and setting
5+
```
6+
sudo apt-get install mysql-server
7+
sudo apt-get install python-mysqldb
8+
mysql -u root -p
9+
# create a user and table in mysql
10+
> CREATE DATABASE testdb;
11+
> CREATE USER 'testuser'@'localhost' IDENTIFIED BY '123';
12+
> USE testdb;
13+
> GRANT ALL ON testdb.* TO 'testuser'@'localhost';
14+
```
15+
16+
17+
### _mysql module
18+
19+
The _mysql module implements the MySQL C API directly.
20+
Not compatible.
21+
22+
Fetch version
23+
24+
```
25+
#!/usr/bin/python
26+
# -*- coding: utf-8 -*-
27+
28+
import _mysql
29+
import sys
30+
31+
try:
32+
con = _mysql.connect('localhost', 'test', '123', 'testdb')
33+
34+
con.query("SELECT VERSION()")
35+
result = con.use_result()
36+
37+
print "MySQL version: %s" % \
38+
result.fetch_row()[0]
39+
40+
except _mysql.Error, e:
41+
42+
print "Error %d: %s" % (e.args[0], e.args[1])
43+
sys.exit(1)
44+
45+
finally:
46+
if con:
47+
con.close()
48+
```
49+
50+
51+
### MySQLdb module
52+
53+
MySQLdb is a thin Python wrapper around _mysql.
54+
55+
56+
1. con = mdb.connect(...)
57+
2. cur = con.cursor() // **get cursor**
58+
3. cur.execute("SELECT * FROM xxx")
59+
4. cur.executemany("INSERT INTO xxx VALUES(%s, %s)", value_list)
60+
4. except mdb.Error, e // **remember this**
61+
5. cur.rowcount
62+
6. cur.fetchone() // **return one**
63+
7. cur.fetchall() // **return a list**
64+
8. cur = con.cursor(mdb.cursors.DictCursor) // **dictionary cursor, we can refer to the data by their column names**
65+
9. desc = cur.description // **table column names**
66+
67+
68+
Fetch version.
69+
70+
```
71+
#!/usr/bin/python
72+
# -*- coding: utf-8 -*-
73+
74+
import MySQLdb as mdb
75+
import sys
76+
77+
try:
78+
con = mdb.connect('localhost', 'test', '123', 'testdb');
79+
cur = con.cursor()
80+
cur.execute("SELECT VERSION()")
81+
82+
ver = cur.fetchone()
83+
print "Database version : %s " % ver
84+
85+
except mdb.Error, e:
86+
print "Error %d: %s" % (e.args[0],e.args[1])
87+
sys.exit(1)
88+
89+
finally:
90+
if con:
91+
con.close()
92+
```
93+
94+
Create a table and populate it with some data
95+
96+
```
97+
#!/usr/bin/python
98+
# -*- coding: utf-8 -*-
99+
100+
import MySQLdb as mdb
101+
102+
con = mdb.connect('localhost', 'test', '123', 'testdb');
103+
104+
with con: # automatically release con
105+
cur = con.cursor()
106+
# Above can be `with mdb.connect(...) as cur`
107+
108+
cur.execute("DROP TABLE IF EXISTS Writers")
109+
cur.execute("CREATE TABLE Writers(Id INT PRIMARY KEY AUTO_INCREMENT, \
110+
Name VARCHAR(25))")
111+
cur.execute("INSERT INTO Writers(Name) VALUES('Jack London')")
112+
```
113+
114+
Retrieving data
115+
116+
```
117+
#!/usr/bin/python
118+
# -*- coding: utf-8 -*-
119+
120+
import MySQLdb as mdb
121+
122+
con = mdb.connect('localhost', 'test', '123', 'testdb');
123+
124+
with con:
125+
cur = con.cursor() # con.cursor(mdb.cursors.DictCursor)
126+
cur.execute("SELECT * FROM Writers")
127+
128+
rows = cur.fetchall() # if is DictCursor rows is a dict
129+
for row in rows:
130+
print row
131+
132+
# or fetch one by one
133+
# for i in range(cur.rowcount):
134+
# row = cur.fetchone()
135+
# print row
136+
```
137+
138+
139+
### Some resources:
140+
[MySQLdb User's Guide](http://mysql-python.sourceforge.net/MySQLdb.html)
141+
[python-mysqldb API](http://mysql-python.sourceforge.net/MySQLdb-1.2.2/)
142+
[StackOverflow-How do I connect to a MySQL Database in Python?](http://stackoverflow.com/questions/372885/how-do-i-connect-to-a-mysql-database-in-python)
143+
[Good start:Zencode](http://zetcode.com/db/mysqlpython/) (I use this :smile:)
144+

illuz/readme.md

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
# My solution for Show-Me-the-Code/python
2+
3+
### The Problems description:
4+
5+
[Chinese Version](https://github.com/illuz/show-me-the-code/blob/master/README.md)
6+
7+
8+
### There are some notes:
9+
10+
- [Python Databases Note - MySQL](./Python Databases Note - MySQL.md)
11+

0 commit comments

Comments
 (0)