存档

‘Script’ 分类的存档

产生网站验证码图片的脚本

2009年12月18日
Comments Off

近日想用 web.py 搭建一个网站,在登录部分想到用验证码,参考了网上的一些代码以后自己改写出想要的版本,其特点如下:

1) 图片内容为代数算式
2) 有线条干扰
3) 除去生成验证码图片外还返回一个元组: (filename, result)

使用倒是挺方便的,先放出源码,希望能启发大家。
这里有一张生成的图片:

验证码例图

源码:

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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Name:     genpic.py
# Author:   xiooli <xioooli[at]yahoo.com.cn>
# Site:     http://joolix.com
# Licence:  GPLv3
# Version:  091218
 
'''用于产生网站验证码图片(代数算式)'''
 
import Image,ImageDraw,ImageFont
import random
import math
import hashlib
import datetime
 
def genpic():
    '''生成验证码图片,返回一个元组(filename,result)'''
    #图片宽度
    width = 130
    #图片高度
    height = 35
    #背景颜色
    bgcolor = (151, random.randint(0,225), random.randint(0,225))
    #生成背景图片
    image = Image.new('RGB',(width,height),bgcolor)
    #加载字体
    font = ImageFont.truetype('/usr/share/fonts/TTF/DejaVuSans-Bold.ttf',27)
    #字体颜色
    fontcolor = (0, 0, 0)
 
    #产生draw对象
    draw = ImageDraw.Draw(image)
 
    # 生成算式
    ops = ['+', '-']
    op = random.choice(ops)
    num1 = random.randint(0, 99)
    num2 = random.randint(0, 99)
    rand_str = str(num1) + " " + op + " " + str(num2)
    result = str(eval(rand_str))
 
    # 生成文件名
    m = hashlib.md5()
    m.update(str(datetime.datetime.now()))
    fnm = m.hexdigest()
 
    #画字体,(0,0)是起始位置
    draw.text((0,0),rand_str + ' =',font=font,fill=fontcolor)
 
    #画线
    #线的颜色
    linecolor= (random.randint(0,225), random.randint(0,225), random.randint(0,225))
    for i in range(0,15):
        #随机产生线条
        x1 = random.randint(0,width)
        x2 = random.randint(0,width)
        y1 = random.randint(0,height)
        y2 = random.randint(0,height)
        draw.line([(x1, y1), (x2, y2)], linecolor)
 
    #释放draw
    del draw
 
    #保存文件到本地
    image.save(fnm + '.jpg')
    return (fnm, result)
 
if __name__ == "__main__":
    pic = genpic()
    print pic

Script , ,

snail 溶剂比例计算器升级版

2009年12月12日
Comments Off

添加了利用现有两种溶液来计算欲配溶液的功能
修复了一些易引发错误的代码。
片片:
snail2 抓图

代码:
snail.py :

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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
#!/usr/bin/python
# -*- coding: utf-8 -*-
 
# Author:   xiooli <xioooli[at]yahoo.com.cn>
# Site:     http://joolix.com
# Licence:  GPLv3
 
import sys, os
from PyQt4 import QtCore, QtGui
from ui_zh import Ui_mainWindow
from PyQt4.QtGui import QMainWindow
from PyQt4.QtCore import pyqtSignature
 
 
class Win(QMainWindow, Ui_mainWindow):
    def __init__(self, parent = None):
        QMainWindow.__init__(self, parent)
        self.setupUi(self)
    @pyqtSignature("")
    def on_pushButton_clicked(self):
        self.label_6_txt = ""
        now_B_A = now_B_B = ""
        continue_com = ""
        vol = ""
        rst = ""
 
        try:
            now_B_A = float(self.lineEdit_4.text())
            now_B_B = float(self.lineEdit_5.text())
        except:
            pass
        try:
            now_A_A = float(self.lineEdit_1.text())
            now_A_B = float(self.lineEdit_2.text())
            now_vol = float(self.lineEdit_3.text())
            want_A = float(self.lineEdit_6.text())
            want_B = float(self.lineEdit_7.text())
        except ValueError:
           self.label_6_txt = "错误:有输入框未输入数字,或输入了非数字字符!"
 
        if ( not self.label_6_txt ) and ( now_B_A and now_B_B ):
            try:
                vol,rst = self.lineEdit_3.text(),\
                        round(now_vol*( now_A_A/(now_A_A+now_A_B)-want_A/(want_A+want_B) ) / \
                        ( want_A/(want_A+want_B)-now_B_A/(now_B_A+now_B_B) ), 4)
            except ZeroDivisionError:
                self.label_6_txt = "错误:试图除零!"
            if rst != "" and rst > 0:
                rst = str(rst)
                self.label_6_txt = "须向 " + vol + " ML 现有溶液 A 中加入现有溶液 B " + rst + " ML"
            else:
                self.label_6_txt = "注意:现有溶液 A 和 B 不能配制出欲配溶液<p>"
                continue_com = 1
 
        if ( not self.label_6_txt ) or continue_com:
            if want_A*(now_A_A+now_A_B) == 0:
                self.label_6_txt = "错误:试图除零!"
            elif want_B != 0 and (now_A_B == 0 or now_A_A / now_A_B > want_A / want_B):
                vol,rst = self.lineEdit_3.text(),\
                        str(round(now_vol*now_A_A*(want_A+want_B)/(want_A*(now_A_A+now_A_B))-now_vol,4))
                self.label_6_txt += "须向 " + vol + " ML 现有溶液 A 中加入溶剂 B " + rst + " ML"
            elif want_B != 0 and now_A_B != 0 and now_A_A / now_A_B == want_A / want_B:
                self.label_6_txt = "现有溶液 A 和欲配溶液是同一种溶液,无须额外动作。"
            else:
                try:
                    vol,rst=self.lineEdit_3.text(),\
                            str(round(now_vol*now_A_B*(want_A+want_B)/(want_B*(now_A_A+now_A_B))-now_vol,4))
                    self.label_6_txt += "须向 " + vol + " ML 现有溶液 A 中加入溶剂 A " + rst + " ML"
                except ZeroDivisionError:
                    self.label_6_txt = "错误:试图除零!"
 
        self.label_6.setText(QtGui.QApplication.translate("mainWindow", self.label_6_txt, None, QtGui.QApplication.UnicodeUTF8))
 
 
if __name__ == "__main__":
    app = QtGui.QApplication(sys.argv)
    win=Win()
    win.show()
    sys.exit(app.exec_())

ui_zh.py :

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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
# -*- coding: utf-8 -*-
 
# Form implementation generated from reading ui file 'snail.ui'
#
# Created: Wed Nov 11 21:15:36 2009
#      by: PyQt4 UI code generator 4.6.1
#
# WARNING! All changes made in this file will be lost!
 
from PyQt4 import QtCore, QtGui
 
