小子 发布的文章

Supervisor安装及配置

Supervisor安装

# 安装
easy_install supervisor
# 生成默认配置文件
echo_supervisord_conf > /etc/supervisord.conf
mkdir /etc/supervisord.conf.d

修改配置文件

include区段修改为

[include]
files = /etc/supervisord.conf.d/*.conf

如需要访问web控制界面,inet_http_server区段修改为

[inet_http_server]
port=0.0.0.0:9001
username=username ; 你的用户名
password=password ; 你的密码

每个需要管理的进程分别写在一个文件里面,放在/etc/supervisord.conf.d/目录下,便于管理。例如:test.conf

[program:sqlparse]
directory = /var/www/python
command = /bin/env python test.py

将supervisord加入系统服务,以下代码来自gist,文件:/etc/init.d/supervisord

#!/bin/sh
#
# /etc/rc.d/init.d/supervisord
#
# Supervisor is a client/server system that
# allows its users to monitor and control a
# number of processes on UNIX-like operating
# systems.
#
# chkconfig: - 64 36
# description: Supervisor Server
# processname: supervisord

# Source init functions
. /etc/init.d/functions

RETVAL=0
prog="supervisord"
pidfile="/tmp/supervisord.pid"
lockfile="/var/lock/subsys/supervisord"

start()
{
        echo -n $"Starting $prog: "
        daemon --pidfile $pidfile supervisord -c /etc/supervisord.conf
        RETVAL=$?
        echo
        [ $RETVAL -eq 0 ] && touch ${lockfile}
}

stop()
{
        echo -n $"Shutting down $prog: "
        killproc -p ${pidfile} /usr/bin/supervisord
        RETVAL=$?
        echo
        if [ $RETVAL -eq 0 ] ; then
                rm -f ${lockfile} ${pidfile}
        fi
}

case "$1" in

  start)
    start
  ;;

  stop)
    stop
  ;;

  status)
        status $prog
  ;;

  restart)
    stop
    start
  ;;

  *)
    echo "Usage: $0 {start|stop|restart|status}"
  ;;

esac
chmod +x /etc/init.d/supervisord
chkconfig supervisord on
service supervisord start

oracle UTL_FILE包操作文件

利用UTL_FILE导出数据

-- 定义fhandle文件句柄
fhandle utl_file.file_type;
-- 打开文件
fhandle := utl_file.fopen(location => './', filename => 'export_' || to_char(sysdate, 'yyMMddHH24mi') || '.txt', open_mode => 'w', max_linesize => 32767);
-- 写入一行数据
utl_file.put_line(file => fhandle, buffer => 'test str');
-- 关闭句柄
utl_file.fclose(file => fhandle);

python中的那些else

python与其他语言不同的是,else不仅可以和if搭配,它还可以跟其他的逻辑语句一起使用;if/else这里就不在记录。

while/else for/else

# 只有当循环正常执行完的时候,才会执行else中的语句,如果循环语句被break的时候,将不会执行else中的语句
for i in range(1, 11):
	if i == 8:
		break
	print(i, end = ',')
else:
	print(11)
# 1,2,3,4,5,6,7,

for i in range(1, 11):
	print(i, end = ',')
else:
	print(11)
# 1,2,3,4,5,6,7,8,9,10,11

try/except/else/finally

try:
	raise(RuntimeError, 'force issue')
except:
	# 抛出错误时执行
	print(1)
else:
	# 在不抛出错误的情况下执行
	print(2)
finally:
	# 不管有没有抛出错误都执行
	print(3)

java调用Jalopy

关于jalopy的资料,我在他的官网上也没发现多少,于是自己看着他的那个主文件,写了个简单的调用出来。

import de.hunsicker.jalopy.Jalopy;

public class Call {
	public static String format(String code) {
		Jalopy codeFormatter = new Jalopy();
		String path = "input.java";
		StringBuffer output = new StringBuffer();
		codeFormatter.setInput(code, path);
		codeFormatter.setOutput(output);
		codeFormatter.format();

		return output.toString();
	}
	public static void main(String[] args) {
		System.out.println(format("public class Test {\n"
+ "			public static void main() {\n"
+ "\n"
+ "			}\n"
+ "		}"));
	}
}

thrift的php TCompactProtocol库bug

bug描述:读取的boolean类型的值始终为false,这纠结了我半天,本来还以为是因为自己不会java,服务器端的java代码写错,于是经过严密的审查,觉得应该是php端出了问题。

# 找到333行,修改为:
$field_type &= 0x0f;
# 找到343行,在上面添加一行:
$field_type = $this->getTType($field_type);
# 搞定

编译thrift的php扩展

php的版本5.4.2

cd /usr/local/src/thrift-0.8.0/lib/php/src/ext/thrift_protocol/
phpize
./configure
make && make install

在php5.4下面上面的编译会出错,直接修改php_thrift_protocol.cpp文件的95行,将function_entry替换为zend_function_entry,然后重新编译就好了。

* warning 就先不考虑了。

以库的形式调用closure compiler

本来是用命令行的方式调用google closure compiler,可是效率不如人意;于是网上查找了些资料,实践了一下。

import com.google.javascript.jscomp.CompilationLevel;
import com.google.javascript.jscomp.Compiler;
import com.google.javascript.jscomp.CompilerOptions;
import com.google.javascript.jscomp.JSSourceFile;

public class CallCompile {
	public static String compile(String code) {
		Compiler compiler = new Compiler();
		CompilerOptions options = new CompilerOptions();
		CompilationLevel.ADVANCED_OPTIMIZATIONS.setOptionsForCompilationLevel(options);

		JSSourceFile external = JSSourceFile.fromCode("external.js", "");
		JSSourceFile primary = JSSourceFile.fromCode("primary.js", code);

		compiler.compile(external, primary, options);

		return compiler.toSource();
	}

	public static void main(String[] args) {
		System.out.println(compile("console.log('hello world.')"));
	}
}

编译执行命令


# Windows下
javac -cp ".;./compiler.jar" CallCompile.java
java -cp ".;./compiler.jar" CallCompile

# Linux下
javac -cp ".:./compiler.jar" CallCompile.java
java -cp ".:./compiler.jar" CallCompile

2014-04-07 20:18 更新

最新的closure compiler有所更新,示例代码修改成如下:

import com.google.javascript.jscomp.Compiler;
import com.google.javascript.jscomp.CompilerOptions;
import com.google.javascript.jscomp.CompilationLevel;
import com.google.javascript.jscomp.SourceFile;

// import java.util.logging.Level;

public class Test {

	public static void main(String[] args) {
		// Compiler.setLoggingLevel(Level.OFF);
		Compiler compiler = new Compiler();
		CompilerOptions options = new CompilerOptions();
		CompilationLevel.ADVANCED_OPTIMIZATIONS.setOptionsForCompilationLevel(options);
		SourceFile extern = SourceFile.fromCode("extern", "");
		SourceFile primary = SourceFile.fromCode("primary", "(function(){console.log('test')})();");
		compiler.compile(extern, primary, options);
		System.out.println(compiler.toSource());
		System.exit(0);
	}
}

C++ split的实现

#include 
#include 
#include 
#include 
#include 

using namespace std;

vector &split(const string &s, char delim, vector &elems) {
    istringstream iss(s);
    string item;
    while(getline(iss, item, delim)) {
        elems.push_back(item);
    }
    return elems;
}


vector split(const string &s, char delim) {
    vector elems;
    split(s, delim, elems);
    return elems;
}

int main() {
	vector elems = split("Hello, world!", ',');
	for(vector::iterator it = elems.begin(); it < elems.end(); it++) {
		cout << *it << endl;
	}
	return 0;
}

python杂记2

判断是否为数字

isdigit()的话,里面不能有小数点。

def is_number(s):
    try:
        n=str(float(s))
        if n == "nan" or n=="inf" or n=="-inf" : return False
    except ValueError:
        return False
    return True

切分list

def chunks(l, n):
    return [l[i: i + n] for i in range(0, len(l), n)]

字符串数字取整

直接用int会报错。

str = "545.2222"
print(int(float(str)))

合并字典

x = {'a':1, 'b': 2}
y = {'b':10, 'c': 11}

# python2.x
z = dict(x.items() + y.items())
# python3.x
z = dict(list(x.items()) + list(y.items()))

# another way
z = dict(x, **y)

os.path.join的坑

如果路径中有绝对路径,则前面的所有路径都会被抛弃

Yii语言包词条提取

据说是哥半年前写的一个用户管理程序,而现在老大要求程序能切换语言;将原来的词条用英文添进去之后,发现写语言包的时候一个一个提取比较麻烦,所以就写了个程序提取。(目前还只能提取Yii::t里面只有两个参数的情况)

<?php

$fileinfo = new FilesystemIterator('group'); // 目录

$words = array();
while($fileinfo->valid()) {
    
    if($fileinfo->getExtension() === 'php') {
        $filename = $fileinfo->getFilename();
        $fileobject = $fileinfo->openFile();

        while($fileobject->valid()) {
            if(preg_match_all('/Yii::t\(([\'"])([^\'"]*?)\\1\s*,\s*([\'"])(.*?)\\3\)/', $fileobject->current(), $matches)) {
                foreach($matches[4] as $match) {
                    $words[$match] = isset($words[$match]) ? $words[$match] . '; ' . $filename . ' # ' . $fileobject->key() : '// ' . $filename . ' # ' . $fileobject->key();
                }
            }
            $fileobject->next();
        }
    }

    $fileinfo->next();
}


function save_to_file($content = '') {
    $fileobject = new SplFileObject('user.trans.php', 'w');
    $fileobject->fwrite($content);
}

ob_start('save_to_file');

echo '<?php
/**
 * @author XiaoZi<245565986@qq.com>
 */
