golden armor

欲变世界,先变其身

Subscribe to RSS feed

2010/11/28 TOEIC Exam

taken at Waseda Technology Department Campus.
About 4000 people.
90% are Japanese.
short summary for exam : a little nervous, not my best shoot

Using Response.Redirect and Response.End in Try...Catch block

from http://wiki.asp.net/page.aspx/721/using-responseredirect-and-responseend-in-trycatch-block/

In ASP.NET if you are using Response.End - Used for terminating page execution or Response.Redirect - used for redirecting page to some other page, and you are including these statements in TRY... CATCH block here is what you need to remember.

Problem:

When Response.Redirect or Response.End is written in TRY block, code in catch block is executed.

Reason:

ASP.NET executes these 2 methods on Response object by throwing ThreadAbort Exception. When written in simple Try...Catch block this results in Catch block catching this exception and processing code written in catch block. This causes unwanted code execution e.g. error logging or genric error display code which is generally written in Catch block.

Solution:

You need to handle ThreadAbort exception separately and do nothing if it is thrown. Refer following code patch:

try
{
// Your actual code
Response.End();
}
catch (ThreadAbortException exc)
{
// This should be first catch block i.e. before generic Exception
// This Catch block is to absorb exception thrown by Response.End
}
catch (Exception exc)
{
// Write actual error handling code here
}

来东京这么久,第一次有机会去迪斯尼玩

留贴纪念,放假的第一天,人居多,早就听说人多得不得了,
这次算见到真架势啦

编程之美中1的数目-我的解法

题目:
给定一个十进制正整数 N,写下从1 开始,到 N的所有整数,然后数一下其中出现的所有“1”的个数。
例如:
N= 2,写下1,2。这样只出现了 1 个“1”。
N= 12,我们会写下1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12。这样,1
的个数是5。
问题是:
写一个函数f (N) , 返回1到N之间出现的“1”的个数,比如f (12)
=5。

书里面用数学归纳法列出公式,进行计算。
我没想那么多,直接用递归解决,看着没人家清楚,不过我可以说俺的代码简洁:0
def sum1s(C) :
    iLen = len(str(C))
    if iLen == 1 :
        return 1
    iFirst = C / (10 ** ( iLen - 1 ))
    if iFirst != 1 :
        return iFirst * sum1s(10**(iLen-1)-1) + 10 ** (iLen-1) + sum1s(C-iFirst*(10**(iLen-1)))
    else :
        return iFirst * sum1s(10**(iLen-1)-1) + C-iFirst*(10**(iLen-1)) + sum1s(C-iFirst*(10**(iLen-1))) + 1

if __name__ == "__main__" :
    iResult = sum1s(9999999999)
    print "result is %d" % iResult

yaws指定mnesia路径

当然总是可以在application中写上mnesia:start()诸如此类的代码,
不过yaws作为本着生成动态页面的webserver,本身具有启动mnesia的功能。
不过linux下都好说,windows下怎么调也不好使,上网google了一下,
限制还不少,不能指定绝对目录,路径还要加上double quote和single quote合起来
代码:
yaws -i -M "'path/to/db'"

zip函数的erlang实现

stdlib中不支持多List的zip函数,最多支持3个List,以下是我的尝试,支持锯齿List组
参数形式为L = [[L11,L12,L13,...],[L21,L22,L23,...],...[Ln1,Ln2,Ln3,...]]

-module(myzip).
%%-compile(export_all).
-export([zip/1,zip_longest/1]).

%%L = [[L11,L12,L13,...],[L21,L22,L23,...],...[Ln1,Ln2,Ln3,...]]
zip(L) ->
zip_tr(L).

zip_tr(L) ->
IniAcc0 = array:to_list(array:new(lists:min([length(I) || I <-L ]),{default,[]})),
Results = [lists:reverse(I) || I <- lists:foldl(fun zipfunc/2, IniAcc0, L )],
%%io:format("~p~n",[Results]),
Results.

zipfunc(Elem, AccIn) ->
%%io:format("~p~n",[AccIn]),
zipfunc_tr(Elem, AccIn, 1, length(AccIn)).