class Ui_mainWindow(object):
    def setupUi(self, mainWindow):
        mainWindow.setObjectName("mainWindow")
        mainWindow.resize(872, 452)
        self.centralwidget = QtGui.QWidget(mainWindow)
        self.centralwidget.setObjectName("centralwidget")
        self.lineEdit_1 = QtGui.QLineEdit(self.centralwidget)
        self.lineEdit_1.setGeometry(QtCore.QRect(250, 90, 171, 51))
        self.lineEdit_1.setStyleSheet("font: 22pt \"Bitstream Vera Sans Mono\";")
        self.lineEdit_1.setObjectName("lineEdit_1")
        self.lineEdit_2 = QtGui.QLineEdit(self.centralwidget)
        self.lineEdit_2.setGeometry(QtCore.QRect(460, 90, 171, 51))
        self.lineEdit_2.setStyleSheet("font: 22pt \"Bitstream Vera Sans Mono\";")
        self.lineEdit_2.setObjectName("lineEdit_2")
        self.lineEdit_3 = QtGui.QLineEdit(self.centralwidget)
        self.lineEdit_3.setGeometry(QtCore.QRect(670, 90, 161, 51))
        self.lineEdit_3.setStyleSheet("font: 22pt \"Bitstream Vera Sans Mono\";")
        self.lineEdit_3.setObjectName("lineEdit_3")
        self.lineEdit_4 = QtGui.QLineEdit(self.centralwidget)
        self.lineEdit_4.setGeometry(QtCore.QRect(250, 170, 171, 51))
        self.lineEdit_4.setStyleSheet("font: 22pt \"Bitstream Vera Sans Mono\";")
        self.lineEdit_4.setObjectName("lineEdit_4")
        self.lineEdit_5 = QtGui.QLineEdit(self.centralwidget)
        self.lineEdit_5.setGeometry(QtCore.QRect(460, 170, 171, 51))
        self.lineEdit_5.setStyleSheet("font: 22pt \"Bitstream Vera Sans Mono\";")
        self.lineEdit_5.setObjectName("lineEdit_5")
        self.label = QtGui.QLabel(self.centralwidget)
        self.label.setGeometry(QtCore.QRect(280, 20, 131, 41))
        self.label.setStyleSheet("font: 22pt \"Bitstream Vera Sans Mono\"; A")
        self.label.setObjectName("label")
        self.label_2 = QtGui.QLabel(self.centralwidget)
        self.label_2.setGeometry(QtCore.QRect(490, 20, 131, 41))
        self.label_2.setStyleSheet("font: 22pt \"Bitstream Vera Sans Mono\"; A")
        self.label_2.setObjectName("label_2")
        self.label_3 = QtGui.QLabel(self.centralwidget)
        self.label_3.setGeometry(QtCore.QRect(710, 20, 131, 41))
        self.label_3.setStyleSheet("font: 22pt \"Bitstream Vera Sans Mono\"; A")
        self.label_3.setObjectName("label_3")
        self.label_4 = QtGui.QLabel(self.centralwidget)
        self.label_4.setGeometry(QtCore.QRect(40, 100, 171, 41))
        self.label_4.setStyleSheet("font: 22pt \"Bitstream Vera Sans Mono\"; A")
        self.label_4.setObjectName("label_4")
        self.label_5 = QtGui.QLabel(self.centralwidget)
        self.label_5.setGeometry(QtCore.QRect(40, 250, 171, 41))
        self.label_5.setStyleSheet("font: 22pt \"Bitstream Vera Sans Mono\"; A")
        self.label_5.setObjectName("label_5")
        self.pushButton = QtGui.QPushButton(self.centralwidget)
        self.pushButton.setGeometry(QtCore.QRect(670, 170, 161, 51))
        self.pushButton.setStyleSheet("font: 22pt \"Bitstream Vera Sans Mono\";")
        self.pushButton.setObjectName("pushButton")
        self.frame = QtGui.QFrame(self.centralwidget)
        self.frame.setEnabled(True)
        self.frame.setGeometry(QtCore.QRect(40, 330, 791, 91))
        self.frame.setMouseTracking(False)
        self.frame.setAutoFillBackground(False)
        self.frame.setFrameShape(QtGui.QFrame.StyledPanel)
        self.frame.setFrameShadow(QtGui.QFrame.Raised)
        self.frame.setObjectName("frame")
        self.label_6 = QtGui.QLabel(self.frame)
        self.label_6.setGeometry(QtCore.QRect(10, 10, 781, 71))
        self.label_6.setStyleSheet("""font: 22pt \"Bitstream Vera Sans Mono\"; color: rgb(0, 0, 255);""")
        self.label_6.setObjectName("label_6")
        self.label_7 = QtGui.QLabel(self.centralwidget)
        self.label_7.setGeometry(QtCore.QRect(40, 180, 171, 41))
        self.label_7.setStyleSheet("font: 22pt \"Bitstream Vera Sans Mono\"; A")
        self.label_7.setObjectName("label_7")
        self.lineEdit_6 = QtGui.QLineEdit(self.centralwidget)
        self.lineEdit_6.setGeometry(QtCore.QRect(250, 250, 171, 51))
        self.lineEdit_6.setStyleSheet("font: 22pt \"Bitstream Vera Sans Mono\";")
        self.lineEdit_6.setObjectName("lineEdit_6")
        self.lineEdit_7 = QtGui.QLineEdit(self.centralwidget)
        self.lineEdit_7.setGeometry(QtCore.QRect(460, 250, 171, 51))
        self.lineEdit_7.setStyleSheet("font: 22pt \"Bitstream Vera Sans Mono\";")
        self.lineEdit_7.setObjectName("lineEdit_7")
        self.pushButton_2 = QtGui.QPushButton(self.centralwidget)
        self.pushButton_2.setGeometry(QtCore.QRect(670, 250, 161, 51))
        self.pushButton_2.setStyleSheet("font: 22pt \"Bitstream Vera Sans Mono\";")
        self.pushButton_2.setObjectName("pushButton_2")
        mainWindow.setCentralWidget(self.centralwidget)
        self.menubar = QtGui.QMenuBar(mainWindow)
        self.menubar.setGeometry(QtCore.QRect(0, 0, 872, 25))
        self.menubar.setObjectName("menubar")
        mainWindow.setMenuBar(self.menubar)
        self.statusbar = QtGui.QStatusBar(mainWindow)
        self.statusbar.setObjectName("statusbar")
        mainWindow.setStatusBar(self.statusbar)
 
        self.retranslateUi(mainWindow)
        QtCore.QObject.connect(self.pushButton, QtCore.SIGNAL("clicked()"), self.label_6.clear)
        QtCore.QObject.connect(self.pushButton_2, QtCore.SIGNAL("clicked()"), mainWindow.close)
        QtCore.QMetaObject.connectSlotsByName(mainWindow)
 
    def retranslateUi(self, mainWindow):
        mainWindow.setWindowTitle(QtGui.QApplication.translate("mainWindow", " 溶剂比例计算器 - Snail", None, QtGui.QApplication.UnicodeUTF8))
        self.lineEdit_3.setText(QtGui.QApplication.translate("mainWindow", "1000", None, QtGui.QApplication.UnicodeUTF8))
        self.label.setText(QtGui.QApplication.translate("mainWindow", " 溶剂 A", None, QtGui.QApplication.UnicodeUTF8))
        self.label_2.setText(QtGui.QApplication.translate("mainWindow", " 溶剂 B", None, QtGui.QApplication.UnicodeUTF8))
        self.label_3.setText(QtGui.QApplication.translate("mainWindow", "体积", None, QtGui.QApplication.UnicodeUTF8))
        self.label_4.setText(QtGui.QApplication.translate("mainWindow", "现有溶液 A", None, QtGui.QApplication.UnicodeUTF8))
        self.label_5.setText(QtGui.QApplication.translate("mainWindow", "欲配溶液", None, QtGui.QApplication.UnicodeUTF8))
        self.pushButton.setText(QtGui.QApplication.translate("mainWindow", "计算", None, QtGui.QApplication.UnicodeUTF8))
        self.label_6.setText(QtGui.QApplication.translate("mainWindow", "欢迎使用溶剂比例计算器 Snail\nxiooli <xioooli@yahoo.com.cn>", None, QtGui.QApplication.UnicodeUTF8))
        self.label_7.setText(QtGui.QApplication.translate("mainWindow", "现有溶液 B", None, QtGui.QApplication.UnicodeUTF8))
        self.pushButton_2.setText(QtGui.QApplication.translate("mainWindow", "关闭", None, QtGui.QApplication.UnicodeUTF8))

