desmume: Mac OS上的DS模拟器

链接在此

拿最新的逆转检视公测版试了一下,效果非常不错:

Screen shot 2009-12-07 at 10.37.52 PM.png
Posted in mac | Tagged , , | 1 Comment

用Python修改Mac OS X的地址簿

什么时候我们会需要 Programmatically 地修改地址簿呢?

一个比较典型的用途是jjgod的apn, 可以利用 Scripting Bridge 给地址簿的中文联系人都设置上相应的拼音。

当然你如果像我一样当初在导入地址簿的时候将大家的学号都导入到地址簿邮件一栏的话,给地址簿当中所有work mail为063020开头的项都加上个@fudan.edu.cn就是非常必要的

本文只是提供一个更为详细的操作AddressBook的例子,通过这个例子,想必大家可以很明显地注意到其实Scripting Bridge做的就是用Python调用一个个原生的Objective C API, 虽然大家不会想到会在Python中写 ABMutableMultiValue.alloc().init() 这样的代码,但这其实就是在调用Objective中的 [[ABMutableMultiValue alloc] init]。

最后,还是要提醒大家,不要去运行这个脚本, 这只是作为一个操作 Multivalue 属性的一个范例。当然为了安全起见,我把最后写入数据的 ab.save() 给注释了。

[code=py]
#!/usr/bin/python2.5
from AddressBook import *
ab = ABAddressBook.sharedAddressBook()
def hack_email_field(): """modify some fields in the addressbook""" people = ab.people() for person in people: emails = person.valueForProperty_(kABEmailProperty) emails_mod = ABMutableMultiValue.alloc().init() if not type(emails) == ABMultiValueCoreDataWrapper: continue for val in range(emails.count()): if emails.labelAtIndex_(val) == kABEmailWorkLabel: if emails.valueAtIndex_(val).find('0630') >= 0 and emails.valueAtIndex_(val).find('fudan.edu.cn') < 0: foo = emails.valueAtIndex_(val) + '@fudan.edu.cn' emails_mod.addValue_withLabel_(foo,kABEmailWorkLabel) elif emails.valueAtIndex_(val).find('edu') > 0 and emails.valueAtIndex_(val).find('com') > 0: emails_mod.addValue_withLabel_(emails.valueAtIndex_(val),emails.labelAtIndex_(val)) person.setValue_forProperty_(emails_mod,kABEmailProperty)
# really careful when you do a save operation. # ab.save()
def main(): """main method""" hack_email_field()
if __name__ == '__main__': main() [/code]
Posted in mac, python | Tagged , , | Leave a comment

最近搭的两个AppEngine上的东西

一个是JTweet, 我觉着想给它加上OAuth的支持,将用户的头像图片也改为从AppEngine的在线代理取了, http://javabirdy.appspot.com/, 以后在教育网就一直用这个看推了。

还有一个是mirrorrr, http://particleparty.appspot.com/,用来fetch一些教育网范围外的东西不错,我得把它的url改为encode过的才能作为一个合格的在线代理

Posted in google, java, python | Tagged , , , | Leave a comment

要小要轻量,打造小巧可定制的 ftp server

pyftpdlib是目前实现ftp协议最完善的Python lib, 使用它能用很短的代码行数打造一个极富定制化的ftpserver。

下面是一个用pyftpdlib实现的用作校内23用途的例子,该库提供的high level interface很适合定制,作为一个大程序的组件也非常堪用。

[code=py]
#
#  ftp23.py
#  «ftp server»
#
#  Created by Malic on 2009-11-25.
#  Copyright 2009 overboming. All rights reserved.
# 
from pyftpdlib import ftpserver
def main(): """run server""" authorizer = ftpserver.DummyAuthorizer() authorizer.add_user('upload','upload','.',perm='elradfmw') ftp_handler = ftpserver.FTPHandler ftp_handler.authorizer = authorizer address = ('10.147.139.20',21) ftpd = ftpserver.FTPServer(address,ftp_handler) ftpd.serve_forever()
if __name__ == "__main__": main() [/code]
Posted in programming, python | Tagged , | Leave a comment

如何获得代码当前运行到的行数?

C语言版本