zipfunc_tr(_,AccIn,_Index,0) ->
AccIn;
zipfunc_tr([H|T], AccIn, Index, Count) ->
%%io:format("~p~n",[element(1,lists:split(Index-1,AccIn)) ++
%% [[H|lists:nth(Index,AccIn)]] ++ element(2,lists:split(Index, AccIn))]),
zipfunc_tr(T, element(1,lists:split(Index-1,AccIn)) ++
[[H|lists:nth(Index,AccIn)]] ++ element(2,lists:split(Index, AccIn)), Index+1, Count-1).

zip_longest(L) ->
zip_longest_tr(L).

zip_longest_tr(L) ->
IniAcc0 = array:to_list(array:new(lists:max([length(I) || I <-L ]),{default,[]})),
Results = [lists:reverse(I) || I <- lists:foldl(fun zipfunc_longest/2, IniAcc0, L )],
%%io:format("~p~n",[Results]),
Results.

zipfunc_longest(Elem, AccIn) ->
zipfunc_longest_tr(Elem, AccIn, 1, length(AccIn)).

zipfunc_longest_tr(_,AccIn,_Index,0) ->
AccIn;
zipfunc_longest_tr([],AccIn,Index,Count) ->
zipfunc_longest_tr([],element(1,lists:split(Index-1,AccIn)) ++
[[undefined|lists:nth(Index,AccIn)]] ++ element(2,lists:split(Index,AccIn)), Index+1, Count-1);
zipfunc_longest_tr([H|T], AccIn, Index, Count) ->
zipfunc_longest_tr(T, element(1,lists:split(Index-1,AccIn)) ++
[[H|lists:nth(Index,AccIn)]] ++ element(2,lists:split(Index,AccIn)), Index+1, Count-1).

输出:
4> L=[[l11,l12,l13],[l21,l22,l23,l24,l25],[l31,l32,l33,l34]].
[[l11,l12,l13],[l21,l22,l23,l24,l25],[l31,l32,l33,l34]]
5> myzip:zip_longest(L).
[[l11,l21,l31],
[l12,l22,l32],
[l13,l23,l33],
[undefined,l24,l34],
[undefined,l25,undefined]]
6> myzip:zip(L).
[[l11,l21,l31],[l12,l22,l32],[l13,l23,l33]]

eight queens problem solution in erlang

the source can be extented to solve N queens problem, just modify the macro.
-module(eightqueen).
-export([start/0]).
-define(N,8).

start() ->
    [eightqueen(P,[],?N) || P <- lists:seq(1,?N)],
    init:stop().

eightqueen(P,L,1) ->
    case isvalid(P,L,1,length(L)) of
        false -> false;
        true  ->
            io:format("----------------~n"),
            [output(L++[P],Col) || Col <- lists:seq(1,?N)]
    end;

eightqueen(P,L,N) ->
    case isvalid(P,L,1,length(L)) of
        false -> false;
        true  ->
            [eightqueen(P1,L ++ [P],N-1) || P1 <- lists:seq(1,?N)]
    end.

isvalid(P,[H|T],Start,Len) ->
    if
        P =:= H ->
            false;
        abs(P - H) =:= Len + 1 - Start ->
            false;
        true ->
            isvalid(P,T,Start+1,Len)
    end;

isvalid(_P,[],_Start,_Len) ->
    true.

output(L,Col) ->
    lists:foreach(fun(P) -> if
                                P =/= Col ->
                                    io:format("-");
                                true ->
                                    io:format("Q")
                            end
                  end, L),
    io:format("~n").


compilation:
erlc eightqueen.erl


execution:
erl -noshell -start eightqueen start

ExtJS中Ajax实现File Download

,

Ajax的处理都是异步的,所以想实现文件下载这种同步的操作,就比较捉襟见肘。
不过google了一下,找到了一个方法,当然不是完美
主旨就是提交一个request,在server端将文件生成好,然后返回文件名,
client端则在js中隐藏一个frame,将frame的src指向生成的文件(根据返回的文件名)