Chemistry, Script , ,

pyqt 的溶剂比例计算器 snail

2009年11月10日

RT
开始做植化了,要用,鑫哥的那个是 for win 的,以前写了个 ruby-gtk 的不知道扔哪里去了,于是重新写了个 pyqt 的。

ps: 图形界面的程序真是浪费表情阿,真正干活的就两三行,一旦要图形界面了就几百行,这个看来是死要面子(图形界面)活受罪的真实写照阿,呵呵。

片片:
snail 抓图

源码:

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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
#!/usr/bin/python
# -*- coding: utf-8 -*-
 
# Form implementation generated from reading ui file 'snail.ui'
#
# Created: Tue Nov 10 17:44:47 2009
#      by: PyQt4 UI code generator 4.6.1
#
# WARNING! All changes made in this file will be lost!
 
import sys, os
from PyQt4 import QtCore, QtGui
from PyQt4.QtGui import QMainWindow
from PyQt4.QtCore import pyqtSignature
 
class Ui_mainWindow(object):
    def setupUi(self, mainWindow):
        mainWindow.setObjectName("mainWindow")
        mainWindow.resize(767, 375)
        self.centralwidget = QtGui.QWidget(mainWindow)
        self.centralwidget.setObjectName("centralwidget")
        self.textEdit = QtGui.QTextEdit(self.centralwidget)
        self.textEdit.setGeometry(QtCore.QRect(170, 90, 171, 51))
        self.textEdit.setStyleSheet("font: 22pt \"Bitstream Vera Sans Mono\";")
        self.textEdit.setObjectName("textEdit")
        self.textEdit_2 = QtGui.QTextEdit(self.centralwidget)
        self.textEdit_2.setGeometry(QtCore.QRect(380, 90, 171, 51))
        self.textEdit_2.setStyleSheet("font: 22pt \"Bitstream Vera Sans Mono\";")
        self.textEdit_2.setObjectName("textEdit_2")
        self.textEdit_3 = QtGui.QTextEdit(self.centralwidget)
        self.textEdit_3.setGeometry(QtCore.QRect(590, 90, 161, 51))
        self.textEdit_3.setStyleSheet("font: 22pt \"Bitstream Vera Sans Mono\";")
        self.textEdit_3.setObjectName("textEdit_3")
        self.textEdit_4 = QtGui.QTextEdit(self.centralwidget)
        self.textEdit_4.setGeometry(QtCore.QRect(170, 180, 171, 51))
        self.textEdit_4.setStyleSheet("font: 22pt \"Bitstream Vera Sans Mono\";")
        self.textEdit_4.setObjectName("textEdit_4")
        self.textEdit_5 = QtGui.QTextEdit(self.centralwidget)
        self.textEdit_5.setGeometry(QtCore.QRect(380, 180, 171, 51))
        self.textEdit_5.setStyleSheet("font: 22pt \"Bitstream Vera Sans Mono\";")
        self.textEdit_5.setObjectName("textEdit_5")
        self.label = QtGui.QLabel(self.centralwidget)
        self.label.setGeometry(QtCore.QRect(200, 20, 131, 41))
        self.label.setStyleSheet("font: 26pt \"Bitstream Vera Sans Mono\"; 溶剂 A")
        self.label.setObjectName("label")
        self.label_2 = QtGui.QLabel(self.centralwidget)
        self.label_2.setGeometry(QtCore.QRect(410, 20, 131, 41))
        self.label_2.setStyleSheet("font: 26pt \"Bitstream Vera Sans Mono\"; 溶剂 A")
        self.label_2.setObjectName("label_2")
        self.label_3 = QtGui.QLabel(self.centralwidget)
        self.label_3.setGeometry(QtCore.QRect(630, 20, 131, 41))
        self.label_3.setStyleSheet("font: 26pt \"Bitstream Vera Sans Mono\"; 溶剂 A")
        self.label_3.setObjectName("label_3")
        self.label_4 = QtGui.QLabel(self.centralwidget)
        self.label_4.setGeometry(QtCore.QRect(20, 90, 151, 41))
        self.label_4.setStyleSheet("font: 26pt \"Bitstream Vera Sans Mono\"; 溶剂 A")
        self.label_4.setObjectName("label_4")
        self.label_5 = QtGui.QLabel(self.centralwidget)
        self.label_5.setGeometry(QtCore.QRect(20, 190, 151, 41))
        self.label_5.setStyleSheet("font: 26pt \"Bitstream Vera Sans Mono\"; 溶剂 A")
        self.label_5.setObjectName("label_5")
        self.pushButton = QtGui.QPushButton(self.centralwidget)
        self.pushButton.setGeometry(QtCore.QRect(590, 180, 161, 51))
        self.pushButton.setStyleSheet("font: 20pt \"Bitstream Vera Sans Mono\";")
        self.pushButton.setObjectName("pushButton")
        self.label_6 = QtGui.QLabel(self.centralwidget)
        self.label_6.setGeometry(QtCore.QRect(30, 270, 721, 71))
        self.label_6.setStyleSheet("""font: 22pt \"Bitstream Vera Sans Mono\"; color: rgb(0, 0, 255);""")
        self.label_6.setObjectName("label_6")
        self.frame = QtGui.QFrame(self.centralwidget)
        self.frame.setEnabled(True)
        self.frame.setGeometry(QtCore.QRect(20, 260, 731, 91))
        self.frame.setMouseTracking(False)
        self.frame.setAutoFillBackground(False)
        self.frame.setFrameShape(QtGui.QFrame.StyledPanel)
        self.frame.setFrameShadow(QtGui.QFrame.Raised)
        self.frame.setObjectName("frame")
        mainWindow.setCentralWidget(self.centralwidget)
        self.menubar = QtGui.QMenuBar(mainWindow)
        self.menubar.setGeometry(QtCore.QRect(0, 0, 767, 25))
        self.menubar.setObjectName("menubar")
        mainWindow.setMenuBar(self.menubar)
        self.statusbar = QtGui.QStatusBar(mainWindow)
        self.statusbar.setObjectName("statusbar")
        mainWindow.setStatusBar(self.statusbar)
 
        self.retranslateUi(mainWindow)
        #QtCore.QObject.connect(self.pushButton, QtCore.SIGNAL("clicked()"), self.label_6.)
        QtCore.QMetaObject.connectSlotsByName(mainWindow)
 
    def retranslateUi(self, mainWindow):
        mainWindow.setWindowTitle(QtGui.QApplication.translate("mainWindow", "溶剂比例计算器 -Snail", None, QtGui.QApplication.UnicodeUTF8))
        self.textEdit_3.setHtml(QtGui.QApplication.translate("mainWindow", "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0//EN\" \"http://www.w3.org/TR/REC-html40/strict.dtd\">\n"
"<html><head><meta name=\"qrichtext\" content=\"1\" /><style type=\"text/css\">\n"
"p, li { white-space: pre-wrap; }\n"
"</style></head><body style=\" font-family:\'Bitstream Vera Sans Mono\'; font-size:22pt; font-weight:400; font-style:normal;\">\n"
"<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">1000</p></body></html>", None, QtGui.QApplication.UnicodeUTF8))
        self.label.setText(QtGui.QApplication.translate("mainWindow", "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0//EN\" \"http://www.w3.org/TR/REC-html40/strict.dtd\">\n"
"<html><head><meta name=\"qrichtext\" content=\"1\" /><style type=\"text/css\">\n"
"p, li { white-space: pre-wrap; }\n"
"</style></head><body style=\" font-family:\'Bitstream Vera Sans Mono\'; font-size:26pt; font-weight:400; font-style:normal;\">\n"
"<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">溶剂 A</p></body></html>", None, QtGui.QApplication.UnicodeUTF8))
        self.label_2.setText(QtGui.QApplication.translate("mainWindow", "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0//EN\" \"http://www.w3.org/TR/REC-html40/strict.dtd\">\n"
"<html><head><meta name=\"qrichtext\" content=\"1\" /><style type=\"text/css\">\n"
"p, li { white-space: pre-wrap; }\n"
"</style></head><body style=\" font-family:\'Bitstream Vera Sans Mono\'; font-size:26pt; font-weight:400; font-style:normal;\">\n"
"<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">溶剂 B</p></body></html>", None, QtGui.QApplication.UnicodeUTF8))
        self.label_3.setText(QtGui.QApplication.translate("mainWindow", "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0//EN\" \"http://www.w3.org/TR/REC-html40/strict.dtd\">\n"
"<html><head><meta name=\"qrichtext\" content=\"1\" /><style type=\"text/css\">\n"
"p, li { white-space: pre-wrap; }\n"
"</style></head><body style=\" font-family:\'Bitstream Vera Sans Mono\'; font-size:26pt; font-weight:400; font-style:normal;\">\n"
"<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">体积</p></body></html>", None, QtGui.QApplication.UnicodeUTF8))
        self.label_4.setText(QtGui.QApplication.translate("mainWindow", "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0//EN\" \"http://www.w3.org/TR/REC-html40/strict.dtd\">\n"
"<html><head><meta name=\"qrichtext\" content=\"1\" /><style type=\"text/css\">\n"
"p, li { white-space: pre-wrap; }\n"
"</style></head><body style=\" font-family:\'Bitstream Vera Sans Mono\'; font-size:26pt; font-weight:400; font-style:normal;\">\n"
"<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">现有溶液</p></body></html>", None, QtGui.QApplication.UnicodeUTF8))
        self.label_5.setText(QtGui.QApplication.translate("mainWindow", "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0//EN\" \"http://www.w3.org/TR/REC-html40/strict.dtd\">\n"
"<html><head><meta name=\"qrichtext\" content=\"1\" /><style type=\"text/css\">\n"
"p, li { white-space: pre-wrap; }\n"
"</style></head><body style=\" font-family:\'Bitstream Vera Sans Mono\'; font-size:26pt; font-weight:400; font-style:normal;\">\n"
"<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">欲配溶液</p></body></html>", None, QtGui.QApplication.UnicodeUTF8))
        self.pushButton.setText(QtGui.QApplication.translate("mainWindow", "也来算一个!", None, QtGui.QApplication.UnicodeUTF8))
        self.label_6.setText(QtGui.QApplication.translate("mainWindow", "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0//EN\" \"http://www.w3.org/TR/REC-html40/strict.dtd\">\n"
"<html><head><meta name=\"qrichtext\" content=\"1\" /><style type=\"text/css\">\n"
"p, li { white-space: pre-wrap; }\n"
"</style></head><body style=\" font-family:\'Bitstream Vera Sans Mono\'; font-size:22pt; font-weight:400; font-style:normal;\">\n"
"<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">欢迎使用溶剂比例计算器 Snail</p>\n"
"<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">Xiooli &lt;xioooli@yahoo.com.cn&gt;</p></body></html>", None, QtGui.QApplication.UnicodeUTF8))
 
 
 
class Win(QMainWindow, Ui_mainWindow):
    def __init__(self, parent = None):
        QMainWindow.__init__(self, parent)
        self.setupUi(self)
    @pyqtSignature("")
    def on_pushButton_clicked(self):
        self.label_6_txt = ""
        try:
            now_A = float(self.textEdit.toPlainText())
            now_B = float(self.textEdit_2.toPlainText())
            now_vol = float(self.textEdit_3.toPlainText())
            want_A = float(self.textEdit_4.toPlainText())
            want_B = float(self.textEdit_5.toPlainText())
        except ValueError:
           self.label_6_txt = "错误:有输入框未输入数字,或输入了非数字字符!"
 
        if not self.label_6_txt:
            if want_A*(now_A+now_B) == 0 or want_B*(now_A+now_B) == 0:
                self.label_6_txt = "错误:试图除零!"
            elif now_A / now_B > want_A / want_B:
                vol,rst=self.textEdit_3.toPlainText(),\
                        str(round(now_vol*now_A*(want_A+want_B)/(want_A*(now_A+now_B))-now_vol,4))
                self.label_6_txt = "须向 " + vol + " ML 现有溶液中加入溶液 B " + rst + " ML"
            elif now_A / now_B == want_A / want_B:
                self.label_6_txt = "现有溶液和欲配溶液是同一种溶液,无须额外动作。"
            else:
                vol,rst=self.textEdit_3.toPlainText(),\
                        str(round(now_vol*now_B*(want_A+want_B)/(want_B*(now_A+now_B))-now_vol,4))
                self.label_6_txt = "须向 " + vol + " ML 现有溶液中加入溶液 A " + rst + " ML"
        self.label_6.setText(QtGui.QApplication.translate("mainWindow", "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0//EN\" \"http://www.w3.org/TR/REC-html40/strict.dtd\">\n"
"<html><head><meta name=\"qrichtext\" content=\"1\" /><style type=\"text/css\">\n"
"p, li { white-space: pre-wrap; }\n"
"</style></head><body style=\" font-family:\'Bitstream Vera Sans Mono\'; font-size:22pt; font-weight:400; font-style:normal;\">\n"
"<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">"+self.label_6_txt+"</p></body></html>", None, QtGui.QApplication.UnicodeUTF8))
 
 
if __name__ == "__main__":
    app = QtGui.QApplication(sys.argv)
    win=Win()
    win.show()
    sys.exit(app.exec_())

Chemistry, Script , , ,

编码和解码莫尔斯电码的脚本

2009年11月4日
Comments Off

RT
中文先将其编码成 urlencode 然后才转换成莫尔斯电码,呵呵,脚本有两个参数,-e 和 -d
-e 是将文本转换成莫尔斯电码, -d 是将电码转回文本,下面是一个例子:

1
2
3
4
5
xiooli@XIOOLI> python morse.py -e "hello 大家好,我是 xiooli!"                             /tmp
.... . .-.. .-.. --- .-.- ..--- ----- .-.- . ..... .-.- .- ....- .-.- .- --... .-.- . ..... .-.- .- . .-.- -... -.... .-.- . ..... .-.- .- ..... .-.- -... -.. .-.- . ..-. .-.- -... -.-. .-.- ---.. -.-. .-.- . -.... .-.- ---.. ---.. .-.- ----. .---- .-.- . -.... .-.- ----. ---.. .-.- .- ..-. .-.- ..--- ----- -..- .. --- --- .-.. .. .-.- . ..-. .-.- -... -.-. .-.- ---.. .----
xiooli@XIOOLI> python morse.py -d ".... . .-.. .-.. --- .-.- ..--- ----- .-.- . ..... .-.- .- ....- .-.- .- --... .-.- . ..... .-.- .- . .-.- -... -.... .-.- . ..... .-.- .- ..... .-.- -... -.. .-.- . ..-. .-.- -... -.-. .-.- ---.. -.-. .-.- . -.... .-.- ---.. ---.. .-.- ----. .---- .-.- . -.... .-.- ----. ---.. .-.- .- ..-. .-.- ..--- ----- -..- .. --- --- .-.. .. .-.- . ..-. .-.- -... -.-. .-.- ---.. .----"
hello 大家好,我是 xiooli!
xiooli@XIOOLI>                                                                              /tmp

大家可以用这个给小mm写情书哦^^

源代码如下:

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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Name:     morse.py
# Author:   xiooli
#           Email:  <xioooli[at]yahoo.com.cn>
#           Site:   http://joolix.com
# Licence:  GPLv3
# Version:  091104
 
''' Generate and transelate the morse code string. 
'''
import re, urllib, sys
 
# the morse code for % is actually the code for ä or æ, I just borrowed it.
txt_morse={'a':'.-', 'b':'-...', 'c':'-.-.', 'd':'-..',
        'e':'.', 'f':'..-.', 'g':'--.', 'h':'....',
        'i':'..', 'j':'.---', 'k':'-.-', 'l':'.-..',
        'm':'--', 'n':'-.', 'o':'---', 'p':'.--.',
        'q':'--.-', 'r':'.-.', 's':'...', 't':'-',
        'u':'..-', 'v':'...-', 'w':'.--', 'x':'-..-',
        'y':'-.--', 'z':'--..', '0':'-----', '1':'.----',
        '2':'..---', '3':'...--', '4':'....-', '5':'.....',
        '6':'-....', '7':'--...', '8':'---..', '9':'----.',
        '.':'.-.-.-', ',':'--..--', ':':'---...', '?':'..--..',
        '-':'-....-', '/':'-..-.', '=':'-...-', '@': '...-.-',
        '!':'...-.-', '\n':'', '%':'.-.-', ',':'--..--',
        ';':'-.-.-.', '_':'..--.-', '"':'.-..-.', '(':'-.--.',
        ')':'-.--.-', '$':'...-..-', ' ':' '
        }
morse_txt = {}
for i,j in txt_morse.items():
    morse_txt[j] = i
 
def gen_mc(str):
    mc = []
    str = urllib.quote(str).lower()
 
    for c in list(str):
        mc.append(txt_morse[c]+ " ")
    return "".join(mc)
 
def decode_mc(str):
    L = []
    l = str.split(" ")
 
    for mc in l:
        L.append(morse_txt[mc])
    str = "".join(L)
    return urllib.unquote(str)
 
if __name__ == "__main__":
    if len(sys.argv) <= 2:
        print "Error, at lest 2 arguments is needed!"
        sys.exit(1)
    elif sys.argv[1] == "-e":
        try:
            print gen_mc(sys.argv[2])
        except:
            print "Morse encoding failed, please check your string."
    elif sys.argv[1] == "-d":
        try:
            print decode_mc(sys.argv[2])
        except:
            print "Morse decoding failed, please check your string."
    else:
        print "Argument not recorded, don't know how to handle!"
        sys.exit(2)

Script

Firefox下直接观看PPS看看

2009年10月16日
Comments Off

ubuntu论坛牛人写了pps的totem插件,可以用于观看pps的节目,具体安装方法debian系的参考http://forum.ubuntu.org.cn/viewtopic.php?f=74&t=223582
archlinux用以下命令即可安装:

yaourt -S libppswrapper-git gst-plugins-pps-git totem-pps-git libpps gst-plugins-sopcast-git totem-sopcast-git

但是这样只可以在totem的窗口里面看,当然也可以点击pps看看节目右边的客户端播放,然后将其关联到totem,但是总离不了一个独立的totem窗口,于是我们的 Hello World 童鞋在自我需求的推动下写了一个greasemonkey脚本,让其可直接在frefox的窗口下播放pps看看(当然是调用totem-pps的)。

要正常使用这个油猴脚本,你需要满足几个基本条件:
1) 能正常使用的totem-pps
2) totem-plugin(arch下的包名字,其他distro.里面自己找找吧)
3) firefox 安装并启用 greasemonkey

一切就绪以后你就可以去pps上面踢馆咯,哈哈!

greasemonkey 脚本从这里下载:http://forum.ubuntu.org.cn/download/file.php?id=80735,解压后拖到firefox的窗口里面进行安装。

秀图一张:
pps-in-ff

Script , , , ,

植化流程图生成脚本

2009年9月9日

RT
做植化的同学写报告的时候常常要画分离的流程图,以往大家都是拖啊拖啊的,看起来就恼火,于是就写了这样一个脚本(以后我也要画这种东西嘛),可以将简单的描述语言直接生成流程图,比如,如下的语言就可以生成如下的图:

a#草药样品
b#粗分浸膏
a#$甲醇提取=>b#
c1#正丁醇相
c2#石油醚相
c3#…
c4#水相
b#^$有机溶剂萃取
b#=>c1#
b#=>c2#
b#=>c3#
b#=>c4#
c2#^$继续柱层析分离
c2#=>d1#成分五
c2#=>d2#成分六

生成的流程图

该描述语言语法非常简单:
#前面是 node 的名字,$后面是描述,=> 将两个 node 连接起来,在其中画箭头,可以连续连接 比如 a# => b# => c# 也是可以的,node 后面 => 前面的 $xxx 是线上的注释,如果某一个点要往下分支的话只需用 node#^ 即可,node#^ 后面可以直接加注释,很简单的,看上面那个例子结合图片就可以搞明白了。

运行该脚本需要 python-yapgvb,此脚本受弯弯同学脚本的启发并参考了部分代码(http://python.ubuntu.org.cn/viewtopic.php?f=162&t=180285&sid=e2ae53902848adb1d59c375bf2325043

使用方法:

python liuchengtu.py -o xxx.png deffile

还有很多个性化选项,请参考源码。

源码如下:

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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
#!/usr/bin/env python
# -*- coding: utf-8 -*-
 
# Author: xioooli<at>yahoo.com.cn,joolix.com
# Licence GPLv2
# Version 2009.09.09
 
import sys
import yapgvb
import optparse
 
FORMATS = {"png" : yapgvb.formats.png,
        "jpg" : yapgvb.formats.jpg,
        "gif" : yapgvb.formats.gif}
ENGINES = {"dot" : yapgvb.engines.dot,
        "neato" : yapgvb.engines.neato,
        "circo" : yapgvb.engines.circo,
        "twopi" : yapgvb.engines.twopi}
 
if __name__ == '__main__':
#    args = sys.argv
#    if len(args) < 2:
#        print "Usage: python state_machine.py <def file>"
#        sys.exit(0)
 
    parser = optparse.OptionParser()
    parser.add_option("-f", "--format", dest="format",
            help="store the flow chart in FORMAT (png, svg, jpg, gif)",
            metavar="FORMAT", default="png")
    parser.add_option("-o", "--output", dest="output",
            help="save the flow chart to FILE",
            metavar="FILE")
    parser.add_option("-e", "--engine", dest="engine",
            help="the layout ENGINE to use for the flow chart (dot, neato, circo, twopi)",
            metavar="ENGINE", default="dot")
    parser.add_option("-c", "--color", dest="fillcolor",
            help="the fillcolor of the node",
            default="white")
    parser.add_option("--fs", "--font-size", dest="fontsize",
            help="the font size of the text",
            default="12")
    parser.add_option("--nfc", "--node-font-color", dest="nodefontcolor",
            help="the fillcolor of the font in node",
            default="black")
    parser.add_option("--nc", "--node-color", dest="nodecolor",
            help="the color of the node frame",
            default="black")
    parser.add_option("--ec", "--edge-color", dest="edgecolor",
            help="the color of the edge",
            default="black")
    parser.add_option("--efc", "--edge-font-color", dest="edgefontcolor",
            help="the font color of the edge text",
            default="black")
    parser.add_option("-s", "--style", dest="style",
            help="the style of the node",
            default="filled")
    parser.add_option("--ah", "--arrowhead", dest="arrowhead",
            help="the style of the arrowhead",
            default="normal")
    parser.add_option("--as", "--arrowsize", dest="arrowsize",
            help="the size of the arrow",
            default=1)
    parser.add_option("--ns", "--nodesep", dest="nodesep",
            help="the sepration between two nodes",
            default=.5)
    parser.add_option("--sp", "--shape", dest="shape",
            help="the shape of the node",
            default="box")
 
    options, args = parser.parse_args()
    if len(args) < 1:
        parser.print_usage()
        sys.exit(0)
 
    graph = yapgvb.Graph("States")
    graph.rankdir="TB"
    graph.nodesep=options.nodesep
    node_dict = {}
 
    with open(args[0]) as def_file:
        lines = [l.strip() for l in def_file.readlines()]
        for line in lines:
            nodes = line.split("=>")
            prev_node = None
            for node in nodes[::-1]:
                label = node.strip().split("#")
                if not node_dict.has_key(label[0]) and label[0] != "":
                    try:
                        lb=label[1].split("$")[0]
                    except:
                        lb=""
                    node_in_graph = graph.add_node(label=lb,
                            shape=options.shape, fillcolor=options.fillcolor,
                            fontcolor=options.nodefontcolor, fontsize=options.fontsize,
                            style=options.style, color=options.nodecolor, width=0.5)
                    node_dict[label[0]] = node_in_graph
                elif label[0] != "":
                    node_in_graph = node_dict[label[0]]
 
                try:
                       blanknode = node.strip().split("#^")
                       if len(blanknode) >= 2:
                           blanknode = blanknode[0]
                       else:
                           blanknode = ""
                except:
                       blanknode = ""
                if node_dict.has_key(blanknode) and blanknode != "":
                    node_dict[blanknode + "_0"] = node_dict[blanknode]
                    node_in_graph = graph.add_node(label="",     
                            shape="circle", fillcolor=options.edgecolor,
                            color=options.edgecolor, style="filled", height=.05, width=.05)
                    node_dict[blanknode] = node_in_graph
                    edge = node_dict[blanknode + "_0"] - node_dict[blanknode]
                    edge.color=options.edgecolor
                    try:
                        edge.label=" "+node.strip().split("$")[1]
                        edge.fontcolor=options.edgefontcolor
                        edge.fontsize=options.fontsize
                    except:
                        pass
 
                if prev_node:
                    edge = node_in_graph - prev_node
                    edge.color=options.edgecolor
                    edge.arrowhead = options.arrowhead
                    edge.arrowsize = options.arrowsize
                    try:
                        edge.label=" "+node.strip().split("$")[1]
                        edge.fontcolor=options.edgefontcolor
                        edge.fontsize=options.fontsize
                    except:
                        pass
 
                prev_node = node_in_graph
 
    graph.layout(ENGINES[options.engine])
    format = FORMATS[options.format]
    if options.output:
        out_file = options.output
    else:
        out_file = args[0] + "." + format
 
    graph.render(out_file, format)

Chemistry, Script , , ,

鼓捣 bash cgi

2009年9月1日
Comments Off

看了骨头的博文:Bash其实也可以做CGI用 也按捺不住,尝试了一把,呵呵,其他语言搞不定,bash 还是玩的转滴。

在自己电脑上面用 lighttpd 搭建了个 webserver,配置了一下,将 /etc/lighttpd.d/lighttpd.conf 里面 mod_cgi 前面的注释去掉,需要注意的是,如果你要使用 .sh 结尾的 cgi 脚本,那么需要将这行改成

static-file.exclude-extensions = ( ".php", ".pl", ".fcgi", ".sh" )

并在 cgi.assign 段添加一个

".sh" => "/bin/bash"

,写一个小脚本测试了一下:

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
#!/bin/bash
 
get_args() {
	local arg_txt arg
	arg_txt="$QUERY_STRING"
	for arg in `echo "$arg_txt"|tr "&" " "`; do
		arg="$(echo $arg|sed "s/%20/ /g"|ascii2uni -a J 2>/dev/null)"
		ARGS="${ARGS} $(echo $arg|sed "s/=.*$//")"
		export "$arg"
	done
}
 
echo "Content-type: text/html"
 
echo
 
echo "<HTML><HEAD>"
echo "<TITLE>Bash CGI writen by Xiooli?</TITLE>"
get_args
echo "</HEAD><BODY>"
 
echo "<B> This is XIOOLI's bash cgi </B>"
echo "<P>"
eval "$cmd"|sed "s/$/<P>/g"
for i in $ARGS; do
	echo "<P> $i=`eval echo \\$$i`"
done
echo "</BODY></HTML>"

来一个测试,url 如下: http://localhost/cgi-bin/tst.sh?hello=xiooli%E5%93%A5%E5%93%A5&kk=yy&bb=pp&cmd=who
得到结果:

This is XIOOLI’s bash cgi

xiooli :0 Aug 31 09:07

xiooli pts/0 Aug 31 09:07 (:0)

hello=xiooli哥哥

kk=yy

bb=pp

cmd=who

呵呵,好玩滴咯,以后写 cgi 就用 bash 鸟 ^^

Script ,

自动为 TEM 照片添加标尺

2009年7月7日
Comments Off

经常要做透射电镜,每次拿回结果的时候都要手工为其添加标尺(就是在图片的某一角落添加一条一定长度的直线,一般是一厘米,然后上面标注上此段长度的线条代表的实际长度,就和地图的比例尺一样),开始我使用gimp标注,一次两次倒还凑活,太多了就受不了了,于是乎决定写一个脚本来自动处理这种事(机械的活就该机器来干嘛,机器的活总是人来干的话,那咱智慧生物岂不白长了个脑袋不是?!)
挽上袖子开工,思路如下:

1) 根据放大倍数算出一定长度(这里是一厘米)代表的实际长度,以此来产生用于标注的文本。算法根据电镜老师的说明:请将图片在PHOTOSHOP中打开,将图片的尺寸改为8.1cmx5.4cm,此时,在10万倍的情况下,1cm代表100nm
2) 将原图缩小到一定尺寸(8.1cmx5.4cm)
3) 在原图上面右下角贴上文字(就是1中算出的实际尺寸)
4) 把一厘米的长度棒贴到文字下面(长度棒是事先画好的一条棒子),完工!

先是尝试了将图片缩小到8.1cmx5.4cm,结果发现图片很小,很奇怪,不过不论gimp/ps做出来的都是这个德性, 因此将图片缩小为8.1*3cmx5.4*3cm的大小,相应的长度棒也增大三倍,这下产生出来的图片就大而清晰了,呵呵 从此就不必再干这种体力活咯,来个图代表一下先:

发件人 xiooli

下面是代码(bar.tiff要自己画,长度是三厘米,这个是gimp上设的三厘米,切忌用尺子在屏幕上量出三厘米哦):

 1  #!/bin/bash
 2  #Author: xiooli <xioooli[at]yahoo.com.cn, http://joolix.com>

 3  #Licence: GPLv3
 4  #Version: 20090707
 5  #注:三个参数(第三个可选),分别是放大倍数(单位是万倍)、原文件和输出文件
 6
 7  Mag="$1"
 8  [ "$1" = "-h" ] && echo "$0 放大倍数(万倍) 原文件 输出文件(可选)" && exit

 9  Infile="$2"
10  Outfile="${3:-"fixed-`basename $2`"}"

11  #标尺图像文件的路径
12  Barpic=$HOME/.Share/bar.tiff
13  Text="`bc -l<<<"10/$Mag*100"`"

14  Text="${Text%.*} nm"
15  #文字位置
16  TextX=560

17  TextY=410
18  #文字与标尺的间距
19  Interval=9
20  Font=Times-New-Roman-Normal

21  FontSize=24
22  
23  [ ! "${#@}" -ge 2 ] && echo "参数个数不对。" && exit

24  
25  [ -f "$Infile" ] && \
26  convert -resize 689×460 "$Infile" "/dev/shm/resize-tmp.tiff"

27  
28  [ -f "/dev/shm/resize-tmp.tiff" ] && \
29  drawtext="convert -font \"$Font\" -fill black -pointsize $FontSize  -draw ‘text  ${TextX},${TextY} \"$Text\"\"/dev/shm/resize-tmp.tiff\"  \"/dev/shm/addtext-tmp.tiff\"" && eval $drawtext

30
31  [ -f "/dev/shm/addtext-tmp.tiff" -a -f "$Barpic" ] && \
32  composite -geometry "+${TextX}+$(($TextY+$Interval))" "$Barpic" \

33  "/dev/shm/addtext-tmp.tiff" "$Outfile"

Script , ,

Archlinux 下提示未安装命令

2009年7月7日

用ubuntu的时候,如果你在命令行里输入一个未安装的命令,bash会给出很人性化的提示,让你先安装xxx软件包,比如:

程序 ‘xxx’ 尚未安装。 您可以通过输入以下命令安装:
sudo apt-get install xxx

通过e-file,再经过一点设置,在gentoo里面也可以达到类似的效果(参考骨头的文章:gentoo也可以提示未安装的命令

这些都是通过重定义bash的command_not_found_handle函数来实现的,archlinux上也有一些方案,比如通过pacman -Si/pacman -Ss 来搜索的,前者只能找软件包而不能提示具体的命令,后者要通过网络实时查找。还有通过一个叫做pac-file(类似gentoo中的e-file)来找,这个命令可以从效果上完美实现这个功能,但是如果程序列表比较大或者机器慢的话,那么查找起来可能就是硬盘飞奔,CPU狂飙,而且过了一段时间后还得自己手动更新软件列表。这几种方案均不是很完美,于是俺只好自己动手,丰衣足食了,思路如下:

1) 在用pacman -Sy的时候自动更新pac-file的软件列表
2) 将所有的可执行命令项放到另一个文件里面,到时候去这里查找(因为pac-file的列表包含了软件包的所有文件项,故查找起来很慢,而我们要提示的是命令,也就是可执行文件,所以可以缩小搜索范围)

好,开工,代码如下,只需将其写到~/.bashrc里面再运行一下 . ~/.bashrc 就可以了:

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
#pacman 简写,pacman更新同时更新pac-file并产生只含有可执行文件项的软件包列表。
pm () {
 
	if [ "`which powerpill 2>/dev/null`" ]; then
		sudo powerpill $@
	else
		sudo pacman $@
	fi
 
	arg="`sed 's/ //g;s/-//g' <<< $@`"
	[ "$arg" -a "$arg" != "${arg//Sy}" ] && {
	sudo pac-file -S
	[ -d $HOME/.Share/ ] || mkdir -p $HOME/.Share/
	pac-file bin/[^\/]+$ > $HOME/.Share/cmd.list && echo "cmd.list 已更新!"
	}
}
 
#命令未找到时的处理,从cmd.list里面去查找软件包
command_not_found_handle() {
	echo "-bash: $1: 命令未找到"
	if [ "`grep bin/$1$ $HOME/.Share/cmd.list`" ]; then
		echo "下列软件包含有命令 $1 :"
		grep bin/$1$ $HOME/.Share/cmd.list
	else
		echo "未搜索到含有命令 $1 的软件包 :("
	fi
}

现在查找速度终于快了哈,而且pacman更新同时就更新了pac-file的列表,再不用担心软件包的版本过期了^^
看看效果吧:

发件人 xiooli

Script ,

天气墙纸脚本:wallther

2009年5月11日

RT
点击下载 wallther 脚本及 icon 素材
看LinuxToy时发现了一个天气墙纸的程序,貌似依赖不少的Gnome组件,很不方便,于是就萌生了用bash脚本写一个相同功能的脚本的想法,经过几个小时的奋战终于搞定了,呵呵,主要是convert等处理图片的软件用得不熟。
这个东东可以自动去获取天气信息(你甚至都不用管城市代码,当然可能有些地方会不准),然后根据获得的天气找到对应的图标,然后将图标和天气情况的文字(是否绘制文字信息可选)合成到背景图片中去,然后将这个合成的图片设置为壁纸。
初次使用需要配置一些东西,主要就是字体,因为我用的雅黑你可能没有。
这里有一张生成的图片大家可以感受一下:

发件人 xiooli

代码见下:

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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
#!/bin/bash
#Copyright (c) 2009 xiooli (xioooli[at]yahoo.com.cn, http://joolix.com)
#Name wallther
#License: GPLv3
#Version 20090511
 
#此脚本需要安装 w3m 和 imagemagick
#城市代码,留空可自动检测(自动检测不一定精确)
#城市代码可在 http://weather.265.com 上查询,是个5位的数字
#受bones7456和wenbob的天气脚本启发。
 
#这儿是城市代码,须自己改,未赋值会自动查询。
Wid=56294
#天气图标的位置
Icondir="`dirname $0`/icons"
#欲用作背景的图片
BackPic="$Icondir/background.jpg"
#最终输出的图片位置
OutPic="/dev/shm/wallpapertmp.png"
#壁纸路径(此为 OutPic 的副本)
Wallpaper="/dev/shm/wallpaper.png"
#是否在图片上绘制文字天气信息,yes/no
DrawText="yes"
#文字的字体,若不是中文字体则中文可能无法正常显示
Font="/usr/share/fonts/winfonts/msyh.ttf"
#文字的大小
FontSize=24
#文字的颜色
TxtColor="white"
#文字信息绘制的位置
TxtPosX=700
TxtPosY=350
#隔多大距离绘制下一行(此距离包括本行的宽度)
TxtYIncr=35
#天气图标绘制的位置
PicGeometry="+650+80"
#壁纸更换的时间间隔(默认 30 分钟)
ChangeTime="30m"
 
WeatherCN=("晴" "多云" "阴" "雨" "雷阵雨" "雾" "雪" "雨夹雪")
WeatherEN=("sun" "suncloud" "cloud" "rain" "storm" "fog" "snow" "snowrain")
 
GET_WEATHER() {
	[ -z "${Wid}" ] && \
	if [ -f "/dev/shm/city" ] ;then
		Wid="$(cat /dev/shm/city)"
	else
		Wid="`wget -q -O - 'http://www.265.com/lookupcity'|awk -F "'" '{print $2}'`"
		echo ${Wid}>/dev/shm/city
	fi
	[ ! -z "${Wid}" ] && WeatherTxt="`w3m -dump "http://wap.weather.com.cn/wap/${Wid}/h24/"`"
}
 
GEN_DRAW_TEXT() {
	[ -z "${WeatherTxt}" ] && GET_WEATHER
	if [ -z "${WeatherTxt}" ]; then
		echo "未能获取天气 :("
	else
		echo "${WeatherTxt}"|sed -n "4p"|sed 's/\ .*$//'
		echo "${WeatherTxt}"|sed -n "5,9p"
	fi \
	|sed "s/^.*$/-draw \\\'text POSITION \\\"&\\\"\\\'/" \
	|while read line; do 
		echo "$line"|sed "s/POSITION/$TxtPosX,$TxtPosY/"
		((TxtPosY+=$TxtYIncr))
	done|tr "\n" " "
}
 
GEN_WEATHER_ICON() {
	local tmp weathercn index 
	[ -z "${WeatherTxt}" ] && GET_WEATHER
	[ -z "${WeatherTxt}" ] || tmp="`echo "${WeatherTxt}"|sed -n "5p"`"
	j=0; k=0
	for i in ${WeatherCN[@]}; do
		[ "${tmp//$i}" != "$tmp" ] && weathercn[$j]="$i" && index[$j]="$k" && ((j++))
		((k++))
	done
	[ "${#weathercn[@]}" -eq 0 ] && Weather[0]="unknown"
	[ "${#weathercn[@]}" -eq 1 ] && Weather[0]="${WeatherEN[${index[0]}]}"
	[ "${#weathercn[@]}" -eq 2 ] && \
	if [ "`echo $tmp|grep "${weathercn[0]}转"`" ];then
		Weather[0]="${WeatherEN[${index[0]}]}"
		Weather[1]="${WeatherEN[${index[1]}]}"
	else
		Weather[0]="${WeatherEN[${index[1]}]}"
		Weather[1]="${WeatherEN[${index[0]}]}"
	fi
	[ "${#weathercn[@]}" -eq 3 ] && \
	{
		Weather[0]="${WeatherEN[${index[0]}]}"
		Weather[1]="${WeatherEN[${index[2]}]}"
	}
	if [ "${#Weather[@]}" -ge 2 ]; then
	   convert +append "$Icondir/${Weather[0]}.png" "$Icondir/${Weather[1]}.png" /dev/shm/weathericon.png
	else
	   ln -sf "$Icondir/${Weather[0]}.png" /dev/shm/weathericon.png
	fi
}
 
GEN_WALLPAPWE() {
	GEN_WEATHER_ICON
	[ -f $BackPic ] || BackPic="$Icondir/background.jpg"
	if [ "$DrawText" = "yes" ]; then
		draw="convert -font \"$Font\" -fill $TxtColor -pointsize $FontSize `GEN_DRAW_TEXT` \"$BackPic\" \"/dev/shm/backpictmp.png\""
		eval "$draw"
		composite -geometry "$PicGeometry" /dev/shm/weathericon.png /dev/shm/backpictmp.png "$OutPic"
	else
		composite -geometry "$PicGeometry" /dev/shm/weathericon.png "$BackPic" "$OutPic"	
	fi
}
 
while :; do
	GET_WEATHER
	[ "${WeatherTxt}" != "$tmp" ] && GEN_WALLPAPWE && tmp="${WeatherTxt}"
	if [ -f "$OutPic" ];then
		mv "$OutPic" "$Wallpaper"
		gconftool-2 -s /desktop/gnome/background/picture_filename --type=string "$Wallpaper"
	fi
	sleep "$ChangeTime"
done

Script , ,