[code=c]
//
//  lineno.c
//  «project»
//
//  Created by Malic on 2009-11-24.
//  Copyright 2009 overboming. All rights reserved.
//
#include "stdio.h"
int main (int argc, char const *argv[]) { //I want to print out the current line number of the source code printf("Source Line No. %d\n", __LINE__); printf("Current Function Name. %s\n", __FUNCTION__); printf("File Name. %s\n", __FILE__); return 0; }
[/code]

输出为:

[code=c]
Source Line No. 14
Current Function Name. main
File Name. /Users/Malic/Documents/Code/C++/lineno.c
[/code]

同样的功能在Java中用StackTrace实现

[code=java]
/** Get the current line number.
 * @return int - Current line number.
 */
public static int getLineNumber() {
    return Thread.currentThread().getStackTrace()[2].getLineNumber();
}
[/code]
Posted in programming | Tagged , | Leave a comment

现在做软件起名字真难

Second Bar 东西还是不错的,多显示器的用户现在可以有多个menu bar了。

Screen shot 2009-11-23 at 3.07.03 PM.png
Posted in mac | Tagged , | Leave a comment

User-Agent for GAE(Java) urlfetch service

No matter how hard you try, you will never get your app engine url fetch service to have the right user-agent value
Following method won't work
[code=java]
                URLFetchService serv = URLFetchServiceFactory.getURLFetchService();             HTTPRequest req = null;
                try {
                        req = new HTTPRequest(new URL(location));
                        req.setHeader(new HTTPHeader("User-Agent","Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.6; en-US; rv:1.9.1.3) Gecko/20090824 Firefox/3.5.3"));
                        for(HTTPHeader header : req.getHeaders()){
                                _log.warning(header.getName());
                                _log.warning(header.getValue());
                        }
                } catch (MalformedURLException e1) {
                        e1.printStackTrace();
                }
[/code]
This doesn't work either
[code=java]
                        URL url = new URL(location);
                        HttpURLConnection connection = (HttpURLConnection) url
                                        .openConnection();
                        connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.6; en-US; rv:1.9.1.3) Gecko/20090824 Firefox/3.5.3");
                        connection.setRequestMethod("GET");
[/code]

No matter how hard you try, you will get
User-Agent: AppEngine-Google; (+http://code.google.com/appengine; appid: overboming-hello)
for the user-agent header put by the urlfetch service
Notice overboming-hello, is your app's id.
btw, according to this resolved issue, the user-agent problem is fixed for Python, but not Java. I have fired this issue here, star this issue to push Google to fix this ASAP.

Posted in google, java | Tagged , , | Leave a comment

解决Torchlight的"Prior installation detected"问题

为了比较一下cider和vmware fusion运行DirectX游戏的性能差异,我选择了Torchlight这款最近比较流行的title。
在虚拟机种尝试安装的时候,因为第一次安装失败,而接着再次运行安装程序会报一个"Prior installation detected, please uninstall it then try again"的错误,在任务管理器中卸载之前的安装包以后任务依旧。解决办法是运行regedit, 删除HKEY_LOCAL_MACHINE/SOFTWARE/RUNIC相关的所有键值。

Posted in mac, windows | Tagged , , , | Leave a comment

下载在线视频网站的flv文件的Python脚本

使用前提: 安装了Python, wget(作为下载工具 ;)
注意: 分析视频文件真实地址使用了 http://www.flvcd.com/的服务
像youku这样对视频文件分块的下载下载的将会是若干个段落,如果你的视频播放器支持只能根据文件名播放下一个文件的话这将不会影响观感。

下载最新的一级One Piece的效果如下
-rw-r--r-- 1 Malic staff 12M Nov 8 13:06 海贼王425_1.flv
-rw-r--r-- 1 Malic staff 12M Nov 8 13:06 海贼王425_2.flv
-rw-r--r-- 1 Malic staff 13M Nov 8 13:06 海贼王425_3.flv
-rw-r--r-- 1 Malic staff 4.8M Nov 8 13:06 海贼王425_4.flv

Screen shot 2009-11-09 at 12.07.18 AM.png

代码

[code=python]
# -*- coding: utf-8 -*-
import urllib,urllib2
import sys
import re
from subprocess import Popen
address = 'http://www.flvcd.com/parse.php?' agent = 'Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.6; en-US; rv:1.9.1.3) Gecko/20090824 Firefox/3.5.3'
def fetchLink(url): """fetch link for the input parameters""" para = {'flag' : '', 'format' : '', 'kw' : url} req = address + urllib.urlencode(para) opener = urllib2.build_opener() opener.addheaders = [('User-agent', agent)] data = opener.open(req).read().decode('gb2312') # print re.findall("if\(copyToClipboard\('(http.*)'\)\)\{alert",data) links = re.findall("(http.*)\s*<[A-Z]>",data) info = re.findall(".{5,20}(.*?)",data)[0] for (index,link) in enumerate(links): print link Popen(['wget','-c', link, '-U', agent, '-O', info + '_' + str(index+1) + '.flv']).wait()


def main(): """main method""" # tudou.com # fetchLink("http://www.tudou.com/programs/view/xHeuSl-QKAI/tid=-1&aid=4573&pid=41010010&oid=100957&isNielson=0") # youku.com # fetchLink("http://v.youku.com/v_show/id_XNTI5MzU1NTY=.html") if len(sys.argv) >= 1: fetchLink(sys.argv[1])


if __name__ == "__main__": main()


[/code]

到学校以后发现因为那个嗅探真实地址的服务在教育网免费范围之外,所以这个脚本暂时还不能满足我的需求。
等忙完这阵子以后,我会将探测真实地址的服务做到gtalkbotplus中, 并提供一个简单的接口,这样教育网就能用了 :) 当然,对于tudou的服务,你可能得在下载的时候提供一个和App Engine一样的User Agent, 否则会被认为是盗链。