client:
Ext.Ajax.request({
url: '/csvoutput/',
success: function(r, o) {
obj = Ext.util.JSON.decode(r.responseText);
try {
Ext.destroy(Ext.get('downloadIframe'));
}
catch(e) {}
Ext.DomHelper.append(document.body, {
tag: 'iframe',
id:'downloadIframe',
frameBorder: 0,
width: 0,
height: 0,
css: 'display:none;visibility:hidden;height:0px;',
src: obj.filename
});
},
failure: function(r, o){
},
headers: {
'my-header': 'csvoutput'
},
params: { }
});

server:(django)
result = {}
result['filename'] = filename
result['success'] = True
return HttpResponse(simplejson.dumps(result), mimetype='text/javascript')

ExtJS做UI,Django做后台处理,让Browser变成Client

,

extjs还真是方便,可惜是一个商业软件,不过按照opensource也可以免费下载
现在js framework是百花齐放百家争鸣,各有各的长处,各有各的不足。
jquery无疑是现在用户群最多的,可以他的代码我愣是没看懂(汗一个,还是我太弱)
倒是extjs不错,document写的也很清楚,代码也很oo,所以很容易懂得。

extjs+django的组合就很完美啦
extjs在前台做UI,通常客户端能实现的功能在单一页面都能很好的实现,
而且支持很多widget,还很pp,而且是以event driven的,业务处理只需要
告诉url和parameters就够了,剩下的交给django来处理好了。
django这边就更方便了,url config的正则表达式匹配,方便的不是一点半点
内嵌的ORM能够处理大部分业务数据处理,做到最后每个view只需要返回json
数据就够了。

几个注意的地方:
1.返回的json数据,如果是嵌套的话,就需要name mapping,不然store不能
正确读出数据。
2.store的baseparam可以提供request参数,初始化定义也行,在load的地方
用也行,不过考虑到灵活性,还是在load的地方指定比较好,因为初始化定义的
参数都是静态的,如果store的参数需要动态获得的话,初始化的时候,有些widget
可能还没有初始化好,这个时候可能取不到值。
3.combobox中valueField,displayField,hiddenName三个属性很重要。
4.取得页面的widget的方法,用get('id')和getCmp('id')都能取得,
后者按照组件的方式返回,能够获得更多的信息。
5.任何panel都支持tbar和bbar,这个很方便的,尤其是页面空间有限的话。。。

最后要说的是,所有提交都是ajax方式的,所以时刻考虑到提交的动作都是异步的
不能按照同步操作那样考虑问题,可能在出bug的时候,更好地发现出现问题的地方。

django下ChoiceField的queryset动态设定

用django尝试写了一个简单的业务类site,真是一波三折。
djangoproject上的doc中规中矩,到挑不出毛病,但是碰到
一些个性化问题,就捉襟见肘啦

1,虽然django1.0已经提供了formwizard了,应该很好用,
可惜我的要求比较变态,还是不能胜任,所以索性就用hiddenfield
来一个一个form传下去(formwizard后台其实也是这么做的)

2,ChoiceField定义的时候,并不能动态的获得显示记录集,这个时候
可以重载form或者ChoiceField构造函数,来为以后的动态设定留下钩子。
例子如下:
class XXXXXXForm( forms.Form ) :
    def __init__( self, myqs, *args, **kwargs ) :
        self.myqs = myqs
        super(XXXXXXForm, self).__init__(*args, **kwargs)
        list_xxxxx = forms.ModelChoiceField( queryset=None,
                                           widget=forms.RadioSelect(), empty_label=None, required=False )
        hidden_xxx_name    = forms.CharField( max_length = 80, widget=forms.HiddenInput() ) 
        hidden_xxxxxx_name = forms.CharField( max_length = 40, widget=forms.HiddenInput() ) 

    def populate( self ) :
        self.fields['list_xxxxx'].queryset = XXXXXXX.objects.filter( xxxxxx_type__code=self.myqs )

声明变量的时候,不要忘了紧接着调用populate
default = {'hidden_xxx_name':xxx, 'hidden_xxxxxx_name': xxxxxx}
form3 = DepartStationListForm( qs, default )
form3.populate()
February 2012
S M T W T F S
January 2012March 2012
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