2012年7月

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
# 介个编译时间有点长,得慢慢等...