INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Return the color property as list of [ R G B ] each 0 - 255.
def rgb_color(self): """Return the color property as list of [R, G, B], each 0-255.""" self.update() return [self._red, self._green, self._blue]
Turn bulb on ( full brightness ).
def turn_on(self): """Turn bulb on (full brightness).""" command = "C {},,,,100,\r\n".format(self._zid) response = self._hub.send_command(command) _LOGGER.debug("Turn on %s: %s", repr(command), response) return response
Set brightness of bulb.
def set_brightness(self, brightness): """Set brightness of bulb.""" command = "C {},,,,{},\r\n".format(self._zid, brightness) response = self._hub.send_command(command) _LOGGER.debug("Set brightness %s: %s", repr(command), response) return response
Set color and brightness of bulb.
def set_all(self, red, green, blue, brightness): """Set color and brightness of bulb.""" command = "C {},{},{},{},{},\r\n".format(self._zid, red, green, blue, brightness) response = self._hub.send_command(command) _LOGGER.debug("Set all %s...
Update light objects to their current values.
def update(self): """Update light objects to their current values.""" bulbs = self._hub.get_lights() if not bulbs: _LOGGER.debug("%s is offline, send command failed", self._zid) self._online = False
fun ( fn ) - > function or fun ( fn args... ) - > call of fn ( args... ): param ifunctional: f: return: decorated function
def functional(ifunctional): """ fun(fn) -> function or fun(fn, args...) -> call of fn(args...) :param ifunctional: f :return: decorated function """ @wraps(ifunctional) def wrapper(fn, *args, **kw): fn = ifunctional(fn) if args or kw: return fn(*args, **kw)...
fun ( 1 2 ) - > fun (( 1 ) ( 2 )) ๋กœ f ( 1 2 3 ) = > f (( 1 ) ( 2 ) ( 3 )): param fn:: return:
def tuple_arg(fn): """ fun(1,2) -> fun((1,), (2,))๋กœ f(1,2,3) => f((1,), (2,), (3,)) :param fn: :return: """ @wraps(fn) def wrapped(*args, **kwargs): args = map(tuplefy, args) return fn(*args, **kwargs) return wrapped
args ํŒŒ์‹ฑ ์œ ํ‹ธ function fun ( p1 p2... pn ** kwargs ) or fun ( [ p1 p2.. ] ** kwargs ) ex ) ์ƒ˜ํ”Œ::
def tuple_args(fn): """ args ํŒŒ์‹ฑ ์œ ํ‹ธ function fun(p1, p2, ...pn, **kwargs) or fun([p1, p2, ..], **kwargs) ex) ์ƒ˜ํ”Œ:: @tuple_arg def f(args, **kwargs): for d in args: print d f(1,2,3) => f([1,2,3]) :param function fn: :return: """ @wraps(...
args ๊ฐฏ์ˆ˜๊ฐ€ nth + 1 ๊ฐœ ์ผ๋•Œ ๊ทธ๊ฒŒ ๋งŒ์•ฝ tuple์ด๋ฉด unpack: param classfun:: param nth: nth = 0 ์ผ๋ฐ˜ ํ•จ์ˆ˜ nth = 1: ํด๋ž˜์Šค ํ•จ์ˆ˜ 1์ด self๋‹ˆ๊น.: return:
def unpack_args(classfun, nth=0): """ args ๊ฐฏ์ˆ˜๊ฐ€ nth + 1 ๊ฐœ ์ผ๋•Œ, ๊ทธ๊ฒŒ ๋งŒ์•ฝ tuple์ด๋ฉด, unpack :param classfun: :param nth: nth = 0, ์ผ๋ฐ˜ ํ•จ์ˆ˜, nth = 1: ํด๋ž˜์Šค ํ•จ์ˆ˜ 1์ด self๋‹ˆ๊น. :return: """ if classfun: nth = 1 def deco(fn): def wrapped(*args, **kwargs): if len(args) == nth + 1 an...
string 1๊ฐœ๋งŒ deco ์ธ์ž๋กœ ์˜ค๊ฑฐ๋‚˜ ์—†๊ฑฐ๋‚˜.: param deco:: return:
def optional_str(deco): """ string 1๊ฐœ๋งŒ deco ์ธ์ž๋กœ ์˜ค๊ฑฐ๋‚˜ ์—†๊ฑฐ๋‚˜. :param deco: :return: """ @wraps(deco) def dispatcher(*args, **kwargs): # when only function arg if not kwargs and len(args) == 1 and not isinstance(args[0], str) \ and args[0] is not None: ...
ํด๋ž˜์Šค ๋ฉค๋ฒ„ ํŒจ์น˜ @patchmethod ( Cls1... [ name = membername ] ) ex ) class A ( object ): def __init__ ( self data ): self. data = data
def patchmethod(*cls, **kwargs): """ ํด๋ž˜์Šค ๋ฉค๋ฒ„ ํŒจ์น˜ @patchmethod(Cls1, ..., [name='membername']) ex) class A(object): def __init__(self, data): self.data = data @patchmethod(A) def sample(self): ''' haha docstrings ''' print self.data @patchmethod(A, name='me...
class getter ํ•จ์ˆ˜ ํŒจ์น˜ decorator EX ) class B ( A ): pass
def patchproperty(*cls, **kwargs): """ class getter ํ•จ์ˆ˜ ํŒจ์น˜ decorator EX) class B(A): pass @patchproperty(B) def prop(self): return 'hello' :param cls: :param kwargs: """ def _patch(fun): m = kwargs.pop('property', None) or fun.__name__ p = proper...
context for handling keyboardinterrupt ex ) with on_interrupt ( handler ): critical_work_to_prevent ()
def on_interrupt(handler, reraise=False): """ context for handling keyboardinterrupt ex) with on_interrupt(handler): critical_work_to_prevent() from logger import logg on_interrupt.signal = None :param function handler: :param bool reraise: :return: context """ def...
context for guard keyboardinterrupt ex ) with interrupt_guard ( need long time ): critical_work_to_prevent ()
def interrupt_guard(msg='', reraise=True): """ context for guard keyboardinterrupt ex) with interrupt_guard('need long time'): critical_work_to_prevent() :param str msg: message to print when interrupted :param reraise: re-raise or not when exit :return: context """ def echo...
is ๋ฉ”์ธ ์“ฐ๋ ˆ๋“œ alive?: rtype: bool
def is_main_alive(): """ is ๋ฉ”์ธ ์“ฐ๋ ˆ๋“œ alive? :rtype: bool """ for t in threading.enumerate(): if t.name == 'MainThread': return t.is_alive() print('MainThread not found') return False
This function takes a file path beginning with edgar and stores the form in a directory. The default directory is sec_filings but can be changed through a keyword argument.
def retrieve_document(file_path, directory='sec_filings'): ''' This function takes a file path beginning with edgar and stores the form in a directory. The default directory is sec_filings but can be changed through a keyword argument. ''' ftp = FTP('ftp.sec.gov', timeout=None) ftp.login...
for overriding: param item:: return:
def action(self, item): """ for overriding :param item: :return: """ fun, args, kwargs = item return fun(*args, **kwargs)
put job if possible non - blocking: param fun:: param args:: param kwargs:: return:
def push_job(self, fun, *args, **kwargs): """ put job if possible, non-blocking :param fun: :param args: :param kwargs: :return: """ assert callable(fun) return self.put((fun, args, kwargs), block=True)
put job if possible non - blocking: param fun:: param args:: param kwargs:: return:
def put_job(self, fun, *args, **kwargs): """ put job if possible, non-blocking :param fun: :param args: :param kwargs: :return: """ if not args and not kwargs and isinstance(fun, (tuple, list)): # ex) q.put_job([fun, args, kwargs]) ...
define a single flag. add_flag ( flagname default_value help = ** kwargs ) add_flag ( [ ( flagname default_value help )... ] ) or define flags without help message add_flag ( flagname default_value help = ** kwargs )
def add_flag(*args, **kwargs): """ define a single flag. add_flag(flagname, default_value, help='', **kwargs) add_flag([(flagname, default_value, help), ...]) or define flags without help message add_flag(flagname, default_value, help='', **kwargs) add_flag('gpu', 1, help='CUDA_VISIBLE_...
: param main: main or sys. modules [ __main__ ]. main: param argv: argument list used in argument parse: param flags: flags to define with defaults: return:
def run(main=None, argv=None, **flags): """ :param main: main or sys.modules['__main__'].main :param argv: argument list used in argument parse :param flags: flags to define with defaults :return: """ """Runs the program with an optional 'main' function and 'argv' list.""" import sys as ...
path ๋ถ€๋ถ„์ด ์—†์œผ๋ฉด mkdir ์„ ํ•œ๋‹ค.: param filepath: ํŒŒ์ผ ํŒจ์“ฐ: return: filpath ๊ทธ๋Œ€๋กœ ๋ฆฌํ„ด
def mkdir_if_not(filepath, ispath=False): """ path ๋ถ€๋ถ„์ด ์—†์œผ๋ฉด mkdir ์„ ํ•œ๋‹ค. :param filepath: ํŒŒ์ผ ํŒจ์“ฐ :return: filpath ๊ทธ๋Œ€๋กœ ๋ฆฌํ„ด """ if not ispath: p, _ = os.path.split(filepath) else: p = filepath if not p: return filepath if not os.path.exists(p): # M.info('%s...
read lines from a textfile: param filepath:: return: list [ line ]
def readlines(filepath): """ read lines from a textfile :param filepath: :return: list[line] """ with open(filepath, 'rt') as f: lines = f.readlines() lines = map(str.strip, lines) lines = [l for l in lines if l] return lines
read file as is
def readtxt(filepath): """ read file as is""" with open(filepath, 'rt') as f: lines = f.readlines() return ''.join(lines)
ํŒŒ์ผ ์žˆ์œผ๋ฉด ๋ฎ์–ด์”€: param obj:: param str filepath:: param compress:: return:
def savefile(obj, filepath, compress=True): """ ํŒŒ์ผ ์žˆ์œผ๋ฉด ๋ฎ์–ด์”€ :param obj: :param str filepath: :param compress: :return: """ try: import cPickle as pickle except Exception: import pickle import joblib # ์ผ๋‹จ ์ž„์‹œ ํŒŒ์ผ์— ์ €์žฅ. tmpfile = filepath + '.tmp' mkdir_if_...
: param filepath:: param mmap_mode: { None โ€˜r + โ€™ โ€˜rโ€™ โ€˜w + โ€™ โ€˜cโ€™ } see. joblib. load: return:
def loadfile(filepath, mmap_mode=None): """ :param filepath: :param mmap_mode: {None, โ€˜r+โ€™, โ€˜rโ€™, โ€˜w+โ€™, โ€˜cโ€™} see. joblib.load :return: """ import joblib try: return joblib.load(filepath, mmap_mode=mmap_mode) except IOError: return None
๊ณ„์‚ฐ๋œ ๊ฒฐ๊ณผ ํŒŒ์ผ์ด ์žˆ์œผ๋ฉด ๋กœ๋”ฉํ•˜๊ณ  ์—†์œผ๋ฉด ๊ณ„์‚ฐํ›„ ์ €์žฅ ex ) res = load_or_run ( file_loadorsave funlongtime.... force = False ): param filepath:: param fun:: param force:: return:
def load_or_run(filepath, fun, *args, **kwargs): """ ๊ณ„์‚ฐ๋œ ๊ฒฐ๊ณผ ํŒŒ์ผ์ด ์žˆ์œผ๋ฉด ๋กœ๋”ฉํ•˜๊ณ , ์—†์œผ๋ฉด ๊ณ„์‚ฐํ›„ ์ €์žฅ ex) res = load_or_run('file_loadorsave', funlongtime, ...., force=False) :param filepath: :param fun: :param force: :return: """ force = kwargs.pop('force', False) compress = kwargs.pop('comp...
matches?: param fname: file name: type fname: str: param patterns: list of filename pattern. see fnmatch. fnamtch: type patterns: [ str ]: rtype: generator of bool
def fnmatches(fname, patterns, matchfun): """" matches? :param fname: file name :type fname: str :param patterns: list of filename pattern. see fnmatch.fnamtch :type patterns: [str] :rtype: generator of bool """ import fnmatch matchfun = matchfun or fnmatch.fnmatch for p in p...
list file ( or folder ) for this path ( NOT recursive ): param p:: param match:: param exclude:: param listtype: ( file | filepath | dir | all ): param matchfun: match fun ( default fnmatch. fnmatch ) True/ False = matchfun ( name pattern ): rtype:
def listdir(p, match='*', exclude='', listtype='file', matchfun=None): """ list file(or folder) for this path (NOT recursive) :param p: :param match: :param exclude: :param listtype: ('file' | 'filepath' |'dir' | 'all') :param matchfun: match fun (default fnmatch.fnmatch) True/False = matchf...
generator of list files in the path. filenames only
def listfile(p): """ generator of list files in the path. filenames only """ try: for entry in scandir.scandir(p): if entry.is_file(): yield entry.name except OSError: return
generator of list files in the path. filenames only
def listfilepath(p): """ generator of list files in the path. filenames only """ for entry in scandir.scandir(p): if entry.is_file(): yield entry.path
generator of list folder in the path. folders only
def listfolder(p): """ generator of list folder in the path. folders only """ for entry in scandir.scandir(p): if entry.is_dir(): yield entry.name
generator of list folder in the path. folders only
def listfolderpath(p): """ generator of list folder in the path. folders only """ for entry in scandir.scandir(p): if entry.is_dir(): yield entry.path
internal use
def _pred_pattern(match='*', exclude='', patterntype='fnmatch'): """ internal use """ m, x = match, exclude if m == '*': if not x: pred = lambda n: True else: x = [x] if _is_str(x) else x matcher = get_match_fun(x, patterntype) pred = lambda n...
recursively find folder path from toppath. patterns to decide to walk folder path or not: type toppath: str: type match: str or list ( str ): type exclude: str or list ( str ): rtype: generator for path str
def findfolder(toppath, match='*', exclude=''): """ recursively find folder path from toppath. patterns to decide to walk folder path or not :type toppath: str :type match: str or list(str) :type exclude: str or list(str) :rtype: generator for path str """ pred = _pred_pattern(match,...
walk folder if pred ( foldername ) is True: type toppath: str: type pred: function ( str ) = > bool
def walkfolder(toppath, pred): """ walk folder if pred(foldername) is True :type toppath: str :type pred: function(str) => bool """ for entry in scandir.scandir(toppath): if not entry.is_dir() or not pred(entry.name): continue yield entry.path for p in walkfol...
์ž„์‹œ ํด๋”๋ฅผ ๋งŒ๋“ค์–ด์„œ ๋ฆฌํ„ด
def tempfolder(prefix=''): """์ž„์‹œ ํด๋”๋ฅผ ๋งŒ๋“ค์–ด์„œ ๋ฆฌํ„ด""" import uuid p = prefix + str(uuid.uuid4()) d = tempdir() tmpd = os.path.join(d, p) return mkdir_if_not(tmpd, ispath=True)
return image size ( height width ): param fname:: return:
def imsize(fname): """ return image size (height, width) :param fname: :return: """ from PIL import Image im = Image.open(fname) return im.size[1], im.size[0]
self์™€ other ํ‚ค๊ฐ€ ๋™์ผํ•œ ์•„์ดํ…œ์˜ dictobj: type other: dict: rtype: dictobj:
def intersect(self, other): """ self์™€ other ํ‚ค๊ฐ€ ๋™์ผํ•œ ์•„์ดํ…œ์˜ dictobj :type other: dict :rtype: dictobj: """ return DictObj({k: self[k] for k in self if k in other})
recursive dict to dictobj ์ปจ๋ฒ„ํŠธ: param dic:: return:
def from_dict(dic): """ recursive dict to dictobj ์ปจ๋ฒ„ํŠธ :param dic: :return: """ return DictObj({k: DictObj.convert_ifdic(v) for k, v in dic.items()})
Clean up after ourselves removing created files.
def _clean_up(paths): """ Clean up after ourselves, removing created files. @param {[String]} A list of file paths specifying the files we've created during run. Will all be deleted. @return {None} """ print('Cleaning up') # Iterate over the given paths, unlinking them for path i...
Create an index file in the given location supplying known lists of present image files and subdirectories.
def _create_index_file( root_dir, location, image_files, dirs, force_no_processing=False): """ Create an index file in the given location, supplying known lists of present image files and subdirectories. @param {String} root_dir - The root directory of the entire crawl. Used to ascertain...
Crawl the root directory downwards generating an index HTML file in each directory on the way down.
def _create_index_files(root_dir, force_no_processing=False): """ Crawl the root directory downwards, generating an index HTML file in each directory on the way down. @param {String} root_dir - The top level directory to crawl down from. In normal usage, this will be '.'. @param {Boolean=Fal...
Get an instance of PIL. Image from the given file.
def _get_image_from_file(dir_path, image_file): """ Get an instance of PIL.Image from the given file. @param {String} dir_path - The directory containing the image file @param {String} image_file - The filename of the image file within dir_path @return {PIL.Image} An instance of the image file as a ...
Get the value to be used as the href for links from thumbnail images. For most image formats this will simply be the image file name itself. However some image formats ( tif ) are not natively displayable by many browsers and therefore we must link to image data in another format.
def _get_image_link_target_from_file(dir_path, image_file, force_no_processing=False): """ Get the value to be used as the href for links from thumbnail images. For most image formats this will simply be the image file name itself. However, some image formats (tif) are not natively displayable by many b...
Get base - 64 encoded data as a string for the given image file s full image for use directly in HTML <img > tags or a path to the original if image scaling is not supported. This is a full - sized version of _get_thumbnail_src_from_file for use in image formats which cannot be displayed directly in - browser and there...
def _get_image_src_from_file(dir_path, image_file, force_no_processing=False): """ Get base-64 encoded data as a string for the given image file's full image, for use directly in HTML <img> tags, or a path to the original if image scaling is not supported. This is a full-sized version of _get_thumbn...
Get base - 64 encoded data as a string for the given image. Fallback to return fallback_image_file if cannot get the image data or img is None.
def _get_src_from_image(img, fallback_image_file): """ Get base-64 encoded data as a string for the given image. Fallback to return fallback_image_file if cannot get the image data or img is None. @param {Image} img - The PIL Image to get src data for @param {String} fallback_image_file - The filena...
Get a PIL. Image from the given image file which has been scaled down to THUMBNAIL_WIDTH wide.
def _get_thumbnail_image_from_file(dir_path, image_file): """ Get a PIL.Image from the given image file which has been scaled down to THUMBNAIL_WIDTH wide. @param {String} dir_path - The directory containing the image file @param {String} image_file - The filename of the image file within dir_path ...
Get base - 64 encoded data as a string for the given image file s thumbnail for use directly in HTML <img > tags or a path to the original if image scaling is not supported.
def _get_thumbnail_src_from_file(dir_path, image_file, force_no_processing=False): """ Get base-64 encoded data as a string for the given image file's thumbnail, for use directly in HTML <img> tags, or a path to the original if image scaling is not supported. @param {String} dir_path - The directory...
Run the image server. This is blocking. Will handle user KeyboardInterrupt and other exceptions appropriately and return control once the server is stopped.
def _run_server(): """ Run the image server. This is blocking. Will handle user KeyboardInterrupt and other exceptions appropriately and return control once the server is stopped. @return {None} """ # Get the port to run on port = _get_server_port() # Configure allow_reuse_address to...
Generate indexes and run server from the given directory downwards.
def serve_dir(dir_path): """ Generate indexes and run server from the given directory downwards. @param {String} dir_path - The directory path (absolute, or relative to CWD) @return {None} """ # Create index files, and store the list of their paths for cleanup later # This time, force no pro...
get caller s __name__
def modulename(cls, depth=1): """ get caller's __name__ """ depth += cls.extra_depth frame = sys._getframe(depth) return frame.f_globals['__name__']
optional argument ๋ฅผ ํฌํ•จํ•˜๋Š” decorator๋ฅผ ๋งŒ๋“œ๋Š” decorator
def deco_optional(decorator): """ optional argument ๋ฅผ ํฌํ•จํ•˜๋Š” decorator๋ฅผ ๋งŒ๋“œ๋Š” decorator """ @functools.wraps(decorator) def dispatcher(*args, **kwargs): one_arg = len(args) == 1 and not kwargs if one_arg and inspect.isfunction(args[0]): decor_obj = decorator() re...
decorator option์€ kwargs๋งŒ ํ—ˆ์šฉ: param deco:: return:
def optional(deco): """ decorator option์€ kwargs๋งŒ ํ—ˆ์šฉ :param deco: :return: """ @functools.wraps(deco) def dispatcher(*args, **kwargs): decorator = deco(**kwargs) if args: assert len(args) == 1 return decorator(args[0]) else: return ...
_ = bind. placeholder # unbound placeholder ( arg ) f = bind ( fun _ _ arg3 kw = kw1 kw2 = kw2 ) f ( arg1 arg2 ): param fun:: param argsbind:: param kwbind:: return:
def bindargs(fun, *argsbind, **kwbind): """ _ = bind.placeholder # unbound placeholder (arg) f = bind(fun, _, _, arg3, kw=kw1, kw2=kw2), f(arg1, arg2) :param fun: :param argsbind: :param kwbind: :return: """ assert argsbind argsb = list(argsbind) iargs = [i for i in range(...
kwarg ๋ฐ”์ธ๋”ฉ๋œ ํ•จ์ˆ˜ return. ex ) def fun ( opt1 opt2 ): print opt1 opt2
def bindkw(fun, **kwbind): """ kwarg ๋ฐ”์ธ๋”ฉ๋œ ํ•จ์ˆ˜ return. ex) def fun(opt1, opt2): print opt1, opt2 f = bind(fun, opt1=2, opt2=3) f() :param function fun: :param kwbind: :return: function """ @functools.wraps(fun) def wrapped(*args, **kwargs): kws = kwbind.co...
change default value for function ex ) def sample ( a b = 1 c = 1 ): print from sample: a b c return a b c fun = default ( sample b = 4 c = 5 ) print fun. default # get default value dictionary fun ( 1 ) # print 1 5 5 and return
def default(fun, **kwdefault): """ change default value for function ex) def sample(a, b=1, c=1): print 'from sample:', a, b, c return a, b, c fun = default(sample, b=4,c=5) print fun.default # get default value dictionary fun(1) # print 1, 5, 5 and return :param fun: ...
call class instance method for initial setup::
def setup_once(initfn): """ call class instance method for initial setup :: class B(object): def init(self, a): print 'init call:', a @setup_once(init) def mycall(self, a): print 'real call:', a b = B() b.mycall(222)...
USE carefully ^^
def static(**kwargs): """ USE carefully ^^ """ def wrap(fn): fn.func_globals['static'] = fn fn.__dict__.update(kwargs) return fn return wrap
random crop # assume imagez has same size ( H W ) # assume sz is less or equal than size of image: param sz: cropped image sz: param imagez: imagez: return: rand cropped image pairs or function bound to sz
def rand_crop(sz, *imagez): """ random crop # assume imagez has same size (H, W) # assume sz is less or equal than size of image :param sz: cropped image sz :param imagez: imagez :return: rand cropped image pairs or function bound to sz """ def _rand_crop(*imgz): imsz = imgz...
: param anglerange:: param imagez:: return:
def rand_rotate(anglerange, *imagez): """ :param anglerange: :param imagez: :return: """ r = float(anglerange[1] - anglerange[0]) s = anglerange[0] def _rand_rotate(*imgz): angle = np.random.random(1)[0] * r + s out = tuple(rotate(img, angle) for img in imgz) ret...
depthmask: shape of [ batch h w ]
def blend_discrete(images, depthmask, depth=None): """ depthmask : shape of [batch, h, w] """ imshape = images.shape depth = depth or images.shape[3] blend = np.empty(shape=(imshape[0], imshape[1], imshape[2])) for d in range(depth): imask = (depthmask == d) channel = images[...
random blending masks
def rand_blend_mask(shape, rand=rand.uniform(-10, 10), **kwargs): """ random blending masks """ # batch, channel = shape[0], shape[3] z = rand(shape[0]) # seed noise = snoise2dz((shape[1], shape[2]), z, **kwargs) return noise
vector parameters: param size:: param vz:: param vscale:: param voctave:: param vpersistence:: param vlacunarity:: return:
def snoise2dvec(size, *params, **kwargs): #, vlacunarity): """ vector parameters :param size: :param vz: :param vscale: :param voctave: :param vpersistence: :param vlacunarity: :return: """ data = (snoise2d(size, *p, **kwargs) for p in zip(*params)) # , vlacunarity)) re...
z value as like a seed
def snoise2d(size, z=0.0, scale=0.05, octaves=1, persistence=0.25, lacunarity=2.0): """ z value as like a seed """ import noise data = np.empty(size, dtype='float32') for y in range(size[0]): for x in range(size[1]): v = noise.snoise3(x * scale, y * scale, z, ...
z as seeds scale์ด ์ž‘์„ ์ˆ˜๋ก ํŒจํ„ด์ด ์ปค์ง€๋Š” ํšจ๊ณผ
def snoise2dz(size, z, scale=0.05, octaves=1, persistence=0.25, lacunarity=2.0): """ z as seeds scale์ด ์ž‘์„ ์ˆ˜๋ก ํŒจํ„ด์ด ์ปค์ง€๋Š” ํšจ๊ณผ """ import noise z_l = len(z) data = np.empty((z_l, size[0], size[1]), dtype='float32') for iz in range(z_l): zvalue = z[iz] for y in range(size[0]): ...
: param images:: param scale: scale for random value: param randfun: any randfun binding except shape: param clamp: clamping range: return:
def rand_brightness(imagez, scale=1.0, randfun=rand.normal(0., .1), clamp=(0., 1.)): """ :param images: :param scale: scale for random value :param randfun: any randfun binding except shape :param clamp: clamping range :return: """ l, h = clamp r = randfun((imagez[0].shape[0], 1, 1, ...
Based on https:// gist. github. com/ erniejunior/ 601cdf56d2b424757de5 elastic deformation of images as described in [ Simard2003 ]
def elastic_transform(im, alpha=0.5, sigma=0.2, affine_sigma=1.): """ Based on https://gist.github.com/erniejunior/601cdf56d2b424757de5 elastic deformation of images as described in [Simard2003] """ # fixme : not implemented for multi channel ! import cv2 islist = isinstance(im, (tuple, lis...
rotate and crop if no img then return crop function: param centerij:: param sz:: param angle:: param img: [ h w d ]: param mode: padding option: return: cropped image or function
def rotate_crop(centerij, sz, angle, img=None, mode='constant', **kwargs): """ rotate and crop if no img, then return crop function :param centerij: :param sz: :param angle: :param img: [h,w,d] :param mode: padding option :return: cropped image or function """ # crop enough s...
crop sz from ij as center: param img:: param center: ij: param sz:: param mode:: return:
def crop(img, center, sz, mode='constant'): """ crop sz from ij as center :param img: :param center: ij :param sz: :param mode: :return: """ center = np.array(center) sz = np.array(sz) istart = (center - sz / 2.).astype('int32') iend = istart + sz imsz = img.shape[:2]...
if no img then return crop function: param sz:: param img:: return:
def cropcenter(sz, img=None): """ if no img, then return crop function :param sz: :param img: :return: """ l = len(sz) sz = np.array(sz) def wrapped(im): imsz = np.array(im.shape) s = (imsz[:l] - sz) / 2 # start index to = s + sz # end index # img[...
pad img if need to guarantee minumum size: param sz_atleast: [ H W ] at least: param img: image np. array [ H W... ]: param mode: str padding mode: return: padded image or asis if enought size
def pad_if_need(sz_atleast, img, mode='constant'): # fixme : function or .... """ pad img if need to guarantee minumum size :param sz_atleast: [H,W] at least :param img: image np.array [H,W, ...] :param mode: str, padding mode :return: padded image or asis if enought size """ # sz_at...
canny edge
def canny(img, threshold1=255/3, threshold2=255, **kwargs): """ canny edge """ import cv2 # edges=None, apertureSize=None, L2gradient=None if img.ndim <= 3: edge = cv2.Canny(img, threshold1, threshold2, **kwargs) if edge.ndim == 2: edge = np.expand_dims(edge, 2) elif img....
package path. return None if failed to guess
def guess_package_path(searchfrom): """ package path. return None if failed to guess """ from snipy.io import fileutil current = searchfrom + '/' init_found = False pack_found = False while not init_found and current != '/': current = os.path.dirname(current) initfile = ...
package path. return None if failed to guess
def find_package_path(searchfrom): """ package path. return None if failed to guess """ current = searchfrom + '/' init_found = False pack_found = False while not init_found and current != '/': current = os.path.dirname(current) initfile = os.path.join(current, '__init__.py'...
this_package. py ์—์„œ ์‚ฌ์šฉ import snipy. this_package
def append_this_package_path(depth=1): """ this_package.py ์—์„œ ์‚ฌ์šฉ import snipy.this_package """ from .caller import caller logg.debug('caller module %s', caller.modulename(depth + 1)) c = caller.abspath(depth + 1) logg.debug('caller path %s', c) p = guess_package_path(dirname(c)) ...
todo: add some example: param args:: return:
def flows(args): """ todo : add some example :param args: :return: """ def flow_if_not(fun): # t = type(fun) if isinstance(fun, iterator): return fun elif isinstance(fun, type) and 'itertools' in str(fun.__class__): return fun else: ...
forever todo: add example
def forever(it): """ forever todo : add example """ while True: # generator ๋‘๋ฒˆ์จฐ iteration ๋ฌดํ•œ ๋ฃจํ”„ ๋ฐฉ์ง€ i = iter(it) try: yield i.next() except StopIteration: raise StopIteration while True: try: yield i.next() ...
add example: param size:: param iterable:: param rest:: return:
def ibatch(size, iterable=None, rest=False): """ add example :param size: :param iterable: :param rest: :return: """ @iterflow def exact_size(it): it = iter(it) while True: yield [it.next() for _ in xrange(size)] @iterflow def at_most(it): ...
todo: add example: param size:: param iterable:: param rest:: return:
def batchzip(size, iterable=None, rest=False): """ todo : add example :param size: :param iterable: :param rest: :return: """ fn = ibatch(size, rest=rest) >> zipflow return fn if iterable is None else fn(iterable)
todo: add example: param size:: param iterable:: param rest:: return:
def batchstack(size, iterable=None, rest=False): """ todo : add example :param size: :param iterable: :param rest: :return: """ def stack(data): import numpy as np return map(np.vstack, data) fn = batchzip(size, rest=rest) >> flow(stack) return fn if iterable i...
add example: param qsize:: param iterable:: return:
def shuffle(qsize=1024, iterable=None): """ add example :param qsize: :param iterable: :return: """ @iterflow def shuffleit(it): from random import randrange q = [] for i, d in enumerate(it): q.insert(randrange(0, len(q) + 1), d) if i < q...
Converts a permutation into a permutation matrix.
def to_permutation_matrix(matches): """Converts a permutation into a permutation matrix. `matches` is a dictionary whose keys are vertices and whose values are partners. For each vertex ``u`` and ``v``, entry (``u``, ``v``) in the returned matrix will be a ``1`` if and only if ``matches[u] == v``. ...
Convenience function that creates a block matrix with the specified blocks.
def four_blocks(topleft, topright, bottomleft, bottomright): """Convenience function that creates a block matrix with the specified blocks. Each argument must be a NumPy matrix. The two top matrices must have the same number of rows, as must the two bottom matrices. The two left matrices must have ...
Returns the adjacency matrix of a bipartite graph whose biadjacency matrix is A.
def to_bipartite_matrix(A): """Returns the adjacency matrix of a bipartite graph whose biadjacency matrix is `A`. `A` must be a NumPy array. If `A` has **m** rows and **n** columns, then the returned matrix has **m + n** rows and columns. """ m, n = A.shape return four_blocks(zeros(m,...
Returns the Boolean matrix in the same shape as D with ones exactly where there are nonzero entries in D.
def to_pattern_matrix(D): """Returns the Boolean matrix in the same shape as `D` with ones exactly where there are nonzero entries in `D`. `D` must be a NumPy array. """ result = np.zeros_like(D) # This is a cleverer way of doing # # for (u, v) in zip(*(D.nonzero())): # ...
Returns the Birkhoff -- von Neumann decomposition of the doubly stochastic matrix D.
def birkhoff_von_neumann_decomposition(D): """Returns the Birkhoff--von Neumann decomposition of the doubly stochastic matrix `D`. The input `D` must be a square NumPy array representing a doubly stochastic matrix (that is, a matrix whose entries are nonnegative reals and whose row sums and column ...
Returns the result of incrementing version.
def bump_version(version, which=None): """Returns the result of incrementing `version`. If `which` is not specified, the "patch" part of the version number will be incremented. If `which` is specified, it must be ``'major'``, ``'minor'``, or ``'patch'``. If it is one of these three strings, the corres...
Gets the current version from the specified file.
def get_version(filename, pattern): """Gets the current version from the specified file. This function assumes the file includes a string of the form:: <pattern> = <version> """ with open(filename) as f: match = re.search(r"^(\s*%s\s*=\s*')(.+?)(')(?sm)" % pattern, f.read()) if ma...
Prints the specified message and exits the program with the specified exit status.
def fail(message=None, exit_status=None): """Prints the specified message and exits the program with the specified exit status. """ print('Error:', message, file=sys.stderr) sys.exit(exit_status or 1)
Tags the current version.
def git_tag(tag): """Tags the current version.""" print('Tagging "{}"'.format(tag)) msg = '"Released version {}"'.format(tag) Popen(['git', 'tag', '-s', '-m', msg, tag]).wait()
initialize with templates path parameters templates_path str the position of templates directory global_data dict globa data can be got in any templates
def initialize(self, templates_path, global_data): """initialize with templates' path parameters templates_path str the position of templates directory global_data dict globa data can be got in any templates""" self.env = Environment(loader=FileSystemLoader(temp...
Render data with template return html unicodes. parameters template str the template s filename data dict the data to render
def render(self, template, **data): """Render data with template, return html unicodes. parameters template str the template's filename data dict the data to render """ # make a copy and update the copy dct = self.global_data.copy() dct.update...
Render data with template and then write to path
def render_to(self, path, template, **data): """Render data with template and then write to path""" html = self.render(template, **data) with open(path, 'w') as f: f.write(html.encode(charset))
shortcut to render data with template. Just add exception catch to renderer. render
def render(template, **data): """shortcut to render data with `template`. Just add exception catch to `renderer.render`""" try: return renderer.render(template, **data) except JinjaTemplateNotFound as e: logger.error(e.__doc__ + ', Template: %r' % template) sys.exit(e.exit_code)
Replace../ leaded url with absolute uri.
def replace_relative_url_to_absolute(self, content): """Replace '../' leaded url with absolute uri. """ p = os.path.join(os.getcwd(), './src', '../') return content.replace('../', p)
Get the DataFrame for this view. Defaults to using self. dataframe.
def get_dataframe(self): """ Get the DataFrame for this view. Defaults to using `self.dataframe`. This method should always be used rather than accessing `self.dataframe` directly, as `self.dataframe` gets evaluated only once, and those results are cached for all subsequ...
Indexes the row based on the request parameters.
def index_row(self, dataframe): """ Indexes the row based on the request parameters. """ return dataframe.loc[self.kwargs[self.lookup_url_kwarg]].to_frame().T
Returns the row the view is displaying.
def get_object(self): """ Returns the row the view is displaying. You may want to override this if you need to provide non-standard queryset lookups. Eg if objects are referenced using multiple keyword arguments in the url conf. """ dataframe = self.filter_dataf...
The paginator instance associated with the view or None.
def paginator(self): """ The paginator instance associated with the view, or `None`. """ if not hasattr(self, '_paginator'): if self.pagination_class is None: self._paginator = None else: self._paginator = self.pagination_class() ...