Skip to content

Instantly share code, notes, and snippets.

View moskytw's full-sized avatar

Mosky Liu moskytw

View GitHub Profile
@moskytw
moskytw / property-with-closure.py
Created March 2, 2013 15:33
A dirty hack which uses closure maps the accessing on an attribute to the __*item__ methods.
setattr(DictLike, attrname,
# it is a colsure
(lambda x:
property(
lambda self: self.__getitem__(x),
lambda self, v: self.__setitem__(x, v),
lambda self: self.__delitem__(x)
)
)(attrname)
)
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import re
def simple_replace(s):
return s.replace('A', 'a').replace('B', 'b').replace('C', 'c')
def dynamic_replace(s):
for t in 'ABC':
@moskytw
moskytw / m_days.py
Last active December 18, 2015 18:49
#!/usr/bin/env python
# -*- coding: utf-8 -*-
for y in (2011, 2012, 2100, 2400):
print 'year:', y
for m in range(1, 12+1):
m_days = 30 + (m+(m>=8))%2 - 2*(m==2) + (m==2 and (not y%4 and not not y%100 or not y%400))
print m, m_days
@moskytw
moskytw / m_days.c
Last active December 18, 2015 18:50
#include <stdio.h>
#define NUM_OF_ELEMENTS(array) (sizeof(array)/sizeof(array[0]))
main() {
int ys[] = {2011, 2012, 2100, 2400};
int i = 0, m = 0;
for(i = 0; i < NUM_OF_ELEMENTS(ys); i++) {
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# http://en.wikipedia.org/wiki/ANSI_escape_code
from sys import stdout
_stream = stdout
def set_stream(stream):
@moskytw
moskytw / test_time.py
Last active December 30, 2015 10:49
It explains the relation between timestamp, timetuple and datetime.
#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
It explains the relation between timestamp, timetuple and datetime.
The principles:
1. If you use datetime without tzinfo (i.e., naive datetime), use mktime with .timetuple to get the timestamp.
2. If you use datetime with tzinfo (i.e., aware datetime), use timegm with .utctimetuple to get the timestamp.
// class Profile
var Profile = function (obj) {
/* Model */
this._model = {};
/* View */
this.$view = $(Profile.template);
this.$nick = this.$view.find('.nick');
this.$error = this.$view.find('.error');
#!/usr/bin/env python
# -*- coding: utf-8 -*-
def deco(f):
def f_warpper(*args, **kagrs):
print 'Hi, I am f_warpper.'
return f(*args, **kagrs)
return f_warpper
import inspect
from pprint import pprint
def f():
pprint(inspect.stack())
x = 1
return x
def g():
y = f()
#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''Output:
$ py fun_with_progress.py
Start doing things without bar ...
Took: 0:00:13.598943
Start doing things with bar ...