return array(
';

foreach($words as $word => $comment) {
    echo "\t" . $comment . PHP_EOL;
    echo "\t" . '\'' . $word . '\' => \'\',' . PHP_EOL;
}

echo ');
';

ob_end_clean();

InnoSetup杂记

那些个控件名

// 输出所有控件名
procedure InitializeWizard;
var
	i: integer;
	te: TMemo;
begin
	te := TMemo.Create(WizardForm);
	te.Parent := WizardForm.WelcomeLabel2;

	with WizardForm do
	begin
		for i:= ComponentCount - 1 downto 0 do
		begin
			if Components[i].Name <> '' then
			begin
				te.Text := te.Text + Components[i].Name + #13 + #10;
			end;
		end;
	end;
end;
BeveledLabel
FinishedHeadingLabel
FinishedLabel
YesRadio
NoRadio
RunList
WizardBitmapImage2
FinishedPage
PageNameLabel
PageDescriptionLabel
WizardSmallBitmapImage
MainPanel
InfoAfterClickLabel
InfoAfterMemo
InfoAfterPage
ProgressGauge
StatusLabel
FilenameLabel
InstallingPage
PreparingNoRadio
PreparingYesRadio
PreparingLabel
PreparingErrorBitmapImage
PreparingPage
ReadyLabel
ReadyMemo
ReadyPage
SelectTasksLabel
TasksList
SelectTasksPage
SelectStartMenuFolderLabel
SelectStartMenuFolderBrowseLabel
GroupEdit
GroupBrowseButton
NoIconsCheck
SelectGroupBitmapImage
SelectProgramGroupPage
SelectComponentsLabel
TypesCombo
ComponentsList
ComponentsDiskSpaceLabel
SelectComponentsPage
SelectDirLabel
SelectDirBrowseLabel
DirEdit
DirBrowseButton
DiskSpaceLabel
SelectDirBitmapImage
SelectDirPage
UserInfoNameLabel
UserInfoNameEdit
UserInfoOrgLabel
UserInfoOrgEdit
UserInfoSerialLabel
UserInfoSerialEdit
UserInfoPage
InfoBeforeClickLabel
InfoBeforeMemo
InfoBeforePage
PasswordLabel
PasswordEditLabel
PasswordEdit
PasswordPage
LicenseLabel1
LicenseMemo
LicenseAcceptedRadio
LicenseNotAcceptedRadio
LicensePage
InnerNotebook
Bevel1
InnerPage
WelcomeLabel1
WelcomeLabel2
WizardBitmapImage
WelcomePage
OuterNotebook
BackButton
NextButton
CancelButton
Bevel

注册表

开机启动
HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Run
文件右键使用my software打开
HKEY_CLASSES_ROOT\*\Shell\Open with My Software\command

例子来自Sublime Text 2的安装包

[Registry]
Root: HKCR; Subkey: "*\Shell\Open with Sublime Text 2\command"; ValueType: String; ValueData: "{app}\sublime_text.exe ""%1"""; Tasks: "contextentry"; MinVersion: 0.0,5.0; Flags: uninsdeletekey 
Root: HKCR; Subkey: "*\Shell\Open with Sublime Text 2"; Tasks: "contextentry"; MinVersion: 0.0,5.0; Flags: uninsdeletekey dontcreatekey
[Tasks]
Name: "contextentry"; Description: "Add to explorer context menu"; MinVersion: 0.0,5.0; 

编译安装gcc-4.7.1

cd /usr/local/src/
wget http://ftp.gnu.org/gnu/gcc/gcc-4.7.1/gcc-4.7.1.tar.gz
tar zxf gcc-4.7.1.tar.gz
cd gcc-4.7.1
./contrib/download_prerequisites
./configure --prefix=/usr/local/gcc
make && make install
# 介个编译时间有点长,得慢慢等...

C++读取配置文件

配置文件格式

 # nimei
host = 127.0.0.1
 port = 80

	key
	=123
mask = 255.255.255.0
# comment

C++代码

/**
 * @author xiaozi<245565986@qq.com>
 */
#include 
#include 
#include 
#include 

using namespace std;

string trim(const string& str);

int main(int agrc, char* argv[]) {
	const char* filename = "parse.conf";
	ifstream ifs(filename);

	string line = "";
	string key = "";
	string value = "";
	string::size_type pos = string::npos;

	map options;

	while(! ifs.eof()) {
		getline(ifs, line);

		line = trim(line);
		// 空行 和 注释行 和 不存在等号的行,跳过
		if(line.empty() || line.at(0) == '#') {
			continue;
		}

		if((pos = line.find('=')) == string::npos) {
			// cout << "语法错误" << endl;
			continue;
		}

		key = trim(line.substr(0, pos));
		value = trim(line.substr(pos + 1, line.size() - pos - 1));

		// key不为空的时候,留下该行数据
		if(! key.empty()) {
			options[key] = value;
		}
	}

	ifs.close();

	// 输出得到的数据
	map::iterator it;
	for(it = options.begin(); it != options.end(); it++) {
		cout << (*it).first << " => " << (*it).second << endl;
	}

	return 0;
}

string trim(const string& str) {
	if(str.empty()) {
		return str;
	}
	string::size_type pos = str.find_first_not_of(" \t\n\r\0\x0B");
	if(pos == string::npos) {
		return str;
	}
	string::size_type pos2 = str.find_last_not_of(" \t\n\r\0\x0B");
	return str.substr(pos, pos2 - pos + 1);
}

Centos硬盘读写速度测试

老看到網上有在前面加time的,而且還用兩個數字除一下,於是我就覺得蛋疼,你說明明顯示出了結果,爲什麼還要自己再算一邊呢?後來才知道是linux4下是不會有速度結果出來的,於是你知道的,”轉載就轉載了,尼瑪動過腦子沒?還把有結果的貼在文章裏面,自己甩自己嘴巴啊。“

PS:最近喜歡上繁體字了,木有辦法啊!

# 測試寫文件的速度:
sync;dd if=/dev/zero of=/tmp/1GB.file bs=1024 count=1000000
# 測試讀文件的速度:
sync;dd if=/tmp/1GB.file of=/dev/null bs=1024 count=1000000


# 測試10次寫文件的速度(有無執行sync的區別比較大):
for i in {1..10}
do
sync
dd if=/dev/zero of=/tmp/1GB.file bs=1024 count=1000000
done

# 測試10次讀文件的速度(有無執行sync沒多大的區別):
for i in {1..10}
do
sync
dd if=/tmp/1GB.file of=/dev/null bs=1024 count=1000000
done


# 由於dd命令結果是顯示在錯誤輸出的上的,若需要進一步處理數據,則需要將結果重定向:
sync;dd if=/dev/zero of=/tmp/1GB.file bs=1024 count=1000000 2>&1 | grep "copied"
sync;dd if=/tmp/1GB.file of=/dev/null bs=1024 count=1000000 2>&1 | grep "copied"