Posted in python | Tagged , , , , , | Leave a comment

From Python to Perl (4)

Notes for Learning Perl Chapter 11 to Chapter 13

  • 文件检测操作
[code=c]
die “Oops! A file called ‘$filename’already exists.\n”
if –e $filename;  #是否存在
warn “Config file is looking pretty old!\n” if –M CONFIG > 28;  #检查是否很久没有被修改过了
[/code]
表 11-1 文件检测选项及其含义
检测选项        含义
-r      文件或目录对此(有效的 ;) 用户(effective user)或组是可读的
-w      文件或目录对此(有效的 ;) 用户或组是可写的
-x      文件或目录对此(有效的 ;) 用户或组是可执行的
-o      文件或目录由本(有效的 ;) 用户所有
-R      文件或目录对此用户(real user)或组是可读的
-W      文件或目录对此用户或组是可写的
-X      文件或目录对此用户或组是可执行的
-O      文件或目录由本用户所有
-e      文件或目录名存在
-z      文件存在,大小为 0(目录恒为 false)
-s      文件或目录存在,大小大于 0(值为文件的大小,单位:字节 ;)
-f      为普通文本
-d      为目录
-l      为符号链接
-S      为 socket
-p      为管道(Entry is a named pipe(a “fifo&rdquo ;) )
-b      为 block-special 文件(如挂载磁盘 ;)
-c      为 character-special 文件(如 I/O 设备 ;)
-u      setuid 的文件或目录
-g      setgid 的文件或目录
-k      File or directory has the sticky bit set
-t      文件句柄为 TTY(系统函数 isatty()的返回结果;不能对文件名使用这个测试 ;)
-T      文件有些像“文本”文件
-B      文件有些像“二进制”文件
-M      修改的时间(单位:天 ;)
-A      访问的时间(单位:天 ;)
-C      索引节点修改时间(单位:天 ;)
  • 一个使用 -s 的例子
[code=c]
my $size_in_k = (-s) / 1024;    #文件名在默认的$_中
[/code]
[code=c]
#获得本地时间
my $local = localtime;
my $global = gmtime;
[/code]
[code=c]
my @original_files = qw/ fred barney betty Wilma pebbles dino bam-bamm/;
my @big_old_files;
#需要移到备份磁带上去的文件
foreach(@orginal_files){
        push @big_old_files, $_ if (-s) > 100_100 and –A _ > 90;  #这里的  _ 重复利用了刚才-s了$_的结果, 节约了一次系统调用的开销
}
[/code]
  • glob, chdir
[code=c]
chdir “/etc”or die “cannot chdir to /etc: $!”;
my @all_files = glob “*”;
my @pm_files = glob “*.pm”;
my @all_files = <*>;    ## 基本上同@all_files = glob “*”一样;
my $dir = “/etc”;
my @dir_files = <$dir/* $dir/.*>;
[/code]
  • 删除文件采用unlink
[code=c]
#一次性删除多个文件
unlink glob "*.o";
unlink $file or warn "fail on $file\n";
[/code]
  • 重命名文件用rename
  • 创建和删除目录mkdir
  • 修改权限chmod
  • 修改所有者chown
  • 修改时间戳utime
  • 寻找字串位置
[code=c]
$where = index($big, $small);
my $where2 = index($stuff, “w”, $where+1);
##同样的 还有rindex
[/code]
  • 获得子串
[code=c]
$part = substr($string, $initial_position, $length);
#如此实在太imba了啊啊啊 my $string = “Hello, world!”; substr($string, 0, 5) = “Goodbye”; # $string 现在变成了 “Goodbye, world!” substr($string, -20) =~ s/fred/barney/g; #传统式 my $previous_value = substr($string, 0, 5, “Goodbye&rdquo ;) ; [/code]
[code=c]
sub big_money {
        my $number = sprintf “%.2f”, shift @_;
        1 while $number =~ s/^(-?\d+) (\d\d\d)/$1,$2/;
        $number =~ s/^(-?)/$1\$/;
        $number;
}
[/code]
  • 自定义排序
[code=c]
sub by_number {
        if($a < $b){-1} elsif($a > $b){1} else {0}
}
#can also be written as
sub by_number {$a <=> $b }
sub case_insenstive {“\L$a”cmp “\L$b”}
my @numbers = sort { $a <=> $b } @some_numbers; my @result = sort by_number @some_numbers;
#sort by value my %score = (“barney”=>, “fred”=>205, “dino”=> 30); my @winners = sort by_score keys %score; sub by_socre { $score{$b} <=> $score{$a}}
my @winners = sort by_score_and_name keys %score; sub by_score_and_name { $score{$b} <=> $score{$a} or $a cmp $b; } [/code]
Posted in programming, python | Tagged , , | Leave a comment