ngram
listlengths 0
82k
|
|---|
[
"x in info.split()] def is_gc_running(ip, port): s = get_gc_status(ip, port)",
"def get_collision(self, bucket): check_bucket(bucket) collisions = defaultdict(dict) hint_data = self.get(\"@collision_all_%x\"",
"(flag, tstamp, ver):\", k, r[1], r[3:] print \"key info mem:\",",
"info disk(ver, vhash, flag, vsz, ts, fid, pos):\", \\ c.get_key_info_disk(k)",
"get_buckets_keys_count(store): \"\"\" return dict: buckets -> count \"\"\" st =",
"collections import defaultdict from beansdbadmin.core.hint import parse_new_hint_body from beansdbadmin.core.data import",
"out = t.read_until('\\n') t.write('quit\\r\\n') t.close() return out.strip(\"\\r\\n\") def connect(server, **kwargs):",
"import defaultdict from beansdbadmin.core.hint import parse_new_hint_body from beansdbadmin.core.data import parse_records",
"return self.addr def set(self, key, data, rev=0): return bool(self.mc.set(key, data,",
"data, rev=0): return bool(self.mc.set(key, data, rev)) def set_raw(self, key, data,",
"vsz, ts, fid, pos):\", \\ c.get_key_info_disk(k) print \"key version:\", c.get_version(k)",
"Exception('get %s from %s, reply = [%s], bucket %x not",
"16) if bucket_ == sub: return int(c) raise Exception('get %s",
"encapsulate @, ?, gc ... use is instead of libmc.Client",
"from beansdbadmin.core.data import parse_records from beansdbadmin.core.hash import get_khash64 def get_url_content(url):",
"'').split('\\n'): if line: d, _, c = line.split(' ') if",
"def get_primary_buckets(store): \"\"\" return possible primary buckets, might be wrong",
"not isinstance(khash, str): khash = \"%016x\" % khash return self.get(\"@@\"",
"{} {}\\n'.format(tree, start_fid, end_fid) t.write(gc_cmd) out = t.read_until('\\n').strip('\\r\\n') assert out",
"while True: status = self.get_gc_status() if status.find('running') >= 0: continue",
"KeyError: logging.error(\"fail to get version %s %s\", self, st) def",
"hint_data is None: return dict() for key, meta, _ in",
"for line in lines: if len(line) == 0: continue d,",
"break result.append(i) return [x[0] for x in result] def get_key_info_disk(store,",
"[(\"\", (int(vhash), ver))] return ret def get_server_version(self): try: st =",
"def set_multi(self, values, return_failure=False): return self.mc.set_multi(values, return_failure=return_failure) def _check_last_error(self): last_err",
"bucket): check_bucket(bucket) collisions = defaultdict(dict) hint_data = self.get(\"@collision_all_%x\" % bucket)",
"port) if s and s.find('running') >= 0: return True return",
"import urllib import itertools import warnings from collections import defaultdict",
"dir! not use it if dir is large!''' for path,",
"dir_to_dict(content) def list_dir(self, d): # FIXME: d should not need",
"c.get_version(k) print \"collision_summary\", c.get_collision_summary(int(b)) print \"gc status:\", c.get_gc_status() if __name__",
"khash32_str = \"@%08x\" % (khash64 >> 32) _dir = self.get_dir(khash32_str)",
"store.get(cmd) if result: lines = result.split('\\n') for line in lines:",
"\"\"\" return possible primary buckets, might be wrong on temporary",
"key): try: r = self.mc.get(key) if r is None: self._check_last_error()",
"= dict() if dir_str: for line in [x for x",
"leaf khash_str = list(leaf)[0] print \"a khash_str\", khash_str r =",
"addr): self.addr = addr self.host, port = addr.split(\":\") self.port =",
"khash return self.get(\"@@\" + khash) def get_records_by_khash(self, khash_str): raw =",
"set_multi(self, values, return_failure=False): return self.mc.set_multi(values, return_failure=return_failure) def _check_last_error(self): last_err =",
"return self.mc.set_multi(values, return_failure=return_failure) def _check_last_error(self): last_err = self.mc.get_last_error() if last_err",
"= 'gc {} {} {}\\n'.format(tree, start_fid, end_fid) t.write(gc_cmd) out =",
"?, gc ... use is instead of libmc.Client ''' import",
"flag=0): if rev < 0: raise Exception(str(rev)) return self.mc.set_raw(key, data,",
"'gc {} {} {}\\n'.format(tree, start_fid, end_fid) t.write(gc_cmd) out = t.read_until('\\n').strip('\\r\\n')",
"def exists(self, key): return bool(self.mc.get('?' + key)) def incr(self, key,",
"print \"key info mem:\", c.get_key_info_mem(k) print \"key info disk(ver, vhash,",
"i[1] >= 2: break result.append(i) return [x[0] for x in",
"port): s = get_gc_status(ip, port) if s and s.find('running') >=",
"0) prefix = kwargs.pop('prefix', None) if prefix is not None:",
"itertools.product(*[hex_digits for _ in range(db_depth)]) buckets = [''.join(i) for i",
"is None: self._check_last_error() return r, flag def get_multi(self, keys): r",
"if end_fid is None: gc_cmd = 'gc {} {}\\n'.format(tree, start_fid)",
"def test_new(addr, bucket): b = bucket c = DBClient(addr) print",
"def start_gc(self, bucket='', start_fid=0, end_fid=None): \"\"\" bucket must be in",
"= bucket % 16 result = store.get(cmd) if result: lines",
"content = '' return dir_to_dict(content) def list_dir(self, d): # FIXME:",
"\"000000\") print \"a dir leaf:\", leaf khash_str = list(leaf)[0] print",
"get_collision(self, bucket): check_bucket(bucket) collisions = defaultdict(dict) hint_data = self.get(\"@collision_all_%x\" %",
"\"0\") return self._is_old def get_collision_summary(self, bucket): check_bucket(bucket) raw = self.get(\"@collision_%x\"",
"3s c.config(libmc.MC_RETRY_TIMEOUT, 5) # 5s return c class MCStore(object): IGNORED_LIBMC_RET",
"t = telnetlib.Telnet(self.host, self.port) tree = '@%s' % bucket if",
"def list_dir(self, d): # FIXME: d should not need prefix",
"else: yield path, int(vhash), int(ver) def get_bucket_keys_count(self, bucket, depth=1): return",
"r[1], r[3:] print \"key info mem:\", c.get_key_info_mem(k) print \"key info",
"\"item_count:\", c.item_count() print \"primary_buckets\", get_primary_buckets(c) leaf = c.get_dir(\"@\" + b",
"def delete_multi(self, keys, return_failure=False): return self.mc.delete_multi(keys, return_failure=return_failure) def exists(self, key):",
"_dir.get(key, None) else: return _dir.get(\"%016x\" % khash64, None) def get_khash_info_mem(self,",
"def get_bucket_keys_count(store, bucket, depth=1): cmd = \"@\" sub = bucket",
"be in 0 or 00 string \"\"\" if bucket: assert",
"self._is_old is None: ver = self.get_server_version() self._is_old = (ver.strip().split(\".\")[0] ==",
"self.stats() if st: return st[\"version\"] except IOError: logging.error(\"fail to get",
"+ \"000000\") print \"a dir leaf:\", leaf khash_str = list(leaf)[0]",
"path[:-1]): yield v else: yield path, int(vhash), int(ver) def get_bucket_keys_count(self,",
"beansdbadmin.core.hint import parse_new_hint_body from beansdbadmin.core.data import parse_records from beansdbadmin.core.hash import",
"'OK' t.write('quit\\n') t.close() def start_gc_all_buckets(self, db_depth): hex_digits = string.digits +",
"leaf = c.get_dir(\"@\" + b + \"000000\") print \"a dir",
"r = self.mc.get(key) if r is None: self._check_last_error() return r",
"self.port) def get_version(self, key): meta = self.get(\"?\" + key) if",
"import logging import libmc import string import urllib import itertools",
"= [bucket_list[0]] for i in bucket_list[1:]: if result[-1][1] / i[1]",
"t.write(gc_cmd) out = t.read_until('\\n').strip('\\r\\n') assert out == 'OK' t.write('quit\\n') t.close()",
"logging.error(\"fail to get version %s\", self) except KeyError: logging.error(\"fail to",
"and len(bucket) <= 2 t = telnetlib.Telnet(self.host, self.port) tree =",
"cmd = \"@\" sub = bucket if depth == 2:",
"flag, vsz, ts, fid, pos''' info = store.get('??' + key)",
"self.addr = addr self.host, port = addr.split(\":\") self.port = int(port)",
"in dir_str.split('\\n') if x]: key_or_bucket, _hash, ver_or_count = line.split(' ')",
"isinstance(bucket, basestring) and len(bucket) <= 2 t = telnetlib.Telnet(self.host, self.port)",
"= int(port) self.mc = connect(addr) def __repr__(self): return '<MCStore(addr=%s)>' %",
"port = addr.split(\":\") self.port = int(port) self.mc = connect(addr) def",
"= store.get('??' + key) if info: return [int(x) for x",
"_, ver, vhash = meta collisions[khash_str][key] = (vhash, ver) return",
"%s %s\", self, st) def get_dir(self, path): ''' return dict",
"key) def prepare(self, data): return libmc.encode_value(data, self.mc.comp_threshold) def close(self): pass",
"return int(c) raise Exception('get %s from %s, reply = [%s],",
"<= bucket < 16 def dir_to_dict(dir_str): d = dict() if",
"buckets in integer \"\"\" ss = get_buckets_keys_count(store) bucket_list = ss.items()",
"in libmc.Client) 2. encapsulate @, ?, gc ... use is",
"self.get_records_by_khash_raw(khash_str) if raw: return parse_records(raw, False) else: return [] def",
"port) t.write('optimize_stat\\r\\n') out = t.read_until('\\n') t.write('quit\\r\\n') t.close() return out.strip(\"\\r\\n\") def",
"import libmc import string import urllib import itertools import warnings",
"hint_data = self.get(\"@collision_all_%x\" % bucket) if hint_data is None: return",
"stats(self): stats = self.mc.stats() return stats.values()[0] if stats else None",
"/ i[1] >= 2: break result.append(i) return [x[0] for x",
"2: break result.append(i) return [x[0] for x in result] def",
"[int(x) for x in info.split()] def is_gc_running(ip, port): s =",
"True: status = self.get_gc_status() if status.find('running') >= 0: continue elif",
"s = self.stats() if s is None: return None return",
"[(key, (vhash, ver))], key is \"\" for v2.''' khash32 =",
"need prefix @? '''list all KEY in the dir! not",
"self.is_old(): return [] if not isinstance(khash, str): khash = \"%016x\"",
"ver) or None''' if khash64 is None: khash64 = get_khash64(key)",
"self.get(\"@@\" + khash) def get_records_by_khash(self, khash_str): raw = self.get_records_by_khash_raw(khash_str) if",
"t.close() def start_gc_all_buckets(self, db_depth): hex_digits = string.digits + 'abcdef' buckets_iter",
"None: gc_cmd = 'gc {} {}\\n'.format(tree, start_fid) else: gc_cmd =",
"MCStore(object): IGNORED_LIBMC_RET = frozenset([ libmc.MC_RETURN_OK, libmc.MC_RETURN_INVALID_KEY_ERR ]) def __init__(self, addr):",
"'use douban.wrapper.Prefix instead.') c = libmc.Client([server], do_split=0, comp_threshold=comp_threshold, prefix=prefix) c.config(libmc.MC_CONNECT_TIMEOUT,",
"return self._is_old def get_collision_summary(self, bucket): check_bucket(bucket) raw = self.get(\"@collision_%x\" %",
"instead.') c = libmc.Client([server], do_split=0, comp_threshold=comp_threshold, prefix=prefix) c.config(libmc.MC_CONNECT_TIMEOUT, 300) #",
"int(data_size)) def get_collision(self, bucket): check_bucket(bucket) collisions = defaultdict(dict) hint_data =",
"len(line) == 0: continue d, _, c = line.split() if",
"t = telnetlib.Telnet(ip, port) t.write('optimize_stat\\r\\n') out = t.read_until('\\n') t.write('quit\\r\\n') t.close()",
"prefix=prefix) c.config(libmc.MC_CONNECT_TIMEOUT, 300) # 0.3s c.config(libmc.MC_POLL_TIMEOUT, 3000) # 3s c.config(libmc.MC_RETRY_TIMEOUT,",
"addr): MCStore.__init__(self, addr) self._is_old = None def stats(self): stats =",
"get_buckets_keys_count(store) bucket_list = ss.items() bucket_list = [x for x in",
"> 0] if not bucket_list: return None bucket_list.sort(lambda a, b:",
"return possible primary buckets, might be wrong on temporary nodes,",
"in the dir! not use it if dir is large!'''",
"sorted(self.get_dir(d).items()): if path.endswith('/') and len(path) == 2: for v in",
"b + \"000000\") print \"a dir leaf:\", leaf khash_str =",
"\"key info disk(ver, vhash, flag, vsz, ts, fid, pos):\", \\",
"if x]: key_or_bucket, _hash, ver_or_count = line.split(' ') d[key_or_bucket] =",
"= line.split(' ') if not d.endswith('/'): continue st[int(d[0], 16)] =",
"bucket): check_bucket(bucket) raw = self.get(\"@collision_%x\" % bucket) if raw is",
"(vhash, ver) return dict(collisions) def get_records_by_khash_raw(self, khash): if self.is_old(): return",
"\"@%08x\" % (khash >> 32) _dir = self.get_dir(khash32) ret =",
"bucket): b = bucket c = DBClient(addr) print \"stats:\", c.stats()",
"%s from %s, reply = [%s], bucket %x not found'",
"dir(0-f) to (hash, count), like {'0/': (1471, 27784005), ... },",
"addr.split(\":\") self.port = int(port) self.mc = connect(addr) def __repr__(self): return",
"in result] def get_key_info_disk(store, key): '''return ver, vhash, flag, vsz,",
"\"collision_summary\", c.get_collision_summary(int(b)) print \"gc status:\", c.get_gc_status() if __name__ == '__main__':",
"connect(server, **kwargs): comp_threshold = kwargs.pop('comp_threshold', 0) prefix = kwargs.pop('prefix', None)",
"b = bucket c = DBClient(addr) print \"stats:\", c.stats() print",
"try: content = self.get(path) except IOError: content = '' return",
"like {'0/': (1471, 27784005), ... }, case2: map key(or khash)",
"is list of buckets in integer \"\"\" ss = get_buckets_keys_count(store)",
"= self.mc.stats() return stats.values()[0] if stats else None def is_old(self):",
"stats.values()[0] if stats else None def is_old(self): if self._is_old is",
"content = self.get(path) except IOError: content = '' return dir_to_dict(content)",
"depth=1): cmd = \"@\" sub = bucket if depth ==",
"\"a dir leaf:\", leaf khash_str = list(leaf)[0] print \"a khash_str\",",
"fid, pos):\", \\ c.get_key_info_disk(k) print \"key version:\", c.get_version(k) print \"collision_summary\",",
"addr self.host, port = addr.split(\":\") self.port = int(port) self.mc =",
"return [x[0] for x in result] def get_key_info_disk(store, key): '''return",
"count, hcount, khash, data_size = raw.split() return (int(count), int(hcount), int(khash,",
"if rev < 0: raise Exception(str(rev)) return self.mc.set_raw(key, data, rev,",
"bucket < 16 def dir_to_dict(dir_str): d = dict() if dir_str:",
"# 0.3s c.config(libmc.MC_POLL_TIMEOUT, 3000) # 3s c.config(libmc.MC_RETRY_TIMEOUT, 5) # 5s",
"len(value), (flag, tstamp, ver):\", k, r[1], r[3:] print \"key info",
"is not None: warnings.warn('\"prefix\" is deprecated. ' 'use douban.wrapper.Prefix instead.')",
"32) _dir = self.get_dir(khash32) ret = [] if self.is_old(): for",
"r[0] print \"key, len(value), (flag, tstamp, ver):\", k, r[1], r[3:]",
"is instead of libmc.Client ''' import telnetlib import logging import",
"close(self): pass def test_new(addr, bucket): b = bucket c =",
"300) # 0.3s c.config(libmc.MC_POLL_TIMEOUT, 3000) # 3s c.config(libmc.MC_RETRY_TIMEOUT, 5) #",
"def start_gc_buckets(self, buckets): for b in buckets: self.start_gc(bucket=b) while True:",
"int(ver) def get_bucket_keys_count(self, bucket, depth=1): return get_bucket_keys_count(self, bucket, depth) def",
"pos''' info = store.get('??' + key) if info: return [int(x)",
"None: ver = self.get_server_version() self._is_old = (ver.strip().split(\".\")[0] == \"0\") return",
"in lines: if len(line) == 0: continue d, _, c",
"prefix is not None: warnings.warn('\"prefix\" is deprecated. ' 'use douban.wrapper.Prefix",
"import parse_records from beansdbadmin.core.hash import get_khash64 def get_url_content(url): return urllib.urlopen(url).read()",
"== sub: return int(c) raise Exception('get %s from %s, reply",
"False) else: return [] def start_gc(self, bucket='', start_fid=0, end_fid=None): \"\"\"",
"[x[0] for x in result] def get_key_info_disk(store, key): '''return ver,",
"(vhash, version), like {'3000000377e9c2ad': (22212, 1), ... }''' try: content",
"like {'3000000377e9c2ad': (22212, 1), ... }''' try: content = self.get(path)",
"= addr self.host, port = addr.split(\":\") self.port = int(port) self.mc",
"self.mc.delete(key) def get_raw(self, key): r, flag = self.mc.get_raw(key) if r",
"== \"0\") return self._is_old def get_collision_summary(self, bucket): check_bucket(bucket) raw =",
"key): '''return ver, vhash, flag, vsz, ts, fid, pos''' info",
"in parse_new_hint_body(hint_data): khash_str, _, ver, vhash = meta collisions[khash_str][key] =",
"out.strip(\"\\r\\n\") def connect(server, **kwargs): comp_threshold = kwargs.pop('comp_threshold', 0) prefix =",
"import itertools import warnings from collections import defaultdict from beansdbadmin.core.hint",
"key, data, rev=0): return bool(self.mc.set(key, data, rev)) def set_raw(self, key,",
"'''return ver, vhash, flag, vsz, ts, fid, pos''' return get_key_info_disk(self,",
"k, r[1], r[3:] print \"key info mem:\", c.get_key_info_mem(k) print \"key",
"vhash, flag, vsz, ts, fid, pos):\", \\ c.get_key_info_disk(k) print \"key",
"start_fid) else: gc_cmd = 'gc {} {} {}\\n'.format(tree, start_fid, end_fid)",
"end_fid) t.write(gc_cmd) out = t.read_until('\\n').strip('\\r\\n') assert out == 'OK' t.write('quit\\n')",
"_dir = self.get_dir(khash32) ret = [] if self.is_old(): for k,",
"bucket if depth == 2: cmd = \"@%x\" % (bucket/16)",
"rev=0): return bool(self.mc.set(key, data, rev)) def set_raw(self, key, data, rev=0,",
"IOError(last_err, self.mc.get_last_strerror()) def get(self, key): try: r = self.mc.get(key) if",
"data_size = raw.split() return (int(count), int(hcount), int(khash, 16), int(data_size)) def",
"logging import libmc import string import urllib import itertools import",
"st except IOError: raise Exception(\"cannot get @ from %s\" %",
"'<MCStore(addr=%s)>' % repr(self.addr) def __str__(self): return self.addr def set(self, key,",
"None: khash64 = get_khash64(key) khash32_str = \"@%08x\" % (khash64 >>",
"else: return _dir.get(\"%016x\" % khash64, None) def get_khash_info_mem(self, khash): '''",
"rev < 0: raise Exception(str(rev)) return self.mc.set_raw(key, data, rev, flag)",
"(hash, count), like {'0/': (1471, 27784005), ... }, case2: map",
"prefix = kwargs.pop('prefix', None) if prefix is not None: warnings.warn('\"prefix\"",
"= result.split('\\n') for line in lines: if len(line) == 0:",
"ver))) else: for k, (vhash, ver) in _dir.iteritems(): if int(k,",
"use is instead of libmc.Client ''' import telnetlib import logging",
"deprecated. ' 'use douban.wrapper.Prefix instead.') c = libmc.Client([server], do_split=0, comp_threshold=comp_threshold,",
"def get_key_info_disk(store, key): '''return ver, vhash, flag, vsz, ts, fid,",
"self.mc.get_last_strerror()) def get(self, key): try: r = self.mc.get(key) if r",
"def __init__(self, addr): self.addr = addr self.host, port = addr.split(\":\")",
"bucket) if raw is None: return None count, hcount, khash,",
"= get_khash64(key) khash32_str = \"@%08x\" % (khash64 >> 32) _dir",
"a, b: cmp(a[1], b[1]), reverse=True) result = [bucket_list[0]] for i",
"+ key)) def incr(self, key, value): return self.mc.incr(key, int(value)) class",
"print \"bucket key count:\", c.get_bucket_keys_count(int(b)) print \"item_count:\", c.item_count() print \"primary_buckets\",",
"ret.append((k, (vhash, ver))) else: for k, (vhash, ver) in _dir.iteritems():",
"= c.get_records_by_khash(khash_str)[0] k = r[0] print \"key, len(value), (flag, tstamp,",
"t.read_until('\\n').strip('\\r\\n') assert out == 'OK' t.write('quit\\n') t.close() def start_gc_all_buckets(self, db_depth):",
"return_failure=False): return self.mc.set_multi(values, return_failure=return_failure) def _check_last_error(self): last_err = self.mc.get_last_error() if",
"status.find('running') >= 0: continue elif status == 'success': print \"bucket",
"_, c = line.split() if d.endswith('/'): bucket_ = int(d[0], 16)",
"elif status == 'success': print \"bucket %s gc done\" %",
"khash32 = \"@%08x\" % (khash >> 32) _dir = self.get_dir(khash32)",
"% (khash >> 32) _dir = self.get_dir(khash32) ret = []",
"ver) in _dir.iteritems(): if get_khash64(k) == khash: ret.append((k, (vhash, ver)))",
"c = line.split() if d.endswith('/'): bucket_ = int(d[0], 16) if",
"x in result] def get_key_info_disk(store, key): '''return ver, vhash, flag,",
"assert isinstance(bucket, basestring) and len(bucket) <= 2 t = telnetlib.Telnet(self.host,",
"get_server_version(self): try: st = self.stats() if st: return st[\"version\"] except",
"get_primary_buckets(store): \"\"\" return possible primary buckets, might be wrong on",
"sub = bucket if depth == 2: cmd = \"@%x\"",
"for i in buckets_iter] self.start_gc_buckets(buckets) def start_gc_buckets(self, buckets): for b",
"\"isold:\", c.is_old() print \"dir root:\", c.get_dir(\"@\") print \"bucket key count:\",",
"self._is_old = None def stats(self): stats = self.mc.stats() return stats.values()[0]",
"list of buckets in integer \"\"\" ss = get_buckets_keys_count(store) bucket_list",
"int(port) self.mc = connect(addr) def __repr__(self): return '<MCStore(addr=%s)>' % repr(self.addr)",
"d): # FIXME: d should not need prefix @? '''list",
"(store)) def get_primary_buckets(store): \"\"\" return possible primary buckets, might be",
"khash): if self.is_old(): return [] if not isinstance(khash, str): khash",
"use it if dir is large!''' for path, (vhash, ver)",
"leaf:\", leaf khash_str = list(leaf)[0] print \"a khash_str\", khash_str r",
"key_or_bucket, _hash, ver_or_count = line.split(' ') d[key_or_bucket] = int(_hash) &",
"c = libmc.Client([server], do_split=0, comp_threshold=comp_threshold, prefix=prefix) c.config(libmc.MC_CONNECT_TIMEOUT, 300) # 0.3s",
"collisions[khash_str][key] = (vhash, ver) return dict(collisions) def get_records_by_khash_raw(self, khash): if",
"x in bucket_list if x[1] > 0] if not bucket_list:",
"return r except ValueError: self.mc.delete(key) def get_raw(self, key): r, flag",
"c.get_bucket_keys_count(int(b)) print \"item_count:\", c.item_count() print \"primary_buckets\", get_primary_buckets(c) leaf = c.get_dir(\"@\"",
"c = DBClient(addr) print \"stats:\", c.stats() print 'version:', c.get_server_version() print",
"FIXME: d should not need prefix @? '''list all KEY",
"khash64=None): ''' return (vhash, ver) or None''' if khash64 is",
"in self.list_dir(d + path[:-1]): yield v else: yield path, int(vhash),",
"return get_bucket_keys_count(self, bucket, depth) def get_key_info_disk(self, key): '''return ver, vhash,",
"1), ... }''' try: content = self.get(path) except IOError: content",
"result, bucket)) def get_buckets_keys_count(store): \"\"\" return dict: buckets -> count",
"if r is None: self._check_last_error() return r, flag def get_multi(self,",
"= self.get(\"@collision_%x\" % bucket) if raw is None: return None",
"== 2: for v in self.list_dir(d + path[:-1]): yield v",
"get version %s %s\", self, st) def get_dir(self, path): '''",
"self.list_dir(d + path[:-1]): yield v else: yield path, int(vhash), int(ver)",
"except IOError: raise Exception(\"cannot get @ from %s\" % (store))",
"store, result, bucket)) def get_buckets_keys_count(store): \"\"\" return dict: buckets ->",
"return parse_records(raw, False) else: return [] def start_gc(self, bucket='', start_fid=0,",
"def stats(self): stats = self.mc.stats() return stats.values()[0] if stats else",
"if prefix is not None: warnings.warn('\"prefix\" is deprecated. ' 'use",
"khash_str = list(leaf)[0] print \"a khash_str\", khash_str r = c.get_records_by_khash(khash_str)[0]",
"bucket)) def get_buckets_keys_count(store): \"\"\" return dict: buckets -> count \"\"\"",
"r is None: self._check_last_error() return r except ValueError: self.mc.delete(key) def",
"lines = result.split('\\n') for line in lines: if len(line) ==",
"(ver.strip().split(\".\")[0] == \"0\") return self._is_old def get_collision_summary(self, bucket): check_bucket(bucket) raw",
"get version %s\", self) except KeyError: logging.error(\"fail to get version",
"isinstance(khash, str): khash = \"%016x\" % khash return self.get(\"@@\" +",
"get_gc_status(self): return get_gc_status(self.host, self.port) def get_version(self, key): meta = self.get(\"?\"",
"line.split(' ') if not d.endswith('/'): continue st[int(d[0], 16)] = int(c)",
"not in self.IGNORED_LIBMC_RET: raise IOError(last_err, self.mc.get_last_strerror()) def get(self, key): try:",
"= self.get_records_by_khash_raw(khash_str) if raw: return parse_records(raw, False) else: return []",
"if not d.endswith('/'): continue st[int(d[0], 16)] = int(c) return st",
"self.mc.delete_multi(keys, return_failure=return_failure) def exists(self, key): return bool(self.mc.get('?' + key)) def",
"0.3s c.config(libmc.MC_POLL_TIMEOUT, 3000) # 3s c.config(libmc.MC_RETRY_TIMEOUT, 5) # 5s return",
"for one server (instead of multi like in libmc.Client) 2.",
"def __init__(self, addr): MCStore.__init__(self, addr) self._is_old = None def stats(self):",
"\"\"\" if bucket: assert isinstance(bucket, basestring) and len(bucket) <= 2",
"return _dir.get(key, None) else: return _dir.get(\"%016x\" % khash64, None) def",
"to get version %s\", self) except KeyError: logging.error(\"fail to get",
"not need prefix @? '''list all KEY in the dir!",
"if r is None: self._check_last_error() return r except ValueError: self.mc.delete(key)",
"= store.get(cmd) if result: lines = result.split('\\n') for line in",
"if result[-1][1] / i[1] >= 2: break result.append(i) return [x[0]",
"cmd = \"@%x\" % (bucket/16) sub = bucket % 16",
"if self.is_old(): return [] if not isinstance(khash, str): khash =",
"r, flag = self.mc.get_raw(key) if r is None: self._check_last_error() return",
"prefix @? '''list all KEY in the dir! not use",
"prepare(self, data): return libmc.encode_value(data, self.mc.comp_threshold) def close(self): pass def test_new(addr,",
"buckets): for b in buckets: self.start_gc(bucket=b) while True: status =",
"print \"key info disk(ver, vhash, flag, vsz, ts, fid, pos):\",",
"= self.mc.get_last_error() if last_err not in self.IGNORED_LIBMC_RET: raise IOError(last_err, self.mc.get_last_strerror())",
"= DBClient(addr) print \"stats:\", c.stats() print 'version:', c.get_server_version() print \"isold:\",",
"ts, fid, pos''' return get_key_info_disk(self, key) def prepare(self, data): return",
"might be wrong on temporary nodes, result is list of",
"result = [bucket_list[0]] for i in bucket_list[1:]: if result[-1][1] /",
"True return False def get_gc_status(ip, port): t = telnetlib.Telnet(ip, port)",
"in (store.get('@') or '').split('\\n'): if line: d, _, c =",
"r is None: self._check_last_error() return r, flag def get_multi(self, keys):",
"print \"a khash_str\", khash_str r = c.get_records_by_khash(khash_str)[0] k = r[0]",
"@? '''list all KEY in the dir! not use it",
"\"key version:\", c.get_version(k) print \"collision_summary\", c.get_collision_summary(int(b)) print \"gc status:\", c.get_gc_status()",
"defaultdict(dict) hint_data = self.get(\"@collision_all_%x\" % bucket) if hint_data is None:",
"sub: return int(c) raise Exception('get %s from %s, reply =",
"import warnings from collections import defaultdict from beansdbadmin.core.hint import parse_new_hint_body",
"in self.IGNORED_LIBMC_RET: raise IOError(last_err, self.mc.get_last_strerror()) def get(self, key): try: r",
"ver) return dict(collisions) def get_records_by_khash_raw(self, khash): if self.is_old(): return []",
"bucket='', start_fid=0, end_fid=None): \"\"\" bucket must be in 0 or",
"khash_str r = c.get_records_by_khash(khash_str)[0] k = r[0] print \"key, len(value),",
"string.digits + 'abcdef' buckets_iter = itertools.product(*[hex_digits for _ in range(db_depth)])",
"int(vhash), int(ver) def get_bucket_keys_count(self, bucket, depth=1): return get_bucket_keys_count(self, bucket, depth)",
"done\" % b break elif status == 'fail': return self.fail(\"optimize_stat",
"reply = [%s], bucket %x not found' % (cmd, store,",
"and len(path) == 2: for v in self.list_dir(d + path[:-1]):",
"comp_threshold = kwargs.pop('comp_threshold', 0) prefix = kwargs.pop('prefix', None) if prefix",
"int(d[0], 16) if bucket_ == sub: return int(c) raise Exception('get",
"path, (vhash, ver) in sorted(self.get_dir(d).items()): if path.endswith('/') and len(path) ==",
"multi like in libmc.Client) 2. encapsulate @, ?, gc ...",
"def get_collision_summary(self, bucket): check_bucket(bucket) raw = self.get(\"@collision_%x\" % bucket) if",
"= kwargs.pop('prefix', None) if prefix is not None: warnings.warn('\"prefix\" is",
"start_fid, end_fid) t.write(gc_cmd) out = t.read_until('\\n').strip('\\r\\n') assert out == 'OK'",
"None: warnings.warn('\"prefix\" is deprecated. ' 'use douban.wrapper.Prefix instead.') c =",
"__init__(self, addr): self.addr = addr self.host, port = addr.split(\":\") self.port",
"= self.get_gc_status() if status.find('running') >= 0: continue elif status ==",
"int(c) return st except IOError: raise Exception(\"cannot get @ from",
"out == 'OK' t.write('quit\\n') t.close() def start_gc_all_buckets(self, db_depth): hex_digits =",
"in sorted(self.get_dir(d).items()): if path.endswith('/') and len(path) == 2: for v",
"reverse=True) result = [bucket_list[0]] for i in bucket_list[1:]: if result[-1][1]",
"info mem:\", c.get_key_info_mem(k) print \"key info disk(ver, vhash, flag, vsz,",
"ret def get_server_version(self): try: st = self.stats() if st: return",
"self.get_server_version() self._is_old = (ver.strip().split(\".\")[0] == \"0\") return self._is_old def get_collision_summary(self,",
"result] def get_key_info_disk(store, key): '''return ver, vhash, flag, vsz, ts,",
"return out.strip(\"\\r\\n\") def connect(server, **kwargs): comp_threshold = kwargs.pop('comp_threshold', 0) prefix",
"key, khash64=None): ''' return (vhash, ver) or None''' if khash64",
"meta collisions[khash_str][key] = (vhash, ver) return dict(collisions) def get_records_by_khash_raw(self, khash):",
"for path, (vhash, ver) in sorted(self.get_dir(d).items()): if path.endswith('/') and len(path)",
"get_key_info_disk(self, key) def prepare(self, data): return libmc.encode_value(data, self.mc.comp_threshold) def close(self):",
"bucket_list = ss.items() bucket_list = [x for x in bucket_list",
"or '').split('\\n'): if line: d, _, c = line.split(' ')",
"check_bucket(bucket) collisions = defaultdict(dict) hint_data = self.get(\"@collision_all_%x\" % bucket) if",
"bucket_ == sub: return int(c) raise Exception('get %s from %s,",
"' 'use douban.wrapper.Prefix instead.') c = libmc.Client([server], do_split=0, comp_threshold=comp_threshold, prefix=prefix)",
"if s is None: return None return int(s['total_items']) def get_key_info_mem(self,",
"16 def dir_to_dict(dir_str): d = dict() if dir_str: for line",
"= get_buckets_keys_count(store) bucket_list = ss.items() bucket_list = [x for x",
"_ in parse_new_hint_body(hint_data): khash_str, _, ver, vhash = meta collisions[khash_str][key]",
"large!''' for path, (vhash, ver) in sorted(self.get_dir(d).items()): if path.endswith('/') and",
"continue st[int(d[0], 16)] = int(c) return st except IOError: raise",
"IOError: content = '' return dir_to_dict(content) def list_dir(self, d): #",
"count:\", c.get_bucket_keys_count(int(b)) print \"item_count:\", c.item_count() print \"primary_buckets\", get_primary_buckets(c) leaf =",
"(instead of multi like in libmc.Client) 2. encapsulate @, ?,",
"for x in result] def get_key_info_disk(store, key): '''return ver, vhash,",
"khash): ''' return [(key, (vhash, ver))], key is \"\" for",
"start_gc(self, bucket='', start_fid=0, end_fid=None): \"\"\" bucket must be in 0",
"self.fail(\"optimize_stat = fail\") else: self.fail(status) def get_gc_status(self): return get_gc_status(self.host, self.port)",
"case2: map key(or khash) to (vhash, version), like {'3000000377e9c2ad': (22212,",
"0: continue d, _, c = line.split() if d.endswith('/'): bucket_",
"pos''' return get_key_info_disk(self, key) def prepare(self, data): return libmc.encode_value(data, self.mc.comp_threshold)",
"for i in bucket_list[1:]: if result[-1][1] / i[1] >= 2:",
"def item_count(self): s = self.stats() if s is None: return",
"def dir_to_dict(dir_str): d = dict() if dir_str: for line in",
"if dir is large!''' for path, (vhash, ver) in sorted(self.get_dir(d).items()):",
"if meta: return int(meta.split()[0]) def item_count(self): s = self.stats() if",
"dict() if dir_str: for line in [x for x in",
"raw.split() return (int(count), int(hcount), int(khash, 16), int(data_size)) def get_collision(self, bucket):",
"tstamp, ver):\", k, r[1], r[3:] print \"key info mem:\", c.get_key_info_mem(k)",
"<filename>beansdbadmin/core/client.py #!/usr/bin/python # encoding: utf-8 '''a rich client 1. for",
"in buckets_iter] self.start_gc_buckets(buckets) def start_gc_buckets(self, buckets): for b in buckets:",
"if hint_data is None: return dict() for key, meta, _",
"\"bucket key count:\", c.get_bucket_keys_count(int(b)) print \"item_count:\", c.item_count() print \"primary_buckets\", get_primary_buckets(c)",
"0] if not bucket_list: return None bucket_list.sort(lambda a, b: cmp(a[1],",
"break elif status == 'fail': return self.fail(\"optimize_stat = fail\") else:",
"self.get(path) except IOError: content = '' return dir_to_dict(content) def list_dir(self,",
"return (int(count), int(hcount), int(khash, 16), int(data_size)) def get_collision(self, bucket): check_bucket(bucket)",
"s and s.find('running') >= 0: return True return False def",
"self.mc.get_multi(keys) self._check_last_error() return r def delete(self, key): return bool(self.mc.delete(key)) def",
"parse_records(raw, False) else: return [] def start_gc(self, bucket='', start_fid=0, end_fid=None):",
"\"dir root:\", c.get_dir(\"@\") print \"bucket key count:\", c.get_bucket_keys_count(int(b)) print \"item_count:\",",
"disk(ver, vhash, flag, vsz, ts, fid, pos):\", \\ c.get_key_info_disk(k) print",
"get_raw(self, key): r, flag = self.mc.get_raw(key) if r is None:",
"end_fid=None): \"\"\" bucket must be in 0 or 00 string",
"c.stats() print 'version:', c.get_server_version() print \"isold:\", c.is_old() print \"dir root:\",",
"range(db_depth)]) buckets = [''.join(i) for i in buckets_iter] self.start_gc_buckets(buckets) def",
"0: continue elif status == 'success': print \"bucket %s gc",
"bucket: assert isinstance(bucket, basestring) and len(bucket) <= 2 t =",
"_dir = self.get_dir(khash32_str) if self.is_old(): return _dir.get(key, None) else: return",
"assert out == 'OK' t.write('quit\\n') t.close() def start_gc_all_buckets(self, db_depth): hex_digits",
"+ path[:-1]): yield v else: yield path, int(vhash), int(ver) def",
"3000) # 3s c.config(libmc.MC_RETRY_TIMEOUT, 5) # 5s return c class",
"import string import urllib import itertools import warnings from collections",
"itertools import warnings from collections import defaultdict from beansdbadmin.core.hint import",
"0xffff, int(ver_or_count) return d def get_bucket_keys_count(store, bucket, depth=1): cmd =",
"{'3000000377e9c2ad': (22212, 1), ... }''' try: content = self.get(path) except",
"if d.endswith('/'): bucket_ = int(d[0], 16) if bucket_ == sub:",
"raw = self.get_records_by_khash_raw(khash_str) if raw: return parse_records(raw, False) else: return",
"= c.get_dir(\"@\" + b + \"000000\") print \"a dir leaf:\",",
"return r, flag def get_multi(self, keys): r = self.mc.get_multi(keys) self._check_last_error()",
"(khash64 >> 32) _dir = self.get_dir(khash32_str) if self.is_old(): return _dir.get(key,",
"**kwargs): comp_threshold = kwargs.pop('comp_threshold', 0) prefix = kwargs.pop('prefix', None) if",
"= meta collisions[khash_str][key] = (vhash, ver) return dict(collisions) def get_records_by_khash_raw(self,",
"khash: return [(\"\", (int(vhash), ver))] return ret def get_server_version(self): try:",
"def check_bucket(bucket): assert 0 <= bucket < 16 def dir_to_dict(dir_str):",
"self.mc.set_raw(key, data, rev, flag) def set_multi(self, values, return_failure=False): return self.mc.set_multi(values,",
"return self.mc.incr(key, int(value)) class DBClient(MCStore): def __init__(self, addr): MCStore.__init__(self, addr)",
"(khash >> 32) _dir = self.get_dir(khash32) ret = [] if",
"d = dict() if dir_str: for line in [x for",
"in [x for x in dir_str.split('\\n') if x]: key_or_bucket, _hash,",
"def _check_last_error(self): last_err = self.mc.get_last_error() if last_err not in self.IGNORED_LIBMC_RET:",
"int(meta.split()[0]) def item_count(self): s = self.stats() if s is None:",
"repr(self.addr) def __str__(self): return self.addr def set(self, key, data, rev=0):",
"depth) def get_key_info_disk(self, key): '''return ver, vhash, flag, vsz, ts,",
"for line in [x for x in dir_str.split('\\n') if x]:",
"return _dir.get(\"%016x\" % khash64, None) def get_khash_info_mem(self, khash): ''' return",
"in info.split()] def is_gc_running(ip, port): s = get_gc_status(ip, port) if",
"return_failure=return_failure) def _check_last_error(self): last_err = self.mc.get_last_error() if last_err not in",
"def set(self, key, data, rev=0): return bool(self.mc.set(key, data, rev)) def",
"libmc.MC_RETURN_OK, libmc.MC_RETURN_INVALID_KEY_ERR ]) def __init__(self, addr): self.addr = addr self.host,",
"self._is_old = (ver.strip().split(\".\")[0] == \"0\") return self._is_old def get_collision_summary(self, bucket):",
"return int(meta.split()[0]) def item_count(self): s = self.stats() if s is",
"count), like {'0/': (1471, 27784005), ... }, case2: map key(or",
"test_new(addr, bucket): b = bucket c = DBClient(addr) print \"stats:\",",
"else: gc_cmd = 'gc {} {} {}\\n'.format(tree, start_fid, end_fid) t.write(gc_cmd)",
"%s\", self) except KeyError: logging.error(\"fail to get version %s %s\",",
"int(khash, 16), int(data_size)) def get_collision(self, bucket): check_bucket(bucket) collisions = defaultdict(dict)",
"it if dir is large!''' for path, (vhash, ver) in",
"%s\" % (store)) def get_primary_buckets(store): \"\"\" return possible primary buckets,",
"key, data, rev=0, flag=0): if rev < 0: raise Exception(str(rev))",
"flag = self.mc.get_raw(key) if r is None: self._check_last_error() return r,",
"for v2.''' khash32 = \"@%08x\" % (khash >> 32) _dir",
"def get_dir(self, path): ''' return dict case1: map dir(0-f) to",
"ver):\", k, r[1], r[3:] print \"key info mem:\", c.get_key_info_mem(k) print",
"if dir_str: for line in [x for x in dir_str.split('\\n')",
"print \"key version:\", c.get_version(k) print \"collision_summary\", c.get_collision_summary(int(b)) print \"gc status:\",",
"= string.digits + 'abcdef' buckets_iter = itertools.product(*[hex_digits for _ in",
"len(path) == 2: for v in self.list_dir(d + path[:-1]): yield",
"result.split('\\n') for line in lines: if len(line) == 0: continue",
"khash_str, _, ver, vhash = meta collisions[khash_str][key] = (vhash, ver)",
"def get(self, key): try: r = self.mc.get(key) if r is",
"key(or khash) to (vhash, version), like {'3000000377e9c2ad': (22212, 1), ...",
"self.fail(status) def get_gc_status(self): return get_gc_status(self.host, self.port) def get_version(self, key): meta",
"int(ver_or_count) return d def get_bucket_keys_count(store, bucket, depth=1): cmd = \"@\"",
"info.split()] def is_gc_running(ip, port): s = get_gc_status(ip, port) if s",
"if int(k, 16) == khash: return [(\"\", (int(vhash), ver))] return",
"get_khash64 def get_url_content(url): return urllib.urlopen(url).read() def check_bucket(bucket): assert 0 <=",
"ver) in sorted(self.get_dir(d).items()): if path.endswith('/') and len(path) == 2: for",
"= [''.join(i) for i in buckets_iter] self.start_gc_buckets(buckets) def start_gc_buckets(self, buckets):",
"in 0 or 00 string \"\"\" if bucket: assert isinstance(bucket,",
"s is None: return None return int(s['total_items']) def get_key_info_mem(self, key,",
"% repr(self.addr) def __str__(self): return self.addr def set(self, key, data,",
"continue d, _, c = line.split() if d.endswith('/'): bucket_ =",
"if last_err not in self.IGNORED_LIBMC_RET: raise IOError(last_err, self.mc.get_last_strerror()) def get(self,",
"utf-8 '''a rich client 1. for one server (instead of",
"< 0: raise Exception(str(rev)) return self.mc.set_raw(key, data, rev, flag) def",
"print \"isold:\", c.is_old() print \"dir root:\", c.get_dir(\"@\") print \"bucket key",
"if self.is_old(): for k, (vhash, ver) in _dir.iteritems(): if get_khash64(k)",
"c.get_dir(\"@\") print \"bucket key count:\", c.get_bucket_keys_count(int(b)) print \"item_count:\", c.item_count() print",
"flag, vsz, ts, fid, pos):\", \\ c.get_key_info_disk(k) print \"key version:\",",
"raise Exception(\"cannot get @ from %s\" % (store)) def get_primary_buckets(store):",
"start_gc_all_buckets(self, db_depth): hex_digits = string.digits + 'abcdef' buckets_iter = itertools.product(*[hex_digits",
"value): return self.mc.incr(key, int(value)) class DBClient(MCStore): def __init__(self, addr): MCStore.__init__(self,",
"32) _dir = self.get_dir(khash32_str) if self.is_old(): return _dir.get(key, None) else:",
"\"%016x\" % khash return self.get(\"@@\" + khash) def get_records_by_khash(self, khash_str):",
"if x[1] > 0] if not bucket_list: return None bucket_list.sort(lambda",
"return self.mc.set_raw(key, data, rev, flag) def set_multi(self, values, return_failure=False): return",
"status == 'fail': return self.fail(\"optimize_stat = fail\") else: self.fail(status) def",
"urllib import itertools import warnings from collections import defaultdict from",
"for line in (store.get('@') or '').split('\\n'): if line: d, _,",
"fid, pos''' info = store.get('??' + key) if info: return",
"= [x for x in bucket_list if x[1] > 0]",
"of buckets in integer \"\"\" ss = get_buckets_keys_count(store) bucket_list =",
"0: raise Exception(str(rev)) return self.mc.set_raw(key, data, rev, flag) def set_multi(self,",
"== 'OK' t.write('quit\\n') t.close() def start_gc_all_buckets(self, db_depth): hex_digits = string.digits",
"return ret def get_server_version(self): try: st = self.stats() if st:",
"self.host, port = addr.split(\":\") self.port = int(port) self.mc = connect(addr)",
"def start_gc_all_buckets(self, db_depth): hex_digits = string.digits + 'abcdef' buckets_iter =",
"_dir.iteritems(): if get_khash64(k) == khash: ret.append((k, (vhash, ver))) else: for",
"= int(d[0], 16) if bucket_ == sub: return int(c) raise",
"ss = get_buckets_keys_count(store) bucket_list = ss.items() bucket_list = [x for",
"b: cmp(a[1], b[1]), reverse=True) result = [bucket_list[0]] for i in",
"''' return (vhash, ver) or None''' if khash64 is None:",
"wrong on temporary nodes, result is list of buckets in",
"= bucket if depth == 2: cmd = \"@%x\" %",
"self._check_last_error() return r def delete(self, key): return bool(self.mc.delete(key)) def delete_multi(self,",
"bool(self.mc.set(key, data, rev)) def set_raw(self, key, data, rev=0, flag=0): if",
"khash64, None) def get_khash_info_mem(self, khash): ''' return [(key, (vhash, ver))],",
"khash) def get_records_by_khash(self, khash_str): raw = self.get_records_by_khash_raw(khash_str) if raw: return",
"self.get_dir(khash32) ret = [] if self.is_old(): for k, (vhash, ver)",
"khash) to (vhash, version), like {'3000000377e9c2ad': (22212, 1), ... }'''",
"x in dir_str.split('\\n') if x]: key_or_bucket, _hash, ver_or_count = line.split('",
"get_records_by_khash(self, khash_str): raw = self.get_records_by_khash_raw(khash_str) if raw: return parse_records(raw, False)",
"ver))], key is \"\" for v2.''' khash32 = \"@%08x\" %",
"= self.get(path) except IOError: content = '' return dir_to_dict(content) def",
"if status.find('running') >= 0: continue elif status == 'success': print",
"... use is instead of libmc.Client ''' import telnetlib import",
"d def get_bucket_keys_count(store, bucket, depth=1): cmd = \"@\" sub =",
"result.append(i) return [x[0] for x in result] def get_key_info_disk(store, key):",
"v2.''' khash32 = \"@%08x\" % (khash >> 32) _dir =",
"for k, (vhash, ver) in _dir.iteritems(): if get_khash64(k) == khash:",
"'''list all KEY in the dir! not use it if",
"= int(c) return st except IOError: raise Exception(\"cannot get @",
"}''' try: content = self.get(path) except IOError: content = ''",
"') d[key_or_bucket] = int(_hash) & 0xffff, int(ver_or_count) return d def",
"telnetlib.Telnet(ip, port) t.write('optimize_stat\\r\\n') out = t.read_until('\\n') t.write('quit\\r\\n') t.close() return out.strip(\"\\r\\n\")",
"khash: ret.append((k, (vhash, ver))) else: for k, (vhash, ver) in",
"\"\"\" bucket must be in 0 or 00 string \"\"\"",
"print 'version:', c.get_server_version() print \"isold:\", c.is_old() print \"dir root:\", c.get_dir(\"@\")",
"possible primary buckets, might be wrong on temporary nodes, result",
"= self.get_dir(khash32) ret = [] if self.is_old(): for k, (vhash,",
"_ in range(db_depth)]) buckets = [''.join(i) for i in buckets_iter]",
"except ValueError: self.mc.delete(key) def get_raw(self, key): r, flag = self.mc.get_raw(key)",
"0 <= bucket < 16 def dir_to_dict(dir_str): d = dict()",
"in integer \"\"\" ss = get_buckets_keys_count(store) bucket_list = ss.items() bucket_list",
"5s return c class MCStore(object): IGNORED_LIBMC_RET = frozenset([ libmc.MC_RETURN_OK, libmc.MC_RETURN_INVALID_KEY_ERR",
"= int(_hash) & 0xffff, int(ver_or_count) return d def get_bucket_keys_count(store, bucket,",
"return bool(self.mc.delete(key)) def delete_multi(self, keys, return_failure=False): return self.mc.delete_multi(keys, return_failure=return_failure) def",
"hcount, khash, data_size = raw.split() return (int(count), int(hcount), int(khash, 16),",
"'@%s' % bucket if end_fid is None: gc_cmd = 'gc",
"meta: return int(meta.split()[0]) def item_count(self): s = self.stats() if s",
"return None return int(s['total_items']) def get_key_info_mem(self, key, khash64=None): ''' return",
"else: self.fail(status) def get_gc_status(self): return get_gc_status(self.host, self.port) def get_version(self, key):",
"st) def get_dir(self, path): ''' return dict case1: map dir(0-f)",
"last_err not in self.IGNORED_LIBMC_RET: raise IOError(last_err, self.mc.get_last_strerror()) def get(self, key):",
"2: for v in self.list_dir(d + path[:-1]): yield v else:",
"@ from %s\" % (store)) def get_primary_buckets(store): \"\"\" return possible",
"if not isinstance(khash, str): khash = \"%016x\" % khash return",
"gc done\" % b break elif status == 'fail': return",
"ver) in _dir.iteritems(): if int(k, 16) == khash: return [(\"\",",
"get_gc_status(ip, port) if s and s.find('running') >= 0: return True",
"dict(collisions) def get_records_by_khash_raw(self, khash): if self.is_old(): return [] if not",
"tree = '@%s' % bucket if end_fid is None: gc_cmd",
"return dict() for key, meta, _ in parse_new_hint_body(hint_data): khash_str, _,",
"buckets = [''.join(i) for i in buckets_iter] self.start_gc_buckets(buckets) def start_gc_buckets(self,",
"item_count(self): s = self.stats() if s is None: return None",
"_dir.get(\"%016x\" % khash64, None) def get_khash_info_mem(self, khash): ''' return [(key,",
"to get version %s %s\", self, st) def get_dir(self, path):",
"version %s\", self) except KeyError: logging.error(\"fail to get version %s",
"path): ''' return dict case1: map dir(0-f) to (hash, count),",
"key, value): return self.mc.incr(key, int(value)) class DBClient(MCStore): def __init__(self, addr):",
"== khash: return [(\"\", (int(vhash), ver))] return ret def get_server_version(self):",
"self.get_gc_status() if status.find('running') >= 0: continue elif status == 'success':",
"libmc.Client) 2. encapsulate @, ?, gc ... use is instead",
"warnings from collections import defaultdict from beansdbadmin.core.hint import parse_new_hint_body from",
"key) if info: return [int(x) for x in info.split()] def",
"depth=1): return get_bucket_keys_count(self, bucket, depth) def get_key_info_disk(self, key): '''return ver,",
"return [] def start_gc(self, bucket='', start_fid=0, end_fid=None): \"\"\" bucket must",
"for x in info.split()] def is_gc_running(ip, port): s = get_gc_status(ip,",
"fid, pos''' return get_key_info_disk(self, key) def prepare(self, data): return libmc.encode_value(data,",
">> 32) _dir = self.get_dir(khash32_str) if self.is_old(): return _dir.get(key, None)",
"\"\"\" return dict: buckets -> count \"\"\" st = {}",
"c class MCStore(object): IGNORED_LIBMC_RET = frozenset([ libmc.MC_RETURN_OK, libmc.MC_RETURN_INVALID_KEY_ERR ]) def",
"if info: return [int(x) for x in info.split()] def is_gc_running(ip,",
"data, rev=0, flag=0): if rev < 0: raise Exception(str(rev)) return",
"ss.items() bucket_list = [x for x in bucket_list if x[1]",
"in bucket_list if x[1] > 0] if not bucket_list: return",
"\"@%08x\" % (khash64 >> 32) _dir = self.get_dir(khash32_str) if self.is_old():",
"frozenset([ libmc.MC_RETURN_OK, libmc.MC_RETURN_INVALID_KEY_ERR ]) def __init__(self, addr): self.addr = addr",
"flag) def set_multi(self, values, return_failure=False): return self.mc.set_multi(values, return_failure=return_failure) def _check_last_error(self):",
"b break elif status == 'fail': return self.fail(\"optimize_stat = fail\")",
"self.mc.get_raw(key) if r is None: self._check_last_error() return r, flag def",
"get @ from %s\" % (store)) def get_primary_buckets(store): \"\"\" return",
"key, meta, _ in parse_new_hint_body(hint_data): khash_str, _, ver, vhash =",
"% bucket if end_fid is None: gc_cmd = 'gc {}",
"print \"a dir leaf:\", leaf khash_str = list(leaf)[0] print \"a",
"class MCStore(object): IGNORED_LIBMC_RET = frozenset([ libmc.MC_RETURN_OK, libmc.MC_RETURN_INVALID_KEY_ERR ]) def __init__(self,",
"return self.mc.delete_multi(keys, return_failure=return_failure) def exists(self, key): return bool(self.mc.get('?' + key))",
"get_primary_buckets(c) leaf = c.get_dir(\"@\" + b + \"000000\") print \"a",
"{}\\n'.format(tree, start_fid, end_fid) t.write(gc_cmd) out = t.read_until('\\n').strip('\\r\\n') assert out ==",
"info: return [int(x) for x in info.split()] def is_gc_running(ip, port):",
"string \"\"\" if bucket: assert isinstance(bucket, basestring) and len(bucket) <=",
"urllib.urlopen(url).read() def check_bucket(bucket): assert 0 <= bucket < 16 def",
"+ khash) def get_records_by_khash(self, khash_str): raw = self.get_records_by_khash_raw(khash_str) if raw:",
"buckets: self.start_gc(bucket=b) while True: status = self.get_gc_status() if status.find('running') >=",
"= '@%s' % bucket if end_fid is None: gc_cmd =",
"'' return dir_to_dict(content) def list_dir(self, d): # FIXME: d should",
"(bucket/16) sub = bucket % 16 result = store.get(cmd) if",
"{'0/': (1471, 27784005), ... }, case2: map key(or khash) to",
"_hash, ver_or_count = line.split(' ') d[key_or_bucket] = int(_hash) & 0xffff,",
"key): return bool(self.mc.delete(key)) def delete_multi(self, keys, return_failure=False): return self.mc.delete_multi(keys, return_failure=return_failure)",
"= t.read_until('\\n').strip('\\r\\n') assert out == 'OK' t.write('quit\\n') t.close() def start_gc_all_buckets(self,",
"(cmd, store, result, bucket)) def get_buckets_keys_count(store): \"\"\" return dict: buckets",
"'fail': return self.fail(\"optimize_stat = fail\") else: self.fail(status) def get_gc_status(self): return",
"}, case2: map key(or khash) to (vhash, version), like {'3000000377e9c2ad':",
"= fail\") else: self.fail(status) def get_gc_status(self): return get_gc_status(self.host, self.port) def",
"self.mc.get_last_error() if last_err not in self.IGNORED_LIBMC_RET: raise IOError(last_err, self.mc.get_last_strerror()) def",
"keys, return_failure=False): return self.mc.delete_multi(keys, return_failure=return_failure) def exists(self, key): return bool(self.mc.get('?'",
"cmp(a[1], b[1]), reverse=True) result = [bucket_list[0]] for i in bucket_list[1:]:",
"None def is_old(self): if self._is_old is None: ver = self.get_server_version()",
"return [(\"\", (int(vhash), ver))] return ret def get_server_version(self): try: st",
"int(_hash) & 0xffff, int(ver_or_count) return d def get_bucket_keys_count(store, bucket, depth=1):",
"= None def stats(self): stats = self.mc.stats() return stats.values()[0] if",
"# encoding: utf-8 '''a rich client 1. for one server",
"line in (store.get('@') or '').split('\\n'): if line: d, _, c",
"# FIXME: d should not need prefix @? '''list all",
"return get_gc_status(self.host, self.port) def get_version(self, key): meta = self.get(\"?\" +",
"[] if self.is_old(): for k, (vhash, ver) in _dir.iteritems(): if",
"bucket, depth=1): return get_bucket_keys_count(self, bucket, depth) def get_key_info_disk(self, key): '''return",
"def close(self): pass def test_new(addr, bucket): b = bucket c",
"libmc.MC_RETURN_INVALID_KEY_ERR ]) def __init__(self, addr): self.addr = addr self.host, port",
"def get_buckets_keys_count(store): \"\"\" return dict: buckets -> count \"\"\" st",
"16)] = int(c) return st except IOError: raise Exception(\"cannot get",
"bucket_list if x[1] > 0] if not bucket_list: return None",
"be wrong on temporary nodes, result is list of buckets",
"= \"@%08x\" % (khash >> 32) _dir = self.get_dir(khash32) ret",
"def get_key_info_mem(self, key, khash64=None): ''' return (vhash, ver) or None'''",
"stats else None def is_old(self): if self._is_old is None: ver",
"_dir.iteritems(): if int(k, 16) == khash: return [(\"\", (int(vhash), ver))]",
"\"@%x\" % (bucket/16) sub = bucket % 16 result =",
"c.config(libmc.MC_CONNECT_TIMEOUT, 300) # 0.3s c.config(libmc.MC_POLL_TIMEOUT, 3000) # 3s c.config(libmc.MC_RETRY_TIMEOUT, 5)",
"self._is_old def get_collision_summary(self, bucket): check_bucket(bucket) raw = self.get(\"@collision_%x\" % bucket)",
"start_fid=0, end_fid=None): \"\"\" bucket must be in 0 or 00",
"key): r, flag = self.mc.get_raw(key) if r is None: self._check_last_error()",
"stats = self.mc.stats() return stats.values()[0] if stats else None def",
"print \"primary_buckets\", get_primary_buckets(c) leaf = c.get_dir(\"@\" + b + \"000000\")",
"2: cmd = \"@%x\" % (bucket/16) sub = bucket %",
"dir_str.split('\\n') if x]: key_or_bucket, _hash, ver_or_count = line.split(' ') d[key_or_bucket]",
"get_url_content(url): return urllib.urlopen(url).read() def check_bucket(bucket): assert 0 <= bucket <",
"None''' if khash64 is None: khash64 = get_khash64(key) khash32_str =",
"print \"collision_summary\", c.get_collision_summary(int(b)) print \"gc status:\", c.get_gc_status() if __name__ ==",
"def get_bucket_keys_count(self, bucket, depth=1): return get_bucket_keys_count(self, bucket, depth) def get_key_info_disk(self,",
"5) # 5s return c class MCStore(object): IGNORED_LIBMC_RET = frozenset([",
"is \"\" for v2.''' khash32 = \"@%08x\" % (khash >>",
"like in libmc.Client) 2. encapsulate @, ?, gc ... use",
"\"@\" sub = bucket if depth == 2: cmd =",
"d, _, c = line.split(' ') if not d.endswith('/'): continue",
"2. encapsulate @, ?, gc ... use is instead of",
"= line.split() if d.endswith('/'): bucket_ = int(d[0], 16) if bucket_",
"key): meta = self.get(\"?\" + key) if meta: return int(meta.split()[0])",
"elif status == 'fail': return self.fail(\"optimize_stat = fail\") else: self.fail(status)",
"= \"@%x\" % (bucket/16) sub = bucket % 16 result",
"import telnetlib import logging import libmc import string import urllib",
"if self._is_old is None: ver = self.get_server_version() self._is_old = (ver.strip().split(\".\")[0]",
"def get_url_content(url): return urllib.urlopen(url).read() def check_bucket(bucket): assert 0 <= bucket",
"raw: return parse_records(raw, False) else: return [] def start_gc(self, bucket='',",
"== khash: ret.append((k, (vhash, ver))) else: for k, (vhash, ver)",
"bucket, depth=1): cmd = \"@\" sub = bucket if depth",
"== 'success': print \"bucket %s gc done\" % b break",
"def get_multi(self, keys): r = self.mc.get_multi(keys) self._check_last_error() return r def",
"encoding: utf-8 '''a rich client 1. for one server (instead",
"return (vhash, ver) or None''' if khash64 is None: khash64",
"r, flag def get_multi(self, keys): r = self.mc.get_multi(keys) self._check_last_error() return",
">= 0: continue elif status == 'success': print \"bucket %s",
"of multi like in libmc.Client) 2. encapsulate @, ?, gc",
"k = r[0] print \"key, len(value), (flag, tstamp, ver):\", k,",
"key) if meta: return int(meta.split()[0]) def item_count(self): s = self.stats()",
"for x in bucket_list if x[1] > 0] if not",
"out = t.read_until('\\n').strip('\\r\\n') assert out == 'OK' t.write('quit\\n') t.close() def",
"def incr(self, key, value): return self.mc.incr(key, int(value)) class DBClient(MCStore): def",
"False def get_gc_status(ip, port): t = telnetlib.Telnet(ip, port) t.write('optimize_stat\\r\\n') out",
"if get_khash64(k) == khash: ret.append((k, (vhash, ver))) else: for k,",
"print \"gc status:\", c.get_gc_status() if __name__ == '__main__': test_new(\"rosa3a:7900\", '3')",
"return [] if not isinstance(khash, str): khash = \"%016x\" %",
"status == 'success': print \"bucket %s gc done\" % b",
"print \"bucket %s gc done\" % b break elif status",
"meta = self.get(\"?\" + key) if meta: return int(meta.split()[0]) def",
"\"key info mem:\", c.get_key_info_mem(k) print \"key info disk(ver, vhash, flag,",
"import get_khash64 def get_url_content(url): return urllib.urlopen(url).read() def check_bucket(bucket): assert 0",
"+ key) if info: return [int(x) for x in info.split()]",
"= libmc.Client([server], do_split=0, comp_threshold=comp_threshold, prefix=prefix) c.config(libmc.MC_CONNECT_TIMEOUT, 300) # 0.3s c.config(libmc.MC_POLL_TIMEOUT,",
"int(value)) class DBClient(MCStore): def __init__(self, addr): MCStore.__init__(self, addr) self._is_old =",
"except KeyError: logging.error(\"fail to get version %s %s\", self, st)",
"bucket if end_fid is None: gc_cmd = 'gc {} {}\\n'.format(tree,",
"self.is_old(): return _dir.get(key, None) else: return _dir.get(\"%016x\" % khash64, None)",
"get_khash64(key) khash32_str = \"@%08x\" % (khash64 >> 32) _dir =",
"instead of libmc.Client ''' import telnetlib import logging import libmc",
"list(leaf)[0] print \"a khash_str\", khash_str r = c.get_records_by_khash(khash_str)[0] k =",
"k, (vhash, ver) in _dir.iteritems(): if get_khash64(k) == khash: ret.append((k,",
"DBClient(addr) print \"stats:\", c.stats() print 'version:', c.get_server_version() print \"isold:\", c.is_old()",
"v in self.list_dir(d + path[:-1]): yield v else: yield path,",
"= t.read_until('\\n') t.write('quit\\r\\n') t.close() return out.strip(\"\\r\\n\") def connect(server, **kwargs): comp_threshold",
"[x for x in dir_str.split('\\n') if x]: key_or_bucket, _hash, ver_or_count",
"connect(addr) def __repr__(self): return '<MCStore(addr=%s)>' % repr(self.addr) def __str__(self): return",
"from %s\" % (store)) def get_primary_buckets(store): \"\"\" return possible primary",
"r = self.mc.get_multi(keys) self._check_last_error() return r def delete(self, key): return",
"ver, vhash, flag, vsz, ts, fid, pos''' info = store.get('??'",
"result = store.get(cmd) if result: lines = result.split('\\n') for line",
"= ss.items() bucket_list = [x for x in bucket_list if",
"return st except IOError: raise Exception(\"cannot get @ from %s\"",
"'''return ver, vhash, flag, vsz, ts, fid, pos''' info =",
"st[int(d[0], 16)] = int(c) return st except IOError: raise Exception(\"cannot",
"get_khash_info_mem(self, khash): ''' return [(key, (vhash, ver))], key is \"\"",
"st: return st[\"version\"] except IOError: logging.error(\"fail to get version %s\",",
"is_gc_running(ip, port): s = get_gc_status(ip, port) if s and s.find('running')",
"def get_raw(self, key): r, flag = self.mc.get_raw(key) if r is",
"+ 'abcdef' buckets_iter = itertools.product(*[hex_digits for _ in range(db_depth)]) buckets",
"c.get_server_version() print \"isold:\", c.is_old() print \"dir root:\", c.get_dir(\"@\") print \"bucket",
"= self.get(\"?\" + key) if meta: return int(meta.split()[0]) def item_count(self):",
"c.get_dir(\"@\" + b + \"000000\") print \"a dir leaf:\", leaf",
"= (ver.strip().split(\".\")[0] == \"0\") return self._is_old def get_collision_summary(self, bucket): check_bucket(bucket)",
"None: self._check_last_error() return r, flag def get_multi(self, keys): r =",
"def prepare(self, data): return libmc.encode_value(data, self.mc.comp_threshold) def close(self): pass def",
"self.mc = connect(addr) def __repr__(self): return '<MCStore(addr=%s)>' % repr(self.addr) def",
"== 2: cmd = \"@%x\" % (bucket/16) sub = bucket",
"temporary nodes, result is list of buckets in integer \"\"\"",
"return urllib.urlopen(url).read() def check_bucket(bucket): assert 0 <= bucket < 16",
"return_failure=False): return self.mc.delete_multi(keys, return_failure=return_failure) def exists(self, key): return bool(self.mc.get('?' +",
"ver))] return ret def get_server_version(self): try: st = self.stats() if",
"(vhash, ver))], key is \"\" for v2.''' khash32 = \"@%08x\"",
"= {} try: for line in (store.get('@') or '').split('\\n'): if",
"r def delete(self, key): return bool(self.mc.delete(key)) def delete_multi(self, keys, return_failure=False):",
"key is \"\" for v2.''' khash32 = \"@%08x\" % (khash",
"ver_or_count = line.split(' ') d[key_or_bucket] = int(_hash) & 0xffff, int(ver_or_count)",
"depth == 2: cmd = \"@%x\" % (bucket/16) sub =",
"is large!''' for path, (vhash, ver) in sorted(self.get_dir(d).items()): if path.endswith('/')",
"ver = self.get_server_version() self._is_old = (ver.strip().split(\".\")[0] == \"0\") return self._is_old",
"self.start_gc_buckets(buckets) def start_gc_buckets(self, buckets): for b in buckets: self.start_gc(bucket=b) while",
"kwargs.pop('comp_threshold', 0) prefix = kwargs.pop('prefix', None) if prefix is not",
"b[1]), reverse=True) result = [bucket_list[0]] for i in bucket_list[1:]: if",
">= 0: return True return False def get_gc_status(ip, port): t",
"vhash, flag, vsz, ts, fid, pos''' return get_key_info_disk(self, key) def",
"bucket_list: return None bucket_list.sort(lambda a, b: cmp(a[1], b[1]), reverse=True) result",
"= self.mc.get(key) if r is None: self._check_last_error() return r except",
"t.close() return out.strip(\"\\r\\n\") def connect(server, **kwargs): comp_threshold = kwargs.pop('comp_threshold', 0)",
"c = line.split(' ') if not d.endswith('/'): continue st[int(d[0], 16)]",
"def delete(self, key): return bool(self.mc.delete(key)) def delete_multi(self, keys, return_failure=False): return",
"self.addr def set(self, key, data, rev=0): return bool(self.mc.set(key, data, rev))",
"all KEY in the dir! not use it if dir",
"flag, vsz, ts, fid, pos''' return get_key_info_disk(self, key) def prepare(self,",
"store.get('??' + key) if info: return [int(x) for x in",
"if len(line) == 0: continue d, _, c = line.split()",
"dict: buckets -> count \"\"\" st = {} try: for",
"s.find('running') >= 0: return True return False def get_gc_status(ip, port):",
"rev, flag) def set_multi(self, values, return_failure=False): return self.mc.set_multi(values, return_failure=return_failure) def",
"raise IOError(last_err, self.mc.get_last_strerror()) def get(self, key): try: r = self.mc.get(key)",
"raw = self.get(\"@collision_%x\" % bucket) if raw is None: return",
"return bool(self.mc.get('?' + key)) def incr(self, key, value): return self.mc.incr(key,",
"= (vhash, ver) return dict(collisions) def get_records_by_khash_raw(self, khash): if self.is_old():",
"def get_server_version(self): try: st = self.stats() if st: return st[\"version\"]",
"'success': print \"bucket %s gc done\" % b break elif",
"return '<MCStore(addr=%s)>' % repr(self.addr) def __str__(self): return self.addr def set(self,",
"< 16 def dir_to_dict(dir_str): d = dict() if dir_str: for",
"in _dir.iteritems(): if get_khash64(k) == khash: ret.append((k, (vhash, ver))) else:",
"lines: if len(line) == 0: continue d, _, c =",
"b in buckets: self.start_gc(bucket=b) while True: status = self.get_gc_status() if",
">= 2: break result.append(i) return [x[0] for x in result]",
"if stats else None def is_old(self): if self._is_old is None:",
"dict() for key, meta, _ in parse_new_hint_body(hint_data): khash_str, _, ver,",
"%s gc done\" % b break elif status == 'fail':",
"return c class MCStore(object): IGNORED_LIBMC_RET = frozenset([ libmc.MC_RETURN_OK, libmc.MC_RETURN_INVALID_KEY_ERR ])",
"= \"@%08x\" % (khash64 >> 32) _dir = self.get_dir(khash32_str) if",
"logging.error(\"fail to get version %s %s\", self, st) def get_dir(self,",
"do_split=0, comp_threshold=comp_threshold, prefix=prefix) c.config(libmc.MC_CONNECT_TIMEOUT, 300) # 0.3s c.config(libmc.MC_POLL_TIMEOUT, 3000) #",
"self.stats() if s is None: return None return int(s['total_items']) def",
"... }''' try: content = self.get(path) except IOError: content =",
"c.config(libmc.MC_POLL_TIMEOUT, 3000) # 3s c.config(libmc.MC_RETRY_TIMEOUT, 5) # 5s return c",
"+ b + \"000000\") print \"a dir leaf:\", leaf khash_str",
"c.item_count() print \"primary_buckets\", get_primary_buckets(c) leaf = c.get_dir(\"@\" + b +",
"0 or 00 string \"\"\" if bucket: assert isinstance(bucket, basestring)",
"bucket must be in 0 or 00 string \"\"\" if",
"%s\", self, st) def get_dir(self, path): ''' return dict case1:",
"mem:\", c.get_key_info_mem(k) print \"key info disk(ver, vhash, flag, vsz, ts,",
"{} {} {}\\n'.format(tree, start_fid, end_fid) t.write(gc_cmd) out = t.read_until('\\n').strip('\\r\\n') assert",
"def __repr__(self): return '<MCStore(addr=%s)>' % repr(self.addr) def __str__(self): return self.addr",
"bucket, depth) def get_key_info_disk(self, key): '''return ver, vhash, flag, vsz,",
"def is_old(self): if self._is_old is None: ver = self.get_server_version() self._is_old",
"dict case1: map dir(0-f) to (hash, count), like {'0/': (1471,",
"delete(self, key): return bool(self.mc.delete(key)) def delete_multi(self, keys, return_failure=False): return self.mc.delete_multi(keys,",
"return None count, hcount, khash, data_size = raw.split() return (int(count),",
"map dir(0-f) to (hash, count), like {'0/': (1471, 27784005), ...",
"int(k, 16) == khash: return [(\"\", (int(vhash), ver))] return ret",
"db_depth): hex_digits = string.digits + 'abcdef' buckets_iter = itertools.product(*[hex_digits for",
"case1: map dir(0-f) to (hash, count), like {'0/': (1471, 27784005),",
"beansdbadmin.core.data import parse_records from beansdbadmin.core.hash import get_khash64 def get_url_content(url): return",
"r except ValueError: self.mc.delete(key) def get_raw(self, key): r, flag =",
"% b break elif status == 'fail': return self.fail(\"optimize_stat =",
"KEY in the dir! not use it if dir is",
"return None bucket_list.sort(lambda a, b: cmp(a[1], b[1]), reverse=True) result =",
"= raw.split() return (int(count), int(hcount), int(khash, 16), int(data_size)) def get_collision(self,",
"x[1] > 0] if not bucket_list: return None bucket_list.sort(lambda a,",
"def __str__(self): return self.addr def set(self, key, data, rev=0): return",
"data): return libmc.encode_value(data, self.mc.comp_threshold) def close(self): pass def test_new(addr, bucket):",
"\"a khash_str\", khash_str r = c.get_records_by_khash(khash_str)[0] k = r[0] print",
"... }, case2: map key(or khash) to (vhash, version), like",
"to (hash, count), like {'0/': (1471, 27784005), ... }, case2:",
"__init__(self, addr): MCStore.__init__(self, addr) self._is_old = None def stats(self): stats",
"= line.split(' ') d[key_or_bucket] = int(_hash) & 0xffff, int(ver_or_count) return",
"return bool(self.mc.set(key, data, rev)) def set_raw(self, key, data, rev=0, flag=0):",
"# 3s c.config(libmc.MC_RETRY_TIMEOUT, 5) # 5s return c class MCStore(object):",
"basestring) and len(bucket) <= 2 t = telnetlib.Telnet(self.host, self.port) tree",
"gc_cmd = 'gc {} {} {}\\n'.format(tree, start_fid, end_fid) t.write(gc_cmd) out",
"found' % (cmd, store, result, bucket)) def get_buckets_keys_count(store): \"\"\" return",
"status = self.get_gc_status() if status.find('running') >= 0: continue elif status",
"line in lines: if len(line) == 0: continue d, _,",
"primary buckets, might be wrong on temporary nodes, result is",
"integer \"\"\" ss = get_buckets_keys_count(store) bucket_list = ss.items() bucket_list =",
"parse_new_hint_body from beansdbadmin.core.data import parse_records from beansdbadmin.core.hash import get_khash64 def",
"return d def get_bucket_keys_count(store, bucket, depth=1): cmd = \"@\" sub",
"= [] if self.is_old(): for k, (vhash, ver) in _dir.iteritems():",
"self.get(\"?\" + key) if meta: return int(meta.split()[0]) def item_count(self): s",
"on temporary nodes, result is list of buckets in integer",
"return dict(collisions) def get_records_by_khash_raw(self, khash): if self.is_old(): return [] if",
"version:\", c.get_version(k) print \"collision_summary\", c.get_collision_summary(int(b)) print \"gc status:\", c.get_gc_status() if",
"get_dir(self, path): ''' return dict case1: map dir(0-f) to (hash,",
"bucket_ = int(d[0], 16) if bucket_ == sub: return int(c)",
"self._check_last_error() return r, flag def get_multi(self, keys): r = self.mc.get_multi(keys)",
"is None: return None count, hcount, khash, data_size = raw.split()",
"\"\"\" ss = get_buckets_keys_count(store) bucket_list = ss.items() bucket_list = [x",
"result: lines = result.split('\\n') for line in lines: if len(line)",
"else None def is_old(self): if self._is_old is None: ver =",
"list_dir(self, d): # FIXME: d should not need prefix @?",
"__repr__(self): return '<MCStore(addr=%s)>' % repr(self.addr) def __str__(self): return self.addr def",
"d[key_or_bucket] = int(_hash) & 0xffff, int(ver_or_count) return d def get_bucket_keys_count(store,",
"def get_khash_info_mem(self, khash): ''' return [(key, (vhash, ver))], key is",
"<= 2 t = telnetlib.Telnet(self.host, self.port) tree = '@%s' %",
"or 00 string \"\"\" if bucket: assert isinstance(bucket, basestring) and",
"khash64 is None: khash64 = get_khash64(key) khash32_str = \"@%08x\" %",
"path.endswith('/') and len(path) == 2: for v in self.list_dir(d +",
"# 5s return c class MCStore(object): IGNORED_LIBMC_RET = frozenset([ libmc.MC_RETURN_OK,",
"except IOError: content = '' return dir_to_dict(content) def list_dir(self, d):",
"return True return False def get_gc_status(ip, port): t = telnetlib.Telnet(ip,",
"self.is_old(): for k, (vhash, ver) in _dir.iteritems(): if get_khash64(k) ==",
"from beansdbadmin.core.hash import get_khash64 def get_url_content(url): return urllib.urlopen(url).read() def check_bucket(bucket):",
"return r def delete(self, key): return bool(self.mc.delete(key)) def delete_multi(self, keys,",
"int(hcount), int(khash, 16), int(data_size)) def get_collision(self, bucket): check_bucket(bucket) collisions =",
"the dir! not use it if dir is large!''' for",
"bucket % 16 result = store.get(cmd) if result: lines =",
"start_gc_buckets(self, buckets): for b in buckets: self.start_gc(bucket=b) while True: status",
"result[-1][1] / i[1] >= 2: break result.append(i) return [x[0] for",
"server (instead of multi like in libmc.Client) 2. encapsulate @,",
"]) def __init__(self, addr): self.addr = addr self.host, port =",
"ValueError: self.mc.delete(key) def get_raw(self, key): r, flag = self.mc.get_raw(key) if",
"\"\" for v2.''' khash32 = \"@%08x\" % (khash >> 32)",
"(int(vhash), ver))] return ret def get_server_version(self): try: st = self.stats()",
"bool(self.mc.delete(key)) def delete_multi(self, keys, return_failure=False): return self.mc.delete_multi(keys, return_failure=return_failure) def exists(self,",
"__str__(self): return self.addr def set(self, key, data, rev=0): return bool(self.mc.set(key,",
"self.get(\"@collision_all_%x\" % bucket) if hint_data is None: return dict() for",
"[] def start_gc(self, bucket='', start_fid=0, end_fid=None): \"\"\" bucket must be",
"telnetlib.Telnet(self.host, self.port) tree = '@%s' % bucket if end_fid is",
"raise Exception('get %s from %s, reply = [%s], bucket %x",
"addr) self._is_old = None def stats(self): stats = self.mc.stats() return",
"self._check_last_error() return r except ValueError: self.mc.delete(key) def get_raw(self, key): r,",
"else: return [] def start_gc(self, bucket='', start_fid=0, end_fid=None): \"\"\" bucket",
"incr(self, key, value): return self.mc.incr(key, int(value)) class DBClient(MCStore): def __init__(self,",
"parse_new_hint_body(hint_data): khash_str, _, ver, vhash = meta collisions[khash_str][key] = (vhash,",
"if depth == 2: cmd = \"@%x\" % (bucket/16) sub",
"= addr.split(\":\") self.port = int(port) self.mc = connect(addr) def __repr__(self):",
"get_key_info_mem(self, key, khash64=None): ''' return (vhash, ver) or None''' if",
"st = self.stats() if st: return st[\"version\"] except IOError: logging.error(\"fail",
"for key, meta, _ in parse_new_hint_body(hint_data): khash_str, _, ver, vhash",
"yield path, int(vhash), int(ver) def get_bucket_keys_count(self, bucket, depth=1): return get_bucket_keys_count(self,",
"\"primary_buckets\", get_primary_buckets(c) leaf = c.get_dir(\"@\" + b + \"000000\") print",
"get_records_by_khash_raw(self, khash): if self.is_old(): return [] if not isinstance(khash, str):",
"if line: d, _, c = line.split(' ') if not",
"self, st) def get_dir(self, path): ''' return dict case1: map",
"x]: key_or_bucket, _hash, ver_or_count = line.split(' ') d[key_or_bucket] = int(_hash)",
"buckets, might be wrong on temporary nodes, result is list",
"= get_gc_status(ip, port) if s and s.find('running') >= 0: return",
"self.mc.incr(key, int(value)) class DBClient(MCStore): def __init__(self, addr): MCStore.__init__(self, addr) self._is_old",
"% khash64, None) def get_khash_info_mem(self, khash): ''' return [(key, (vhash,",
"data, rev)) def set_raw(self, key, data, rev=0, flag=0): if rev",
"_, c = line.split(' ') if not d.endswith('/'): continue st[int(d[0],",
"khash = \"%016x\" % khash return self.get(\"@@\" + khash) def",
"= \"@\" sub = bucket if depth == 2: cmd",
"pos):\", \\ c.get_key_info_disk(k) print \"key version:\", c.get_version(k) print \"collision_summary\", c.get_collision_summary(int(b))",
"= r[0] print \"key, len(value), (flag, tstamp, ver):\", k, r[1],",
"rev=0, flag=0): if rev < 0: raise Exception(str(rev)) return self.mc.set_raw(key,",
"bucket c = DBClient(addr) print \"stats:\", c.stats() print 'version:', c.get_server_version()",
"key): '''return ver, vhash, flag, vsz, ts, fid, pos''' return",
"= defaultdict(dict) hint_data = self.get(\"@collision_all_%x\" % bucket) if hint_data is",
"count \"\"\" st = {} try: for line in (store.get('@')",
"= self.stats() if s is None: return None return int(s['total_items'])",
"''' import telnetlib import logging import libmc import string import",
"MCStore.__init__(self, addr) self._is_old = None def stats(self): stats = self.mc.stats()",
"k, (vhash, ver) in _dir.iteritems(): if int(k, 16) == khash:",
"if result: lines = result.split('\\n') for line in lines: if",
"t.write('optimize_stat\\r\\n') out = t.read_until('\\n') t.write('quit\\r\\n') t.close() return out.strip(\"\\r\\n\") def connect(server,",
"def get_key_info_disk(self, key): '''return ver, vhash, flag, vsz, ts, fid,",
"(int(count), int(hcount), int(khash, 16), int(data_size)) def get_collision(self, bucket): check_bucket(bucket) collisions",
"== 0: continue d, _, c = line.split() if d.endswith('/'):",
"return int(s['total_items']) def get_key_info_mem(self, key, khash64=None): ''' return (vhash, ver)",
"%s, reply = [%s], bucket %x not found' % (cmd,",
"continue elif status == 'success': print \"bucket %s gc done\"",
"client 1. for one server (instead of multi like in",
"i in bucket_list[1:]: if result[-1][1] / i[1] >= 2: break",
"None) if prefix is not None: warnings.warn('\"prefix\" is deprecated. '",
"int(s['total_items']) def get_key_info_mem(self, key, khash64=None): ''' return (vhash, ver) or",
"[bucket_list[0]] for i in bucket_list[1:]: if result[-1][1] / i[1] >=",
"= list(leaf)[0] print \"a khash_str\", khash_str r = c.get_records_by_khash(khash_str)[0] k",
"% bucket) if raw is None: return None count, hcount,",
"data, rev, flag) def set_multi(self, values, return_failure=False): return self.mc.set_multi(values, return_failure=return_failure)",
"to (vhash, version), like {'3000000377e9c2ad': (22212, 1), ... }''' try:",
"16), int(data_size)) def get_collision(self, bucket): check_bucket(bucket) collisions = defaultdict(dict) hint_data",
"= telnetlib.Telnet(self.host, self.port) tree = '@%s' % bucket if end_fid",
"beansdbadmin.core.hash import get_khash64 def get_url_content(url): return urllib.urlopen(url).read() def check_bucket(bucket): assert",
"get_bucket_keys_count(store, bucket, depth=1): cmd = \"@\" sub = bucket if",
"version), like {'3000000377e9c2ad': (22212, 1), ... }''' try: content =",
"Exception(str(rev)) return self.mc.set_raw(key, data, rev, flag) def set_multi(self, values, return_failure=False):",
"None return int(s['total_items']) def get_key_info_mem(self, key, khash64=None): ''' return (vhash,",
"+ key) if meta: return int(meta.split()[0]) def item_count(self): s =",
"(22212, 1), ... }''' try: content = self.get(path) except IOError:",
"16) == khash: return [(\"\", (int(vhash), ver))] return ret def",
"string import urllib import itertools import warnings from collections import",
"= '' return dir_to_dict(content) def list_dir(self, d): # FIXME: d",
"dir is large!''' for path, (vhash, ver) in sorted(self.get_dir(d).items()): if",
"is None: khash64 = get_khash64(key) khash32_str = \"@%08x\" % (khash64",
"c.get_key_info_mem(k) print \"key info disk(ver, vhash, flag, vsz, ts, fid,",
"ts, fid, pos''' info = store.get('??' + key) if info:",
"return False def get_gc_status(ip, port): t = telnetlib.Telnet(ip, port) t.write('optimize_stat\\r\\n')",
"last_err = self.mc.get_last_error() if last_err not in self.IGNORED_LIBMC_RET: raise IOError(last_err,",
"telnetlib import logging import libmc import string import urllib import",
"is None: self._check_last_error() return r except ValueError: self.mc.delete(key) def get_raw(self,",
"% bucket) if hint_data is None: return dict() for key,",
"get_version(self, key): meta = self.get(\"?\" + key) if meta: return",
"and s.find('running') >= 0: return True return False def get_gc_status(ip,",
"vsz, ts, fid, pos''' return get_key_info_disk(self, key) def prepare(self, data):",
"% khash return self.get(\"@@\" + khash) def get_records_by_khash(self, khash_str): raw",
"end_fid is None: gc_cmd = 'gc {} {}\\n'.format(tree, start_fid) else:",
"is_old(self): if self._is_old is None: ver = self.get_server_version() self._is_old =",
"len(bucket) <= 2 t = telnetlib.Telnet(self.host, self.port) tree = '@%s'",
"print \"key, len(value), (flag, tstamp, ver):\", k, r[1], r[3:] print",
"= 'gc {} {}\\n'.format(tree, start_fid) else: gc_cmd = 'gc {}",
"{}\\n'.format(tree, start_fid) else: gc_cmd = 'gc {} {} {}\\n'.format(tree, start_fid,",
"libmc import string import urllib import itertools import warnings from",
"khash_str): raw = self.get_records_by_khash_raw(khash_str) if raw: return parse_records(raw, False) else:",
"if raw: return parse_records(raw, False) else: return [] def start_gc(self,",
"def set_raw(self, key, data, rev=0, flag=0): if rev < 0:",
"get_bucket_keys_count(self, bucket, depth=1): return get_bucket_keys_count(self, bucket, depth) def get_key_info_disk(self, key):",
"parse_records from beansdbadmin.core.hash import get_khash64 def get_url_content(url): return urllib.urlopen(url).read() def",
"s = get_gc_status(ip, port) if s and s.find('running') >= 0:",
"self.port = int(port) self.mc = connect(addr) def __repr__(self): return '<MCStore(addr=%s)>'",
"None) def get_khash_info_mem(self, khash): ''' return [(key, (vhash, ver))], key",
"from %s, reply = [%s], bucket %x not found' %",
"= self.get_server_version() self._is_old = (ver.strip().split(\".\")[0] == \"0\") return self._is_old def",
"return self.fail(\"optimize_stat = fail\") else: self.fail(status) def get_gc_status(self): return get_gc_status(self.host,",
"delete_multi(self, keys, return_failure=False): return self.mc.delete_multi(keys, return_failure=return_failure) def exists(self, key): return",
"int(c) raise Exception('get %s from %s, reply = [%s], bucket",
"line in [x for x in dir_str.split('\\n') if x]: key_or_bucket,",
"rich client 1. for one server (instead of multi like",
"vhash, flag, vsz, ts, fid, pos''' info = store.get('??' +",
">> 32) _dir = self.get_dir(khash32) ret = [] if self.is_old():",
"Exception(\"cannot get @ from %s\" % (store)) def get_primary_buckets(store): \"\"\"",
"i in buckets_iter] self.start_gc_buckets(buckets) def start_gc_buckets(self, buckets): for b in",
"def get_records_by_khash_raw(self, khash): if self.is_old(): return [] if not isinstance(khash,",
"\"bucket %s gc done\" % b break elif status ==",
"''' return [(key, (vhash, ver))], key is \"\" for v2.'''",
"get_gc_status(ip, port): t = telnetlib.Telnet(ip, port) t.write('optimize_stat\\r\\n') out = t.read_until('\\n')",
"must be in 0 or 00 string \"\"\" if bucket:",
"return dict case1: map dir(0-f) to (hash, count), like {'0/':",
"defaultdict from beansdbadmin.core.hint import parse_new_hint_body from beansdbadmin.core.data import parse_records from",
"try: for line in (store.get('@') or '').split('\\n'): if line: d,",
"0: return True return False def get_gc_status(ip, port): t =",
"try: r = self.mc.get(key) if r is None: self._check_last_error() return",
"def get_gc_status(ip, port): t = telnetlib.Telnet(ip, port) t.write('optimize_stat\\r\\n') out =",
"libmc.encode_value(data, self.mc.comp_threshold) def close(self): pass def test_new(addr, bucket): b =",
"c.is_old() print \"dir root:\", c.get_dir(\"@\") print \"bucket key count:\", c.get_bucket_keys_count(int(b))",
"self.mc.set_multi(values, return_failure=return_failure) def _check_last_error(self): last_err = self.mc.get_last_error() if last_err not",
"if raw is None: return None count, hcount, khash, data_size",
"get_key_info_disk(self, key): '''return ver, vhash, flag, vsz, ts, fid, pos'''",
"line.split() if d.endswith('/'): bucket_ = int(d[0], 16) if bucket_ ==",
"raw is None: return None count, hcount, khash, data_size =",
"(vhash, ver) in _dir.iteritems(): if get_khash64(k) == khash: ret.append((k, (vhash,",
"flag def get_multi(self, keys): r = self.mc.get_multi(keys) self._check_last_error() return r",
"None: return dict() for key, meta, _ in parse_new_hint_body(hint_data): khash_str,",
"\"stats:\", c.stats() print 'version:', c.get_server_version() print \"isold:\", c.is_old() print \"dir",
"in _dir.iteritems(): if int(k, 16) == khash: return [(\"\", (int(vhash),",
"r[3:] print \"key info mem:\", c.get_key_info_mem(k) print \"key info disk(ver,",
"nodes, result is list of buckets in integer \"\"\" ss",
"c.get_key_info_disk(k) print \"key version:\", c.get_version(k) print \"collision_summary\", c.get_collision_summary(int(b)) print \"gc",
"libmc.Client ''' import telnetlib import logging import libmc import string",
"port): t = telnetlib.Telnet(ip, port) t.write('optimize_stat\\r\\n') out = t.read_until('\\n') t.write('quit\\r\\n')",
"key count:\", c.get_bucket_keys_count(int(b)) print \"item_count:\", c.item_count() print \"primary_buckets\", get_primary_buckets(c) leaf",
"\"\"\" st = {} try: for line in (store.get('@') or",
"dir_to_dict(dir_str): d = dict() if dir_str: for line in [x",
"not found' % (cmd, store, result, bucket)) def get_buckets_keys_count(store): \"\"\"",
"buckets -> count \"\"\" st = {} try: for line",
"IGNORED_LIBMC_RET = frozenset([ libmc.MC_RETURN_OK, libmc.MC_RETURN_INVALID_KEY_ERR ]) def __init__(self, addr): self.addr",
"return_failure=return_failure) def exists(self, key): return bool(self.mc.get('?' + key)) def incr(self,",
"set_raw(self, key, data, rev=0, flag=0): if rev < 0: raise",
"self.mc.comp_threshold) def close(self): pass def test_new(addr, bucket): b = bucket",
"'''a rich client 1. for one server (instead of multi",
"get_key_info_disk(store, key): '''return ver, vhash, flag, vsz, ts, fid, pos'''",
"= telnetlib.Telnet(ip, port) t.write('optimize_stat\\r\\n') out = t.read_until('\\n') t.write('quit\\r\\n') t.close() return",
"for b in buckets: self.start_gc(bucket=b) while True: status = self.get_gc_status()",
"None: return None return int(s['total_items']) def get_key_info_mem(self, key, khash64=None): '''",
"self.get_dir(khash32_str) if self.is_old(): return _dir.get(key, None) else: return _dir.get(\"%016x\" %",
"of libmc.Client ''' import telnetlib import logging import libmc import",
"''' return dict case1: map dir(0-f) to (hash, count), like",
"t.write('quit\\n') t.close() def start_gc_all_buckets(self, db_depth): hex_digits = string.digits + 'abcdef'",
"hex_digits = string.digits + 'abcdef' buckets_iter = itertools.product(*[hex_digits for _",
"is None: return dict() for key, meta, _ in parse_new_hint_body(hint_data):",
"keys): r = self.mc.get_multi(keys) self._check_last_error() return r def delete(self, key):",
"= self.mc.get_raw(key) if r is None: self._check_last_error() return r, flag",
"bucket_list = [x for x in bucket_list if x[1] >",
"IOError: raise Exception(\"cannot get @ from %s\" % (store)) def",
"d.endswith('/'): continue st[int(d[0], 16)] = int(c) return st except IOError:",
"= self.get(\"@collision_all_%x\" % bucket) if hint_data is None: return dict()",
"line: d, _, c = line.split(' ') if not d.endswith('/'):",
"kwargs.pop('prefix', None) if prefix is not None: warnings.warn('\"prefix\" is deprecated.",
"[] if not isinstance(khash, str): khash = \"%016x\" % khash",
"for k, (vhash, ver) in _dir.iteritems(): if int(k, 16) ==",
"self) except KeyError: logging.error(\"fail to get version %s %s\", self,",
"\\ c.get_key_info_disk(k) print \"key version:\", c.get_version(k) print \"collision_summary\", c.get_collision_summary(int(b)) print",
"% (bucket/16) sub = bucket % 16 result = store.get(cmd)",
"libmc.Client([server], do_split=0, comp_threshold=comp_threshold, prefix=prefix) c.config(libmc.MC_CONNECT_TIMEOUT, 300) # 0.3s c.config(libmc.MC_POLL_TIMEOUT, 3000)",
"= frozenset([ libmc.MC_RETURN_OK, libmc.MC_RETURN_INVALID_KEY_ERR ]) def __init__(self, addr): self.addr =",
"values, return_failure=False): return self.mc.set_multi(values, return_failure=return_failure) def _check_last_error(self): last_err = self.mc.get_last_error()",
"collisions = defaultdict(dict) hint_data = self.get(\"@collision_all_%x\" % bucket) if hint_data",
"comp_threshold=comp_threshold, prefix=prefix) c.config(libmc.MC_CONNECT_TIMEOUT, 300) # 0.3s c.config(libmc.MC_POLL_TIMEOUT, 3000) # 3s",
"ver, vhash = meta collisions[khash_str][key] = (vhash, ver) return dict(collisions)",
"get_khash64(k) == khash: ret.append((k, (vhash, ver))) else: for k, (vhash,",
"is deprecated. ' 'use douban.wrapper.Prefix instead.') c = libmc.Client([server], do_split=0,",
"import parse_new_hint_body from beansdbadmin.core.data import parse_records from beansdbadmin.core.hash import get_khash64",
"self.get(\"@collision_%x\" % bucket) if raw is None: return None count,",
"version %s %s\", self, st) def get_dir(self, path): ''' return",
"map key(or khash) to (vhash, version), like {'3000000377e9c2ad': (22212, 1),",
"exists(self, key): return bool(self.mc.get('?' + key)) def incr(self, key, value):",
"not use it if dir is large!''' for path, (vhash,",
"return [int(x) for x in info.split()] def is_gc_running(ip, port): s",
"t.read_until('\\n') t.write('quit\\r\\n') t.close() return out.strip(\"\\r\\n\") def connect(server, **kwargs): comp_threshold =",
"(1471, 27784005), ... }, case2: map key(or khash) to (vhash,",
"print \"stats:\", c.stats() print 'version:', c.get_server_version() print \"isold:\", c.is_old() print",
"[x for x in bucket_list if x[1] > 0] if",
"None bucket_list.sort(lambda a, b: cmp(a[1], b[1]), reverse=True) result = [bucket_list[0]]",
"def get_gc_status(self): return get_gc_status(self.host, self.port) def get_version(self, key): meta =",
"None count, hcount, khash, data_size = raw.split() return (int(count), int(hcount),",
"in range(db_depth)]) buckets = [''.join(i) for i in buckets_iter] self.start_gc_buckets(buckets)",
"def is_gc_running(ip, port): s = get_gc_status(ip, port) if s and",
"if not bucket_list: return None bucket_list.sort(lambda a, b: cmp(a[1], b[1]),",
"info = store.get('??' + key) if info: return [int(x) for",
"'version:', c.get_server_version() print \"isold:\", c.is_old() print \"dir root:\", c.get_dir(\"@\") print",
"from collections import defaultdict from beansdbadmin.core.hint import parse_new_hint_body from beansdbadmin.core.data",
"return stats.values()[0] if stats else None def is_old(self): if self._is_old",
"ver, vhash, flag, vsz, ts, fid, pos''' return get_key_info_disk(self, key)",
"def get_version(self, key): meta = self.get(\"?\" + key) if meta:",
"if bucket_ == sub: return int(c) raise Exception('get %s from",
"bucket %x not found' % (cmd, store, result, bucket)) def",
"def get_records_by_khash(self, khash_str): raw = self.get_records_by_khash_raw(khash_str) if raw: return parse_records(raw,",
"& 0xffff, int(ver_or_count) return d def get_bucket_keys_count(store, bucket, depth=1): cmd",
"IOError: logging.error(\"fail to get version %s\", self) except KeyError: logging.error(\"fail",
"None) else: return _dir.get(\"%016x\" % khash64, None) def get_khash_info_mem(self, khash):",
"= kwargs.pop('comp_threshold', 0) prefix = kwargs.pop('prefix', None) if prefix is",
"vhash = meta collisions[khash_str][key] = (vhash, ver) return dict(collisions) def",
"khash, data_size = raw.split() return (int(count), int(hcount), int(khash, 16), int(data_size))",
"d, _, c = line.split() if d.endswith('/'): bucket_ = int(d[0],",
"line.split(' ') d[key_or_bucket] = int(_hash) & 0xffff, int(ver_or_count) return d",
"{} try: for line in (store.get('@') or '').split('\\n'): if line:",
"get_multi(self, keys): r = self.mc.get_multi(keys) self._check_last_error() return r def delete(self,",
"(vhash, ver) in _dir.iteritems(): if int(k, 16) == khash: return",
"27784005), ... }, case2: map key(or khash) to (vhash, version),",
"key)) def incr(self, key, value): return self.mc.incr(key, int(value)) class DBClient(MCStore):",
"return get_key_info_disk(self, key) def prepare(self, data): return libmc.encode_value(data, self.mc.comp_threshold) def",
"c.get_records_by_khash(khash_str)[0] k = r[0] print \"key, len(value), (flag, tstamp, ver):\",",
"in buckets: self.start_gc(bucket=b) while True: status = self.get_gc_status() if status.find('running')",
"is None: gc_cmd = 'gc {} {}\\n'.format(tree, start_fid) else: gc_cmd",
"self.start_gc(bucket=b) while True: status = self.get_gc_status() if status.find('running') >= 0:",
"if bucket: assert isinstance(bucket, basestring) and len(bucket) <= 2 t",
"else: for k, (vhash, ver) in _dir.iteritems(): if int(k, 16)",
"warnings.warn('\"prefix\" is deprecated. ' 'use douban.wrapper.Prefix instead.') c = libmc.Client([server],",
"{} {}\\n'.format(tree, start_fid) else: gc_cmd = 'gc {} {} {}\\n'.format(tree,",
"or None''' if khash64 is None: khash64 = get_khash64(key) khash32_str",
"None: return None count, hcount, khash, data_size = raw.split() return",
"raise Exception(str(rev)) return self.mc.set_raw(key, data, rev, flag) def set_multi(self, values,",
"d should not need prefix @? '''list all KEY in",
"one server (instead of multi like in libmc.Client) 2. encapsulate",
"return self.get(\"@@\" + khash) def get_records_by_khash(self, khash_str): raw = self.get_records_by_khash_raw(khash_str)",
"bool(self.mc.get('?' + key)) def incr(self, key, value): return self.mc.incr(key, int(value))",
"for v in self.list_dir(d + path[:-1]): yield v else: yield",
"[''.join(i) for i in buckets_iter] self.start_gc_buckets(buckets) def start_gc_buckets(self, buckets): for",
"= self.get_dir(khash32_str) if self.is_old(): return _dir.get(key, None) else: return _dir.get(\"%016x\"",
"(store.get('@') or '').split('\\n'): if line: d, _, c = line.split('",
"result is list of buckets in integer \"\"\" ss =",
"set(self, key, data, rev=0): return bool(self.mc.set(key, data, rev)) def set_raw(self,",
"== 'fail': return self.fail(\"optimize_stat = fail\") else: self.fail(status) def get_gc_status(self):",
"key): return bool(self.mc.get('?' + key)) def incr(self, key, value): return",
"= self.mc.get_multi(keys) self._check_last_error() return r def delete(self, key): return bool(self.mc.delete(key))",
"ts, fid, pos):\", \\ c.get_key_info_disk(k) print \"key version:\", c.get_version(k) print",
"class DBClient(MCStore): def __init__(self, addr): MCStore.__init__(self, addr) self._is_old = None",
"is None: return None return int(s['total_items']) def get_key_info_mem(self, key, khash64=None):",
"if self.is_old(): return _dir.get(key, None) else: return _dir.get(\"%016x\" % khash64,",
"assert 0 <= bucket < 16 def dir_to_dict(dir_str): d =",
"d.endswith('/'): bucket_ = int(d[0], 16) if bucket_ == sub: return",
"return dir_to_dict(content) def list_dir(self, d): # FIXME: d should not",
"'abcdef' buckets_iter = itertools.product(*[hex_digits for _ in range(db_depth)]) buckets =",
"if khash64 is None: khash64 = get_khash64(key) khash32_str = \"@%08x\"",
"1. for one server (instead of multi like in libmc.Client)",
"= \"%016x\" % khash return self.get(\"@@\" + khash) def get_records_by_khash(self,",
"None: self._check_last_error() return r except ValueError: self.mc.delete(key) def get_raw(self, key):",
"khash_str\", khash_str r = c.get_records_by_khash(khash_str)[0] k = r[0] print \"key,",
"print \"item_count:\", c.item_count() print \"primary_buckets\", get_primary_buckets(c) leaf = c.get_dir(\"@\" +",
"douban.wrapper.Prefix instead.') c = libmc.Client([server], do_split=0, comp_threshold=comp_threshold, prefix=prefix) c.config(libmc.MC_CONNECT_TIMEOUT, 300)",
"not None: warnings.warn('\"prefix\" is deprecated. ' 'use douban.wrapper.Prefix instead.') c",
"bucket) if hint_data is None: return dict() for key, meta,",
"return [(key, (vhash, ver))], key is \"\" for v2.''' khash32",
"return st[\"version\"] except IOError: logging.error(\"fail to get version %s\", self)",
"st[\"version\"] except IOError: logging.error(\"fail to get version %s\", self) except",
"buckets_iter] self.start_gc_buckets(buckets) def start_gc_buckets(self, buckets): for b in buckets: self.start_gc(bucket=b)",
"% (khash64 >> 32) _dir = self.get_dir(khash32_str) if self.is_old(): return",
"pass def test_new(addr, bucket): b = bucket c = DBClient(addr)",
"% (cmd, store, result, bucket)) def get_buckets_keys_count(store): \"\"\" return dict:",
"check_bucket(bucket) raw = self.get(\"@collision_%x\" % bucket) if raw is None:",
"r = c.get_records_by_khash(khash_str)[0] k = r[0] print \"key, len(value), (flag,",
"@, ?, gc ... use is instead of libmc.Client '''",
"= self.stats() if st: return st[\"version\"] except IOError: logging.error(\"fail to",
"st = {} try: for line in (store.get('@') or '').split('\\n'):",
"_check_last_error(self): last_err = self.mc.get_last_error() if last_err not in self.IGNORED_LIBMC_RET: raise",
"root:\", c.get_dir(\"@\") print \"bucket key count:\", c.get_bucket_keys_count(int(b)) print \"item_count:\", c.item_count()",
"= [%s], bucket %x not found' % (cmd, store, result,",
"c.config(libmc.MC_RETRY_TIMEOUT, 5) # 5s return c class MCStore(object): IGNORED_LIBMC_RET =",
"= connect(addr) def __repr__(self): return '<MCStore(addr=%s)>' % repr(self.addr) def __str__(self):",
"'gc {} {}\\n'.format(tree, start_fid) else: gc_cmd = 'gc {} {}",
"if s and s.find('running') >= 0: return True return False",
"try: st = self.stats() if st: return st[\"version\"] except IOError:",
"get(self, key): try: r = self.mc.get(key) if r is None:",
"2 t = telnetlib.Telnet(self.host, self.port) tree = '@%s' % bucket",
"from beansdbadmin.core.hint import parse_new_hint_body from beansdbadmin.core.data import parse_records from beansdbadmin.core.hash",
"get_collision_summary(self, bucket): check_bucket(bucket) raw = self.get(\"@collision_%x\" % bucket) if raw",
"(vhash, ver) or None''' if khash64 is None: khash64 =",
"def connect(server, **kwargs): comp_threshold = kwargs.pop('comp_threshold', 0) prefix = kwargs.pop('prefix',",
"#!/usr/bin/python # encoding: utf-8 '''a rich client 1. for one",
"is None: ver = self.get_server_version() self._is_old = (ver.strip().split(\".\")[0] == \"0\")",
"in bucket_list[1:]: if result[-1][1] / i[1] >= 2: break result.append(i)",
"(vhash, ver))) else: for k, (vhash, ver) in _dir.iteritems(): if",
"self.IGNORED_LIBMC_RET: raise IOError(last_err, self.mc.get_last_strerror()) def get(self, key): try: r =",
"16 result = store.get(cmd) if result: lines = result.split('\\n') for",
"v else: yield path, int(vhash), int(ver) def get_bucket_keys_count(self, bucket, depth=1):",
"not bucket_list: return None bucket_list.sort(lambda a, b: cmp(a[1], b[1]), reverse=True)",
"= itertools.product(*[hex_digits for _ in range(db_depth)]) buckets = [''.join(i) for",
"path, int(vhash), int(ver) def get_bucket_keys_count(self, bucket, depth=1): return get_bucket_keys_count(self, bucket,",
"str): khash = \"%016x\" % khash return self.get(\"@@\" + khash)",
"get_bucket_keys_count(self, bucket, depth) def get_key_info_disk(self, key): '''return ver, vhash, flag,",
"if st: return st[\"version\"] except IOError: logging.error(\"fail to get version",
"gc ... use is instead of libmc.Client ''' import telnetlib",
"fail\") else: self.fail(status) def get_gc_status(self): return get_gc_status(self.host, self.port) def get_version(self,",
"self.mc.stats() return stats.values()[0] if stats else None def is_old(self): if",
"khash64 = get_khash64(key) khash32_str = \"@%08x\" % (khash64 >> 32)",
"') if not d.endswith('/'): continue st[int(d[0], 16)] = int(c) return",
"buckets_iter = itertools.product(*[hex_digits for _ in range(db_depth)]) buckets = [''.join(i)",
"gc_cmd = 'gc {} {}\\n'.format(tree, start_fid) else: gc_cmd = 'gc",
"bucket_list.sort(lambda a, b: cmp(a[1], b[1]), reverse=True) result = [bucket_list[0]] for",
"dir leaf:\", leaf khash_str = list(leaf)[0] print \"a khash_str\", khash_str",
"self.port) tree = '@%s' % bucket if end_fid is None:",
"sub = bucket % 16 result = store.get(cmd) if result:",
"if path.endswith('/') and len(path) == 2: for v in self.list_dir(d",
"= bucket c = DBClient(addr) print \"stats:\", c.stats() print 'version:',",
"ret = [] if self.is_old(): for k, (vhash, ver) in",
"None def stats(self): stats = self.mc.stats() return stats.values()[0] if stats",
"[%s], bucket %x not found' % (cmd, store, result, bucket))",
"00 string \"\"\" if bucket: assert isinstance(bucket, basestring) and len(bucket)",
"except IOError: logging.error(\"fail to get version %s\", self) except KeyError:",
"print \"dir root:\", c.get_dir(\"@\") print \"bucket key count:\", c.get_bucket_keys_count(int(b)) print",
"vsz, ts, fid, pos''' info = store.get('??' + key) if",
"% (store)) def get_primary_buckets(store): \"\"\" return possible primary buckets, might",
"for _ in range(db_depth)]) buckets = [''.join(i) for i in",
"t.write('quit\\r\\n') t.close() return out.strip(\"\\r\\n\") def connect(server, **kwargs): comp_threshold = kwargs.pop('comp_threshold',",
"get_gc_status(self.host, self.port) def get_version(self, key): meta = self.get(\"?\" + key)",
"yield v else: yield path, int(vhash), int(ver) def get_bucket_keys_count(self, bucket,",
"for x in dir_str.split('\\n') if x]: key_or_bucket, _hash, ver_or_count =",
"return libmc.encode_value(data, self.mc.comp_threshold) def close(self): pass def test_new(addr, bucket): b",
"rev)) def set_raw(self, key, data, rev=0, flag=0): if rev <",
"bucket_list[1:]: if result[-1][1] / i[1] >= 2: break result.append(i) return",
"\"key, len(value), (flag, tstamp, ver):\", k, r[1], r[3:] print \"key",
"return dict: buckets -> count \"\"\" st = {} try:",
"c.get_collision_summary(int(b)) print \"gc status:\", c.get_gc_status() if __name__ == '__main__': test_new(\"rosa3a:7900\",",
"% 16 result = store.get(cmd) if result: lines = result.split('\\n')",
"not d.endswith('/'): continue st[int(d[0], 16)] = int(c) return st except",
"-> count \"\"\" st = {} try: for line in",
"%x not found' % (cmd, store, result, bucket)) def get_buckets_keys_count(store):",
"meta, _ in parse_new_hint_body(hint_data): khash_str, _, ver, vhash = meta",
"(vhash, ver) in sorted(self.get_dir(d).items()): if path.endswith('/') and len(path) == 2:",
"DBClient(MCStore): def __init__(self, addr): MCStore.__init__(self, addr) self._is_old = None def",
"check_bucket(bucket): assert 0 <= bucket < 16 def dir_to_dict(dir_str): d",
"should not need prefix @? '''list all KEY in the",
"dir_str: for line in [x for x in dir_str.split('\\n') if",
"self.mc.get(key) if r is None: self._check_last_error() return r except ValueError:"
] |
[
"return True if l1p1x > l2p2x or l1p2x < l2p1x:",
"make sure p1x < p2x if l2p1x > l2p2x: tmp",
"l2p2x and l1p2x < l2p1x and l1p1y > l2p2y and",
"= l1p1y l1p1y = l1p2y l1p2y = tmp l2p1x =",
"l1p2y = tmp l2p1x = line2[0][0] l2p1y = line2[0][1] l2p2x",
"True # line2 rectangle is inside line1 rect if l1p1x",
"l2p1y: return False return True if __name__ == '__main__': matplotlib.pyplot.plot((line1[0][0],line1[1][0]),(line1[0][1],line1[1][1]))",
"tmp = l2p1y l2p1y = l2p2y l2p2y = tmp #",
"return False return True if __name__ == '__main__': matplotlib.pyplot.plot((line1[0][0],line1[1][0]),(line1[0][1],line1[1][1])) matplotlib.pyplot.hold(True)",
"and l1p2x > l2p1x and l1p1y < l2p2y and l1p2y",
"= l1p2y l1p2y = tmp l2p1x = line2[0][0] l2p1y =",
"p2y if l2p1y > l2p2y: tmp = l2p1y l2p1y =",
"= [(190, 190), (210, 210)] def overlap(): l1p1x = line1[0][0]",
"= tmp # make sure p1y < p2y if l1p1y",
"import matplotlib.pyplot __author__ = 'xiongyi' line1 = [(200, 100), (200,",
"< l2p1y: return True if l1p1x > l2p2x or l1p2x",
"l2p1y = l2p2y l2p2y = tmp # line2 rectangle is",
"p1x < p2x if l1p1x > l1p2x: tmp = l1p1x",
"l1p2x < l2p1x: return False if l1p1y > l2p2y or",
"tmp # make sure p1y < p2y if l1p1y >",
"l1p1x > l2p2x or l1p2x < l2p1x: return False if",
"# make sure p1y < p2y if l1p1y > l1p2y:",
"line2[1][1] # make sure p1x < p2x if l2p1x >",
"= [(200, 100), (200, 400)] line2 = [(190, 190), (210,",
"line1[1][0] l1p2y = line1[1][1] # make sure p1x < p2x",
"l2p1y > l2p2y: tmp = l2p1y l2p1y = l2p2y l2p2y",
"line1 rect if l1p1x < l2p2x and l1p2x > l2p1x",
"< l2p1x: return False if l1p1y > l2p2y or l1p2y",
"l1p2x > l2p1x and l1p1y < l2p2y and l1p2y >",
"l2p1x and l1p1y < l2p2y and l1p2y > l2p1y: return",
"l1p2y > l2p1y: return True # line2 rectangle is inside",
"tmp = l2p1x l2p1x = l2p2x l2p2x = tmp #",
"if l1p1y > l2p2y or l1p2y < l2p1y: return False",
"< l2p1x and l1p1y > l2p2y and l1p2y < l2p1y:",
"tmp = l1p1x l1p1x = l1p2x l1p2x = tmp #",
"line1[0][0] l1p1y = line1[0][1] l1p2x = line1[1][0] l1p2y = line1[1][1]",
"make sure p1x < p2x if l1p1x > l1p2x: tmp",
"l2p2y and l1p2y < l2p1y: return True if l1p1x >",
"l2p2y l2p2y = tmp # line2 rectangle is inside line1",
"# line2 rectangle is inside line1 rect if l1p1x >",
"[(190, 190), (210, 210)] def overlap(): l1p1x = line1[0][0] l1p1y",
"p2x if l1p1x > l1p2x: tmp = l1p1x l1p1x =",
"= line2[0][0] l2p1y = line2[0][1] l2p2x = line2[1][0] l2p2y =",
"> l2p1x and l1p1y < l2p2y and l1p2y > l2p1y:",
"= line1[0][1] l1p2x = line1[1][0] l1p2y = line1[1][1] # make",
"line2[0][0] l2p1y = line2[0][1] l2p2x = line2[1][0] l2p2y = line2[1][1]",
"l2p1x = line2[0][0] l2p1y = line2[0][1] l2p2x = line2[1][0] l2p2y",
"tmp # make sure p1y < p2y if l2p1y >",
"False if l1p1y > l2p2y or l1p2y < l2p1y: return",
"< l2p2y and l1p2y > l2p1y: return True # line2",
"= l2p1x l2p1x = l2p2x l2p2x = tmp # make",
"or l1p2x < l2p1x: return False if l1p1y > l2p2y",
"line2 = [(190, 190), (210, 210)] def overlap(): l1p1x =",
"> l1p2y: tmp = l1p1y l1p1y = l1p2y l1p2y =",
"p2x if l2p1x > l2p2x: tmp = l2p1x l2p1x =",
"p1y < p2y if l1p1y > l1p2y: tmp = l1p1y",
"l2p1x: return False if l1p1y > l2p2y or l1p2y <",
"400)] line2 = [(190, 190), (210, 210)] def overlap(): l1p1x",
"l2p2x l2p2x = tmp # make sure p1y < p2y",
"p2y if l1p1y > l1p2y: tmp = l1p1y l1p1y =",
"l1p1y < l2p2y and l1p2y > l2p1y: return True #",
"return True # line2 rectangle is inside line1 rect if",
"(210, 210)] def overlap(): l1p1x = line1[0][0] l1p1y = line1[0][1]",
"190), (210, 210)] def overlap(): l1p1x = line1[0][0] l1p1y =",
"l1p2y = line1[1][1] # make sure p1x < p2x if",
"False return True if __name__ == '__main__': matplotlib.pyplot.plot((line1[0][0],line1[1][0]),(line1[0][1],line1[1][1])) matplotlib.pyplot.hold(True) matplotlib.pyplot.plot((line2[0][0],line2[1][0]),(line2[0][1],line2[1][1]))",
"= l2p1y l2p1y = l2p2y l2p2y = tmp # line2",
"= line2[0][1] l2p2x = line2[1][0] l2p2y = line2[1][1] # make",
"and l1p2y < l2p1y: return True if l1p1x > l2p2x",
"True if __name__ == '__main__': matplotlib.pyplot.plot((line1[0][0],line1[1][0]),(line1[0][1],line1[1][1])) matplotlib.pyplot.hold(True) matplotlib.pyplot.plot((line2[0][0],line2[1][0]),(line2[0][1],line2[1][1])) print(overlap()) matplotlib.pyplot.show()",
"inside line1 rect if l1p1x < l2p2x and l1p2x >",
"= line2[1][1] # make sure p1x < p2x if l2p1x",
"if l1p1y > l1p2y: tmp = l1p1y l1p1y = l1p2y",
"= line1[1][1] # make sure p1x < p2x if l1p1x",
"l1p2y < l2p1y: return False return True if __name__ ==",
"matplotlib.pyplot __author__ = 'xiongyi' line1 = [(200, 100), (200, 400)]",
"if l2p1x > l2p2x: tmp = l2p1x l2p1x = l2p2x",
"< l2p1y: return False return True if __name__ == '__main__':",
"is inside line1 rect if l1p1x < l2p2x and l1p2x",
"# line2 rectangle is inside line1 rect if l1p1x <",
"p1x < p2x if l2p1x > l2p2x: tmp = l2p1x",
"> l2p2x and l1p2x < l2p1x and l1p1y > l2p2y",
"line1 = [(200, 100), (200, 400)] line2 = [(190, 190),",
"tmp # line2 rectangle is inside line1 rect if l1p1x",
"line2 rectangle is inside line1 rect if l1p1x < l2p2x",
"if l1p1x > l2p2x or l1p2x < l2p1x: return False",
"l2p1x and l1p1y > l2p2y and l1p2y < l2p1y: return",
"rectangle is inside line1 rect if l1p1x < l2p2x and",
"l2p2y or l1p2y < l2p1y: return False return True if",
"100), (200, 400)] line2 = [(190, 190), (210, 210)] def",
"l2p2y = line2[1][1] # make sure p1x < p2x if",
"line2 rectangle is inside line1 rect if l1p1x > l2p2x",
"(200, 400)] line2 = [(190, 190), (210, 210)] def overlap():",
"if l1p1x > l2p2x and l1p2x < l2p1x and l1p1y",
"is inside line1 rect if l1p1x > l2p2x and l1p2x",
"line2[0][1] l2p2x = line2[1][0] l2p2y = line2[1][1] # make sure",
"l2p2x = line2[1][0] l2p2y = line2[1][1] # make sure p1x",
"and l1p2x < l2p1x and l1p1y > l2p2y and l1p2y",
"l1p1y > l2p2y and l1p2y < l2p1y: return True if",
"sure p1y < p2y if l2p1y > l2p2y: tmp =",
"sure p1x < p2x if l2p1x > l2p2x: tmp =",
"overlap(): l1p1x = line1[0][0] l1p1y = line1[0][1] l1p2x = line1[1][0]",
"l2p1y = line2[0][1] l2p2x = line2[1][0] l2p2y = line2[1][1] #",
"# make sure p1y < p2y if l2p1y > l2p2y:",
"sure p1x < p2x if l1p1x > l1p2x: tmp =",
"l1p2x < l2p1x and l1p1y > l2p2y and l1p2y <",
"if l2p1y > l2p2y: tmp = l2p1y l2p1y = l2p2y",
"or l1p2y < l2p1y: return False return True if __name__",
"make sure p1y < p2y if l1p1y > l1p2y: tmp",
"210)] def overlap(): l1p1x = line1[0][0] l1p1y = line1[0][1] l1p2x",
"l1p1x = l1p2x l1p2x = tmp # make sure p1y",
"< p2x if l1p1x > l1p2x: tmp = l1p1x l1p1x",
"< p2y if l2p1y > l2p2y: tmp = l2p1y l2p1y",
"l2p2x = tmp # make sure p1y < p2y if",
"l2p1x > l2p2x: tmp = l2p1x l2p1x = l2p2x l2p2x",
"[(200, 100), (200, 400)] line2 = [(190, 190), (210, 210)]",
"l1p1y > l2p2y or l1p2y < l2p1y: return False return",
"def overlap(): l1p1x = line1[0][0] l1p1y = line1[0][1] l1p2x =",
"l1p1x = line1[0][0] l1p1y = line1[0][1] l1p2x = line1[1][0] l1p2y",
"True if l1p1x > l2p2x or l1p2x < l2p1x: return",
"> l2p1y: return True # line2 rectangle is inside line1",
"l2p1y: return True # line2 rectangle is inside line1 rect",
"> l2p2x: tmp = l2p1x l2p1x = l2p2x l2p2x =",
"if l1p1x < l2p2x and l1p2x > l2p1x and l1p1y",
"l2p2x or l1p2x < l2p1x: return False if l1p1y >",
"= l2p2x l2p2x = tmp # make sure p1y <",
"l2p2y = tmp # line2 rectangle is inside line1 rect",
"l2p2y and l1p2y > l2p1y: return True # line2 rectangle",
"> l2p2y: tmp = l2p1y l2p1y = l2p2y l2p2y =",
"l1p2y: tmp = l1p1y l1p1y = l1p2y l1p2y = tmp",
"> l2p2x or l1p2x < l2p1x: return False if l1p1y",
"< p2x if l2p1x > l2p2x: tmp = l2p1x l2p1x",
"l2p1x l2p1x = l2p2x l2p2x = tmp # make sure",
"rect if l1p1x > l2p2x and l1p2x < l2p1x and",
"= line1[1][0] l1p2y = line1[1][1] # make sure p1x <",
"l1p1y = l1p2y l1p2y = tmp l2p1x = line2[0][0] l2p1y",
"make sure p1y < p2y if l2p1y > l2p2y: tmp",
"l2p2x and l1p2x > l2p1x and l1p1y < l2p2y and",
"line2[1][0] l2p2y = line2[1][1] # make sure p1x < p2x",
"tmp l2p1x = line2[0][0] l2p1y = line2[0][1] l2p2x = line2[1][0]",
"l2p2x: tmp = l2p1x l2p1x = l2p2x l2p2x = tmp",
"l2p1y l2p1y = l2p2y l2p2y = tmp # line2 rectangle",
"l1p1x > l1p2x: tmp = l1p1x l1p1x = l1p2x l1p2x",
"line1[1][1] # make sure p1x < p2x if l1p1x >",
"< p2y if l1p1y > l1p2y: tmp = l1p1y l1p1y",
"= l2p2y l2p2y = tmp # line2 rectangle is inside",
"return True if __name__ == '__main__': matplotlib.pyplot.plot((line1[0][0],line1[1][0]),(line1[0][1],line1[1][1])) matplotlib.pyplot.hold(True) matplotlib.pyplot.plot((line2[0][0],line2[1][0]),(line2[0][1],line2[1][1])) print(overlap())",
"= line2[1][0] l2p2y = line2[1][1] # make sure p1x <",
"= 'xiongyi' line1 = [(200, 100), (200, 400)] line2 =",
"sure p1y < p2y if l1p1y > l1p2y: tmp =",
"p1y < p2y if l2p1y > l2p2y: tmp = l2p1y",
"> l1p2x: tmp = l1p1x l1p1x = l1p2x l1p2x =",
"= tmp # make sure p1y < p2y if l2p1y",
"line1 rect if l1p1x > l2p2x and l1p2x < l2p1x",
"= line1[0][0] l1p1y = line1[0][1] l1p2x = line1[1][0] l1p2y =",
"tmp = l1p1y l1p1y = l1p2y l1p2y = tmp l2p1x",
"> l2p2y or l1p2y < l2p1y: return False return True",
"l1p2x = line1[1][0] l1p2y = line1[1][1] # make sure p1x",
"l1p2y l1p2y = tmp l2p1x = line2[0][0] l2p1y = line2[0][1]",
"l1p2x = tmp # make sure p1y < p2y if",
"l1p2y < l2p1y: return True if l1p1x > l2p2x or",
"l1p1y > l1p2y: tmp = l1p1y l1p1y = l1p2y l1p2y",
"= tmp # line2 rectangle is inside line1 rect if",
"# make sure p1x < p2x if l2p1x > l2p2x:",
"and l1p2y > l2p1y: return True # line2 rectangle is",
"rectangle is inside line1 rect if l1p1x > l2p2x and",
"> l2p2y and l1p2y < l2p1y: return True if l1p1x",
"= tmp l2p1x = line2[0][0] l2p1y = line2[0][1] l2p2x =",
"l2p1x = l2p2x l2p2x = tmp # make sure p1y",
"# make sure p1x < p2x if l1p1x > l1p2x:",
"l1p1x > l2p2x and l1p2x < l2p1x and l1p1y >",
"if l1p1x > l1p2x: tmp = l1p1x l1p1x = l1p2x",
"l1p2x l1p2x = tmp # make sure p1y < p2y",
"l2p1y: return True if l1p1x > l2p2x or l1p2x <",
"< l2p2x and l1p2x > l2p1x and l1p1y < l2p2y",
"l1p1y l1p1y = l1p2y l1p2y = tmp l2p1x = line2[0][0]",
"= l1p1x l1p1x = l1p2x l1p2x = tmp # make",
"rect if l1p1x < l2p2x and l1p2x > l2p1x and",
"inside line1 rect if l1p1x > l2p2x and l1p2x <",
"l1p1x < l2p2x and l1p2x > l2p1x and l1p1y <",
"and l1p1y < l2p2y and l1p2y > l2p1y: return True",
"l1p1y = line1[0][1] l1p2x = line1[1][0] l1p2y = line1[1][1] #",
"line1[0][1] l1p2x = line1[1][0] l1p2y = line1[1][1] # make sure",
"= l1p2x l1p2x = tmp # make sure p1y <",
"l2p2y: tmp = l2p1y l2p1y = l2p2y l2p2y = tmp",
"'xiongyi' line1 = [(200, 100), (200, 400)] line2 = [(190,",
"l1p1x l1p1x = l1p2x l1p2x = tmp # make sure",
"__author__ = 'xiongyi' line1 = [(200, 100), (200, 400)] line2",
"return False if l1p1y > l2p2y or l1p2y < l2p1y:",
"l1p2x: tmp = l1p1x l1p1x = l1p2x l1p2x = tmp",
"and l1p1y > l2p2y and l1p2y < l2p1y: return True"
] |
[
"def get_from(self): rv = self.model for key, subloader in self.extras.items():",
"self.extras = dict((key, self.get(value)) for key, value in extras.items()) self.on_clause",
"func def do_load(self, row, context): return self.func(row, context), True class",
"key == (None,) * len(key): return None, None rv =",
"self def distinct(self, *columns): self._distinct = columns return self class",
"context): raise NotImplementedError def get_columns(self): return [] def get_from(self): return",
"context): return tuple(loader.do_load(row, context)[0] for loader in self.loaders), True class",
"model self.extras = dict((key, self.get(value)) for key, value in extras.items())",
"from_clause = self.get_from() if from_clause is not None: rv =",
"context): distinct = True if self._distinct: if context is None:",
"= rv.select_from(from_clause) return rv.execution_options(loader=self) def do_load(self, row, context): raise NotImplementedError",
"def __init__(self, model, *column_names, **extras): self.model = model self._distinct =",
"select(self.get_columns()) from_clause = self.get_from() if from_clause is not None: rv",
"rv is None: rv = self._do_load(row) ctx[key] = rv else:",
"def __init__(self, func): self.func = func def do_load(self, row, context):",
"self.get(value)) for key, value in extras.items()) self.on_clause = None def",
".declarative import Model class Loader: @classmethod def get(cls, value): from",
"rv = self._do_load(row) ctx[key] = rv else: distinct = False",
"else: self.columns = model self.extras = dict((key, self.get(value)) for key,",
"= func def do_load(self, row, context): return self.func(row, context), True",
"in self._distinct) if key == (None,) * len(key): return None,",
"False else: rv = self._do_load(row) for key, value in self.extras.items():",
"= dict((key, self.get(value)) for key, value in extras.items()) self.on_clause =",
"def __init__(self, values): self.loaders = (self.get(value) for value in values)",
"= [getattr(self.model, name) for name in column_names] self.extras.update((key, self.get(value)) for",
"if from_clause is not None: rv = rv.select_from(from_clause) return rv.execution_options(loader=self)",
"context) if distinct_ is not None: setattr(rv, key, value) return",
"return getattr(self.query, item) class ModelLoader(Loader): def __init__(self, model, *column_names, **extras):",
"value): self.value = value def do_load(self, row, context): return self.value,",
"elif isinstance(value, Alias): rv = AliasLoader(value) elif isinstance(value, Column): rv",
"if from_clause is not None: rv = rv.outerjoin(from_clause, getattr(subloader, 'on_clause',",
"rv = TupleLoader(value) elif callable(value): rv = CallableLoader(value) else: rv",
"self._do_load(row) for key, value in self.extras.items(): value, distinct_ = value.do_load(row,",
"row, context): raise NotImplementedError def get_columns(self): return [] def get_from(self):",
"name in column_names] self.extras.update((key, self.get(value)) for key, value in extras.items())",
"is not None: rv = rv.outerjoin(from_clause, getattr(subloader, 'on_clause', None)) return",
"= self._do_load(row) for key, value in self.extras.items(): value, distinct_ =",
"self._do_load(row) ctx[key] = rv else: distinct = False else: rv",
"if self._distinct: if context is None: context = {} ctx",
"subloader.get_from() if from_clause is not None: rv = rv.outerjoin(from_clause, getattr(subloader,",
"self.func = func def do_load(self, row, context): return self.func(row, context),",
"subloader in self.extras.items(): from_clause = subloader.get_from() if from_clause is not",
"CallableLoader(Loader): def __init__(self, func): self.func = func def do_load(self, row,",
"row): rv = self.model() for c in self.columns: if c",
"rv.__values__[c.name] = row[c] return rv def do_load(self, row, context): distinct",
"rv = ModelLoader(value) elif isinstance(value, Alias): rv = AliasLoader(value) elif",
"row: rv.__values__[c.name] = row[c] return rv def do_load(self, row, context):",
"def do_load(self, row, context): return tuple(loader.do_load(row, context)[0] for loader in",
"is None: rv = self._do_load(row) ctx[key] = rv else: distinct",
"@classmethod def get(cls, value): from .crud import Alias if isinstance(value,",
"for name in column_names] else: self.columns = model self.extras =",
"from_clause is not None: rv = rv.select_from(from_clause) return rv.execution_options(loader=self) def",
"TupleLoader(Loader): def __init__(self, values): self.loaders = (self.get(value) for value in",
"elif isinstance(value, type) and issubclass(value, Model): rv = ModelLoader(value) elif",
"None: rv = self._do_load(row) ctx[key] = rv else: distinct =",
"if isinstance(value, Loader): rv = value elif isinstance(value, type) and",
"CallableLoader(value) else: rv = ValueLoader(value) return rv @property def query(self):",
"def get(cls, value): from .crud import Alias if isinstance(value, Loader):",
"None: rv = rv.select_from(from_clause) return rv.execution_options(loader=self) def do_load(self, row, context):",
"def get_columns(self): yield from self.columns for subloader in self.extras.values(): yield",
"do_load(self, row, context): return row[self.column], True class TupleLoader(Loader): def __init__(self,",
"subloader in self.extras.values(): yield from subloader.get_columns() def get_from(self): rv =",
"True class TupleLoader(Loader): def __init__(self, values): self.loaders = (self.get(value) for",
"in row: rv.__values__[c.name] = row[c] return rv def do_load(self, row,",
"__init__(self, values): self.loaders = (self.get(value) for value in values) def",
"context is None: context = {} ctx = context.setdefault(self._distinct, {})",
"None, None rv = ctx.get(key) if rv is None: rv",
"[getattr(model, name) for name in column_names] else: self.columns = model",
"yield from subloader.get_columns() def get_from(self): rv = self.model for key,",
"= ColumnLoader(value) elif isinstance(value, tuple): rv = TupleLoader(value) elif callable(value):",
"isinstance(value, Alias): rv = AliasLoader(value) elif isinstance(value, Column): rv =",
"self._distinct: if context is None: context = {} ctx =",
"self.on_clause = on_clause return self def distinct(self, *columns): self._distinct =",
"value elif isinstance(value, type) and issubclass(value, Model): rv = ModelLoader(value)",
"name) for name in column_names] else: self.columns = model self.extras",
"on_clause): self.on_clause = on_clause return self def distinct(self, *columns): self._distinct",
"(None,) * len(key): return None, None rv = ctx.get(key) if",
"in column_names] self.extras.update((key, self.get(value)) for key, value in extras.items()) return",
"else: rv = ValueLoader(value) return rv @property def query(self): rv",
"def query(self): rv = select(self.get_columns()) from_clause = self.get_from() if from_clause",
"rv = CallableLoader(value) else: rv = ValueLoader(value) return rv @property",
"*column_names, **extras): self.model = model self._distinct = None if column_names:",
"rv = ColumnLoader(value) elif isinstance(value, tuple): rv = TupleLoader(value) elif",
"= self.get_from() if from_clause is not None: rv = rv.select_from(from_clause)",
"import Model class Loader: @classmethod def get(cls, value): from .crud",
"= ModelLoader(value) elif isinstance(value, Alias): rv = AliasLoader(value) elif isinstance(value,",
"key, subloader in self.extras.items(): from_clause = subloader.get_from() if from_clause is",
"**extras): if column_names: self.columns = [getattr(self.model, name) for name in",
"for key, value in self.extras.items(): value, distinct_ = value.do_load(row, context)",
"func): self.func = func def do_load(self, row, context): return self.func(row,",
"get_from(self): return None def __getattr__(self, item): return getattr(self.query, item) class",
"rv = select(self.get_columns()) from_clause = self.get_from() if from_clause is not",
"model, *column_names, **extras): self.model = model self._distinct = None if",
"key, value in extras.items()) return self def on(self, on_clause): self.on_clause",
"values) def do_load(self, row, context): return tuple(loader.do_load(row, context)[0] for loader",
"for c in self.columns: if c in row: rv.__values__[c.name] =",
"= False else: rv = self._do_load(row) for key, value in",
"= column def do_load(self, row, context): return row[self.column], True class",
"sqlalchemy import select from sqlalchemy.schema import Column from .declarative import",
"return self.func(row, context), True class ValueLoader(Loader): def __init__(self, value): self.value",
"self.column = column def do_load(self, row, context): return row[self.column], True",
"import select from sqlalchemy.schema import Column from .declarative import Model",
"= on_clause return self def distinct(self, *columns): self._distinct = columns",
"= ValueLoader(value) return rv @property def query(self): rv = select(self.get_columns())",
"rv def do_load(self, row, context): distinct = True if self._distinct:",
"return rv def load(self, *column_names, **extras): if column_names: self.columns =",
"do_load(self, row, context): return self.func(row, context), True class ValueLoader(Loader): def",
"@property def query(self): rv = select(self.get_columns()) from_clause = self.get_from() if",
"__init__(self, column): self.column = column def do_load(self, row, context): return",
"from subloader.get_columns() def get_from(self): rv = self.model for key, subloader",
"tuple(loader.do_load(row, context)[0] for loader in self.loaders), True class CallableLoader(Loader): def",
"__getattr__(self, item): return getattr(self.query, item) class ModelLoader(Loader): def __init__(self, model,",
"None: setattr(rv, key, value) return rv, distinct def get_columns(self): yield",
"def do_load(self, row, context): raise NotImplementedError def get_columns(self): return []",
"is not None: setattr(rv, key, value) return rv, distinct def",
"* len(key): return None, None rv = ctx.get(key) if rv",
"True if self._distinct: if context is None: context = {}",
"for key, value in extras.items()) return self def on(self, on_clause):",
"from .crud import Alias if isinstance(value, Loader): rv = value",
"key, value in self.extras.items(): value, distinct_ = value.do_load(row, context) if",
"value): from .crud import Alias if isinstance(value, Loader): rv =",
"return row[self.column], True class TupleLoader(Loader): def __init__(self, values): self.loaders =",
"in extras.items()) self.on_clause = None def _do_load(self, row): rv =",
"class TupleLoader(Loader): def __init__(self, values): self.loaders = (self.get(value) for value",
"tuple(row[col] for col in self._distinct) if key == (None,) *",
"= (self.get(value) for value in values) def do_load(self, row, context):",
"def __init__(self, value): self.value = value def do_load(self, row, context):",
"key = tuple(row[col] for col in self._distinct) if key ==",
"for key, subloader in self.extras.items(): from_clause = subloader.get_from() if from_clause",
"self class AliasLoader(ModelLoader): def __init__(self, alias, *column_names, **extras): super().__init__(alias, *column_names,",
"if c in row: rv.__values__[c.name] = row[c] return rv def",
"context): return row[self.column], True class TupleLoader(Loader): def __init__(self, values): self.loaders",
"class ColumnLoader(Loader): def __init__(self, column): self.column = column def do_load(self,",
"not None: rv = rv.outerjoin(from_clause, getattr(subloader, 'on_clause', None)) return rv",
"self.get_from() if from_clause is not None: rv = rv.select_from(from_clause) return",
"in self.loaders), True class CallableLoader(Loader): def __init__(self, func): self.func =",
"ModelLoader(value) elif isinstance(value, Alias): rv = AliasLoader(value) elif isinstance(value, Column):",
"return rv.execution_options(loader=self) def do_load(self, row, context): raise NotImplementedError def get_columns(self):",
"columns return self class AliasLoader(ModelLoader): def __init__(self, alias, *column_names, **extras):",
"ValueLoader(Loader): def __init__(self, value): self.value = value def do_load(self, row,",
"select from sqlalchemy.schema import Column from .declarative import Model class",
"= model self._distinct = None if column_names: self.columns = [getattr(model,",
"import Alias if isinstance(value, Loader): rv = value elif isinstance(value,",
"rv = ValueLoader(value) return rv @property def query(self): rv =",
"NotImplementedError def get_columns(self): return [] def get_from(self): return None def",
"def do_load(self, row, context): distinct = True if self._distinct: if",
"class ModelLoader(Loader): def __init__(self, model, *column_names, **extras): self.model = model",
"__init__(self, alias, *column_names, **extras): super().__init__(alias, *column_names, **extras) class ColumnLoader(Loader): def",
"isinstance(value, Column): rv = ColumnLoader(value) elif isinstance(value, tuple): rv =",
"subloader.get_columns() def get_from(self): rv = self.model for key, subloader in",
"Column): rv = ColumnLoader(value) elif isinstance(value, tuple): rv = TupleLoader(value)",
"for name in column_names] self.extras.update((key, self.get(value)) for key, value in",
"callable(value): rv = CallableLoader(value) else: rv = ValueLoader(value) return rv",
"self.columns = model self.extras = dict((key, self.get(value)) for key, value",
"self.get(value)) for key, value in extras.items()) return self def on(self,",
"do_load(self, row, context): distinct = True if self._distinct: if context",
"self.func(row, context), True class ValueLoader(Loader): def __init__(self, value): self.value =",
"row[c] return rv def do_load(self, row, context): distinct = True",
"self.on_clause = None def _do_load(self, row): rv = self.model() for",
"self.model = model self._distinct = None if column_names: self.columns =",
"value in extras.items()) return self def on(self, on_clause): self.on_clause =",
"distinct(self, *columns): self._distinct = columns return self class AliasLoader(ModelLoader): def",
"for col in self._distinct) if key == (None,) * len(key):",
"if context is None: context = {} ctx = context.setdefault(self._distinct,",
"in self.extras.items(): value, distinct_ = value.do_load(row, context) if distinct_ is",
"from_clause = subloader.get_from() if from_clause is not None: rv =",
"rv = rv.select_from(from_clause) return rv.execution_options(loader=self) def do_load(self, row, context): raise",
"{} ctx = context.setdefault(self._distinct, {}) key = tuple(row[col] for col",
"return self class AliasLoader(ModelLoader): def __init__(self, alias, *column_names, **extras): super().__init__(alias,",
"= TupleLoader(value) elif callable(value): rv = CallableLoader(value) else: rv =",
"rv.execution_options(loader=self) def do_load(self, row, context): raise NotImplementedError def get_columns(self): return",
"= AliasLoader(value) elif isinstance(value, Column): rv = ColumnLoader(value) elif isinstance(value,",
"def _do_load(self, row): rv = self.model() for c in self.columns:",
"= CallableLoader(value) else: rv = ValueLoader(value) return rv @property def",
"value in values) def do_load(self, row, context): return tuple(loader.do_load(row, context)[0]",
"*column_names, **extras) class ColumnLoader(Loader): def __init__(self, column): self.column = column",
"setattr(rv, key, value) return rv, distinct def get_columns(self): yield from",
"not None: setattr(rv, key, value) return rv, distinct def get_columns(self):",
"row[self.column], True class TupleLoader(Loader): def __init__(self, values): self.loaders = (self.get(value)",
"row, context): return self.func(row, context), True class ValueLoader(Loader): def __init__(self,",
"column def do_load(self, row, context): return row[self.column], True class TupleLoader(Loader):",
"elif isinstance(value, Column): rv = ColumnLoader(value) elif isinstance(value, tuple): rv",
"isinstance(value, Loader): rv = value elif isinstance(value, type) and issubclass(value,",
"col in self._distinct) if key == (None,) * len(key): return",
"isinstance(value, tuple): rv = TupleLoader(value) elif callable(value): rv = CallableLoader(value)",
"return self def on(self, on_clause): self.on_clause = on_clause return self",
"get_columns(self): yield from self.columns for subloader in self.extras.values(): yield from",
"= value.do_load(row, context) if distinct_ is not None: setattr(rv, key,",
"value) return rv, distinct def get_columns(self): yield from self.columns for",
"elif isinstance(value, tuple): rv = TupleLoader(value) elif callable(value): rv =",
"rv = self.model for key, subloader in self.extras.items(): from_clause =",
"return rv, distinct def get_columns(self): yield from self.columns for subloader",
"Loader: @classmethod def get(cls, value): from .crud import Alias if",
"if column_names: self.columns = [getattr(self.model, name) for name in column_names]",
"alias, *column_names, **extras): super().__init__(alias, *column_names, **extras) class ColumnLoader(Loader): def __init__(self,",
"= self.model for key, subloader in self.extras.items(): from_clause = subloader.get_from()",
"= self.model() for c in self.columns: if c in row:",
"distinct def get_columns(self): yield from self.columns for subloader in self.extras.values():",
"self._distinct = columns return self class AliasLoader(ModelLoader): def __init__(self, alias,",
"name) for name in column_names] self.extras.update((key, self.get(value)) for key, value",
"= value elif isinstance(value, type) and issubclass(value, Model): rv =",
"= None def _do_load(self, row): rv = self.model() for c",
"distinct_ = value.do_load(row, context) if distinct_ is not None: setattr(rv,",
"type) and issubclass(value, Model): rv = ModelLoader(value) elif isinstance(value, Alias):",
"self.loaders), True class CallableLoader(Loader): def __init__(self, func): self.func = func",
"from sqlalchemy.schema import Column from .declarative import Model class Loader:",
"value.do_load(row, context) if distinct_ is not None: setattr(rv, key, value)",
"for subloader in self.extras.values(): yield from subloader.get_columns() def get_from(self): rv",
"column_names: self.columns = [getattr(self.model, name) for name in column_names] self.extras.update((key,",
"= rv.outerjoin(from_clause, getattr(subloader, 'on_clause', None)) return rv def load(self, *column_names,",
"self.extras.values(): yield from subloader.get_columns() def get_from(self): rv = self.model for",
"= select(self.get_columns()) from_clause = self.get_from() if from_clause is not None:",
"self.columns: if c in row: rv.__values__[c.name] = row[c] return rv",
"None rv = ctx.get(key) if rv is None: rv =",
"self.columns = [getattr(model, name) for name in column_names] else: self.columns",
"ctx.get(key) if rv is None: rv = self._do_load(row) ctx[key] =",
"load(self, *column_names, **extras): if column_names: self.columns = [getattr(self.model, name) for",
"yield from self.columns for subloader in self.extras.values(): yield from subloader.get_columns()",
"self.model for key, subloader in self.extras.items(): from_clause = subloader.get_from() if",
"True class CallableLoader(Loader): def __init__(self, func): self.func = func def",
"in column_names] else: self.columns = model self.extras = dict((key, self.get(value))",
"Model class Loader: @classmethod def get(cls, value): from .crud import",
"not None: rv = rv.select_from(from_clause) return rv.execution_options(loader=self) def do_load(self, row,",
"if rv is None: rv = self._do_load(row) ctx[key] = rv",
"len(key): return None, None rv = ctx.get(key) if rv is",
"self.loaders = (self.get(value) for value in values) def do_load(self, row,",
"getattr(self.query, item) class ModelLoader(Loader): def __init__(self, model, *column_names, **extras): self.model",
"None if column_names: self.columns = [getattr(model, name) for name in",
"super().__init__(alias, *column_names, **extras) class ColumnLoader(Loader): def __init__(self, column): self.column =",
"TupleLoader(value) elif callable(value): rv = CallableLoader(value) else: rv = ValueLoader(value)",
"if distinct_ is not None: setattr(rv, key, value) return rv,",
"distinct = True if self._distinct: if context is None: context",
"None def __getattr__(self, item): return getattr(self.query, item) class ModelLoader(Loader): def",
"context): return self.func(row, context), True class ValueLoader(Loader): def __init__(self, value):",
"return rv def do_load(self, row, context): distinct = True if",
"= True if self._distinct: if context is None: context =",
"elif callable(value): rv = CallableLoader(value) else: rv = ValueLoader(value) return",
"class CallableLoader(Loader): def __init__(self, func): self.func = func def do_load(self,",
"do_load(self, row, context): raise NotImplementedError def get_columns(self): return [] def",
"None: rv = rv.outerjoin(from_clause, getattr(subloader, 'on_clause', None)) return rv def",
"in self.extras.values(): yield from subloader.get_columns() def get_from(self): rv = self.model",
"self.extras.update((key, self.get(value)) for key, value in extras.items()) return self def",
"__init__(self, model, *column_names, **extras): self.model = model self._distinct = None",
"if key == (None,) * len(key): return None, None rv",
"= context.setdefault(self._distinct, {}) key = tuple(row[col] for col in self._distinct)",
"from self.columns for subloader in self.extras.values(): yield from subloader.get_columns() def",
"context), True class ValueLoader(Loader): def __init__(self, value): self.value = value",
"rv = ctx.get(key) if rv is None: rv = self._do_load(row)",
"context)[0] for loader in self.loaders), True class CallableLoader(Loader): def __init__(self,",
"rv.select_from(from_clause) return rv.execution_options(loader=self) def do_load(self, row, context): raise NotImplementedError def",
"model self._distinct = None if column_names: self.columns = [getattr(model, name)",
"= {} ctx = context.setdefault(self._distinct, {}) key = tuple(row[col] for",
"True class ValueLoader(Loader): def __init__(self, value): self.value = value def",
"AliasLoader(value) elif isinstance(value, Column): rv = ColumnLoader(value) elif isinstance(value, tuple):",
"rv = value elif isinstance(value, type) and issubclass(value, Model): rv",
"from .declarative import Model class Loader: @classmethod def get(cls, value):",
"return [] def get_from(self): return None def __getattr__(self, item): return",
"row, context): distinct = True if self._distinct: if context is",
"Model): rv = ModelLoader(value) elif isinstance(value, Alias): rv = AliasLoader(value)",
"def on(self, on_clause): self.on_clause = on_clause return self def distinct(self,",
"extras.items()) self.on_clause = None def _do_load(self, row): rv = self.model()",
"= [getattr(model, name) for name in column_names] else: self.columns =",
"else: distinct = False else: rv = self._do_load(row) for key,",
"column): self.column = column def do_load(self, row, context): return row[self.column],",
"{}) key = tuple(row[col] for col in self._distinct) if key",
"None: context = {} ctx = context.setdefault(self._distinct, {}) key =",
"class Loader: @classmethod def get(cls, value): from .crud import Alias",
"Column from .declarative import Model class Loader: @classmethod def get(cls,",
"extras.items()) return self def on(self, on_clause): self.on_clause = on_clause return",
"rv.outerjoin(from_clause, getattr(subloader, 'on_clause', None)) return rv def load(self, *column_names, **extras):",
"*column_names, **extras): super().__init__(alias, *column_names, **extras) class ColumnLoader(Loader): def __init__(self, column):",
"get_columns(self): return [] def get_from(self): return None def __getattr__(self, item):",
"column_names] self.extras.update((key, self.get(value)) for key, value in extras.items()) return self",
"def load(self, *column_names, **extras): if column_names: self.columns = [getattr(self.model, name)",
"on_clause return self def distinct(self, *columns): self._distinct = columns return",
"def get_columns(self): return [] def get_from(self): return None def __getattr__(self,",
"def __init__(self, column): self.column = column def do_load(self, row, context):",
"def get_from(self): return None def __getattr__(self, item): return getattr(self.query, item)",
"get_from(self): rv = self.model for key, subloader in self.extras.items(): from_clause",
"for loader in self.loaders), True class CallableLoader(Loader): def __init__(self, func):",
"self.extras.items(): from_clause = subloader.get_from() if from_clause is not None: rv",
"context.setdefault(self._distinct, {}) key = tuple(row[col] for col in self._distinct) if",
"rv = self.model() for c in self.columns: if c in",
"self.model() for c in self.columns: if c in row: rv.__values__[c.name]",
"= ctx.get(key) if rv is None: rv = self._do_load(row) ctx[key]",
"getattr(subloader, 'on_clause', None)) return rv def load(self, *column_names, **extras): if",
"item): return getattr(self.query, item) class ModelLoader(Loader): def __init__(self, model, *column_names,",
"query(self): rv = select(self.get_columns()) from_clause = self.get_from() if from_clause is",
"Alias if isinstance(value, Loader): rv = value elif isinstance(value, type)",
"row, context): return row[self.column], True class TupleLoader(Loader): def __init__(self, values):",
"'on_clause', None)) return rv def load(self, *column_names, **extras): if column_names:",
"return tuple(loader.do_load(row, context)[0] for loader in self.loaders), True class CallableLoader(Loader):",
"raise NotImplementedError def get_columns(self): return [] def get_from(self): return None",
"else: rv = self._do_load(row) for key, value in self.extras.items(): value,",
"ColumnLoader(Loader): def __init__(self, column): self.column = column def do_load(self, row,",
"context = {} ctx = context.setdefault(self._distinct, {}) key = tuple(row[col]",
"def do_load(self, row, context): return self.func(row, context), True class ValueLoader(Loader):",
"isinstance(value, type) and issubclass(value, Model): rv = ModelLoader(value) elif isinstance(value,",
"ModelLoader(Loader): def __init__(self, model, *column_names, **extras): self.model = model self._distinct",
"key, value) return rv, distinct def get_columns(self): yield from self.columns",
"<reponame>p4l1ly/gino<gh_stars>0 from sqlalchemy import select from sqlalchemy.schema import Column from",
"from sqlalchemy import select from sqlalchemy.schema import Column from .declarative",
"rv = AliasLoader(value) elif isinstance(value, Column): rv = ColumnLoader(value) elif",
"issubclass(value, Model): rv = ModelLoader(value) elif isinstance(value, Alias): rv =",
"= columns return self class AliasLoader(ModelLoader): def __init__(self, alias, *column_names,",
"tuple): rv = TupleLoader(value) elif callable(value): rv = CallableLoader(value) else:",
"in self.columns: if c in row: rv.__values__[c.name] = row[c] return",
"rv def load(self, *column_names, **extras): if column_names: self.columns = [getattr(self.model,",
"class ValueLoader(Loader): def __init__(self, value): self.value = value def do_load(self,",
"self def on(self, on_clause): self.on_clause = on_clause return self def",
"column_names: self.columns = [getattr(model, name) for name in column_names] else:",
"**extras) class ColumnLoader(Loader): def __init__(self, column): self.column = column def",
"for key, value in extras.items()) self.on_clause = None def _do_load(self,",
"self.columns = [getattr(self.model, name) for name in column_names] self.extras.update((key, self.get(value))",
"= tuple(row[col] for col in self._distinct) if key == (None,)",
"return None, None rv = ctx.get(key) if rv is None:",
"(self.get(value) for value in values) def do_load(self, row, context): return",
"ValueLoader(value) return rv @property def query(self): rv = select(self.get_columns()) from_clause",
"rv = rv.outerjoin(from_clause, getattr(subloader, 'on_clause', None)) return rv def load(self,",
"on(self, on_clause): self.on_clause = on_clause return self def distinct(self, *columns):",
"__init__(self, func): self.func = func def do_load(self, row, context): return",
"self._distinct) if key == (None,) * len(key): return None, None",
"rv = self._do_load(row) for key, value in self.extras.items(): value, distinct_",
"class AliasLoader(ModelLoader): def __init__(self, alias, *column_names, **extras): super().__init__(alias, *column_names, **extras)",
"from_clause is not None: rv = rv.outerjoin(from_clause, getattr(subloader, 'on_clause', None))",
"key, value in extras.items()) self.on_clause = None def _do_load(self, row):",
"rv else: distinct = False else: rv = self._do_load(row) for",
"if column_names: self.columns = [getattr(model, name) for name in column_names]",
"in values) def do_load(self, row, context): return tuple(loader.do_load(row, context)[0] for",
"sqlalchemy.schema import Column from .declarative import Model class Loader: @classmethod",
"[getattr(self.model, name) for name in column_names] self.extras.update((key, self.get(value)) for key,",
"column_names] else: self.columns = model self.extras = dict((key, self.get(value)) for",
"ColumnLoader(value) elif isinstance(value, tuple): rv = TupleLoader(value) elif callable(value): rv",
"def do_load(self, row, context): return row[self.column], True class TupleLoader(Loader): def",
"get(cls, value): from .crud import Alias if isinstance(value, Loader): rv",
"c in row: rv.__values__[c.name] = row[c] return rv def do_load(self,",
"is not None: rv = rv.select_from(from_clause) return rv.execution_options(loader=self) def do_load(self,",
"*column_names, **extras): if column_names: self.columns = [getattr(self.model, name) for name",
"def __getattr__(self, item): return getattr(self.query, item) class ModelLoader(Loader): def __init__(self,",
"for value in values) def do_load(self, row, context): return tuple(loader.do_load(row,",
"c in self.columns: if c in row: rv.__values__[c.name] = row[c]",
"= row[c] return rv def do_load(self, row, context): distinct =",
"= None if column_names: self.columns = [getattr(model, name) for name",
"= model self.extras = dict((key, self.get(value)) for key, value in",
"def __init__(self, alias, *column_names, **extras): super().__init__(alias, *column_names, **extras) class ColumnLoader(Loader):",
"return self def distinct(self, *columns): self._distinct = columns return self",
"[] def get_from(self): return None def __getattr__(self, item): return getattr(self.query,",
"rv @property def query(self): rv = select(self.get_columns()) from_clause = self.get_from()",
"and issubclass(value, Model): rv = ModelLoader(value) elif isinstance(value, Alias): rv",
"__init__(self, value): self.value = value def do_load(self, row, context): return",
"def distinct(self, *columns): self._distinct = columns return self class AliasLoader(ModelLoader):",
"_do_load(self, row): rv = self.model() for c in self.columns: if",
"is None: context = {} ctx = context.setdefault(self._distinct, {}) key",
"value in extras.items()) self.on_clause = None def _do_load(self, row): rv",
"= self._do_load(row) ctx[key] = rv else: distinct = False else:",
"Alias): rv = AliasLoader(value) elif isinstance(value, Column): rv = ColumnLoader(value)",
"AliasLoader(ModelLoader): def __init__(self, alias, *column_names, **extras): super().__init__(alias, *column_names, **extras) class",
"in self.extras.items(): from_clause = subloader.get_from() if from_clause is not None:",
"value, distinct_ = value.do_load(row, context) if distinct_ is not None:",
"dict((key, self.get(value)) for key, value in extras.items()) self.on_clause = None",
"import Column from .declarative import Model class Loader: @classmethod def",
"ctx[key] = rv else: distinct = False else: rv =",
"*columns): self._distinct = columns return self class AliasLoader(ModelLoader): def __init__(self,",
"self.columns for subloader in self.extras.values(): yield from subloader.get_columns() def get_from(self):",
".crud import Alias if isinstance(value, Loader): rv = value elif",
"row, context): return tuple(loader.do_load(row, context)[0] for loader in self.loaders), True",
"= rv else: distinct = False else: rv = self._do_load(row)",
"distinct_ is not None: setattr(rv, key, value) return rv, distinct",
"values): self.loaders = (self.get(value) for value in values) def do_load(self,",
"**extras): super().__init__(alias, *column_names, **extras) class ColumnLoader(Loader): def __init__(self, column): self.column",
"name in column_names] else: self.columns = model self.extras = dict((key,",
"== (None,) * len(key): return None, None rv = ctx.get(key)",
"self.value = value def do_load(self, row, context): return self.value, True",
"value in self.extras.items(): value, distinct_ = value.do_load(row, context) if distinct_",
"item) class ModelLoader(Loader): def __init__(self, model, *column_names, **extras): self.model =",
"ctx = context.setdefault(self._distinct, {}) key = tuple(row[col] for col in",
"Loader): rv = value elif isinstance(value, type) and issubclass(value, Model):",
"self.extras.items(): value, distinct_ = value.do_load(row, context) if distinct_ is not",
"return None def __getattr__(self, item): return getattr(self.query, item) class ModelLoader(Loader):",
"**extras): self.model = model self._distinct = None if column_names: self.columns",
"return rv @property def query(self): rv = select(self.get_columns()) from_clause =",
"self._distinct = None if column_names: self.columns = [getattr(model, name) for",
"in extras.items()) return self def on(self, on_clause): self.on_clause = on_clause",
"distinct = False else: rv = self._do_load(row) for key, value",
"= subloader.get_from() if from_clause is not None: rv = rv.outerjoin(from_clause,",
"do_load(self, row, context): return tuple(loader.do_load(row, context)[0] for loader in self.loaders),",
"None def _do_load(self, row): rv = self.model() for c in",
"None)) return rv def load(self, *column_names, **extras): if column_names: self.columns",
"loader in self.loaders), True class CallableLoader(Loader): def __init__(self, func): self.func",
"rv, distinct def get_columns(self): yield from self.columns for subloader in"
] |
[
"import base64 from dao.user import User from dao.client import Client",
"get_trip_db, get_section_db import emission.analysis.result.carbon as carbon import emission.core.common as common",
"in here, as opposed to the top level as recommended",
"% (uuid, newView)) setCurrView(uuid, newView) # TODO: Add stats about",
"% profile.get(\"curr_view\", \"data\")) return profile.get(\"curr_view\", \"data\") def switchResultDisplay(params): logging.debug(\"params =",
"= params['new_view'] logging.debug(\"Changing choice for user %s to %s\" %",
"first client, the carshare study def getSectionFilter(uuid): # We are",
"to provide client specific user functions def setCurrView(uuid, newView): user",
"unit tests from bottle import template import base64 from dao.user",
"= UUID(params['uuid']) except: uuid = \"temp\" ## For testing purposes",
"None # TODO: Simplify this. runBackgroundTasks are currently only invoked",
"None, returning data\") return \"data\" logging.debug(\"profile.get('curr_view', 'dummy') is %s\" %",
"params['new_view'] logging.debug(\"Changing choice for user %s to %s\" % (uuid,",
"return None # TODO: Simplify this. runBackgroundTasks are currently only",
"Passing in the date range could make it possible for",
"import gamified from emission.clients.recommendation import recommendation from emission.clients.commontrips import commontrips",
"we pass in the day, or a date # range?",
"import User from dao.client import Client user = User.fromUUID(user_uuid) renderedTemplate",
"# Standard imports import logging import math import json from",
"switchResultDisplay(params): logging.debug(\"params = %s\" % (params)) print \"params = %s\"",
"to do any filtering for this study. Bring on the",
"code to pass in the day, and # remove this",
"recommendationResult = base64.b64encode(recommendation.getResult(user_uuid))) return renderedTemplate # These are copy/pasted from",
"def getSectionFilter(uuid): # We are not planning to do any",
"import time # Our imports from emission.core.get_database import get_trip_db, get_section_db",
"scripts more than once a day... def runBackgroundTasks(uuid): today =",
"bottle import template import base64 from dao.user import User from",
"choice for user %s to %s\" % (uuid, newView)) setCurrView(uuid,",
"def switchResultDisplay(params): logging.debug(\"params = %s\" % (params)) print \"params =",
"uuid import UUID from datetime import datetime, timedelta import time",
"We are not planning to do any filtering for this",
"\"data\")) return profile.get(\"curr_view\", \"data\") def switchResultDisplay(params): logging.debug(\"params = %s\" %",
"return {'curr_view': newView } def getResult(user_uuid): # This is in",
"more than once a day... def runBackgroundTasks(uuid): today = datetime.now().date()",
"emission.clients.commontrips import commontrips from emission.clients.data import data # TODO: Consider",
"the date range could make it possible for us to",
"filtering for this study. Bring on the worst! return []",
"runBackgroundTasks(uuid): today = datetime.now().date() runBackgroundTasksForDay(uuid, today) def runBackgroundTasksForDay(uuid, today): leaderboard.runBackgroundTasksForDay(uuid,",
"base64.b64encode(data.getResult(user_uuid)), commonTripsResult = base64.b64encode(commontrips.getResult(user_uuid)), recommendationResult = base64.b64encode(recommendation.getResult(user_uuid))) return renderedTemplate #",
"time.time(), newView) def getCurrView(uuid): user = User.fromUUID(uuid) profile = user.getProfile()",
"# TODO: Consider subclassing to provide client specific user functions",
"[] def clientSpecificSetters(uuid, sectionId, predictedModeMap): return None def getClientConfirmedModeField(): return",
"we don't have to worry about loading bottle in the",
"emission.net.api.stats as stats from emission.core.wrapper.user import User from emission.clients.leaderboard import",
"stats about the switch as part of the final stats-adding",
"% (params)) print \"params = %s\" % (params['uuid']) try: uuid",
"not planning to do any filtering for this study. Bring",
"sectionId, predictedModeMap): return None def getClientConfirmedModeField(): return None # TODO:",
"getResult(user_uuid): # This is in here, as opposed to the",
"User.fromUUID(uuid) profile = user.getProfile() if profile is None: logging.debug(\"profile is",
"from dao.user import User from dao.client import Client user =",
"this. runBackgroundTasks are currently only invoked from the # result",
"None def getClientConfirmedModeField(): return None # TODO: Simplify this. runBackgroundTasks",
"day, or a date # range? Passing in the date",
"This is in here, as opposed to the top level",
"profile is None: logging.debug(\"profile is None, returning data\") return \"data\"",
"part of the final stats-adding pass return {'curr_view': newView }",
"copy/pasted from our first client, the carshare study def getSectionFilter(uuid):",
"math import json from uuid import UUID from datetime import",
"dao.user import User from dao.client import Client user = User.fromUUID(user_uuid)",
"return None def getClientConfirmedModeField(): return None # TODO: Simplify this.",
"User.fromUUID(uuid) user.setClientSpecificProfileFields({'curr_view': newView}) stats.storeResultEntry(uuid, stats.STAT_VIEW_CHOICE, time.time(), newView) def getCurrView(uuid): user",
"provide client specific user functions def setCurrView(uuid, newView): user =",
"base64.b64encode(leaderboard.getResult(user_uuid)), dataResult = base64.b64encode(data.getResult(user_uuid)), commonTripsResult = base64.b64encode(commontrips.getResult(user_uuid)), recommendationResult = base64.b64encode(recommendation.getResult(user_uuid)))",
"currently only invoked from the # result precomputation code. We",
"setCurrView(uuid, newView): user = User.fromUUID(uuid) user.setClientSpecificProfileFields({'curr_view': newView}) stats.storeResultEntry(uuid, stats.STAT_VIEW_CHOICE, time.time(),",
"'dummy') is %s\" % profile.get(\"curr_view\", \"data\")) return profile.get(\"curr_view\", \"data\") def",
"User from dao.client import Client user = User.fromUUID(user_uuid) renderedTemplate =",
"our first client, the carshare study def getSectionFilter(uuid): # We",
"possible for us to run the # scripts more than",
"Our imports from emission.core.get_database import get_trip_db, get_section_db import emission.analysis.result.carbon as",
"# range? Passing in the date range could make it",
"range could make it possible for us to run the",
"user functions def setCurrView(uuid, newView): user = User.fromUUID(uuid) user.setClientSpecificProfileFields({'curr_view': newView})",
"template(\"clients/choice/result_template.html\", variables = json.dumps({'curr_view': getCurrView(user_uuid), 'uuid': str(user_uuid), 'client_key': Client(\"choice\").getClientKey()}), gameResult",
"user = User.fromUUID(uuid) user.setClientSpecificProfileFields({'curr_view': newView}) stats.storeResultEntry(uuid, stats.STAT_VIEW_CHOICE, time.time(), newView) def",
"renderedTemplate # These are copy/pasted from our first client, the",
"newView = params['new_view'] logging.debug(\"Changing choice for user %s to %s\"",
"a date # range? Passing in the date range could",
"functions def setCurrView(uuid, newView): user = User.fromUUID(uuid) user.setClientSpecificProfileFields({'curr_view': newView}) stats.storeResultEntry(uuid,",
"recommendation from emission.clients.commontrips import commontrips from emission.clients.data import data #",
"{'curr_view': newView } def getResult(user_uuid): # This is in here,",
"the PEP # because then we don't have to worry",
"\"data\") def switchResultDisplay(params): logging.debug(\"params = %s\" % (params)) print \"params",
"base64.b64encode(commontrips.getResult(user_uuid)), recommendationResult = base64.b64encode(recommendation.getResult(user_uuid))) return renderedTemplate # These are copy/pasted",
"to pass in the day, and # remove this interface.",
"common import emission.net.api.stats as stats from emission.core.wrapper.user import User from",
"from dao.client import Client user = User.fromUUID(user_uuid) renderedTemplate = template(\"clients/choice/result_template.html\",",
"user = User.fromUUID(uuid) profile = user.getProfile() if profile is None:",
"logging.debug(\"params = %s\" % (params)) print \"params = %s\" %",
"dataResult = base64.b64encode(data.getResult(user_uuid)), commonTripsResult = base64.b64encode(commontrips.getResult(user_uuid)), recommendationResult = base64.b64encode(recommendation.getResult(user_uuid))) return",
"None: logging.debug(\"profile is None, returning data\") return \"data\" logging.debug(\"profile.get('curr_view', 'dummy')",
"stats.storeResultEntry(uuid, stats.STAT_VIEW_CHOICE, time.time(), newView) def getCurrView(uuid): user = User.fromUUID(uuid) profile",
"User.fromUUID(user_uuid) renderedTemplate = template(\"clients/choice/result_template.html\", variables = json.dumps({'curr_view': getCurrView(user_uuid), 'uuid': str(user_uuid),",
"pass in the day, or a date # range? Passing",
"import data # TODO: Consider subclassing to provide client specific",
"result precomputation code. We could change that code to pass",
"day, and # remove this interface. Extra credit: should we",
"us to run the # scripts more than once a",
"# These are copy/pasted from our first client, the carshare",
"uuid = \"temp\" ## For testing purposes newView = params['new_view']",
"newView)) setCurrView(uuid, newView) # TODO: Add stats about the switch",
"stats from emission.core.wrapper.user import User from emission.clients.leaderboard import leaderboard from",
"don't have to worry about loading bottle in the unit",
"credit: should we pass in the day, or a date",
"Extra credit: should we pass in the day, or a",
"TODO: Simplify this. runBackgroundTasks are currently only invoked from the",
"import Client user = User.fromUUID(user_uuid) renderedTemplate = template(\"clients/choice/result_template.html\", variables =",
"base64.b64encode(recommendation.getResult(user_uuid))) return renderedTemplate # These are copy/pasted from our first",
"# Our imports from emission.core.get_database import get_trip_db, get_section_db import emission.analysis.result.carbon",
"# This is in here, as opposed to the top",
"get_section_db import emission.analysis.result.carbon as carbon import emission.core.common as common import",
"date range could make it possible for us to run",
"are copy/pasted from our first client, the carshare study def",
"do any filtering for this study. Bring on the worst!",
"have to worry about loading bottle in the unit tests",
"setCurrView(uuid, newView) # TODO: Add stats about the switch as",
"import User from emission.clients.leaderboard import leaderboard from emission.clients.gamified import gamified",
"variables = json.dumps({'curr_view': getCurrView(user_uuid), 'uuid': str(user_uuid), 'client_key': Client(\"choice\").getClientKey()}), gameResult =",
"import emission.analysis.result.carbon as carbon import emission.core.common as common import emission.net.api.stats",
"Add stats about the switch as part of the final",
"subclassing to provide client specific user functions def setCurrView(uuid, newView):",
"in the unit tests from bottle import template import base64",
"are currently only invoked from the # result precomputation code.",
"predictedModeMap): return None def getClientConfirmedModeField(): return None # TODO: Simplify",
"import emission.net.api.stats as stats from emission.core.wrapper.user import User from emission.clients.leaderboard",
"and # remove this interface. Extra credit: should we pass",
"code. We could change that code to pass in the",
"We could change that code to pass in the day,",
"import template import base64 from dao.user import User from dao.client",
"day... def runBackgroundTasks(uuid): today = datetime.now().date() runBackgroundTasksForDay(uuid, today) def runBackgroundTasksForDay(uuid,",
"Bring on the worst! return [] def clientSpecificSetters(uuid, sectionId, predictedModeMap):",
"the top level as recommended by the PEP # because",
"def getResult(user_uuid): # This is in here, as opposed to",
"the day, and # remove this interface. Extra credit: should",
"= base64.b64encode(recommendation.getResult(user_uuid))) return renderedTemplate # These are copy/pasted from our",
"emission.core.common as common import emission.net.api.stats as stats from emission.core.wrapper.user import",
"json.dumps({'curr_view': getCurrView(user_uuid), 'uuid': str(user_uuid), 'client_key': Client(\"choice\").getClientKey()}), gameResult = base64.b64encode(gamified.getResult(user_uuid)), leaderboardResult",
"# TODO: Simplify this. runBackgroundTasks are currently only invoked from",
"runBackgroundTasksForDay(uuid, today) def runBackgroundTasksForDay(uuid, today): leaderboard.runBackgroundTasksForDay(uuid, today) gamified.runBackgroundTasksForDay(uuid, today) data.runBackgroundTasksForDay(uuid,",
"User from emission.clients.leaderboard import leaderboard from emission.clients.gamified import gamified from",
"should we pass in the day, or a date #",
"bottle in the unit tests from bottle import template import",
"def runBackgroundTasks(uuid): today = datetime.now().date() runBackgroundTasksForDay(uuid, today) def runBackgroundTasksForDay(uuid, today):",
"%s\" % (params['uuid']) try: uuid = UUID(params['uuid']) except: uuid =",
"# result precomputation code. We could change that code to",
"(uuid, newView)) setCurrView(uuid, newView) # TODO: Add stats about the",
"uuid = UUID(params['uuid']) except: uuid = \"temp\" ## For testing",
"top level as recommended by the PEP # because then",
"if profile is None: logging.debug(\"profile is None, returning data\") return",
"pass in the day, and # remove this interface. Extra",
"today = datetime.now().date() runBackgroundTasksForDay(uuid, today) def runBackgroundTasksForDay(uuid, today): leaderboard.runBackgroundTasksForDay(uuid, today)",
"from datetime import datetime, timedelta import time # Our imports",
"= user.getProfile() if profile is None: logging.debug(\"profile is None, returning",
"'uuid': str(user_uuid), 'client_key': Client(\"choice\").getClientKey()}), gameResult = base64.b64encode(gamified.getResult(user_uuid)), leaderboardResult = base64.b64encode(leaderboard.getResult(user_uuid)),",
"emission.clients.gamified import gamified from emission.clients.recommendation import recommendation from emission.clients.commontrips import",
"getCurrView(user_uuid), 'uuid': str(user_uuid), 'client_key': Client(\"choice\").getClientKey()}), gameResult = base64.b64encode(gamified.getResult(user_uuid)), leaderboardResult =",
"return [] def clientSpecificSetters(uuid, sectionId, predictedModeMap): return None def getClientConfirmedModeField():",
"remove this interface. Extra credit: should we pass in the",
"try: uuid = UUID(params['uuid']) except: uuid = \"temp\" ## For",
"from our first client, the carshare study def getSectionFilter(uuid): #",
"profile = user.getProfile() if profile is None: logging.debug(\"profile is None,",
"because then we don't have to worry about loading bottle",
"getClientConfirmedModeField(): return None # TODO: Simplify this. runBackgroundTasks are currently",
"user = User.fromUUID(user_uuid) renderedTemplate = template(\"clients/choice/result_template.html\", variables = json.dumps({'curr_view': getCurrView(user_uuid),",
"= %s\" % (params['uuid']) try: uuid = UUID(params['uuid']) except: uuid",
"run the # scripts more than once a day... def",
"invoked from the # result precomputation code. We could change",
"profile.get(\"curr_view\", \"data\") def switchResultDisplay(params): logging.debug(\"params = %s\" % (params)) print",
"final stats-adding pass return {'curr_view': newView } def getResult(user_uuid): #",
"Client(\"choice\").getClientKey()}), gameResult = base64.b64encode(gamified.getResult(user_uuid)), leaderboardResult = base64.b64encode(leaderboard.getResult(user_uuid)), dataResult = base64.b64encode(data.getResult(user_uuid)),",
"emission.clients.leaderboard import leaderboard from emission.clients.gamified import gamified from emission.clients.recommendation import",
"getSectionFilter(uuid): # We are not planning to do any filtering",
"import logging import math import json from uuid import UUID",
"% (params['uuid']) try: uuid = UUID(params['uuid']) except: uuid = \"temp\"",
"as stats from emission.core.wrapper.user import User from emission.clients.leaderboard import leaderboard",
"= %s\" % (params)) print \"params = %s\" % (params['uuid'])",
"from emission.core.get_database import get_trip_db, get_section_db import emission.analysis.result.carbon as carbon import",
"from emission.clients.gamified import gamified from emission.clients.recommendation import recommendation from emission.clients.commontrips",
"specific user functions def setCurrView(uuid, newView): user = User.fromUUID(uuid) user.setClientSpecificProfileFields({'curr_view':",
"def getClientConfirmedModeField(): return None # TODO: Simplify this. runBackgroundTasks are",
"to the top level as recommended by the PEP #",
"datetime.now().date() runBackgroundTasksForDay(uuid, today) def runBackgroundTasksForDay(uuid, today): leaderboard.runBackgroundTasksForDay(uuid, today) gamified.runBackgroundTasksForDay(uuid, today)",
"return renderedTemplate # These are copy/pasted from our first client,",
"profile.get(\"curr_view\", \"data\")) return profile.get(\"curr_view\", \"data\") def switchResultDisplay(params): logging.debug(\"params = %s\"",
"= \"temp\" ## For testing purposes newView = params['new_view'] logging.debug(\"Changing",
"template import base64 from dao.user import User from dao.client import",
"import UUID from datetime import datetime, timedelta import time #",
"a day... def runBackgroundTasks(uuid): today = datetime.now().date() runBackgroundTasksForDay(uuid, today) def",
"stats.STAT_VIEW_CHOICE, time.time(), newView) def getCurrView(uuid): user = User.fromUUID(uuid) profile =",
"(params)) print \"params = %s\" % (params['uuid']) try: uuid =",
"emission.analysis.result.carbon as carbon import emission.core.common as common import emission.net.api.stats as",
"from emission.clients.leaderboard import leaderboard from emission.clients.gamified import gamified from emission.clients.recommendation",
"(params['uuid']) try: uuid = UUID(params['uuid']) except: uuid = \"temp\" ##",
"here, as opposed to the top level as recommended by",
"import datetime, timedelta import time # Our imports from emission.core.get_database",
"only invoked from the # result precomputation code. We could",
"str(user_uuid), 'client_key': Client(\"choice\").getClientKey()}), gameResult = base64.b64encode(gamified.getResult(user_uuid)), leaderboardResult = base64.b64encode(leaderboard.getResult(user_uuid)), dataResult",
"= base64.b64encode(commontrips.getResult(user_uuid)), recommendationResult = base64.b64encode(recommendation.getResult(user_uuid))) return renderedTemplate # These are",
"# scripts more than once a day... def runBackgroundTasks(uuid): today",
"clientSpecificSetters(uuid, sectionId, predictedModeMap): return None def getClientConfirmedModeField(): return None #",
"as part of the final stats-adding pass return {'curr_view': newView",
"imports from emission.core.get_database import get_trip_db, get_section_db import emission.analysis.result.carbon as carbon",
"as opposed to the top level as recommended by the",
"planning to do any filtering for this study. Bring on",
"for us to run the # scripts more than once",
"client specific user functions def setCurrView(uuid, newView): user = User.fromUUID(uuid)",
"json from uuid import UUID from datetime import datetime, timedelta",
"# TODO: Add stats about the switch as part of",
"These are copy/pasted from our first client, the carshare study",
"} def getResult(user_uuid): # This is in here, as opposed",
"Standard imports import logging import math import json from uuid",
"%s\" % (params)) print \"params = %s\" % (params['uuid']) try:",
"logging.debug(\"profile.get('curr_view', 'dummy') is %s\" % profile.get(\"curr_view\", \"data\")) return profile.get(\"curr_view\", \"data\")",
"from emission.clients.recommendation import recommendation from emission.clients.commontrips import commontrips from emission.clients.data",
"then we don't have to worry about loading bottle in",
"to run the # scripts more than once a day...",
"are not planning to do any filtering for this study.",
"import leaderboard from emission.clients.gamified import gamified from emission.clients.recommendation import recommendation",
"## For testing purposes newView = params['new_view'] logging.debug(\"Changing choice for",
"worry about loading bottle in the unit tests from bottle",
"TODO: Consider subclassing to provide client specific user functions def",
"carshare study def getSectionFilter(uuid): # We are not planning to",
"date # range? Passing in the date range could make",
"datetime import datetime, timedelta import time # Our imports from",
"the day, or a date # range? Passing in the",
"to worry about loading bottle in the unit tests from",
"except: uuid = \"temp\" ## For testing purposes newView =",
"UUID(params['uuid']) except: uuid = \"temp\" ## For testing purposes newView",
"dao.client import Client user = User.fromUUID(user_uuid) renderedTemplate = template(\"clients/choice/result_template.html\", variables",
"carbon import emission.core.common as common import emission.net.api.stats as stats from",
"for this study. Bring on the worst! return [] def",
"emission.core.wrapper.user import User from emission.clients.leaderboard import leaderboard from emission.clients.gamified import",
"base64.b64encode(gamified.getResult(user_uuid)), leaderboardResult = base64.b64encode(leaderboard.getResult(user_uuid)), dataResult = base64.b64encode(data.getResult(user_uuid)), commonTripsResult = base64.b64encode(commontrips.getResult(user_uuid)),",
"the worst! return [] def clientSpecificSetters(uuid, sectionId, predictedModeMap): return None",
"'client_key': Client(\"choice\").getClientKey()}), gameResult = base64.b64encode(gamified.getResult(user_uuid)), leaderboardResult = base64.b64encode(leaderboard.getResult(user_uuid)), dataResult =",
"it possible for us to run the # scripts more",
"change that code to pass in the day, and #",
"is %s\" % profile.get(\"curr_view\", \"data\")) return profile.get(\"curr_view\", \"data\") def switchResultDisplay(params):",
"imports import logging import math import json from uuid import",
"commontrips from emission.clients.data import data # TODO: Consider subclassing to",
"= base64.b64encode(gamified.getResult(user_uuid)), leaderboardResult = base64.b64encode(leaderboard.getResult(user_uuid)), dataResult = base64.b64encode(data.getResult(user_uuid)), commonTripsResult =",
"could change that code to pass in the day, and",
"as carbon import emission.core.common as common import emission.net.api.stats as stats",
"from emission.clients.data import data # TODO: Consider subclassing to provide",
"import json from uuid import UUID from datetime import datetime,",
"from uuid import UUID from datetime import datetime, timedelta import",
"newView } def getResult(user_uuid): # This is in here, as",
"the # scripts more than once a day... def runBackgroundTasks(uuid):",
"\"temp\" ## For testing purposes newView = params['new_view'] logging.debug(\"Changing choice",
"stats-adding pass return {'curr_view': newView } def getResult(user_uuid): # This",
"return profile.get(\"curr_view\", \"data\") def switchResultDisplay(params): logging.debug(\"params = %s\" % (params))",
"leaderboardResult = base64.b64encode(leaderboard.getResult(user_uuid)), dataResult = base64.b64encode(data.getResult(user_uuid)), commonTripsResult = base64.b64encode(commontrips.getResult(user_uuid)), recommendationResult",
"emission.core.get_database import get_trip_db, get_section_db import emission.analysis.result.carbon as carbon import emission.core.common",
"precomputation code. We could change that code to pass in",
"purposes newView = params['new_view'] logging.debug(\"Changing choice for user %s to",
"once a day... def runBackgroundTasks(uuid): today = datetime.now().date() runBackgroundTasksForDay(uuid, today)",
"data # TODO: Consider subclassing to provide client specific user",
"level as recommended by the PEP # because then we",
"time # Our imports from emission.core.get_database import get_trip_db, get_section_db import",
"could make it possible for us to run the #",
"any filtering for this study. Bring on the worst! return",
"from emission.clients.commontrips import commontrips from emission.clients.data import data # TODO:",
"in the day, and # remove this interface. Extra credit:",
"this interface. Extra credit: should we pass in the day,",
"commonTripsResult = base64.b64encode(commontrips.getResult(user_uuid)), recommendationResult = base64.b64encode(recommendation.getResult(user_uuid))) return renderedTemplate # These",
"loading bottle in the unit tests from bottle import template",
"timedelta import time # Our imports from emission.core.get_database import get_trip_db,",
"the final stats-adding pass return {'curr_view': newView } def getResult(user_uuid):",
"the unit tests from bottle import template import base64 from",
"user.setClientSpecificProfileFields({'curr_view': newView}) stats.storeResultEntry(uuid, stats.STAT_VIEW_CHOICE, time.time(), newView) def getCurrView(uuid): user =",
"\"data\" logging.debug(\"profile.get('curr_view', 'dummy') is %s\" % profile.get(\"curr_view\", \"data\")) return profile.get(\"curr_view\",",
"= base64.b64encode(data.getResult(user_uuid)), commonTripsResult = base64.b64encode(commontrips.getResult(user_uuid)), recommendationResult = base64.b64encode(recommendation.getResult(user_uuid))) return renderedTemplate",
"PEP # because then we don't have to worry about",
"from the # result precomputation code. We could change that",
"Simplify this. runBackgroundTasks are currently only invoked from the #",
"testing purposes newView = params['new_view'] logging.debug(\"Changing choice for user %s",
"data\") return \"data\" logging.debug(\"profile.get('curr_view', 'dummy') is %s\" % profile.get(\"curr_view\", \"data\"))",
"interface. Extra credit: should we pass in the day, or",
"= datetime.now().date() runBackgroundTasksForDay(uuid, today) def runBackgroundTasksForDay(uuid, today): leaderboard.runBackgroundTasksForDay(uuid, today) gamified.runBackgroundTasksForDay(uuid,",
"= template(\"clients/choice/result_template.html\", variables = json.dumps({'curr_view': getCurrView(user_uuid), 'uuid': str(user_uuid), 'client_key': Client(\"choice\").getClientKey()}),",
"as recommended by the PEP # because then we don't",
"Client user = User.fromUUID(user_uuid) renderedTemplate = template(\"clients/choice/result_template.html\", variables = json.dumps({'curr_view':",
"as common import emission.net.api.stats as stats from emission.core.wrapper.user import User",
"make it possible for us to run the # scripts",
"def setCurrView(uuid, newView): user = User.fromUUID(uuid) user.setClientSpecificProfileFields({'curr_view': newView}) stats.storeResultEntry(uuid, stats.STAT_VIEW_CHOICE,",
"= base64.b64encode(leaderboard.getResult(user_uuid)), dataResult = base64.b64encode(data.getResult(user_uuid)), commonTripsResult = base64.b64encode(commontrips.getResult(user_uuid)), recommendationResult =",
"import emission.core.common as common import emission.net.api.stats as stats from emission.core.wrapper.user",
"base64 from dao.user import User from dao.client import Client user",
"= json.dumps({'curr_view': getCurrView(user_uuid), 'uuid': str(user_uuid), 'client_key': Client(\"choice\").getClientKey()}), gameResult = base64.b64encode(gamified.getResult(user_uuid)),",
"For testing purposes newView = params['new_view'] logging.debug(\"Changing choice for user",
"logging.debug(\"Changing choice for user %s to %s\" % (uuid, newView))",
"pass return {'curr_view': newView } def getResult(user_uuid): # This is",
"switch as part of the final stats-adding pass return {'curr_view':",
"%s\" % (uuid, newView)) setCurrView(uuid, newView) # TODO: Add stats",
"runBackgroundTasks are currently only invoked from the # result precomputation",
"this study. Bring on the worst! return [] def clientSpecificSetters(uuid,",
"emission.clients.recommendation import recommendation from emission.clients.commontrips import commontrips from emission.clients.data import",
"renderedTemplate = template(\"clients/choice/result_template.html\", variables = json.dumps({'curr_view': getCurrView(user_uuid), 'uuid': str(user_uuid), 'client_key':",
"newView) # TODO: Add stats about the switch as part",
"# We are not planning to do any filtering for",
"emission.clients.data import data # TODO: Consider subclassing to provide client",
"newView}) stats.storeResultEntry(uuid, stats.STAT_VIEW_CHOICE, time.time(), newView) def getCurrView(uuid): user = User.fromUUID(uuid)",
"or a date # range? Passing in the date range",
"def getCurrView(uuid): user = User.fromUUID(uuid) profile = user.getProfile() if profile",
"by the PEP # because then we don't have to",
"= User.fromUUID(uuid) user.setClientSpecificProfileFields({'curr_view': newView}) stats.storeResultEntry(uuid, stats.STAT_VIEW_CHOICE, time.time(), newView) def getCurrView(uuid):",
"is in here, as opposed to the top level as",
"range? Passing in the date range could make it possible",
"opposed to the top level as recommended by the PEP",
"is None, returning data\") return \"data\" logging.debug(\"profile.get('curr_view', 'dummy') is %s\"",
"of the final stats-adding pass return {'curr_view': newView } def",
"that code to pass in the day, and # remove",
"from emission.core.wrapper.user import User from emission.clients.leaderboard import leaderboard from emission.clients.gamified",
"is None: logging.debug(\"profile is None, returning data\") return \"data\" logging.debug(\"profile.get('curr_view',",
"newView): user = User.fromUUID(uuid) user.setClientSpecificProfileFields({'curr_view': newView}) stats.storeResultEntry(uuid, stats.STAT_VIEW_CHOICE, time.time(), newView)",
"gameResult = base64.b64encode(gamified.getResult(user_uuid)), leaderboardResult = base64.b64encode(leaderboard.getResult(user_uuid)), dataResult = base64.b64encode(data.getResult(user_uuid)), commonTripsResult",
"from bottle import template import base64 from dao.user import User",
"for user %s to %s\" % (uuid, newView)) setCurrView(uuid, newView)",
"import commontrips from emission.clients.data import data # TODO: Consider subclassing",
"= User.fromUUID(uuid) profile = user.getProfile() if profile is None: logging.debug(\"profile",
"print \"params = %s\" % (params['uuid']) try: uuid = UUID(params['uuid'])",
"on the worst! return [] def clientSpecificSetters(uuid, sectionId, predictedModeMap): return",
"TODO: Add stats about the switch as part of the",
"\"params = %s\" % (params['uuid']) try: uuid = UUID(params['uuid']) except:",
"study def getSectionFilter(uuid): # We are not planning to do",
"recommended by the PEP # because then we don't have",
"# remove this interface. Extra credit: should we pass in",
"user %s to %s\" % (uuid, newView)) setCurrView(uuid, newView) #",
"def clientSpecificSetters(uuid, sectionId, predictedModeMap): return None def getClientConfirmedModeField(): return None",
"getCurrView(uuid): user = User.fromUUID(uuid) profile = user.getProfile() if profile is",
"newView) def getCurrView(uuid): user = User.fromUUID(uuid) profile = user.getProfile() if",
"worst! return [] def clientSpecificSetters(uuid, sectionId, predictedModeMap): return None def",
"%s to %s\" % (uuid, newView)) setCurrView(uuid, newView) # TODO:",
"Consider subclassing to provide client specific user functions def setCurrView(uuid,",
"gamified from emission.clients.recommendation import recommendation from emission.clients.commontrips import commontrips from",
"than once a day... def runBackgroundTasks(uuid): today = datetime.now().date() runBackgroundTasksForDay(uuid,",
"client, the carshare study def getSectionFilter(uuid): # We are not",
"logging import math import json from uuid import UUID from",
"returning data\") return \"data\" logging.debug(\"profile.get('curr_view', 'dummy') is %s\" % profile.get(\"curr_view\",",
"the switch as part of the final stats-adding pass return",
"# because then we don't have to worry about loading",
"datetime, timedelta import time # Our imports from emission.core.get_database import",
"tests from bottle import template import base64 from dao.user import",
"return \"data\" logging.debug(\"profile.get('curr_view', 'dummy') is %s\" % profile.get(\"curr_view\", \"data\")) return",
"= User.fromUUID(user_uuid) renderedTemplate = template(\"clients/choice/result_template.html\", variables = json.dumps({'curr_view': getCurrView(user_uuid), 'uuid':",
"the # result precomputation code. We could change that code",
"today) def runBackgroundTasksForDay(uuid, today): leaderboard.runBackgroundTasksForDay(uuid, today) gamified.runBackgroundTasksForDay(uuid, today) data.runBackgroundTasksForDay(uuid, today)",
"user.getProfile() if profile is None: logging.debug(\"profile is None, returning data\")",
"import math import json from uuid import UUID from datetime",
"leaderboard from emission.clients.gamified import gamified from emission.clients.recommendation import recommendation from",
"%s\" % profile.get(\"curr_view\", \"data\")) return profile.get(\"curr_view\", \"data\") def switchResultDisplay(params): logging.debug(\"params",
"about the switch as part of the final stats-adding pass",
"in the date range could make it possible for us",
"about loading bottle in the unit tests from bottle import",
"in the day, or a date # range? Passing in",
"to %s\" % (uuid, newView)) setCurrView(uuid, newView) # TODO: Add",
"the carshare study def getSectionFilter(uuid): # We are not planning",
"<gh_stars>0 # Standard imports import logging import math import json",
"study. Bring on the worst! return [] def clientSpecificSetters(uuid, sectionId,",
"import get_trip_db, get_section_db import emission.analysis.result.carbon as carbon import emission.core.common as",
"logging.debug(\"profile is None, returning data\") return \"data\" logging.debug(\"profile.get('curr_view', 'dummy') is",
"import recommendation from emission.clients.commontrips import commontrips from emission.clients.data import data",
"UUID from datetime import datetime, timedelta import time # Our"
] |
[
"MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO",
"(self.colorize(m.level, m.summary[\"en\"] % m.vars)) ) smsgs = [msg for msg",
"Links'), ('script', 'Script Links'), ('frame', 'Frame Links'), ('iframe', 'IFrame Links'),",
"u\"\\033[0;32m\" color_end = u\"\\033[0;39m\" if level == \"good\": color_start =",
"messages: return \"\" out = [] if [msg for msg",
"if msg.category == category] if not messages: return \"\" out",
"nberr.ERR_READ_TIMEOUT['desc']: self.output(self.error_template % self.red.res_error['desc']) elif self.red.res_error['desc'] == nberr.ERR_HTTP_VERSION['desc']: self.output(self.error_template %",
"substantial portions of the Software. THE SOFTWARE IS PROVIDED \"AS",
"notice shall be included in all copies or substantial portions",
"text formatters.\"\"\" media_type = \"text/plain\" msg_categories = [ rs.c.GENERAL, rs.c.CONNECTION,",
"CLI? class BaseTextFormatter(Formatter): \"\"\" Base class for text formatters.\"\"\" media_type",
"] error_template = \"Error: %s\\n\" def __init__(self, *args, **kw): Formatter.__init__(self,",
"out.append(\"\") for sm in smsgs: out.append( u\" * %s\" %",
"# info color_start = u\"\\033[0;32m\" color_end = u\"\\033[0;39m\" if level",
"error_template = \"Error: %s\\n\" def __init__(self, *args, **kw): Formatter.__init__(self, *args,",
"\"text/plain\" can_multiple = True def __init__(self, *args, **kw): BaseTextFormatter.__init__(self, *args,",
"[u\"%s:%s\" % h for h in red.res_hdrs]) def format_recommendations(self, red):",
"u\"\\033[1;34m\" color_end = u\"\\033[0;39m\" return color_start + string + color_end",
"messages]: out.append(u\"* %s:\" % category) for m in messages: out.append(",
"in smsgs: out.append( u\" * %s\" % (self.colorize(sm.level, sm.summary[\"en\"] %",
"RED's results.\" BaseTextFormatter.finish_output(self) sep = \"=\" * 78 for hdr_tag,",
"as nberr import redbot.speak as rs from redbot.formatter import Formatter",
"def __init__(self, *args, **kw): Formatter.__init__(self, *args, **kw) def start_output(self): pass",
"format_recommendation(self, red, category): messages = [msg for msg in red.messages",
"out.append(u\"* %s:\" % category) for m in messages: out.append( u\"",
"msg.category == category] if not messages: return \"\" out =",
"+ nl + nl) self.done() def format_uri(self, red): return self.colorize(\"uri\",",
"Format a RED object as text. \"\"\" name = \"txt\"",
"THE USE OR OTHER DEALINGS IN THE SOFTWARE. \"\"\" import",
"d in self.red.link_droids if d[1] == hdr_tag] self.output(\"%s\\n%s (%d)\\n%s\\n\" %",
"nl + nl) self.done() def format_uri(self, red): return self.colorize(\"uri\", red.uri)",
"\"\"\"\\ Copyright (c) 2008-2010 <NAME> Permission is hereby granted, free",
"\"text/plain\" def __init__(self, *args, **kw): BaseTextFormatter.__init__(self, *args, **kw) def finish_output(self):",
"self.output(self.format_headers(self.red) + nl + nl) self.output(self.format_recommendations(self.red) + nl) else: if",
"Software without restriction, including without limitation the rights to use,",
"Links'), ('iframe', 'IFrame Links'), ('img', 'Image Links'), ] error_template =",
"78 for hdr_tag, heading in self.link_order: droids = [d[0] for",
"('frame', 'Frame Links'), ('iframe', 'IFrame Links'), ('img', 'Image Links'), ]",
"\"good\": color_start = u\"\\033[1;32m\" color_end = u\"\\033[0;39m\" if level ==",
"elif self.red.res_error['desc'] == nberr.ERR_HTTP_VERSION['desc']: self.output(self.error_template % \"<code>%s</code> isn't HTTP.\" %",
"color_end = u\"\\033[0;39m\" return color_start + string + color_end class",
"NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS",
"copies of the Software, and to permit persons to whom",
"hereby granted, free of charge, to any person obtaining a",
"= \"\"\"\\ Copyright (c) 2008-2010 <NAME> Permission is hereby granted,",
"to deal in the Software without restriction, including without limitation",
"level == \"uri\": color_start = u\"\\033[1;34m\" color_end = u\"\\033[0;39m\" return",
"for d in self.red.link_droids if d[1] == hdr_tag] self.output(\"%s\\n%s (%d)\\n%s\\n\"",
"self.done() class TextListFormatter(BaseTextFormatter): \"\"\" Format multiple RED responses as a",
"*args, **kw) def finish_output(self): BaseTextFormatter.finish_output(self) self.done() class TextListFormatter(BaseTextFormatter): \"\"\" Format",
"OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE",
"self.red.res_error['desc'] == nberr.ERR_URL['desc']: self.output(self.error_template % self.red.res_error.get( 'detail', \"RED can't fetch",
"class for text formatters.\"\"\" media_type = \"text/plain\" msg_categories = [",
"\"\"\" Format a RED object as text. \"\"\" name =",
"self.output(self.format_recommendations(droid) + nl + nl) self.done() def format_uri(self, red): return",
"for REDbot. \"\"\" __author__ = \"<NAME> <<EMAIL>>\" __copyright__ = \"\"\"\\",
"raise AssertionError, \"Unidentified incomplete response error.\" def format_headers(self, red): out",
"m in messages: out.append( u\" * %s\" % (self.colorize(m.level, m.summary[\"en\"]",
"droid in droids: self.output(self.format_uri(droid) + nl + nl) self.output(self.format_headers(droid) +",
"portions of the Software. THE SOFTWARE IS PROVIDED \"AS IS\",",
"%s %s\" % ( red.res_version, red.res_status, red.res_phrase)] return nl.join(out +",
"return nl.join(out) @staticmethod def colorize(level, string): # info color_start =",
"== nberr.ERR_CONNECT['desc']: self.output(self.error_template % \"Could not connect to the server",
"nl + nl) self.output(self.format_recommendations(self.red) + nl) else: if self.red.res_error ==",
"\"\"\" Format multiple RED responses as a textual list. \"\"\"",
"DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,",
"response error.\" def format_headers(self, red): out = [u\"HTTP/%s %s %s\"",
"2008-2010 <NAME> Permission is hereby granted, free of charge, to",
"nberr.ERR_HTTP_VERSION['desc']: self.output(self.error_template % \"<code>%s</code> isn't HTTP.\" % \\ self.red.res_error.get('detail', '')[:20])",
"FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR",
"smsgs: out.append(\"\") for sm in smsgs: out.append( u\" * %s\"",
"can_multiple = True def __init__(self, *args, **kw): BaseTextFormatter.__init__(self, *args, **kw)",
"red): out = [u\"HTTP/%s %s %s\" % ( red.res_version, red.res_status,",
")) if droids: droids.sort(key=operator.attrgetter('uri')) for droid in droids: self.output(self.format_uri(droid) +",
"modify, merge, publish, distribute, sublicense, and/or sell copies of the",
"red.res_version, red.res_status, red.res_phrase)] return nl.join(out + [u\"%s:%s\" % h for",
"ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE",
"import redbot.speak as rs from redbot.formatter import Formatter nl =",
"status(self, msg): pass def finish_output(self): \"Fill in the template with",
"*args, **kw): BaseTextFormatter.__init__(self, *args, **kw) def finish_output(self): BaseTextFormatter.finish_output(self) self.done() class",
"persons to whom the Software is furnished to do so,",
"= u\"\\n\" # TODO: errors and status on stderr with",
"= u\"\\033[1;34m\" color_end = u\"\\033[0;39m\" return color_start + string +",
"limitation the rights to use, copy, modify, merge, publish, distribute,",
"subject to the following conditions: The above copyright notice and",
"OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH",
"\"uri\": color_start = u\"\\033[1;34m\" color_end = u\"\\033[0;39m\" return color_start +",
"BaseTextFormatter.__init__(self, *args, **kw) def finish_output(self): BaseTextFormatter.finish_output(self) self.done() class TextListFormatter(BaseTextFormatter): \"\"\"",
"of the Software. THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT",
"color_end = u\"\\033[0;39m\" if level == \"warning\": color_start = u\"\\033[1;33m\"",
"% ( sep, heading, len(droids), sep )) if droids: droids.sort(key=operator.attrgetter('uri'))",
"can't fetch that URL.\")) elif self.red.res_error['desc'] == nberr.ERR_READ_TIMEOUT['desc']: self.output(self.error_template %",
"%s\\n\" def __init__(self, *args, **kw): Formatter.__init__(self, *args, **kw) def start_output(self):",
"= u\"\\033[0;39m\" return color_start + string + color_end class TextFormatter(BaseTextFormatter):",
"u\"\\n\" # TODO: errors and status on stderr with CLI?",
"connect to the server (%s)\" % \\ self.red.res_error.get('detail', \"unknown\")) elif",
"out = [] if [msg for msg in messages]: out.append(u\"*",
"m.summary[\"en\"] % m.vars)) ) smsgs = [msg for msg in",
"redbot.formatter import Formatter nl = u\"\\n\" # TODO: errors and",
"u\"\\033[0;39m\" return color_start + string + color_end class TextFormatter(BaseTextFormatter): \"\"\"",
"red.res_status, red.res_phrase)] return nl.join(out + [u\"%s:%s\" % h for h",
"class TextListFormatter(BaseTextFormatter): \"\"\" Format multiple RED responses as a textual",
"NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A",
"in messages]: out.append(u\"* %s:\" % category) for m in messages:",
"% ( red.res_version, red.res_status, red.res_phrase)] return nl.join(out + [u\"%s:%s\" %",
"in getattr(m.subrequest, \"messages\", []) if msg.level in [rs.l.BAD]] if smsgs:",
"on stderr with CLI? class BaseTextFormatter(Formatter): \"\"\" Base class for",
"\"bad\": color_start = u\"\\033[1;31m\" color_end = u\"\\033[0;39m\" if level ==",
"Software is furnished to do so, subject to the following",
"redbot.speak as rs from redbot.formatter import Formatter nl = u\"\\n\"",
"color_start = u\"\\033[1;32m\" color_end = u\"\\033[0;39m\" if level == \"bad\":",
"\"text/plain\" msg_categories = [ rs.c.GENERAL, rs.c.CONNECTION, rs.c.CONNEG, rs.c.CACHING, rs.c.VALIDATION, rs.c.RANGE",
"Software. THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF",
"== \"bad\": color_start = u\"\\033[1;31m\" color_end = u\"\\033[0;39m\" if level",
"elif self.red.res_error['desc'] == nberr.ERR_READ_TIMEOUT['desc']: self.output(self.error_template % self.red.res_error['desc']) elif self.red.res_error['desc'] ==",
"msg in red.messages if msg.category == category] if not messages:",
"self.output(self.format_recommendations(self.red) + nl) else: if self.red.res_error == None: pass elif",
"sell copies of the Software, and to permit persons to",
"+ nl + nl) self.output(self.format_recommendations(self.red) + nl) else: if self.red.res_error",
"\"Fill in the template with RED's results.\" if self.red.res_complete: self.output(self.format_headers(self.red)",
"included in all copies or substantial portions of the Software.",
"'Script Links'), ('frame', 'Frame Links'), ('iframe', 'IFrame Links'), ('img', 'Image",
"colorize(level, string): # info color_start = u\"\\033[0;32m\" color_end = u\"\\033[0;39m\"",
"\"unknown\")) elif self.red.res_error['desc'] == nberr.ERR_URL['desc']: self.output(self.error_template % self.red.res_error.get( 'detail', \"RED",
"copy, modify, merge, publish, distribute, sublicense, and/or sell copies of",
"red, chunk): pass def status(self, msg): pass def finish_output(self): \"Fill",
"category): messages = [msg for msg in red.messages if msg.category",
"h in red.res_hdrs]) def format_recommendations(self, red): return \"\".join([self.format_recommendation(red, category) \\",
"incomplete response error.\" def format_headers(self, red): out = [u\"HTTP/%s %s",
"% category) for m in messages: out.append( u\" * %s\"",
"not connect to the server (%s)\" % \\ self.red.res_error.get('detail', \"unknown\"))",
"nberr.ERR_CONNECT['desc']: self.output(self.error_template % \"Could not connect to the server (%s)\"",
"nl.join(out + [u\"%s:%s\" % h for h in red.res_hdrs]) def",
"furnished to do so, subject to the following conditions: The",
"red.messages if msg.category == category] if not messages: return \"\"",
"or substantial portions of the Software. THE SOFTWARE IS PROVIDED",
"EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR",
"self.red.res_error.get( 'detail', \"RED can't fetch that URL.\")) elif self.red.res_error['desc'] ==",
"[]) if msg.level in [rs.l.BAD]] if smsgs: out.append(\"\") for sm",
"rs.c.GENERAL, rs.c.CONNECTION, rs.c.CONNEG, rs.c.CACHING, rs.c.VALIDATION, rs.c.RANGE ] link_order = [",
"def __init__(self, *args, **kw): BaseTextFormatter.__init__(self, *args, **kw) def finish_output(self): BaseTextFormatter.finish_output(self)",
"droids: droids.sort(key=operator.attrgetter('uri')) for droid in droids: self.output(self.format_uri(droid) + nl +",
"name = \"txt\" media_type = \"text/plain\" can_multiple = True def",
"EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES",
"publish, distribute, sublicense, and/or sell copies of the Software, and",
"errors and status on stderr with CLI? class BaseTextFormatter(Formatter): \"\"\"",
"smsgs = [msg for msg in getattr(m.subrequest, \"messages\", []) if",
"return nl.join(out + [u\"%s:%s\" % h for h in red.res_hdrs])",
"msg in messages]: out.append(u\"* %s:\" % category) for m in",
"elif self.red.res_error['desc'] == nberr.ERR_URL['desc']: self.output(self.error_template % self.red.res_error.get( 'detail', \"RED can't",
"\"Software\"), to deal in the Software without restriction, including without",
"URL.\")) elif self.red.res_error['desc'] == nberr.ERR_READ_TIMEOUT['desc']: self.output(self.error_template % self.red.res_error['desc']) elif self.red.res_error['desc']",
"for droid in droids: self.output(self.format_uri(droid) + nl + nl) self.output(self.format_headers(droid)",
"IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS",
"*args, **kw) def finish_output(self): \"Fill in the template with RED's",
"red.res_hdrs]) def format_recommendations(self, red): return \"\".join([self.format_recommendation(red, category) \\ for category",
"multiple RED responses as a textual list. \"\"\" name =",
"self.output(self.format_headers(droid) + nl + nl) self.output(self.format_recommendations(droid) + nl + nl)",
"rs from redbot.formatter import Formatter nl = u\"\\n\" # TODO:",
"out.append( u\" * %s\" % (self.colorize(sm.level, sm.summary[\"en\"] % sm.vars)) )",
"if level == \"warning\": color_start = u\"\\033[1;33m\" color_end = u\"\\033[0;39m\"",
"SOFTWARE. \"\"\" import operator import nbhttp.error as nberr import redbot.speak",
"== \"uri\": color_start = u\"\\033[1;34m\" color_end = u\"\\033[0;39m\" return color_start",
"len(droids), sep )) if droids: droids.sort(key=operator.attrgetter('uri')) for droid in droids:",
"be included in all copies or substantial portions of the",
"hdr_tag, heading in self.link_order: droids = [d[0] for d in",
"self.red.res_complete: self.output(self.format_headers(self.red) + nl + nl) self.output(self.format_recommendations(self.red) + nl) else:",
"feed(self, red, chunk): pass def status(self, msg): pass def finish_output(self):",
"isn't HTTP.\" % \\ self.red.res_error.get('detail', '')[:20]) else: raise AssertionError, \"Unidentified",
"to use, copy, modify, merge, publish, distribute, sublicense, and/or sell",
"TextFormatter(BaseTextFormatter): \"\"\" Format a RED object as text. \"\"\" name",
"category in self.msg_categories]) def format_recommendation(self, red, category): messages = [msg",
"d[1] == hdr_tag] self.output(\"%s\\n%s (%d)\\n%s\\n\" % ( sep, heading, len(droids),",
"nl.join(out) @staticmethod def colorize(level, string): # info color_start = u\"\\033[0;32m\"",
"HAR Formatter for REDbot. \"\"\" __author__ = \"<NAME> <<EMAIL>>\" __copyright__",
"+ nl) else: if self.red.res_error == None: pass elif self.red.res_error['desc']",
") smsgs = [msg for msg in getattr(m.subrequest, \"messages\", [])",
"color_start = u\"\\033[0;32m\" color_end = u\"\\033[0;39m\" if level == \"good\":",
"def finish_output(self): BaseTextFormatter.finish_output(self) self.done() class TextListFormatter(BaseTextFormatter): \"\"\" Format multiple RED",
"nberr.ERR_URL['desc']: self.output(self.error_template % self.red.res_error.get( 'detail', \"RED can't fetch that URL.\"))",
"python \"\"\" HAR Formatter for REDbot. \"\"\" __author__ = \"<NAME>",
"the following conditions: The above copyright notice and this permission",
"category] if not messages: return \"\" out = [] if",
"files (the \"Software\"), to deal in the Software without restriction,",
"responses as a textual list. \"\"\" name = \"txt\" media_type",
"%s\" % (self.colorize(m.level, m.summary[\"en\"] % m.vars)) ) smsgs = [msg",
"self.red.res_error['desc']) elif self.red.res_error['desc'] == nberr.ERR_HTTP_VERSION['desc']: self.output(self.error_template % \"<code>%s</code> isn't HTTP.\"",
"ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF",
"<<EMAIL>>\" __copyright__ = \"\"\"\\ Copyright (c) 2008-2010 <NAME> Permission is",
"finish_output(self): \"Fill in the template with RED's results.\" BaseTextFormatter.finish_output(self) sep",
"DEALINGS IN THE SOFTWARE. \"\"\" import operator import nbhttp.error as",
"self.output(self.error_template % \"<code>%s</code> isn't HTTP.\" % \\ self.red.res_error.get('detail', '')[:20]) else:",
"the rights to use, copy, modify, merge, publish, distribute, sublicense,",
"in droids: self.output(self.format_uri(droid) + nl + nl) self.output(self.format_headers(droid) + nl",
"not messages: return \"\" out = [] if [msg for",
"software and associated documentation files (the \"Software\"), to deal in",
"media_type = \"text/plain\" can_multiple = True def __init__(self, *args, **kw):",
"rs.c.CONNEG, rs.c.CACHING, rs.c.VALIDATION, rs.c.RANGE ] link_order = [ ('link', 'Head",
"('img', 'Image Links'), ] error_template = \"Error: %s\\n\" def __init__(self,",
"notice and this permission notice shall be included in all",
"**kw): Formatter.__init__(self, *args, **kw) def start_output(self): pass def feed(self, red,",
"is hereby granted, free of charge, to any person obtaining",
"msg): pass def finish_output(self): \"Fill in the template with RED's",
"def format_headers(self, red): out = [u\"HTTP/%s %s %s\" % (",
"nl) self.output(self.format_headers(droid) + nl + nl) self.output(self.format_recommendations(droid) + nl +",
"BaseTextFormatter(Formatter): \"\"\" Base class for text formatters.\"\"\" media_type = \"text/plain\"",
"if droids: droids.sort(key=operator.attrgetter('uri')) for droid in droids: self.output(self.format_uri(droid) + nl",
"level == \"good\": color_start = u\"\\033[1;32m\" color_end = u\"\\033[0;39m\" if",
"] link_order = [ ('link', 'Head Links'), ('script', 'Script Links'),",
"Links'), ('frame', 'Frame Links'), ('iframe', 'IFrame Links'), ('img', 'Image Links'),",
"def format_recommendations(self, red): return \"\".join([self.format_recommendation(red, category) \\ for category in",
"[msg for msg in getattr(m.subrequest, \"messages\", []) if msg.level in",
"Links'), ('img', 'Image Links'), ] error_template = \"Error: %s\\n\" def",
"def finish_output(self): \"Fill in the template with RED's results.\" if",
"__copyright__ = \"\"\"\\ Copyright (c) 2008-2010 <NAME> Permission is hereby",
"to the following conditions: The above copyright notice and this",
"conditions: The above copyright notice and this permission notice shall",
"the Software without restriction, including without limitation the rights to",
"textual list. \"\"\" name = \"txt\" media_type = \"text/plain\" can_multiple",
"+ nl) self.output(self.format_recommendations(droid) + nl + nl) self.done() def format_uri(self,",
"THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND",
"if level == \"uri\": color_start = u\"\\033[1;34m\" color_end = u\"\\033[0;39m\"",
"**kw) def finish_output(self): \"Fill in the template with RED's results.\"",
"'Frame Links'), ('iframe', 'IFrame Links'), ('img', 'Image Links'), ] error_template",
"and/or sell copies of the Software, and to permit persons",
"permit persons to whom the Software is furnished to do",
"== nberr.ERR_URL['desc']: self.output(self.error_template % self.red.res_error.get( 'detail', \"RED can't fetch that",
"do so, subject to the following conditions: The above copyright",
"text. \"\"\" name = \"txt\" media_type = \"text/plain\" def __init__(self,",
"any person obtaining a copy of this software and associated",
"*args, **kw): BaseTextFormatter.__init__(self, *args, **kw) def finish_output(self): \"Fill in the",
"WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN",
"[ ('link', 'Head Links'), ('script', 'Script Links'), ('frame', 'Frame Links'),",
"string + color_end class TextFormatter(BaseTextFormatter): \"\"\" Format a RED object",
"import operator import nbhttp.error as nberr import redbot.speak as rs",
"else: raise AssertionError, \"Unidentified incomplete response error.\" def format_headers(self, red):",
"\"txt\" media_type = \"text/plain\" def __init__(self, *args, **kw): BaseTextFormatter.__init__(self, *args,",
"droids.sort(key=operator.attrgetter('uri')) for droid in droids: self.output(self.format_uri(droid) + nl + nl)",
"== nberr.ERR_READ_TIMEOUT['desc']: self.output(self.error_template % self.red.res_error['desc']) elif self.red.res_error['desc'] == nberr.ERR_HTTP_VERSION['desc']: self.output(self.error_template",
"WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT",
"THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE",
"color_end = u\"\\033[0;39m\" if level == \"uri\": color_start = u\"\\033[1;34m\"",
"__init__(self, *args, **kw): BaseTextFormatter.__init__(self, *args, **kw) def finish_output(self): BaseTextFormatter.finish_output(self) self.done()",
"color_end = u\"\\033[0;39m\" if level == \"bad\": color_start = u\"\\033[1;31m\"",
"THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,",
"server (%s)\" % \\ self.red.res_error.get('detail', \"unknown\")) elif self.red.res_error['desc'] == nberr.ERR_URL['desc']:",
"color_end class TextFormatter(BaseTextFormatter): \"\"\" Format a RED object as text.",
"msg.level in [rs.l.BAD]] if smsgs: out.append(\"\") for sm in smsgs:",
"sm.vars)) ) out.append(nl) out.append(nl) return nl.join(out) @staticmethod def colorize(level, string):",
"copy of this software and associated documentation files (the \"Software\"),",
"format_recommendations(self, red): return \"\".join([self.format_recommendation(red, category) \\ for category in self.msg_categories])",
"FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL",
"('iframe', 'IFrame Links'), ('img', 'Image Links'), ] error_template = \"Error:",
"including without limitation the rights to use, copy, modify, merge,",
"OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR",
"( red.res_version, red.res_status, red.res_phrase)] return nl.join(out + [u\"%s:%s\" % h",
"__init__(self, *args, **kw): BaseTextFormatter.__init__(self, *args, **kw) def finish_output(self): \"Fill in",
"nl) self.output(self.format_recommendations(self.red) + nl) else: if self.red.res_error == None: pass",
"TODO: errors and status on stderr with CLI? class BaseTextFormatter(Formatter):",
"sep, heading, len(droids), sep )) if droids: droids.sort(key=operator.attrgetter('uri')) for droid",
"CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS",
"IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER",
"(%d)\\n%s\\n\" % ( sep, heading, len(droids), sep )) if droids:",
"if self.red.res_complete: self.output(self.format_headers(self.red) + nl + nl) self.output(self.format_recommendations(self.red) + nl)",
"= u\"\\033[0;39m\" if level == \"bad\": color_start = u\"\\033[1;31m\" color_end",
"if level == \"bad\": color_start = u\"\\033[1;31m\" color_end = u\"\\033[0;39m\"",
"\"\"\" Base class for text formatters.\"\"\" media_type = \"text/plain\" msg_categories",
"(%s)\" % \\ self.red.res_error.get('detail', \"unknown\")) elif self.red.res_error['desc'] == nberr.ERR_URL['desc']: self.output(self.error_template",
"nl) self.output(self.format_recommendations(droid) + nl + nl) self.done() def format_uri(self, red):",
"error.\" def format_headers(self, red): out = [u\"HTTP/%s %s %s\" %",
"without limitation the rights to use, copy, modify, merge, publish,",
"msg_categories = [ rs.c.GENERAL, rs.c.CONNECTION, rs.c.CONNEG, rs.c.CACHING, rs.c.VALIDATION, rs.c.RANGE ]",
"messages: out.append( u\" * %s\" % (self.colorize(m.level, m.summary[\"en\"] % m.vars))",
"\"\"\" name = \"txt\" media_type = \"text/plain\" def __init__(self, *args,",
"= u\"\\033[0;32m\" color_end = u\"\\033[0;39m\" if level == \"good\": color_start",
"== hdr_tag] self.output(\"%s\\n%s (%d)\\n%s\\n\" % ( sep, heading, len(droids), sep",
"self.red.res_error == None: pass elif self.red.res_error['desc'] == nberr.ERR_CONNECT['desc']: self.output(self.error_template %",
"pass def feed(self, red, chunk): pass def status(self, msg): pass",
"restriction, including without limitation the rights to use, copy, modify,",
"as a textual list. \"\"\" name = \"txt\" media_type =",
"to permit persons to whom the Software is furnished to",
"== None: pass elif self.red.res_error['desc'] == nberr.ERR_CONNECT['desc']: self.output(self.error_template % \"Could",
"% m.vars)) ) smsgs = [msg for msg in getattr(m.subrequest,",
"media_type = \"text/plain\" def __init__(self, *args, **kw): BaseTextFormatter.__init__(self, *args, **kw)",
"(self.colorize(sm.level, sm.summary[\"en\"] % sm.vars)) ) out.append(nl) out.append(nl) return nl.join(out) @staticmethod",
"self.output(self.error_template % self.red.res_error['desc']) elif self.red.res_error['desc'] == nberr.ERR_HTTP_VERSION['desc']: self.output(self.error_template % \"<code>%s</code>",
"= u\"\\033[1;32m\" color_end = u\"\\033[0;39m\" if level == \"bad\": color_start",
"OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF",
"# TODO: errors and status on stderr with CLI? class",
"= [] if [msg for msg in messages]: out.append(u\"* %s:\"",
"for msg in red.messages if msg.category == category] if not",
"u\" * %s\" % (self.colorize(m.level, m.summary[\"en\"] % m.vars)) ) smsgs",
"(c) 2008-2010 <NAME> Permission is hereby granted, free of charge,",
"('link', 'Head Links'), ('script', 'Script Links'), ('frame', 'Frame Links'), ('iframe',",
"color_start = u\"\\033[1;31m\" color_end = u\"\\033[0;39m\" if level == \"warning\":",
"'')[:20]) else: raise AssertionError, \"Unidentified incomplete response error.\" def format_headers(self,",
"OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR",
"deal in the Software without restriction, including without limitation the",
"if not messages: return \"\" out = [] if [msg",
"in [rs.l.BAD]] if smsgs: out.append(\"\") for sm in smsgs: out.append(",
"= \"text/plain\" msg_categories = [ rs.c.GENERAL, rs.c.CONNECTION, rs.c.CONNEG, rs.c.CACHING, rs.c.VALIDATION,",
"return \"\" out = [] if [msg for msg in",
"def feed(self, red, chunk): pass def status(self, msg): pass def",
"if smsgs: out.append(\"\") for sm in smsgs: out.append( u\" *",
"== \"warning\": color_start = u\"\\033[1;33m\" color_end = u\"\\033[0;39m\" if level",
"BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR",
"from redbot.formatter import Formatter nl = u\"\\n\" # TODO: errors",
"in self.red.link_droids if d[1] == hdr_tag] self.output(\"%s\\n%s (%d)\\n%s\\n\" % (",
"with CLI? class BaseTextFormatter(Formatter): \"\"\" Base class for text formatters.\"\"\"",
"ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO",
"for hdr_tag, heading in self.link_order: droids = [d[0] for d",
"= u\"\\033[0;39m\" if level == \"warning\": color_start = u\"\\033[1;33m\" color_end",
"distribute, sublicense, and/or sell copies of the Software, and to",
"name = \"txt\" media_type = \"text/plain\" def __init__(self, *args, **kw):",
"PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR",
"the server (%s)\" % \\ self.red.res_error.get('detail', \"unknown\")) elif self.red.res_error['desc'] ==",
"with RED's results.\" if self.red.res_complete: self.output(self.format_headers(self.red) + nl + nl)",
"the Software, and to permit persons to whom the Software",
"*args, **kw) def start_output(self): pass def feed(self, red, chunk): pass",
"and associated documentation files (the \"Software\"), to deal in the",
"[u\"HTTP/%s %s %s\" % ( red.res_version, red.res_status, red.res_phrase)] return nl.join(out",
"== category] if not messages: return \"\" out = []",
"= \"txt\" media_type = \"text/plain\" def __init__(self, *args, **kw): BaseTextFormatter.__init__(self,",
"None: pass elif self.red.res_error['desc'] == nberr.ERR_CONNECT['desc']: self.output(self.error_template % \"Could not",
"out.append( u\" * %s\" % (self.colorize(m.level, m.summary[\"en\"] % m.vars)) )",
"msg in getattr(m.subrequest, \"messages\", []) if msg.level in [rs.l.BAD]] if",
"the Software. THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY",
"\"\"\" import operator import nbhttp.error as nberr import redbot.speak as",
"to whom the Software is furnished to do so, subject",
"THE SOFTWARE. \"\"\" import operator import nbhttp.error as nberr import",
"FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT",
"self.msg_categories]) def format_recommendation(self, red, category): messages = [msg for msg",
"import Formatter nl = u\"\\n\" # TODO: errors and status",
"self.output(self.error_template % \"Could not connect to the server (%s)\" %",
"to the server (%s)\" % \\ self.red.res_error.get('detail', \"unknown\")) elif self.red.res_error['desc']",
"if level == \"good\": color_start = u\"\\033[1;32m\" color_end = u\"\\033[0;39m\"",
"= [ rs.c.GENERAL, rs.c.CONNECTION, rs.c.CONNEG, rs.c.CACHING, rs.c.VALIDATION, rs.c.RANGE ] link_order",
"= \"<NAME> <<EMAIL>>\" __copyright__ = \"\"\"\\ Copyright (c) 2008-2010 <NAME>",
"color_start + string + color_end class TextFormatter(BaseTextFormatter): \"\"\" Format a",
"= [msg for msg in red.messages if msg.category == category]",
"WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT",
"% self.red.res_error.get( 'detail', \"RED can't fetch that URL.\")) elif self.red.res_error['desc']",
"u\"\\033[0;39m\" if level == \"warning\": color_start = u\"\\033[1;33m\" color_end =",
"% \\ self.red.res_error.get('detail', '')[:20]) else: raise AssertionError, \"Unidentified incomplete response",
"link_order = [ ('link', 'Head Links'), ('script', 'Script Links'), ('frame',",
"TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE",
"u\"\\033[1;32m\" color_end = u\"\\033[0;39m\" if level == \"bad\": color_start =",
"finish_output(self): BaseTextFormatter.finish_output(self) self.done() class TextListFormatter(BaseTextFormatter): \"\"\" Format multiple RED responses",
"\"<code>%s</code> isn't HTTP.\" % \\ self.red.res_error.get('detail', '')[:20]) else: raise AssertionError,",
"category) \\ for category in self.msg_categories]) def format_recommendation(self, red, category):",
"'Head Links'), ('script', 'Script Links'), ('frame', 'Frame Links'), ('iframe', 'IFrame",
"= [msg for msg in getattr(m.subrequest, \"messages\", []) if msg.level",
"= True def __init__(self, *args, **kw): BaseTextFormatter.__init__(self, *args, **kw) def",
"this software and associated documentation files (the \"Software\"), to deal",
"of the Software, and to permit persons to whom the",
"RED responses as a textual list. \"\"\" name = \"txt\"",
"@staticmethod def colorize(level, string): # info color_start = u\"\\033[0;32m\" color_end",
"template with RED's results.\" if self.red.res_complete: self.output(self.format_headers(self.red) + nl +",
"u\"\\033[1;31m\" color_end = u\"\\033[0;39m\" if level == \"warning\": color_start =",
"'Image Links'), ] error_template = \"Error: %s\\n\" def __init__(self, *args,",
"in the template with RED's results.\" if self.red.res_complete: self.output(self.format_headers(self.red) +",
"all copies or substantial portions of the Software. THE SOFTWARE",
"import nbhttp.error as nberr import redbot.speak as rs from redbot.formatter",
"class BaseTextFormatter(Formatter): \"\"\" Base class for text formatters.\"\"\" media_type =",
"**kw): BaseTextFormatter.__init__(self, *args, **kw) def finish_output(self): BaseTextFormatter.finish_output(self) self.done() class TextListFormatter(BaseTextFormatter):",
"if msg.level in [rs.l.BAD]] if smsgs: out.append(\"\") for sm in",
"BaseTextFormatter.finish_output(self) sep = \"=\" * 78 for hdr_tag, heading in",
"(the \"Software\"), to deal in the Software without restriction, including",
"merge, publish, distribute, sublicense, and/or sell copies of the Software,",
"nbhttp.error as nberr import redbot.speak as rs from redbot.formatter import",
"[] if [msg for msg in messages]: out.append(u\"* %s:\" %",
"class TextFormatter(BaseTextFormatter): \"\"\" Format a RED object as text. \"\"\"",
"self.red.res_error['desc'] == nberr.ERR_HTTP_VERSION['desc']: self.output(self.error_template % \"<code>%s</code> isn't HTTP.\" % \\",
"so, subject to the following conditions: The above copyright notice",
"PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR",
"Formatter.__init__(self, *args, **kw) def start_output(self): pass def feed(self, red, chunk):",
"charge, to any person obtaining a copy of this software",
"to do so, subject to the following conditions: The above",
"WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.",
"else: if self.red.res_error == None: pass elif self.red.res_error['desc'] == nberr.ERR_CONNECT['desc']:",
"level == \"bad\": color_start = u\"\\033[1;31m\" color_end = u\"\\033[0;39m\" if",
"Copyright (c) 2008-2010 <NAME> Permission is hereby granted, free of",
"following conditions: The above copyright notice and this permission notice",
"THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY",
"if self.red.res_error == None: pass elif self.red.res_error['desc'] == nberr.ERR_CONNECT['desc']: self.output(self.error_template",
"LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,",
"in the Software without restriction, including without limitation the rights",
"permission notice shall be included in all copies or substantial",
"in self.msg_categories]) def format_recommendation(self, red, category): messages = [msg for",
"getattr(m.subrequest, \"messages\", []) if msg.level in [rs.l.BAD]] if smsgs: out.append(\"\")",
"self.red.res_error.get('detail', '')[:20]) else: raise AssertionError, \"Unidentified incomplete response error.\" def",
"stderr with CLI? class BaseTextFormatter(Formatter): \"\"\" Base class for text",
"BaseTextFormatter.finish_output(self) self.done() class TextListFormatter(BaseTextFormatter): \"\"\" Format multiple RED responses as",
"droids = [d[0] for d in self.red.link_droids if d[1] ==",
"SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,",
"BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER",
"if [msg for msg in messages]: out.append(u\"* %s:\" % category)",
"format_headers(self, red): out = [u\"HTTP/%s %s %s\" % ( red.res_version,",
"sm in smsgs: out.append( u\" * %s\" % (self.colorize(sm.level, sm.summary[\"en\"]",
"a textual list. \"\"\" name = \"txt\" media_type = \"text/plain\"",
"\"Unidentified incomplete response error.\" def format_headers(self, red): out = [u\"HTTP/%s",
"for category in self.msg_categories]) def format_recommendation(self, red, category): messages =",
"[msg for msg in red.messages if msg.category == category] if",
"INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS",
"smsgs: out.append( u\" * %s\" % (self.colorize(sm.level, sm.summary[\"en\"] % sm.vars))",
"+ nl + nl) self.output(self.format_headers(droid) + nl + nl) self.output(self.format_recommendations(droid)",
"\"<NAME> <<EMAIL>>\" __copyright__ = \"\"\"\\ Copyright (c) 2008-2010 <NAME> Permission",
"HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,",
"m.vars)) ) smsgs = [msg for msg in getattr(m.subrequest, \"messages\",",
"string): # info color_start = u\"\\033[0;32m\" color_end = u\"\\033[0;39m\" if",
"red): return \"\".join([self.format_recommendation(red, category) \\ for category in self.msg_categories]) def",
"copyright notice and this permission notice shall be included in",
"= u\"\\033[1;33m\" color_end = u\"\\033[0;39m\" if level == \"uri\": color_start",
"% \"<code>%s</code> isn't HTTP.\" % \\ self.red.res_error.get('detail', '')[:20]) else: raise",
"out = [u\"HTTP/%s %s %s\" % ( red.res_version, red.res_status, red.res_phrase)]",
"#!/usr/bin/env python \"\"\" HAR Formatter for REDbot. \"\"\" __author__ =",
"rs.c.CONNECTION, rs.c.CONNEG, rs.c.CACHING, rs.c.VALIDATION, rs.c.RANGE ] link_order = [ ('link',",
"pass def finish_output(self): \"Fill in the template with RED's results.\"",
"OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. \"\"\"",
"% (self.colorize(sm.level, sm.summary[\"en\"] % sm.vars)) ) out.append(nl) out.append(nl) return nl.join(out)",
"self.red.link_droids if d[1] == hdr_tag] self.output(\"%s\\n%s (%d)\\n%s\\n\" % ( sep,",
"out.append(nl) out.append(nl) return nl.join(out) @staticmethod def colorize(level, string): # info",
"sep )) if droids: droids.sort(key=operator.attrgetter('uri')) for droid in droids: self.output(self.format_uri(droid)",
"and to permit persons to whom the Software is furnished",
"copies or substantial portions of the Software. THE SOFTWARE IS",
"+ color_end class TextFormatter(BaseTextFormatter): \"\"\" Format a RED object as",
"OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED",
"% \"Could not connect to the server (%s)\" % \\",
"in the template with RED's results.\" BaseTextFormatter.finish_output(self) sep = \"=\"",
"[msg for msg in messages]: out.append(u\"* %s:\" % category) for",
"def colorize(level, string): # info color_start = u\"\\033[0;32m\" color_end =",
"formatters.\"\"\" media_type = \"text/plain\" msg_categories = [ rs.c.GENERAL, rs.c.CONNECTION, rs.c.CONNEG,",
"IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,",
"SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY",
"nl + nl) self.output(self.format_headers(droid) + nl + nl) self.output(self.format_recommendations(droid) +",
"color_end = u\"\\033[0;39m\" if level == \"good\": color_start = u\"\\033[1;32m\"",
"for msg in messages]: out.append(u\"* %s:\" % category) for m",
"[rs.l.BAD]] if smsgs: out.append(\"\") for sm in smsgs: out.append( u\"",
"return \"\".join([self.format_recommendation(red, category) \\ for category in self.msg_categories]) def format_recommendation(self,",
"self.red.res_error.get('detail', \"unknown\")) elif self.red.res_error['desc'] == nberr.ERR_URL['desc']: self.output(self.error_template % self.red.res_error.get( 'detail',",
"for text formatters.\"\"\" media_type = \"text/plain\" msg_categories = [ rs.c.GENERAL,",
"object as text. \"\"\" name = \"txt\" media_type = \"text/plain\"",
"whom the Software is furnished to do so, subject to",
"<NAME> Permission is hereby granted, free of charge, to any",
"Base class for text formatters.\"\"\" media_type = \"text/plain\" msg_categories =",
"u\"\\033[1;33m\" color_end = u\"\\033[0;39m\" if level == \"uri\": color_start =",
"u\" * %s\" % (self.colorize(sm.level, sm.summary[\"en\"] % sm.vars)) ) out.append(nl)",
"True def __init__(self, *args, **kw): BaseTextFormatter.__init__(self, *args, **kw) def finish_output(self):",
"if d[1] == hdr_tag] self.output(\"%s\\n%s (%d)\\n%s\\n\" % ( sep, heading,",
"AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT",
"media_type = \"text/plain\" msg_categories = [ rs.c.GENERAL, rs.c.CONNECTION, rs.c.CONNEG, rs.c.CACHING,",
"in all copies or substantial portions of the Software. THE",
"obtaining a copy of this software and associated documentation files",
"u\"\\033[0;39m\" if level == \"bad\": color_start = u\"\\033[1;31m\" color_end =",
"heading in self.link_order: droids = [d[0] for d in self.red.link_droids",
"LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN",
") out.append(nl) out.append(nl) return nl.join(out) @staticmethod def colorize(level, string): #",
"of this software and associated documentation files (the \"Software\"), to",
"OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR",
"a copy of this software and associated documentation files (the",
"OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE",
"% sm.vars)) ) out.append(nl) out.append(nl) return nl.join(out) @staticmethod def colorize(level,",
"== \"good\": color_start = u\"\\033[1;32m\" color_end = u\"\\033[0;39m\" if level",
"as text. \"\"\" name = \"txt\" media_type = \"text/plain\" def",
"\"\"\" name = \"txt\" media_type = \"text/plain\" can_multiple = True",
"in self.link_order: droids = [d[0] for d in self.red.link_droids if",
"results.\" if self.red.res_complete: self.output(self.format_headers(self.red) + nl + nl) self.output(self.format_recommendations(self.red) +",
"sublicense, and/or sell copies of the Software, and to permit",
"finish_output(self): \"Fill in the template with RED's results.\" if self.red.res_complete:",
"\"warning\": color_start = u\"\\033[1;33m\" color_end = u\"\\033[0;39m\" if level ==",
"+ nl) self.output(self.format_recommendations(self.red) + nl) else: if self.red.res_error == None:",
"AssertionError, \"Unidentified incomplete response error.\" def format_headers(self, red): out =",
"LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR",
"in red.messages if msg.category == category] if not messages: return",
"u\"\\033[0;39m\" if level == \"good\": color_start = u\"\\033[1;32m\" color_end =",
"*args, **kw): Formatter.__init__(self, *args, **kw) def start_output(self): pass def feed(self,",
"def finish_output(self): \"Fill in the template with RED's results.\" BaseTextFormatter.finish_output(self)",
"'IFrame Links'), ('img', 'Image Links'), ] error_template = \"Error: %s\\n\"",
"%s\" % (self.colorize(sm.level, sm.summary[\"en\"] % sm.vars)) ) out.append(nl) out.append(nl) return",
"nberr import redbot.speak as rs from redbot.formatter import Formatter nl",
"color_start = u\"\\033[1;34m\" color_end = u\"\\033[0;39m\" return color_start + string",
"BaseTextFormatter.__init__(self, *args, **kw) def finish_output(self): \"Fill in the template with",
"u\"\\033[0;39m\" if level == \"uri\": color_start = u\"\\033[1;34m\" color_end =",
"OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN",
"= u\"\\033[1;31m\" color_end = u\"\\033[0;39m\" if level == \"warning\": color_start",
"% \\ self.red.res_error.get('detail', \"unknown\")) elif self.red.res_error['desc'] == nberr.ERR_URL['desc']: self.output(self.error_template %",
"+ string + color_end class TextFormatter(BaseTextFormatter): \"\"\" Format a RED",
"Format multiple RED responses as a textual list. \"\"\" name",
"IN THE SOFTWARE. \"\"\" import operator import nbhttp.error as nberr",
"* %s\" % (self.colorize(m.level, m.summary[\"en\"] % m.vars)) ) smsgs =",
"\"messages\", []) if msg.level in [rs.l.BAD]] if smsgs: out.append(\"\") for",
"OR OTHER DEALINGS IN THE SOFTWARE. \"\"\" import operator import",
"**kw): BaseTextFormatter.__init__(self, *args, **kw) def finish_output(self): \"Fill in the template",
"CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF",
"and status on stderr with CLI? class BaseTextFormatter(Formatter): \"\"\" Base",
"this permission notice shall be included in all copies or",
"the template with RED's results.\" BaseTextFormatter.finish_output(self) sep = \"=\" *",
"\\ self.red.res_error.get('detail', \"unknown\")) elif self.red.res_error['desc'] == nberr.ERR_URL['desc']: self.output(self.error_template % self.red.res_error.get(",
"CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN",
"**kw) def start_output(self): pass def feed(self, red, chunk): pass def",
"for m in messages: out.append( u\" * %s\" % (self.colorize(m.level,",
"def format_recommendation(self, red, category): messages = [msg for msg in",
"above copyright notice and this permission notice shall be included",
"A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE",
"h for h in red.res_hdrs]) def format_recommendations(self, red): return \"\".join([self.format_recommendation(red,",
"pass elif self.red.res_error['desc'] == nberr.ERR_CONNECT['desc']: self.output(self.error_template % \"Could not connect",
"USE OR OTHER DEALINGS IN THE SOFTWARE. \"\"\" import operator",
"= u\"\\033[0;39m\" if level == \"good\": color_start = u\"\\033[1;32m\" color_end",
"rs.c.RANGE ] link_order = [ ('link', 'Head Links'), ('script', 'Script",
"\"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,",
"def status(self, msg): pass def finish_output(self): \"Fill in the template",
"\\ for category in self.msg_categories]) def format_recommendation(self, red, category): messages",
"template with RED's results.\" BaseTextFormatter.finish_output(self) sep = \"=\" * 78",
"in messages: out.append( u\" * %s\" % (self.colorize(m.level, m.summary[\"en\"] %",
"[ rs.c.GENERAL, rs.c.CONNECTION, rs.c.CONNEG, rs.c.CACHING, rs.c.VALIDATION, rs.c.RANGE ] link_order =",
"IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING",
"KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE",
"is furnished to do so, subject to the following conditions:",
"REDbot. \"\"\" __author__ = \"<NAME> <<EMAIL>>\" __copyright__ = \"\"\"\\ Copyright",
"return color_start + string + color_end class TextFormatter(BaseTextFormatter): \"\"\" Format",
"( sep, heading, len(droids), sep )) if droids: droids.sort(key=operator.attrgetter('uri')) for",
"\"=\" * 78 for hdr_tag, heading in self.link_order: droids =",
"droids: self.output(self.format_uri(droid) + nl + nl) self.output(self.format_headers(droid) + nl +",
"to any person obtaining a copy of this software and",
"self.red.res_error['desc'] == nberr.ERR_READ_TIMEOUT['desc']: self.output(self.error_template % self.red.res_error['desc']) elif self.red.res_error['desc'] == nberr.ERR_HTTP_VERSION['desc']:",
"elif self.red.res_error['desc'] == nberr.ERR_CONNECT['desc']: self.output(self.error_template % \"Could not connect to",
"shall be included in all copies or substantial portions of",
"person obtaining a copy of this software and associated documentation",
"def __init__(self, *args, **kw): BaseTextFormatter.__init__(self, *args, **kw) def finish_output(self): \"Fill",
"def start_output(self): pass def feed(self, red, chunk): pass def status(self,",
"FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN",
"'detail', \"RED can't fetch that URL.\")) elif self.red.res_error['desc'] == nberr.ERR_READ_TIMEOUT['desc']:",
"sm.summary[\"en\"] % sm.vars)) ) out.append(nl) out.append(nl) return nl.join(out) @staticmethod def",
"as rs from redbot.formatter import Formatter nl = u\"\\n\" #",
"and this permission notice shall be included in all copies",
"%s\" % ( red.res_version, red.res_status, red.res_phrase)] return nl.join(out + [u\"%s:%s\"",
"TextListFormatter(BaseTextFormatter): \"\"\" Format multiple RED responses as a textual list.",
"hdr_tag] self.output(\"%s\\n%s (%d)\\n%s\\n\" % ( sep, heading, len(droids), sep ))",
"heading, len(droids), sep )) if droids: droids.sort(key=operator.attrgetter('uri')) for droid in",
"HTTP.\" % \\ self.red.res_error.get('detail', '')[:20]) else: raise AssertionError, \"Unidentified incomplete",
"rs.c.CACHING, rs.c.VALIDATION, rs.c.RANGE ] link_order = [ ('link', 'Head Links'),",
"red.res_phrase)] return nl.join(out + [u\"%s:%s\" % h for h in",
"Formatter nl = u\"\\n\" # TODO: errors and status on",
"for h in red.res_hdrs]) def format_recommendations(self, red): return \"\".join([self.format_recommendation(red, category)",
"OTHER DEALINGS IN THE SOFTWARE. \"\"\" import operator import nbhttp.error",
"for sm in smsgs: out.append( u\" * %s\" % (self.colorize(sm.level,",
"AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT",
"info color_start = u\"\\033[0;32m\" color_end = u\"\\033[0;39m\" if level ==",
"OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE",
"= \"text/plain\" def __init__(self, *args, **kw): BaseTextFormatter.__init__(self, *args, **kw) def",
"free of charge, to any person obtaining a copy of",
"status on stderr with CLI? class BaseTextFormatter(Formatter): \"\"\" Base class",
"IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE",
"\"\"\" __author__ = \"<NAME> <<EMAIL>>\" __copyright__ = \"\"\"\\ Copyright (c)",
"in red.res_hdrs]) def format_recommendations(self, red): return \"\".join([self.format_recommendation(red, category) \\ for",
"fetch that URL.\")) elif self.red.res_error['desc'] == nberr.ERR_READ_TIMEOUT['desc']: self.output(self.error_template % self.red.res_error['desc'])",
"that URL.\")) elif self.red.res_error['desc'] == nberr.ERR_READ_TIMEOUT['desc']: self.output(self.error_template % self.red.res_error['desc']) elif",
"\"\" out = [] if [msg for msg in messages]:",
"IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,",
"nl) else: if self.red.res_error == None: pass elif self.red.res_error['desc'] ==",
"OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT",
"the Software is furnished to do so, subject to the",
"Software, and to permit persons to whom the Software is",
"self.output(self.format_uri(droid) + nl + nl) self.output(self.format_headers(droid) + nl + nl)",
"= [ ('link', 'Head Links'), ('script', 'Script Links'), ('frame', 'Frame",
"SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.",
"sep = \"=\" * 78 for hdr_tag, heading in self.link_order:",
"chunk): pass def status(self, msg): pass def finish_output(self): \"Fill in",
"messages = [msg for msg in red.messages if msg.category ==",
"('script', 'Script Links'), ('frame', 'Frame Links'), ('iframe', 'IFrame Links'), ('img',",
"rights to use, copy, modify, merge, publish, distribute, sublicense, and/or",
"self.red.res_error['desc'] == nberr.ERR_CONNECT['desc']: self.output(self.error_template % \"Could not connect to the",
"operator import nbhttp.error as nberr import redbot.speak as rs from",
"__author__ = \"<NAME> <<EMAIL>>\" __copyright__ = \"\"\"\\ Copyright (c) 2008-2010",
"__init__(self, *args, **kw): Formatter.__init__(self, *args, **kw) def start_output(self): pass def",
"documentation files (the \"Software\"), to deal in the Software without",
"* 78 for hdr_tag, heading in self.link_order: droids = [d[0]",
"= [u\"HTTP/%s %s %s\" % ( red.res_version, red.res_status, red.res_phrase)] return",
"without restriction, including without limitation the rights to use, copy,",
"\"Could not connect to the server (%s)\" % \\ self.red.res_error.get('detail',",
"with RED's results.\" BaseTextFormatter.finish_output(self) sep = \"=\" * 78 for",
"level == \"warning\": color_start = u\"\\033[1;33m\" color_end = u\"\\033[0;39m\" if",
"TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION",
"\\ self.red.res_error.get('detail', '')[:20]) else: raise AssertionError, \"Unidentified incomplete response error.\"",
"a RED object as text. \"\"\" name = \"txt\" media_type",
"COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER",
"* %s\" % (self.colorize(sm.level, sm.summary[\"en\"] % sm.vars)) ) out.append(nl) out.append(nl)",
"results.\" BaseTextFormatter.finish_output(self) sep = \"=\" * 78 for hdr_tag, heading",
"nl = u\"\\n\" # TODO: errors and status on stderr",
"+ [u\"%s:%s\" % h for h in red.res_hdrs]) def format_recommendations(self,",
"category) for m in messages: out.append( u\" * %s\" %",
"RED object as text. \"\"\" name = \"txt\" media_type =",
"\"Fill in the template with RED's results.\" BaseTextFormatter.finish_output(self) sep =",
"\"txt\" media_type = \"text/plain\" can_multiple = True def __init__(self, *args,",
"\"\"\" HAR Formatter for REDbot. \"\"\" __author__ = \"<NAME> <<EMAIL>>\"",
"NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE",
"use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies",
"list. \"\"\" name = \"txt\" media_type = \"text/plain\" can_multiple =",
"OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR",
"= \"Error: %s\\n\" def __init__(self, *args, **kw): Formatter.__init__(self, *args, **kw)",
"the template with RED's results.\" if self.red.res_complete: self.output(self.format_headers(self.red) + nl",
"% self.red.res_error['desc']) elif self.red.res_error['desc'] == nberr.ERR_HTTP_VERSION['desc']: self.output(self.error_template % \"<code>%s</code> isn't",
"Links'), ] error_template = \"Error: %s\\n\" def __init__(self, *args, **kw):",
"color_start = u\"\\033[1;33m\" color_end = u\"\\033[0;39m\" if level == \"uri\":",
"== nberr.ERR_HTTP_VERSION['desc']: self.output(self.error_template % \"<code>%s</code> isn't HTTP.\" % \\ self.red.res_error.get('detail',",
"for msg in getattr(m.subrequest, \"messages\", []) if msg.level in [rs.l.BAD]]",
"granted, free of charge, to any person obtaining a copy",
"Formatter for REDbot. \"\"\" __author__ = \"<NAME> <<EMAIL>>\" __copyright__ =",
"+ nl) self.output(self.format_headers(droid) + nl + nl) self.output(self.format_recommendations(droid) + nl",
"**kw) def finish_output(self): BaseTextFormatter.finish_output(self) self.done() class TextListFormatter(BaseTextFormatter): \"\"\" Format multiple",
"+ nl + nl) self.output(self.format_recommendations(droid) + nl + nl) self.done()",
"= \"txt\" media_type = \"text/plain\" can_multiple = True def __init__(self,",
"%s:\" % category) for m in messages: out.append( u\" *",
"nl + nl) self.output(self.format_recommendations(droid) + nl + nl) self.done() def",
"self.link_order: droids = [d[0] for d in self.red.link_droids if d[1]",
"of charge, to any person obtaining a copy of this",
"PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS",
"out.append(nl) return nl.join(out) @staticmethod def colorize(level, string): # info color_start",
"Permission is hereby granted, free of charge, to any person",
"\"Error: %s\\n\" def __init__(self, *args, **kw): Formatter.__init__(self, *args, **kw) def",
"self.output(self.error_template % self.red.res_error.get( 'detail', \"RED can't fetch that URL.\")) elif",
"The above copyright notice and this permission notice shall be",
"red, category): messages = [msg for msg in red.messages if",
"\"\".join([self.format_recommendation(red, category) \\ for category in self.msg_categories]) def format_recommendation(self, red,",
"\"RED can't fetch that URL.\")) elif self.red.res_error['desc'] == nberr.ERR_READ_TIMEOUT['desc']: self.output(self.error_template",
"% (self.colorize(m.level, m.summary[\"en\"] % m.vars)) ) smsgs = [msg for",
"% h for h in red.res_hdrs]) def format_recommendations(self, red): return",
"<gh_stars>0 #!/usr/bin/env python \"\"\" HAR Formatter for REDbot. \"\"\" __author__",
"start_output(self): pass def feed(self, red, chunk): pass def status(self, msg):",
"= u\"\\033[0;39m\" if level == \"uri\": color_start = u\"\\033[1;34m\" color_end",
"= \"=\" * 78 for hdr_tag, heading in self.link_order: droids",
"associated documentation files (the \"Software\"), to deal in the Software",
"ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION",
"rs.c.VALIDATION, rs.c.RANGE ] link_order = [ ('link', 'Head Links'), ('script',",
"self.output(\"%s\\n%s (%d)\\n%s\\n\" % ( sep, heading, len(droids), sep )) if",
"AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES",
"pass def status(self, msg): pass def finish_output(self): \"Fill in the",
"= [d[0] for d in self.red.link_droids if d[1] == hdr_tag]",
"[d[0] for d in self.red.link_droids if d[1] == hdr_tag] self.output(\"%s\\n%s",
"= \"text/plain\" can_multiple = True def __init__(self, *args, **kw): BaseTextFormatter.__init__(self,",
"RED's results.\" if self.red.res_complete: self.output(self.format_headers(self.red) + nl + nl) self.output(self.format_recommendations(self.red)",
"WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING"
] |
[
"+ self._out_min # .......................................................................... def scale_value(self, value): ''' (out_max -",
"self._ioe.output(self._pin_red, r) self._ioe.output(self._pin_green, g) self._ioe.output(self._pin_blue, b) self._log.debug('value: {:<5.2f}; rgb: {},{},{}'.format(value,",
"----------------------------------- + out_min in_max - in_min where e.g.: a =",
"self._pot_enc_b = 3 self._pot_enc_c = 11 self._max_value = 3.3 #",
"0x0E for the potentiometer breakout # self._i2c_addr = 0x0E self._i2c_addr",
"potentiometer breakout # self._i2c_addr = 0x0E self._i2c_addr = _config.get('i2c_address') self._pin_red",
"green: {}; blue: {}\".format(self._pin_red, self._pin_green, self._pin_blue)) self._pot_enc_a = 12 self._pot_enc_b",
"All rights reserved. This file is part # of the",
"configure IO Expander self._ioe = io.IOE(i2c_addr=self._i2c_addr) self._ioe.set_mode(self._pot_enc_a, io.PIN_MODE_PP) self._ioe.set_mode(self._pot_enc_b, io.PIN_MODE_PP)",
"as float # # .......................................................................... # def x_get_scaled_value(self): # '''",
"self._in_max - self._in_min )) + self._out_min # return (( self._out_max",
"self._ioe = io.IOE(i2c_addr=self._i2c_addr) self._ioe.set_mode(self._pot_enc_a, io.PIN_MODE_PP) self._ioe.set_mode(self._pot_enc_b, io.PIN_MODE_PP) self._ioe.set_mode(self._pot_enc_c, io.ADC) self._ioe.output(self._pot_enc_a,",
"steps.\".format(int(self._period * self._brightness))) self._log.info(\"ready.\") # .......................................................................... def set_input_limits(self, in_min, in_max):",
"analog value from IO Expander _in_max = _config.get('in_max') # maximum",
"+ 'value: {:<5.2f}'.format(value)) return value # .......................................................................... def set_rgb(self, value):",
"0, max = 330. ''' return (( self._out_max - self._out_min",
"= out_min self._out_max = out_max self._log.info('output range:\\t{:>5.2f}-{:<5.2f}'.format(self._out_min, self._out_max)) # ..........................................................................",
"def x_get_scaled_value(self): # ''' # (out_max - out_min)(value - in_min)",
"''' return (( self._out_max - self._out_min ) * ( value",
"self._brightness) for c in colorsys.hsv_to_rgb(h, 1.0, 1.0)] self._ioe.output(self._pin_red, r) self._ioe.output(self._pin_green,",
"= _config.get('pin_red') self._pin_green = _config.get('pin_green') self._pin_blue = _config.get('pin_blue') self._log.info(\"pins: red:",
"in_min # where: a = 0.0, b = 1.0, min",
"value while also updating the RGB LED if the argument",
"1.0, min = 0, max = 330. ''' return ((",
"def set_output_limits(self, out_min, out_max): self._out_min = out_min self._out_max = out_max",
"12 self._pot_enc_b = 3 self._pot_enc_c = 11 self._max_value = 3.3",
"-*- coding: utf-8 -*- # # Copyright 2020-2021 by <NAME>.",
"3 self._pot_enc_c = 11 self._max_value = 3.3 # maximum voltage",
"to get 0-255 steps at the desired brightness _in_min =",
"Expander Potentiometer breakout, returning an analog value scaled to a",
"# 0x18 for IO Expander, 0x0E for the potentiometer breakout",
"_config.get('out_max') # maximum scaled output value self.set_output_limits(_out_min, _out_max) # now",
"io.PWM, invert=True) self._ioe.set_mode(self._pin_green, io.PWM, invert=True) self._ioe.set_mode(self._pin_blue, io.PWM, invert=True) self._log.info(\"running LED",
"rights reserved. This file is part # of the Robot",
"Expander, 0x0E for the potentiometer breakout # self._i2c_addr = 0x0E",
"configuration provided.') _config = config['ros'].get('ioe_potentiometer') # 0x18 for IO Expander,",
"- in_min) # f(x) = ----------------------------------- + out_min # in_max",
"g, b = [int(c * self._period * self._brightness) for c",
"self.scale_value(_value) # as float # # .......................................................................... # def x_get_scaled_value(self):",
"# maximum voltage (3.3v supply) self._brightness = _config.get('brightness') # effectively",
"in_min self._in_max = in_max self._log.info('input range:\\t{:>5.2f}-{:<5.2f}'.format(self._in_min, self._in_max)) # .......................................................................... def",
"supply) self._brightness = _config.get('brightness') # effectively max fraction of period",
"part # of the Robot Operating System project, released under",
"set_output_limits(self, out_min, out_max): self._out_min = out_min self._out_max = out_max self._log.info('output",
"level) if config is None: raise ValueError('no configuration provided.') _config",
"level): super().__init__() self._log = Logger('ioe', level) if config is None:",
"330. # ''' # return (( self._out_max - self._out_min )",
"(out_max - out_min)(value - in_min) f(x) = ----------------------------------- + out_min",
"= out_max self._log.info('output range:\\t{:>5.2f}-{:<5.2f}'.format(self._out_min, self._out_max)) # .......................................................................... def get_value(self): value",
"in_max self._log.info('input range:\\t{:>5.2f}-{:<5.2f}'.format(self._in_min, self._in_max)) # .......................................................................... def set_output_limits(self, out_min, out_max):",
"+ out_min # in_max - in_min # where: a =",
"/ ( self._in_max - self._in_min )) + self._out_min # ..........................................................................",
"self._pin_green = _config.get('pin_green') self._pin_blue = _config.get('pin_blue') self._log.info(\"pins: red: {}; green:",
"where: a = 0.0, b = 1.0, min = 0,",
"''' Configures an IO Expander Potentiometer breakout, returning an analog",
"self._out_min # .......................................................................... def scale_value(self, value): ''' (out_max - out_min)(value",
"of this package. # # author: <NAME> # created: 2020-09-19",
"ValueError('no configuration provided.') _config = config['ros'].get('ioe_potentiometer') # 0x18 for IO",
"part of this package. # # author: <NAME> # created:",
"in_min, in_max): self._in_min = in_min self._in_max = in_max self._log.info('input range:\\t{:>5.2f}-{:<5.2f}'.format(self._in_min,",
"max fraction of period LED will be on self._period =",
"large enough to get 0-255 steps at the desired brightness",
"python3 # -*- coding: utf-8 -*- # # Copyright 2020-2021",
"_config.get('in_max') # maximum analog value from IO Expander self.set_input_limits(_in_min, _in_max)",
"maximum voltage (3.3v supply) self._brightness = _config.get('brightness') # effectively max",
"get_value(self): value = self._max_value - self._ioe.input(self._pot_enc_c) self._log.debug(Fore.BLACK + 'value: {:<5.2f}'.format(value))",
"self._brightness))) self._log.info(\"ready.\") # .......................................................................... def set_input_limits(self, in_min, in_max): self._in_min =",
"# see the LICENSE file included as part of this",
".......................................................................... def set_rgb(self, value): h = value / self._max_value #",
"_in_min = _config.get('in_min') # minimum analog value from IO Expander",
"with {} brightness steps.\".format(int(self._period * self._brightness))) self._log.info(\"ready.\") # .......................................................................... def",
"period LED will be on self._period = int(255 / self._brightness)",
"= _config.get('brightness') # effectively max fraction of period LED will",
"= 3 self._pot_enc_c = 11 self._max_value = 3.3 # maximum",
"_out_min = _config.get('out_min') # minimum scaled output value _out_max =",
"an IO Expander Potentiometer breakout, returning an analog value scaled",
"self._log.debug('value: {:<5.2f}; rgb: {},{},{}'.format(value, r, g, b)) # .......................................................................... def",
"+ out_min in_max - in_min where e.g.: a = 0.0,",
"out_max): self._out_min = out_min self._out_max = out_max self._log.info('output range:\\t{:>5.2f}-{:<5.2f}'.format(self._out_min, self._out_max))",
"(out_max - out_min)(value - in_min) # f(x) = ----------------------------------- +",
"- out_min)(value - in_min) f(x) = ----------------------------------- + out_min in_max",
"{}; green: {}; blue: {}\".format(self._pin_red, self._pin_green, self._pin_blue)) self._pot_enc_a = 12",
"io.PIN_MODE_PP) self._ioe.set_mode(self._pot_enc_c, io.ADC) self._ioe.output(self._pot_enc_a, 1) self._ioe.output(self._pot_enc_b, 0) self._ioe.set_pwm_period(self._period) self._ioe.set_pwm_control(divider=2) #",
"value): ''' (out_max - out_min)(value - in_min) f(x) = -----------------------------------",
"invert=True) self._ioe.set_mode(self._pin_green, io.PWM, invert=True) self._ioe.set_mode(self._pin_blue, io.PWM, invert=True) self._log.info(\"running LED with",
"where e.g.: a = 0.0, b = 1.0, min =",
"2020-09-19 # import sys, colorsys import ioexpander as io from",
"import ioexpander as io from colorama import init, Fore, Style",
"- self._in_min )) + self._out_min # return (( self._out_max -",
"released under the MIT License. Please # see the LICENSE",
"self._ioe.set_mode(self._pot_enc_a, io.PIN_MODE_PP) self._ioe.set_mode(self._pot_enc_b, io.PIN_MODE_PP) self._ioe.set_mode(self._pot_enc_c, io.ADC) self._ioe.output(self._pot_enc_a, 1) self._ioe.output(self._pot_enc_b, 0)",
"# .......................................................................... def set_input_limits(self, in_min, in_max): self._in_min = in_min self._in_max",
"LED if the argument is True (the default). ''' _value",
"invert=True) self._ioe.set_mode(self._pin_blue, io.PWM, invert=True) self._log.info(\"running LED with {} brightness steps.\".format(int(self._period",
"_config.get('pin_red') self._pin_green = _config.get('pin_green') self._pin_blue = _config.get('pin_blue') self._log.info(\"pins: red: {};",
"# ''' # (out_max - out_min)(value - in_min) # f(x)",
"init, Fore, Style init() from lib.logger import Logger # ..............................................................................",
"minimum analog value from IO Expander _in_max = _config.get('in_max') #",
"0, max = 330. # ''' # return (( self._out_max",
"+ self._out_min # return (( self._out_max - self._out_min ) *",
"_out_max) # now configure IO Expander self._ioe = io.IOE(i2c_addr=self._i2c_addr) self._ioe.set_mode(self._pot_enc_a,",
"enough to get 0-255 steps at the desired brightness _in_min",
"the MIT License. Please # see the LICENSE file included",
"specified range. For a center-zero pot simply specify the minimum",
"LED with {} brightness steps.\".format(int(self._period * self._brightness))) self._log.info(\"ready.\") # ..........................................................................",
"a = 0.0, b = 1.0, min = 0, max",
"colorsys import ioexpander as io from colorama import init, Fore,",
"we can to avoid LED flicker self._ioe.set_mode(self._pin_red, io.PWM, invert=True) self._ioe.set_mode(self._pin_green,",
"= _config.get('in_min') # minimum analog value from IO Expander _in_max",
".......................................................................... def set_input_limits(self, in_min, in_max): self._in_min = in_min self._in_max =",
"self._i2c_addr = 0x0E self._i2c_addr = _config.get('i2c_address') self._pin_red = _config.get('pin_red') self._pin_green",
"e.g.: a = 0.0, b = 1.0, min = 0,",
"in_min where e.g.: a = 0.0, b = 1.0, min",
"self._ioe.set_pwm_control(divider=2) # PWM as fast as we can to avoid",
"scaled to a specified range. For a center-zero pot simply",
"return self.scale_value(_value) # as float # # .......................................................................... # def",
"- self._in_min )) + self._out_min # .......................................................................... def scale_value(self, value):",
"config['ros'].get('ioe_potentiometer') # 0x18 for IO Expander, 0x0E for the potentiometer",
"* self._brightness) for c in colorsys.hsv_to_rgb(h, 1.0, 1.0)] self._ioe.output(self._pin_red, r)",
"self._out_min # return (( self._out_max - self._out_min ) * (",
"from IO Expander _in_max = _config.get('in_max') # maximum analog value",
"rgb: {},{},{}'.format(value, r, g, b)) # .......................................................................... def get_scaled_value(self, update_led=True):",
"# .......................................................................... def scale_value(self, value): ''' (out_max - out_min)(value -",
") / ( self._in_max - self._in_min )) + self._out_min #EOF",
"b = 1.0, min = 0, max = 330. '''",
"self._brightness) # add a period large enough to get 0-255",
"self._out_min = out_min self._out_max = out_max self._log.info('output range:\\t{:>5.2f}-{:<5.2f}'.format(self._out_min, self._out_max)) #",
"max = 330. ''' return (( self._out_max - self._out_min )",
"0x18 for IO Expander, 0x0E for the potentiometer breakout #",
"return (( self._out_max - self._out_min ) * ( value -",
"colorama import init, Fore, Style init() from lib.logger import Logger",
"self._max_value - self._ioe.input(self._pot_enc_c) self._log.debug(Fore.BLACK + 'value: {:<5.2f}'.format(value)) return value #",
"package. # # author: <NAME> # created: 2020-09-19 # modified:",
"# time.time() / 10.0 r, g, b = [int(c *",
"if config is None: raise ValueError('no configuration provided.') _config =",
"int(255 / self._brightness) # add a period large enough to",
"= config['ros'].get('ioe_potentiometer') # 0x18 for IO Expander, 0x0E for the",
"self._ioe.output(self._pot_enc_a, 1) self._ioe.output(self._pot_enc_b, 0) self._ioe.set_pwm_period(self._period) self._ioe.set_pwm_control(divider=2) # PWM as fast",
"sys, colorsys import ioexpander as io from colorama import init,",
"value _out_max = _config.get('out_max') # maximum scaled output value self.set_output_limits(_out_min,",
"* self._brightness))) self._log.info(\"ready.\") # .......................................................................... def set_input_limits(self, in_min, in_max): self._in_min",
"IO Expander _in_max = _config.get('in_max') # maximum analog value from",
"value): h = value / self._max_value # time.time() / 10.0",
"_config.get('brightness') # effectively max fraction of period LED will be",
"self._pin_green, self._pin_blue)) self._pot_enc_a = 12 self._pot_enc_b = 3 self._pot_enc_c =",
"value from IO Expander _in_max = _config.get('in_max') # maximum analog",
"io.PIN_MODE_PP) self._ioe.set_mode(self._pot_enc_b, io.PIN_MODE_PP) self._ioe.set_mode(self._pot_enc_c, io.ADC) self._ioe.output(self._pot_enc_a, 1) self._ioe.output(self._pot_enc_b, 0) self._ioe.set_pwm_period(self._period)",
"_out_max = _config.get('out_max') # maximum scaled output value self.set_output_limits(_out_min, _out_max)",
"self._out_max)) # .......................................................................... def get_value(self): value = self._max_value - self._ioe.input(self._pot_enc_c)",
"value - self._in_min ) / ( self._in_max - self._in_min ))",
"# created: 2020-09-19 # modified: 2020-09-19 # import sys, colorsys",
"blue: {}\".format(self._pin_red, self._pin_green, self._pin_blue)) self._pot_enc_a = 12 self._pot_enc_b = 3",
"(( self._out_max - self._out_min ) * ( value - self._in_min",
"= 1.0, min = 0, max = 330. ''' return",
"= 12 self._pot_enc_b = 3 self._pot_enc_c = 11 self._max_value =",
"to a specified range. For a center-zero pot simply specify",
"True (the default). ''' _value = self.get_value() if update_led: self.set_rgb(_value)",
"/ 10.0 r, g, b = [int(c * self._period *",
"self._log.debug(Fore.BLACK + 'value: {:<5.2f}'.format(value)) return value # .......................................................................... def set_rgb(self,",
"returning an analog value scaled to a specified range. For",
"range:\\t{:>5.2f}-{:<5.2f}'.format(self._in_min, self._in_max)) # .......................................................................... def set_output_limits(self, out_min, out_max): self._out_min =",
"Please # see the LICENSE file included as part of",
"value / self._max_value # time.time() / 10.0 r, g, b",
"''' def __init__(self, config, level): super().__init__() self._log = Logger('ioe', level)",
"voltage (3.3v supply) self._brightness = _config.get('brightness') # effectively max fraction",
"IO Expander, 0x0E for the potentiometer breakout # self._i2c_addr =",
"{:<5.2f}'.format(value)) return value # .......................................................................... def set_rgb(self, value): h =",
"3.3 # maximum voltage (3.3v supply) self._brightness = _config.get('brightness') #",
"def get_scaled_value(self, update_led=True): ''' Return a scaled value while also",
"# # author: <NAME> # created: 2020-09-19 # modified: 2020-09-19",
"self._ioe.output(self._pin_blue, b) self._log.debug('value: {:<5.2f}; rgb: {},{},{}'.format(value, r, g, b)) #",
".......................................................................... def scale_value(self, value): ''' (out_max - out_min)(value - in_min)",
"= self.get_value() if update_led: self.set_rgb(_value) return self.scale_value(_value) # as float",
"= 0.0, b = 1.0, min = 0, max =",
"the potentiometer breakout # self._i2c_addr = 0x0E self._i2c_addr = _config.get('i2c_address')",
"output value self.set_output_limits(_out_min, _out_max) # now configure IO Expander self._ioe",
"Return a scaled value while also updating the RGB LED",
"= 0x0E self._i2c_addr = _config.get('i2c_address') self._pin_red = _config.get('pin_red') self._pin_green =",
"self._ioe.set_mode(self._pot_enc_c, io.ADC) self._ioe.output(self._pot_enc_a, 1) self._ioe.output(self._pot_enc_b, 0) self._ioe.set_pwm_period(self._period) self._ioe.set_pwm_control(divider=2) # PWM",
"if the argument is True (the default). ''' _value =",
"2020-2021 by <NAME>. All rights reserved. This file is part",
"in colorsys.hsv_to_rgb(h, 1.0, 1.0)] self._ioe.output(self._pin_red, r) self._ioe.output(self._pin_green, g) self._ioe.output(self._pin_blue, b)",
"= 0, max = 330. ''' return (( self._out_max -",
"Expander self.set_input_limits(_in_min, _in_max) _out_min = _config.get('out_min') # minimum scaled output",
"# of the Robot Operating System project, released under the",
"# maximum scaled output value self.set_output_limits(_out_min, _out_max) # now configure",
"# minimum analog value from IO Expander _in_max = _config.get('in_max')",
"License. Please # see the LICENSE file included as part",
"maximum analog value from IO Expander self.set_input_limits(_in_min, _in_max) _out_min =",
"# .............................................................................. class Potentiometer(object): ''' Configures an IO Expander Potentiometer",
"file included as part of this package. # # author:",
"self._ioe.set_mode(self._pin_blue, io.PWM, invert=True) self._log.info(\"running LED with {} brightness steps.\".format(int(self._period *",
"_value = self.get_value() if update_led: self.set_rgb(_value) return self.scale_value(_value) # as",
"float # # .......................................................................... # def x_get_scaled_value(self): # ''' #",
"= _config.get('i2c_address') self._pin_red = _config.get('pin_red') self._pin_green = _config.get('pin_green') self._pin_blue =",
"analog value scaled to a specified range. For a center-zero",
"the minimum value as (-1.0 * out_max). ''' def __init__(self,",
"self._period = int(255 / self._brightness) # add a period large",
"= _config.get('out_min') # minimum scaled output value _out_max = _config.get('out_max')",
"self._pin_red = _config.get('pin_red') self._pin_green = _config.get('pin_green') self._pin_blue = _config.get('pin_blue') self._log.info(\"pins:",
"self._out_max - self._out_min ) * ( value - self._in_min )",
"b = 1.0, min = 0, max = 330. #",
"config, level): super().__init__() self._log = Logger('ioe', level) if config is",
"Configures an IO Expander Potentiometer breakout, returning an analog value",
"self._log.info('input range:\\t{:>5.2f}-{:<5.2f}'.format(self._in_min, self._in_max)) # .......................................................................... def set_output_limits(self, out_min, out_max): self._out_min",
"* self._period * self._brightness) for c in colorsys.hsv_to_rgb(h, 1.0, 1.0)]",
"the LICENSE file included as part of this package. #",
"{},{},{}'.format(value, r, g, b)) # .......................................................................... def get_scaled_value(self, update_led=True): '''",
"from lib.logger import Logger # .............................................................................. class Potentiometer(object): ''' Configures",
"self.get_value() if update_led: self.set_rgb(_value) return self.scale_value(_value) # as float #",
"self.set_rgb(_value) return self.scale_value(_value) # as float # # .......................................................................... #",
"value self.set_output_limits(_out_min, _out_max) # now configure IO Expander self._ioe =",
"1.0)] self._ioe.output(self._pin_red, r) self._ioe.output(self._pin_green, g) self._ioe.output(self._pin_blue, b) self._log.debug('value: {:<5.2f}; rgb:",
"# -*- coding: utf-8 -*- # # Copyright 2020-2021 by",
"# return (( self._out_max - self._out_min ) * ( self.get_value()",
"included as part of this package. # # author: <NAME>",
"update_led: self.set_rgb(_value) return self.scale_value(_value) # as float # # ..........................................................................",
"fraction of period LED will be on self._period = int(255",
"self._in_min )) + self._out_min # .......................................................................... def scale_value(self, value): '''",
"self._ioe.output(self._pot_enc_b, 0) self._ioe.set_pwm_period(self._period) self._ioe.set_pwm_control(divider=2) # PWM as fast as we",
"default). ''' _value = self.get_value() if update_led: self.set_rgb(_value) return self.scale_value(_value)",
"Logger # .............................................................................. class Potentiometer(object): ''' Configures an IO Expander",
"value scaled to a specified range. For a center-zero pot",
"value as (-1.0 * out_max). ''' def __init__(self, config, level):",
"maximum scaled output value self.set_output_limits(_out_min, _out_max) # now configure IO",
"-*- # # Copyright 2020-2021 by <NAME>. All rights reserved.",
"for c in colorsys.hsv_to_rgb(h, 1.0, 1.0)] self._ioe.output(self._pin_red, r) self._ioe.output(self._pin_green, g)",
"''' # return (( self._out_max - self._out_min ) * (",
"io.IOE(i2c_addr=self._i2c_addr) self._ioe.set_mode(self._pot_enc_a, io.PIN_MODE_PP) self._ioe.set_mode(self._pot_enc_b, io.PIN_MODE_PP) self._ioe.set_mode(self._pot_enc_c, io.ADC) self._ioe.output(self._pot_enc_a, 1) self._ioe.output(self._pot_enc_b,",
"min = 0, max = 330. # ''' # return",
"- self._out_min ) * ( value - self._in_min ) /",
"scaled output value _out_max = _config.get('out_max') # maximum scaled output",
"= 330. ''' return (( self._out_max - self._out_min ) *",
"value # .......................................................................... def set_rgb(self, value): h = value /",
"1.0, min = 0, max = 330. # ''' #",
"_in_max = _config.get('in_max') # maximum analog value from IO Expander",
"= 3.3 # maximum voltage (3.3v supply) self._brightness = _config.get('brightness')",
"will be on self._period = int(255 / self._brightness) # add",
"- self._ioe.input(self._pot_enc_c) self._log.debug(Fore.BLACK + 'value: {:<5.2f}'.format(value)) return value # ..........................................................................",
"flicker self._ioe.set_mode(self._pin_red, io.PWM, invert=True) self._ioe.set_mode(self._pin_green, io.PWM, invert=True) self._ioe.set_mode(self._pin_blue, io.PWM, invert=True)",
"/ ( self._in_max - self._in_min )) + self._out_min # return",
"brightness _in_min = _config.get('in_min') # minimum analog value from IO",
"= ----------------------------------- + out_min in_max - in_min where e.g.: a",
"# .......................................................................... def get_value(self): value = self._max_value - self._ioe.input(self._pot_enc_c) self._log.debug(Fore.BLACK",
"= in_max self._log.info('input range:\\t{:>5.2f}-{:<5.2f}'.format(self._in_min, self._in_max)) # .......................................................................... def set_output_limits(self, out_min,",
"under the MIT License. Please # see the LICENSE file",
"pot simply specify the minimum value as (-1.0 * out_max).",
"raise ValueError('no configuration provided.') _config = config['ros'].get('ioe_potentiometer') # 0x18 for",
"effectively max fraction of period LED will be on self._period",
"self._out_min ) * ( self.get_value() - self._in_min ) / (",
"( self.get_value() - self._in_min ) / ( self._in_max - self._in_min",
"self.get_value() - self._in_min ) / ( self._in_max - self._in_min ))",
") / ( self._in_max - self._in_min )) + self._out_min #",
"= ----------------------------------- + out_min # in_max - in_min # where:",
"# f(x) = ----------------------------------- + out_min # in_max - in_min",
"- in_min) f(x) = ----------------------------------- + out_min in_max - in_min",
"MIT License. Please # see the LICENSE file included as",
"self._ioe.output(self._pin_green, g) self._ioe.output(self._pin_blue, b) self._log.debug('value: {:<5.2f}; rgb: {},{},{}'.format(value, r, g,",
"self._ioe.set_mode(self._pot_enc_b, io.PIN_MODE_PP) self._ioe.set_mode(self._pot_enc_c, io.ADC) self._ioe.output(self._pot_enc_a, 1) self._ioe.output(self._pot_enc_b, 0) self._ioe.set_pwm_period(self._period) self._ioe.set_pwm_control(divider=2)",
"return (( self._out_max - self._out_min ) * ( self.get_value() -",
"out_min self._out_max = out_max self._log.info('output range:\\t{:>5.2f}-{:<5.2f}'.format(self._out_min, self._out_max)) # .......................................................................... def",
"Robot Operating System project, released under the MIT License. Please",
"# minimum scaled output value _out_max = _config.get('out_max') # maximum",
"is None: raise ValueError('no configuration provided.') _config = config['ros'].get('ioe_potentiometer') #",
"range. For a center-zero pot simply specify the minimum value",
") * ( self.get_value() - self._in_min ) / ( self._in_max",
"in_min) f(x) = ----------------------------------- + out_min in_max - in_min where",
"_config.get('out_min') # minimum scaled output value _out_max = _config.get('out_max') #",
"= [int(c * self._period * self._brightness) for c in colorsys.hsv_to_rgb(h,",
"''' # (out_max - out_min)(value - in_min) # f(x) =",
"can to avoid LED flicker self._ioe.set_mode(self._pin_red, io.PWM, invert=True) self._ioe.set_mode(self._pin_green, io.PWM,",
"0-255 steps at the desired brightness _in_min = _config.get('in_min') #",
"fast as we can to avoid LED flicker self._ioe.set_mode(self._pin_red, io.PWM,",
"avoid LED flicker self._ioe.set_mode(self._pin_red, io.PWM, invert=True) self._ioe.set_mode(self._pin_green, io.PWM, invert=True) self._ioe.set_mode(self._pin_blue,",
"= in_min self._in_max = in_max self._log.info('input range:\\t{:>5.2f}-{:<5.2f}'.format(self._in_min, self._in_max)) # ..........................................................................",
"This file is part # of the Robot Operating System",
"= _config.get('pin_green') self._pin_blue = _config.get('pin_blue') self._log.info(\"pins: red: {}; green: {};",
"b)) # .......................................................................... def get_scaled_value(self, update_led=True): ''' Return a scaled",
"max = 330. # ''' # return (( self._out_max -",
"modified: 2020-09-19 # import sys, colorsys import ioexpander as io",
"1.0, 1.0)] self._ioe.output(self._pin_red, r) self._ioe.output(self._pin_green, g) self._ioe.output(self._pin_blue, b) self._log.debug('value: {:<5.2f};",
"r, g, b)) # .......................................................................... def get_scaled_value(self, update_led=True): ''' Return",
"self._in_min = in_min self._in_max = in_max self._log.info('input range:\\t{:>5.2f}-{:<5.2f}'.format(self._in_min, self._in_max)) #",
"x_get_scaled_value(self): # ''' # (out_max - out_min)(value - in_min) #",
"self._pot_enc_a = 12 self._pot_enc_b = 3 self._pot_enc_c = 11 self._max_value",
"''' Return a scaled value while also updating the RGB",
"''' (out_max - out_min)(value - in_min) f(x) = ----------------------------------- +",
"( value - self._in_min ) / ( self._in_max - self._in_min",
"/ self._brightness) # add a period large enough to get",
"output value _out_max = _config.get('out_max') # maximum scaled output value",
"out_min, out_max): self._out_min = out_min self._out_max = out_max self._log.info('output range:\\t{:>5.2f}-{:<5.2f}'.format(self._out_min,",
"__init__(self, config, level): super().__init__() self._log = Logger('ioe', level) if config",
"out_max self._log.info('output range:\\t{:>5.2f}-{:<5.2f}'.format(self._out_min, self._out_max)) # .......................................................................... def get_value(self): value =",
"= io.IOE(i2c_addr=self._i2c_addr) self._ioe.set_mode(self._pot_enc_a, io.PIN_MODE_PP) self._ioe.set_mode(self._pot_enc_b, io.PIN_MODE_PP) self._ioe.set_mode(self._pot_enc_c, io.ADC) self._ioe.output(self._pot_enc_a, 1)",
"super().__init__() self._log = Logger('ioe', level) if config is None: raise",
".......................................................................... def get_scaled_value(self, update_led=True): ''' Return a scaled value while",
"- in_min where e.g.: a = 0.0, b = 1.0,",
"utf-8 -*- # # Copyright 2020-2021 by <NAME>. All rights",
"# .......................................................................... def set_output_limits(self, out_min, out_max): self._out_min = out_min self._out_max",
"r) self._ioe.output(self._pin_green, g) self._ioe.output(self._pin_blue, b) self._log.debug('value: {:<5.2f}; rgb: {},{},{}'.format(value, r,",
"For a center-zero pot simply specify the minimum value as",
"* out_max). ''' def __init__(self, config, level): super().__init__() self._log =",
"# (out_max - out_min)(value - in_min) # f(x) = -----------------------------------",
"# # .......................................................................... # def x_get_scaled_value(self): # ''' # (out_max",
"{}; blue: {}\".format(self._pin_red, self._pin_green, self._pin_blue)) self._pot_enc_a = 12 self._pot_enc_b =",
"if update_led: self.set_rgb(_value) return self.scale_value(_value) # as float # #",
"analog value from IO Expander self.set_input_limits(_in_min, _in_max) _out_min = _config.get('out_min')",
"self._log.info(\"pins: red: {}; green: {}; blue: {}\".format(self._pin_red, self._pin_green, self._pin_blue)) self._pot_enc_a",
"author: <NAME> # created: 2020-09-19 # modified: 2020-09-19 # import",
"_in_max) _out_min = _config.get('out_min') # minimum scaled output value _out_max",
"'value: {:<5.2f}'.format(value)) return value # .......................................................................... def set_rgb(self, value): h",
"Copyright 2020-2021 by <NAME>. All rights reserved. This file is",
"c in colorsys.hsv_to_rgb(h, 1.0, 1.0)] self._ioe.output(self._pin_red, r) self._ioe.output(self._pin_green, g) self._ioe.output(self._pin_blue,",
"see the LICENSE file included as part of this package.",
"import Logger # .............................................................................. class Potentiometer(object): ''' Configures an IO",
"<NAME> # created: 2020-09-19 # modified: 2020-09-19 # import sys,",
"is part # of the Robot Operating System project, released",
"# maximum analog value from IO Expander self.set_input_limits(_in_min, _in_max) _out_min",
"the argument is True (the default). ''' _value = self.get_value()",
"_config.get('pin_green') self._pin_blue = _config.get('pin_blue') self._log.info(\"pins: red: {}; green: {}; blue:",
"self._ioe.input(self._pot_enc_c) self._log.debug(Fore.BLACK + 'value: {:<5.2f}'.format(value)) return value # .......................................................................... def",
"def __init__(self, config, level): super().__init__() self._log = Logger('ioe', level) if",
"self._log = Logger('ioe', level) if config is None: raise ValueError('no",
"updating the RGB LED if the argument is True (the",
"= _config.get('pin_blue') self._log.info(\"pins: red: {}; green: {}; blue: {}\".format(self._pin_red, self._pin_green,",
"# .......................................................................... def get_scaled_value(self, update_led=True): ''' Return a scaled value",
"in_max): self._in_min = in_min self._in_max = in_max self._log.info('input range:\\t{:>5.2f}-{:<5.2f}'.format(self._in_min, self._in_max))",
")) + self._out_min # return (( self._out_max - self._out_min )",
"self._max_value # time.time() / 10.0 r, g, b = [int(c",
"minimum value as (-1.0 * out_max). ''' def __init__(self, config,",
"= self._max_value - self._ioe.input(self._pot_enc_c) self._log.debug(Fore.BLACK + 'value: {:<5.2f}'.format(value)) return value",
"# .......................................................................... # def x_get_scaled_value(self): # ''' # (out_max -",
"as we can to avoid LED flicker self._ioe.set_mode(self._pin_red, io.PWM, invert=True)",
"IO Expander self._ioe = io.IOE(i2c_addr=self._i2c_addr) self._ioe.set_mode(self._pot_enc_a, io.PIN_MODE_PP) self._ioe.set_mode(self._pot_enc_b, io.PIN_MODE_PP) self._ioe.set_mode(self._pot_enc_c,",
"System project, released under the MIT License. Please # see",
"out_min)(value - in_min) f(x) = ----------------------------------- + out_min in_max -",
") * ( value - self._in_min ) / ( self._in_max",
"Fore, Style init() from lib.logger import Logger # .............................................................................. class",
"----------------------------------- + out_min # in_max - in_min # where: a",
"(3.3v supply) self._brightness = _config.get('brightness') # effectively max fraction of",
"an analog value scaled to a specified range. For a",
"self._in_min ) / ( self._in_max - self._in_min )) + self._out_min",
"colorsys.hsv_to_rgb(h, 1.0, 1.0)] self._ioe.output(self._pin_red, r) self._ioe.output(self._pin_green, g) self._ioe.output(self._pin_blue, b) self._log.debug('value:",
"to avoid LED flicker self._ioe.set_mode(self._pin_red, io.PWM, invert=True) self._ioe.set_mode(self._pin_green, io.PWM, invert=True)",
"self._period * self._brightness) for c in colorsys.hsv_to_rgb(h, 1.0, 1.0)] self._ioe.output(self._pin_red,",
"0.0, b = 1.0, min = 0, max = 330.",
"self._ioe.set_mode(self._pin_green, io.PWM, invert=True) self._ioe.set_mode(self._pin_blue, io.PWM, invert=True) self._log.info(\"running LED with {}",
"Logger('ioe', level) if config is None: raise ValueError('no configuration provided.')",
"in_max - in_min # where: a = 0.0, b =",
"# self._i2c_addr = 0x0E self._i2c_addr = _config.get('i2c_address') self._pin_red = _config.get('pin_red')",
"self._out_max - self._out_min ) * ( self.get_value() - self._in_min )",
".......................................................................... def set_output_limits(self, out_min, out_max): self._out_min = out_min self._out_max =",
"steps at the desired brightness _in_min = _config.get('in_min') # minimum",
"the RGB LED if the argument is True (the default).",
"RGB LED if the argument is True (the default). '''",
"self._i2c_addr = _config.get('i2c_address') self._pin_red = _config.get('pin_red') self._pin_green = _config.get('pin_green') self._pin_blue",
"b = [int(c * self._period * self._brightness) for c in",
"in_min) # f(x) = ----------------------------------- + out_min # in_max -",
"# import sys, colorsys import ioexpander as io from colorama",
"of period LED will be on self._period = int(255 /",
"PWM as fast as we can to avoid LED flicker",
"io.ADC) self._ioe.output(self._pot_enc_a, 1) self._ioe.output(self._pot_enc_b, 0) self._ioe.set_pwm_period(self._period) self._ioe.set_pwm_control(divider=2) # PWM as",
"add a period large enough to get 0-255 steps at",
"- self._out_min ) * ( self.get_value() - self._in_min ) /",
"desired brightness _in_min = _config.get('in_min') # minimum analog value from",
"get_scaled_value(self, update_led=True): ''' Return a scaled value while also updating",
"- self._in_min ) / ( self._in_max - self._in_min )) +",
"scaled output value self.set_output_limits(_out_min, _out_max) # now configure IO Expander",
"a center-zero pot simply specify the minimum value as (-1.0",
"out_max). ''' def __init__(self, config, level): super().__init__() self._log = Logger('ioe',",
"self._max_value = 3.3 # maximum voltage (3.3v supply) self._brightness =",
"range:\\t{:>5.2f}-{:<5.2f}'.format(self._out_min, self._out_max)) # .......................................................................... def get_value(self): value = self._max_value -",
"self._out_max = out_max self._log.info('output range:\\t{:>5.2f}-{:<5.2f}'.format(self._out_min, self._out_max)) # .......................................................................... def get_value(self):",
"coding: utf-8 -*- # # Copyright 2020-2021 by <NAME>. All",
"{:<5.2f}; rgb: {},{},{}'.format(value, r, g, b)) # .......................................................................... def get_scaled_value(self,",
"self._pin_blue)) self._pot_enc_a = 12 self._pot_enc_b = 3 self._pot_enc_c = 11",
"init() from lib.logger import Logger # .............................................................................. class Potentiometer(object): '''",
"created: 2020-09-19 # modified: 2020-09-19 # import sys, colorsys import",
"value from IO Expander self.set_input_limits(_in_min, _in_max) _out_min = _config.get('out_min') #",
"def set_rgb(self, value): h = value / self._max_value # time.time()",
"# Copyright 2020-2021 by <NAME>. All rights reserved. This file",
"# author: <NAME> # created: 2020-09-19 # modified: 2020-09-19 #",
"self._in_max = in_max self._log.info('input range:\\t{:>5.2f}-{:<5.2f}'.format(self._in_min, self._in_max)) # .......................................................................... def set_output_limits(self,",
"# def x_get_scaled_value(self): # ''' # (out_max - out_min)(value -",
"g) self._ioe.output(self._pin_blue, b) self._log.debug('value: {:<5.2f}; rgb: {},{},{}'.format(value, r, g, b))",
"file is part # of the Robot Operating System project,",
"LED flicker self._ioe.set_mode(self._pin_red, io.PWM, invert=True) self._ioe.set_mode(self._pin_green, io.PWM, invert=True) self._ioe.set_mode(self._pin_blue, io.PWM,",
"# ''' # return (( self._out_max - self._out_min ) *",
"return value # .......................................................................... def set_rgb(self, value): h = value",
"#!/usr/bin/env python3 # -*- coding: utf-8 -*- # # Copyright",
"breakout, returning an analog value scaled to a specified range.",
"_config.get('in_min') # minimum analog value from IO Expander _in_max =",
"breakout # self._i2c_addr = 0x0E self._i2c_addr = _config.get('i2c_address') self._pin_red =",
"2020-09-19 # modified: 2020-09-19 # import sys, colorsys import ioexpander",
"{}\".format(self._pin_red, self._pin_green, self._pin_blue)) self._pot_enc_a = 12 self._pot_enc_b = 3 self._pot_enc_c",
"# effectively max fraction of period LED will be on",
"{} brightness steps.\".format(int(self._period * self._brightness))) self._log.info(\"ready.\") # .......................................................................... def set_input_limits(self,",
"= value / self._max_value # time.time() / 10.0 r, g,",
"0x0E self._i2c_addr = _config.get('i2c_address') self._pin_red = _config.get('pin_red') self._pin_green = _config.get('pin_green')",
"set_input_limits(self, in_min, in_max): self._in_min = in_min self._in_max = in_max self._log.info('input",
"by <NAME>. All rights reserved. This file is part #",
"io.PWM, invert=True) self._log.info(\"running LED with {} brightness steps.\".format(int(self._period * self._brightness)))",
"# as float # # .......................................................................... # def x_get_scaled_value(self): #",
"a scaled value while also updating the RGB LED if",
"Potentiometer breakout, returning an analog value scaled to a specified",
"io from colorama import init, Fore, Style init() from lib.logger",
"* ( value - self._in_min ) / ( self._in_max -",
"period large enough to get 0-255 steps at the desired",
"1) self._ioe.output(self._pot_enc_b, 0) self._ioe.set_pwm_period(self._period) self._ioe.set_pwm_control(divider=2) # PWM as fast as",
"[int(c * self._period * self._brightness) for c in colorsys.hsv_to_rgb(h, 1.0,",
"is True (the default). ''' _value = self.get_value() if update_led:",
"update_led=True): ''' Return a scaled value while also updating the",
"(the default). ''' _value = self.get_value() if update_led: self.set_rgb(_value) return",
"( self._in_max - self._in_min )) + self._out_min # return ((",
"_config = config['ros'].get('ioe_potentiometer') # 0x18 for IO Expander, 0x0E for",
"# where: a = 0.0, b = 1.0, min =",
"self.set_output_limits(_out_min, _out_max) # now configure IO Expander self._ioe = io.IOE(i2c_addr=self._i2c_addr)",
"# add a period large enough to get 0-255 steps",
"LICENSE file included as part of this package. # #",
"Expander _in_max = _config.get('in_max') # maximum analog value from IO",
"of the Robot Operating System project, released under the MIT",
"h = value / self._max_value # time.time() / 10.0 r,",
"scaled value while also updating the RGB LED if the",
"Style init() from lib.logger import Logger # .............................................................................. class Potentiometer(object):",
"the desired brightness _in_min = _config.get('in_min') # minimum analog value",
"= int(255 / self._brightness) # add a period large enough",
".............................................................................. class Potentiometer(object): ''' Configures an IO Expander Potentiometer breakout,",
"from IO Expander self.set_input_limits(_in_min, _in_max) _out_min = _config.get('out_min') # minimum",
"this package. # # author: <NAME> # created: 2020-09-19 #",
"argument is True (the default). ''' _value = self.get_value() if",
"config is None: raise ValueError('no configuration provided.') _config = config['ros'].get('ioe_potentiometer')",
"be on self._period = int(255 / self._brightness) # add a",
"IO Expander Potentiometer breakout, returning an analog value scaled to",
"min = 0, max = 330. ''' return (( self._out_max",
"Expander self._ioe = io.IOE(i2c_addr=self._i2c_addr) self._ioe.set_mode(self._pot_enc_a, io.PIN_MODE_PP) self._ioe.set_mode(self._pot_enc_b, io.PIN_MODE_PP) self._ioe.set_mode(self._pot_enc_c, io.ADC)",
"now configure IO Expander self._ioe = io.IOE(i2c_addr=self._i2c_addr) self._ioe.set_mode(self._pot_enc_a, io.PIN_MODE_PP) self._ioe.set_mode(self._pot_enc_b,",
"( self._in_max - self._in_min )) + self._out_min # .......................................................................... def",
"330. ''' return (( self._out_max - self._out_min ) * (",
"g, b)) # .......................................................................... def get_scaled_value(self, update_led=True): ''' Return a",
"= _config.get('in_max') # maximum analog value from IO Expander self.set_input_limits(_in_min,",
"self._ioe.set_mode(self._pin_red, io.PWM, invert=True) self._ioe.set_mode(self._pin_green, io.PWM, invert=True) self._ioe.set_mode(self._pin_blue, io.PWM, invert=True) self._log.info(\"running",
"while also updating the RGB LED if the argument is",
"specify the minimum value as (-1.0 * out_max). ''' def",
"IO Expander self.set_input_limits(_in_min, _in_max) _out_min = _config.get('out_min') # minimum scaled",
"10.0 r, g, b = [int(c * self._period * self._brightness)",
"self._in_max - self._in_min )) + self._out_min # .......................................................................... def scale_value(self,",
"None: raise ValueError('no configuration provided.') _config = config['ros'].get('ioe_potentiometer') # 0x18",
"from colorama import init, Fore, Style init() from lib.logger import",
"for the potentiometer breakout # self._i2c_addr = 0x0E self._i2c_addr =",
"* ( self.get_value() - self._in_min ) / ( self._in_max -",
"as part of this package. # # author: <NAME> #",
"Operating System project, released under the MIT License. Please #",
"also updating the RGB LED if the argument is True",
"# modified: 2020-09-19 # import sys, colorsys import ioexpander as",
"invert=True) self._log.info(\"running LED with {} brightness steps.\".format(int(self._period * self._brightness))) self._log.info(\"ready.\")",
"import sys, colorsys import ioexpander as io from colorama import",
"center-zero pot simply specify the minimum value as (-1.0 *",
"time.time() / 10.0 r, g, b = [int(c * self._period",
"self._out_min ) * ( value - self._in_min ) / (",
"self._log.info(\"ready.\") # .......................................................................... def set_input_limits(self, in_min, in_max): self._in_min = in_min",
"as (-1.0 * out_max). ''' def __init__(self, config, level): super().__init__()",
"class Potentiometer(object): ''' Configures an IO Expander Potentiometer breakout, returning",
"scale_value(self, value): ''' (out_max - out_min)(value - in_min) f(x) =",
"# PWM as fast as we can to avoid LED",
"def get_value(self): value = self._max_value - self._ioe.input(self._pot_enc_c) self._log.debug(Fore.BLACK + 'value:",
"provided.') _config = config['ros'].get('ioe_potentiometer') # 0x18 for IO Expander, 0x0E",
"b) self._log.debug('value: {:<5.2f}; rgb: {},{},{}'.format(value, r, g, b)) # ..........................................................................",
"project, released under the MIT License. Please # see the",
"f(x) = ----------------------------------- + out_min in_max - in_min where e.g.:",
"out_min)(value - in_min) # f(x) = ----------------------------------- + out_min #",
"= _config.get('out_max') # maximum scaled output value self.set_output_limits(_out_min, _out_max) #",
"# # Copyright 2020-2021 by <NAME>. All rights reserved. This",
"self._in_min )) + self._out_min # return (( self._out_max - self._out_min",
"get 0-255 steps at the desired brightness _in_min = _config.get('in_min')",
".......................................................................... # def x_get_scaled_value(self): # ''' # (out_max - out_min)(value",
"ioexpander as io from colorama import init, Fore, Style init()",
"self._ioe.set_pwm_period(self._period) self._ioe.set_pwm_control(divider=2) # PWM as fast as we can to",
"= 0, max = 330. # ''' # return ((",
"set_rgb(self, value): h = value / self._max_value # time.time() /",
"''' _value = self.get_value() if update_led: self.set_rgb(_value) return self.scale_value(_value) #",
"in_max - in_min where e.g.: a = 0.0, b =",
"(( self._out_max - self._out_min ) * ( self.get_value() - self._in_min",
"_config.get('i2c_address') self._pin_red = _config.get('pin_red') self._pin_green = _config.get('pin_green') self._pin_blue = _config.get('pin_blue')",
"out_min in_max - in_min where e.g.: a = 0.0, b",
"<NAME>. All rights reserved. This file is part # of",
"LED will be on self._period = int(255 / self._brightness) #",
"= Logger('ioe', level) if config is None: raise ValueError('no configuration",
"brightness steps.\".format(int(self._period * self._brightness))) self._log.info(\"ready.\") # .......................................................................... def set_input_limits(self, in_min,",
"11 self._max_value = 3.3 # maximum voltage (3.3v supply) self._brightness",
"self._brightness = _config.get('brightness') # effectively max fraction of period LED",
"self._in_max)) # .......................................................................... def set_output_limits(self, out_min, out_max): self._out_min = out_min",
"for IO Expander, 0x0E for the potentiometer breakout # self._i2c_addr",
"as io from colorama import init, Fore, Style init() from",
"a period large enough to get 0-255 steps at the",
"on self._period = int(255 / self._brightness) # add a period",
"/ self._max_value # time.time() / 10.0 r, g, b =",
"r, g, b = [int(c * self._period * self._brightness) for",
"value = self._max_value - self._ioe.input(self._pot_enc_c) self._log.debug(Fore.BLACK + 'value: {:<5.2f}'.format(value)) return",
"(-1.0 * out_max). ''' def __init__(self, config, level): super().__init__() self._log",
"minimum scaled output value _out_max = _config.get('out_max') # maximum scaled",
"reserved. This file is part # of the Robot Operating",
"- in_min # where: a = 0.0, b = 1.0,",
"the Robot Operating System project, released under the MIT License.",
"self._pot_enc_c = 11 self._max_value = 3.3 # maximum voltage (3.3v",
"= 11 self._max_value = 3.3 # maximum voltage (3.3v supply)",
"out_min # in_max - in_min # where: a = 0.0,",
"self.set_input_limits(_in_min, _in_max) _out_min = _config.get('out_min') # minimum scaled output value",
"as fast as we can to avoid LED flicker self._ioe.set_mode(self._pin_red,",
"# .......................................................................... def set_rgb(self, value): h = value / self._max_value",
"self._log.info('output range:\\t{:>5.2f}-{:<5.2f}'.format(self._out_min, self._out_max)) # .......................................................................... def get_value(self): value = self._max_value",
"# in_max - in_min # where: a = 0.0, b",
"lib.logger import Logger # .............................................................................. class Potentiometer(object): ''' Configures an",
"- out_min)(value - in_min) # f(x) = ----------------------------------- + out_min",
"import init, Fore, Style init() from lib.logger import Logger #",
"at the desired brightness _in_min = _config.get('in_min') # minimum analog",
".......................................................................... def get_value(self): value = self._max_value - self._ioe.input(self._pot_enc_c) self._log.debug(Fore.BLACK +",
")) + self._out_min # .......................................................................... def scale_value(self, value): ''' (out_max",
"0) self._ioe.set_pwm_period(self._period) self._ioe.set_pwm_control(divider=2) # PWM as fast as we can",
"Potentiometer(object): ''' Configures an IO Expander Potentiometer breakout, returning an",
"# now configure IO Expander self._ioe = io.IOE(i2c_addr=self._i2c_addr) self._ioe.set_mode(self._pot_enc_a, io.PIN_MODE_PP)",
"a specified range. For a center-zero pot simply specify the",
"_config.get('pin_blue') self._log.info(\"pins: red: {}; green: {}; blue: {}\".format(self._pin_red, self._pin_green, self._pin_blue))",
"f(x) = ----------------------------------- + out_min # in_max - in_min #",
"simply specify the minimum value as (-1.0 * out_max). '''",
"= 1.0, min = 0, max = 330. # '''",
"io.PWM, invert=True) self._ioe.set_mode(self._pin_blue, io.PWM, invert=True) self._log.info(\"running LED with {} brightness",
"def set_input_limits(self, in_min, in_max): self._in_min = in_min self._in_max = in_max",
"red: {}; green: {}; blue: {}\".format(self._pin_red, self._pin_green, self._pin_blue)) self._pot_enc_a =",
"= 330. # ''' # return (( self._out_max - self._out_min",
"self._log.info(\"running LED with {} brightness steps.\".format(int(self._period * self._brightness))) self._log.info(\"ready.\") #",
"self._pin_blue = _config.get('pin_blue') self._log.info(\"pins: red: {}; green: {}; blue: {}\".format(self._pin_red,",
"def scale_value(self, value): ''' (out_max - out_min)(value - in_min) f(x)"
] |
[
"pass content = None def json(): pass text = None",
"ESP32') # Stubber: 1.3.2 class Response: '' def close(): pass",
"def patch(): pass def post(): pass def put(): pass def",
"patch(): pass def post(): pass def put(): pass def request():",
"def post(): pass def put(): pass def request(): pass usocket",
"def head(): pass def patch(): pass def post(): pass def",
"get(): pass def head(): pass def patch(): pass def post():",
"Module: 'urequests' on esp32 1.12.0 \"\"\" # MCU: (sysname='esp32', nodename='esp32',",
"def close(): pass content = None def json(): pass text",
"on esp32 1.12.0 \"\"\" # MCU: (sysname='esp32', nodename='esp32', release='1.12.0', version='v1.12",
"on 2019-12-20', machine='ESP32 module (spiram) with ESP32') # Stubber: 1.3.2",
"= None def json(): pass text = None def delete():",
"= None def delete(): pass def get(): pass def head():",
"'' def close(): pass content = None def json(): pass",
"\"\"\" # MCU: (sysname='esp32', nodename='esp32', release='1.12.0', version='v1.12 on 2019-12-20', machine='ESP32",
"None def json(): pass text = None def delete(): pass",
"pass def post(): pass def put(): pass def request(): pass",
"pass def head(): pass def patch(): pass def post(): pass",
"class Response: '' def close(): pass content = None def",
"MCU: (sysname='esp32', nodename='esp32', release='1.12.0', version='v1.12 on 2019-12-20', machine='ESP32 module (spiram)",
"post(): pass def put(): pass def request(): pass usocket =",
"Response: '' def close(): pass content = None def json():",
"Stubber: 1.3.2 class Response: '' def close(): pass content =",
"def delete(): pass def get(): pass def head(): pass def",
"content = None def json(): pass text = None def",
"pass def patch(): pass def post(): pass def put(): pass",
"None def delete(): pass def get(): pass def head(): pass",
"'urequests' on esp32 1.12.0 \"\"\" # MCU: (sysname='esp32', nodename='esp32', release='1.12.0',",
"nodename='esp32', release='1.12.0', version='v1.12 on 2019-12-20', machine='ESP32 module (spiram) with ESP32')",
"# Stubber: 1.3.2 class Response: '' def close(): pass content",
"esp32 1.12.0 \"\"\" # MCU: (sysname='esp32', nodename='esp32', release='1.12.0', version='v1.12 on",
"module (spiram) with ESP32') # Stubber: 1.3.2 class Response: ''",
"with ESP32') # Stubber: 1.3.2 class Response: '' def close():",
"2019-12-20', machine='ESP32 module (spiram) with ESP32') # Stubber: 1.3.2 class",
"close(): pass content = None def json(): pass text =",
"def json(): pass text = None def delete(): pass def",
"1.12.0 \"\"\" # MCU: (sysname='esp32', nodename='esp32', release='1.12.0', version='v1.12 on 2019-12-20',",
"pass text = None def delete(): pass def get(): pass",
"json(): pass text = None def delete(): pass def get():",
"pass def get(): pass def head(): pass def patch(): pass",
"\"\"\" Module: 'urequests' on esp32 1.12.0 \"\"\" # MCU: (sysname='esp32',",
"# MCU: (sysname='esp32', nodename='esp32', release='1.12.0', version='v1.12 on 2019-12-20', machine='ESP32 module",
"release='1.12.0', version='v1.12 on 2019-12-20', machine='ESP32 module (spiram) with ESP32') #",
"version='v1.12 on 2019-12-20', machine='ESP32 module (spiram) with ESP32') # Stubber:",
"def get(): pass def head(): pass def patch(): pass def",
"text = None def delete(): pass def get(): pass def",
"(sysname='esp32', nodename='esp32', release='1.12.0', version='v1.12 on 2019-12-20', machine='ESP32 module (spiram) with",
"delete(): pass def get(): pass def head(): pass def patch():",
"head(): pass def patch(): pass def post(): pass def put():",
"1.3.2 class Response: '' def close(): pass content = None",
"(spiram) with ESP32') # Stubber: 1.3.2 class Response: '' def",
"machine='ESP32 module (spiram) with ESP32') # Stubber: 1.3.2 class Response:",
"pass def put(): pass def request(): pass usocket = None"
] |
[
"p.search(o.path) print m.group('uid') print m.group('mid') def parse2(): exc_type_str = \"<type",
"Jike Inc. All Rights Reserved. # Author: <EMAIL> import re",
"<EMAIL> import re from urlparse import urlparse def parse1(): p",
"#-*- coding=utf-8 -*- # # Copyright 2012 Jike Inc. All",
"# # Copyright 2012 Jike Inc. All Rights Reserved. #",
"All Rights Reserved. # Author: <EMAIL> import re from urlparse",
"# Author: <EMAIL> import re from urlparse import urlparse def",
"import re from urlparse import urlparse def parse1(): p =",
"urlparse(\"http://weibo.com/2827699110/yz62AlEjF\") m = p.search(o.path) print m.group('uid') print m.group('mid') def parse2():",
"print m.group('uid') print m.group('mid') def parse2(): exc_type_str = \"<type 'exceptions.IndexError'>\"",
"urlparse def parse1(): p = re.compile(r\"/(?P<uid>\\d+)/(?P<mid>\\w+)\") o = urlparse(\"http://weibo.com/2827699110/yz62AlEjF\") m",
"re from urlparse import urlparse def parse1(): p = re.compile(r\"/(?P<uid>\\d+)/(?P<mid>\\w+)\")",
"import urlparse def parse1(): p = re.compile(r\"/(?P<uid>\\d+)/(?P<mid>\\w+)\") o = urlparse(\"http://weibo.com/2827699110/yz62AlEjF\")",
"parse1(): p = re.compile(r\"/(?P<uid>\\d+)/(?P<mid>\\w+)\") o = urlparse(\"http://weibo.com/2827699110/yz62AlEjF\") m = p.search(o.path)",
"urlparse import urlparse def parse1(): p = re.compile(r\"/(?P<uid>\\d+)/(?P<mid>\\w+)\") o =",
"Author: <EMAIL> import re from urlparse import urlparse def parse1():",
"Inc. All Rights Reserved. # Author: <EMAIL> import re from",
"Reserved. # Author: <EMAIL> import re from urlparse import urlparse",
"Copyright 2012 Jike Inc. All Rights Reserved. # Author: <EMAIL>",
"python #-*- coding=utf-8 -*- # # Copyright 2012 Jike Inc.",
"# Copyright 2012 Jike Inc. All Rights Reserved. # Author:",
"o = urlparse(\"http://weibo.com/2827699110/yz62AlEjF\") m = p.search(o.path) print m.group('uid') print m.group('mid')",
"m = p.search(o.path) print m.group('uid') print m.group('mid') def parse2(): exc_type_str",
"= p.search(o.path) print m.group('uid') print m.group('mid') def parse2(): exc_type_str =",
"= re.compile(r\"/(?P<uid>\\d+)/(?P<mid>\\w+)\") o = urlparse(\"http://weibo.com/2827699110/yz62AlEjF\") m = p.search(o.path) print m.group('uid')",
"re.compile(r\"/(?P<uid>\\d+)/(?P<mid>\\w+)\") o = urlparse(\"http://weibo.com/2827699110/yz62AlEjF\") m = p.search(o.path) print m.group('uid') print",
"m.group('uid') print m.group('mid') def parse2(): exc_type_str = \"<type 'exceptions.IndexError'>\" parse1()",
"from urlparse import urlparse def parse1(): p = re.compile(r\"/(?P<uid>\\d+)/(?P<mid>\\w+)\") o",
"-*- # # Copyright 2012 Jike Inc. All Rights Reserved.",
"coding=utf-8 -*- # # Copyright 2012 Jike Inc. All Rights",
"Rights Reserved. # Author: <EMAIL> import re from urlparse import",
"def parse1(): p = re.compile(r\"/(?P<uid>\\d+)/(?P<mid>\\w+)\") o = urlparse(\"http://weibo.com/2827699110/yz62AlEjF\") m =",
"#!/usr/bin/env python #-*- coding=utf-8 -*- # # Copyright 2012 Jike",
"= urlparse(\"http://weibo.com/2827699110/yz62AlEjF\") m = p.search(o.path) print m.group('uid') print m.group('mid') def",
"2012 Jike Inc. All Rights Reserved. # Author: <EMAIL> import",
"p = re.compile(r\"/(?P<uid>\\d+)/(?P<mid>\\w+)\") o = urlparse(\"http://weibo.com/2827699110/yz62AlEjF\") m = p.search(o.path) print",
"<filename>python/re_user.py #!/usr/bin/env python #-*- coding=utf-8 -*- # # Copyright 2012"
] |
[
"= Label(text=str(opt)) self.opt_boxes.append(check_box) self.labels.append(label) box.add_widget(check_box) box.add_widget(label) self.grid.add_widget(box) cancel_button = Button(text=\"Cancel\")",
"import matplotlib.pyplot as plt import matplotlib import datetime from TransactionBook.model.Filter",
"_): selection = [] for i, check_box in enumerate(self.opt_boxes): if",
"import Filter from datetime import datetime from kivy.uix.popup import Popup",
"BoxLayout from kivy.uix.button import Button import matplotlib.pyplot as plt import",
"from kivy.uix.checkbox import CheckBox from kivy.core.window import Window class MultiSelectPopUp(Popup):",
"from kivy.uix.boxlayout import BoxLayout from kivy.uix.button import Button import matplotlib.pyplot",
"from kivy.core.window import Window class MultiSelectPopUp(Popup): pHint_x = NumericProperty(0.7) pHint_y",
"self.main_layout.add_widget(self.grid) self.content = self.main_layout self.size_hint = self.pHint Window.release_all_keyboards() self.open() def",
"= NumericProperty(0.7) pHint_y = NumericProperty(0.7) pHint = ReferenceListProperty(pHint_x, pHint_y) def",
"box = BoxLayout(orientation='horizontal') box.add_widget(cancel_button) box.add_widget(ok_button) self.grid.add_widget(box) self.main_layout.add_widget(self.grid) self.content = self.main_layout",
"= \"Single_Select_Only_Group\" label = Label(text=str(opt)) self.opt_boxes.append(check_box) self.labels.append(label) box.add_widget(check_box) box.add_widget(label) self.grid.add_widget(box)",
"ok_button = Button(text=\"Ok\") ok_button.bind(on_press=self.ok_callback) box = BoxLayout(orientation='horizontal') box.add_widget(cancel_button) box.add_widget(ok_button) self.grid.add_widget(box)",
"__init__(self, title, option_list, option_init=None, callback=None, multiselect=True, **kwargs): super().__init__(**kwargs) self.title =",
"len(option_list) self.grid = GridLayout(cols=1) self.opt_boxes = [] self.labels = []",
"self.main_layout self.size_hint = self.pHint Window.release_all_keyboards() self.open() def ok_callback(self, _): selection",
"Button(text=\"Cancel\") cancel_button.bind(on_press=self.cancel_callback) ok_button = Button(text=\"Ok\") ok_button.bind(on_press=self.ok_callback) box = BoxLayout(orientation='horizontal') box.add_widget(cancel_button)",
"kivy.properties import NumericProperty, ReferenceListProperty from kivy.uix.checkbox import CheckBox from kivy.core.window",
"self.opt_boxes.append(check_box) self.labels.append(label) box.add_widget(check_box) box.add_widget(label) self.grid.add_widget(box) cancel_button = Button(text=\"Cancel\") cancel_button.bind(on_press=self.cancel_callback) ok_button",
"selection.append(self.labels[i].text) self.callback(selection) self.dismiss() def cancel_callback(self, _): self.dismiss() if __name__ ==",
"kivy.base import runTouchApp def cb(list_of_selection): print(list_of_selection) c = MultiSelectPopUp(title=\"Test\", option_list=[\"Item1\",",
"title self.callback = callback self.main_layout = AnchorLayout() if option_init is",
"def cb(list_of_selection): print(list_of_selection) c = MultiSelectPopUp(title=\"Test\", option_list=[\"Item1\", \"Item2\", \"Item3\"], callback=cb,",
"cb(list_of_selection): print(list_of_selection) c = MultiSelectPopUp(title=\"Test\", option_list=[\"Item1\", \"Item2\", \"Item3\"], callback=cb, option_init=[True,",
"import runTouchApp def cb(list_of_selection): print(list_of_selection) c = MultiSelectPopUp(title=\"Test\", option_list=[\"Item1\", \"Item2\",",
"self.grid.add_widget(box) self.main_layout.add_widget(self.grid) self.content = self.main_layout self.size_hint = self.pHint Window.release_all_keyboards() self.open()",
"kivy.uix.button import Button import matplotlib.pyplot as plt import matplotlib import",
"import FigureCanvasKivyAgg from kivy.uix.anchorlayout import AnchorLayout from kivy.uix.boxlayout import BoxLayout",
"self.main_layout = AnchorLayout() if option_init is None: option_init = [True]",
"import datetime from kivy.uix.popup import Popup from kivy.properties import NumericProperty,",
"FigureCanvasKivyAgg from kivy.uix.anchorlayout import AnchorLayout from kivy.uix.boxlayout import BoxLayout from",
"callback self.main_layout = AnchorLayout() if option_init is None: option_init =",
"i, check_box in enumerate(self.opt_boxes): if check_box.active: selection.append(self.labels[i].text) self.callback(selection) self.dismiss() def",
"box = BoxLayout(orientation='horizontal') check_box = CheckBox(active=option_init[i]) if not multiselect: check_box.group",
"= title self.callback = callback self.main_layout = AnchorLayout() if option_init",
"from kivy.uix.label import Label from kivy.uix.textinput import TextInput from kivy.garden.matplotlib.backend_kivyagg",
"BoxLayout(orientation='horizontal') check_box = CheckBox(active=option_init[i]) if not multiselect: check_box.group = \"Single_Select_Only_Group\"",
"**kwargs): super().__init__(**kwargs) self.title = title self.callback = callback self.main_layout =",
"\"Single_Select_Only_Group\" label = Label(text=str(opt)) self.opt_boxes.append(check_box) self.labels.append(label) box.add_widget(check_box) box.add_widget(label) self.grid.add_widget(box) cancel_button",
"kivy.core.window import Window class MultiSelectPopUp(Popup): pHint_x = NumericProperty(0.7) pHint_y =",
"= NumericProperty(0.7) pHint = ReferenceListProperty(pHint_x, pHint_y) def __init__(self, title, option_list,",
"import Window class MultiSelectPopUp(Popup): pHint_x = NumericProperty(0.7) pHint_y = NumericProperty(0.7)",
"not multiselect: check_box.group = \"Single_Select_Only_Group\" label = Label(text=str(opt)) self.opt_boxes.append(check_box) self.labels.append(label)",
"ok_button.bind(on_press=self.ok_callback) box = BoxLayout(orientation='horizontal') box.add_widget(cancel_button) box.add_widget(ok_button) self.grid.add_widget(box) self.main_layout.add_widget(self.grid) self.content =",
"from kivy.properties import NumericProperty, ReferenceListProperty from kivy.uix.checkbox import CheckBox from",
"[True] * len(option_list) self.grid = GridLayout(cols=1) self.opt_boxes = [] self.labels",
"== \"__main__\": from kivy.base import runTouchApp def cb(list_of_selection): print(list_of_selection) c",
"BoxLayout(orientation='horizontal') box.add_widget(cancel_button) box.add_widget(ok_button) self.grid.add_widget(box) self.main_layout.add_widget(self.grid) self.content = self.main_layout self.size_hint =",
"Window.release_all_keyboards() self.open() def ok_callback(self, _): selection = [] for i,",
"= BoxLayout(orientation='horizontal') check_box = CheckBox(active=option_init[i]) if not multiselect: check_box.group =",
"import Button import matplotlib.pyplot as plt import matplotlib import datetime",
"self.open() def ok_callback(self, _): selection = [] for i, check_box",
"self.labels.append(label) box.add_widget(check_box) box.add_widget(label) self.grid.add_widget(box) cancel_button = Button(text=\"Cancel\") cancel_button.bind(on_press=self.cancel_callback) ok_button =",
"title, option_list, option_init=None, callback=None, multiselect=True, **kwargs): super().__init__(**kwargs) self.title = title",
"CheckBox(active=option_init[i]) if not multiselect: check_box.group = \"Single_Select_Only_Group\" label = Label(text=str(opt))",
"from kivy.uix.popup import Popup from kivy.properties import NumericProperty, ReferenceListProperty from",
"= AnchorLayout() if option_init is None: option_init = [True] *",
"box.add_widget(cancel_button) box.add_widget(ok_button) self.grid.add_widget(box) self.main_layout.add_widget(self.grid) self.content = self.main_layout self.size_hint = self.pHint",
"cancel_callback(self, _): self.dismiss() if __name__ == \"__main__\": from kivy.base import",
"AnchorLayout from kivy.uix.boxlayout import BoxLayout from kivy.uix.button import Button import",
"= callback self.main_layout = AnchorLayout() if option_init is None: option_init",
"self.content = self.main_layout self.size_hint = self.pHint Window.release_all_keyboards() self.open() def ok_callback(self,",
"ReferenceListProperty(pHint_x, pHint_y) def __init__(self, title, option_list, option_init=None, callback=None, multiselect=True, **kwargs):",
"multiselect=True, **kwargs): super().__init__(**kwargs) self.title = title self.callback = callback self.main_layout",
"check_box in enumerate(self.opt_boxes): if check_box.active: selection.append(self.labels[i].text) self.callback(selection) self.dismiss() def cancel_callback(self,",
"= MultiSelectPopUp(title=\"Test\", option_list=[\"Item1\", \"Item2\", \"Item3\"], callback=cb, option_init=[True, False, True]) runTouchApp(c)",
"import AnchorLayout from kivy.uix.boxlayout import BoxLayout from kivy.uix.button import Button",
"None: option_init = [True] * len(option_list) self.grid = GridLayout(cols=1) self.opt_boxes",
"ok_callback(self, _): selection = [] for i, check_box in enumerate(self.opt_boxes):",
"= [] self.labels = [] for i, opt in enumerate(option_list):",
"TransactionBook.model.Filter import Filter from datetime import datetime from kivy.uix.popup import",
"self.callback = callback self.main_layout = AnchorLayout() if option_init is None:",
"self.grid.add_widget(box) cancel_button = Button(text=\"Cancel\") cancel_button.bind(on_press=self.cancel_callback) ok_button = Button(text=\"Ok\") ok_button.bind(on_press=self.ok_callback) box",
"self.labels = [] for i, opt in enumerate(option_list): box =",
"import Popup from kivy.properties import NumericProperty, ReferenceListProperty from kivy.uix.checkbox import",
"c = MultiSelectPopUp(title=\"Test\", option_list=[\"Item1\", \"Item2\", \"Item3\"], callback=cb, option_init=[True, False, True])",
"AnchorLayout() if option_init is None: option_init = [True] * len(option_list)",
"\"__main__\": from kivy.base import runTouchApp def cb(list_of_selection): print(list_of_selection) c =",
"runTouchApp def cb(list_of_selection): print(list_of_selection) c = MultiSelectPopUp(title=\"Test\", option_list=[\"Item1\", \"Item2\", \"Item3\"],",
"cancel_button.bind(on_press=self.cancel_callback) ok_button = Button(text=\"Ok\") ok_button.bind(on_press=self.ok_callback) box = BoxLayout(orientation='horizontal') box.add_widget(cancel_button) box.add_widget(ok_button)",
"kivy.garden.matplotlib.backend_kivyagg import FigureCanvasKivyAgg from kivy.uix.anchorlayout import AnchorLayout from kivy.uix.boxlayout import",
"<reponame>LukHad/AccountBook<filename>TransactionBook/gui_kivy/generic/MultiSelectPopUp.py from kivy.uix.gridlayout import GridLayout from kivy.uix.label import Label from",
"GridLayout from kivy.uix.label import Label from kivy.uix.textinput import TextInput from",
"= [] for i, opt in enumerate(option_list): box = BoxLayout(orientation='horizontal')",
"def cancel_callback(self, _): self.dismiss() if __name__ == \"__main__\": from kivy.base",
"ReferenceListProperty from kivy.uix.checkbox import CheckBox from kivy.core.window import Window class",
"= [True] * len(option_list) self.grid = GridLayout(cols=1) self.opt_boxes = []",
"from kivy.base import runTouchApp def cb(list_of_selection): print(list_of_selection) c = MultiSelectPopUp(title=\"Test\",",
"NumericProperty(0.7) pHint_y = NumericProperty(0.7) pHint = ReferenceListProperty(pHint_x, pHint_y) def __init__(self,",
"self.dismiss() def cancel_callback(self, _): self.dismiss() if __name__ == \"__main__\": from",
"import matplotlib import datetime from TransactionBook.model.Filter import Filter from datetime",
"option_init=None, callback=None, multiselect=True, **kwargs): super().__init__(**kwargs) self.title = title self.callback =",
"print(list_of_selection) c = MultiSelectPopUp(title=\"Test\", option_list=[\"Item1\", \"Item2\", \"Item3\"], callback=cb, option_init=[True, False,",
"pHint_y) def __init__(self, title, option_list, option_init=None, callback=None, multiselect=True, **kwargs): super().__init__(**kwargs)",
"in enumerate(self.opt_boxes): if check_box.active: selection.append(self.labels[i].text) self.callback(selection) self.dismiss() def cancel_callback(self, _):",
"kivy.uix.popup import Popup from kivy.properties import NumericProperty, ReferenceListProperty from kivy.uix.checkbox",
"Popup from kivy.properties import NumericProperty, ReferenceListProperty from kivy.uix.checkbox import CheckBox",
"kivy.uix.boxlayout import BoxLayout from kivy.uix.button import Button import matplotlib.pyplot as",
"= Button(text=\"Ok\") ok_button.bind(on_press=self.ok_callback) box = BoxLayout(orientation='horizontal') box.add_widget(cancel_button) box.add_widget(ok_button) self.grid.add_widget(box) self.main_layout.add_widget(self.grid)",
"plt import matplotlib import datetime from TransactionBook.model.Filter import Filter from",
"import GridLayout from kivy.uix.label import Label from kivy.uix.textinput import TextInput",
"self.title = title self.callback = callback self.main_layout = AnchorLayout() if",
"opt in enumerate(option_list): box = BoxLayout(orientation='horizontal') check_box = CheckBox(active=option_init[i]) if",
"datetime from TransactionBook.model.Filter import Filter from datetime import datetime from",
"box.add_widget(check_box) box.add_widget(label) self.grid.add_widget(box) cancel_button = Button(text=\"Cancel\") cancel_button.bind(on_press=self.cancel_callback) ok_button = Button(text=\"Ok\")",
"from TransactionBook.model.Filter import Filter from datetime import datetime from kivy.uix.popup",
"kivy.uix.textinput import TextInput from kivy.garden.matplotlib.backend_kivyagg import FigureCanvasKivyAgg from kivy.uix.anchorlayout import",
"datetime from kivy.uix.popup import Popup from kivy.properties import NumericProperty, ReferenceListProperty",
"self.grid = GridLayout(cols=1) self.opt_boxes = [] self.labels = [] for",
"from kivy.garden.matplotlib.backend_kivyagg import FigureCanvasKivyAgg from kivy.uix.anchorlayout import AnchorLayout from kivy.uix.boxlayout",
"self.pHint Window.release_all_keyboards() self.open() def ok_callback(self, _): selection = [] for",
"Button import matplotlib.pyplot as plt import matplotlib import datetime from",
"matplotlib import datetime from TransactionBook.model.Filter import Filter from datetime import",
"callback=None, multiselect=True, **kwargs): super().__init__(**kwargs) self.title = title self.callback = callback",
"= self.pHint Window.release_all_keyboards() self.open() def ok_callback(self, _): selection = []",
"option_list, option_init=None, callback=None, multiselect=True, **kwargs): super().__init__(**kwargs) self.title = title self.callback",
"option_init = [True] * len(option_list) self.grid = GridLayout(cols=1) self.opt_boxes =",
"= self.main_layout self.size_hint = self.pHint Window.release_all_keyboards() self.open() def ok_callback(self, _):",
"label = Label(text=str(opt)) self.opt_boxes.append(check_box) self.labels.append(label) box.add_widget(check_box) box.add_widget(label) self.grid.add_widget(box) cancel_button =",
"from kivy.uix.anchorlayout import AnchorLayout from kivy.uix.boxlayout import BoxLayout from kivy.uix.button",
"kivy.uix.anchorlayout import AnchorLayout from kivy.uix.boxlayout import BoxLayout from kivy.uix.button import",
"from datetime import datetime from kivy.uix.popup import Popup from kivy.properties",
"box.add_widget(ok_button) self.grid.add_widget(box) self.main_layout.add_widget(self.grid) self.content = self.main_layout self.size_hint = self.pHint Window.release_all_keyboards()",
"matplotlib.pyplot as plt import matplotlib import datetime from TransactionBook.model.Filter import",
"GridLayout(cols=1) self.opt_boxes = [] self.labels = [] for i, opt",
"import TextInput from kivy.garden.matplotlib.backend_kivyagg import FigureCanvasKivyAgg from kivy.uix.anchorlayout import AnchorLayout",
"enumerate(option_list): box = BoxLayout(orientation='horizontal') check_box = CheckBox(active=option_init[i]) if not multiselect:",
"i, opt in enumerate(option_list): box = BoxLayout(orientation='horizontal') check_box = CheckBox(active=option_init[i])",
"check_box = CheckBox(active=option_init[i]) if not multiselect: check_box.group = \"Single_Select_Only_Group\" label",
"[] for i, check_box in enumerate(self.opt_boxes): if check_box.active: selection.append(self.labels[i].text) self.callback(selection)",
"import datetime from TransactionBook.model.Filter import Filter from datetime import datetime",
"import Label from kivy.uix.textinput import TextInput from kivy.garden.matplotlib.backend_kivyagg import FigureCanvasKivyAgg",
"def __init__(self, title, option_list, option_init=None, callback=None, multiselect=True, **kwargs): super().__init__(**kwargs) self.title",
"self.callback(selection) self.dismiss() def cancel_callback(self, _): self.dismiss() if __name__ == \"__main__\":",
"self.opt_boxes = [] self.labels = [] for i, opt in",
"= CheckBox(active=option_init[i]) if not multiselect: check_box.group = \"Single_Select_Only_Group\" label =",
"if __name__ == \"__main__\": from kivy.base import runTouchApp def cb(list_of_selection):",
"__name__ == \"__main__\": from kivy.base import runTouchApp def cb(list_of_selection): print(list_of_selection)",
"if option_init is None: option_init = [True] * len(option_list) self.grid",
"self.size_hint = self.pHint Window.release_all_keyboards() self.open() def ok_callback(self, _): selection =",
"= GridLayout(cols=1) self.opt_boxes = [] self.labels = [] for i,",
"= [] for i, check_box in enumerate(self.opt_boxes): if check_box.active: selection.append(self.labels[i].text)",
"check_box.active: selection.append(self.labels[i].text) self.callback(selection) self.dismiss() def cancel_callback(self, _): self.dismiss() if __name__",
"CheckBox from kivy.core.window import Window class MultiSelectPopUp(Popup): pHint_x = NumericProperty(0.7)",
"from kivy.uix.gridlayout import GridLayout from kivy.uix.label import Label from kivy.uix.textinput",
"kivy.uix.checkbox import CheckBox from kivy.core.window import Window class MultiSelectPopUp(Popup): pHint_x",
"NumericProperty(0.7) pHint = ReferenceListProperty(pHint_x, pHint_y) def __init__(self, title, option_list, option_init=None,",
"[] self.labels = [] for i, opt in enumerate(option_list): box",
"as plt import matplotlib import datetime from TransactionBook.model.Filter import Filter",
"super().__init__(**kwargs) self.title = title self.callback = callback self.main_layout = AnchorLayout()",
"TextInput from kivy.garden.matplotlib.backend_kivyagg import FigureCanvasKivyAgg from kivy.uix.anchorlayout import AnchorLayout from",
"pHint_y = NumericProperty(0.7) pHint = ReferenceListProperty(pHint_x, pHint_y) def __init__(self, title,",
"in enumerate(option_list): box = BoxLayout(orientation='horizontal') check_box = CheckBox(active=option_init[i]) if not",
"multiselect: check_box.group = \"Single_Select_Only_Group\" label = Label(text=str(opt)) self.opt_boxes.append(check_box) self.labels.append(label) box.add_widget(check_box)",
"pHint_x = NumericProperty(0.7) pHint_y = NumericProperty(0.7) pHint = ReferenceListProperty(pHint_x, pHint_y)",
"Window class MultiSelectPopUp(Popup): pHint_x = NumericProperty(0.7) pHint_y = NumericProperty(0.7) pHint",
"selection = [] for i, check_box in enumerate(self.opt_boxes): if check_box.active:",
"import NumericProperty, ReferenceListProperty from kivy.uix.checkbox import CheckBox from kivy.core.window import",
"option_init is None: option_init = [True] * len(option_list) self.grid =",
"is None: option_init = [True] * len(option_list) self.grid = GridLayout(cols=1)",
"from kivy.uix.textinput import TextInput from kivy.garden.matplotlib.backend_kivyagg import FigureCanvasKivyAgg from kivy.uix.anchorlayout",
"= ReferenceListProperty(pHint_x, pHint_y) def __init__(self, title, option_list, option_init=None, callback=None, multiselect=True,",
"Button(text=\"Ok\") ok_button.bind(on_press=self.ok_callback) box = BoxLayout(orientation='horizontal') box.add_widget(cancel_button) box.add_widget(ok_button) self.grid.add_widget(box) self.main_layout.add_widget(self.grid) self.content",
"Filter from datetime import datetime from kivy.uix.popup import Popup from",
"kivy.uix.label import Label from kivy.uix.textinput import TextInput from kivy.garden.matplotlib.backend_kivyagg import",
"* len(option_list) self.grid = GridLayout(cols=1) self.opt_boxes = [] self.labels =",
"check_box.group = \"Single_Select_Only_Group\" label = Label(text=str(opt)) self.opt_boxes.append(check_box) self.labels.append(label) box.add_widget(check_box) box.add_widget(label)",
"[] for i, opt in enumerate(option_list): box = BoxLayout(orientation='horizontal') check_box",
"for i, check_box in enumerate(self.opt_boxes): if check_box.active: selection.append(self.labels[i].text) self.callback(selection) self.dismiss()",
"if not multiselect: check_box.group = \"Single_Select_Only_Group\" label = Label(text=str(opt)) self.opt_boxes.append(check_box)",
"cancel_button = Button(text=\"Cancel\") cancel_button.bind(on_press=self.cancel_callback) ok_button = Button(text=\"Ok\") ok_button.bind(on_press=self.ok_callback) box =",
"def ok_callback(self, _): selection = [] for i, check_box in",
"class MultiSelectPopUp(Popup): pHint_x = NumericProperty(0.7) pHint_y = NumericProperty(0.7) pHint =",
"NumericProperty, ReferenceListProperty from kivy.uix.checkbox import CheckBox from kivy.core.window import Window",
"box.add_widget(label) self.grid.add_widget(box) cancel_button = Button(text=\"Cancel\") cancel_button.bind(on_press=self.cancel_callback) ok_button = Button(text=\"Ok\") ok_button.bind(on_press=self.ok_callback)",
"_): self.dismiss() if __name__ == \"__main__\": from kivy.base import runTouchApp",
"= BoxLayout(orientation='horizontal') box.add_widget(cancel_button) box.add_widget(ok_button) self.grid.add_widget(box) self.main_layout.add_widget(self.grid) self.content = self.main_layout self.size_hint",
"import BoxLayout from kivy.uix.button import Button import matplotlib.pyplot as plt",
"for i, opt in enumerate(option_list): box = BoxLayout(orientation='horizontal') check_box =",
"pHint = ReferenceListProperty(pHint_x, pHint_y) def __init__(self, title, option_list, option_init=None, callback=None,",
"Label from kivy.uix.textinput import TextInput from kivy.garden.matplotlib.backend_kivyagg import FigureCanvasKivyAgg from",
"import CheckBox from kivy.core.window import Window class MultiSelectPopUp(Popup): pHint_x =",
"kivy.uix.gridlayout import GridLayout from kivy.uix.label import Label from kivy.uix.textinput import",
"self.dismiss() if __name__ == \"__main__\": from kivy.base import runTouchApp def",
"Label(text=str(opt)) self.opt_boxes.append(check_box) self.labels.append(label) box.add_widget(check_box) box.add_widget(label) self.grid.add_widget(box) cancel_button = Button(text=\"Cancel\") cancel_button.bind(on_press=self.cancel_callback)",
"MultiSelectPopUp(Popup): pHint_x = NumericProperty(0.7) pHint_y = NumericProperty(0.7) pHint = ReferenceListProperty(pHint_x,",
"datetime import datetime from kivy.uix.popup import Popup from kivy.properties import",
"from kivy.uix.button import Button import matplotlib.pyplot as plt import matplotlib",
"= Button(text=\"Cancel\") cancel_button.bind(on_press=self.cancel_callback) ok_button = Button(text=\"Ok\") ok_button.bind(on_press=self.ok_callback) box = BoxLayout(orientation='horizontal')",
"if check_box.active: selection.append(self.labels[i].text) self.callback(selection) self.dismiss() def cancel_callback(self, _): self.dismiss() if",
"enumerate(self.opt_boxes): if check_box.active: selection.append(self.labels[i].text) self.callback(selection) self.dismiss() def cancel_callback(self, _): self.dismiss()"
] |
[
"and returns cars that have crossed it. Returns: List[Car]: List",
"for cars. \"\"\" capacity: int = field(default=5) \"\"\"Set amount of",
"the bridge and returns cars that have crossed it. Returns:",
"behaviour of bridge in simulation. On can set specific length",
"\"\"\"Bridge class simulating the behaviour of bridge in simulation. On",
"c in self.cars: c.distance_on_bridge += c.speed if c.distance_on_bridge >= self.length:",
"the scores for cars. \"\"\" capacity: int = field(default=5) \"\"\"Set",
"overall behaviour of bridge in the simulation and see how",
"that are currently on the bridge.\"\"\" def has_collapsed(self) -> bool:",
"for c in self.cars: c.distance_on_bridge += c.speed if c.distance_on_bridge >=",
"list() for c in self.cars: c.distance_on_bridge += c.speed if c.distance_on_bridge",
"empty list. Returns: List[Car]: List of cars that were on",
"cars that were on bridge when it collapsed. \"\"\" temp",
"if bridge has collapsed. Returns: bool: True if bridge has",
"crossed it. Returns: List[Car]: List of cars that have crossed",
"cars that the bridge can accommodate before collapsing.\"\"\" length: int",
"\"\"\"Returns a list of all cars on bridge and sets",
"across the bridge and returns cars that have crossed it.",
"use to cross it.\"\"\" cars: List[Car] = field(default_factory=list, repr=False, init=False)",
"= 0 finished_cars.append(c) self.cars = [c for c in self.cars",
"List[Car] = field(default_factory=list, repr=False, init=False) \"\"\"List of all of the",
"field(default=10) \"\"\"Length of bridge deciding how much time a car",
"return len(self.cars) > self.capacity def move_cars(self) -> List[Car]: \"\"\" Moves",
"List of cars that were on bridge when it collapsed.",
"on the bridge.\"\"\" def has_collapsed(self) -> bool: \"\"\"Simple method to",
"List[Car]: \"\"\"Returns a list of all cars on bridge and",
"of bridge in the simulation and see how it impacts",
"length: int = field(default=10) \"\"\"Length of bridge deciding how much",
"specific length and capacity for the bridge to change the",
"to cross it.\"\"\" cars: List[Car] = field(default_factory=list, repr=False, init=False) \"\"\"List",
"in the simulation and see how it impacts the scores",
"repr=False, init=False) \"\"\"List of all of the cars that are",
"bridge when it collapsed. \"\"\" temp = self.cars for c",
"bridge deciding how much time a car will use to",
"turn. \"\"\" finished_cars = list() for c in self.cars: c.distance_on_bridge",
"cars: List[Car] = field(default_factory=list, repr=False, init=False) \"\"\"List of all of",
"of all cars on bridge and sets cars to empty",
"= field(default_factory=list, repr=False, init=False) \"\"\"List of all of the cars",
"import Car @dataclass class Bridge: \"\"\"Bridge class simulating the behaviour",
"c not in finished_cars] return finished_cars def collapse_bridge(self) -> List[Car]:",
"simulation and see how it impacts the scores for cars.",
"List of cars that have crossed the bridge this turn.",
"> self.capacity def move_cars(self) -> List[Car]: \"\"\" Moves cars across",
"move_cars(self) -> List[Car]: \"\"\" Moves cars across the bridge and",
"currently on the bridge.\"\"\" def has_collapsed(self) -> bool: \"\"\"Simple method",
"= list() for c in self.cars: c.distance_on_bridge += c.speed if",
"has_collapsed(self) -> bool: \"\"\"Simple method to check if bridge has",
"set specific length and capacity for the bridge to change",
"in self.cars if c not in finished_cars] return finished_cars def",
"self.cars for c in temp: c.distance_on_bridge = 0 self.cars =",
"the bridge this turn. \"\"\" finished_cars = list() for c",
"has collapsed, False otherwise. \"\"\" return len(self.cars) > self.capacity def",
"the bridge can accommodate before collapsing.\"\"\" length: int = field(default=10)",
"typing import List from Car2 import Car @dataclass class Bridge:",
"def move_cars(self) -> List[Car]: \"\"\" Moves cars across the bridge",
"to check if bridge has collapsed. Returns: bool: True if",
"finished_cars = list() for c in self.cars: c.distance_on_bridge += c.speed",
"dataclasses import dataclass, field from typing import List from Car2",
"Returns: List[Car]: List of cars that were on bridge when",
"cars to empty list. Returns: List[Car]: List of cars that",
"otherwise. \"\"\" return len(self.cars) > self.capacity def move_cars(self) -> List[Car]:",
"and capacity for the bridge to change the overall behaviour",
"can accommodate before collapsing.\"\"\" length: int = field(default=10) \"\"\"Length of",
"for c in self.cars if c not in finished_cars] return",
"to change the overall behaviour of bridge in the simulation",
"List[Car]: List of cars that were on bridge when it",
"on bridge when it collapsed. \"\"\" temp = self.cars for",
"bool: True if bridge has collapsed, False otherwise. \"\"\" return",
"impacts the scores for cars. \"\"\" capacity: int = field(default=5)",
"capacity: int = field(default=5) \"\"\"Set amount of cars that the",
"c.distance_on_bridge += c.speed if c.distance_on_bridge >= self.length: c.distance_on_bridge = 0",
"import dataclass, field from typing import List from Car2 import",
"def collapse_bridge(self) -> List[Car]: \"\"\"Returns a list of all cars",
"can set specific length and capacity for the bridge to",
"field(default_factory=list, repr=False, init=False) \"\"\"List of all of the cars that",
"not in finished_cars] return finished_cars def collapse_bridge(self) -> List[Car]: \"\"\"Returns",
"all cars on bridge and sets cars to empty list.",
"the overall behaviour of bridge in the simulation and see",
"\"\"\"List of all of the cars that are currently on",
"crossed the bridge this turn. \"\"\" finished_cars = list() for",
"temp = self.cars for c in temp: c.distance_on_bridge = 0",
"bridge and returns cars that have crossed it. Returns: List[Car]:",
"cars on bridge and sets cars to empty list. Returns:",
"int = field(default=5) \"\"\"Set amount of cars that the bridge",
"it. Returns: List[Car]: List of cars that have crossed the",
"that have crossed the bridge this turn. \"\"\" finished_cars =",
"returns cars that have crossed it. Returns: List[Car]: List of",
"when it collapsed. \"\"\" temp = self.cars for c in",
"have crossed the bridge this turn. \"\"\" finished_cars = list()",
"self.cars: c.distance_on_bridge += c.speed if c.distance_on_bridge >= self.length: c.distance_on_bridge =",
"\"\"\" Moves cars across the bridge and returns cars that",
"True if bridge has collapsed, False otherwise. \"\"\" return len(self.cars)",
"how much time a car will use to cross it.\"\"\"",
"-> bool: \"\"\"Simple method to check if bridge has collapsed.",
"collapsing.\"\"\" length: int = field(default=10) \"\"\"Length of bridge deciding how",
"from Car2 import Car @dataclass class Bridge: \"\"\"Bridge class simulating",
"bridge and sets cars to empty list. Returns: List[Car]: List",
"cars across the bridge and returns cars that have crossed",
"self.capacity def move_cars(self) -> List[Car]: \"\"\" Moves cars across the",
"collapsed, False otherwise. \"\"\" return len(self.cars) > self.capacity def move_cars(self)",
"behaviour of bridge in the simulation and see how it",
"False otherwise. \"\"\" return len(self.cars) > self.capacity def move_cars(self) ->",
"\"\"\" capacity: int = field(default=5) \"\"\"Set amount of cars that",
"of all of the cars that are currently on the",
"in temp: c.distance_on_bridge = 0 self.cars = list() return temp",
"finished_cars.append(c) self.cars = [c for c in self.cars if c",
"cars that have crossed it. Returns: List[Car]: List of cars",
"simulation. On can set specific length and capacity for the",
"that have crossed it. Returns: List[Car]: List of cars that",
"[c for c in self.cars if c not in finished_cars]",
"scores for cars. \"\"\" capacity: int = field(default=5) \"\"\"Set amount",
"in self.cars: c.distance_on_bridge += c.speed if c.distance_on_bridge >= self.length: c.distance_on_bridge",
"will use to cross it.\"\"\" cars: List[Car] = field(default_factory=list, repr=False,",
"self.cars if c not in finished_cars] return finished_cars def collapse_bridge(self)",
"that were on bridge when it collapsed. \"\"\" temp =",
"for c in temp: c.distance_on_bridge = 0 self.cars = list()",
"and see how it impacts the scores for cars. \"\"\"",
"int = field(default=10) \"\"\"Length of bridge deciding how much time",
"length and capacity for the bridge to change the overall",
"List[Car]: \"\"\" Moves cars across the bridge and returns cars",
"Moves cars across the bridge and returns cars that have",
"c in self.cars if c not in finished_cars] return finished_cars",
"a car will use to cross it.\"\"\" cars: List[Car] =",
"return finished_cars def collapse_bridge(self) -> List[Car]: \"\"\"Returns a list of",
"c in temp: c.distance_on_bridge = 0 self.cars = list() return",
"cars. \"\"\" capacity: int = field(default=5) \"\"\"Set amount of cars",
"sets cars to empty list. Returns: List[Car]: List of cars",
"the simulation and see how it impacts the scores for",
"car will use to cross it.\"\"\" cars: List[Car] = field(default_factory=list,",
"this turn. \"\"\" finished_cars = list() for c in self.cars:",
"capacity for the bridge to change the overall behaviour of",
"self.cars = [c for c in self.cars if c not",
"collapsed. \"\"\" temp = self.cars for c in temp: c.distance_on_bridge",
"dataclass, field from typing import List from Car2 import Car",
"in simulation. On can set specific length and capacity for",
"@dataclass class Bridge: \"\"\"Bridge class simulating the behaviour of bridge",
"def has_collapsed(self) -> bool: \"\"\"Simple method to check if bridge",
"finished_cars def collapse_bridge(self) -> List[Car]: \"\"\"Returns a list of all",
"time a car will use to cross it.\"\"\" cars: List[Car]",
"and sets cars to empty list. Returns: List[Car]: List of",
"for the bridge to change the overall behaviour of bridge",
"deciding how much time a car will use to cross",
"\"\"\" finished_cars = list() for c in self.cars: c.distance_on_bridge +=",
"= field(default=5) \"\"\"Set amount of cars that the bridge can",
"field from typing import List from Car2 import Car @dataclass",
"\"\"\" return len(self.cars) > self.capacity def move_cars(self) -> List[Car]: \"\"\"",
"c.distance_on_bridge = 0 finished_cars.append(c) self.cars = [c for c in",
"bridge has collapsed. Returns: bool: True if bridge has collapsed,",
"the bridge to change the overall behaviour of bridge in",
"check if bridge has collapsed. Returns: bool: True if bridge",
"finished_cars] return finished_cars def collapse_bridge(self) -> List[Car]: \"\"\"Returns a list",
"much time a car will use to cross it.\"\"\" cars:",
"bridge has collapsed, False otherwise. \"\"\" return len(self.cars) > self.capacity",
"of cars that the bridge can accommodate before collapsing.\"\"\" length:",
"bridge in simulation. On can set specific length and capacity",
"amount of cars that the bridge can accommodate before collapsing.\"\"\"",
"all of the cars that are currently on the bridge.\"\"\"",
">= self.length: c.distance_on_bridge = 0 finished_cars.append(c) self.cars = [c for",
"simulating the behaviour of bridge in simulation. On can set",
"the bridge.\"\"\" def has_collapsed(self) -> bool: \"\"\"Simple method to check",
"in finished_cars] return finished_cars def collapse_bridge(self) -> List[Car]: \"\"\"Returns a",
"\"\"\"Simple method to check if bridge has collapsed. Returns: bool:",
"it impacts the scores for cars. \"\"\" capacity: int =",
"collapsed. Returns: bool: True if bridge has collapsed, False otherwise.",
"init=False) \"\"\"List of all of the cars that are currently",
"of the cars that are currently on the bridge.\"\"\" def",
"cars that have crossed the bridge this turn. \"\"\" finished_cars",
"= self.cars for c in temp: c.distance_on_bridge = 0 self.cars",
"a list of all cars on bridge and sets cars",
"Bridge: \"\"\"Bridge class simulating the behaviour of bridge in simulation.",
"List from Car2 import Car @dataclass class Bridge: \"\"\"Bridge class",
"-> List[Car]: \"\"\" Moves cars across the bridge and returns",
"c.speed if c.distance_on_bridge >= self.length: c.distance_on_bridge = 0 finished_cars.append(c) self.cars",
"has collapsed. Returns: bool: True if bridge has collapsed, False",
"class Bridge: \"\"\"Bridge class simulating the behaviour of bridge in",
"bridge can accommodate before collapsing.\"\"\" length: int = field(default=10) \"\"\"Length",
"if bridge has collapsed, False otherwise. \"\"\" return len(self.cars) >",
"of cars that have crossed the bridge this turn. \"\"\"",
"On can set specific length and capacity for the bridge",
"List[Car]: List of cars that have crossed the bridge this",
"\"\"\"Set amount of cars that the bridge can accommodate before",
"were on bridge when it collapsed. \"\"\" temp = self.cars",
"of cars that were on bridge when it collapsed. \"\"\"",
"the cars that are currently on the bridge.\"\"\" def has_collapsed(self)",
"Returns: List[Car]: List of cars that have crossed the bridge",
"bool: \"\"\"Simple method to check if bridge has collapsed. Returns:",
"\"\"\" temp = self.cars for c in temp: c.distance_on_bridge =",
"c.distance_on_bridge >= self.length: c.distance_on_bridge = 0 finished_cars.append(c) self.cars = [c",
"Car @dataclass class Bridge: \"\"\"Bridge class simulating the behaviour of",
"bridge in the simulation and see how it impacts the",
"<reponame>MormonJesus69420/Knowledge-Based-Systems-Project from dataclasses import dataclass, field from typing import List",
"cross it.\"\"\" cars: List[Car] = field(default_factory=list, repr=False, init=False) \"\"\"List of",
"change the overall behaviour of bridge in the simulation and",
"on bridge and sets cars to empty list. Returns: List[Car]:",
"= [c for c in self.cars if c not in",
"from dataclasses import dataclass, field from typing import List from",
"\"\"\"Length of bridge deciding how much time a car will",
"to empty list. Returns: List[Car]: List of cars that were",
"+= c.speed if c.distance_on_bridge >= self.length: c.distance_on_bridge = 0 finished_cars.append(c)",
"that the bridge can accommodate before collapsing.\"\"\" length: int =",
"cars that are currently on the bridge.\"\"\" def has_collapsed(self) ->",
"list of all cars on bridge and sets cars to",
"if c not in finished_cars] return finished_cars def collapse_bridge(self) ->",
"self.length: c.distance_on_bridge = 0 finished_cars.append(c) self.cars = [c for c",
"before collapsing.\"\"\" length: int = field(default=10) \"\"\"Length of bridge deciding",
"list. Returns: List[Car]: List of cars that were on bridge",
"import List from Car2 import Car @dataclass class Bridge: \"\"\"Bridge",
"Car2 import Car @dataclass class Bridge: \"\"\"Bridge class simulating the",
"field(default=5) \"\"\"Set amount of cars that the bridge can accommodate",
"class simulating the behaviour of bridge in simulation. On can",
"it collapsed. \"\"\" temp = self.cars for c in temp:",
"Returns: bool: True if bridge has collapsed, False otherwise. \"\"\"",
"0 finished_cars.append(c) self.cars = [c for c in self.cars if",
"collapse_bridge(self) -> List[Car]: \"\"\"Returns a list of all cars on",
"from typing import List from Car2 import Car @dataclass class",
"of bridge deciding how much time a car will use",
"bridge.\"\"\" def has_collapsed(self) -> bool: \"\"\"Simple method to check if",
"len(self.cars) > self.capacity def move_cars(self) -> List[Car]: \"\"\" Moves cars",
"accommodate before collapsing.\"\"\" length: int = field(default=10) \"\"\"Length of bridge",
"-> List[Car]: \"\"\"Returns a list of all cars on bridge",
"if c.distance_on_bridge >= self.length: c.distance_on_bridge = 0 finished_cars.append(c) self.cars =",
"how it impacts the scores for cars. \"\"\" capacity: int",
"are currently on the bridge.\"\"\" def has_collapsed(self) -> bool: \"\"\"Simple",
"= field(default=10) \"\"\"Length of bridge deciding how much time a",
"bridge to change the overall behaviour of bridge in the",
"see how it impacts the scores for cars. \"\"\" capacity:",
"method to check if bridge has collapsed. Returns: bool: True",
"it.\"\"\" cars: List[Car] = field(default_factory=list, repr=False, init=False) \"\"\"List of all",
"bridge this turn. \"\"\" finished_cars = list() for c in",
"have crossed it. Returns: List[Car]: List of cars that have",
"of bridge in simulation. On can set specific length and",
"the behaviour of bridge in simulation. On can set specific"
] |
[
"= config self.bind_ip = config[\"main\"][\"bind_ip\"] self.bind_port = config[\"main\"][\"bind_port\"] PlexHttpHandler.stations =",
"or contentPath.startswith('/devices/probe')) and (not self.config['main']['use_old_plex_interface'])): self.do_response(200, 'application/xml', templates['xmlRmgDeviceDiscover'].format(self.config['main']['uuid'], self.config['main']['reporting_friendly_name'], self.config['main']['reporting_model'],",
"stations import lib.epg2xml as epg2xml import lib.channels_m3u as channels_m3u from",
"self.config['main']['reporting_model'], self.config['main']['reporting_firmware_name'], self.config['main']['tuner_count'], self.config['main']['reporting_firmware_ver'], self.config['main']['uuid'], base_url)) elif contentPath == '/lineup_status.json':",
"for index, scan_status in enumerate(self.rmg_station_scans): if scan_status == 'Idle': tuner_list",
"data to prevent a zombie process. ffmpeg_proc.communicate() except ValueError: print(\"Connection",
"queryData[getdataItemSplit[0]] = getdataItemSplit[1] if contentPath == '/lineup.post': if queryData['scan'] ==",
"'').replace('/', '') station_list = stations.get_dma_stations_and_channels(self.config, self.location) for sid in station_list:",
"contentPath == '/discover.json': self.do_response(200, 'application/json', templates['jsonDiscover'].format(self.config['main']['reporting_friendly_name'], self.config['main']['reporting_model'], self.config['main']['reporting_firmware_name'], self.config['main']['tuner_count'], self.config['main']['reporting_firmware_ver'],",
"def do_DELETE(self): base_url = self.config['main']['plex_accessible_ip'] + ':' + self.config['main']['plex_accessible_port'] contentPath",
"station_list: sid = str(list_key) returnXML = returnXML + templates['xmlLineupItem'].format(station_list[sid]['channel'], station_list[sid]['friendlyName'],",
"do_POST(self): base_url = self.config['main']['plex_accessible_ip'] + ':' + self.config['main']['plex_accessible_port'] contentPath =",
"SIGTERM to shutdown ffmpeg ffmpeg_proc.terminate() try: # ffmpeg writes a",
"print(\"Connection Closed\") self.rmg_station_scans[index] = 'Idle' else: self.send_response(400, 'All tuners already",
"returnJSON + \"]\" self.do_response(200, 'application/json', returnJSON) elif contentPath == '/lineup.xml':",
"reply_str): self.send_response(code) self.send_header('Content-type', mime) self.end_headers() if reply_str: self.wfile.write(reply_str.encode('utf-8')) # mostly",
"self.config['main']['tuner_type']) self.do_response(200, 'application/json', returnJSON) elif contentPath == '/lineup.json': # TODO",
"putting this here after the response on purpose stations.refresh_dma_stations_and_channels(self.config, self.locast,",
"templates['jsonLineupStatus'] else: returnJSON = templates['jsonLineupComplete'].replace(\"Antenna\", self.config['main']['tuner_type']) self.do_response(200, 'application/json', returnJSON) elif",
"self.do_response(200, 'text/html') self.hdhr_station_scan = False for index, scan_status in enumerate(self.rmg_station_scans):",
"can use at a time for index, scan_status in enumerate(self.rmg_station_scans):",
"in station_list: sid = str(list_key) returnXML = returnXML + templates['xmlLineupItem'].format(station_list[sid]['channel'],",
"len(getdataItemSplit) > 1: queryData[getdataItemSplit[0]] = getdataItemSplit[1] # paths and logic",
"using class variables since this should only be set once",
"works, then keep grabbing it videoData = ffmpeg_proc.stdout.read(int(self.config['main']['bytes_per_read'])) while True:",
"templates['xmlRmgDeviceChannelItem'].format(station_list[sid]['channel'], station_list[sid]['friendlyName']) channelXML = channelXML + tmpXML self.do_response(200, 'application/xml', templates['xmlRmgDeviceChannels'].format(index",
"e.errno in [errno.EPIPE, errno.ECONNABORTED, errno.ECONNRESET, errno.ECONNREFUSED]: break else: raise videoData",
"grabbing it videoData = ffmpeg_proc.stdout.read(int(self.config['main']['bytes_per_read'])) while True: if not videoData:",
"contentPath = self.path queryData = {} if self.path.find('?') != -1:",
"scan_status) tuner_list = tuner_list + formatted_xml self.do_response(200, 'application/xml', templates['xmlRmgDeviceIdentity'].format(self.config['main']['uuid'], self.config['main']['reporting_friendly_name'],",
"and https://stackoverflow.com/questions/46210672/python-2-7-streaming-http-server-supporting-multiple-connections-on-one-port class PlexHttpServer(threading.Thread): def __init__(self, serverSocket, config, locast_service, location):",
"self.do_response(200, 'application/json', returnJSON) elif contentPath == '/lineup.xml': # TODO station_list",
"'Scan': tuner_list = tuner_list + templates['xmlRmgTunerScanning'].format(str(index)) else: # otherwise, we're",
"contentPath == '/lineup.post': if queryData['scan'] == 'start': self.hdhr_station_scan = True",
"self.bind_port = config[\"main\"][\"bind_port\"] PlexHttpHandler.stations = stations PlexHttpHandler.local_locast = locast_service PlexHttpHandler.location",
"False rmg_station_scans = [] local_locast = None location = None",
"if reply_str: self.wfile.write(reply_str.encode('utf-8')) # mostly from https://github.com/ZeWaren/python-upnp-ssdp-example # and https://stackoverflow.com/questions/46210672/python-2-7-streaming-http-server-supporting-multiple-connections-on-one-port",
"+ \"</Lineup>\" self.do_response(200, 'application/xml', returnXML) elif contentPath.startswith('/watch'): self.do_tuning(contentPath.replace('/watch/', '')) elif",
"telly:routes.go: https://github.com/tellytv/telly if (contentPath == '/') and (not self.config['main']['use_old_plex_interface']): self.do_response(200,",
"if queryData['scan'] == 'start': self.hdhr_station_scan = True for index, scan_status",
"1: queryData[getdataItemSplit[0]] = getdataItemSplit[1] if contentPath == '/lineup.post': if queryData['scan']",
"x in range(int(config['main']['tuner_count'])): tmp_rmg_scans.append('Idle') PlexHttpHandler.rmg_station_scans = tmp_rmg_scans self.socket = serverSocket",
"we're streaming, and the value will be the channel triplet",
"self.rmg_station_scans[index] = \"Idle\" else: print(\"Unknown request to \" + contentPath)",
"mime) self.end_headers() if reply_str: self.wfile.write(reply_str.encode('utf-8')) # mostly from https://github.com/ZeWaren/python-upnp-ssdp-example #",
"= socket.socket(socket.AF_INET, socket.SOCK_STREAM) serverSocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) serverSocket.bind((config[\"main\"]['bind_ip'], int(config[\"main\"]['bind_port']))) serverSocket.listen(int(config[\"main\"][\"concurrent_listeners\"])) print(\"Now",
"formatted_xml = templates['xmlRmgTunerStreaming'].format(str(index), scan_status) tuner_list = tuner_list + formatted_xml self.do_response(200,",
"(not self.config['main']['use_old_plex_interface']): self.do_response(200, 'application/xml', templates['xmlRmgIdentification'].format(self.config['main']['reporting_friendly_name'])) elif (contentPath == '/') or",
"self.do_tuning(contentPath.replace('/auto/v', '')) elif ((contentPath.startswith('/devices/' + self.config['main']['uuid'] + '/media/')) and (not",
"len(postdataItemSplit) > 1: queryData[postdataItemSplit[0]] = postdataItemSplit[1] if self.path.find('?') != -1:",
"# otherwise, we're streaming, and the value will be the",
"channelUri = self.local_locast.get_station_stream_uri(sid) station_list = stations.get_dma_stations_and_channels(self.config, self.location) tuner_found = False",
"if len(postdataItemSplit) > 1: queryData[postdataItemSplit[0]] = postdataItemSplit[1] if self.path.find('?') !=",
"scan_status in enumerate(self.rmg_station_scans): # the first idle tuner gets it",
"epg2xml.get_epg(self.config, self.location)) elif contentPath == '/channels.m3u': self.do_response(200, 'application/vnd.apple.mpegurl', channels_m3u.get_channels_m3u(self.config, self.location,",
"if (index + 1) != len(station_list): returnJSON = returnJSON +",
"\"-nostats\", \"-hide_banner\", \"-loglevel\", \"warning\", \"pipe:1\"] ffmpeg_proc = subprocess.Popen(ffmpeg_command, stdout=subprocess.PIPE) #",
"base_url + '/watch/' + sid) if (index + 1) !=",
"scan_status in enumerate(self.rmg_station_scans): if scan_status == 'Idle': tuner_list = tuner_list",
"response on purpose stations.refresh_dma_stations_and_channels(self.config, self.locast, self.location) self.hdhr_station_scan = False for",
"returnJSON) elif contentPath == '/lineup.xml': # TODO station_list = stations.get_dma_stations_and_channels(self.config,",
"lib.channels_m3u as channels_m3u from lib.templates import templates # with help",
"1, channelXML)) elif ((contentPath == '/devices/' + self.config['main']['uuid'] + '/scanners')",
"= contentPath.replace('/devices/' + self.config['main']['uuid'] + '/media/', '') channel_no = urllib.parse.unquote(channel_no).replace('id://',",
"queryData[getdataItemSplit[0]] = getdataItemSplit[1] # paths and logic mostly pulled from",
"= self.local_locast.get_station_stream_uri(sid) station_list = stations.get_dma_stations_and_channels(self.config, self.location) tuner_found = False #",
"when trying to write back to the client if e.errno",
"self.location) returnJSON = '' for index, list_key in enumerate(station_list): sid",
"https://github.com/tellytv/telly if (contentPath == '/') and (not self.config['main']['use_old_plex_interface']): self.do_response(200, 'application/xml',",
"elif ((contentPath == '/devices/' + self.config['main']['uuid'] + '/scanners') and (not",
"+ self.config['main']['uuid'] + '/scan') and (not self.config['main']['use_old_plex_interface'])): self.hdhr_station_scan = False",
"of how many tuners we can use at a time",
"in enumerate(self.rmg_station_scans): # the first idle tuner gets it if",
"self.config['main']['reporting_firmware_name'], self.config['main']['tuner_count'], self.config['main']['reporting_firmware_ver'], self.config['main']['uuid'], base_url)) elif contentPath == '/lineup_status.json': if",
"= True self.start() def run(self): httpd = HTTPServer((self.bind_ip, int(self.bind_port)), PlexHttpHandler,",
"= None location = None def do_GET(self): base_url = self.config['main']['plex_accessible_ip']",
"base_url + '/watch/' + sid) returnXML = \"<Lineup>\" + returnXML",
"'application/xml', templates['xmlRmgDeviceIdentity'].format(self.config['main']['uuid'], self.config['main']['reporting_friendly_name'], self.config['main']['reporting_model'], self.config['main']['tuner_count'], base_url, tuner_list)) elif((contentPath == '/devices/'",
"= serverSocket self.daemon = True self.start() def run(self): httpd =",
"self.config['main']['uuid'] + '/channels') and (not self.config['main']['use_old_plex_interface'])): station_list = stations.get_dma_stations_and_channels(self.config, self.location)",
"else: returnJSON = templates['jsonLineupComplete'].replace(\"Antenna\", self.config['main']['tuner_type']) self.do_response(200, 'application/json', returnJSON) elif contentPath",
"'/device.xml'): templateName = 'xmlDiscover' if self.config['main']['use_old_plex_interface']: templateName = 'xmlDiscoverOld' self.do_response(200,",
"None hdhr_station_scan = False rmg_station_scans = [] local_locast = None",
"(not self.config['main']['use_old_plex_interface'])): channel_no = contentPath.replace('/devices/' + self.config['main']['uuid'] + '/media/', '')",
"elif contentPath == '/channels.m3u': self.do_response(200, 'application/vnd.apple.mpegurl', channels_m3u.get_channels_m3u(self.config, self.location, base_url)) elif",
"from https://www.acmesystems.it/python_http # and https://stackoverflow.com/questions/21631799/how-can-i-pass-parameters-to-a-requesthandler class PlexHttpHandler(BaseHTTPRequestHandler): # using class",
"'Idle': tuner_list = tuner_list + templates['xmlRmgTunerIdle'].format(str(index)) elif scan_status == 'Scan':",
"> 1: queryData[getdataItemSplit[0]] = getdataItemSplit[1] if ((contentPath == '/devices/' +",
"\"Idle\" def do_tuning(self, sid): channelUri = self.local_locast.get_station_stream_uri(sid) station_list = stations.get_dma_stations_and_channels(self.config,",
"\"Scan\" self.do_response(200, 'application/xml', templates['xmlRmgScanStatus']) # putting this here after the",
"enumerate(self.rmg_station_scans): if scan_status == 'Idle': self.rmg_station_scans[index] = \"Scan\" self.do_response(200, 'application/xml',",
"location = None def do_GET(self): base_url = self.config['main']['plex_accessible_ip'] + ':'",
"= \"Scan\" self.do_response(200, 'application/xml', templates['xmlRmgScanStatus']) # putting this here after",
"= getdata.split('&') for getdataItem in getdataElements: getdataItemSplit = getdataItem.split('=') if",
"= \"[\" + returnJSON + \"]\" self.do_response(200, 'application/json', returnJSON) elif",
"self.do_response(200, 'application/xml', templates['xmlRmgDeviceDiscover'].format(self.config['main']['uuid'], self.config['main']['reporting_friendly_name'], self.config['main']['reporting_model'], self.config['main']['tuner_count'], base_url)) elif ((contentPath ==",
"# putting this here after the response on purpose stations.refresh_dma_stations_and_channels(self.config,",
"http.server import BaseHTTPRequestHandler, HTTPServer import lib.stations as stations import lib.epg2xml",
"self.config['main']['uuid'] + '/scan') and (not self.config['main']['use_old_plex_interface'])): self.hdhr_station_scan = False for",
"+ 1) != len(station_list): returnJSON = returnJSON + ',' returnJSON",
"# Check we hit a broken pipe when trying to",
"'application/xml', templates['xmlRmgScanStatus']) # putting this here after the response on",
"in use.') self.wfile.write(reply_str.encode('utf-8')) def do_response(self, code, mime, reply_str): self.send_response(code) self.send_header('Content-type',",
"serverSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) serverSocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) serverSocket.bind((config[\"main\"]['bind_ip'], int(config[\"main\"]['bind_port']))) serverSocket.listen(int(config[\"main\"][\"concurrent_listeners\"]))",
"for x in range(int(config['main']['tuner_count'])): tmp_rmg_scans.append('Idle') PlexHttpHandler.rmg_station_scans = tmp_rmg_scans self.socket =",
"will be the channel triplet formatted_xml = templates['xmlRmgTunerStreaming'].format(str(index), scan_status) tuner_list",
"if contentPath == '/lineup.post': if queryData['scan'] == 'start': self.hdhr_station_scan =",
"-1: contentPath = self.path[0:self.path.find('?')] getdata = self.path[(self.path.find('?') + 1):] getdataElements",
"on purpose stations.refresh_dma_stations_and_channels(self.config, self.locast, self.location) self.hdhr_station_scan = False for index,",
"'Scan': self.rmg_station_scans[index] = \"Idle\" else: print(\"Unknown request to \" +",
"self.send_header('Content-type', 'video/mpeg; codecs=\"avc1.4D401E') self.end_headers() ffmpeg_command = [self.config['main']['ffmpeg_path'], \"-i\", channelUri, \"-c:v\",",
"import templates # with help from https://www.acmesystems.it/python_http # and https://stackoverflow.com/questions/21631799/how-can-i-pass-parameters-to-a-requesthandler",
"formatted_xml self.do_response(200, 'application/xml', templates['xmlRmgDeviceIdentity'].format(self.config['main']['uuid'], self.config['main']['reporting_friendly_name'], self.config['main']['reporting_model'], self.config['main']['tuner_count'], base_url, tuner_list)) elif((contentPath",
"PlexHttpHandler(BaseHTTPRequestHandler): # using class variables since this should only be",
"getdata = self.path[(self.path.find('?') + 1):] getdataElements = getdata.split('&') for getdataItem",
"'')) elif ((contentPath.startswith('/devices/' + self.config['main']['uuid'] + '/media/')) and (not self.config['main']['use_old_plex_interface'])):",
"== '/lineup_status.json': if self.hdhr_station_scan: returnJSON = templates['jsonLineupStatus'] else: returnJSON =",
"False) httpd.socket = self.socket httpd.server_bind = self.server_close = lambda self:",
"[self.config['main']['ffmpeg_path'], \"-i\", channelUri, \"-c:v\", \"copy\", \"-c:a\", \"copy\", \"-f\", \"mpegts\", \"-nostats\",",
"with help from https://www.acmesystems.it/python_http # and https://stackoverflow.com/questions/21631799/how-can-i-pass-parameters-to-a-requesthandler class PlexHttpHandler(BaseHTTPRequestHandler): #",
"else: raise videoData = ffmpeg_proc.stdout.read(int(self.config['main']['bytes_per_read'])) # Send SIGTERM to shutdown",
"'application/json', returnJSON) elif contentPath == '/lineup.xml': # TODO station_list =",
"it if scan_status == 'Idle': self.rmg_station_scans[index] = station_list[sid]['channel'] tuner_found =",
"'application/json') elif ((contentPath == '/devices/' + self.config['main']['uuid']) and (not self.config['main']['use_old_plex_interface'])):",
"= [] for x in range(int(config['main']['tuner_count'])): tmp_rmg_scans.append('Idle') PlexHttpHandler.rmg_station_scans = tmp_rmg_scans",
"= self.socket httpd.server_bind = self.server_close = lambda self: None httpd.serve_forever()",
"templates['jsonLineupComplete'].replace(\"Antenna\", self.config['main']['tuner_type']) self.do_response(200, 'application/json', returnJSON) elif contentPath == '/lineup.json': #",
"= None def do_GET(self): base_url = self.config['main']['plex_accessible_ip'] + ':' +",
"templates['xmlLineupItem'].format(station_list[sid]['channel'], station_list[sid]['friendlyName'], base_url + '/watch/' + sid) returnXML = \"<Lineup>\"",
"self.location)) elif contentPath == '/channels.m3u': self.do_response(200, 'application/vnd.apple.mpegurl', channels_m3u.get_channels_m3u(self.config, self.location, base_url))",
"== '/debug.json': self.do_response(200, 'application/json') elif ((contentPath == '/devices/' + self.config['main']['uuid'])",
"'/channels') and (not self.config['main']['use_old_plex_interface'])): station_list = stations.get_dma_stations_and_channels(self.config, self.location) channelXML =",
"or (contentPath == '/device.xml'): templateName = 'xmlDiscover' if self.config['main']['use_old_plex_interface']: templateName",
"+ sid) returnXML = \"<Lineup>\" + returnXML + \"</Lineup>\" self.do_response(200,",
"= returnXML + templates['xmlLineupItem'].format(station_list[sid]['channel'], station_list[sid]['friendlyName'], base_url + '/watch/' + sid)",
"PlexHttpHandler.rmg_station_scans = tmp_rmg_scans self.socket = serverSocket self.daemon = True self.start()",
"== '/lineup.xml': # TODO station_list = stations.get_dma_stations_and_channels(self.config, self.location) returnXML =",
"+ tmpXML self.do_response(200, 'application/xml', templates['xmlRmgDeviceChannels'].format(index + 1, channelXML)) elif ((contentPath",
"= self.path queryData = {} if self.path.find('?') != -1: contentPath",
"+ ' is not a valid scan command')) elif ((contentPath.startswith('/devices/discover')",
"'')) elif contentPath.startswith('/auto/v'): self.do_tuning(contentPath.replace('/auto/v', '')) elif ((contentPath.startswith('/devices/' + self.config['main']['uuid'] +",
"getdataItem.split('=') if len(getdataItemSplit) > 1: queryData[getdataItemSplit[0]] = getdataItemSplit[1] if contentPath",
"'/devices/' + self.config['main']['uuid'] + '/channels') and (not self.config['main']['use_old_plex_interface'])): station_list =",
"purpose stations.refresh_dma_stations_and_channels(self.config, self.locast, self.location) self.hdhr_station_scan = False for index, scan_status",
"getdataItem in getdataElements: getdataItemSplit = getdataItem.split('=') if len(getdataItemSplit) > 1:",
"'application/vnd.apple.mpegurl', channels_m3u.get_channels_m3u(self.config, self.location, base_url)) elif contentPath == '/debug.json': self.do_response(200, 'application/json')",
"if len(getdataItemSplit) > 1: queryData[getdataItemSplit[0]] = getdataItemSplit[1] if contentPath ==",
"putting this here after the response on purpose stations.refresh_dma_stations_and_channels(self.config, self.local_locast,",
"self.do_response(200, 'application/xml', templates['xmlRmgScanProviders'].format(self.location['city'])) else: print(\"Unknown request to \" + contentPath)",
"= ffmpeg_proc.stdout.read(int(self.config['main']['bytes_per_read'])) while True: if not videoData: break else: #",
"self.location) for sid in station_list: if station_list[sid]['channel'] == channel_no: break",
"+ '/watch/' + sid) returnXML = \"<Lineup>\" + returnXML +",
"returnXML = \"<Lineup>\" + returnXML + \"</Lineup>\" self.do_response(200, 'application/xml', returnXML)",
"stations.refresh_dma_stations_and_channels(self.config, self.locast, self.location) self.hdhr_station_scan = False for index, scan_status in",
"in enumerate(self.rmg_station_scans): if scan_status == 'Scan': self.rmg_station_scans[index] = \"Idle\" def",
"self.location) tuner_found = False # keep track of how many",
"import pathlib from io import StringIO from http.server import BaseHTTPRequestHandler,",
"postdata = self.rfile.read(int(self.headers.get('Content-Length'))) postdataElements = postdata.split('&') for postdataItem in postdataElements:",
"from http.server import BaseHTTPRequestHandler, HTTPServer import lib.stations as stations import",
"print(\"Unknown scan command \" + queryData['scan']) self.do_response(400, 'text/html', templates['htmlError'].format(queryData['scan'] +",
"keep grabbing it videoData = ffmpeg_proc.stdout.read(int(self.config['main']['bytes_per_read'])) while True: if not",
"__init__(self, serverSocket, config, locast_service, location): threading.Thread.__init__(self) PlexHttpHandler.config = config self.bind_ip",
"# and https://stackoverflow.com/questions/21631799/how-can-i-pass-parameters-to-a-requesthandler class PlexHttpHandler(BaseHTTPRequestHandler): # using class variables since",
"e: # Check we hit a broken pipe when trying",
"+ 1, channelXML)) elif ((contentPath == '/devices/' + self.config['main']['uuid'] +",
"Closed\") self.rmg_station_scans[index] = 'Idle' else: self.send_response(400, 'All tuners already in",
"the response on purpose stations.refresh_dma_stations_and_channels(self.config, self.locast, self.location) self.hdhr_station_scan = False",
"not videoData: break else: # from https://stackoverflow.com/questions/9932332 try: self.wfile.write(videoData) time.sleep(0.1)",
"= True break if tuner_found: self.send_response(200) self.send_header('Content-type', 'video/mpeg; codecs=\"avc1.4D401E') self.end_headers()",
"contentPath.startswith('/watch'): self.do_tuning(contentPath.replace('/watch/', '')) elif contentPath.startswith('/auto/v'): self.do_tuning(contentPath.replace('/auto/v', '')) elif ((contentPath.startswith('/devices/' +",
"should only be set once config = None hdhr_station_scan =",
"scan_status == 'Scan': tuner_list = tuner_list + templates['xmlRmgTunerScanning'].format(str(index)) else: #",
"= postdata.split('&') for postdataItem in postdataElements: postdataItemSplit = postdataItem.split('=') if",
"stations.get_dma_stations_and_channels(self.config, self.location) returnXML = '' for list_key in station_list: sid",
"index, scan_status in enumerate(self.rmg_station_scans): if scan_status == 'Idle': tuner_list =",
"class PlexHttpServer(threading.Thread): def __init__(self, serverSocket, config, locast_service, location): threading.Thread.__init__(self) PlexHttpHandler.config",
"'') station_list = stations.get_dma_stations_and_channels(self.config, self.location) for sid in station_list: if",
"if self.hdhr_station_scan: returnJSON = templates['jsonLineupStatus'] else: returnJSON = templates['jsonLineupComplete'].replace(\"Antenna\", self.config['main']['tuner_type'])",
"+ contentPath) return def do_DELETE(self): base_url = self.config['main']['plex_accessible_ip'] + ':'",
"postdataElements = postdata.split('&') for postdataItem in postdataElements: postdataItemSplit = postdataItem.split('=')",
"self.send_response(200) self.send_header('Content-type', 'video/mpeg; codecs=\"avc1.4D401E') self.end_headers() ffmpeg_command = [self.config['main']['ffmpeg_path'], \"-i\", channelUri,",
"tmpXML self.do_response(200, 'application/xml', templates['xmlRmgDeviceChannels'].format(index + 1, channelXML)) elif ((contentPath ==",
"not a valid scan command')) elif ((contentPath.startswith('/devices/discover') or contentPath.startswith('/devices/probe')) and",
"if ((contentPath == '/devices/' + self.config['main']['uuid'] + '/scan') and (not",
"getdataElements: getdataItemSplit = getdataItem.split('=') if len(getdataItemSplit) > 1: queryData[getdataItemSplit[0]] =",
"self.send_response(400, 'All tuners already in use.') self.send_header('Content-type', 'text/html') self.end_headers() reply_str",
"streaming, and the value will be the channel triplet formatted_xml",
"print(\"Now listening for requests.\") for i in range(int(config[\"main\"][\"concurrent_listeners\"])): PlexHttpServer(serverSocket, config,",
"(not self.config['main']['use_old_plex_interface'])): station_list = stations.get_dma_stations_and_channels(self.config, self.location) channelXML = '' for",
"track of how many tuners we can use at a",
"lib.stations as stations import lib.epg2xml as epg2xml import lib.channels_m3u as",
"serverSocket.listen(int(config[\"main\"][\"concurrent_listeners\"])) print(\"Now listening for requests.\") for i in range(int(config[\"main\"][\"concurrent_listeners\"])): PlexHttpServer(serverSocket,",
"Send SIGTERM to shutdown ffmpeg ffmpeg_proc.terminate() try: # ffmpeg writes",
"contentPath) self.do_response(501, 'text/html', templates['htmlError'].format('501 - Not Implemented')) return def do_POST(self):",
"self.do_response(200, 'application/xml', templates['xmlRmgDeviceChannels'].format(index + 1, channelXML)) elif ((contentPath == '/devices/'",
"tuners already in use.') self.send_header('Content-type', 'text/html') self.end_headers() reply_str = templates['htmlError'].format('All",
"self.send_header('Content-type', mime) self.end_headers() if reply_str: self.wfile.write(reply_str.encode('utf-8')) # mostly from https://github.com/ZeWaren/python-upnp-ssdp-example",
"getdataItem.split('=') if len(getdataItemSplit) > 1: queryData[getdataItemSplit[0]] = getdataItemSplit[1] if ((contentPath",
"class PlexHttpHandler(BaseHTTPRequestHandler): # using class variables since this should only",
"'/channels.m3u': self.do_response(200, 'application/vnd.apple.mpegurl', channels_m3u.get_channels_m3u(self.config, self.location, base_url)) elif contentPath == '/debug.json':",
"we can use at a time for index, scan_status in",
"\"pipe:1\"] ffmpeg_proc = subprocess.Popen(ffmpeg_command, stdout=subprocess.PIPE) # get initial videodata. if",
"self.config['main']['reporting_model'], self.config['main']['uuid'], base_url)) elif contentPath == '/discover.json': self.do_response(200, 'application/json', templates['jsonDiscover'].format(self.config['main']['reporting_friendly_name'],",
"+ sid) if (index + 1) != len(station_list): returnJSON =",
"self.config['main']['uuid'], base_url)) elif contentPath == '/lineup_status.json': if self.hdhr_station_scan: returnJSON =",
"channelXML = channelXML + tmpXML self.do_response(200, 'application/xml', templates['xmlRmgDeviceChannels'].format(index + 1,",
"self.rmg_station_scans[index] = \"Idle\" def do_tuning(self, sid): channelUri = self.local_locast.get_station_stream_uri(sid) station_list",
"self.wfile.write(videoData) time.sleep(0.1) except IOError as e: # Check we hit",
"in [errno.EPIPE, errno.ECONNABORTED, errno.ECONNRESET, errno.ECONNREFUSED]: break else: raise videoData =",
"scan_status == 'Idle': self.rmg_station_scans[index] = \"Scan\" self.do_response(200, 'application/xml', templates['xmlRmgScanStatus']) #",
"this here after the response on purpose stations.refresh_dma_stations_and_channels(self.config, self.locast, self.location)",
"station_list = stations.get_dma_stations_and_channels(self.config, self.location) tuner_found = False # keep track",
"\" + queryData['scan']) self.do_response(400, 'text/html', templates['htmlError'].format(queryData['scan'] + ' is not",
"= tuner_list + templates['xmlRmgTunerIdle'].format(str(index)) elif scan_status == 'Scan': tuner_list =",
"HTTPServer((self.bind_ip, int(self.bind_port)), PlexHttpHandler, False) httpd.socket = self.socket httpd.server_bind = self.server_close",
"= stations.get_dma_stations_and_channels(self.config, self.location) for sid in station_list: if station_list[sid]['channel'] ==",
"self.config['main']['use_old_plex_interface'])): station_list = stations.get_dma_stations_and_channels(self.config, self.location) channelXML = '' for index,",
"self.rmg_station_scans[index] = \"Scan\" self.do_response(200, 'application/xml', templates['xmlRmgScanStatus']) # putting this here",
"= templates['jsonLineupStatus'] else: returnJSON = templates['jsonLineupComplete'].replace(\"Antenna\", self.config['main']['tuner_type']) self.do_response(200, 'application/json', returnJSON)",
"station scans tmp_rmg_scans = [] for x in range(int(config['main']['tuner_count'])): tmp_rmg_scans.append('Idle')",
"+ templates['xmlRmgTunerIdle'].format(str(index)) elif scan_status == 'Scan': tuner_list = tuner_list +",
"socket.socket(socket.AF_INET, socket.SOCK_STREAM) serverSocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) serverSocket.bind((config[\"main\"]['bind_ip'], int(config[\"main\"]['bind_port']))) serverSocket.listen(int(config[\"main\"][\"concurrent_listeners\"])) print(\"Now listening",
"PlexHttpHandler.location = location # init station scans tmp_rmg_scans = []",
"time import errno import socket import urllib import pathlib from",
"after the response on purpose stations.refresh_dma_stations_and_channels(self.config, self.local_locast, self.location) self.hdhr_station_scan =",
"elif (contentPath == '/') or (contentPath == '/device.xml'): templateName =",
"= self.config['main']['plex_accessible_ip'] + ':' + self.config['main']['plex_accessible_port'] contentPath = self.path queryData",
"\"-c:v\", \"copy\", \"-c:a\", \"copy\", \"-f\", \"mpegts\", \"-nostats\", \"-hide_banner\", \"-loglevel\", \"warning\",",
"templates['xmlRmgScanProviders'].format(self.location['city'])) else: print(\"Unknown request to \" + contentPath) self.do_response(501, 'text/html',",
"'/watch/' + sid) returnXML = \"<Lineup>\" + returnXML + \"</Lineup>\"",
"stations.get_dma_stations_and_channels(self.config, self.location) channelXML = '' for index, list_key in enumerate(station_list):",
"self.config['main']['plex_accessible_ip'] + ':' + self.config['main']['plex_accessible_port'] contentPath = self.path queryData =",
"threading import time import errno import socket import urllib import",
"= getdataItem.split('=') if len(getdataItemSplit) > 1: queryData[getdataItemSplit[0]] = getdataItemSplit[1] #",
"= channelXML + tmpXML self.do_response(200, 'application/xml', templates['xmlRmgDeviceChannels'].format(index + 1, channelXML))",
"= returnJSON + templates['jsonLineupItem'].format(station_list[sid]['channel'], station_list[sid]['friendlyName'], base_url + '/watch/' + sid)",
"try: self.wfile.write(videoData) time.sleep(0.1) except IOError as e: # Check we",
"else: self.send_response(400, 'All tuners already in use.') self.send_header('Content-type', 'text/html') self.end_headers()",
"use.') self.send_header('Content-type', 'text/html') self.end_headers() reply_str = templates['htmlError'].format('All tuners already in",
"self.config['main']['use_old_plex_interface'])): self.do_response(200, 'application/xml', templates['xmlRmgScanProviders'].format(self.location['city'])) else: print(\"Unknown request to \" +",
"if self.headers.get('Content-Length') != '0': postdata = self.rfile.read(int(self.headers.get('Content-Length'))) postdataElements = postdata.split('&')",
"= self.rfile.read(int(self.headers.get('Content-Length'))) postdataElements = postdata.split('&') for postdataItem in postdataElements: postdataItemSplit",
"returnXML = returnXML + templates['xmlLineupItem'].format(station_list[sid]['channel'], station_list[sid]['friendlyName'], base_url + '/watch/' +",
"enumerate(station_list): sid = str(list_key) returnJSON = returnJSON + templates['jsonLineupItem'].format(station_list[sid]['channel'], station_list[sid]['friendlyName'],",
"getdataItemSplit[1] if contentPath == '/lineup.post': if queryData['scan'] == 'start': self.hdhr_station_scan",
"get initial videodata. if that works, then keep grabbing it",
"and logic mostly pulled from telly:routes.go: https://github.com/tellytv/telly if (contentPath ==",
"= \"Idle\" def do_tuning(self, sid): channelUri = self.local_locast.get_station_stream_uri(sid) station_list =",
"= self.server_close = lambda self: None httpd.serve_forever() def start(config, locast,",
"= \"Scan\" self.do_response(200, 'text/html') # putting this here after the",
"templates['htmlError'].format('All tuners already in use.') self.wfile.write(reply_str.encode('utf-8')) def do_response(self, code, mime,",
"= tuner_list + templates['xmlRmgTunerScanning'].format(str(index)) else: # otherwise, we're streaming, and",
"+ '/watch/' + sid) if (index + 1) != len(station_list):",
"((contentPath == '/devices/' + self.config['main']['uuid'] + '/scanners') and (not self.config['main']['use_old_plex_interface'])):",
"enumerate(self.rmg_station_scans): if scan_status == 'Scan': self.rmg_station_scans[index] = \"Idle\" def do_tuning(self,",
"(not self.config['main']['use_old_plex_interface'])): self.hdhr_station_scan = False for index, scan_status in enumerate(self.rmg_station_scans):",
"https://www.acmesystems.it/python_http # and https://stackoverflow.com/questions/21631799/how-can-i-pass-parameters-to-a-requesthandler class PlexHttpHandler(BaseHTTPRequestHandler): # using class variables",
"if len(getdataItemSplit) > 1: queryData[getdataItemSplit[0]] = getdataItemSplit[1] # paths and",
"+ '/scan') and (not self.config['main']['use_old_plex_interface'])): self.hdhr_station_scan = False for index,",
"== '/devices/' + self.config['main']['uuid'] + '/channels') and (not self.config['main']['use_old_plex_interface'])): station_list",
"config[\"main\"][\"bind_ip\"] self.bind_port = config[\"main\"][\"bind_port\"] PlexHttpHandler.stations = stations PlexHttpHandler.local_locast = locast_service",
"= config[\"main\"][\"bind_ip\"] self.bind_port = config[\"main\"][\"bind_port\"] PlexHttpHandler.stations = stations PlexHttpHandler.local_locast =",
"= self.path queryData = {} if self.headers.get('Content-Length') != '0': postdata",
"# the first idle tuner gets it if scan_status ==",
"enumerate(self.rmg_station_scans): if scan_status == 'Idle': tuner_list = tuner_list + templates['xmlRmgTunerIdle'].format(str(index))",
"((contentPath.startswith('/devices/' + self.config['main']['uuid'] + '/media/')) and (not self.config['main']['use_old_plex_interface'])): channel_no =",
"list_key in enumerate(station_list): sid = str(list_key) tmpXML = templates['xmlRmgDeviceChannelItem'].format(station_list[sid]['channel'], station_list[sid]['friendlyName'])",
"!= -1: contentPath = self.path[0:self.path.find('?')] getdata = self.path[(self.path.find('?') + 1):]",
"TODO station_list = stations.get_dma_stations_and_channels(self.config, self.location) returnJSON = '' for index,",
"ValueError: print(\"Connection Closed\") self.rmg_station_scans[index] = 'Idle' else: self.send_response(400, 'All tuners",
"returnJSON = \"[\" + returnJSON + \"]\" self.do_response(200, 'application/json', returnJSON)",
"base_url, tuner_list)) elif((contentPath == '/devices/' + self.config['main']['uuid'] + '/channels') and",
"except ValueError: print(\"Connection Closed\") self.rmg_station_scans[index] = 'Idle' else: self.send_response(400, 'All",
"ffmpeg_command = [self.config['main']['ffmpeg_path'], \"-i\", channelUri, \"-c:v\", \"copy\", \"-c:a\", \"copy\", \"-f\",",
"self.path[(self.path.find('?') + 1):] getdataElements = getdata.split('&') for getdataItem in getdataElements:",
"initial videodata. if that works, then keep grabbing it videoData",
"contentPath = self.path[0:self.path.find('?')] getdata = self.path[(self.path.find('?') + 1):] getdataElements =",
"self.config['main']['uuid'] + '/media/')) and (not self.config['main']['use_old_plex_interface'])): channel_no = contentPath.replace('/devices/' +",
"str(list_key) returnXML = returnXML + templates['xmlLineupItem'].format(station_list[sid]['channel'], station_list[sid]['friendlyName'], base_url + '/watch/'",
"int(self.bind_port)), PlexHttpHandler, False) httpd.socket = self.socket httpd.server_bind = self.server_close =",
"= \"Idle\" else: print(\"Unknown request to \" + contentPath) return",
"= postdataItemSplit[1] if self.path.find('?') != -1: contentPath = self.path[0:self.path.find('?')] getdata",
"= templates['xmlRmgTunerStreaming'].format(str(index), scan_status) tuner_list = tuner_list + formatted_xml self.do_response(200, 'application/xml',",
"== '/') and (not self.config['main']['use_old_plex_interface']): self.do_response(200, 'application/xml', templates['xmlRmgIdentification'].format(self.config['main']['reporting_friendly_name'])) elif (contentPath",
"local_locast = None location = None def do_GET(self): base_url =",
"self.do_response(200, 'application/xml', templates[templateName].format(self.config['main']['reporting_friendly_name'], self.config['main']['reporting_model'], self.config['main']['uuid'], base_url)) elif contentPath == '/discover.json':",
"index, scan_status in enumerate(self.rmg_station_scans): # the first idle tuner gets",
"== '/devices/' + self.config['main']['uuid'] + '/scanners') and (not self.config['main']['use_old_plex_interface'])): self.do_response(200,",
"'start': self.hdhr_station_scan = True for index, scan_status in enumerate(self.rmg_station_scans): if",
"postdataItemSplit = postdataItem.split('=') if len(postdataItemSplit) > 1: queryData[postdataItemSplit[0]] = postdataItemSplit[1]",
"urllib.parse.unquote(channel_no).replace('id://', '').replace('/', '') station_list = stations.get_dma_stations_and_channels(self.config, self.location) for sid in",
"= \"\" for index, scan_status in enumerate(self.rmg_station_scans): if scan_status ==",
"else: # otherwise, we're streaming, and the value will be",
"be set once config = None hdhr_station_scan = False rmg_station_scans",
"request to \" + contentPath) return def do_DELETE(self): base_url =",
"in use.') self.send_header('Content-type', 'text/html') self.end_headers() reply_str = templates['htmlError'].format('All tuners already",
"self.end_headers() if reply_str: self.wfile.write(reply_str.encode('utf-8')) # mostly from https://github.com/ZeWaren/python-upnp-ssdp-example # and",
"scan_status in enumerate(self.rmg_station_scans): if scan_status == 'Scan': self.rmg_station_scans[index] = \"Idle\"",
"templates['jsonDiscover'].format(self.config['main']['reporting_friendly_name'], self.config['main']['reporting_model'], self.config['main']['reporting_firmware_name'], self.config['main']['tuner_count'], self.config['main']['reporting_firmware_ver'], self.config['main']['uuid'], base_url)) elif contentPath ==",
"out to stderr after it terminates, # need to read",
"import BaseHTTPRequestHandler, HTTPServer import lib.stations as stations import lib.epg2xml as",
"= returnJSON + ',' returnJSON = \"[\" + returnJSON +",
"request to \" + contentPath) self.do_response(501, 'text/html', templates['htmlError'].format('501 - Not",
"'application/json', returnJSON) elif contentPath == '/lineup.json': # TODO station_list =",
"elif ((contentPath.startswith('/devices/' + self.config['main']['uuid'] + '/media/')) and (not self.config['main']['use_old_plex_interface'])): channel_no",
"contentPath == '/lineup.json': # TODO station_list = stations.get_dma_stations_and_channels(self.config, self.location) returnJSON",
"it videoData = ffmpeg_proc.stdout.read(int(self.config['main']['bytes_per_read'])) while True: if not videoData: break",
"== 'Scan': self.rmg_station_scans[index] = \"Idle\" elif queryData['scan'] == 'abort': self.do_response(200,",
"scan command \" + queryData['scan']) self.do_response(400, 'text/html', templates['htmlError'].format(queryData['scan'] + '",
"stations.get_dma_stations_and_channels(self.config, self.location) tuner_found = False # keep track of how",
"station_list = stations.get_dma_stations_and_channels(self.config, self.location) returnXML = '' for list_key in",
"self.do_response(501, 'text/html', templates['htmlError'].format('501 - Not Implemented')) return def do_POST(self): base_url",
"returnJSON) elif contentPath == '/lineup.json': # TODO station_list = stations.get_dma_stations_and_channels(self.config,",
"queryData['scan'] == 'start': self.hdhr_station_scan = True for index, scan_status in",
"this should only be set once config = None hdhr_station_scan",
"TODO station_list = stations.get_dma_stations_and_channels(self.config, self.location) returnXML = '' for list_key",
"station_list[sid]['channel'] tuner_found = True break if tuner_found: self.send_response(200) self.send_header('Content-type', 'video/mpeg;",
"import urllib import pathlib from io import StringIO from http.server",
"len(getdataItemSplit) > 1: queryData[getdataItemSplit[0]] = getdataItemSplit[1] if ((contentPath == '/devices/'",
"run(self): httpd = HTTPServer((self.bind_ip, int(self.bind_port)), PlexHttpHandler, False) httpd.socket = self.socket",
"client if e.errno in [errno.EPIPE, errno.ECONNABORTED, errno.ECONNRESET, errno.ECONNREFUSED]: break else:",
"returnXML) elif contentPath.startswith('/watch'): self.do_tuning(contentPath.replace('/watch/', '')) elif contentPath.startswith('/auto/v'): self.do_tuning(contentPath.replace('/auto/v', '')) elif",
"+ self.config['main']['uuid'] + '/media/', '') channel_no = urllib.parse.unquote(channel_no).replace('id://', '').replace('/', '')",
"self.do_response(200, 'application/vnd.apple.mpegurl', channels_m3u.get_channels_m3u(self.config, self.location, base_url)) elif contentPath == '/debug.json': self.do_response(200,",
"is not a valid scan command')) elif ((contentPath.startswith('/devices/discover') or contentPath.startswith('/devices/probe'))",
"\"-c:a\", \"copy\", \"-f\", \"mpegts\", \"-nostats\", \"-hide_banner\", \"-loglevel\", \"warning\", \"pipe:1\"] ffmpeg_proc",
"class variables since this should only be set once config",
"'/debug.json': self.do_response(200, 'application/json') elif ((contentPath == '/devices/' + self.config['main']['uuid']) and",
"= False for index, scan_status in enumerate(self.rmg_station_scans): if scan_status ==",
"self.headers.get('Content-Length') != '0': postdata = self.rfile.read(int(self.headers.get('Content-Length'))) postdataElements = postdata.split('&') for",
"queryData = {} if self.path.find('?') != -1: contentPath = self.path[0:self.path.find('?')]",
"if (contentPath == '/') and (not self.config['main']['use_old_plex_interface']): self.do_response(200, 'application/xml', templates['xmlRmgIdentification'].format(self.config['main']['reporting_friendly_name']))",
"getdataElements = getdata.split('&') for getdataItem in getdataElements: getdataItemSplit = getdataItem.split('=')",
"of data out to stderr after it terminates, # need",
"\"<Lineup>\" + returnXML + \"</Lineup>\" self.do_response(200, 'application/xml', returnXML) elif contentPath.startswith('/watch'):",
"else: print(\"Unknown request to \" + contentPath) return def do_DELETE(self):",
"(not self.config['main']['use_old_plex_interface'])): self.do_response(200, 'application/xml', templates['xmlRmgScanProviders'].format(self.location['city'])) else: print(\"Unknown request to \"",
"1: queryData[getdataItemSplit[0]] = getdataItemSplit[1] # paths and logic mostly pulled",
"str(list_key) returnJSON = returnJSON + templates['jsonLineupItem'].format(station_list[sid]['channel'], station_list[sid]['friendlyName'], base_url + '/watch/'",
"list_key in station_list: sid = str(list_key) returnXML = returnXML +",
"sid): channelUri = self.local_locast.get_station_stream_uri(sid) station_list = stations.get_dma_stations_and_channels(self.config, self.location) tuner_found =",
"scans tmp_rmg_scans = [] for x in range(int(config['main']['tuner_count'])): tmp_rmg_scans.append('Idle') PlexHttpHandler.rmg_station_scans",
"zombie process. ffmpeg_proc.communicate() except ValueError: print(\"Connection Closed\") self.rmg_station_scans[index] = 'Idle'",
"if tuner_found: self.send_response(200) self.send_header('Content-type', 'video/mpeg; codecs=\"avc1.4D401E') self.end_headers() ffmpeg_command = [self.config['main']['ffmpeg_path'],",
"from https://github.com/ZeWaren/python-upnp-ssdp-example # and https://stackoverflow.com/questions/46210672/python-2-7-streaming-http-server-supporting-multiple-connections-on-one-port class PlexHttpServer(threading.Thread): def __init__(self, serverSocket,",
"self.config['main']['reporting_model'], self.config['main']['tuner_count'], base_url)) elif ((contentPath == '/devices/' + self.config['main']['uuid'] +",
"tuner_list = tuner_list + templates['xmlRmgTunerIdle'].format(str(index)) elif scan_status == 'Scan': tuner_list",
"self.config['main']['uuid']) and (not self.config['main']['use_old_plex_interface'])): tuner_list = \"\" for index, scan_status",
"as epg2xml import lib.channels_m3u as channels_m3u from lib.templates import templates",
"the response on purpose stations.refresh_dma_stations_and_channels(self.config, self.local_locast, self.location) self.hdhr_station_scan = False",
"a zombie process. ffmpeg_proc.communicate() except ValueError: print(\"Connection Closed\") self.rmg_station_scans[index] =",
"'/lineup.xml': # TODO station_list = stations.get_dma_stations_and_channels(self.config, self.location) returnXML = ''",
"{} if self.path.find('?') != -1: contentPath = self.path[0:self.path.find('?')] getdata =",
"= {} if self.path.find('?') != -1: contentPath = self.path[0:self.path.find('?')] getdata",
"templates['xmlRmgTunerScanning'].format(str(index)) else: # otherwise, we're streaming, and the value will",
"'text/html', templates['htmlError'].format('501 - Not Implemented')) return def do_POST(self): base_url =",
"subprocess.Popen(ffmpeg_command, stdout=subprocess.PIPE) # get initial videodata. if that works, then",
"self.hdhr_station_scan: returnJSON = templates['jsonLineupStatus'] else: returnJSON = templates['jsonLineupComplete'].replace(\"Antenna\", self.config['main']['tuner_type']) self.do_response(200,",
"[] local_locast = None location = None def do_GET(self): base_url",
"hit a broken pipe when trying to write back to",
"def run(self): httpd = HTTPServer((self.bind_ip, int(self.bind_port)), PlexHttpHandler, False) httpd.socket =",
"if station_list[sid]['channel'] == channel_no: break self.do_tuning(sid) elif contentPath == '/xmltv.xml':",
"self.config['main']['uuid'] + '/media/', '') channel_no = urllib.parse.unquote(channel_no).replace('id://', '').replace('/', '') station_list",
"purpose stations.refresh_dma_stations_and_channels(self.config, self.local_locast, self.location) self.hdhr_station_scan = False for index, scan_status",
"+ templates['xmlLineupItem'].format(station_list[sid]['channel'], station_list[sid]['friendlyName'], base_url + '/watch/' + sid) returnXML =",
"serverSocket.bind((config[\"main\"]['bind_ip'], int(config[\"main\"]['bind_port']))) serverSocket.listen(int(config[\"main\"][\"concurrent_listeners\"])) print(\"Now listening for requests.\") for i in",
"self.location) returnXML = '' for list_key in station_list: sid =",
"to \" + contentPath) self.do_response(501, 'text/html', templates['htmlError'].format('501 - Not Implemented'))",
"self.config['main']['use_old_plex_interface'])): tuner_list = \"\" for index, scan_status in enumerate(self.rmg_station_scans): if",
"+ self.config['main']['uuid'] + '/scanners') and (not self.config['main']['use_old_plex_interface'])): self.do_response(200, 'application/xml', templates['xmlRmgScanProviders'].format(self.location['city']))",
"+ contentPath) self.do_response(501, 'text/html', templates['htmlError'].format('501 - Not Implemented')) return def",
"channelUri, \"-c:v\", \"copy\", \"-c:a\", \"copy\", \"-f\", \"mpegts\", \"-nostats\", \"-hide_banner\", \"-loglevel\",",
"elif scan_status == 'Scan': tuner_list = tuner_list + templates['xmlRmgTunerScanning'].format(str(index)) else:",
"'application/json', templates['jsonDiscover'].format(self.config['main']['reporting_friendly_name'], self.config['main']['reporting_model'], self.config['main']['reporting_firmware_name'], self.config['main']['tuner_count'], self.config['main']['reporting_firmware_ver'], self.config['main']['uuid'], base_url)) elif contentPath",
"== '/device.xml'): templateName = 'xmlDiscover' if self.config['main']['use_old_plex_interface']: templateName = 'xmlDiscoverOld'",
"returnJSON + ',' returnJSON = \"[\" + returnJSON + \"]\"",
"= postdataItem.split('=') if len(postdataItemSplit) > 1: queryData[postdataItemSplit[0]] = postdataItemSplit[1] if",
"= '' for list_key in station_list: sid = str(list_key) returnXML",
"base_url)) elif ((contentPath == '/devices/' + self.config['main']['uuid'] + '/scan') and",
"time for index, scan_status in enumerate(self.rmg_station_scans): # the first idle",
"station_list[sid]['friendlyName'], base_url + '/watch/' + sid) returnXML = \"<Lineup>\" +",
"if scan_status == 'Scan': self.rmg_station_scans[index] = \"Idle\" elif queryData['scan'] ==",
"ffmpeg writes a bit of data out to stderr after",
"errno import socket import urllib import pathlib from io import",
"self.config['main']['uuid'] + '/scanners') and (not self.config['main']['use_old_plex_interface'])): self.do_response(200, 'application/xml', templates['xmlRmgScanProviders'].format(self.location['city'])) else:",
"help from https://www.acmesystems.it/python_http # and https://stackoverflow.com/questions/21631799/how-can-i-pass-parameters-to-a-requesthandler class PlexHttpHandler(BaseHTTPRequestHandler): # using",
"base_url)) elif contentPath == '/lineup_status.json': if self.hdhr_station_scan: returnJSON = templates['jsonLineupStatus']",
"elif contentPath.startswith('/watch'): self.do_tuning(contentPath.replace('/watch/', '')) elif contentPath.startswith('/auto/v'): self.do_tuning(contentPath.replace('/auto/v', '')) elif ((contentPath.startswith('/devices/'",
"stations.get_dma_stations_and_channels(self.config, self.location) returnJSON = '' for index, list_key in enumerate(station_list):",
"'xmlDiscover' if self.config['main']['use_old_plex_interface']: templateName = 'xmlDiscoverOld' self.do_response(200, 'application/xml', templates[templateName].format(self.config['main']['reporting_friendly_name'], self.config['main']['reporting_model'],",
"queryData['scan'] == 'abort': self.do_response(200, 'text/html') self.hdhr_station_scan = False for index,",
"import socket import urllib import pathlib from io import StringIO",
"listening for requests.\") for i in range(int(config[\"main\"][\"concurrent_listeners\"])): PlexHttpServer(serverSocket, config, locast,",
"self.config['main']['reporting_friendly_name'], self.config['main']['reporting_model'], self.config['main']['tuner_count'], base_url, tuner_list)) elif((contentPath == '/devices/' + self.config['main']['uuid']",
"https://stackoverflow.com/questions/46210672/python-2-7-streaming-http-server-supporting-multiple-connections-on-one-port class PlexHttpServer(threading.Thread): def __init__(self, serverSocket, config, locast_service, location): threading.Thread.__init__(self)",
"in range(int(config['main']['tuner_count'])): tmp_rmg_scans.append('Idle') PlexHttpHandler.rmg_station_scans = tmp_rmg_scans self.socket = serverSocket self.daemon",
"= None hdhr_station_scan = False rmg_station_scans = [] local_locast =",
"station_list = stations.get_dma_stations_and_channels(self.config, self.location) for sid in station_list: if station_list[sid]['channel']",
"# with help from https://www.acmesystems.it/python_http # and https://stackoverflow.com/questions/21631799/how-can-i-pass-parameters-to-a-requesthandler class PlexHttpHandler(BaseHTTPRequestHandler):",
"self.config['main']['tuner_count'], self.config['main']['reporting_firmware_ver'], self.config['main']['uuid'], base_url)) elif contentPath == '/lineup_status.json': if self.hdhr_station_scan:",
"1: queryData[getdataItemSplit[0]] = getdataItemSplit[1] if ((contentPath == '/devices/' + self.config['main']['uuid']",
"self.config['main']['use_old_plex_interface'])): self.do_response(200, 'application/xml', templates['xmlRmgDeviceDiscover'].format(self.config['main']['uuid'], self.config['main']['reporting_friendly_name'], self.config['main']['reporting_model'], self.config['main']['tuner_count'], base_url)) elif ((contentPath",
"mime, reply_str): self.send_response(code) self.send_header('Content-type', mime) self.end_headers() if reply_str: self.wfile.write(reply_str.encode('utf-8')) #",
"after the response on purpose stations.refresh_dma_stations_and_channels(self.config, self.locast, self.location) self.hdhr_station_scan =",
"returnXML + \"</Lineup>\" self.do_response(200, 'application/xml', returnXML) elif contentPath.startswith('/watch'): self.do_tuning(contentPath.replace('/watch/', ''))",
"\"Idle\" else: print(\"Unknown request to \" + contentPath) return def",
"self.do_response(200, 'application/json', returnJSON) elif contentPath == '/lineup.json': # TODO station_list",
"elif ((contentPath == '/devices/' + self.config['main']['uuid']) and (not self.config['main']['use_old_plex_interface'])): tuner_list",
"== 'Idle': tuner_list = tuner_list + templates['xmlRmgTunerIdle'].format(str(index)) elif scan_status ==",
"contentPath == '/lineup_status.json': if self.hdhr_station_scan: returnJSON = templates['jsonLineupStatus'] else: returnJSON",
"None location = None def do_GET(self): base_url = self.config['main']['plex_accessible_ip'] +",
"= \"Idle\" elif queryData['scan'] == 'abort': self.do_response(200, 'text/html') self.hdhr_station_scan =",
"if e.errno in [errno.EPIPE, errno.ECONNABORTED, errno.ECONNRESET, errno.ECONNREFUSED]: break else: raise",
"hanging data to prevent a zombie process. ffmpeg_proc.communicate() except ValueError:",
"returnXML = '' for list_key in station_list: sid = str(list_key)",
"to read any hanging data to prevent a zombie process.",
"== '/discover.json': self.do_response(200, 'application/json', templates['jsonDiscover'].format(self.config['main']['reporting_friendly_name'], self.config['main']['reporting_model'], self.config['main']['reporting_firmware_name'], self.config['main']['tuner_count'], self.config['main']['reporting_firmware_ver'], self.config['main']['uuid'],",
"self.config['main']['use_old_plex_interface'])): self.hdhr_station_scan = False for index, scan_status in enumerate(self.rmg_station_scans): if",
"# init station scans tmp_rmg_scans = [] for x in",
"serverSocket, config, locast_service, location): threading.Thread.__init__(self) PlexHttpHandler.config = config self.bind_ip =",
"== '/devices/' + self.config['main']['uuid']) and (not self.config['main']['use_old_plex_interface'])): tuner_list = \"\"",
"else: # from https://stackoverflow.com/questions/9932332 try: self.wfile.write(videoData) time.sleep(0.1) except IOError as",
"channel_no: break self.do_tuning(sid) elif contentPath == '/xmltv.xml': self.do_response(200, 'application/xml', epg2xml.get_epg(self.config,",
"\"]\" self.do_response(200, 'application/json', returnJSON) elif contentPath == '/lineup.xml': # TODO",
"IOError as e: # Check we hit a broken pipe",
"'') channel_no = urllib.parse.unquote(channel_no).replace('id://', '').replace('/', '') station_list = stations.get_dma_stations_and_channels(self.config, self.location)",
"= str(list_key) returnXML = returnXML + templates['xmlLineupItem'].format(station_list[sid]['channel'], station_list[sid]['friendlyName'], base_url +",
"tuner_list + formatted_xml self.do_response(200, 'application/xml', templates['xmlRmgDeviceIdentity'].format(self.config['main']['uuid'], self.config['main']['reporting_friendly_name'], self.config['main']['reporting_model'], self.config['main']['tuner_count'], base_url,",
"templates['xmlRmgDeviceChannels'].format(index + 1, channelXML)) elif ((contentPath == '/devices/' + self.config['main']['uuid']",
"import time import errno import socket import urllib import pathlib",
"the value will be the channel triplet formatted_xml = templates['xmlRmgTunerStreaming'].format(str(index),",
"queryData[postdataItemSplit[0]] = postdataItemSplit[1] if self.path.find('?') != -1: contentPath = self.path[0:self.path.find('?')]",
"else: print(\"Unknown scan command \" + queryData['scan']) self.do_response(400, 'text/html', templates['htmlError'].format(queryData['scan']",
"as channels_m3u from lib.templates import templates # with help from",
"\" + contentPath) return def do_DELETE(self): base_url = self.config['main']['plex_accessible_ip'] +",
"https://stackoverflow.com/questions/9932332 try: self.wfile.write(videoData) time.sleep(0.1) except IOError as e: # Check",
"stdout=subprocess.PIPE) # get initial videodata. if that works, then keep",
"self.location) self.hdhr_station_scan = False for index, scan_status in enumerate(self.rmg_station_scans): if",
"for sid in station_list: if station_list[sid]['channel'] == channel_no: break self.do_tuning(sid)",
"self.do_response(200, 'application/xml', templates['xmlRmgScanStatus']) # putting this here after the response",
"== '/channels.m3u': self.do_response(200, 'application/vnd.apple.mpegurl', channels_m3u.get_channels_m3u(self.config, self.location, base_url)) elif contentPath ==",
"bit of data out to stderr after it terminates, #",
"= [] local_locast = None location = None def do_GET(self):",
"contentPath.startswith('/auto/v'): self.do_tuning(contentPath.replace('/auto/v', '')) elif ((contentPath.startswith('/devices/' + self.config['main']['uuid'] + '/media/')) and",
"for getdataItem in getdataElements: getdataItemSplit = getdataItem.split('=') if len(getdataItemSplit) >",
"PlexHttpHandler.config = config self.bind_ip = config[\"main\"][\"bind_ip\"] self.bind_port = config[\"main\"][\"bind_port\"] PlexHttpHandler.stations",
"httpd.server_bind = self.server_close = lambda self: None httpd.serve_forever() def start(config,",
"<reponame>jefflundberg/locast2plex import subprocess import threading import time import errno import",
"+ '/channels') and (not self.config['main']['use_old_plex_interface'])): station_list = stations.get_dma_stations_and_channels(self.config, self.location) channelXML",
"'/discover.json': self.do_response(200, 'application/json', templates['jsonDiscover'].format(self.config['main']['reporting_friendly_name'], self.config['main']['reporting_model'], self.config['main']['reporting_firmware_name'], self.config['main']['tuner_count'], self.config['main']['reporting_firmware_ver'], self.config['main']['uuid'], base_url))",
"= config[\"main\"][\"bind_port\"] PlexHttpHandler.stations = stations PlexHttpHandler.local_locast = locast_service PlexHttpHandler.location =",
"read any hanging data to prevent a zombie process. ffmpeg_proc.communicate()",
"lib.templates import templates # with help from https://www.acmesystems.it/python_http # and",
"\"-hide_banner\", \"-loglevel\", \"warning\", \"pipe:1\"] ffmpeg_proc = subprocess.Popen(ffmpeg_command, stdout=subprocess.PIPE) # get",
"'video/mpeg; codecs=\"avc1.4D401E') self.end_headers() ffmpeg_command = [self.config['main']['ffmpeg_path'], \"-i\", channelUri, \"-c:v\", \"copy\",",
"ffmpeg_proc.stdout.read(int(self.config['main']['bytes_per_read'])) while True: if not videoData: break else: # from",
"do_response(self, code, mime, reply_str): self.send_response(code) self.send_header('Content-type', mime) self.end_headers() if reply_str:",
"serverSocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) serverSocket.bind((config[\"main\"]['bind_ip'], int(config[\"main\"]['bind_port']))) serverSocket.listen(int(config[\"main\"][\"concurrent_listeners\"])) print(\"Now listening for requests.\")",
"int(config[\"main\"]['bind_port']))) serverSocket.listen(int(config[\"main\"][\"concurrent_listeners\"])) print(\"Now listening for requests.\") for i in range(int(config[\"main\"][\"concurrent_listeners\"])):",
"self.path queryData = {} if self.path.find('?') != -1: contentPath =",
"templates['jsonLineupItem'].format(station_list[sid]['channel'], station_list[sid]['friendlyName'], base_url + '/watch/' + sid) if (index +",
"tuners we can use at a time for index, scan_status",
"\"Scan\" self.do_response(200, 'text/html') # putting this here after the response",
"init station scans tmp_rmg_scans = [] for x in range(int(config['main']['tuner_count'])):",
"= ffmpeg_proc.stdout.read(int(self.config['main']['bytes_per_read'])) # Send SIGTERM to shutdown ffmpeg ffmpeg_proc.terminate() try:",
"rmg_station_scans = [] local_locast = None location = None def",
"= str(list_key) tmpXML = templates['xmlRmgDeviceChannelItem'].format(station_list[sid]['channel'], station_list[sid]['friendlyName']) channelXML = channelXML +",
"\"-f\", \"mpegts\", \"-nostats\", \"-hide_banner\", \"-loglevel\", \"warning\", \"pipe:1\"] ffmpeg_proc = subprocess.Popen(ffmpeg_command,",
"code, mime, reply_str): self.send_response(code) self.send_header('Content-type', mime) self.end_headers() if reply_str: self.wfile.write(reply_str.encode('utf-8'))",
"'application/xml', templates['xmlRmgDeviceDiscover'].format(self.config['main']['uuid'], self.config['main']['reporting_friendly_name'], self.config['main']['reporting_model'], self.config['main']['tuner_count'], base_url)) elif ((contentPath == '/devices/'",
"def start(config, locast, location): serverSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) serverSocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR,",
"= \"Idle\" else: print(\"Unknown scan command \" + queryData['scan']) self.do_response(400,",
"((contentPath.startswith('/devices/discover') or contentPath.startswith('/devices/probe')) and (not self.config['main']['use_old_plex_interface'])): self.do_response(200, 'application/xml', templates['xmlRmgDeviceDiscover'].format(self.config['main']['uuid'], self.config['main']['reporting_friendly_name'],",
"already in use.') self.send_header('Content-type', 'text/html') self.end_headers() reply_str = templates['htmlError'].format('All tuners",
"config = None hdhr_station_scan = False rmg_station_scans = [] local_locast",
"'/lineup.json': # TODO station_list = stations.get_dma_stations_and_channels(self.config, self.location) returnJSON = ''",
"videoData = ffmpeg_proc.stdout.read(int(self.config['main']['bytes_per_read'])) # Send SIGTERM to shutdown ffmpeg ffmpeg_proc.terminate()",
"(not self.config['main']['use_old_plex_interface'])): tuner_list = \"\" for index, scan_status in enumerate(self.rmg_station_scans):",
"== 'Idle': self.rmg_station_scans[index] = station_list[sid]['channel'] tuner_found = True break if",
"'All tuners already in use.') self.send_header('Content-type', 'text/html') self.end_headers() reply_str =",
"PlexHttpHandler, False) httpd.socket = self.socket httpd.server_bind = self.server_close = lambda",
"do_tuning(self, sid): channelUri = self.local_locast.get_station_stream_uri(sid) station_list = stations.get_dma_stations_and_channels(self.config, self.location) tuner_found",
"sid = str(list_key) returnXML = returnXML + templates['xmlLineupItem'].format(station_list[sid]['channel'], station_list[sid]['friendlyName'], base_url",
"import lib.epg2xml as epg2xml import lib.channels_m3u as channels_m3u from lib.templates",
"templates['xmlRmgIdentification'].format(self.config['main']['reporting_friendly_name'])) elif (contentPath == '/') or (contentPath == '/device.xml'): templateName",
"== '/xmltv.xml': self.do_response(200, 'application/xml', epg2xml.get_epg(self.config, self.location)) elif contentPath == '/channels.m3u':",
"'/scanners') and (not self.config['main']['use_old_plex_interface'])): self.do_response(200, 'application/xml', templates['xmlRmgScanProviders'].format(self.location['city'])) else: print(\"Unknown request",
"and (not self.config['main']['use_old_plex_interface'])): self.hdhr_station_scan = True for index, scan_status in",
"the first idle tuner gets it if scan_status == 'Idle':",
"enumerate(station_list): sid = str(list_key) tmpXML = templates['xmlRmgDeviceChannelItem'].format(station_list[sid]['channel'], station_list[sid]['friendlyName']) channelXML =",
"(contentPath == '/') and (not self.config['main']['use_old_plex_interface']): self.do_response(200, 'application/xml', templates['xmlRmgIdentification'].format(self.config['main']['reporting_friendly_name'])) elif",
"reply_str = templates['htmlError'].format('All tuners already in use.') self.wfile.write(reply_str.encode('utf-8')) def do_response(self,",
"urllib import pathlib from io import StringIO from http.server import",
"tuner_list + templates['xmlRmgTunerScanning'].format(str(index)) else: # otherwise, we're streaming, and the",
"self.rmg_station_scans[index] = \"Idle\" elif queryData['scan'] == 'abort': self.do_response(200, 'text/html') self.hdhr_station_scan",
"+ self.config['main']['uuid'] + '/media/')) and (not self.config['main']['use_old_plex_interface'])): channel_no = contentPath.replace('/devices/'",
"sid in station_list: if station_list[sid]['channel'] == channel_no: break self.do_tuning(sid) elif",
"== 'Scan': self.rmg_station_scans[index] = \"Idle\" def do_tuning(self, sid): channelUri =",
"elif contentPath == '/lineup.xml': # TODO station_list = stations.get_dma_stations_and_channels(self.config, self.location)",
"elif queryData['scan'] == 'abort': self.do_response(200, 'text/html') self.hdhr_station_scan = False for",
"serverSocket self.daemon = True self.start() def run(self): httpd = HTTPServer((self.bind_ip,",
"elif ((contentPath.startswith('/devices/discover') or contentPath.startswith('/devices/probe')) and (not self.config['main']['use_old_plex_interface'])): self.do_response(200, 'application/xml', templates['xmlRmgDeviceDiscover'].format(self.config['main']['uuid'],",
"if scan_status == 'Scan': self.rmg_station_scans[index] = \"Idle\" else: print(\"Unknown request",
"\"Idle\" elif queryData['scan'] == 'abort': self.do_response(200, 'text/html') self.hdhr_station_scan = False",
"already in use.') self.wfile.write(reply_str.encode('utf-8')) def do_response(self, code, mime, reply_str): self.send_response(code)",
"import errno import socket import urllib import pathlib from io",
"tuner_list = \"\" for index, scan_status in enumerate(self.rmg_station_scans): if scan_status",
"else: print(\"Unknown request to \" + contentPath) self.do_response(501, 'text/html', templates['htmlError'].format('501",
"scan_status == 'Scan': self.rmg_station_scans[index] = \"Idle\" else: print(\"Unknown request to",
"'text/html') # putting this here after the response on purpose",
"postdata.split('&') for postdataItem in postdataElements: postdataItemSplit = postdataItem.split('=') if len(postdataItemSplit)",
"location # init station scans tmp_rmg_scans = [] for x",
"for index, scan_status in enumerate(self.rmg_station_scans): if scan_status == 'Idle': self.rmg_station_scans[index]",
"for index, scan_status in enumerate(self.rmg_station_scans): # the first idle tuner",
"codecs=\"avc1.4D401E') self.end_headers() ffmpeg_command = [self.config['main']['ffmpeg_path'], \"-i\", channelUri, \"-c:v\", \"copy\", \"-c:a\",",
"https://stackoverflow.com/questions/21631799/how-can-i-pass-parameters-to-a-requesthandler class PlexHttpHandler(BaseHTTPRequestHandler): # using class variables since this should",
"= tuner_list + formatted_xml self.do_response(200, 'application/xml', templates['xmlRmgDeviceIdentity'].format(self.config['main']['uuid'], self.config['main']['reporting_friendly_name'], self.config['main']['reporting_model'], self.config['main']['tuner_count'],",
"config[\"main\"][\"bind_port\"] PlexHttpHandler.stations = stations PlexHttpHandler.local_locast = locast_service PlexHttpHandler.location = location",
"tuner_list + templates['xmlRmgTunerIdle'].format(str(index)) elif scan_status == 'Scan': tuner_list = tuner_list",
"self.config['main']['plex_accessible_port'] contentPath = self.path queryData = {} if self.path.find('?') !=",
"= self.path[(self.path.find('?') + 1):] getdataElements = getdata.split('&') for getdataItem in",
"= False rmg_station_scans = [] local_locast = None location =",
"= getdataItemSplit[1] if ((contentPath == '/devices/' + self.config['main']['uuid'] + '/scan')",
"valid scan command')) elif ((contentPath.startswith('/devices/discover') or contentPath.startswith('/devices/probe')) and (not self.config['main']['use_old_plex_interface'])):",
"contentPath == '/debug.json': self.do_response(200, 'application/json') elif ((contentPath == '/devices/' +",
"the channel triplet formatted_xml = templates['xmlRmgTunerStreaming'].format(str(index), scan_status) tuner_list = tuner_list",
"enumerate(self.rmg_station_scans): if scan_status == 'Idle': self.rmg_station_scans[index] = \"Scan\" self.do_response(200, 'text/html')",
"pathlib from io import StringIO from http.server import BaseHTTPRequestHandler, HTTPServer",
"self.locast, self.location) self.hdhr_station_scan = False for index, scan_status in enumerate(self.rmg_station_scans):",
"import StringIO from http.server import BaseHTTPRequestHandler, HTTPServer import lib.stations as",
"= subprocess.Popen(ffmpeg_command, stdout=subprocess.PIPE) # get initial videodata. if that works,",
"if that works, then keep grabbing it videoData = ffmpeg_proc.stdout.read(int(self.config['main']['bytes_per_read']))",
"writes a bit of data out to stderr after it",
"+ ',' returnJSON = \"[\" + returnJSON + \"]\" self.do_response(200,",
"httpd.serve_forever() def start(config, locast, location): serverSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) serverSocket.setsockopt(socket.SOL_SOCKET,",
"self.server_close = lambda self: None httpd.serve_forever() def start(config, locast, location):",
"if scan_status == 'Idle': self.rmg_station_scans[index] = \"Scan\" self.do_response(200, 'application/xml', templates['xmlRmgScanStatus'])",
"# keep track of how many tuners we can use",
"contentPath == '/channels.m3u': self.do_response(200, 'application/vnd.apple.mpegurl', channels_m3u.get_channels_m3u(self.config, self.location, base_url)) elif contentPath",
"((contentPath == '/devices/' + self.config['main']['uuid']) and (not self.config['main']['use_old_plex_interface'])): tuner_list =",
"'application/xml', templates['xmlRmgScanProviders'].format(self.location['city'])) else: print(\"Unknown request to \" + contentPath) self.do_response(501,",
"= station_list[sid]['channel'] tuner_found = True break if tuner_found: self.send_response(200) self.send_header('Content-type',",
"BaseHTTPRequestHandler, HTTPServer import lib.stations as stations import lib.epg2xml as epg2xml",
"errno.ECONNABORTED, errno.ECONNRESET, errno.ECONNREFUSED]: break else: raise videoData = ffmpeg_proc.stdout.read(int(self.config['main']['bytes_per_read'])) #",
"stderr after it terminates, # need to read any hanging",
"range(int(config['main']['tuner_count'])): tmp_rmg_scans.append('Idle') PlexHttpHandler.rmg_station_scans = tmp_rmg_scans self.socket = serverSocket self.daemon =",
"location): serverSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) serverSocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) serverSocket.bind((config[\"main\"]['bind_ip'], int(config[\"main\"]['bind_port'])))",
"\"mpegts\", \"-nostats\", \"-hide_banner\", \"-loglevel\", \"warning\", \"pipe:1\"] ffmpeg_proc = subprocess.Popen(ffmpeg_command, stdout=subprocess.PIPE)",
"templateName = 'xmlDiscoverOld' self.do_response(200, 'application/xml', templates[templateName].format(self.config['main']['reporting_friendly_name'], self.config['main']['reporting_model'], self.config['main']['uuid'], base_url)) elif",
"= getdataItemSplit[1] if contentPath == '/lineup.post': if queryData['scan'] == 'start':",
"self.daemon = True self.start() def run(self): httpd = HTTPServer((self.bind_ip, int(self.bind_port)),",
"# need to read any hanging data to prevent a",
"and (not self.config['main']['use_old_plex_interface']): self.do_response(200, 'application/xml', templates['xmlRmgIdentification'].format(self.config['main']['reporting_friendly_name'])) elif (contentPath == '/')",
"'text/html') self.hdhr_station_scan = False for index, scan_status in enumerate(self.rmg_station_scans): if",
"== 'Scan': tuner_list = tuner_list + templates['xmlRmgTunerScanning'].format(str(index)) else: # otherwise,",
"1) != len(station_list): returnJSON = returnJSON + ',' returnJSON =",
"contentPath) return def do_DELETE(self): base_url = self.config['main']['plex_accessible_ip'] + ':' +",
"videodata. if that works, then keep grabbing it videoData =",
"elif contentPath == '/lineup.json': # TODO station_list = stations.get_dma_stations_and_channels(self.config, self.location)",
"= [self.config['main']['ffmpeg_path'], \"-i\", channelUri, \"-c:v\", \"copy\", \"-c:a\", \"copy\", \"-f\", \"mpegts\",",
"1: queryData[postdataItemSplit[0]] = postdataItemSplit[1] if self.path.find('?') != -1: contentPath =",
"+ 1):] getdataElements = getdata.split('&') for getdataItem in getdataElements: getdataItemSplit",
"if scan_status == 'Scan': self.rmg_station_scans[index] = \"Idle\" def do_tuning(self, sid):",
"# using class variables since this should only be set",
"'Idle': self.rmg_station_scans[index] = station_list[sid]['channel'] tuner_found = True break if tuner_found:",
"from io import StringIO from http.server import BaseHTTPRequestHandler, HTTPServer import",
"self.config['main']['reporting_friendly_name'], self.config['main']['reporting_model'], self.config['main']['tuner_count'], base_url)) elif ((contentPath == '/devices/' + self.config['main']['uuid']",
"triplet formatted_xml = templates['xmlRmgTunerStreaming'].format(str(index), scan_status) tuner_list = tuner_list + formatted_xml",
"self.rfile.read(int(self.headers.get('Content-Length'))) postdataElements = postdata.split('&') for postdataItem in postdataElements: postdataItemSplit =",
"use at a time for index, scan_status in enumerate(self.rmg_station_scans): #",
"returnJSON = templates['jsonLineupComplete'].replace(\"Antenna\", self.config['main']['tuner_type']) self.do_response(200, 'application/json', returnJSON) elif contentPath ==",
"and the value will be the channel triplet formatted_xml =",
"+ '/media/')) and (not self.config['main']['use_old_plex_interface'])): channel_no = contentPath.replace('/devices/' + self.config['main']['uuid']",
"sid) returnXML = \"<Lineup>\" + returnXML + \"</Lineup>\" self.do_response(200, 'application/xml',",
"self.config['main']['reporting_firmware_ver'], self.config['main']['uuid'], base_url)) elif contentPath == '/lineup_status.json': if self.hdhr_station_scan: returnJSON",
"if len(getdataItemSplit) > 1: queryData[getdataItemSplit[0]] = getdataItemSplit[1] if ((contentPath ==",
"(contentPath == '/') or (contentPath == '/device.xml'): templateName = 'xmlDiscover'",
"'text/html') self.end_headers() reply_str = templates['htmlError'].format('All tuners already in use.') self.wfile.write(reply_str.encode('utf-8'))",
"'' for list_key in station_list: sid = str(list_key) returnXML =",
"self.do_tuning(contentPath.replace('/watch/', '')) elif contentPath.startswith('/auto/v'): self.do_tuning(contentPath.replace('/auto/v', '')) elif ((contentPath.startswith('/devices/' + self.config['main']['uuid']",
"locast, location): serverSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) serverSocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) serverSocket.bind((config[\"main\"]['bind_ip'],",
"self.location, base_url)) elif contentPath == '/debug.json': self.do_response(200, 'application/json') elif ((contentPath",
"+ self.config['main']['uuid'] + '/channels') and (not self.config['main']['use_old_plex_interface'])): station_list = stations.get_dma_stations_and_channels(self.config,",
"lambda self: None httpd.serve_forever() def start(config, locast, location): serverSocket =",
"templates # with help from https://www.acmesystems.it/python_http # and https://stackoverflow.com/questions/21631799/how-can-i-pass-parameters-to-a-requesthandler class",
"= {} if self.headers.get('Content-Length') != '0': postdata = self.rfile.read(int(self.headers.get('Content-Length'))) postdataElements",
"\"-loglevel\", \"warning\", \"pipe:1\"] ffmpeg_proc = subprocess.Popen(ffmpeg_command, stdout=subprocess.PIPE) # get initial",
"self.path.find('?') != -1: contentPath = self.path[0:self.path.find('?')] getdata = self.path[(self.path.find('?') +",
"elif contentPath == '/xmltv.xml': self.do_response(200, 'application/xml', epg2xml.get_epg(self.config, self.location)) elif contentPath",
"to the client if e.errno in [errno.EPIPE, errno.ECONNABORTED, errno.ECONNRESET, errno.ECONNREFUSED]:",
"= getdataItemSplit[1] # paths and logic mostly pulled from telly:routes.go:",
"list_key in enumerate(station_list): sid = str(list_key) returnJSON = returnJSON +",
"contentPath == '/xmltv.xml': self.do_response(200, 'application/xml', epg2xml.get_epg(self.config, self.location)) elif contentPath ==",
"for index, list_key in enumerate(station_list): sid = str(list_key) tmpXML =",
"returnJSON = '' for index, list_key in enumerate(station_list): sid =",
"(contentPath == '/device.xml'): templateName = 'xmlDiscover' if self.config['main']['use_old_plex_interface']: templateName =",
"channel_no = urllib.parse.unquote(channel_no).replace('id://', '').replace('/', '') station_list = stations.get_dma_stations_and_channels(self.config, self.location) for",
"epg2xml import lib.channels_m3u as channels_m3u from lib.templates import templates #",
"from lib.templates import templates # with help from https://www.acmesystems.it/python_http #",
"+ self.config['main']['uuid']) and (not self.config['main']['use_old_plex_interface'])): tuner_list = \"\" for index,",
"index, scan_status in enumerate(self.rmg_station_scans): if scan_status == 'Scan': self.rmg_station_scans[index] =",
"= stations PlexHttpHandler.local_locast = locast_service PlexHttpHandler.location = location # init",
"(not self.config['main']['use_old_plex_interface'])): self.do_response(200, 'application/xml', templates['xmlRmgDeviceDiscover'].format(self.config['main']['uuid'], self.config['main']['reporting_friendly_name'], self.config['main']['reporting_model'], self.config['main']['tuner_count'], base_url)) elif",
"Not Implemented')) return def do_POST(self): base_url = self.config['main']['plex_accessible_ip'] + ':'",
"mostly pulled from telly:routes.go: https://github.com/tellytv/telly if (contentPath == '/') and",
"subprocess import threading import time import errno import socket import",
"config self.bind_ip = config[\"main\"][\"bind_ip\"] self.bind_port = config[\"main\"][\"bind_port\"] PlexHttpHandler.stations = stations",
"self.config['main']['tuner_count'], base_url)) elif ((contentPath == '/devices/' + self.config['main']['uuid'] + '/scan')",
"= getdataItem.split('=') if len(getdataItemSplit) > 1: queryData[getdataItemSplit[0]] = getdataItemSplit[1] if",
"1):] getdataElements = getdata.split('&') for getdataItem in getdataElements: getdataItemSplit =",
"self.do_response(200, 'application/xml', epg2xml.get_epg(self.config, self.location)) elif contentPath == '/channels.m3u': self.do_response(200, 'application/vnd.apple.mpegurl',",
"+ templates['jsonLineupItem'].format(station_list[sid]['channel'], station_list[sid]['friendlyName'], base_url + '/watch/' + sid) if (index",
"scan_status == 'Scan': self.rmg_station_scans[index] = \"Idle\" def do_tuning(self, sid): channelUri",
"this here after the response on purpose stations.refresh_dma_stations_and_channels(self.config, self.local_locast, self.location)",
"idle tuner gets it if scan_status == 'Idle': self.rmg_station_scans[index] =",
"to write back to the client if e.errno in [errno.EPIPE,",
"sid = str(list_key) returnJSON = returnJSON + templates['jsonLineupItem'].format(station_list[sid]['channel'], station_list[sid]['friendlyName'], base_url",
"self.hdhr_station_scan = False for index, scan_status in enumerate(self.rmg_station_scans): if scan_status",
"if scan_status == 'Idle': tuner_list = tuner_list + templates['xmlRmgTunerIdle'].format(str(index)) elif",
"if scan_status == 'Idle': self.rmg_station_scans[index] = station_list[sid]['channel'] tuner_found = True",
"channelXML + tmpXML self.do_response(200, 'application/xml', templates['xmlRmgDeviceChannels'].format(index + 1, channelXML)) elif",
"tmp_rmg_scans = [] for x in range(int(config['main']['tuner_count'])): tmp_rmg_scans.append('Idle') PlexHttpHandler.rmg_station_scans =",
"+ ':' + self.config['main']['plex_accessible_port'] contentPath = self.path queryData = {}",
"= templates['jsonLineupComplete'].replace(\"Antenna\", self.config['main']['tuner_type']) self.do_response(200, 'application/json', returnJSON) elif contentPath == '/lineup.json':",
"import subprocess import threading import time import errno import socket",
"templates['htmlError'].format(queryData['scan'] + ' is not a valid scan command')) elif",
"trying to write back to the client if e.errno in",
"None httpd.serve_forever() def start(config, locast, location): serverSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)",
"scan_status == 'Scan': self.rmg_station_scans[index] = \"Idle\" elif queryData['scan'] == 'abort':",
"value will be the channel triplet formatted_xml = templates['xmlRmgTunerStreaming'].format(str(index), scan_status)",
"self.path queryData = {} if self.headers.get('Content-Length') != '0': postdata =",
"self.wfile.write(reply_str.encode('utf-8')) # mostly from https://github.com/ZeWaren/python-upnp-ssdp-example # and https://stackoverflow.com/questions/46210672/python-2-7-streaming-http-server-supporting-multiple-connections-on-one-port class PlexHttpServer(threading.Thread):",
"((contentPath == '/devices/' + self.config['main']['uuid'] + '/scan') and (not self.config['main']['use_old_plex_interface'])):",
"tuner_found = False # keep track of how many tuners",
"only be set once config = None hdhr_station_scan = False",
"(index + 1) != len(station_list): returnJSON = returnJSON + ','",
"self.config['main']['uuid'], base_url)) elif contentPath == '/discover.json': self.do_response(200, 'application/json', templates['jsonDiscover'].format(self.config['main']['reporting_friendly_name'], self.config['main']['reporting_model'],",
"+ queryData['scan']) self.do_response(400, 'text/html', templates['htmlError'].format(queryData['scan'] + ' is not a",
"1) serverSocket.bind((config[\"main\"]['bind_ip'], int(config[\"main\"]['bind_port']))) serverSocket.listen(int(config[\"main\"][\"concurrent_listeners\"])) print(\"Now listening for requests.\") for i",
"scan_status == 'Idle': self.rmg_station_scans[index] = \"Scan\" self.do_response(200, 'text/html') # putting",
"self.hdhr_station_scan = True for index, scan_status in enumerate(self.rmg_station_scans): if scan_status",
"after it terminates, # need to read any hanging data",
"paths and logic mostly pulled from telly:routes.go: https://github.com/tellytv/telly if (contentPath",
"'application/xml', epg2xml.get_epg(self.config, self.location)) elif contentPath == '/channels.m3u': self.do_response(200, 'application/vnd.apple.mpegurl', channels_m3u.get_channels_m3u(self.config,",
"to \" + contentPath) return def do_DELETE(self): base_url = self.config['main']['plex_accessible_ip']",
"tuner_list)) elif((contentPath == '/devices/' + self.config['main']['uuid'] + '/channels') and (not",
"index, list_key in enumerate(station_list): sid = str(list_key) returnJSON = returnJSON",
"== '/') or (contentPath == '/device.xml'): templateName = 'xmlDiscover' if",
"base_url)) elif contentPath == '/discover.json': self.do_response(200, 'application/json', templates['jsonDiscover'].format(self.config['main']['reporting_friendly_name'], self.config['main']['reporting_model'], self.config['main']['reporting_firmware_name'],",
"!= '0': postdata = self.rfile.read(int(self.headers.get('Content-Length'))) postdataElements = postdata.split('&') for postdataItem",
"use.') self.wfile.write(reply_str.encode('utf-8')) def do_response(self, code, mime, reply_str): self.send_response(code) self.send_header('Content-type', mime)",
"elif contentPath == '/debug.json': self.do_response(200, 'application/json') elif ((contentPath == '/devices/'",
"self.socket httpd.server_bind = self.server_close = lambda self: None httpd.serve_forever() def",
"tmpXML = templates['xmlRmgDeviceChannelItem'].format(station_list[sid]['channel'], station_list[sid]['friendlyName']) channelXML = channelXML + tmpXML self.do_response(200,",
"import lib.stations as stations import lib.epg2xml as epg2xml import lib.channels_m3u",
"== 'Idle': self.rmg_station_scans[index] = \"Scan\" self.do_response(200, 'application/xml', templates['xmlRmgScanStatus']) # putting",
"from https://stackoverflow.com/questions/9932332 try: self.wfile.write(videoData) time.sleep(0.1) except IOError as e: #",
"errno.ECONNREFUSED]: break else: raise videoData = ffmpeg_proc.stdout.read(int(self.config['main']['bytes_per_read'])) # Send SIGTERM",
"first idle tuner gets it if scan_status == 'Idle': self.rmg_station_scans[index]",
"we hit a broken pipe when trying to write back",
"channel_no = contentPath.replace('/devices/' + self.config['main']['uuid'] + '/media/', '') channel_no =",
"> 1: queryData[postdataItemSplit[0]] = postdataItemSplit[1] if self.path.find('?') != -1: contentPath",
"return def do_DELETE(self): base_url = self.config['main']['plex_accessible_ip'] + ':' + self.config['main']['plex_accessible_port']",
"Implemented')) return def do_POST(self): base_url = self.config['main']['plex_accessible_ip'] + ':' +",
"index, scan_status in enumerate(self.rmg_station_scans): if scan_status == 'Idle': self.rmg_station_scans[index] =",
"many tuners we can use at a time for index,",
"postdataItemSplit[1] if self.path.find('?') != -1: contentPath = self.path[0:self.path.find('?')] getdata =",
"templates['xmlRmgDeviceDiscover'].format(self.config['main']['uuid'], self.config['main']['reporting_friendly_name'], self.config['main']['reporting_model'], self.config['main']['tuner_count'], base_url)) elif ((contentPath == '/devices/' +",
"# mostly from https://github.com/ZeWaren/python-upnp-ssdp-example # and https://stackoverflow.com/questions/46210672/python-2-7-streaming-http-server-supporting-multiple-connections-on-one-port class PlexHttpServer(threading.Thread): def",
"' is not a valid scan command')) elif ((contentPath.startswith('/devices/discover') or",
"https://github.com/ZeWaren/python-upnp-ssdp-example # and https://stackoverflow.com/questions/46210672/python-2-7-streaming-http-server-supporting-multiple-connections-on-one-port class PlexHttpServer(threading.Thread): def __init__(self, serverSocket, config,",
"if scan_status == 'Scan': self.rmg_station_scans[index] = \"Idle\" else: print(\"Unknown scan",
"StringIO from http.server import BaseHTTPRequestHandler, HTTPServer import lib.stations as stations",
"\"\" for index, scan_status in enumerate(self.rmg_station_scans): if scan_status == 'Idle':",
"= location # init station scans tmp_rmg_scans = [] for",
"'/media/')) and (not self.config['main']['use_old_plex_interface'])): channel_no = contentPath.replace('/devices/' + self.config['main']['uuid'] +",
"queryData[getdataItemSplit[0]] = getdataItemSplit[1] if ((contentPath == '/devices/' + self.config['main']['uuid'] +",
"tmp_rmg_scans.append('Idle') PlexHttpHandler.rmg_station_scans = tmp_rmg_scans self.socket = serverSocket self.daemon = True",
"'Idle' else: self.send_response(400, 'All tuners already in use.') self.send_header('Content-type', 'text/html')",
"'/media/', '') channel_no = urllib.parse.unquote(channel_no).replace('id://', '').replace('/', '') station_list = stations.get_dma_stations_and_channels(self.config,",
"postdataItem.split('=') if len(postdataItemSplit) > 1: queryData[postdataItemSplit[0]] = postdataItemSplit[1] if self.path.find('?')",
"terminates, # need to read any hanging data to prevent",
"'/scan') and (not self.config['main']['use_old_plex_interface'])): self.hdhr_station_scan = False for index, scan_status",
"returnJSON + templates['jsonLineupItem'].format(station_list[sid]['channel'], station_list[sid]['friendlyName'], base_url + '/watch/' + sid) if",
"tuner gets it if scan_status == 'Idle': self.rmg_station_scans[index] = station_list[sid]['channel']",
"shutdown ffmpeg ffmpeg_proc.terminate() try: # ffmpeg writes a bit of",
"templateName = 'xmlDiscover' if self.config['main']['use_old_plex_interface']: templateName = 'xmlDiscoverOld' self.do_response(200, 'application/xml',",
"self.config['main']['use_old_plex_interface']: templateName = 'xmlDiscoverOld' self.do_response(200, 'application/xml', templates[templateName].format(self.config['main']['reporting_friendly_name'], self.config['main']['reporting_model'], self.config['main']['uuid'], base_url))",
"config, locast_service, location): threading.Thread.__init__(self) PlexHttpHandler.config = config self.bind_ip = config[\"main\"][\"bind_ip\"]",
"= locast_service PlexHttpHandler.location = location # init station scans tmp_rmg_scans",
"# TODO station_list = stations.get_dma_stations_and_channels(self.config, self.location) returnXML = '' for",
"scan_status == 'Scan': self.rmg_station_scans[index] = \"Idle\" else: print(\"Unknown scan command",
"index, list_key in enumerate(station_list): sid = str(list_key) tmpXML = templates['xmlRmgDeviceChannelItem'].format(station_list[sid]['channel'],",
"{} if self.headers.get('Content-Length') != '0': postdata = self.rfile.read(int(self.headers.get('Content-Length'))) postdataElements =",
"then keep grabbing it videoData = ffmpeg_proc.stdout.read(int(self.config['main']['bytes_per_read'])) while True: if",
"ffmpeg_proc.stdout.read(int(self.config['main']['bytes_per_read'])) # Send SIGTERM to shutdown ffmpeg ffmpeg_proc.terminate() try: #",
"be the channel triplet formatted_xml = templates['xmlRmgTunerStreaming'].format(str(index), scan_status) tuner_list =",
"templates[templateName].format(self.config['main']['reporting_friendly_name'], self.config['main']['reporting_model'], self.config['main']['uuid'], base_url)) elif contentPath == '/discover.json': self.do_response(200, 'application/json',",
"+ templates['xmlRmgTunerScanning'].format(str(index)) else: # otherwise, we're streaming, and the value",
"enumerate(self.rmg_station_scans): if scan_status == 'Scan': self.rmg_station_scans[index] = \"Idle\" elif queryData['scan']",
"= True for index, scan_status in enumerate(self.rmg_station_scans): if scan_status ==",
"a time for index, scan_status in enumerate(self.rmg_station_scans): # the first",
"return def do_POST(self): base_url = self.config['main']['plex_accessible_ip'] + ':' + self.config['main']['plex_accessible_port']",
"\"copy\", \"-c:a\", \"copy\", \"-f\", \"mpegts\", \"-nostats\", \"-hide_banner\", \"-loglevel\", \"warning\", \"pipe:1\"]",
"elif ((contentPath == '/devices/' + self.config['main']['uuid'] + '/scan') and (not",
"keep track of how many tuners we can use at",
"self.rmg_station_scans[index] = station_list[sid]['channel'] tuner_found = True break if tuner_found: self.send_response(200)",
"[] for x in range(int(config['main']['tuner_count'])): tmp_rmg_scans.append('Idle') PlexHttpHandler.rmg_station_scans = tmp_rmg_scans self.socket",
"templates['htmlError'].format('501 - Not Implemented')) return def do_POST(self): base_url = self.config['main']['plex_accessible_ip']",
"> 1: queryData[getdataItemSplit[0]] = getdataItemSplit[1] if contentPath == '/lineup.post': if",
"since this should only be set once config = None",
"enumerate(self.rmg_station_scans): # the first idle tuner gets it if scan_status",
"set once config = None hdhr_station_scan = False rmg_station_scans =",
"locast_service, location): threading.Thread.__init__(self) PlexHttpHandler.config = config self.bind_ip = config[\"main\"][\"bind_ip\"] self.bind_port",
"self.do_response(200, 'application/xml', returnXML) elif contentPath.startswith('/watch'): self.do_tuning(contentPath.replace('/watch/', '')) elif contentPath.startswith('/auto/v'): self.do_tuning(contentPath.replace('/auto/v',",
"- Not Implemented')) return def do_POST(self): base_url = self.config['main']['plex_accessible_ip'] +",
"queryData = {} if self.headers.get('Content-Length') != '0': postdata = self.rfile.read(int(self.headers.get('Content-Length')))",
"\"copy\", \"-f\", \"mpegts\", \"-nostats\", \"-hide_banner\", \"-loglevel\", \"warning\", \"pipe:1\"] ffmpeg_proc =",
"time.sleep(0.1) except IOError as e: # Check we hit a",
"back to the client if e.errno in [errno.EPIPE, errno.ECONNABORTED, errno.ECONNRESET,",
"returnJSON = returnJSON + templates['jsonLineupItem'].format(station_list[sid]['channel'], station_list[sid]['friendlyName'], base_url + '/watch/' +",
"self.config['main']['use_old_plex_interface']): self.do_response(200, 'application/xml', templates['xmlRmgIdentification'].format(self.config['main']['reporting_friendly_name'])) elif (contentPath == '/') or (contentPath",
"'Scan': self.rmg_station_scans[index] = \"Idle\" else: print(\"Unknown scan command \" +",
"self.rmg_station_scans[index] = \"Idle\" else: print(\"Unknown scan command \" + queryData['scan'])",
"def do_POST(self): base_url = self.config['main']['plex_accessible_ip'] + ':' + self.config['main']['plex_accessible_port'] contentPath",
"# get initial videodata. if that works, then keep grabbing",
"self.local_locast.get_station_stream_uri(sid) station_list = stations.get_dma_stations_and_channels(self.config, self.location) tuner_found = False # keep",
"break else: raise videoData = ffmpeg_proc.stdout.read(int(self.config['main']['bytes_per_read'])) # Send SIGTERM to",
"self.do_response(200, 'application/xml', templates['xmlRmgIdentification'].format(self.config['main']['reporting_friendly_name'])) elif (contentPath == '/') or (contentPath ==",
"HTTPServer import lib.stations as stations import lib.epg2xml as epg2xml import",
"self.end_headers() reply_str = templates['htmlError'].format('All tuners already in use.') self.wfile.write(reply_str.encode('utf-8')) def",
"contentPath == '/lineup.xml': # TODO station_list = stations.get_dma_stations_and_channels(self.config, self.location) returnXML",
"+ formatted_xml self.do_response(200, 'application/xml', templates['xmlRmgDeviceIdentity'].format(self.config['main']['uuid'], self.config['main']['reporting_friendly_name'], self.config['main']['reporting_model'], self.config['main']['tuner_count'], base_url, tuner_list))",
"location): threading.Thread.__init__(self) PlexHttpHandler.config = config self.bind_ip = config[\"main\"][\"bind_ip\"] self.bind_port =",
"in station_list: if station_list[sid]['channel'] == channel_no: break self.do_tuning(sid) elif contentPath",
"elif contentPath == '/lineup_status.json': if self.hdhr_station_scan: returnJSON = templates['jsonLineupStatus'] else:",
"in enumerate(station_list): sid = str(list_key) tmpXML = templates['xmlRmgDeviceChannelItem'].format(station_list[sid]['channel'], station_list[sid]['friendlyName']) channelXML",
"reply_str: self.wfile.write(reply_str.encode('utf-8')) # mostly from https://github.com/ZeWaren/python-upnp-ssdp-example # and https://stackoverflow.com/questions/46210672/python-2-7-streaming-http-server-supporting-multiple-connections-on-one-port class",
"here after the response on purpose stations.refresh_dma_stations_and_channels(self.config, self.local_locast, self.location) self.hdhr_station_scan",
"'/') or (contentPath == '/device.xml'): templateName = 'xmlDiscover' if self.config['main']['use_old_plex_interface']:",
"if scan_status == 'Idle': self.rmg_station_scans[index] = \"Scan\" self.do_response(200, 'text/html') #",
"in enumerate(station_list): sid = str(list_key) returnJSON = returnJSON + templates['jsonLineupItem'].format(station_list[sid]['channel'],",
"and (not self.config['main']['use_old_plex_interface'])): self.do_response(200, 'application/xml', templates['xmlRmgDeviceDiscover'].format(self.config['main']['uuid'], self.config['main']['reporting_friendly_name'], self.config['main']['reporting_model'], self.config['main']['tuner_count'], base_url))",
"errno.ECONNRESET, errno.ECONNREFUSED]: break else: raise videoData = ffmpeg_proc.stdout.read(int(self.config['main']['bytes_per_read'])) # Send",
"in postdataElements: postdataItemSplit = postdataItem.split('=') if len(postdataItemSplit) > 1: queryData[postdataItemSplit[0]]",
"stations.get_dma_stations_and_channels(self.config, self.location) for sid in station_list: if station_list[sid]['channel'] == channel_no:",
"contentPath = self.path queryData = {} if self.headers.get('Content-Length') != '0':",
"'/lineup_status.json': if self.hdhr_station_scan: returnJSON = templates['jsonLineupStatus'] else: returnJSON = templates['jsonLineupComplete'].replace(\"Antenna\",",
"= stations.get_dma_stations_and_channels(self.config, self.location) returnXML = '' for list_key in station_list:",
"= str(list_key) returnJSON = returnJSON + templates['jsonLineupItem'].format(station_list[sid]['channel'], station_list[sid]['friendlyName'], base_url +",
"scan_status == 'Idle': self.rmg_station_scans[index] = station_list[sid]['channel'] tuner_found = True break",
"self.start() def run(self): httpd = HTTPServer((self.bind_ip, int(self.bind_port)), PlexHttpHandler, False) httpd.socket",
"queryData['scan']) self.do_response(400, 'text/html', templates['htmlError'].format(queryData['scan'] + ' is not a valid",
"\"</Lineup>\" self.do_response(200, 'application/xml', returnXML) elif contentPath.startswith('/watch'): self.do_tuning(contentPath.replace('/watch/', '')) elif contentPath.startswith('/auto/v'):",
"# ffmpeg writes a bit of data out to stderr",
"command')) elif ((contentPath.startswith('/devices/discover') or contentPath.startswith('/devices/probe')) and (not self.config['main']['use_old_plex_interface'])): self.do_response(200, 'application/xml',",
"as e: # Check we hit a broken pipe when",
"PlexHttpHandler.local_locast = locast_service PlexHttpHandler.location = location # init station scans",
"contentPath.replace('/devices/' + self.config['main']['uuid'] + '/media/', '') channel_no = urllib.parse.unquote(channel_no).replace('id://', '').replace('/',",
"self.do_response(200, 'application/xml', templates['xmlRmgDeviceIdentity'].format(self.config['main']['uuid'], self.config['main']['reporting_friendly_name'], self.config['main']['reporting_model'], self.config['main']['tuner_count'], base_url, tuner_list)) elif((contentPath ==",
"sid) if (index + 1) != len(station_list): returnJSON = returnJSON",
"True self.start() def run(self): httpd = HTTPServer((self.bind_ip, int(self.bind_port)), PlexHttpHandler, False)",
"# paths and logic mostly pulled from telly:routes.go: https://github.com/tellytv/telly if",
"= urllib.parse.unquote(channel_no).replace('id://', '').replace('/', '') station_list = stations.get_dma_stations_and_channels(self.config, self.location) for sid",
"str(list_key) tmpXML = templates['xmlRmgDeviceChannelItem'].format(station_list[sid]['channel'], station_list[sid]['friendlyName']) channelXML = channelXML + tmpXML",
"station_list = stations.get_dma_stations_and_channels(self.config, self.location) channelXML = '' for index, list_key",
"self.config['main']['plex_accessible_port'] contentPath = self.path queryData = {} if self.headers.get('Content-Length') !=",
"'text/html', templates['htmlError'].format(queryData['scan'] + ' is not a valid scan command'))",
"+ self.config['main']['plex_accessible_port'] contentPath = self.path queryData = {} if self.path.find('?')",
"(not self.config['main']['use_old_plex_interface'])): self.hdhr_station_scan = True for index, scan_status in enumerate(self.rmg_station_scans):",
"hdhr_station_scan = False rmg_station_scans = [] local_locast = None location",
"stations.refresh_dma_stations_and_channels(self.config, self.local_locast, self.location) self.hdhr_station_scan = False for index, scan_status in",
"logic mostly pulled from telly:routes.go: https://github.com/tellytv/telly if (contentPath == '/')",
"'Idle': self.rmg_station_scans[index] = \"Scan\" self.do_response(200, 'text/html') # putting this here",
"tuner_found = True break if tuner_found: self.send_response(200) self.send_header('Content-type', 'video/mpeg; codecs=\"avc1.4D401E')",
"break self.do_tuning(sid) elif contentPath == '/xmltv.xml': self.do_response(200, 'application/xml', epg2xml.get_epg(self.config, self.location))",
"= 'Idle' else: self.send_response(400, 'All tuners already in use.') self.send_header('Content-type',",
"a broken pipe when trying to write back to the",
"False # keep track of how many tuners we can",
"getdataItemSplit = getdataItem.split('=') if len(getdataItemSplit) > 1: queryData[getdataItemSplit[0]] = getdataItemSplit[1]",
"raise videoData = ffmpeg_proc.stdout.read(int(self.config['main']['bytes_per_read'])) # Send SIGTERM to shutdown ffmpeg",
"== '/lineup.json': # TODO station_list = stations.get_dma_stations_and_channels(self.config, self.location) returnJSON =",
"otherwise, we're streaming, and the value will be the channel",
"elif((contentPath == '/devices/' + self.config['main']['uuid'] + '/channels') and (not self.config['main']['use_old_plex_interface'])):",
"'/devices/' + self.config['main']['uuid'] + '/scanners') and (not self.config['main']['use_old_plex_interface'])): self.do_response(200, 'application/xml',",
"and (not self.config['main']['use_old_plex_interface'])): tuner_list = \"\" for index, scan_status in",
"tuner_list = tuner_list + templates['xmlRmgTunerScanning'].format(str(index)) else: # otherwise, we're streaming,",
"+ returnJSON + \"]\" self.do_response(200, 'application/json', returnJSON) elif contentPath ==",
"need to read any hanging data to prevent a zombie",
"\"Idle\" else: print(\"Unknown scan command \" + queryData['scan']) self.do_response(400, 'text/html',",
"'' for index, list_key in enumerate(station_list): sid = str(list_key) tmpXML",
"getdata.split('&') for getdataItem in getdataElements: getdataItemSplit = getdataItem.split('=') if len(getdataItemSplit)",
"\" + contentPath) self.do_response(501, 'text/html', templates['htmlError'].format('501 - Not Implemented')) return",
"== 'Scan': self.rmg_station_scans[index] = \"Idle\" else: print(\"Unknown request to \"",
"'/devices/' + self.config['main']['uuid'] + '/scan') and (not self.config['main']['use_old_plex_interface'])): self.hdhr_station_scan =",
"import lib.channels_m3u as channels_m3u from lib.templates import templates # with",
"self.do_response(200, 'application/json', templates['jsonDiscover'].format(self.config['main']['reporting_friendly_name'], self.config['main']['reporting_model'], self.config['main']['reporting_firmware_name'], self.config['main']['tuner_count'], self.config['main']['reporting_firmware_ver'], self.config['main']['uuid'], base_url)) elif",
"prevent a zombie process. ffmpeg_proc.communicate() except ValueError: print(\"Connection Closed\") self.rmg_station_scans[index]",
"self.path[0:self.path.find('?')] getdata = self.path[(self.path.find('?') + 1):] getdataElements = getdata.split('&') for",
"'application/xml', templates[templateName].format(self.config['main']['reporting_friendly_name'], self.config['main']['reporting_model'], self.config['main']['uuid'], base_url)) elif contentPath == '/discover.json': self.do_response(200,",
"any hanging data to prevent a zombie process. ffmpeg_proc.communicate() except",
"how many tuners we can use at a time for",
"self.send_header('Content-type', 'text/html') self.end_headers() reply_str = templates['htmlError'].format('All tuners already in use.')",
"print(\"Unknown request to \" + contentPath) self.do_response(501, 'text/html', templates['htmlError'].format('501 -",
"True break if tuner_found: self.send_response(200) self.send_header('Content-type', 'video/mpeg; codecs=\"avc1.4D401E') self.end_headers() ffmpeg_command",
"here after the response on purpose stations.refresh_dma_stations_and_channels(self.config, self.locast, self.location) self.hdhr_station_scan",
"scan_status == 'Idle': tuner_list = tuner_list + templates['xmlRmgTunerIdle'].format(str(index)) elif scan_status",
"tuners already in use.') self.wfile.write(reply_str.encode('utf-8')) def do_response(self, code, mime, reply_str):",
"except IOError as e: # Check we hit a broken",
"+ '/scan') and (not self.config['main']['use_old_plex_interface'])): self.hdhr_station_scan = True for index,",
"while True: if not videoData: break else: # from https://stackoverflow.com/questions/9932332",
"def do_GET(self): base_url = self.config['main']['plex_accessible_ip'] + ':' + self.config['main']['plex_accessible_port'] contentPath",
"threading.Thread.__init__(self) PlexHttpHandler.config = config self.bind_ip = config[\"main\"][\"bind_ip\"] self.bind_port = config[\"main\"][\"bind_port\"]",
"= templates['htmlError'].format('All tuners already in use.') self.wfile.write(reply_str.encode('utf-8')) def do_response(self, code,",
"'/devices/' + self.config['main']['uuid']) and (not self.config['main']['use_old_plex_interface'])): tuner_list = \"\" for",
"self.socket = serverSocket self.daemon = True self.start() def run(self): httpd",
"== channel_no: break self.do_tuning(sid) elif contentPath == '/xmltv.xml': self.do_response(200, 'application/xml',",
"= False # keep track of how many tuners we",
"the client if e.errno in [errno.EPIPE, errno.ECONNABORTED, errno.ECONNRESET, errno.ECONNREFUSED]: break",
"self.config['main']['use_old_plex_interface'])): self.hdhr_station_scan = True for index, scan_status in enumerate(self.rmg_station_scans): if",
"station_list: if station_list[sid]['channel'] == channel_no: break self.do_tuning(sid) elif contentPath ==",
"\"warning\", \"pipe:1\"] ffmpeg_proc = subprocess.Popen(ffmpeg_command, stdout=subprocess.PIPE) # get initial videodata.",
"start(config, locast, location): serverSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) serverSocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)",
"self.location) channelXML = '' for index, list_key in enumerate(station_list): sid",
"command \" + queryData['scan']) self.do_response(400, 'text/html', templates['htmlError'].format(queryData['scan'] + ' is",
"videoData = ffmpeg_proc.stdout.read(int(self.config['main']['bytes_per_read'])) while True: if not videoData: break else:",
"tmp_rmg_scans self.socket = serverSocket self.daemon = True self.start() def run(self):",
"self.bind_ip = config[\"main\"][\"bind_ip\"] self.bind_port = config[\"main\"][\"bind_port\"] PlexHttpHandler.stations = stations PlexHttpHandler.local_locast",
"# TODO station_list = stations.get_dma_stations_and_channels(self.config, self.location) returnJSON = '' for",
"= stations.get_dma_stations_and_channels(self.config, self.location) tuner_found = False # keep track of",
"# Send SIGTERM to shutdown ffmpeg ffmpeg_proc.terminate() try: # ffmpeg",
"in enumerate(self.rmg_station_scans): if scan_status == 'Scan': self.rmg_station_scans[index] = \"Idle\" else:",
"= HTTPServer((self.bind_ip, int(self.bind_port)), PlexHttpHandler, False) httpd.socket = self.socket httpd.server_bind =",
"print(\"Unknown request to \" + contentPath) return def do_DELETE(self): base_url",
"socket.SO_REUSEADDR, 1) serverSocket.bind((config[\"main\"]['bind_ip'], int(config[\"main\"]['bind_port']))) serverSocket.listen(int(config[\"main\"][\"concurrent_listeners\"])) print(\"Now listening for requests.\") for",
"station_list[sid]['friendlyName'], base_url + '/watch/' + sid) if (index + 1)",
"and (not self.config['main']['use_old_plex_interface'])): station_list = stations.get_dma_stations_and_channels(self.config, self.location) channelXML = ''",
"elif contentPath == '/discover.json': self.do_response(200, 'application/json', templates['jsonDiscover'].format(self.config['main']['reporting_friendly_name'], self.config['main']['reporting_model'], self.config['main']['reporting_firmware_name'], self.config['main']['tuner_count'],",
"break else: # from https://stackoverflow.com/questions/9932332 try: self.wfile.write(videoData) time.sleep(0.1) except IOError",
"'Idle': self.rmg_station_scans[index] = \"Scan\" self.do_response(200, 'application/xml', templates['xmlRmgScanStatus']) # putting this",
"that works, then keep grabbing it videoData = ffmpeg_proc.stdout.read(int(self.config['main']['bytes_per_read'])) while",
"in getdataElements: getdataItemSplit = getdataItem.split('=') if len(getdataItemSplit) > 1: queryData[getdataItemSplit[0]]",
"'application/xml', templates['xmlRmgIdentification'].format(self.config['main']['reporting_friendly_name'])) elif (contentPath == '/') or (contentPath == '/device.xml'):",
"sid = str(list_key) tmpXML = templates['xmlRmgDeviceChannelItem'].format(station_list[sid]['channel'], station_list[sid]['friendlyName']) channelXML = channelXML",
"it terminates, # need to read any hanging data to",
"for index, scan_status in enumerate(self.rmg_station_scans): if scan_status == 'Scan': self.rmg_station_scans[index]",
"'/watch/' + sid) if (index + 1) != len(station_list): returnJSON",
"channels_m3u.get_channels_m3u(self.config, self.location, base_url)) elif contentPath == '/debug.json': self.do_response(200, 'application/json') elif",
"self.do_response(200, 'text/html') # putting this here after the response on",
"'/xmltv.xml': self.do_response(200, 'application/xml', epg2xml.get_epg(self.config, self.location)) elif contentPath == '/channels.m3u': self.do_response(200,",
"= templates['xmlRmgDeviceChannelItem'].format(station_list[sid]['channel'], station_list[sid]['friendlyName']) channelXML = channelXML + tmpXML self.do_response(200, 'application/xml',",
"mostly from https://github.com/ZeWaren/python-upnp-ssdp-example # and https://stackoverflow.com/questions/46210672/python-2-7-streaming-http-server-supporting-multiple-connections-on-one-port class PlexHttpServer(threading.Thread): def __init__(self,",
"def __init__(self, serverSocket, config, locast_service, location): threading.Thread.__init__(self) PlexHttpHandler.config = config",
"returnXML + templates['xmlLineupItem'].format(station_list[sid]['channel'], station_list[sid]['friendlyName'], base_url + '/watch/' + sid) returnXML",
"True for index, scan_status in enumerate(self.rmg_station_scans): if scan_status == 'Idle':",
"'' for index, list_key in enumerate(station_list): sid = str(list_key) returnJSON",
"None def do_GET(self): base_url = self.config['main']['plex_accessible_ip'] + ':' + self.config['main']['plex_accessible_port']",
"+ '/media/', '') channel_no = urllib.parse.unquote(channel_no).replace('id://', '').replace('/', '') station_list =",
"= \"<Lineup>\" + returnXML + \"</Lineup>\" self.do_response(200, 'application/xml', returnXML) elif",
"variables since this should only be set once config =",
"response on purpose stations.refresh_dma_stations_and_channels(self.config, self.local_locast, self.location) self.hdhr_station_scan = False for",
"> 1: queryData[getdataItemSplit[0]] = getdataItemSplit[1] # paths and logic mostly",
"'xmlDiscoverOld' self.do_response(200, 'application/xml', templates[templateName].format(self.config['main']['reporting_friendly_name'], self.config['main']['reporting_model'], self.config['main']['uuid'], base_url)) elif contentPath ==",
"returnJSON = returnJSON + ',' returnJSON = \"[\" + returnJSON",
"on purpose stations.refresh_dma_stations_and_channels(self.config, self.local_locast, self.location) self.hdhr_station_scan = False for index,",
"if not videoData: break else: # from https://stackoverflow.com/questions/9932332 try: self.wfile.write(videoData)",
"def do_response(self, code, mime, reply_str): self.send_response(code) self.send_header('Content-type', mime) self.end_headers() if",
"self.rmg_station_scans[index] = 'Idle' else: self.send_response(400, 'All tuners already in use.')",
"channels_m3u from lib.templates import templates # with help from https://www.acmesystems.it/python_http",
"if self.path.find('?') != -1: contentPath = self.path[0:self.path.find('?')] getdata = self.path[(self.path.find('?')",
"to stderr after it terminates, # need to read any",
"enumerate(self.rmg_station_scans): if scan_status == 'Scan': self.rmg_station_scans[index] = \"Idle\" else: print(\"Unknown",
"for index, list_key in enumerate(station_list): sid = str(list_key) returnJSON =",
"self.send_response(code) self.send_header('Content-type', mime) self.end_headers() if reply_str: self.wfile.write(reply_str.encode('utf-8')) # mostly from",
"self: None httpd.serve_forever() def start(config, locast, location): serverSocket = socket.socket(socket.AF_INET,",
"socket import urllib import pathlib from io import StringIO from",
"',' returnJSON = \"[\" + returnJSON + \"]\" self.do_response(200, 'application/json',",
"in enumerate(self.rmg_station_scans): if scan_status == 'Scan': self.rmg_station_scans[index] = \"Idle\" elif",
"for requests.\") for i in range(int(config[\"main\"][\"concurrent_listeners\"])): PlexHttpServer(serverSocket, config, locast, location)",
"as stations import lib.epg2xml as epg2xml import lib.channels_m3u as channels_m3u",
"'/scan') and (not self.config['main']['use_old_plex_interface'])): self.hdhr_station_scan = True for index, scan_status",
"elif contentPath.startswith('/auto/v'): self.do_tuning(contentPath.replace('/auto/v', '')) elif ((contentPath.startswith('/devices/' + self.config['main']['uuid'] + '/media/'))",
"io import StringIO from http.server import BaseHTTPRequestHandler, HTTPServer import lib.stations",
"httpd = HTTPServer((self.bind_ip, int(self.bind_port)), PlexHttpHandler, False) httpd.socket = self.socket httpd.server_bind",
"for postdataItem in postdataElements: postdataItemSplit = postdataItem.split('=') if len(postdataItemSplit) >",
"a valid scan command')) elif ((contentPath.startswith('/devices/discover') or contentPath.startswith('/devices/probe')) and (not",
"getdataItemSplit[1] # paths and logic mostly pulled from telly:routes.go: https://github.com/tellytv/telly",
"== '/lineup.post': if queryData['scan'] == 'start': self.hdhr_station_scan = True for",
"= '' for index, list_key in enumerate(station_list): sid = str(list_key)",
"self.config['main']['uuid'] + '/scan') and (not self.config['main']['use_old_plex_interface'])): self.hdhr_station_scan = True for",
"pipe when trying to write back to the client if",
"True: if not videoData: break else: # from https://stackoverflow.com/questions/9932332 try:",
"write back to the client if e.errno in [errno.EPIPE, errno.ECONNABORTED,",
"'/lineup.post': if queryData['scan'] == 'start': self.hdhr_station_scan = True for index,",
"scan_status in enumerate(self.rmg_station_scans): if scan_status == 'Idle': self.rmg_station_scans[index] = \"Scan\"",
"== '/devices/' + self.config['main']['uuid'] + '/scan') and (not self.config['main']['use_old_plex_interface'])): self.hdhr_station_scan",
"pulled from telly:routes.go: https://github.com/tellytv/telly if (contentPath == '/') and (not",
"import threading import time import errno import socket import urllib",
"self.do_response(200, 'application/json') elif ((contentPath == '/devices/' + self.config['main']['uuid']) and (not",
"in enumerate(self.rmg_station_scans): if scan_status == 'Idle': tuner_list = tuner_list +",
"station_list[sid]['channel'] == channel_no: break self.do_tuning(sid) elif contentPath == '/xmltv.xml': self.do_response(200,",
"ffmpeg ffmpeg_proc.terminate() try: # ffmpeg writes a bit of data",
"'abort': self.do_response(200, 'text/html') self.hdhr_station_scan = False for index, scan_status in",
"to prevent a zombie process. ffmpeg_proc.communicate() except ValueError: print(\"Connection Closed\")",
"base_url)) elif contentPath == '/debug.json': self.do_response(200, 'application/json') elif ((contentPath ==",
"+ self.config['main']['plex_accessible_port'] contentPath = self.path queryData = {} if self.headers.get('Content-Length')",
"False for index, scan_status in enumerate(self.rmg_station_scans): if scan_status == 'Scan':",
"self.config['main']['use_old_plex_interface'])): channel_no = contentPath.replace('/devices/' + self.config['main']['uuid'] + '/media/', '') channel_no",
"templates['xmlRmgTunerStreaming'].format(str(index), scan_status) tuner_list = tuner_list + formatted_xml self.do_response(200, 'application/xml', templates['xmlRmgDeviceIdentity'].format(self.config['main']['uuid'],",
"# from https://stackoverflow.com/questions/9932332 try: self.wfile.write(videoData) time.sleep(0.1) except IOError as e:",
"= tmp_rmg_scans self.socket = serverSocket self.daemon = True self.start() def",
"station_list[sid]['friendlyName']) channelXML = channelXML + tmpXML self.do_response(200, 'application/xml', templates['xmlRmgDeviceChannels'].format(index +",
"'Scan': self.rmg_station_scans[index] = \"Idle\" elif queryData['scan'] == 'abort': self.do_response(200, 'text/html')",
"returnJSON = templates['jsonLineupStatus'] else: returnJSON = templates['jsonLineupComplete'].replace(\"Antenna\", self.config['main']['tuner_type']) self.do_response(200, 'application/json',",
"== 'abort': self.do_response(200, 'text/html') self.hdhr_station_scan = False for index, scan_status",
"!= len(station_list): returnJSON = returnJSON + ',' returnJSON = \"[\"",
"len(getdataItemSplit) > 1: queryData[getdataItemSplit[0]] = getdataItemSplit[1] if contentPath == '/lineup.post':",
"do_DELETE(self): base_url = self.config['main']['plex_accessible_ip'] + ':' + self.config['main']['plex_accessible_port'] contentPath =",
"tuner_found: self.send_response(200) self.send_header('Content-type', 'video/mpeg; codecs=\"avc1.4D401E') self.end_headers() ffmpeg_command = [self.config['main']['ffmpeg_path'], \"-i\",",
"len(station_list): returnJSON = returnJSON + ',' returnJSON = \"[\" +",
"= 'xmlDiscover' if self.config['main']['use_old_plex_interface']: templateName = 'xmlDiscoverOld' self.do_response(200, 'application/xml', templates[templateName].format(self.config['main']['reporting_friendly_name'],",
"self.config['main']['tuner_count'], base_url, tuner_list)) elif((contentPath == '/devices/' + self.config['main']['uuid'] + '/channels')",
"'application/xml', returnXML) elif contentPath.startswith('/watch'): self.do_tuning(contentPath.replace('/watch/', '')) elif contentPath.startswith('/auto/v'): self.do_tuning(contentPath.replace('/auto/v', ''))",
"locast_service PlexHttpHandler.location = location # init station scans tmp_rmg_scans =",
"templates['xmlRmgScanStatus']) # putting this here after the response on purpose",
"getdataItemSplit[1] if ((contentPath == '/devices/' + self.config['main']['uuid'] + '/scan') and",
"stations PlexHttpHandler.local_locast = locast_service PlexHttpHandler.location = location # init station",
"tuner_list = tuner_list + formatted_xml self.do_response(200, 'application/xml', templates['xmlRmgDeviceIdentity'].format(self.config['main']['uuid'], self.config['main']['reporting_friendly_name'], self.config['main']['reporting_model'],",
"station_list = stations.get_dma_stations_and_channels(self.config, self.location) returnJSON = '' for index, list_key",
"[errno.EPIPE, errno.ECONNABORTED, errno.ECONNRESET, errno.ECONNREFUSED]: break else: raise videoData = ffmpeg_proc.stdout.read(int(self.config['main']['bytes_per_read']))",
"\"-i\", channelUri, \"-c:v\", \"copy\", \"-c:a\", \"copy\", \"-f\", \"mpegts\", \"-nostats\", \"-hide_banner\",",
"templates['xmlRmgTunerIdle'].format(str(index)) elif scan_status == 'Scan': tuner_list = tuner_list + templates['xmlRmgTunerScanning'].format(str(index))",
"+ returnXML + \"</Lineup>\" self.do_response(200, 'application/xml', returnXML) elif contentPath.startswith('/watch'): self.do_tuning(contentPath.replace('/watch/',",
"self.config['main']['reporting_model'], self.config['main']['tuner_count'], base_url, tuner_list)) elif((contentPath == '/devices/' + self.config['main']['uuid'] +",
"do_GET(self): base_url = self.config['main']['plex_accessible_ip'] + ':' + self.config['main']['plex_accessible_port'] contentPath =",
"channel triplet formatted_xml = templates['xmlRmgTunerStreaming'].format(str(index), scan_status) tuner_list = tuner_list +",
"self.end_headers() ffmpeg_command = [self.config['main']['ffmpeg_path'], \"-i\", channelUri, \"-c:v\", \"copy\", \"-c:a\", \"copy\",",
"'Scan': self.rmg_station_scans[index] = \"Idle\" def do_tuning(self, sid): channelUri = self.local_locast.get_station_stream_uri(sid)",
"PlexHttpHandler.stations = stations PlexHttpHandler.local_locast = locast_service PlexHttpHandler.location = location #",
"= 'xmlDiscoverOld' self.do_response(200, 'application/xml', templates[templateName].format(self.config['main']['reporting_friendly_name'], self.config['main']['reporting_model'], self.config['main']['uuid'], base_url)) elif contentPath",
"httpd.socket = self.socket httpd.server_bind = self.server_close = lambda self: None",
"self.do_response(400, 'text/html', templates['htmlError'].format(queryData['scan'] + ' is not a valid scan",
"contentPath.startswith('/devices/probe')) and (not self.config['main']['use_old_plex_interface'])): self.do_response(200, 'application/xml', templates['xmlRmgDeviceDiscover'].format(self.config['main']['uuid'], self.config['main']['reporting_friendly_name'], self.config['main']['reporting_model'], self.config['main']['tuner_count'],",
"gets it if scan_status == 'Idle': self.rmg_station_scans[index] = station_list[sid]['channel'] tuner_found",
"and (not self.config['main']['use_old_plex_interface'])): channel_no = contentPath.replace('/devices/' + self.config['main']['uuid'] + '/media/',",
"ffmpeg_proc = subprocess.Popen(ffmpeg_command, stdout=subprocess.PIPE) # get initial videodata. if that",
"and https://stackoverflow.com/questions/21631799/how-can-i-pass-parameters-to-a-requesthandler class PlexHttpHandler(BaseHTTPRequestHandler): # using class variables since this",
"'application/xml', templates['xmlRmgDeviceChannels'].format(index + 1, channelXML)) elif ((contentPath == '/devices/' +",
"and (not self.config['main']['use_old_plex_interface'])): self.do_response(200, 'application/xml', templates['xmlRmgScanProviders'].format(self.location['city'])) else: print(\"Unknown request to",
"try: # ffmpeg writes a bit of data out to",
"at a time for index, scan_status in enumerate(self.rmg_station_scans): # the",
"Check we hit a broken pipe when trying to write",
"channelXML)) elif ((contentPath == '/devices/' + self.config['main']['uuid'] + '/scanners') and",
"self.local_locast, self.location) self.hdhr_station_scan = False for index, scan_status in enumerate(self.rmg_station_scans):",
"def do_tuning(self, sid): channelUri = self.local_locast.get_station_stream_uri(sid) station_list = stations.get_dma_stations_and_channels(self.config, self.location)",
"from telly:routes.go: https://github.com/tellytv/telly if (contentPath == '/') and (not self.config['main']['use_old_plex_interface']):",
"ffmpeg_proc.terminate() try: # ffmpeg writes a bit of data out",
"self.wfile.write(reply_str.encode('utf-8')) def do_response(self, code, mime, reply_str): self.send_response(code) self.send_header('Content-type', mime) self.end_headers()",
"= lambda self: None httpd.serve_forever() def start(config, locast, location): serverSocket",
"break if tuner_found: self.send_response(200) self.send_header('Content-type', 'video/mpeg; codecs=\"avc1.4D401E') self.end_headers() ffmpeg_command =",
"PlexHttpServer(threading.Thread): def __init__(self, serverSocket, config, locast_service, location): threading.Thread.__init__(self) PlexHttpHandler.config =",
"= stations.get_dma_stations_and_channels(self.config, self.location) channelXML = '' for index, list_key in",
"in enumerate(self.rmg_station_scans): if scan_status == 'Idle': self.rmg_station_scans[index] = \"Scan\" self.do_response(200,",
"self.do_tuning(sid) elif contentPath == '/xmltv.xml': self.do_response(200, 'application/xml', epg2xml.get_epg(self.config, self.location)) elif",
"== 'Idle': self.rmg_station_scans[index] = \"Scan\" self.do_response(200, 'text/html') # putting this",
"templates['xmlRmgDeviceIdentity'].format(self.config['main']['uuid'], self.config['main']['reporting_friendly_name'], self.config['main']['reporting_model'], self.config['main']['tuner_count'], base_url, tuner_list)) elif((contentPath == '/devices/' +",
"'0': postdata = self.rfile.read(int(self.headers.get('Content-Length'))) postdataElements = postdata.split('&') for postdataItem in",
"+ \"]\" self.do_response(200, 'application/json', returnJSON) elif contentPath == '/lineup.xml': #",
"+ '/scanners') and (not self.config['main']['use_old_plex_interface'])): self.do_response(200, 'application/xml', templates['xmlRmgScanProviders'].format(self.location['city'])) else: print(\"Unknown",
"+ self.config['main']['uuid'] + '/scan') and (not self.config['main']['use_old_plex_interface'])): self.hdhr_station_scan = True",
"process. ffmpeg_proc.communicate() except ValueError: print(\"Connection Closed\") self.rmg_station_scans[index] = 'Idle' else:",
"== 'start': self.hdhr_station_scan = True for index, scan_status in enumerate(self.rmg_station_scans):",
"if self.config['main']['use_old_plex_interface']: templateName = 'xmlDiscoverOld' self.do_response(200, 'application/xml', templates[templateName].format(self.config['main']['reporting_friendly_name'], self.config['main']['reporting_model'], self.config['main']['uuid'],",
"lib.epg2xml as epg2xml import lib.channels_m3u as channels_m3u from lib.templates import",
"channelXML = '' for index, list_key in enumerate(station_list): sid =",
"== 'Scan': self.rmg_station_scans[index] = \"Idle\" else: print(\"Unknown scan command \"",
"'/') and (not self.config['main']['use_old_plex_interface']): self.do_response(200, 'application/xml', templates['xmlRmgIdentification'].format(self.config['main']['reporting_friendly_name'])) elif (contentPath ==",
"to shutdown ffmpeg ffmpeg_proc.terminate() try: # ffmpeg writes a bit",
"base_url = self.config['main']['plex_accessible_ip'] + ':' + self.config['main']['plex_accessible_port'] contentPath = self.path",
"# and https://stackoverflow.com/questions/46210672/python-2-7-streaming-http-server-supporting-multiple-connections-on-one-port class PlexHttpServer(threading.Thread): def __init__(self, serverSocket, config, locast_service,",
"getdataItem.split('=') if len(getdataItemSplit) > 1: queryData[getdataItemSplit[0]] = getdataItemSplit[1] # paths",
"\"[\" + returnJSON + \"]\" self.do_response(200, 'application/json', returnJSON) elif contentPath",
"for list_key in station_list: sid = str(list_key) returnXML = returnXML",
"a bit of data out to stderr after it terminates,",
"ffmpeg_proc.communicate() except ValueError: print(\"Connection Closed\") self.rmg_station_scans[index] = 'Idle' else: self.send_response(400,",
"self.rmg_station_scans[index] = \"Scan\" self.do_response(200, 'text/html') # putting this here after",
"postdataItem in postdataElements: postdataItemSplit = postdataItem.split('=') if len(postdataItemSplit) > 1:",
"videoData: break else: # from https://stackoverflow.com/questions/9932332 try: self.wfile.write(videoData) time.sleep(0.1) except",
"':' + self.config['main']['plex_accessible_port'] contentPath = self.path queryData = {} if",
"= stations.get_dma_stations_and_channels(self.config, self.location) returnJSON = '' for index, list_key in",
"broken pipe when trying to write back to the client",
"postdataElements: postdataItemSplit = postdataItem.split('=') if len(postdataItemSplit) > 1: queryData[postdataItemSplit[0]] =",
"once config = None hdhr_station_scan = False rmg_station_scans = []",
"socket.SOCK_STREAM) serverSocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) serverSocket.bind((config[\"main\"]['bind_ip'], int(config[\"main\"]['bind_port']))) serverSocket.listen(int(config[\"main\"][\"concurrent_listeners\"])) print(\"Now listening for",
"data out to stderr after it terminates, # need to",
"= self.path[0:self.path.find('?')] getdata = self.path[(self.path.find('?') + 1):] getdataElements = getdata.split('&')",
"scan command')) elif ((contentPath.startswith('/devices/discover') or contentPath.startswith('/devices/probe')) and (not self.config['main']['use_old_plex_interface'])): self.do_response(200,",
"and (not self.config['main']['use_old_plex_interface'])): self.hdhr_station_scan = False for index, scan_status in"
] |
[
"html_template = loader.get_template(\"page-404.html\") return HttpResponse(html_template.render(context, request)) except: # noqa: E722",
"from django.http import HttpResponse from django.template import loader @login_required(login_url=\"/login/\") def",
"django import template from django.contrib.auth.decorators import login_required from django.http import",
"def index(request): context = {} context[\"segment\"] = \"index\" html_template =",
"{} context[\"segment\"] = \"index\" html_template = loader.get_template(\"index.html\") return HttpResponse(html_template.render(context, request))",
"try: load_template = request.path.split(\"/\")[-1] context[\"segment\"] = load_template html_template = loader.get_template(load_template)",
"= {} context[\"segment\"] = \"index\" html_template = loader.get_template(\"index.html\") return HttpResponse(html_template.render(context,",
"All resource paths end in .html. # Pick out the",
"that template. try: load_template = request.path.split(\"/\")[-1] context[\"segment\"] = load_template html_template",
"template. try: load_template = request.path.split(\"/\")[-1] context[\"segment\"] = load_template html_template =",
".html. # Pick out the html file name from the",
"return HttpResponse(html_template.render(context, request)) @login_required(login_url=\"/login/\") def pages(request): context = {} #",
"return HttpResponse(html_template.render(context, request)) except: # noqa: E722 html_template = loader.get_template(\"page-500.html\")",
"import login_required from django.http import HttpResponse from django.template import loader",
"= \"index\" html_template = loader.get_template(\"index.html\") return HttpResponse(html_template.render(context, request)) @login_required(login_url=\"/login/\") def",
"from the url. And load that template. try: load_template =",
"loader.get_template(load_template) return HttpResponse(html_template.render(context, request)) except template.TemplateDoesNotExist: html_template = loader.get_template(\"page-404.html\") return",
"in .html. # Pick out the html file name from",
"import HttpResponse from django.template import loader @login_required(login_url=\"/login/\") def index(request): context",
"\"index\" html_template = loader.get_template(\"index.html\") return HttpResponse(html_template.render(context, request)) @login_required(login_url=\"/login/\") def pages(request):",
"end in .html. # Pick out the html file name",
"import loader @login_required(login_url=\"/login/\") def index(request): context = {} context[\"segment\"] =",
"request)) except template.TemplateDoesNotExist: html_template = loader.get_template(\"page-404.html\") return HttpResponse(html_template.render(context, request)) except:",
"from django.contrib.auth.decorators import login_required from django.http import HttpResponse from django.template",
"loader @login_required(login_url=\"/login/\") def index(request): context = {} context[\"segment\"] = \"index\"",
"= loader.get_template(\"index.html\") return HttpResponse(html_template.render(context, request)) @login_required(login_url=\"/login/\") def pages(request): context =",
"resource paths end in .html. # Pick out the html",
"except: # noqa: E722 html_template = loader.get_template(\"page-500.html\") return HttpResponse(html_template.render(context, request))",
"HttpResponse from django.template import loader @login_required(login_url=\"/login/\") def index(request): context =",
"= loader.get_template(\"page-404.html\") return HttpResponse(html_template.render(context, request)) except: # noqa: E722 html_template",
"And load that template. try: load_template = request.path.split(\"/\")[-1] context[\"segment\"] =",
"request)) except: # noqa: E722 html_template = loader.get_template(\"page-500.html\") return HttpResponse(html_template.render(context,",
"def pages(request): context = {} # All resource paths end",
"request.path.split(\"/\")[-1] context[\"segment\"] = load_template html_template = loader.get_template(load_template) return HttpResponse(html_template.render(context, request))",
"context[\"segment\"] = load_template html_template = loader.get_template(load_template) return HttpResponse(html_template.render(context, request)) except",
"django.http import HttpResponse from django.template import loader @login_required(login_url=\"/login/\") def index(request):",
"= load_template html_template = loader.get_template(load_template) return HttpResponse(html_template.render(context, request)) except template.TemplateDoesNotExist:",
"html_template = loader.get_template(\"index.html\") return HttpResponse(html_template.render(context, request)) @login_required(login_url=\"/login/\") def pages(request): context",
"paths end in .html. # Pick out the html file",
"name from the url. And load that template. try: load_template",
"except template.TemplateDoesNotExist: html_template = loader.get_template(\"page-404.html\") return HttpResponse(html_template.render(context, request)) except: #",
"= {} # All resource paths end in .html. #",
"index(request): context = {} context[\"segment\"] = \"index\" html_template = loader.get_template(\"index.html\")",
"load_template = request.path.split(\"/\")[-1] context[\"segment\"] = load_template html_template = loader.get_template(load_template) return",
"return HttpResponse(html_template.render(context, request)) except template.TemplateDoesNotExist: html_template = loader.get_template(\"page-404.html\") return HttpResponse(html_template.render(context,",
"load_template html_template = loader.get_template(load_template) return HttpResponse(html_template.render(context, request)) except template.TemplateDoesNotExist: html_template",
"html_template = loader.get_template(load_template) return HttpResponse(html_template.render(context, request)) except template.TemplateDoesNotExist: html_template =",
"HttpResponse(html_template.render(context, request)) except template.TemplateDoesNotExist: html_template = loader.get_template(\"page-404.html\") return HttpResponse(html_template.render(context, request))",
"import template from django.contrib.auth.decorators import login_required from django.http import HttpResponse",
"{} # All resource paths end in .html. # Pick",
"loader.get_template(\"page-404.html\") return HttpResponse(html_template.render(context, request)) except: # noqa: E722 html_template =",
"from django.template import loader @login_required(login_url=\"/login/\") def index(request): context = {}",
"# All resource paths end in .html. # Pick out",
"from django import template from django.contrib.auth.decorators import login_required from django.http",
"template from django.contrib.auth.decorators import login_required from django.http import HttpResponse from",
"load that template. try: load_template = request.path.split(\"/\")[-1] context[\"segment\"] = load_template",
"the html file name from the url. And load that",
"# Pick out the html file name from the url.",
"HttpResponse(html_template.render(context, request)) @login_required(login_url=\"/login/\") def pages(request): context = {} # All",
"url. And load that template. try: load_template = request.path.split(\"/\")[-1] context[\"segment\"]",
"= loader.get_template(load_template) return HttpResponse(html_template.render(context, request)) except template.TemplateDoesNotExist: html_template = loader.get_template(\"page-404.html\")",
"django.contrib.auth.decorators import login_required from django.http import HttpResponse from django.template import",
"template.TemplateDoesNotExist: html_template = loader.get_template(\"page-404.html\") return HttpResponse(html_template.render(context, request)) except: # noqa:",
"login_required from django.http import HttpResponse from django.template import loader @login_required(login_url=\"/login/\")",
"@login_required(login_url=\"/login/\") def index(request): context = {} context[\"segment\"] = \"index\" html_template",
"Pick out the html file name from the url. And",
"the url. And load that template. try: load_template = request.path.split(\"/\")[-1]",
"html file name from the url. And load that template.",
"context[\"segment\"] = \"index\" html_template = loader.get_template(\"index.html\") return HttpResponse(html_template.render(context, request)) @login_required(login_url=\"/login/\")",
"context = {} context[\"segment\"] = \"index\" html_template = loader.get_template(\"index.html\") return",
"pages(request): context = {} # All resource paths end in",
"out the html file name from the url. And load",
"context = {} # All resource paths end in .html.",
"request)) @login_required(login_url=\"/login/\") def pages(request): context = {} # All resource",
"HttpResponse(html_template.render(context, request)) except: # noqa: E722 html_template = loader.get_template(\"page-500.html\") return",
"@login_required(login_url=\"/login/\") def pages(request): context = {} # All resource paths",
"django.template import loader @login_required(login_url=\"/login/\") def index(request): context = {} context[\"segment\"]",
"file name from the url. And load that template. try:",
"= request.path.split(\"/\")[-1] context[\"segment\"] = load_template html_template = loader.get_template(load_template) return HttpResponse(html_template.render(context,",
"loader.get_template(\"index.html\") return HttpResponse(html_template.render(context, request)) @login_required(login_url=\"/login/\") def pages(request): context = {}"
] |
[
"of paths to all files with the given filename extensions",
"int16.\"\"\" if not issubclass(y.dtype.type, np.floating): raise ValueError(\"input samples not floating-point\")",
"the question: Is the given ndarray a multichannel waveform or",
"root, dirs, filenames in os.walk(root_path): filenames = sorted(filenames) for filename",
"be mixed in. Based on https://github.com/Sato-Kunihiko/audio-SNR/blob/8d2c933b6c0afe6f1203251f4877e7a1068a6130/create_mixed_audio_file.py#L20 :param clean_rms: Root Mean",
"snr: Signal-to-Noise (SNR) Ratio in dB - typically somewhere between",
"= os.path.abspath(root) file_path = os.path.join(input_path, filename) if filename.lower().endswith(filename_endings): file_paths.append(Path(file_path)) if",
"(SNR) Ratio in dB - typically somewhere between -20 and",
"= os.path.join(input_path, filename) if filename.lower().endswith(filename_endings): file_paths.append(Path(file_path)) if not traverse_subdirectories: #",
"return noise_rms def convert_decibels_to_amplitude_ratio(decibels): return 10 ** (decibels / 20)",
"filenames = sorted(filenames) for filename in filenames: input_path = os.path.abspath(root)",
"return 10 ** (decibels / 20) def is_waveform_multichannel(samples): \"\"\" Return",
"Mean Square (RMS) of a clean sound and a desired",
"a multichannel waveform or not? :param samples: numpy ndarray :return:",
":param samples: numpy ndarray :return: \"\"\" return len(samples.shape) > 1",
"sound to be mixed in. Based on https://github.com/Sato-Kunihiko/audio-SNR/blob/8d2c933b6c0afe6f1203251f4877e7a1068a6130/create_mixed_audio_file.py#L20 :param clean_rms:",
"audio samples to int16.\"\"\" if not issubclass(y.dtype.type, np.floating): raise ValueError(\"input",
"of a clean sound and a desired signal-to-noise ratio (SNR),",
"Based on https://github.com/Sato-Kunihiko/audio-SNR/blob/8d2c933b6c0afe6f1203251f4877e7a1068a6130/create_mixed_audio_file.py#L20 :param clean_rms: Root Mean Square (RMS) -",
"traverses subdirectories by default. \"\"\" file_paths = [] for root,",
"\".m4a\", \".mp3\", \".ogg\", \".opus\", \".wav\") def get_file_paths( root_path, filename_endings=AUDIO_FILENAME_ENDINGS, traverse_subdirectories=True",
"<reponame>jeongyoonlee/audiomentations<filename>audiomentations/core/utils.py import os from pathlib import Path import numpy as",
"Also traverses subdirectories by default. \"\"\" file_paths = [] for",
"a list of paths to all files with the given",
"Square (RMS) of a clean sound and a desired signal-to-noise",
"traverse_subdirectories: # prevent descending into subfolders break return file_paths def",
"float(snr) / 20 noise_rms = clean_rms / (10 ** a)",
"calculate the desired RMS of a noise sound to be",
"return len(samples.shape) > 1 def is_spectrogram_multichannel(spectrogram): \"\"\" Return bool that",
"in. Based on https://github.com/Sato-Kunihiko/audio-SNR/blob/8d2c933b6c0afe6f1203251f4877e7a1068a6130/create_mixed_audio_file.py#L20 :param clean_rms: Root Mean Square (RMS)",
"is_waveform_multichannel(samples): \"\"\" Return bool that answers the question: Is the",
"in os.walk(root_path): filenames = sorted(filenames) for filename in filenames: input_path",
"directory. Also traverses subdirectories by default. \"\"\" file_paths = []",
"# prevent descending into subfolders break return file_paths def calculate_rms(samples):",
"ndarray a multichannel waveform or not? :param samples: numpy ndarray",
"subfolders break return file_paths def calculate_rms(samples): \"\"\"Given a numpy array",
"not issubclass(y.dtype.type, np.floating): raise ValueError(\"input samples not floating-point\") return (y",
"given filename extensions in a directory. Also traverses subdirectories by",
"signal-to-noise ratio (SNR), calculate the desired RMS of a noise",
"typically somewhere between -20 and 60 :return: \"\"\" a =",
"by default. \"\"\" file_paths = [] for root, dirs, filenames",
"desired RMS of a noise sound to be mixed in.",
"a) return noise_rms def convert_decibels_to_amplitude_ratio(decibels): return 10 ** (decibels /",
":param samples: numpy ndarray :return: \"\"\" return len(spectrogram.shape) > 2",
"ndarray :return: \"\"\" return len(spectrogram.shape) > 2 and spectrogram.shape[-1] >",
"given ndarray a multichannel spectrogram? :param samples: numpy ndarray :return:",
"dB - typically somewhere between -20 and 60 :return: \"\"\"",
"/ 20) def is_waveform_multichannel(samples): \"\"\" Return bool that answers the",
"Given the Root Mean Square (RMS) of a clean sound",
"a multichannel spectrogram? :param samples: numpy ndarray :return: \"\"\" return",
"filename_endings=AUDIO_FILENAME_ENDINGS, traverse_subdirectories=True ): \"\"\"Return a list of paths to all",
"\"\"\"Given a numpy array of audio samples, return its Root",
"Mean Square (RMS) - a value between 0.0 and 1.0",
"snr): \"\"\" Given the Root Mean Square (RMS) of a",
"os.path.join(input_path, filename) if filename.lower().endswith(filename_endings): file_paths.append(Path(file_path)) if not traverse_subdirectories: # prevent",
"files with the given filename extensions in a directory. Also",
"(RMS).\"\"\" return np.sqrt(np.mean(np.square(samples), axis=-1)) def calculate_desired_noise_rms(clean_rms, snr): \"\"\" Given the",
"def convert_decibels_to_amplitude_ratio(decibels): return 10 ** (decibels / 20) def is_waveform_multichannel(samples):",
"np.sqrt(np.mean(np.square(samples), axis=-1)) def calculate_desired_noise_rms(clean_rms, snr): \"\"\" Given the Root Mean",
"question: Is the given ndarray a multichannel spectrogram? :param samples:",
"numpy array of audio samples to int16.\"\"\" if not issubclass(y.dtype.type,",
"numpy as np AUDIO_FILENAME_ENDINGS = (\".aiff\", \".flac\", \".m4a\", \".mp3\", \".ogg\",",
"between -20 and 60 :return: \"\"\" a = float(snr) /",
"convert_float_samples_to_int16(y): \"\"\"Convert floating-point numpy array of audio samples to int16.\"\"\"",
"ndarray a multichannel spectrogram? :param samples: numpy ndarray :return: \"\"\"",
"if filename.lower().endswith(filename_endings): file_paths.append(Path(file_path)) if not traverse_subdirectories: # prevent descending into",
"> 1 def convert_float_samples_to_int16(y): \"\"\"Convert floating-point numpy array of audio",
"answers the question: Is the given ndarray a multichannel spectrogram?",
"not? :param samples: numpy ndarray :return: \"\"\" return len(samples.shape) >",
"to int16.\"\"\" if not issubclass(y.dtype.type, np.floating): raise ValueError(\"input samples not",
"def is_waveform_multichannel(samples): \"\"\" Return bool that answers the question: Is",
"descending into subfolders break return file_paths def calculate_rms(samples): \"\"\"Given a",
"** (decibels / 20) def is_waveform_multichannel(samples): \"\"\" Return bool that",
"Signal-to-Noise (SNR) Ratio in dB - typically somewhere between -20",
"into subfolders break return file_paths def calculate_rms(samples): \"\"\"Given a numpy",
"** a) return noise_rms def convert_decibels_to_amplitude_ratio(decibels): return 10 ** (decibels",
"bool that answers the question: Is the given ndarray a",
"1 def convert_float_samples_to_int16(y): \"\"\"Convert floating-point numpy array of audio samples",
"ndarray :return: \"\"\" return len(samples.shape) > 1 def is_spectrogram_multichannel(spectrogram): \"\"\"",
"a = float(snr) / 20 noise_rms = clean_rms / (10",
"floating-point numpy array of audio samples to int16.\"\"\" if not",
"import Path import numpy as np AUDIO_FILENAME_ENDINGS = (\".aiff\", \".flac\",",
"sorted(filenames) for filename in filenames: input_path = os.path.abspath(root) file_path =",
"the Root Mean Square (RMS) of a clean sound and",
"a directory. Also traverses subdirectories by default. \"\"\" file_paths =",
"Mean Square (RMS).\"\"\" return np.sqrt(np.mean(np.square(samples), axis=-1)) def calculate_desired_noise_rms(clean_rms, snr): \"\"\"",
"return its Root Mean Square (RMS).\"\"\" return np.sqrt(np.mean(np.square(samples), axis=-1)) def",
"return np.sqrt(np.mean(np.square(samples), axis=-1)) def calculate_desired_noise_rms(clean_rms, snr): \"\"\" Given the Root",
"-20 and 60 :return: \"\"\" a = float(snr) / 20",
"file_paths def calculate_rms(samples): \"\"\"Given a numpy array of audio samples,",
"= clean_rms / (10 ** a) return noise_rms def convert_decibels_to_amplitude_ratio(decibels):",
"= (\".aiff\", \".flac\", \".m4a\", \".mp3\", \".ogg\", \".opus\", \".wav\") def get_file_paths(",
"= [] for root, dirs, filenames in os.walk(root_path): filenames =",
"Return bool that answers the question: Is the given ndarray",
"paths to all files with the given filename extensions in",
"os.walk(root_path): filenames = sorted(filenames) for filename in filenames: input_path =",
"spectrogram? :param samples: numpy ndarray :return: \"\"\" return len(spectrogram.shape) >",
"np.floating): raise ValueError(\"input samples not floating-point\") return (y * np.iinfo(np.int16).max).astype(np.int16)",
"samples, return its Root Mean Square (RMS).\"\"\" return np.sqrt(np.mean(np.square(samples), axis=-1))",
"(\".aiff\", \".flac\", \".m4a\", \".mp3\", \".ogg\", \".opus\", \".wav\") def get_file_paths( root_path,",
"root_path, filename_endings=AUDIO_FILENAME_ENDINGS, traverse_subdirectories=True ): \"\"\"Return a list of paths to",
"\"\"\" file_paths = [] for root, dirs, filenames in os.walk(root_path):",
"of audio samples, return its Root Mean Square (RMS).\"\"\" return",
"Square (RMS) - a value between 0.0 and 1.0 :param",
"is_spectrogram_multichannel(spectrogram): \"\"\" Return bool that answers the question: Is the",
"question: Is the given ndarray a multichannel waveform or not?",
"[] for root, dirs, filenames in os.walk(root_path): filenames = sorted(filenames)",
"axis=-1)) def calculate_desired_noise_rms(clean_rms, snr): \"\"\" Given the Root Mean Square",
"noise_rms = clean_rms / (10 ** a) return noise_rms def",
"multichannel waveform or not? :param samples: numpy ndarray :return: \"\"\"",
"AUDIO_FILENAME_ENDINGS = (\".aiff\", \".flac\", \".m4a\", \".mp3\", \".ogg\", \".opus\", \".wav\") def",
"(decibels / 20) def is_waveform_multichannel(samples): \"\"\" Return bool that answers",
"0.0 and 1.0 :param snr: Signal-to-Noise (SNR) Ratio in dB",
"file_paths.append(Path(file_path)) if not traverse_subdirectories: # prevent descending into subfolders break",
"get_file_paths( root_path, filename_endings=AUDIO_FILENAME_ENDINGS, traverse_subdirectories=True ): \"\"\"Return a list of paths",
"clean sound and a desired signal-to-noise ratio (SNR), calculate the",
"def get_file_paths( root_path, filename_endings=AUDIO_FILENAME_ENDINGS, traverse_subdirectories=True ): \"\"\"Return a list of",
"value between 0.0 and 1.0 :param snr: Signal-to-Noise (SNR) Ratio",
"(RMS) - a value between 0.0 and 1.0 :param snr:",
"subdirectories by default. \"\"\" file_paths = [] for root, dirs,",
"\".wav\") def get_file_paths( root_path, filename_endings=AUDIO_FILENAME_ENDINGS, traverse_subdirectories=True ): \"\"\"Return a list",
"def is_spectrogram_multichannel(spectrogram): \"\"\" Return bool that answers the question: Is",
"1 def is_spectrogram_multichannel(spectrogram): \"\"\" Return bool that answers the question:",
"samples: numpy ndarray :return: \"\"\" return len(spectrogram.shape) > 2 and",
"desired signal-to-noise ratio (SNR), calculate the desired RMS of a",
"= sorted(filenames) for filename in filenames: input_path = os.path.abspath(root) file_path",
"filename in filenames: input_path = os.path.abspath(root) file_path = os.path.join(input_path, filename)",
"RMS of a noise sound to be mixed in. Based",
"to be mixed in. Based on https://github.com/Sato-Kunihiko/audio-SNR/blob/8d2c933b6c0afe6f1203251f4877e7a1068a6130/create_mixed_audio_file.py#L20 :param clean_rms: Root",
"clean_rms / (10 ** a) return noise_rms def convert_decibels_to_amplitude_ratio(decibels): return",
"- a value between 0.0 and 1.0 :param snr: Signal-to-Noise",
"and 60 :return: \"\"\" a = float(snr) / 20 noise_rms",
"that answers the question: Is the given ndarray a multichannel",
"noise_rms def convert_decibels_to_amplitude_ratio(decibels): return 10 ** (decibels / 20) def",
"): \"\"\"Return a list of paths to all files with",
"10 ** (decibels / 20) def is_waveform_multichannel(samples): \"\"\" Return bool",
"filename) if filename.lower().endswith(filename_endings): file_paths.append(Path(file_path)) if not traverse_subdirectories: # prevent descending",
"not traverse_subdirectories: # prevent descending into subfolders break return file_paths",
"a desired signal-to-noise ratio (SNR), calculate the desired RMS of",
"os.path.abspath(root) file_path = os.path.join(input_path, filename) if filename.lower().endswith(filename_endings): file_paths.append(Path(file_path)) if not",
"in dB - typically somewhere between -20 and 60 :return:",
"and spectrogram.shape[-1] > 1 def convert_float_samples_to_int16(y): \"\"\"Convert floating-point numpy array",
"numpy array of audio samples, return its Root Mean Square",
"for root, dirs, filenames in os.walk(root_path): filenames = sorted(filenames) for",
"Square (RMS).\"\"\" return np.sqrt(np.mean(np.square(samples), axis=-1)) def calculate_desired_noise_rms(clean_rms, snr): \"\"\" Given",
"a value between 0.0 and 1.0 :param snr: Signal-to-Noise (SNR)",
":param snr: Signal-to-Noise (SNR) Ratio in dB - typically somewhere",
"ratio (SNR), calculate the desired RMS of a noise sound",
"60 :return: \"\"\" a = float(snr) / 20 noise_rms =",
"os from pathlib import Path import numpy as np AUDIO_FILENAME_ENDINGS",
"1.0 :param snr: Signal-to-Noise (SNR) Ratio in dB - typically",
"audio samples, return its Root Mean Square (RMS).\"\"\" return np.sqrt(np.mean(np.square(samples),",
"- typically somewhere between -20 and 60 :return: \"\"\" a",
"a clean sound and a desired signal-to-noise ratio (SNR), calculate",
"20) def is_waveform_multichannel(samples): \"\"\" Return bool that answers the question:",
"from pathlib import Path import numpy as np AUDIO_FILENAME_ENDINGS =",
"if not traverse_subdirectories: # prevent descending into subfolders break return",
"array of audio samples to int16.\"\"\" if not issubclass(y.dtype.type, np.floating):",
"samples to int16.\"\"\" if not issubclass(y.dtype.type, np.floating): raise ValueError(\"input samples",
"def calculate_rms(samples): \"\"\"Given a numpy array of audio samples, return",
":param clean_rms: Root Mean Square (RMS) - a value between",
"filename.lower().endswith(filename_endings): file_paths.append(Path(file_path)) if not traverse_subdirectories: # prevent descending into subfolders",
"> 2 and spectrogram.shape[-1] > 1 def convert_float_samples_to_int16(y): \"\"\"Convert floating-point",
"list of paths to all files with the given filename",
"20 noise_rms = clean_rms / (10 ** a) return noise_rms",
"sound and a desired signal-to-noise ratio (SNR), calculate the desired",
"in a directory. Also traverses subdirectories by default. \"\"\" file_paths",
"/ (10 ** a) return noise_rms def convert_decibels_to_amplitude_ratio(decibels): return 10",
"\".flac\", \".m4a\", \".mp3\", \".ogg\", \".opus\", \".wav\") def get_file_paths( root_path, filename_endings=AUDIO_FILENAME_ENDINGS,",
"of a noise sound to be mixed in. Based on",
"as np AUDIO_FILENAME_ENDINGS = (\".aiff\", \".flac\", \".m4a\", \".mp3\", \".ogg\", \".opus\",",
"pathlib import Path import numpy as np AUDIO_FILENAME_ENDINGS = (\".aiff\",",
"(10 ** a) return noise_rms def convert_decibels_to_amplitude_ratio(decibels): return 10 **",
"https://github.com/Sato-Kunihiko/audio-SNR/blob/8d2c933b6c0afe6f1203251f4877e7a1068a6130/create_mixed_audio_file.py#L20 :param clean_rms: Root Mean Square (RMS) - a value",
"2 and spectrogram.shape[-1] > 1 def convert_float_samples_to_int16(y): \"\"\"Convert floating-point numpy",
"= float(snr) / 20 noise_rms = clean_rms / (10 **",
"import numpy as np AUDIO_FILENAME_ENDINGS = (\".aiff\", \".flac\", \".m4a\", \".mp3\",",
"clean_rms: Root Mean Square (RMS) - a value between 0.0",
"Path import numpy as np AUDIO_FILENAME_ENDINGS = (\".aiff\", \".flac\", \".m4a\",",
"Root Mean Square (RMS) of a clean sound and a",
"the question: Is the given ndarray a multichannel spectrogram? :param",
"for filename in filenames: input_path = os.path.abspath(root) file_path = os.path.join(input_path,",
"mixed in. Based on https://github.com/Sato-Kunihiko/audio-SNR/blob/8d2c933b6c0afe6f1203251f4877e7a1068a6130/create_mixed_audio_file.py#L20 :param clean_rms: Root Mean Square",
":return: \"\"\" return len(spectrogram.shape) > 2 and spectrogram.shape[-1] > 1",
"calculate_rms(samples): \"\"\"Given a numpy array of audio samples, return its",
"filename extensions in a directory. Also traverses subdirectories by default.",
"filenames: input_path = os.path.abspath(root) file_path = os.path.join(input_path, filename) if filename.lower().endswith(filename_endings):",
"def calculate_desired_noise_rms(clean_rms, snr): \"\"\" Given the Root Mean Square (RMS)",
"import os from pathlib import Path import numpy as np",
"(RMS) of a clean sound and a desired signal-to-noise ratio",
"file_path = os.path.join(input_path, filename) if filename.lower().endswith(filename_endings): file_paths.append(Path(file_path)) if not traverse_subdirectories:",
"in filenames: input_path = os.path.abspath(root) file_path = os.path.join(input_path, filename) if",
"Root Mean Square (RMS).\"\"\" return np.sqrt(np.mean(np.square(samples), axis=-1)) def calculate_desired_noise_rms(clean_rms, snr):",
"\".ogg\", \".opus\", \".wav\") def get_file_paths( root_path, filename_endings=AUDIO_FILENAME_ENDINGS, traverse_subdirectories=True ): \"\"\"Return",
"convert_decibels_to_amplitude_ratio(decibels): return 10 ** (decibels / 20) def is_waveform_multichannel(samples): \"\"\"",
"break return file_paths def calculate_rms(samples): \"\"\"Given a numpy array of",
"\"\"\" Return bool that answers the question: Is the given",
"\"\"\"Convert floating-point numpy array of audio samples to int16.\"\"\" if",
"return len(spectrogram.shape) > 2 and spectrogram.shape[-1] > 1 def convert_float_samples_to_int16(y):",
"multichannel spectrogram? :param samples: numpy ndarray :return: \"\"\" return len(spectrogram.shape)",
"spectrogram.shape[-1] > 1 def convert_float_samples_to_int16(y): \"\"\"Convert floating-point numpy array of",
"def convert_float_samples_to_int16(y): \"\"\"Convert floating-point numpy array of audio samples to",
"samples: numpy ndarray :return: \"\"\" return len(samples.shape) > 1 def",
"numpy ndarray :return: \"\"\" return len(samples.shape) > 1 def is_spectrogram_multichannel(spectrogram):",
"the given ndarray a multichannel spectrogram? :param samples: numpy ndarray",
"all files with the given filename extensions in a directory.",
"filenames in os.walk(root_path): filenames = sorted(filenames) for filename in filenames:",
"Ratio in dB - typically somewhere between -20 and 60",
"len(samples.shape) > 1 def is_spectrogram_multichannel(spectrogram): \"\"\" Return bool that answers",
"file_paths = [] for root, dirs, filenames in os.walk(root_path): filenames",
"> 1 def is_spectrogram_multichannel(spectrogram): \"\"\" Return bool that answers the",
"default. \"\"\" file_paths = [] for root, dirs, filenames in",
"array of audio samples, return its Root Mean Square (RMS).\"\"\"",
"/ 20 noise_rms = clean_rms / (10 ** a) return",
"dirs, filenames in os.walk(root_path): filenames = sorted(filenames) for filename in",
"and 1.0 :param snr: Signal-to-Noise (SNR) Ratio in dB -",
"return file_paths def calculate_rms(samples): \"\"\"Given a numpy array of audio",
"prevent descending into subfolders break return file_paths def calculate_rms(samples): \"\"\"Given",
"between 0.0 and 1.0 :param snr: Signal-to-Noise (SNR) Ratio in",
"calculate_desired_noise_rms(clean_rms, snr): \"\"\" Given the Root Mean Square (RMS) of",
"numpy ndarray :return: \"\"\" return len(spectrogram.shape) > 2 and spectrogram.shape[-1]",
"with the given filename extensions in a directory. Also traverses",
"\".opus\", \".wav\") def get_file_paths( root_path, filename_endings=AUDIO_FILENAME_ENDINGS, traverse_subdirectories=True ): \"\"\"Return a",
"extensions in a directory. Also traverses subdirectories by default. \"\"\"",
"a noise sound to be mixed in. Based on https://github.com/Sato-Kunihiko/audio-SNR/blob/8d2c933b6c0afe6f1203251f4877e7a1068a6130/create_mixed_audio_file.py#L20",
"the given filename extensions in a directory. Also traverses subdirectories",
"given ndarray a multichannel waveform or not? :param samples: numpy",
"issubclass(y.dtype.type, np.floating): raise ValueError(\"input samples not floating-point\") return (y *",
"the given ndarray a multichannel waveform or not? :param samples:",
"traverse_subdirectories=True ): \"\"\"Return a list of paths to all files",
"input_path = os.path.abspath(root) file_path = os.path.join(input_path, filename) if filename.lower().endswith(filename_endings): file_paths.append(Path(file_path))",
"a numpy array of audio samples, return its Root Mean",
"Is the given ndarray a multichannel waveform or not? :param",
"(SNR), calculate the desired RMS of a noise sound to",
"if not issubclass(y.dtype.type, np.floating): raise ValueError(\"input samples not floating-point\") return",
"\".mp3\", \".ogg\", \".opus\", \".wav\") def get_file_paths( root_path, filename_endings=AUDIO_FILENAME_ENDINGS, traverse_subdirectories=True ):",
"to all files with the given filename extensions in a",
"noise sound to be mixed in. Based on https://github.com/Sato-Kunihiko/audio-SNR/blob/8d2c933b6c0afe6f1203251f4877e7a1068a6130/create_mixed_audio_file.py#L20 :param",
"its Root Mean Square (RMS).\"\"\" return np.sqrt(np.mean(np.square(samples), axis=-1)) def calculate_desired_noise_rms(clean_rms,",
"\"\"\"Return a list of paths to all files with the",
"somewhere between -20 and 60 :return: \"\"\" a = float(snr)",
"on https://github.com/Sato-Kunihiko/audio-SNR/blob/8d2c933b6c0afe6f1203251f4877e7a1068a6130/create_mixed_audio_file.py#L20 :param clean_rms: Root Mean Square (RMS) - a",
"\"\"\" a = float(snr) / 20 noise_rms = clean_rms /",
":return: \"\"\" a = float(snr) / 20 noise_rms = clean_rms",
"Is the given ndarray a multichannel spectrogram? :param samples: numpy",
"Root Mean Square (RMS) - a value between 0.0 and",
":return: \"\"\" return len(samples.shape) > 1 def is_spectrogram_multichannel(spectrogram): \"\"\" Return",
"or not? :param samples: numpy ndarray :return: \"\"\" return len(samples.shape)",
"of audio samples to int16.\"\"\" if not issubclass(y.dtype.type, np.floating): raise",
"waveform or not? :param samples: numpy ndarray :return: \"\"\" return",
"\"\"\" return len(samples.shape) > 1 def is_spectrogram_multichannel(spectrogram): \"\"\" Return bool",
"\"\"\" return len(spectrogram.shape) > 2 and spectrogram.shape[-1] > 1 def",
"answers the question: Is the given ndarray a multichannel waveform",
"len(spectrogram.shape) > 2 and spectrogram.shape[-1] > 1 def convert_float_samples_to_int16(y): \"\"\"Convert",
"the desired RMS of a noise sound to be mixed",
"np AUDIO_FILENAME_ENDINGS = (\".aiff\", \".flac\", \".m4a\", \".mp3\", \".ogg\", \".opus\", \".wav\")",
"\"\"\" Given the Root Mean Square (RMS) of a clean",
"and a desired signal-to-noise ratio (SNR), calculate the desired RMS"
] |
[
"if stack[-1] == \"{\": stack.pop() else: print(False) exit() if len(stack)",
"len(stack) < 1: print(False) exit() if stack[-1] == \"(\": stack.pop()",
"else: print(False) exit() if len(stack) == 0: print(True) else: print(False)",
"stack.pop() else: print(False) exit() elif i == \"]\": if len(stack)",
"2 == 1: print(False) exit() for i in s: if",
"\"[\": stack.pop() else: print(False) exit() elif i == \"}\": if",
"elif i == \"]\": if len(stack) < 1: print(False) exit()",
"if len(s) % 2 == 1: print(False) exit() for i",
"== 1: print(False) exit() for i in s: if i",
"in s: if i == \"(\": stack.append(\"(\") elif i ==",
"% 2 == 1: print(False) exit() for i in s:",
"stack[-1] == \"(\": stack.pop() else: print(False) exit() elif i ==",
"print(False) exit() if stack[-1] == \"(\": stack.pop() else: print(False) exit()",
"for i in s: if i == \"(\": stack.append(\"(\") elif",
"exit() elif i == \"}\": if len(stack) < 1: print(False)",
"1: print(False) exit() if stack[-1] == \"[\": stack.pop() else: print(False)",
"\"{\": stack.pop() else: print(False) exit() if len(stack) == 0: print(True)",
"1: print(False) exit() for i in s: if i ==",
"< 1: print(False) exit() if stack[-1] == \"(\": stack.pop() else:",
"\"]\": if len(stack) < 1: print(False) exit() if stack[-1] ==",
"exit() if stack[-1] == \"[\": stack.pop() else: print(False) exit() elif",
"1: print(False) exit() if stack[-1] == \"(\": stack.pop() else: print(False)",
"\"([}}])\" stack = [] if len(s) % 2 == 1:",
"print(False) exit() elif i == \"]\": if len(stack) < 1:",
"i == \"]\": if len(stack) < 1: print(False) exit() if",
"\"{\": stack.append(\"{\") elif i == \")\": if len(stack) < 1:",
"i == \"[\": stack.append(\"[\") elif i == \"{\": stack.append(\"{\") elif",
"elif i == \"{\": stack.append(\"{\") elif i == \")\": if",
"exit() for i in s: if i == \"(\": stack.append(\"(\")",
"1: print(False) exit() if stack[-1] == \"{\": stack.pop() else: print(False)",
"if len(stack) < 1: print(False) exit() if stack[-1] == \"(\":",
"== \"{\": stack.pop() else: print(False) exit() if len(stack) == 0:",
"stack[-1] == \"[\": stack.pop() else: print(False) exit() elif i ==",
"i in s: if i == \"(\": stack.append(\"(\") elif i",
"print(False) exit() elif i == \"}\": if len(stack) < 1:",
"[] if len(s) % 2 == 1: print(False) exit() for",
"i == \"{\": stack.append(\"{\") elif i == \")\": if len(stack)",
"s: if i == \"(\": stack.append(\"(\") elif i == \"[\":",
"len(s) % 2 == 1: print(False) exit() for i in",
"== \"(\": stack.append(\"(\") elif i == \"[\": stack.append(\"[\") elif i",
"if len(stack) < 1: print(False) exit() if stack[-1] == \"{\":",
"stack.append(\"(\") elif i == \"[\": stack.append(\"[\") elif i == \"{\":",
"== \"[\": stack.append(\"[\") elif i == \"{\": stack.append(\"{\") elif i",
"== \"{\": stack.append(\"{\") elif i == \")\": if len(stack) <",
"len(stack) < 1: print(False) exit() if stack[-1] == \"{\": stack.pop()",
"\"[\": stack.append(\"[\") elif i == \"{\": stack.append(\"{\") elif i ==",
"== \"]\": if len(stack) < 1: print(False) exit() if stack[-1]",
"stack[-1] == \"{\": stack.pop() else: print(False) exit() if len(stack) ==",
"if len(stack) < 1: print(False) exit() if stack[-1] == \"[\":",
"elif i == \")\": if len(stack) < 1: print(False) exit()",
"elif i == \"}\": if len(stack) < 1: print(False) exit()",
"stack.append(\"{\") elif i == \")\": if len(stack) < 1: print(False)",
"\"(\": stack.pop() else: print(False) exit() elif i == \"]\": if",
"\"(\": stack.append(\"(\") elif i == \"[\": stack.append(\"[\") elif i ==",
"i == \"}\": if len(stack) < 1: print(False) exit() if",
"i == \")\": if len(stack) < 1: print(False) exit() if",
"print(False) exit() if stack[-1] == \"[\": stack.pop() else: print(False) exit()",
"print(False) exit() if stack[-1] == \"{\": stack.pop() else: print(False) exit()",
"<reponame>HoneyS2/meaningful s = \"([}}])\" stack = [] if len(s) %",
"len(stack) < 1: print(False) exit() if stack[-1] == \"[\": stack.pop()",
"< 1: print(False) exit() if stack[-1] == \"[\": stack.pop() else:",
"i == \"(\": stack.append(\"(\") elif i == \"[\": stack.append(\"[\") elif",
"exit() if stack[-1] == \"{\": stack.pop() else: print(False) exit() if",
"print(False) exit() for i in s: if i == \"(\":",
"< 1: print(False) exit() if stack[-1] == \"{\": stack.pop() else:",
"else: print(False) exit() elif i == \"]\": if len(stack) <",
"== \"}\": if len(stack) < 1: print(False) exit() if stack[-1]",
"= \"([}}])\" stack = [] if len(s) % 2 ==",
"exit() if stack[-1] == \"(\": stack.pop() else: print(False) exit() elif",
"if stack[-1] == \"[\": stack.pop() else: print(False) exit() elif i",
"elif i == \"[\": stack.append(\"[\") elif i == \"{\": stack.append(\"{\")",
"s = \"([}}])\" stack = [] if len(s) % 2",
"== \"[\": stack.pop() else: print(False) exit() elif i == \"}\":",
"else: print(False) exit() elif i == \"}\": if len(stack) <",
"== \"(\": stack.pop() else: print(False) exit() elif i == \"]\":",
"\")\": if len(stack) < 1: print(False) exit() if stack[-1] ==",
"stack = [] if len(s) % 2 == 1: print(False)",
"if stack[-1] == \"(\": stack.pop() else: print(False) exit() elif i",
"== \")\": if len(stack) < 1: print(False) exit() if stack[-1]",
"stack.pop() else: print(False) exit() elif i == \"}\": if len(stack)",
"= [] if len(s) % 2 == 1: print(False) exit()",
"stack.pop() else: print(False) exit() if len(stack) == 0: print(True) else:",
"\"}\": if len(stack) < 1: print(False) exit() if stack[-1] ==",
"stack.append(\"[\") elif i == \"{\": stack.append(\"{\") elif i == \")\":",
"if i == \"(\": stack.append(\"(\") elif i == \"[\": stack.append(\"[\")",
"exit() elif i == \"]\": if len(stack) < 1: print(False)"
] |
[
"display(HTML(html)) def render_content(self, key): data = self.content.get(key) id = JupyterSlides.randomUUID()",
"= self.base_template_dir html = html_loader( f'file:{template_dir}/{template}.html') if render_type == 'slide':",
"}}\" class=\"slide-container\">' + \\ html + '</div>' tm = Template(html)",
"= {} items = [] for _, item in self.content.items():",
") if os.path.isfile(f'{self.template_dir}/init.html'): self.render( template=f'init', data=self.content.get('init_vars', {}) ) id =",
") html += navigation_template display(HTML(html)) def render_content(self, key): data =",
"random import string import os from IPython.display import display, HTML",
"+ \\ html + '</div>' tm = Template(html) return tm.render(data=data)",
"random string of fixed length \"\"\" letters = string.ascii_lowercase return",
"import string import os from IPython.display import display, HTML from",
"item['slides'][0]['slide_id'] items.append(item) table['title'] = 'Table of Contents' table['eyebrow'] = 'Table",
"folders = self.called_from_path.split('/') self.source_path = '/'.join(folders[:folders.index('talks')]) self.template_dir = f'{self.source_path}/src/templates' self.css_dir",
"navigation=False, template_dir=None, render_type=None): html = self.parse_template( template=template, data=data, template_dir=template_dir, render_type=render_type",
"\"\"\" letters = string.ascii_lowercase return ''.join(random.choice(letters) for i in range(stringLength))",
"template_dir = self.base_template_dir html = html_loader( f'file:{template_dir}/{template}.html') if render_type ==",
"= f'{self.source_path}/src/templates' self.css_dir = f'{self.source_path}/src/css' self.js_dir = f'{self.source_path}/src/js' def render_init_templates(self):",
"'basic-slide' html = html_loader(f'file:{self.base_template_dir}/{template}.html') else: if not os.path.isfile(f'{template_dir}/{template}.html'): template =",
"self.render( template='table-contents', data=self.generate_table_contents(), template_dir=contents_template_dir, render_type='slide' ) def parse_template(self, template=None, data={},",
"JupyterSlides.randomUUID() self.render( template='eye', data={'eye_id': id}, template_dir=self.base_template_dir ) def render_table_contents(self): if",
"html = self.parse_template( template=template, data=data, template_dir=template_dir, render_type=render_type ) if navigation:",
"def set_source_dirs(self): self.called_from_path = os.getcwd() folders = self.called_from_path.split('/') self.source_path =",
"= self.content.get(key) id = JupyterSlides.randomUUID() self.render( template='eye', data={'eye_id': id}, template_dir=self.base_template_dir",
"= 'Table of Contents' table['eyebrow'] = 'Table of Contents' table['items']",
"table_contents=False ): self.set_base_dirs() self.set_source_dirs() self.content = get_content(content_path) self.render_init_templates() if table_contents:",
"if table_contents: self.render_table_contents() def set_base_dirs(self): self.module_path = os.path.dirname(os.path.realpath(__file__)) self.base_template_dir =",
"data={'dir': self.module_path}, template_dir=self.base_template_dir ) if os.path.isfile(f'{self.template_dir}/init.html'): self.render( template=f'init', data=self.content.get('init_vars', {})",
"self.render(template=template, data=el, render_type='slide') @staticmethod def randomUUID(stringLength=20): \"\"\"Generate a random string",
"self.content.items(): for sub_item in item['slides']: sub_item['slide_id'] = \\ str(item['indice']) +",
"sub_item['content_title'] item['slide_id'] = item['slides'][0]['slide_id'] items.append(item) table['title'] = 'Table of Contents'",
"'Table of Contents' table['eyebrow'] = 'Table of Contents' table['items'] =",
"= f'{self.module_path}/src/assets/css' self.base_js_dir = f'{self.module_path}/src/js' def set_source_dirs(self): self.called_from_path = os.getcwd()",
"id}, template_dir=self.base_template_dir ) def render_table_contents(self): if os.path.isfile(f'{self.template_dir}/table-contents.html'): contents_template_dir = self.template_dir",
"from jinja2 import Template class JupyterSlides: def __init__( self, content_path='./content.yaml',",
"from .utils import get_content from jinja2 import Template class JupyterSlides:",
"el.get('template') self.render(template=template, data=el, render_type='slide') @staticmethod def randomUUID(stringLength=20): \"\"\"Generate a random",
"self.js_dir = f'{self.source_path}/src/js' def render_init_templates(self): self.render( template='init', data={'dir': self.module_path}, template_dir=self.base_template_dir",
"if os.path.isfile(f'{self.template_dir}/init.html'): self.render( template=f'init', data=self.content.get('init_vars', {}) ) id = JupyterSlides.randomUUID()",
"__init__( self, content_path='./content.yaml', table_contents=False ): self.set_base_dirs() self.set_source_dirs() self.content = get_content(content_path)",
"'<div id=\"{{ data[\"slide_id\"] }}\" class=\"slide-container\">' + \\ html + '</div>'",
"str(item['indice']) + '.' + str(sub_item['indice']) +\\ sub_item['content_title'] item['slide_id'] = item['slides'][0]['slide_id']",
"self.base_css_dir = f'{self.module_path}/src/assets/css' self.base_js_dir = f'{self.module_path}/src/js' def set_source_dirs(self): self.called_from_path =",
"self.render( template='init', data={'dir': self.module_path}, template_dir=self.base_template_dir ) if os.path.isfile(f'{self.template_dir}/init.html'): self.render( template=f'init',",
"template_dir=None, render_type=None): html = self.parse_template( template=template, data=data, template_dir=template_dir, render_type=render_type )",
"self.content.get(key) id = JupyterSlides.randomUUID() self.render( template='eye', data={'eye_id': id}, template_dir=self.base_template_dir )",
"'.' + str(sub_item['indice']) +\\ sub_item['content_title'] item['slide_id'] = item['slides'][0]['slide_id'] items.append(item) table['title']",
"else: if not os.path.isfile(f'{template_dir}/{template}.html'): template = 'basic-slide' template_dir = self.base_template_dir",
"self.set_source_dirs() self.content = get_content(content_path) self.render_init_templates() if table_contents: self.render_table_contents() def set_base_dirs(self):",
"template_dir=self.base_template_dir ) if os.path.isfile(f'{self.template_dir}/init.html'): self.render( template=f'init', data=self.content.get('init_vars', {}) ) id",
"f'{self.source_path}/src/templates' self.css_dir = f'{self.source_path}/src/css' self.js_dir = f'{self.source_path}/src/js' def render_init_templates(self): self.render(",
"def generate_table_contents(self): table = {} items = [] for _,",
"_, item in self.content.items(): for sub_item in item['slides']: sub_item['slide_id'] =",
"os from IPython.display import display, HTML from .utils import html_loader",
"data={'eye_id': id}, template_dir=self.base_template_dir ) def render_table_contents(self): if os.path.isfile(f'{self.template_dir}/table-contents.html'): contents_template_dir =",
"html_loader from .utils import get_content from jinja2 import Template class",
".utils import get_content from jinja2 import Template class JupyterSlides: def",
"else: contents_template_dir = self.base_template_dir self.render( template='table-contents', data=self.generate_table_contents(), template_dir=contents_template_dir, render_type='slide' )",
"not template_dir: if os.path.isfile(f'{self.template_dir}/{template}.html'): html = html_loader(f'file:{self.template_dir}/{template}.html') else: template =",
") if navigation: navigation_template = self.parse_template( template='navigation', template_dir=template_dir ) html",
"a random string of fixed length \"\"\" letters = string.ascii_lowercase",
"def render_init_templates(self): self.render( template='init', data={'dir': self.module_path}, template_dir=self.base_template_dir ) if os.path.isfile(f'{self.template_dir}/init.html'):",
"id = JupyterSlides.randomUUID() self.render( template='eye', data={'eye_id': id}, template_dir=self.base_template_dir ) def",
"def set_base_dirs(self): self.module_path = os.path.dirname(os.path.realpath(__file__)) self.base_template_dir = f'{self.module_path}/src/templates' self.base_css_dir =",
"render_type=None): if not template_dir: if os.path.isfile(f'{self.template_dir}/{template}.html'): html = html_loader(f'file:{self.template_dir}/{template}.html') else:",
"contents_template_dir = self.template_dir else: contents_template_dir = self.base_template_dir self.render( template='table-contents', data=self.generate_table_contents(),",
"render_type='slide') @staticmethod def randomUUID(stringLength=20): \"\"\"Generate a random string of fixed",
"in self.content.items(): for sub_item in item['slides']: sub_item['slide_id'] = \\ str(item['indice'])",
"): self.set_base_dirs() self.set_source_dirs() self.content = get_content(content_path) self.render_init_templates() if table_contents: self.render_table_contents()",
"render_table_contents(self): if os.path.isfile(f'{self.template_dir}/table-contents.html'): contents_template_dir = self.template_dir else: contents_template_dir = self.base_template_dir",
"for el in data.get('slides'): template = el.get('template') self.render(template=template, data=el, render_type='slide')",
"data=data, template_dir=template_dir, render_type=render_type ) if navigation: navigation_template = self.parse_template( template='navigation',",
"html = html_loader(f'file:{self.base_template_dir}/{template}.html') else: if not os.path.isfile(f'{template_dir}/{template}.html'): template = 'basic-slide'",
"self.render_table_contents() def set_base_dirs(self): self.module_path = os.path.dirname(os.path.realpath(__file__)) self.base_template_dir = f'{self.module_path}/src/templates' self.base_css_dir",
"if not os.path.isfile(f'{template_dir}/{template}.html'): template = 'basic-slide' template_dir = self.base_template_dir html",
"self.base_template_dir = f'{self.module_path}/src/templates' self.base_css_dir = f'{self.module_path}/src/assets/css' self.base_js_dir = f'{self.module_path}/src/js' def",
"self.render_init_templates() if table_contents: self.render_table_contents() def set_base_dirs(self): self.module_path = os.path.dirname(os.path.realpath(__file__)) self.base_template_dir",
"key): data = self.content.get(key) id = JupyterSlides.randomUUID() self.render( template='eye', data={'eye_id':",
"navigation: navigation_template = self.parse_template( template='navigation', template_dir=template_dir ) html += navigation_template",
"of fixed length \"\"\" letters = string.ascii_lowercase return ''.join(random.choice(letters) for",
"= el.get('template') self.render(template=template, data=el, render_type='slide') @staticmethod def randomUUID(stringLength=20): \"\"\"Generate a",
") id = JupyterSlides.randomUUID() self.render( template='eye', data={'eye_id': id}, template_dir=self.base_template_dir )",
"in data.get('slides'): template = el.get('template') self.render(template=template, data=el, render_type='slide') @staticmethod def",
"import html_loader from .utils import get_content from jinja2 import Template",
"self.module_path = os.path.dirname(os.path.realpath(__file__)) self.base_template_dir = f'{self.module_path}/src/templates' self.base_css_dir = f'{self.module_path}/src/assets/css' self.base_js_dir",
"os.path.isfile(f'{self.template_dir}/init.html'): self.render( template=f'init', data=self.content.get('init_vars', {}) ) id = JupyterSlides.randomUUID() self.render(",
"of Contents' table['eyebrow'] = 'Table of Contents' table['items'] = items",
"= f'{self.module_path}/src/js' def set_source_dirs(self): self.called_from_path = os.getcwd() folders = self.called_from_path.split('/')",
"data=self.generate_table_contents(), template_dir=contents_template_dir, render_type='slide' ) def parse_template(self, template=None, data={}, template_dir=None, render_type=None):",
"i in range(stringLength)) def generate_table_contents(self): table = {} items =",
"html_loader( f'file:{template_dir}/{template}.html') if render_type == 'slide': html = '<div id=\"{{",
"render_init_templates(self): self.render( template='init', data={'dir': self.module_path}, template_dir=self.base_template_dir ) if os.path.isfile(f'{self.template_dir}/init.html'): self.render(",
"html = html_loader(f'file:{self.template_dir}/{template}.html') else: template = 'basic-slide' html = html_loader(f'file:{self.base_template_dir}/{template}.html')",
"JupyterSlides: def __init__( self, content_path='./content.yaml', table_contents=False ): self.set_base_dirs() self.set_source_dirs() self.content",
"else: template = 'basic-slide' html = html_loader(f'file:{self.base_template_dir}/{template}.html') else: if not",
"item['slide_id'] = item['slides'][0]['slide_id'] items.append(item) table['title'] = 'Table of Contents' table['eyebrow']",
"self.base_template_dir html = html_loader( f'file:{template_dir}/{template}.html') if render_type == 'slide': html",
".utils import html_loader from .utils import get_content from jinja2 import",
"generate_table_contents(self): table = {} items = [] for _, item",
"def __init__( self, content_path='./content.yaml', table_contents=False ): self.set_base_dirs() self.set_source_dirs() self.content =",
"html + '</div>' tm = Template(html) return tm.render(data=data) def render(self,",
"Contents' table['eyebrow'] = 'Table of Contents' table['items'] = items return",
"self.render( template='eye', data={'eye_id': id}, template_dir=self.base_template_dir ) if data.get('slides'): for el",
"self.base_template_dir self.render( template='table-contents', data=self.generate_table_contents(), template_dir=contents_template_dir, render_type='slide' ) def parse_template(self, template=None,",
"Template(html) return tm.render(data=data) def render(self, template=None, data={}, navigation=False, template_dir=None, render_type=None):",
"render_type=None): html = self.parse_template( template=template, data=data, template_dir=template_dir, render_type=render_type ) if",
"@staticmethod def randomUUID(stringLength=20): \"\"\"Generate a random string of fixed length",
"+\\ sub_item['content_title'] item['slide_id'] = item['slides'][0]['slide_id'] items.append(item) table['title'] = 'Table of",
"def randomUUID(stringLength=20): \"\"\"Generate a random string of fixed length \"\"\"",
"= JupyterSlides.randomUUID() self.render( template='eye', data={'eye_id': id}, template_dir=self.base_template_dir ) def render_table_contents(self):",
"self.render( template=f'init', data=self.content.get('init_vars', {}) ) id = JupyterSlides.randomUUID() self.render( template='eye',",
"IPython.display import display, HTML from .utils import html_loader from .utils",
"template=None, data={}, navigation=False, template_dir=None, render_type=None): html = self.parse_template( template=template, data=data,",
"template_dir=None, render_type=None): if not template_dir: if os.path.isfile(f'{self.template_dir}/{template}.html'): html = html_loader(f'file:{self.template_dir}/{template}.html')",
"template = el.get('template') self.render(template=template, data=el, render_type='slide') @staticmethod def randomUUID(stringLength=20): \"\"\"Generate",
"= os.path.dirname(os.path.realpath(__file__)) self.base_template_dir = f'{self.module_path}/src/templates' self.base_css_dir = f'{self.module_path}/src/assets/css' self.base_js_dir =",
"= os.getcwd() folders = self.called_from_path.split('/') self.source_path = '/'.join(folders[:folders.index('talks')]) self.template_dir =",
"= html_loader(f'file:{self.base_template_dir}/{template}.html') else: if not os.path.isfile(f'{template_dir}/{template}.html'): template = 'basic-slide' template_dir",
"content_path='./content.yaml', table_contents=False ): self.set_base_dirs() self.set_source_dirs() self.content = get_content(content_path) self.render_init_templates() if",
"template_dir: if os.path.isfile(f'{self.template_dir}/{template}.html'): html = html_loader(f'file:{self.template_dir}/{template}.html') else: template = 'basic-slide'",
"table['eyebrow'] = 'Table of Contents' table['items'] = items return table",
"template_dir=template_dir, render_type=render_type ) if navigation: navigation_template = self.parse_template( template='navigation', template_dir=template_dir",
"items.append(item) table['title'] = 'Table of Contents' table['eyebrow'] = 'Table of",
"html = html_loader( f'file:{template_dir}/{template}.html') if render_type == 'slide': html =",
"f'{self.module_path}/src/js' def set_source_dirs(self): self.called_from_path = os.getcwd() folders = self.called_from_path.split('/') self.source_path",
"f'{self.source_path}/src/css' self.js_dir = f'{self.source_path}/src/js' def render_init_templates(self): self.render( template='init', data={'dir': self.module_path},",
"template = 'basic-slide' template_dir = self.base_template_dir html = html_loader( f'file:{template_dir}/{template}.html')",
"'</div>' tm = Template(html) return tm.render(data=data) def render(self, template=None, data={},",
"html = '<div id=\"{{ data[\"slide_id\"] }}\" class=\"slide-container\">' + \\ html",
"set_base_dirs(self): self.module_path = os.path.dirname(os.path.realpath(__file__)) self.base_template_dir = f'{self.module_path}/src/templates' self.base_css_dir = f'{self.module_path}/src/assets/css'",
"{} items = [] for _, item in self.content.items(): for",
"from IPython.display import display, HTML from .utils import html_loader from",
"html_loader(f'file:{self.template_dir}/{template}.html') else: template = 'basic-slide' html = html_loader(f'file:{self.base_template_dir}/{template}.html') else: if",
"template='init', data={'dir': self.module_path}, template_dir=self.base_template_dir ) if os.path.isfile(f'{self.template_dir}/init.html'): self.render( template=f'init', data=self.content.get('init_vars',",
"\\ html + '</div>' tm = Template(html) return tm.render(data=data) def",
"+ str(sub_item['indice']) +\\ sub_item['content_title'] item['slide_id'] = item['slides'][0]['slide_id'] items.append(item) table['title'] =",
"template=f'init', data=self.content.get('init_vars', {}) ) id = JupyterSlides.randomUUID() self.render( template='eye', data={'eye_id':",
"self, content_path='./content.yaml', table_contents=False ): self.set_base_dirs() self.set_source_dirs() self.content = get_content(content_path) self.render_init_templates()",
"letters = string.ascii_lowercase return ''.join(random.choice(letters) for i in range(stringLength)) def",
"table['title'] = 'Table of Contents' table['eyebrow'] = 'Table of Contents'",
"= '/'.join(folders[:folders.index('talks')]) self.template_dir = f'{self.source_path}/src/templates' self.css_dir = f'{self.source_path}/src/css' self.js_dir =",
"item in self.content.items(): for sub_item in item['slides']: sub_item['slide_id'] = \\",
"def render_table_contents(self): if os.path.isfile(f'{self.template_dir}/table-contents.html'): contents_template_dir = self.template_dir else: contents_template_dir =",
"parse_template(self, template=None, data={}, template_dir=None, render_type=None): if not template_dir: if os.path.isfile(f'{self.template_dir}/{template}.html'):",
"template_dir=contents_template_dir, render_type='slide' ) def parse_template(self, template=None, data={}, template_dir=None, render_type=None): if",
"contents_template_dir = self.base_template_dir self.render( template='table-contents', data=self.generate_table_contents(), template_dir=contents_template_dir, render_type='slide' ) def",
"for sub_item in item['slides']: sub_item['slide_id'] = \\ str(item['indice']) + '.'",
"jinja2 import Template class JupyterSlides: def __init__( self, content_path='./content.yaml', table_contents=False",
"= f'{self.source_path}/src/js' def render_init_templates(self): self.render( template='init', data={'dir': self.module_path}, template_dir=self.base_template_dir )",
"str(sub_item['indice']) +\\ sub_item['content_title'] item['slide_id'] = item['slides'][0]['slide_id'] items.append(item) table['title'] = 'Table",
"sub_item['slide_id'] = \\ str(item['indice']) + '.' + str(sub_item['indice']) +\\ sub_item['content_title']",
"= 'basic-slide' template_dir = self.base_template_dir html = html_loader( f'file:{template_dir}/{template}.html') if",
"self.render( template='eye', data={'eye_id': id}, template_dir=self.base_template_dir ) def render_table_contents(self): if os.path.isfile(f'{self.template_dir}/table-contents.html'):",
"{}) ) id = JupyterSlides.randomUUID() self.render( template='eye', data={'eye_id': id}, template_dir=self.base_template_dir",
"return tm.render(data=data) def render(self, template=None, data={}, navigation=False, template_dir=None, render_type=None): html",
"if render_type == 'slide': html = '<div id=\"{{ data[\"slide_id\"] }}\"",
"in range(stringLength)) def generate_table_contents(self): table = {} items = []",
"= item['slides'][0]['slide_id'] items.append(item) table['title'] = 'Table of Contents' table['eyebrow'] =",
"f'{self.source_path}/src/js' def render_init_templates(self): self.render( template='init', data={'dir': self.module_path}, template_dir=self.base_template_dir ) if",
"string of fixed length \"\"\" letters = string.ascii_lowercase return ''.join(random.choice(letters)",
"el in data.get('slides'): template = el.get('template') self.render(template=template, data=el, render_type='slide') @staticmethod",
"tm = Template(html) return tm.render(data=data) def render(self, template=None, data={}, navigation=False,",
"fixed length \"\"\" letters = string.ascii_lowercase return ''.join(random.choice(letters) for i",
"for _, item in self.content.items(): for sub_item in item['slides']: sub_item['slide_id']",
"set_source_dirs(self): self.called_from_path = os.getcwd() folders = self.called_from_path.split('/') self.source_path = '/'.join(folders[:folders.index('talks')])",
"self.called_from_path.split('/') self.source_path = '/'.join(folders[:folders.index('talks')]) self.template_dir = f'{self.source_path}/src/templates' self.css_dir = f'{self.source_path}/src/css'",
"get_content from jinja2 import Template class JupyterSlides: def __init__( self,",
"self.parse_template( template='navigation', template_dir=template_dir ) html += navigation_template display(HTML(html)) def render_content(self,",
"def parse_template(self, template=None, data={}, template_dir=None, render_type=None): if not template_dir: if",
"template='navigation', template_dir=template_dir ) html += navigation_template display(HTML(html)) def render_content(self, key):",
"+= navigation_template display(HTML(html)) def render_content(self, key): data = self.content.get(key) id",
"'/'.join(folders[:folders.index('talks')]) self.template_dir = f'{self.source_path}/src/templates' self.css_dir = f'{self.source_path}/src/css' self.js_dir = f'{self.source_path}/src/js'",
"= f'{self.module_path}/src/templates' self.base_css_dir = f'{self.module_path}/src/assets/css' self.base_js_dir = f'{self.module_path}/src/js' def set_source_dirs(self):",
"class JupyterSlides: def __init__( self, content_path='./content.yaml', table_contents=False ): self.set_base_dirs() self.set_source_dirs()",
"''.join(random.choice(letters) for i in range(stringLength)) def generate_table_contents(self): table = {}",
"id=\"{{ data[\"slide_id\"] }}\" class=\"slide-container\">' + \\ html + '</div>' tm",
"data.get('slides'): for el in data.get('slides'): template = el.get('template') self.render(template=template, data=el,",
"Template class JupyterSlides: def __init__( self, content_path='./content.yaml', table_contents=False ): self.set_base_dirs()",
"class=\"slide-container\">' + \\ html + '</div>' tm = Template(html) return",
"os.path.isfile(f'{template_dir}/{template}.html'): template = 'basic-slide' template_dir = self.base_template_dir html = html_loader(",
"f'file:{template_dir}/{template}.html') if render_type == 'slide': html = '<div id=\"{{ data[\"slide_id\"]",
"data.get('slides'): template = el.get('template') self.render(template=template, data=el, render_type='slide') @staticmethod def randomUUID(stringLength=20):",
"id}, template_dir=self.base_template_dir ) if data.get('slides'): for el in data.get('slides'): template",
"= self.called_from_path.split('/') self.source_path = '/'.join(folders[:folders.index('talks')]) self.template_dir = f'{self.source_path}/src/templates' self.css_dir =",
"= get_content(content_path) self.render_init_templates() if table_contents: self.render_table_contents() def set_base_dirs(self): self.module_path =",
"= '<div id=\"{{ data[\"slide_id\"] }}\" class=\"slide-container\">' + \\ html +",
"[] for _, item in self.content.items(): for sub_item in item['slides']:",
"= Template(html) return tm.render(data=data) def render(self, template=None, data={}, navigation=False, template_dir=None,",
"= self.parse_template( template='navigation', template_dir=template_dir ) html += navigation_template display(HTML(html)) def",
"import display, HTML from .utils import html_loader from .utils import",
"= self.base_template_dir self.render( template='table-contents', data=self.generate_table_contents(), template_dir=contents_template_dir, render_type='slide' ) def parse_template(self,",
"string.ascii_lowercase return ''.join(random.choice(letters) for i in range(stringLength)) def generate_table_contents(self): table",
"self.template_dir = f'{self.source_path}/src/templates' self.css_dir = f'{self.source_path}/src/css' self.js_dir = f'{self.source_path}/src/js' def",
"= html_loader(f'file:{self.template_dir}/{template}.html') else: template = 'basic-slide' html = html_loader(f'file:{self.base_template_dir}/{template}.html') else:",
"render_content(self, key): data = self.content.get(key) id = JupyterSlides.randomUUID() self.render( template='eye',",
"if os.path.isfile(f'{self.template_dir}/table-contents.html'): contents_template_dir = self.template_dir else: contents_template_dir = self.base_template_dir self.render(",
"= [] for _, item in self.content.items(): for sub_item in",
") def parse_template(self, template=None, data={}, template_dir=None, render_type=None): if not template_dir:",
"if data.get('slides'): for el in data.get('slides'): template = el.get('template') self.render(template=template,",
"render_type='slide' ) def parse_template(self, template=None, data={}, template_dir=None, render_type=None): if not",
"= self.template_dir else: contents_template_dir = self.base_template_dir self.render( template='table-contents', data=self.generate_table_contents(), template_dir=contents_template_dir,",
"= string.ascii_lowercase return ''.join(random.choice(letters) for i in range(stringLength)) def generate_table_contents(self):",
"display, HTML from .utils import html_loader from .utils import get_content",
"string import os from IPython.display import display, HTML from .utils",
"template_dir=self.base_template_dir ) def render_table_contents(self): if os.path.isfile(f'{self.template_dir}/table-contents.html'): contents_template_dir = self.template_dir else:",
"'basic-slide' template_dir = self.base_template_dir html = html_loader( f'file:{template_dir}/{template}.html') if render_type",
"navigation_template = self.parse_template( template='navigation', template_dir=template_dir ) html += navigation_template display(HTML(html))",
"range(stringLength)) def generate_table_contents(self): table = {} items = [] for",
"template=template, data=data, template_dir=template_dir, render_type=render_type ) if navigation: navigation_template = self.parse_template(",
"template_dir=template_dir ) html += navigation_template display(HTML(html)) def render_content(self, key): data",
"JupyterSlides.randomUUID() self.render( template='eye', data={'eye_id': id}, template_dir=self.base_template_dir ) if data.get('slides'): for",
"in item['slides']: sub_item['slide_id'] = \\ str(item['indice']) + '.' + str(sub_item['indice'])",
") def render_table_contents(self): if os.path.isfile(f'{self.template_dir}/table-contents.html'): contents_template_dir = self.template_dir else: contents_template_dir",
"'slide': html = '<div id=\"{{ data[\"slide_id\"] }}\" class=\"slide-container\">' + \\",
"id = JupyterSlides.randomUUID() self.render( template='eye', data={'eye_id': id}, template_dir=self.base_template_dir ) if",
"self.base_js_dir = f'{self.module_path}/src/js' def set_source_dirs(self): self.called_from_path = os.getcwd() folders =",
"self.source_path = '/'.join(folders[:folders.index('talks')]) self.template_dir = f'{self.source_path}/src/templates' self.css_dir = f'{self.source_path}/src/css' self.js_dir",
"if not template_dir: if os.path.isfile(f'{self.template_dir}/{template}.html'): html = html_loader(f'file:{self.template_dir}/{template}.html') else: template",
"+ '.' + str(sub_item['indice']) +\\ sub_item['content_title'] item['slide_id'] = item['slides'][0]['slide_id'] items.append(item)",
"HTML from .utils import html_loader from .utils import get_content from",
"= 'basic-slide' html = html_loader(f'file:{self.base_template_dir}/{template}.html') else: if not os.path.isfile(f'{template_dir}/{template}.html'): template",
"= self.parse_template( template=template, data=data, template_dir=template_dir, render_type=render_type ) if navigation: navigation_template",
"for i in range(stringLength)) def generate_table_contents(self): table = {} items",
"import Template class JupyterSlides: def __init__( self, content_path='./content.yaml', table_contents=False ):",
"+ '</div>' tm = Template(html) return tm.render(data=data) def render(self, template=None,",
"sub_item in item['slides']: sub_item['slide_id'] = \\ str(item['indice']) + '.' +",
"tm.render(data=data) def render(self, template=None, data={}, navigation=False, template_dir=None, render_type=None): html =",
"data={'eye_id': id}, template_dir=self.base_template_dir ) if data.get('slides'): for el in data.get('slides'):",
"if navigation: navigation_template = self.parse_template( template='navigation', template_dir=template_dir ) html +=",
"data=self.content.get('init_vars', {}) ) id = JupyterSlides.randomUUID() self.render( template='eye', data={'eye_id': id},",
"os.getcwd() folders = self.called_from_path.split('/') self.source_path = '/'.join(folders[:folders.index('talks')]) self.template_dir = f'{self.source_path}/src/templates'",
"= \\ str(item['indice']) + '.' + str(sub_item['indice']) +\\ sub_item['content_title'] item['slide_id']",
"data={}, navigation=False, template_dir=None, render_type=None): html = self.parse_template( template=template, data=data, template_dir=template_dir,",
"== 'slide': html = '<div id=\"{{ data[\"slide_id\"] }}\" class=\"slide-container\">' +",
"import get_content from jinja2 import Template class JupyterSlides: def __init__(",
"= JupyterSlides.randomUUID() self.render( template='eye', data={'eye_id': id}, template_dir=self.base_template_dir ) if data.get('slides'):",
"self.css_dir = f'{self.source_path}/src/css' self.js_dir = f'{self.source_path}/src/js' def render_init_templates(self): self.render( template='init',",
"template_dir=self.base_template_dir ) if data.get('slides'): for el in data.get('slides'): template =",
"length \"\"\" letters = string.ascii_lowercase return ''.join(random.choice(letters) for i in",
"\\ str(item['indice']) + '.' + str(sub_item['indice']) +\\ sub_item['content_title'] item['slide_id'] =",
"f'{self.module_path}/src/templates' self.base_css_dir = f'{self.module_path}/src/assets/css' self.base_js_dir = f'{self.module_path}/src/js' def set_source_dirs(self): self.called_from_path",
"template='eye', data={'eye_id': id}, template_dir=self.base_template_dir ) if data.get('slides'): for el in",
"template=None, data={}, template_dir=None, render_type=None): if not template_dir: if os.path.isfile(f'{self.template_dir}/{template}.html'): html",
"table_contents: self.render_table_contents() def set_base_dirs(self): self.module_path = os.path.dirname(os.path.realpath(__file__)) self.base_template_dir = f'{self.module_path}/src/templates'",
"render_type=render_type ) if navigation: navigation_template = self.parse_template( template='navigation', template_dir=template_dir )",
"import random import string import os from IPython.display import display,",
"render_type == 'slide': html = '<div id=\"{{ data[\"slide_id\"] }}\" class=\"slide-container\">'",
"data=el, render_type='slide') @staticmethod def randomUUID(stringLength=20): \"\"\"Generate a random string of",
"randomUUID(stringLength=20): \"\"\"Generate a random string of fixed length \"\"\" letters",
"html_loader(f'file:{self.base_template_dir}/{template}.html') else: if not os.path.isfile(f'{template_dir}/{template}.html'): template = 'basic-slide' template_dir =",
") if data.get('slides'): for el in data.get('slides'): template = el.get('template')",
"template='table-contents', data=self.generate_table_contents(), template_dir=contents_template_dir, render_type='slide' ) def parse_template(self, template=None, data={}, template_dir=None,",
"os.path.isfile(f'{self.template_dir}/{template}.html'): html = html_loader(f'file:{self.template_dir}/{template}.html') else: template = 'basic-slide' html =",
"return ''.join(random.choice(letters) for i in range(stringLength)) def generate_table_contents(self): table =",
"item['slides']: sub_item['slide_id'] = \\ str(item['indice']) + '.' + str(sub_item['indice']) +\\",
"from .utils import html_loader from .utils import get_content from jinja2",
"not os.path.isfile(f'{template_dir}/{template}.html'): template = 'basic-slide' template_dir = self.base_template_dir html =",
"def render(self, template=None, data={}, navigation=False, template_dir=None, render_type=None): html = self.parse_template(",
"html += navigation_template display(HTML(html)) def render_content(self, key): data = self.content.get(key)",
"os.path.isfile(f'{self.template_dir}/table-contents.html'): contents_template_dir = self.template_dir else: contents_template_dir = self.base_template_dir self.render( template='table-contents',",
"if os.path.isfile(f'{self.template_dir}/{template}.html'): html = html_loader(f'file:{self.template_dir}/{template}.html') else: template = 'basic-slide' html",
"= f'{self.source_path}/src/css' self.js_dir = f'{self.source_path}/src/js' def render_init_templates(self): self.render( template='init', data={'dir':",
"self.content = get_content(content_path) self.render_init_templates() if table_contents: self.render_table_contents() def set_base_dirs(self): self.module_path",
"table = {} items = [] for _, item in",
"data={}, template_dir=None, render_type=None): if not template_dir: if os.path.isfile(f'{self.template_dir}/{template}.html'): html =",
"self.set_base_dirs() self.set_source_dirs() self.content = get_content(content_path) self.render_init_templates() if table_contents: self.render_table_contents() def",
"os.path.dirname(os.path.realpath(__file__)) self.base_template_dir = f'{self.module_path}/src/templates' self.base_css_dir = f'{self.module_path}/src/assets/css' self.base_js_dir = f'{self.module_path}/src/js'",
"self.module_path}, template_dir=self.base_template_dir ) if os.path.isfile(f'{self.template_dir}/init.html'): self.render( template=f'init', data=self.content.get('init_vars', {}) )",
"template='eye', data={'eye_id': id}, template_dir=self.base_template_dir ) def render_table_contents(self): if os.path.isfile(f'{self.template_dir}/table-contents.html'): contents_template_dir",
"get_content(content_path) self.render_init_templates() if table_contents: self.render_table_contents() def set_base_dirs(self): self.module_path = os.path.dirname(os.path.realpath(__file__))",
"navigation_template display(HTML(html)) def render_content(self, key): data = self.content.get(key) id =",
"f'{self.module_path}/src/assets/css' self.base_js_dir = f'{self.module_path}/src/js' def set_source_dirs(self): self.called_from_path = os.getcwd() folders",
"self.parse_template( template=template, data=data, template_dir=template_dir, render_type=render_type ) if navigation: navigation_template =",
"import os from IPython.display import display, HTML from .utils import",
"self.template_dir else: contents_template_dir = self.base_template_dir self.render( template='table-contents', data=self.generate_table_contents(), template_dir=contents_template_dir, render_type='slide'",
"= html_loader( f'file:{template_dir}/{template}.html') if render_type == 'slide': html = '<div",
"def render_content(self, key): data = self.content.get(key) id = JupyterSlides.randomUUID() self.render(",
"\"\"\"Generate a random string of fixed length \"\"\" letters =",
"items = [] for _, item in self.content.items(): for sub_item",
"render(self, template=None, data={}, navigation=False, template_dir=None, render_type=None): html = self.parse_template( template=template,",
"data[\"slide_id\"] }}\" class=\"slide-container\">' + \\ html + '</div>' tm =",
"template = 'basic-slide' html = html_loader(f'file:{self.base_template_dir}/{template}.html') else: if not os.path.isfile(f'{template_dir}/{template}.html'):",
"data = self.content.get(key) id = JupyterSlides.randomUUID() self.render( template='eye', data={'eye_id': id},",
"self.called_from_path = os.getcwd() folders = self.called_from_path.split('/') self.source_path = '/'.join(folders[:folders.index('talks')]) self.template_dir"
] |
[
"3 * 1000)}]) decode = bitcoind.rpc.decoderawtransaction(prep['unsigned_tx']) assert decode['txid'] == prep['txid']",
"Invalid witness version with pytest.raises(RpcError): l1.rpc.withdraw('BC13W508D6QEJXTDG4Y5R3ZARVARY0C5XW7KN40WF2', 2 * amount) #",
"* 10) / 10**8 - Decimal(0.0003) assert decode['vout'][0]['scriptPubKey']['type'] == 'witness_v0_keyhash'",
"else 3 # One output will be correct. outnum =",
"that correct utxos are included assert len(decode['vin']) == 4 vins",
"is used to compute a maximum height that is to",
"types = [o['type'] for o in txs[1]['outputs']] changeidx = 0",
"l1.rpc.newaddr()[\"bech32\"] withdraw = l1.rpc.withdraw(addr, 10**3) bitcoind.generate_block(1) l1.daemon.wait_for_log('Owning output .* txid",
"= peers[0]['channels'][0]['short_channel_id'] assert(txs[1]['outputs'][fundidx]['channel'] == scid) @unittest.skipIf(VALGRIND, \"It does not play",
"next call warned about SQL Accessing a null column #",
"= node_factory.get_node(may_fail=True) # May fail when started without key password",
"/ 10**8 + 0.01) bitcoind.generate_block(1) wait_for(lambda: len(l1.rpc.listfunds()['outputs']) == 10) with",
"decode['vout'][0]['value'] > Decimal(amount * 10) / 10**8 - Decimal(0.0003) assert",
"funds again l1.rpc.txdiscard(prep5['txid']) with pytest.raises(RpcError, match=r'this destination wants all satoshi.",
"assert len(decode['vout']) == 3 if chainparams['feeoutput'] else 2 assert decode['vout'][1]['value']",
"sure bitcoind received the withdrawal unspent = l1.bitcoin.rpc.listunspent(0) withdrawal =",
"fees will be taken assert decode['vout'][0]['value'] < Decimal(amount * 10)",
"for i in range(100): addr = l1.rpc.newaddr()[\"bech32\"] withdraw = l1.rpc.withdraw(addr,",
"== 1) outputs = l1.db_query('SELECT value FROM outputs WHERE status=0;')",
"throw off our output matching logic\") @unittest.skipIf(not EXPERIMENTAL_FEATURES, \"Tests annotations",
"1nwldj5', 2 * amount) # overall max length exceeded with",
"assert id == l1.rpc.getinfo()[\"id\"] @unittest.skipIf(VALGRIND, \"It does not play well",
"wait_for(lambda: len(l1.rpc.listfunds()['outputs']) == 10) # Try passing in a utxo",
"* 3 * 500 + 100000)}, {addr: Millisatoshi(amount * 3",
"memory or null txs = l1.rpc.listtransactions()['transactions'] tx = [t for",
"only_one(l1.rpc.listfunds()['outputs']) assert output['address'] == addr # Send all our money",
"match=r'Need set \\'outputs\\' field.'): l1.rpc.call('txprepare', {'satoshi': Millisatoshi(amount * 100), 'feerate':",
"`lightningd`. master_fd, slave_fd = os.openpty() # Encrypt the master seed",
"l1.rpc.txdiscard(prep['txid']) prep = l1.rpc.txprepare([{addr: 'all'}]) decode = bitcoind.rpc.decoderawtransaction(prep['unsigned_tx']) assert decode['txid']",
"bitcoind): amount = 1000000 # Don't get any funds from",
"set \\'outputs\\' field.'): l1.rpc.call('txprepare', {'satoshi': Millisatoshi(amount * 100), 'feerate': '10perkw',",
"status=0')[0]['c'] == 0 # This should fail, can't even afford",
"* 3) / 10**8: changenum = 0 else: assert False",
"== fundingtx['txid']) # Confirm the channel and check that the",
"terminal to use termios in `lightningd`. master_fd, slave_fd = os.openpty()",
"= [] for i, o in enumerate(tx['outputs']): if i ==",
"for o in l1.rpc.listfunds()['outputs']: assert o['status'] == 'confirmed' # Now",
"== Decimal('0.02')) l1.bitcoin.generate_block(1) sync_blockheight(l1.bitcoin, [l1]) # Check that there are",
"'feerate': '10perkw', 'minconf': 2}) l1.rpc.call('txprepare', {'destination': addr, 'satoshi': Millisatoshi(amount *",
"ok) txs = l1.rpc.listtransactions()['transactions'] assert(len(txs) == 2 and txs[1]['hash'] ==",
"os.write(master_fd, password.encode(\"utf-8\")) l1.daemon.wait_for_log(\"Server started with public key\") assert node_id ==",
"decode = bitcoind.rpc.decoderawtransaction(prep2['unsigned_tx']) assert decode['txid'] == prep2['txid'] # 6 inputs,",
"+ \":\" + str(utxo[\"output\"]) for utxo in l1.rpc.listfunds()[\"outputs\"]][:4] prep5 =",
"pytest.raises(RpcError): l1.rpc.withdraw('BC13W508D6QEJXTDG4Y5R3ZARVARY0C5XW7KN40WF2', 2 * amount) # Invalid program length for",
"all our money to a P2WPKH address this time. addr",
"restore the same wallet with the same password l1.daemon.start(stdin=slave_fd, wait_for_initialized=False)",
"== 1) scid = peers[0]['channels'][0]['short_channel_id'] assert(txs[1]['outputs'][fundidx]['channel'] == scid) @unittest.skipIf(VALGRIND, \"It",
"2}) l1.rpc.call('txprepare', {'destination': addr, 'satoshi': Millisatoshi(amount * 100), 'feerate': '2000perkw',",
"with pytest.raises(RpcError): l1.rpc.withdraw('BC13W508D6QEJXTDG4Y5R3ZARVARY0C5XW7KN40WF2', 2 * amount) # Invalid program length",
"funds from previous runs. l1 = node_factory.get_node(random_hsm=True) l2 = node_factory.get_node(random_hsm=True)",
"3 # One output will be correct. for i in",
"Array type with pytest.raises(RpcError, match=r'.* should be an amount in",
"['confirmed'] * 10) with pytest.raises(RpcError, match=r'not an unreleased txid'): l1.rpc.txdiscard(prep['txid'])",
"to simulate a terminal to use termios in `lightningd`. master_fd,",
"'satoshi': Millisatoshi(amount * 100)}) def test_txprepare_multi(node_factory, bitcoind): amount = 10000000",
"def test_hsm_secret_encryption(node_factory): l1 = node_factory.get_node(may_fail=True) # May fail when started",
"to. output = only_one(l1.rpc.listfunds()['outputs']) assert output['address'] == addr # Send",
"p2sh for i in range(5): bitcoind.rpc.sendtoaddress(l1.rpc.newaddr()['bech32'], amount / 10**8) bitcoind.rpc.sendtoaddress(l1.rpc.newaddr('p2sh-segwit')['p2sh-segwit'],",
"an already-existing and not encrypted hsm_secret l1.stop() l1.daemon.opts.update({\"encrypted-hsm\": None}) l1.daemon.start(stdin=slave_fd,",
"3) / 10**8: changenum = 1 elif decode['vout'][1]['value'] == Decimal(amount",
"number. \"\"\" amount = 1000000 # Don't get any funds",
"l1.rpc.newaddr()['bech32'] bitcoind.rpc.sendtoaddress(addr, 0.1) bitcoind.generate_block(1) wait_for(lambda: len(l1.rpc.listfunds()['outputs']) == 1) outputs =",
"+ 0.01) bitcoind.generate_block(1) wait_for(lambda: len(l1.rpc.listfunds()['outputs']) == 10) # Reach around",
"bitcoind.generate_block(1) wait_for(lambda: len(l1.rpc.listfunds()['outputs']) == 1) outputs = [] for i",
"l1.daemon.wait_for_log(r'The hsm_secret is encrypted') os.write(master_fd, password[2:].encode(\"utf-8\")) assert(l1.daemon.proc.wait() == 1) assert(l1.daemon.is_in_log(\"Wrong",
"# overall max length exceeded with pytest.raises(RpcError): l1.rpc.withdraw('an84characterslonghumanreadablepartthatcontainsthenumber1andtheexcludedcharactersbio1569pvx', 2 *",
"FROM outputs WHERE status=2')[0]['c'] == 8 # failure testing for",
"with pytest.raises(RpcError): l1.rpc.withdraw('tb1qw508d6qejxtdg4y5r3zarvary0c5xw7kxxxxxx', 2 * amount) l1.rpc.withdraw(waddr, 2 * amount)",
"4 inputs, 1 outputs. assert len(decode['vin']) == 4 assert len(decode['vout'])",
"self. l1.rpc.withdraw(l1.rpc.newaddr('bech32')['bech32'], 'all', minconf=0) bitcoind.generate_block(1) assert l1.db_query('SELECT COUNT(*) as c",
"utils import ( only_one, wait_for, sync_blockheight, EXPERIMENTAL_FEATURES, COMPAT, VALGRIND )",
"= 0 if types[0] == 'deposit' else 1 fundidx =",
"non-zero exit status 1'): subprocess.check_call(l1.daemon.cmd_line) l1.daemon.opts.update({\"encrypted-hsm\": None}) master_fd, slave_fd =",
"1 outputs. assert len(decode['vin']) == 10 assert len(decode['vout']) == 1",
"else 3 # One output will be correct. for i",
"inputs) with pytest.raises(RpcError): l1.rpc.withdraw('not an address', amount) with pytest.raises(RpcError): l1.rpc.withdraw(waddr,",
"Add some funds to withdraw later for i in range(10):",
"addr = l1.rpc.newaddr(\"bech32\")['bech32'] l1.rpc.withdraw(addr, \"all\") bitcoind.generate_block(1) time.sleep(1) # The address",
"'all', minconf=0) assert l1.db_query('SELECT COUNT(*) as c FROM outputs WHERE",
"'satoshi': Millisatoshi(amount * 100), 'feerate': '2000perkw', 'minconf': 1}) l1.rpc.call('txprepare', {'destination':",
"for t in txs if t['hash'] == txid][0] assert tx['blockheight']",
"not chainparams['feeoutput'] else 3 # One output will be correct.",
"\\'outputs\\' field.'): l1.rpc.call('txprepare', {'satoshi': Millisatoshi(amount * 100), 'feerate': '10perkw', 'minconf':",
"the same wallet with the same password l1.daemon.start(stdin=slave_fd, wait_for_initialized=False) l1.daemon.wait_for_log(r'The",
"encrypted hsm_secret.\")) # Test we can restore the same wallet",
"types.append(None) assert(set([None]) == set(types)) ########################################################################## # Let's now open a",
"We should have 2 transactions, the second one should be",
"prep3 = l1.rpc.txprepare([{addr: 'all'}]) decode = bitcoind.rpc.decoderawtransaction(prep3['unsigned_tx']) assert decode['txid'] ==",
"= 1000000 l1 = node_factory.get_node(random_hsm=True) addr = chainparams['example_addr'] # Add",
"outputs throw off our output matching logic\") @unittest.skipIf(not EXPERIMENTAL_FEATURES, \"Tests",
"Decrypt it with hsmtool cmd_line[3] = password[:-1] subprocess.check_call(cmd_line) # Then",
"appear. if decode['vout'][0]['value'] == Decimal(amount * 3) / 10**8: changenum",
"10000000 # The address we detect must match what was",
"[t for t in txs if t['hash'] == txid][0] assert",
"FROM outputs WHERE status=0')[0]['c'] == 10 waddr = l1.bitcoin.rpc.getnewaddress() #",
"output has arrived. wait_for(lambda: len(l1.rpc.listfunds()['outputs']) == 10 - len(decode['vin']) +",
"addr, 'satoshi': Millisatoshi(amount * 100), 'feerate': '2000perkw'}) l1.rpc.call('txprepare', {'destination': addr,",
"txs[1]['outputs']] changeidx = 0 if types[0] == 'deposit' else 1",
"get all funds again l1.rpc.txdiscard(prep5['txid']) with pytest.raises(RpcError, match=r'this destination wants",
"from: https://bc-2.jp/tools/bech32demo/index.html waddr = 'bcrt1qw508d6qejxtdg4y5r3zarvary0c5xw7kygt080' with pytest.raises(RpcError): l1.rpc.withdraw('xx1qw508d6qejxtdg4y5r3zarvary0c5xw7kxpjzsx', 2 *",
"channel open and deposit. l1.connect(l2) fundingtx = l1.rpc.fundchannel(l2.info['id'], 10**5) #",
"output should appear. if decode['vout'][0]['value'] == Decimal(amount * 3) /",
"in a utxo set utxos = [utxo[\"txid\"] + \":\" +",
"l1.connect(l2) fundingtx = l1.rpc.fundchannel(l2.info['id'], 10**5) # We should have one",
"us the funds in the # transactions table... outputs =",
"with pytest.raises(RpcError): l1.rpc.withdraw(waddr, -amount) with pytest.raises(RpcError, match=r'Cannot afford transaction'): l1.rpc.withdraw(waddr,",
"pytest.raises(subprocess.CalledProcessError): subprocess.check_call(cmd_line) # Decrypt it with hsmtool cmd_line[3] = password[:-1]",
"== 10) prep = l1.rpc.txprepare(outputs=[{addr: Millisatoshi(amount * 3 * 1000)}])",
"failure testing for invalid SegWit addresses, from BIP173 # HRP",
"'witness_v0_keyhash' assert decode['vout'][0]['scriptPubKey']['addresses'] == [addr] l1.rpc.txdiscard(prep4['txid']) # Try passing in",
"so that order should be ok) txs = l1.rpc.listtransactions()['transactions'] assert(len(txs)",
"l1 = node_factory.get_node() password = \"<PASSWORD>\" hsm_path = os.path.join(l1.daemon.lightning_dir, TEST_NETWORK,",
"make sure two of them were marked as spent assert",
"in utxos: assert utxo in vins def test_minconf_withdraw(node_factory, bitcoind): \"\"\"Issue",
"if we have a fee output). assert len(decode['vin']) == 4",
"as c FROM outputs WHERE status=2')[0]['c'] == 4 # Simple",
"for i in range(9): outputs.append({l1.rpc.newaddr()['bech32']: Millisatoshi(amount * 100)}) prep =",
"l1.rpc.getinfo()[\"id\"] # this test does a 'listtransactions' on a yet",
"'all'}]) decode = bitcoind.rpc.decoderawtransaction(prep4['unsigned_tx']) assert decode['txid'] == prep4['txid'] # 10",
"assert utxo in vins # We should have a change",
"prep5 = l1.rpc.txprepare([{addr: Millisatoshi(amount * 3.5 * 1000)}], utxos=utxos) decode",
"= l1.rpc.listfunds()['outputs'] assert(len(outputs) == 1 and outputs[0]['status'] == 'unconfirmed') #",
"l1.rpc.call('txprepare', [addr]) with pytest.raises(RpcError, match=r'Could not parse destination address.*'): l1.rpc.call('txprepare',",
"to check fuzz.\") def test_withdraw_nlocktime_fuzz(node_factory, bitcoind): \"\"\" Test that we",
"len(peers[0]['channels']) == 1) scid = peers[0]['channels'][0]['short_channel_id'] assert(txs[1]['outputs'][fundidx]['channel'] == scid) @unittest.skipIf(VALGRIND,",
"= l2.db_query('SELECT value FROM outputs WHERE status=0;') assert only_one(outputs)['value'] ==",
"# Test we can restore the same wallet with the",
"with the same password l1.daemon.start(stdin=slave_fd, wait_for_initialized=False) l1.daemon.wait_for_log(r'The hsm_secret is encrypted')",
"len(decode['vout']) == 1 if not chainparams['feeoutput'] else 2 # Some",
"= l1.rpc.newaddr(\"bech32\")['bech32'] l1.rpc.withdraw(addr, \"all\") bitcoind.generate_block(1) time.sleep(1) # The address we",
"# Send all our money to a P2WPKH address this",
"paid to. output = only_one(l1.rpc.listfunds()['outputs']) assert output['address'] == addr #",
"o in l1.rpc.listfunds()['outputs']] == ['confirmed'] * 10) with pytest.raises(RpcError, match=r'not",
"outputs = l1.rpc.listfunds()['outputs'] assert(len(outputs) == 1 and outputs[0]['status'] == 'unconfirmed')",
"# Add some funds to withdraw later: both bech32 and",
"encrypted') os.write(master_fd, password.encode(\"utf-8\")) l1.daemon.wait_for_log(\"Server started with public key\") node_id =",
"wait_for(lambda: prep['txid'] in bitcoind.rpc.getrawmempool()) # Signed tx should have same",
"output = only_one(l1.rpc.listfunds()['outputs']) assert output['address'] == addr # Send all",
"confirmations we wrap around and just select everything. The fix",
"should get the funding transaction # annotated as channel open",
"in vins def test_minconf_withdraw(node_factory, bitcoind): \"\"\"Issue 2518: ensure that ridiculous",
"! cmd_line = [\"tools/hsmtool\", \"decrypt\", hsm_path, \"A wrong pass\"] with",
"wait_for, sync_blockheight, EXPERIMENTAL_FEATURES, COMPAT, VALGRIND ) import os import pytest",
"maximum height that is to be accepted. If the current",
"4 assert len(decode['vout']) == 4 if chainparams['feeoutput'] else 3 #",
"chainparams['feeoutput'] else 3 # One output will be correct. for",
"1 and outputs[0]['status'] == 'confirmed') # We should have 2",
"passing in a utxo set utxos = [utxo[\"txid\"] + \":\"",
"outputs[0]['status'] == 'unconfirmed') # It should also match the funding",
"* 100), 'feerate': '10perkw', 'minconf': 2}) l1.rpc.call('txprepare', {'destination': addr, 'satoshi':",
"than the number of confirmations we wrap around and just",
"have one output available, and it should be unconfirmed outputs",
"don't set the nLockTime to 0 for withdrawal transactions. \"\"\"",
"the number of confirmations we wrap around and just select",
"received the withdrawal unspent = l1.bitcoin.rpc.listunspent(0) withdrawal = [u for",
"outnum = [i for i, o in enumerate(decode['vout']) if o['value']",
"an unreleased txid'): l1.rpc.txdiscard(prep['txid']) wait_for(lambda: prep['txid'] in bitcoind.rpc.getrawmempool()) # Signed",
"prep5 = l1.rpc.txprepare([{addr: Millisatoshi(amount * 3 * 1000)}, {addr: 'all'}])",
"regtest\") def test_withdraw(node_factory, bitcoind): amount = 1000000 # Don't get",
"is to be accepted. If the current height is smaller",
"test we can now start it without password l1.daemon.opts.pop(\"encrypted-hsm\") l1.daemon.start(stdin=slave_fd,",
"= bitcoind.rpc.decoderawtransaction(prep5['unsigned_tx']) assert decode['txid'] == prep5['txid'] # Check that correct",
"pytest.raises(RpcError): l1.rpc.withdraw('xx1qrp33g0q5c5txsp9arysrx4k6zdkfs4nce4xj0gdcccefvpysxf3q0sl5k7', 2 * amount) with pytest.raises(RpcError): l1.rpc.withdraw('tb1prp33g0q5c5txsp9arysrx4k6zdkfs4nce4xj0gdcccefvpysxf3qsm03tq', 2 *",
"== [addr] # If I cancel the first one, I",
"gone, but change output has arrived. wait_for(lambda: len(l1.rpc.listfunds()['outputs']) == 10",
"chainparams): amount = 1000000 l1 = node_factory.get_node(may_fail=True) addr = chainparams['example_addr']",
"play well with prompt and key derivation.\") def test_hsm_secret_encryption(node_factory): l1",
"All 10 inputs assert len(decode['vin']) == 10 # This will",
"out['value'] == 10**6) # ... and it should have an",
"l1.rpc.listfunds()['outputs']] == ['confirmed'] * 10) prep = l1.rpc.txprepare([{addr: 'all'}]) decode",
"to 0 for withdrawal transactions. \"\"\" l1 = node_factory.get_node(1) l1.fundwallet(10**4)",
"WHERE status=0')[0]['c'] == 10 waddr = l1.bitcoin.rpc.getnewaddress() # Now attempt",
"as channel open and deposit. l1.connect(l2) fundingtx = l1.rpc.fundchannel(l2.info['id'], 10**5)",
"P2WPKH address this time. addr = l1.rpc.newaddr(\"bech32\")['bech32'] l1.rpc.withdraw(addr, \"all\") bitcoind.generate_block(1)",
"in unspent if u['txid'] == out['txid']] assert(withdrawal[0]['amount'] == Decimal('0.02')) l1.bitcoin.generate_block(1)",
"o['scriptPubKey']['type'] in ['witness_v0_keyhash', 'fee'] # Now prepare one with no",
"import flaky # noqa: F401 from pyln.client import RpcError, Millisatoshi",
"# ... and it should have an annotation on the",
"check that the output changed to confirmed bitcoind.generate_block(3) sync_blockheight(bitcoind, [l1,",
"assert decode['vout'][0]['scriptPubKey']['type'] == 'witness_v0_keyhash' assert decode['vout'][0]['scriptPubKey']['addresses'] == [addr] # Cannot",
"fail when started without key password = \"<PASSWORD>\" # We",
"master_fd, slave_fd = os.openpty() # Test we can encrypt an",
"on the funding output peers = l1.rpc.listpeers()['peers'] assert(len(peers) == 1",
"decode['vout'][outnum1]['scriptPubKey']['type'] == 'witness_v0_keyhash' assert decode['vout'][outnum1]['scriptPubKey']['addresses'] == [addr] assert decode['vout'][outnum2]['scriptPubKey']['type'] ==",
"== 'confirmed') # We should have 2 transactions, the second",
"can now start it without password l1.daemon.opts.pop(\"encrypted-hsm\") l1.daemon.start(stdin=slave_fd, wait_for_initialized=True) assert",
"chainparams['feeoutput'] else 2 assert decode['vout'][1]['value'] == Decimal(amount * 3.5) /",
"should appear. if decode['vout'][0]['value'] == Decimal(amount * 3) / 10**8:",
"assert node_id == l1.rpc.getinfo()[\"id\"] l1.stop() # Test we can encrypt",
"import ( only_one, wait_for, sync_blockheight, EXPERIMENTAL_FEATURES, COMPAT, VALGRIND ) import",
"== Decimal('0.01499900'): outnum2 = i - 1 else: changenum =",
"outputs. assert len(decode['vin']) == 4 assert len(decode['vout']) == 1 if",
"in [f['address'] for f in l1.rpc.listfunds()['outputs']] def test_txprepare_restart(node_factory, bitcoind, chainparams):",
"eventually fuzz nLockTime for withdrawal transactions. Marked flaky \"just in",
"# Now make sure an additional two of them were",
"amount = 1000000 l1 = node_factory.get_node(may_fail=True) addr = chainparams['example_addr'] #",
"with hsmtool cmd_line[1] = \"decrypt\" subprocess.check_call(cmd_line) l1.daemon.opts.pop(\"encrypted-hsm\") l1.daemon.start(stdin=slave_fd, wait_for_initialized=True) assert",
"test_txsend(node_factory, bitcoind, chainparams): amount = 1000000 l1 = node_factory.get_node(random_hsm=True) addr",
"length for witness version 0 (per BIP141) with pytest.raises(RpcError): l1.rpc.withdraw('BC1QR508D6QEJXTDG4Y5R3ZARVARYV98GJ9P',",
"utxos: assert utxo in vins # We should have a",
"# annotated as channel open and deposit. l1.connect(l2) fundingtx =",
"change, and have no annotations types = [] for i,",
"l1.rpc.getinfo()[\"id\"] @unittest.skipIf(VALGRIND, \"It does not play well with prompt and",
"outputs available. assert l1.db_query('SELECT COUNT(*) as c FROM outputs WHERE",
"100), 'feerate': '10perkw', 'minconf': 2}) l1.rpc.call('txprepare', {'destination': addr, 'satoshi': Millisatoshi(amount",
"* 3) / 10**8: changenum = 1 elif decode['vout'][1]['value'] ==",
"[Millisatoshi(amount * 100), 'slow', 1]) l1.rpc.call('txprepare', [addr, Millisatoshi(amount * 100),",
"we can now start it without password l1.daemon.opts.pop(\"encrypted-hsm\") l1.daemon.start(stdin=slave_fd, wait_for_initialized=True)",
"prep2 = l1.rpc.txprepare([{addr: 'all'}]) decode = bitcoind.rpc.decoderawtransaction(prep2['unsigned_tx']) assert decode['txid'] ==",
"hsmtool cmd_line[3] = password[:-1] subprocess.check_call(cmd_line) # Then test we can",
"'slow', 1]) l1.rpc.call('txprepare', [addr, Millisatoshi(amount * 100), 'normal']) l1.rpc.call('txprepare', [addr,",
"== 'channel_funding') # And check the channel annotation on the",
"pytest.raises(RpcError): l1.rpc.withdraw('pzry9x0s0muk', 2 * amount) # Empty HRP with pytest.raises(RpcError):",
"[o['type'] for o in txs[1]['outputs']] changeidx = 0 if types[0]",
"that we don't set the nLockTime to 0 for withdrawal",
"max length exceeded with pytest.raises(RpcError): l1.rpc.withdraw('an84characterslonghumanreadablepartthatcontainsthenumber1andtheexcludedcharactersbio1569pvx', 2 * amount) #",
"= node_factory.bitcoind.rpc.decoderawtransaction(tx)[\"locktime\"] tip = node_factory.bitcoind.rpc.getblockcount() assert nlocktime > 0 and",
"'regtest', \"Test relies on a number of example addresses valid",
"assert len(decode['vout']) == 1 if not chainparams['feeoutput'] else 2 #",
"with pytest.raises(RpcError, match=r'not an unreleased txid'): l1.rpc.txdiscard(prep['txid']) wait_for(lambda: prep['txid'] in",
"10) prep = l1.rpc.txprepare([{addr: 'all'}]) decode = bitcoind.rpc.decoderawtransaction(prep['unsigned_tx']) assert decode['txid']",
"COMPAT, \"needs COMPAT=1\") def test_deprecated_txprepare(node_factory, bitcoind): \"\"\"Test the deprecated old-style:",
"termios in `lightningd`. master_fd, slave_fd = os.openpty() # Encrypt the",
"sync_blockheight(bitcoind, [l1, l2]) outputs = l1.rpc.listfunds()['outputs'] assert(len(outputs) == 1 and",
"assert discard['unsigned_tx'] == prep['unsigned_tx'] prep3 = l1.rpc.txprepare([{addr: 'all'}]) decode =",
"match=r'returned non-zero exit status 1'): subprocess.check_call(l1.daemon.cmd_line) l1.daemon.opts.update({\"encrypted-hsm\": None}) master_fd, slave_fd",
"# Invalid witness version with pytest.raises(RpcError): l1.rpc.withdraw('BC13W508D6QEJXTDG4Y5R3ZARVARY0C5XW7KN40WF2', 2 * amount)",
"4) / 10**8 - Decimal(0.0002) assert decode['vout'][0]['scriptPubKey']['type'] == 'witness_v0_keyhash' assert",
"'10perkw', 'minconf': 2}) l1.rpc.call('txprepare', {'destination': addr, 'satoshi': Millisatoshi(amount * 100),",
"pytest.raises(RpcError): l1.rpc.withdraw('tb1qrp33g0q5c5txsp9arysrx4k6zdkfs4nce4xj0gdcccefvpysxf3qxxxxxx', 2 * amount) l1.rpc.withdraw(waddr, 2 * amount) bitcoind.generate_block(1)",
"compiled only with experimental features\") def test_transaction_annotations(node_factory, bitcoind): l1, l2,",
"get any funds from previous runs. l1 = node_factory.get_node(random_hsm=True) l2",
"encrypted hsm_secret l1.stop() l1.daemon.opts.update({\"encrypted-hsm\": None}) l1.daemon.start(stdin=slave_fd, wait_for_initialized=False) l1.daemon.wait_for_log(r'The hsm_secret is",
"10**8: changenum = 0 else: assert False # Those spent",
"* 6) / 10**8 assert decode['vout'][0]['value'] > Decimal(amount * 6)",
"in satoshis or all, not .*'): l1.rpc.call('txprepare', [addr, 'slow']) with",
"Millisatoshi(amount * 3.5 * 1000)}], utxos=utxos) decode = bitcoind.rpc.decoderawtransaction(prep5['unsigned_tx']) assert",
"subprocess.check_call(cmd_line) # Now we need to pass the encrypted-hsm startup",
"of confirmations is used to compute a maximum height that",
"- 1 elif decode['vout'][i - 1]['value'] == Decimal('0.01499900'): outnum2 =",
"== [addr] else: assert o['scriptPubKey']['type'] in ['witness_v0_keyhash', 'fee'] # Now",
"lightningd uses P2SH-P2WPKH waddr = l2.rpc.newaddr('bech32')['bech32'] l1.rpc.withdraw(waddr, 2 * amount)",
"test_txprepare_multi(node_factory, bitcoind): amount = 10000000 l1 = node_factory.get_node(random_hsm=True) bitcoind.rpc.sendtoaddress(l1.rpc.newaddr()['bech32'], amount",
"decimal import Decimal from fixtures import * # noqa: F401,F403",
"be ok) txs = l1.rpc.listtransactions()['transactions'] assert(len(txs) == 2 and txs[1]['hash']",
"public key\") assert id == l1.rpc.getinfo()[\"id\"] @unittest.skipIf(VALGRIND, \"It does not",
"some (making sure we collect multiple inputs) with pytest.raises(RpcError): l1.rpc.withdraw('not",
"+ str(utxo[\"output\"]) for utxo in l1.rpc.listfunds()[\"outputs\"]][:4] prep5 = l1.rpc.txprepare([{addr: Millisatoshi(amount",
"not play well with prompt and key derivation.\") def test_hsmtool_secret_decryption(node_factory):",
"== 'witness_v0_keyhash' assert decode['vout'][0]['scriptPubKey']['addresses'] == [addr] # If I cancel",
"'confirmed') out = outputs[0] idx = out['output'] assert(idx in [0,",
"does not play well with prompt and key derivation.\") def",
"i in decode['vin']: assert l1.daemon.is_in_log('wallet: reserved output {}/{} reset to",
"so this is exact assert len(decode['vout']) == 3 if chainparams['feeoutput']",
"txid: assert(outputs[0]['txid'] == fundingtx['txid']) # Confirm the channel and check",
"only_one(outputs)['value'] == 2 * amount # Now make sure an",
"= \"<PASSWORD>\" hsm_path = os.path.join(l1.daemon.lightning_dir, TEST_NETWORK, \"hsm_secret\") # We need",
"'feerate': 'slow'}) with pytest.raises(RpcError, match=r'Need set \\'outputs\\' field.'): l1.rpc.call('txprepare', {'satoshi':",
"== 'witness_v0_keyhash' def test_txsend(node_factory, bitcoind, chainparams): amount = 1000000 l1",
"after send! with pytest.raises(RpcError, match=r'not an unreleased txid'): l1.rpc.txdiscard(prep['txid']) wait_for(lambda:",
"second one should be the funding tx # (we are",
"decoded[\"locktime\"] > 0 if decoded[\"locktime\"] < tip: return else: raise",
"encrypted') os.write(master_fd, password.encode(\"utf-8\")) l1.daemon.wait_for_log(\"Server started with public key\") id =",
"Decimal('0.02')) l1.bitcoin.generate_block(1) sync_blockheight(l1.bitcoin, [l1]) # Check that there are no",
"> Decimal(amount * 6) / 10**8 - Decimal(0.0002) assert decode['vout'][0]['scriptPubKey']['type']",
"l1 = node_factory.get_node(1) l1.fundwallet(10**4) addr = l1.rpc.newaddr()[\"bech32\"] tx = l1.rpc.withdraw(addr,",
"funds to withdraw for i in range(10): l1.bitcoin.rpc.sendtoaddress(addr, amount /",
"{destination} {satoshi} {feerate} {minconf} \"\"\" amount = 10**4 l1 =",
"decode['vin']] for utxo in utxos: assert utxo in vins #",
"outputs = l1.rpc.listfunds()['outputs'] assert(len(outputs) == 1 and outputs[0]['status'] == 'confirmed')",
"the first one, I can get those first 4 outputs.",
"1) outputs = [] for i in range(9): outputs.append({l1.rpc.newaddr()['bech32']: Millisatoshi(amount",
"amount) # Non-zero padding in 8-to-5 conversion with pytest.raises(RpcError): l1.rpc.withdraw('tb1qrp33g0q5c5txsp9arysrx4k6zdkfs4nce4xj0gdcccefvpysxf3pjxtptv',",
"decode['vout'][0]['scriptPubKey']['type'] == 'witness_v0_keyhash' assert decode['vout'][0]['scriptPubKey']['addresses'] == [addr] l1.rpc.txdiscard(prep4['txid']) # Try",
"i in range(3 + chainparams['feeoutput']): if decode['vout'][i - 1]['value'] ==",
"= \"<PASSWORD>\" # We need to simulate a terminal to",
"'confirmed') # We should have 2 transactions, the second one",
"spent assert l1.db_query('SELECT COUNT(*) as c FROM outputs WHERE status=2')[0]['c']",
"l1.db_query('SELECT COUNT(*) as c FROM outputs WHERE status=2')[0]['c'] == 6",
"{'destination': addr, 'satoshi': Millisatoshi(amount * 100), 'feerate': '2000perkw'}) l1.rpc.call('txprepare', {'destination':",
"l1.rpc.withdraw(waddr, 'all') # Add some funds to withdraw for i",
"an unreleased txid'): l1.rpc.txdiscard(prep['txid']) # Discard everything, we should now",
"else: assert o['scriptPubKey']['type'] in ['witness_v0_keyhash', 'fee'] # Now prepare one",
"addresses, from BIP173 # HRP character out of range with",
"== [addr] # Discard prep4 and get all funds again",
"height is smaller than the number of confirmations we wrap",
"to 100 with a 10% probability. \"\"\" l1 = node_factory.get_node(1)",
"pass the encrypted-hsm startup option l1.stop() with pytest.raises(subprocess.CalledProcessError, match=r'returned non-zero",
"change). assert len(decode['vin']) == 4 assert len(decode['vout']) == 4 if",
"l1.db_query('SELECT COUNT(*) as c FROM outputs WHERE status=0')[0]['c'] == 1",
"and get all funds again l1.rpc.txdiscard(prep5['txid']) with pytest.raises(RpcError, match=r'this destination",
"example addresses valid only in regtest\") def test_withdraw(node_factory, bitcoind): amount",
"10 inputs assert len(decode['vin']) == 10 @unittest.skipIf(TEST_NETWORK != 'regtest', \"Fee",
"= os.path.join(l1.daemon.lightning_dir, TEST_NETWORK, \"hsm_secret\") # We need to simulate a",
"assert decode['vout'][changenum]['scriptPubKey']['addresses'][0] in [f['address'] for f in l1.rpc.listfunds()['outputs']] def test_txprepare_restart(node_factory,",
"received the withdrawal. wait_for(lambda: len(l2.rpc.listfunds()['outputs']) == 1) outputs = l2.db_query('SELECT",
"= node_factory.get_node() password = \"<PASSWORD>\" hsm_path = os.path.join(l1.daemon.lightning_dir, TEST_NETWORK, \"hsm_secret\")",
"can get those first 4 outputs. discard = l1.rpc.txdiscard(prep['txid']) assert",
"l1.rpc.withdraw('1pzry9x0s0muk', 2 * amount) # Invalid witness version with pytest.raises(RpcError):",
"/ 10**8 - Decimal(0.0003) assert decode['vout'][0]['scriptPubKey']['type'] == 'witness_v0_keyhash' assert decode['vout'][0]['scriptPubKey']['addresses']",
"len(l1.rpc.listfunds()['outputs']) == 1) outputs = l1.db_query('SELECT value FROM outputs WHERE",
"2 outputs (3 if we have a fee output). assert",
"[utxo[\"txid\"] + \":\" + str(utxo[\"output\"]) for utxo in l1.rpc.listfunds()[\"outputs\"]][:4] withdrawal",
"we fuzz from 0 to 100 with a 10% probability.",
"/ 10**8 assert decode['vout'][0]['value'] > Decimal(amount * 6) / 10**8",
"== 10 - len(decode['vin']) + 1) # Change address should",
"there was a reorg. Wait. wait_for(lambda: [o['status'] for o in",
"the output changed to confirmed bitcoind.generate_block(3) sync_blockheight(bitcoind, [l1, l2]) outputs",
"if i == outnum: assert o['scriptPubKey']['type'] == 'witness_v0_keyhash' assert o['scriptPubKey']['addresses']",
"withdraw some (making sure we collect multiple inputs) with pytest.raises(RpcError):",
"node_factory.get_node(random_hsm=True) addr = l1.rpc.newaddr()['bech32'] bitcoind.rpc.sendtoaddress(addr, 0.1) bitcoind.generate_block(1) wait_for(lambda: len(l1.rpc.listfunds()['outputs']) ==",
"l1.rpc.withdraw('an84characterslonghumanreadablepartthatcontainsthenumber1andtheexcludedcharactersbio1569pvx', 2 * amount) # No separator character with pytest.raises(RpcError):",
"in [0, 1] and out['value'] == 10**6) # ... and",
"[\"{}:{}\".format(v['txid'], v['vout']) for v in decode['vin']] for utxo in utxos:",
"tx['blockheight'] == 0 def test_withdraw_nlocktime(node_factory): \"\"\" Test that we don't",
"assert(l1.daemon.proc.wait() == 1) assert(l1.daemon.is_in_log(\"Wrong password for encrypted hsm_secret.\")) # Test",
"== [addr] assert decode['vout'][outnum2]['scriptPubKey']['type'] == 'witness_v0_keyhash' assert decode['vout'][outnum2]['scriptPubKey']['addresses'] == [addr]",
"decode['txid'] == prep2['txid'] # 6 inputs, 1 outputs. assert len(decode['vin'])",
"= bitcoind.rpc.decoderawtransaction(prep3['unsigned_tx']) assert decode['txid'] == prep3['txid'] # 4 inputs, 1",
"get those first 4 outputs. discard = l1.rpc.txdiscard(prep['txid']) assert discard['txid']",
"another password l1.daemon.opts.update({\"encrypted-hsm\": None}) l1.daemon.start(stdin=slave_fd, stderr=subprocess.STDOUT, wait_for_initialized=False) l1.daemon.wait_for_log(r'The hsm_secret is",
"exit status 1'): subprocess.check_call(l1.daemon.cmd_line) l1.daemon.opts.update({\"encrypted-hsm\": None}) master_fd, slave_fd = os.openpty()",
"range with pytest.raises(RpcError): l1.rpc.withdraw(' 1nwldj5', 2 * amount) # overall",
"in range(5): bitcoind.rpc.sendtoaddress(l1.rpc.newaddr()['bech32'], amount / 10**8) bitcoind.rpc.sendtoaddress(l1.rpc.newaddr('p2sh-segwit')['p2sh-segwit'], amount / 10**8)",
"match=r'not an unreleased txid'): l1.rpc.txdiscard(prep['txid']) wait_for(lambda: prep['txid'] in bitcoind.rpc.getrawmempool()) #",
"l1.db_query('SELECT COUNT(*) as c FROM outputs WHERE status=2')[0]['c'] == 2",
"= \"decrypt\" subprocess.check_call(cmd_line) l1.daemon.opts.pop(\"encrypted-hsm\") l1.daemon.start(stdin=slave_fd, wait_for_initialized=True) assert node_id == l1.rpc.getinfo()[\"id\"]",
"can leave funds! l1 = node_factory.get_node(random_hsm=True) addr = l1.rpc.newaddr()['bech32'] bitcoind.rpc.sendtoaddress(addr,",
"status 1'): subprocess.check_call(l1.daemon.cmd_line) # Test we cannot restore the same",
"outputs.append({l1.rpc.newaddr()['bech32']: Millisatoshi(amount * 100)}) prep = l1.rpc.txprepare(outputs=outputs) l1.rpc.txdiscard(prep['txid']) def test_txprepare(node_factory,",
"as c FROM outputs WHERE status=0')[0]['c'] == 1 l1.rpc.withdraw(waddr, 'all',",
"is to clamp the maxheight parameter to a positive small",
"used to check fuzz.\") def test_withdraw_nlocktime_fuzz(node_factory, bitcoind): \"\"\" Test that",
"flaky # noqa: F401 from pyln.client import RpcError, Millisatoshi from",
"-amount) with pytest.raises(RpcError, match=r'Cannot afford transaction'): l1.rpc.withdraw(waddr, amount * 100)",
"address we detect must match what was paid to. output",
"cmd_line[3] = password[:-1] subprocess.check_call(cmd_line) # Then test we can now",
"in txs if t['hash'] == txid][0] assert tx['blockheight'] == 0",
"'slow'}) with pytest.raises(RpcError, match=r'Need set \\'outputs\\' field.'): l1.rpc.call('txprepare', {'satoshi': Millisatoshi(amount",
"l1.rpc.txprepare([{addr: 'all'}]) decode = bitcoind.rpc.decoderawtransaction(prep4['unsigned_tx']) assert decode['txid'] == prep4['txid'] #",
"first 4 outputs. discard = l1.rpc.txdiscard(prep['txid']) assert discard['txid'] == prep['txid']",
"2518: ensure that ridiculous confirmation levels don't overflow The number",
"@unittest.skipIf(not COMPAT, \"needs COMPAT=1\") def test_deprecated_txprepare(node_factory, bitcoind): \"\"\"Test the deprecated",
"1000)}]) decode = bitcoind.rpc.decoderawtransaction(prep['unsigned_tx']) assert decode['txid'] == prep['txid'] # 4",
"can encrypt it offline cmd_line[1] = \"encrypt\" subprocess.check_call(cmd_line) # Now",
"wait_for(lambda: len(l1.rpc.listfunds()['outputs']) == 10) with pytest.raises(RpcError): l1.rpc.withdraw(destination=addr, satoshi=10000, feerate='normal', minconf=9999999)",
"annotated types types = [o['type'] for o in txs[1]['outputs']] changeidx",
"added assert l1.db_query('SELECT COUNT(*) as c FROM outputs WHERE status=0')[0]['c']",
"- Decimal(0.0003) assert decode['vout'][0]['scriptPubKey']['type'] == 'witness_v0_keyhash' assert decode['vout'][0]['scriptPubKey']['addresses'] == [addr]",
"decode['vout'][1]['value'] == Decimal(amount * 3.5) / 10**8 assert decode['vout'][1]['scriptPubKey']['type'] ==",
"if u['txid'] == out['txid']] assert(withdrawal[0]['amount'] == Decimal('0.02')) l1.bitcoin.generate_block(1) sync_blockheight(l1.bitcoin, [l1])",
"bitcoind): amount = 10000000 l1 = node_factory.get_node(random_hsm=True) bitcoind.rpc.sendtoaddress(l1.rpc.newaddr()['bech32'], amount /",
"l1.restart() # It goes backwards in blockchain just in case",
"in range(3 + chainparams['feeoutput']): if decode['vout'][i - 1]['value'] == Decimal('0.01500100'):",
"os.write(master_fd, password.encode(\"utf-8\")) l1.daemon.wait_for_log(\"Server started with public key\") id = l1.rpc.getinfo()[\"id\"]",
"now start it without password l1.daemon.opts.pop(\"encrypted-hsm\") l1.daemon.start(stdin=slave_fd, wait_for_initialized=True) assert node_id",
"our output matching logic\") @unittest.skipIf(not EXPERIMENTAL_FEATURES, \"Tests annotations which are",
"amount) with pytest.raises(RpcError): l1.rpc.withdraw('tb1prp33g0q5c5txsp9arysrx4k6zdkfs4nce4xj0gdcccefvpysxf3qsm03tq', 2 * amount) with pytest.raises(RpcError): l1.rpc.withdraw('tb1qrp33g0q5c5txsp9arysrx4k6zdkfs4nce4xj0gdcccefvpysxf3qxxxxxx',",
"l1, l2, l3 = node_factory.get_nodes(3) l1.fundwallet(10**6) # We should now",
"fuzz nLockTime for withdrawal transactions. Marked flaky \"just in case\"",
"levels don't overflow The number of confirmations is used to",
"password for encrypted hsm_secret.\")) # Test we can restore the",
"l1.bitcoin.rpc.sendtoaddress(addr, amount / 10**8 + 0.01) bitcoind.generate_block(1) wait_for(lambda: len(l1.rpc.listfunds()['outputs']) ==",
"'minconf': 2}) l1.rpc.call('txprepare', {'destination': addr, 'satoshi': Millisatoshi(amount * 100), 'feerate':",
"for v in decode['vin']] for utxo in utxos: assert utxo",
"should have an annotation on the output reading 'deposit' txs",
"overflow The number of confirmations is used to compute a",
"2 * amount) # Should have 6 outputs available. assert",
"a transaction that gave us the funds in the #",
"== [addr] assert decode['vout'][changenum]['scriptPubKey']['type'] == 'witness_v0_keyhash' def test_txsend(node_factory, bitcoind, chainparams):",
"select everything. The fix is to clamp the maxheight parameter",
"l1.rpc.withdraw('tb1qrp33g0q5c5txsp9arysrx4k6zdkfs4nce4xj0gdcccefvpysxf3q0sL5k7', 2 * amount) # Non-zero padding in 8-to-5 conversion",
"== 4 if chainparams['feeoutput'] else 3 # One output will",
"\"A big loop is used to check fuzz.\") def test_withdraw_nlocktime_fuzz(node_factory,",
"it should have an annotation on the output reading 'deposit'",
"vins = [\"{}:{}\".format(v['txid'], v['vout']) for v in decode['vin']] for utxo",
"two of them were marked as spent assert l1.db_query('SELECT COUNT(*)",
"with pytest.raises(RpcError): l1.rpc.withdraw('1pzry9x0s0muk', 2 * amount) # Invalid witness version",
"assert len(decode['vin']) == 10 # This will also work if",
"we can encrypt it offline cmd_line[1] = \"encrypt\" subprocess.check_call(cmd_line) #",
"decode['vout'][0]['value'] > Decimal(amount * 6) / 10**8 - Decimal(0.0002) assert",
"to pass the encrypted-hsm startup option l1.stop() with pytest.raises(subprocess.CalledProcessError, match=r'returned",
"txid'): l1.rpc.txdiscard(prep['txid']) # Discard everything, we should now spend all",
"cmd_line = [\"tools/hsmtool\", \"decrypt\", hsm_path, \"A wrong pass\"] with pytest.raises(subprocess.CalledProcessError):",
"discard = l1.rpc.txdiscard(prep['txid']) assert discard['txid'] == prep['txid'] assert discard['unsigned_tx'] ==",
"== l1.rpc.getinfo()[\"id\"] # this test does a 'listtransactions' on a",
"in l1.rpc.listfunds()['outputs']] == ['confirmed'] * 10) with pytest.raises(RpcError, match=r'not an",
"Cannot discard twice. with pytest.raises(RpcError, match=r'not an unreleased txid'): l1.rpc.txdiscard(prep['txid'])",
"for accessing random memory or null txs = l1.rpc.listtransactions()['transactions'] tx",
"out of range with pytest.raises(RpcError): l1.rpc.withdraw(' 1nwldj5', 2 * amount)",
"import Decimal from fixtures import * # noqa: F401,F403 from",
"2 # Some fees will be taken assert decode['vout'][0]['value'] <",
"None, 1]) l1.rpc.call('txprepare', [addr, Millisatoshi(amount * 100)]) # Object type",
"assert l1.db_query('SELECT COUNT(*) as c FROM outputs WHERE status=0')[0]['c'] ==",
"afford transaction'): l1.rpc.withdraw(waddr, amount * 100) out = l1.rpc.withdraw(waddr, 2",
"# Signed tx should have same txid decode = bitcoind.rpc.decoderawtransaction(out['tx'])",
"u['txid'] == out['txid']] assert(withdrawal[0]['amount'] == Decimal('0.02')) l1.bitcoin.generate_block(1) sync_blockheight(l1.bitcoin, [l1]) #",
"the funding txid: assert(outputs[0]['txid'] == fundingtx['txid']) # Confirm the channel",
"/ 10**8) bitcoind.generate_block(1) wait_for(lambda: len(l1.rpc.listfunds()['outputs']) == 1) outputs = []",
"= l1.rpc.withdraw(addr, 10**3)[\"tx\"] nlocktime = node_factory.bitcoind.rpc.decoderawtransaction(tx)[\"locktime\"] tip = node_factory.bitcoind.rpc.getblockcount() assert",
"== prep5['txid'] # Check that correct utxos are included assert",
"l1.fundwallet(10**8) bitcoind.generate_block(1) sync_blockheight(bitcoind, [l1]) wait_for(lambda: len(l1.rpc.listfunds()['outputs']) == 7) # Array",
"node_factory.bitcoind.rpc.getblockcount() assert nlocktime > 0 and nlocktime <= tip @flaky",
"tip = node_factory.bitcoind.rpc.getblockcount() assert decoded[\"locktime\"] > 0 if decoded[\"locktime\"] <",
"l1 = node_factory.get_node(may_fail=True) # May fail when started without key",
"withdrawal = [u for u in unspent if u['txid'] ==",
"sync_blockheight(l1.bitcoin, [l1]) # Check that there are no unconfirmed outputs",
"a P2WPKH address this time. addr = l1.rpc.newaddr(\"bech32\")['bech32'] l1.rpc.withdraw(addr, \"all\")",
"# We should have a change output, so this is",
"hsm_secret is encrypted') os.write(master_fd, password[2:].encode(\"utf-8\")) assert(l1.daemon.proc.wait() == 1) assert(l1.daemon.is_in_log(\"Wrong password",
"password l1.daemon.opts.update({\"encrypted-hsm\": None}) l1.daemon.start(stdin=slave_fd, stderr=subprocess.STDOUT, wait_for_initialized=False) l1.daemon.wait_for_log(r'The hsm_secret is encrypted')",
"Add some funds to withdraw later: both bech32 and p2sh",
"decode['txid'] == prep['txid'] # All 10 inputs assert len(decode['vin']) ==",
"decode['vout'][0]['value'] > Decimal(amount * 4) / 10**8 - Decimal(0.0002) assert",
"satoshis or all, not .*'): l1.rpc.call('txprepare', [addr, 'slow']) with pytest.raises(RpcError,",
"{addr: 'all'}]) prep5 = l1.rpc.txprepare([{addr: Millisatoshi(amount * 3 * 500",
"out['txid']] assert(withdrawal[0]['amount'] == Decimal('0.02')) l1.bitcoin.generate_block(1) sync_blockheight(l1.bitcoin, [l1]) # Check that",
"node_factory.get_node(random_hsm=True) addr = l1.rpc.newaddr()['bech32'] # Add some funds to withdraw",
"# Make sure bitcoind received the withdrawal unspent = l1.bitcoin.rpc.listunspent(0)",
"Millisatoshi(amount * 100), 'slow', 1]) l1.rpc.call('txprepare', [addr, Millisatoshi(amount * 100),",
"https://bc-2.jp/tools/bech32demo/index.html waddr = 'bcrt1qw508d6qejxtdg4y5r3zarvary0c5xw7kygt080' with pytest.raises(RpcError): l1.rpc.withdraw('xx1qw508d6qejxtdg4y5r3zarvary0c5xw7kxpjzsx', 2 * amount)",
"(we are ordering by blockheight and txindex, so that order",
"yet unconfirmed channel def test_fundchannel_listtransaction(node_factory, bitcoind): l1, l2 = node_factory.get_nodes(2)",
"l1, l2 = node_factory.get_nodes(2) l1.fundwallet(10**6) l1.connect(l2) txid = l1.rpc.fundchannel(l2.info['id'], 10**5)['txid']",
"l1.rpc.withdraw(addr, \"all\") bitcoind.generate_block(1) time.sleep(1) # The address we detect must",
"Discard everything, we should now spend all inputs. l1.rpc.txdiscard(prep2['txid']) l1.rpc.txdiscard(prep3['txid'])",
"and txindex, so that order should be ok) txs =",
"2 * amount) # Empty HRP with pytest.raises(RpcError): l1.rpc.withdraw('1pzry9x0s0muk', 2",
"pytest.raises(RpcError): l1.rpc.withdraw('not an address', amount) with pytest.raises(RpcError): l1.rpc.withdraw(waddr, 'not an",
"the master seed l1.stop() l1.daemon.opts.update({\"encrypted-hsm\": None}) l1.daemon.start(stdin=slave_fd, wait_for_initialized=False) l1.daemon.wait_for_log(r'The hsm_secret",
"the channel annotation on the funding output peers = l1.rpc.listpeers()['peers']",
"= node_factory.get_nodes(2) l1.fundwallet(10**6) l1.connect(l2) txid = l1.rpc.fundchannel(l2.info['id'], 10**5)['txid'] # next",
"i in range(100): addr = l1.rpc.newaddr()[\"bech32\"] withdraw = l1.rpc.withdraw(addr, 10**3)",
"wants all satoshi. The count of outputs can\\'t be more",
"\"hsm_secret\") # We need to simulate a terminal to use",
"cmd_line[1] = \"decrypt\" subprocess.check_call(cmd_line) l1.daemon.opts.pop(\"encrypted-hsm\") l1.daemon.start(stdin=slave_fd, wait_for_initialized=True) assert node_id ==",
"we can also decrypt if encrypted with hsmtool cmd_line[1] =",
"== '1000000000msat') # ... and all other output should be",
"10**5) # We should have one output available, and it",
"and not encrypted hsm_secret l1.stop() l1.daemon.opts.update({\"encrypted-hsm\": None}) l1.daemon.start(stdin=slave_fd, wait_for_initialized=False) l1.daemon.wait_for_log(r'The",
"amount) # overall max length exceeded with pytest.raises(RpcError): l1.rpc.withdraw('an84characterslonghumanreadablepartthatcontainsthenumber1andtheexcludedcharactersbio1569pvx', 2",
"field.'): l1.rpc.call('txprepare', {'destination': addr, 'feerate': 'slow'}) with pytest.raises(RpcError, match=r'Need set",
"we don't set the nLockTime to 0 for withdrawal transactions.",
"wait_for_initialized=False) l1.daemon.wait_for_log(r'The hsm_secret is encrypted') os.write(master_fd, password.encode(\"utf-8\")) l1.daemon.wait_for_log(\"Server started with",
"output peers = l1.rpc.listpeers()['peers'] assert(len(peers) == 1 and len(peers[0]['channels']) ==",
"# Add some funds to withdraw later for i in",
"Now attempt to withdraw some (making sure we collect multiple",
"500 + 100000)}, {addr: Millisatoshi(amount * 3 * 500 -",
"# All 10 inputs assert len(decode['vin']) == 10 @unittest.skipIf(TEST_NETWORK !=",
"Decimal(amount * 3) / 10**8: changenum = 0 else: assert",
"assert decode['txid'] == prep3['txid'] # 4 inputs, 1 outputs. assert",
"assert len(decode['vout']) == 2 if not chainparams['feeoutput'] else 3 #",
"def test_txprepare_multi(node_factory, bitcoind): amount = 10000000 l1 = node_factory.get_node(random_hsm=True) bitcoind.rpc.sendtoaddress(l1.rpc.newaddr()['bech32'],",
"with public key\") assert node_id == l1.rpc.getinfo()[\"id\"] l1.stop() # And",
"4 inputs, 3 outputs(include change). assert len(decode['vin']) == 4 assert",
"a wrong password ! cmd_line = [\"tools/hsmtool\", \"decrypt\", hsm_path, \"A",
"+ 0.01) bitcoind.generate_block(1) wait_for(lambda: len(l1.rpc.listfunds()['outputs']) == 10) # Try passing",
"'witness_v0_keyhash' assert decode['vout'][outnum1]['scriptPubKey']['addresses'] == [addr] assert decode['vout'][outnum2]['scriptPubKey']['type'] == 'witness_v0_keyhash' assert",
"\"Test relies on a number of example addresses valid only",
"l1.rpc.withdraw('BC1QR508D6QEJXTDG4Y5R3ZARVARYV98GJ9P', 2 * amount) # Mixed case with pytest.raises(RpcError): l1.rpc.withdraw('tb1qrp33g0q5c5txsp9arysrx4k6zdkfs4nce4xj0gdcccefvpysxf3q0sL5k7',",
"pytest.raises(RpcError, match=r'Need set \\'outputs\\' field.'): l1.rpc.call('txprepare', {'destination': addr, 'feerate': 'slow'})",
"prep4['txid'] # 10 inputs, 1 outputs. assert len(decode['vin']) == 10",
"l1.daemon.opts.update({\"encrypted-hsm\": None}) l1.daemon.start(stdin=slave_fd, wait_for_initialized=False) l1.daemon.wait_for_log(r'The hsm_secret is encrypted') os.write(master_fd, password.encode(\"utf-8\"))",
"will be taken assert decode['vout'][0]['value'] < Decimal(amount * 10) /",
"program length for witness version 0 (per BIP141) with pytest.raises(RpcError):",
"= node_factory.get_nodes(3) l1.fundwallet(10**6) # We should now have a transaction",
"in case\" as we fuzz from 0 to 100 with",
"l1.stop() # Test we cannot start the same wallet without",
"len(decode['vout']) == 3 if chainparams['feeoutput'] else 2 assert decode['vout'][1]['value'] ==",
"assert len(decode['vin']) == 4 assert len(decode['vout']) == 2 if not",
"waddr = l2.rpc.newaddr('bech32')['bech32'] l1.rpc.withdraw(waddr, 2 * amount) bitcoind.generate_block(1) # Make",
"1 fundidx = 1 - changeidx assert(types[changeidx] == 'deposit' and",
"check that outputs were added assert l1.db_query('SELECT COUNT(*) as c",
"don't overflow The number of confirmations is used to compute",
"def test_withdraw_nlocktime(node_factory): \"\"\" Test that we don't set the nLockTime",
"* 500 - 100000)}]) decode = bitcoind.rpc.decoderawtransaction(prep5['unsigned_tx']) assert decode['txid'] ==",
"l1.stop() l1.daemon.opts.update({\"encrypted-hsm\": None}) l1.daemon.start(stdin=slave_fd, wait_for_initialized=False) l1.daemon.wait_for_log(r'The hsm_secret is encrypted') os.write(master_fd,",
"3 * 1000)}]) out = l1.rpc.txsend(prep['txid']) # Cannot discard after",
"if encrypted with hsmtool cmd_line[1] = \"decrypt\" subprocess.check_call(cmd_line) l1.daemon.opts.pop(\"encrypted-hsm\") l1.daemon.start(stdin=slave_fd,",
"len(decode['vin']) == 10 # This will also work if we",
"decode['vin']] for utxo in utxos: assert utxo in vins def",
"decode['txid'] == withdrawal['txid'] # Check that correct utxos are included",
"8-to-5 conversion with pytest.raises(RpcError): l1.rpc.withdraw('tb1qrp33g0q5c5txsp9arysrx4k6zdkfs4nce4xj0gdcccefvpysxf3pjxtptv', 2 * amount) # Should",
"output changed to confirmed bitcoind.generate_block(3) sync_blockheight(bitcoind, [l1, l2]) outputs =",
"with same bitcoind can leave funds! l1 = node_factory.get_node(random_hsm=True) addr",
"assert(idx in [0, 1] and out['value'] == 10**6) # ...",
"on a yet unconfirmed channel def test_fundchannel_listtransaction(node_factory, bitcoind): l1, l2",
"only_one, wait_for, sync_blockheight, EXPERIMENTAL_FEATURES, COMPAT, VALGRIND ) import os import",
"unspent = l1.bitcoin.rpc.listunspent(0) withdrawal = [u for u in unspent",
"assert decode['vout'][0]['value'] > Decimal(amount * 10) / 10**8 - Decimal(0.0003)",
"/ 10**8) bitcoind.rpc.sendtoaddress(l1.rpc.newaddr('p2sh-segwit')['p2sh-segwit'], amount / 10**8) bitcoind.generate_block(1) wait_for(lambda: [o['status'] for",
"deprecated old-style: txprepare {destination} {satoshi} {feerate} {minconf} \"\"\" amount =",
"assert(set([None]) == set(types)) ########################################################################## # Let's now open a channel.",
"test that we can also decrypt if encrypted with hsmtool",
"# Test we cannot restore the same wallet with another",
"l2. # lightningd uses P2SH-P2WPKH waddr = l2.rpc.newaddr('bech32')['bech32'] l1.rpc.withdraw(waddr, 2",
"100000)}, {addr: Millisatoshi(amount * 3 * 500 - 100000)}]) decode",
"overall max length exceeded with pytest.raises(RpcError): l1.rpc.withdraw('an84characterslonghumanreadablepartthatcontainsthenumber1andtheexcludedcharactersbio1569pvx', 2 * amount)",
"maxheight parameter to a positive small number. \"\"\" amount =",
"assert node_id == l1.rpc.getinfo()[\"id\"] # this test does a 'listtransactions'",
"bitcoind.generate_block(1) wait_for(lambda: len(l1.rpc.listfunds()['outputs']) == 10) with pytest.raises(RpcError): l1.rpc.withdraw(destination=addr, satoshi=10000, feerate='normal',",
"match the funding txid: assert(outputs[0]['txid'] == fundingtx['txid']) # Confirm the",
"os.write(master_fd, password.encode(\"utf-8\")) l1.daemon.wait_for_log(\"Server started with public key\") assert id ==",
"same wallet with the same password l1.daemon.start(stdin=slave_fd, wait_for_initialized=False) l1.daemon.wait_for_log(r'The hsm_secret",
"goes backwards in blockchain just in case there was a",
"txs[0] output = tx['outputs'][idx] assert(output['type'] == 'deposit' and output['satoshis'] ==",
"l1.rpc.withdraw('not an address', amount) with pytest.raises(RpcError): l1.rpc.withdraw(waddr, 'not an amount')",
"EXPERIMENTAL_FEATURES, COMPAT, VALGRIND ) import os import pytest import subprocess",
"from previous runs. l1 = node_factory.get_node(random_hsm=True) l2 = node_factory.get_node(random_hsm=True) addr",
"with public key\") node_id = l1.rpc.getinfo()[\"id\"] l1.stop() # We can't",
"- changeidx assert(types[changeidx] == 'deposit' and types[fundidx] == 'channel_funding') #",
"= [t for t in txs if t['hash'] == txid][0]",
"v['vout']) for v in decode['vin']] for utxo in utxos: assert",
"l1.rpc.txprepare(outputs=[{addr: Millisatoshi(amount * 3 * 1000)}]) decode = bitcoind.rpc.decoderawtransaction(prep['unsigned_tx']) assert",
"be correct. for i in range(3 + chainparams['feeoutput']): if decode['vout'][i",
"wallet with the same password l1.daemon.start(stdin=slave_fd, wait_for_initialized=False) l1.daemon.wait_for_log(r'The hsm_secret is",
"= 1 elif decode['vout'][1]['value'] == Decimal(amount * 3) / 10**8:",
"l1.rpc.withdraw(waddr, 2 * amount) bitcoind.generate_block(1) # Make sure l2 received",
"2 transactions, the second one should be the funding tx",
"decode = bitcoind.rpc.decoderawtransaction(prep['unsigned_tx']) assert decode['txid'] == prep['txid'] # All 10",
"( only_one, wait_for, sync_blockheight, EXPERIMENTAL_FEATURES, COMPAT, VALGRIND ) import os",
"each output. for i in decode['vin']: assert l1.daemon.is_in_log('wallet: reserved output",
"a utxo set utxos = [utxo[\"txid\"] + \":\" + str(utxo[\"output\"])",
"\"needs COMPAT=1\") def test_deprecated_txprepare(node_factory, bitcoind): \"\"\"Test the deprecated old-style: txprepare",
"1 elif decode['vout'][1]['value'] == Decimal(amount * 3) / 10**8: changenum",
"as c FROM outputs WHERE status=2')[0]['c'] == 6 # Simple",
"l1.daemon.start(stdin=slave_fd, stderr=subprocess.STDOUT, wait_for_initialized=False) l1.daemon.wait_for_log(r'The hsm_secret is encrypted') os.write(master_fd, password[2:].encode(\"utf-8\")) assert(l1.daemon.proc.wait()",
"addr = l1.rpc.newaddr()['bech32'] # Add some funds to withdraw later",
"COUNT(*) as c FROM outputs WHERE status=2')[0]['c'] == 2 #",
"--encrypted-hsm l1.daemon.opts.pop(\"encrypted-hsm\") with pytest.raises(subprocess.CalledProcessError, match=r'returned non-zero exit status 1'): subprocess.check_call(l1.daemon.cmd_line)",
"len(l1.rpc.listfunds()['outputs']) == 7) # Array type with pytest.raises(RpcError, match=r'.* should",
"password.encode(\"utf-8\")) l1.daemon.wait_for_log(\"Server started with public key\") assert id == l1.rpc.getinfo()[\"id\"]",
"and outputs[0]['status'] == 'unconfirmed') # It should also match the",
"= l1.bitcoin.rpc.listunspent(0) withdrawal = [u for u in unspent if",
"4 # Simple test for withdrawal to P2WPKH # Address",
"= txs[0] output = tx['outputs'][idx] assert(output['type'] == 'deposit' and output['satoshis']",
"= l1.rpc.listtransactions()['transactions'] assert(len(txs) == 2 and txs[1]['hash'] == fundingtx['txid']) #",
"outputs are gone, but change output has arrived. wait_for(lambda: len(l1.rpc.listfunds()['outputs'])",
"'listtransactions' on a yet unconfirmed channel def test_fundchannel_listtransaction(node_factory, bitcoind): l1,",
"detect must match what was paid to. output = only_one(l1.rpc.listfunds()['outputs'])",
"tip @flaky @unittest.skipIf(VALGRIND, \"A big loop is used to check",
"node_id == l1.rpc.getinfo()[\"id\"] # this test does a 'listtransactions' on",
"encrypted') os.write(master_fd, password.encode(\"utf-8\")) l1.daemon.wait_for_log(\"Server started with public key\") assert node_id",
"sure additional two of them were marked as spent assert",
"= l1.rpc.withdraw(waddr, 2 * amount, utxos=utxos) decode = bitcoind.rpc.decoderawtransaction(withdrawal['tx']) assert",
"output['address'] == addr # Send all our money to a",
"6 inputs, 1 outputs. assert len(decode['vin']) == 6 assert len(decode['vout'])",
"addr # Send all our money to a P2WPKH address",
"a 10% probability. \"\"\" l1 = node_factory.get_node(1) l1.fundwallet(10**8) for i",
"funding transaction # annotated as channel open and deposit. l1.connect(l2)",
"if i == idx: continue if 'type' in o: types.append(o['type'])",
"password.encode(\"utf-8\")) l1.daemon.wait_for_log(\"Server started with public key\") id = l1.rpc.getinfo()[\"id\"] l1.stop()",
"COUNT(*) as c FROM outputs WHERE status=2')[0]['c'] == 8 #",
"= i - 1 elif decode['vout'][i - 1]['value'] == Decimal('0.01499900'):",
"minconf=0) assert l1.db_query('SELECT COUNT(*) as c FROM outputs WHERE status=0')[0]['c']",
"1) assert(l1.daemon.is_in_log(\"Wrong password for encrypted hsm_secret.\")) # Test we can",
"No separator character with pytest.raises(RpcError): l1.rpc.withdraw('pzry9x0s0muk', 2 * amount) #",
"== Decimal(amount * 3) / 10**8: changenum = 1 elif",
"prep4 and get all funds again l1.rpc.txdiscard(prep5['txid']) with pytest.raises(RpcError, match=r'this",
"None}) l1.daemon.start(stdin=slave_fd, stderr=subprocess.STDOUT, wait_for_initialized=False) l1.daemon.wait_for_log(r'The hsm_secret is encrypted') os.write(master_fd, password[2:].encode(\"utf-8\"))",
"smaller than the number of confirmations we wrap around and",
"and it should be unconfirmed outputs = l1.rpc.listfunds()['outputs'] assert(len(outputs) ==",
"it should be unconfirmed outputs = l1.rpc.listfunds()['outputs'] assert(len(outputs) == 1",
"l1.rpc.call('txprepare', {'destination': addr, 'satoshi': Millisatoshi(amount * 100), 'feerate': '2000perkw'}) l1.rpc.call('txprepare',",
"Accessing a null column # and crashed the daemon for",
"set \\'outputs\\' field.'): l1.rpc.call('txprepare', {'destination': addr, 'feerate': 'slow'}) with pytest.raises(RpcError,",
"l1.daemon.wait_for_log(\"Server started with public key\") assert node_id == l1.rpc.getinfo()[\"id\"] l1.stop()",
"out = outputs[0] idx = out['output'] assert(idx in [0, 1]",
"the withdrawal. wait_for(lambda: len(l2.rpc.listfunds()['outputs']) == 1) outputs = l2.db_query('SELECT value",
"in enumerate(tx['outputs']): if i == idx: continue if 'type' in",
"with pytest.raises(RpcError): l1.rpc.withdraw('tb1prp33g0q5c5txsp9arysrx4k6zdkfs4nce4xj0gdcccefvpysxf3qsm03tq', 2 * amount) with pytest.raises(RpcError): l1.rpc.withdraw('tb1qrp33g0q5c5txsp9arysrx4k6zdkfs4nce4xj0gdcccefvpysxf3qxxxxxx', 2",
"with prompt and key derivation.\") def test_hsm_secret_encryption(node_factory): l1 = node_factory.get_node(may_fail=True)",
"6 assert len(decode['vout']) == 1 if not chainparams['feeoutput'] else 2",
"a change output, so this is exact assert len(decode['vout']) ==",
"= l1.rpc.newaddr()[\"bech32\"] withdraw = l1.rpc.withdraw(addr, 10**3) bitcoind.generate_block(1) l1.daemon.wait_for_log('Owning output .*",
"+ 1) # Change address should appear in listfunds() assert",
"in l1.rpc.listfunds()['outputs']] == ['confirmed'] * 10) # It should have",
"assert utxo in vins def test_minconf_withdraw(node_factory, bitcoind): \"\"\"Issue 2518: ensure",
"EXPERIMENTAL_FEATURES, \"Tests annotations which are compiled only with experimental features\")",
"* 10) / 10**8 assert decode['vout'][0]['value'] > Decimal(amount * 10)",
"have 6 outputs available. assert l1.db_query('SELECT COUNT(*) as c FROM",
"pytest.raises(RpcError): l1.rpc.withdraw('xx1qw508d6qejxtdg4y5r3zarvary0c5xw7kxpjzsx', 2 * amount) with pytest.raises(RpcError): l1.rpc.withdraw('tb1pw508d6qejxtdg4y5r3zarvary0c5xw7kdl9fad', 2 *",
"str(utxo[\"output\"]) for utxo in l1.rpc.listfunds()[\"outputs\"]][:4] withdrawal = l1.rpc.withdraw(waddr, 2 *",
"assert decode['vout'][outnum1]['scriptPubKey']['type'] == 'witness_v0_keyhash' assert decode['vout'][outnum1]['scriptPubKey']['addresses'] == [addr] assert decode['vout'][outnum2]['scriptPubKey']['type']",
"some funds to withdraw later: both bech32 and p2sh for",
"with public key\") assert id == l1.rpc.getinfo()[\"id\"] @unittest.skipIf(VALGRIND, \"It does",
"# Now send some money to l2. # lightningd uses",
"len(l1.rpc.listfunds()['outputs']) == 10) prep = l1.rpc.txprepare(outputs=[{addr: Millisatoshi(amount * 3 *",
"test_hsm_secret_encryption(node_factory): l1 = node_factory.get_node(may_fail=True) # May fail when started without",
"encrypt an already-existing and not encrypted hsm_secret l1.stop() l1.daemon.opts.update({\"encrypted-hsm\": None})",
"= bitcoind.rpc.decoderawtransaction(prep4['unsigned_tx']) assert decode['txid'] == prep4['txid'] # 10 inputs, 1",
"with pytest.raises(RpcError): l1.rpc.withdraw('xx1qw508d6qejxtdg4y5r3zarvary0c5xw7kxpjzsx', 2 * amount) with pytest.raises(RpcError): l1.rpc.withdraw('tb1pw508d6qejxtdg4y5r3zarvary0c5xw7kdl9fad', 2",
"chainparams['feeoutput'] else 2 # Some fees will be taken assert",
"1 and outputs[0]['status'] == 'unconfirmed') # It should also match",
"ridiculous confirmation levels don't overflow The number of confirmations is",
"decode = bitcoind.rpc.decoderawtransaction(prep4['unsigned_tx']) assert decode['txid'] == prep4['txid'] # 10 inputs,",
"= l1.rpc.fundchannel(l2.info['id'], 10**5)['txid'] # next call warned about SQL Accessing",
"blockheight and txindex, so that order should be ok) txs",
"sync_blockheight(bitcoind, [l1]) wait_for(lambda: len(l1.rpc.listfunds()['outputs']) == 7) # Array type with",
"= node_factory.bitcoind.rpc.getblockcount() assert decoded[\"locktime\"] > 0 if decoded[\"locktime\"] < tip:",
"os.openpty() l1.daemon.start(stdin=slave_fd, stderr=subprocess.STDOUT, wait_for_initialized=False) l1.daemon.wait_for_log(r'The hsm_secret is encrypted') os.write(master_fd, password.encode(\"utf-8\"))",
"master_fd, slave_fd = os.openpty() # Encrypt the master seed l1.stop()",
"in vins # We should have a change output, so",
"+ \":\" + str(utxo[\"output\"]) for utxo in l1.rpc.listfunds()[\"outputs\"]][:4] withdrawal =",
"leave funds! l1 = node_factory.get_node(random_hsm=True) addr = l1.rpc.newaddr()['bech32'] bitcoind.rpc.sendtoaddress(addr, 0.1)",
"pytest.raises(RpcError): l1.rpc.withdraw('tb1qrp33g0q5c5txsp9arysrx4k6zdkfs4nce4xj0gdcccefvpysxf3pjxtptv', 2 * amount) # Should have 6 outputs",
"for withdrawal to P2WSH # Address from: https://bc-2.jp/tools/bech32demo/index.html waddr =",
"decode['vout'][outnum2]['scriptPubKey']['addresses'] == [addr] assert decode['vout'][changenum]['scriptPubKey']['type'] == 'witness_v0_keyhash' def test_txsend(node_factory, bitcoind,",
"decode['vout'][0]['scriptPubKey']['addresses'] == [addr] # If I cancel the first one,",
"of outputs can\\'t be more than 1'): prep5 = l1.rpc.txprepare([{addr:",
"address should appear in listfunds() assert decode['vout'][changenum]['scriptPubKey']['addresses'][0] in [f['address'] for",
"2 * amount) # Non-zero padding in 8-to-5 conversion with",
"can encrypt an already-existing and not encrypted hsm_secret l1.stop() l1.daemon.opts.update({\"encrypted-hsm\":",
"fuzz from 0 to 100 with a 10% probability. \"\"\"",
"for i in range(5): bitcoind.rpc.sendtoaddress(l1.rpc.newaddr()['bech32'], amount / 10**8) bitcoind.rpc.sendtoaddress(l1.rpc.newaddr('p2sh-segwit')['p2sh-segwit'], amount",
"relies on a number of example addresses valid only in",
"with pytest.raises(RpcError): l1.rpc.withdraw('pzry9x0s0muk', 2 * amount) # Empty HRP with",
"== 4 # Simple test for withdrawal to P2WPKH #",
"the daemon without telling it explicitly \"\"\" # Previous runs",
"l1.rpc.txprepare([{addr: 'all'}]) decode = bitcoind.rpc.decoderawtransaction(prep['unsigned_tx']) assert decode['txid'] == prep['txid'] #",
"decode['vout'][1]['scriptPubKey']['type'] == 'witness_v0_keyhash' assert decode['vout'][1]['scriptPubKey']['addresses'] == [addr] # Discard prep4",
"P2WPKH # Address from: https://bc-2.jp/tools/bech32demo/index.html waddr = 'bcrt1qw508d6qejxtdg4y5r3zarvary0c5xw7kygt080' with pytest.raises(RpcError):",
"decode['vout'][outnum2]['scriptPubKey']['type'] == 'witness_v0_keyhash' assert decode['vout'][outnum2]['scriptPubKey']['addresses'] == [addr] assert decode['vout'][changenum]['scriptPubKey']['type'] ==",
"has arrived. wait_for(lambda: len(l1.rpc.listfunds()['outputs']) == 10 - len(decode['vin']) + 1)",
"0 to 100 with a 10% probability. \"\"\" l1 =",
"== 'witness_v0_keyhash' assert decode['vout'][outnum1]['scriptPubKey']['addresses'] == [addr] assert decode['vout'][outnum2]['scriptPubKey']['type'] == 'witness_v0_keyhash'",
"fees will be paid. assert decode['vout'][0]['value'] < Decimal(amount * 6)",
"types.append(o['type']) else: types.append(None) assert(set([None]) == set(types)) ########################################################################## # Let's now",
"assert len(decode['vin']) == 4 vins = [\"{}:{}\".format(v['txid'], v['vout']) for v",
"with pytest.raises(RpcError, match=r'this destination wants all satoshi. The count of",
"can also decrypt if encrypted with hsmtool cmd_line[1] = \"decrypt\"",
"else: changenum = i - 1 assert decode['vout'][outnum1]['scriptPubKey']['type'] == 'witness_v0_keyhash'",
"c FROM outputs WHERE status=2')[0]['c'] == 2 # Now send",
"* 4) / 10**8 - Decimal(0.0002) assert decode['vout'][0]['scriptPubKey']['type'] == 'witness_v0_keyhash'",
"in ['witness_v0_keyhash', 'fee'] # Now prepare one with no change.",
"option l1.stop() with pytest.raises(subprocess.CalledProcessError, match=r'returned non-zero exit status 1'): subprocess.check_call(l1.daemon.cmd_line)",
"+ str(utxo[\"output\"]) for utxo in l1.rpc.listfunds()[\"outputs\"]][:4] withdrawal = l1.rpc.withdraw(waddr, 2",
"l1.daemon.start(stdin=slave_fd, wait_for_initialized=False) l1.daemon.wait_for_log(r'The hsm_secret is encrypted') os.write(master_fd, password.encode(\"utf-8\")) l1.daemon.wait_for_log(\"Server started",
"we need to pass the encrypted-hsm startup option l1.stop() with",
"pytest.raises(RpcError, match=r'Need set \\'satoshi\\' field.'): l1.rpc.call('txprepare', [addr]) with pytest.raises(RpcError, match=r'Could",
"fundingtx['txid']) # Check the annotated types types = [o['type'] for",
"= [\"tools/hsmtool\", \"decrypt\", hsm_path, \"A wrong pass\"] with pytest.raises(subprocess.CalledProcessError): subprocess.check_call(cmd_line)",
"l1.rpc.txdiscard(prep5['txid']) with pytest.raises(RpcError, match=r'this destination wants all satoshi. The count",
"else 2 assert decode['vout'][1]['value'] == Decimal(amount * 3.5) / 10**8",
"bitcoind can leave funds! l1 = node_factory.get_node(random_hsm=True) addr = l1.rpc.newaddr()['bech32']",
"2 * amount) # overall max length exceeded with pytest.raises(RpcError):",
"pytest.raises(RpcError, match=r'not an unreleased txid'): l1.rpc.txdiscard(prep['txid']) wait_for(lambda: prep['txid'] in bitcoind.rpc.getrawmempool())",
"outputs. assert len(decode['vin']) == 10 assert len(decode['vout']) == 1 if",
"field.'): l1.rpc.call('txprepare', {'satoshi': Millisatoshi(amount * 100), 'feerate': '10perkw', 'minconf': 2})",
"to compute a maximum height that is to be accepted.",
"1 and len(peers[0]['channels']) == 1) scid = peers[0]['channels'][0]['short_channel_id'] assert(txs[1]['outputs'][fundidx]['channel'] ==",
"deposit. l1.connect(l2) fundingtx = l1.rpc.fundchannel(l2.info['id'], 10**5) # We should have",
"assert decode['vout'][1]['scriptPubKey']['addresses'] == [addr] # Discard prep4 and get all",
"make sure an additional two of them were marked as",
"node_factory.bitcoind.rpc.getblockcount() assert decoded[\"locktime\"] > 0 if decoded[\"locktime\"] < tip: return",
"= [o['type'] for o in txs[1]['outputs']] changeidx = 0 if",
"subprocess.check_call(cmd_line) l1.daemon.opts.pop(\"encrypted-hsm\") l1.daemon.start(stdin=slave_fd, wait_for_initialized=True) assert node_id == l1.rpc.getinfo()[\"id\"] # this",
"nLockTime to 0 for withdrawal transactions. \"\"\" l1 = node_factory.get_node(1)",
"* 100)]) # Object type with pytest.raises(RpcError, match=r'Need set \\'outputs\\'",
"L1 will forget all about it. l1.restart() # It goes",
"parse destination address.*'): l1.rpc.call('txprepare', [Millisatoshi(amount * 100), 'slow', 1]) l1.rpc.call('txprepare',",
"\"\"\" # Previous runs with same bitcoind can leave funds!",
"o['scriptPubKey']['addresses'] == [addr] else: assert o['scriptPubKey']['type'] in ['witness_v0_keyhash', 'fee'] #",
"decode['vout'][i - 1]['value'] == Decimal('0.01499900'): outnum2 = i - 1",
"WHERE status=2')[0]['c'] == 6 # Simple test for withdrawal to",
"= i - 1 assert decode['vout'][outnum1]['scriptPubKey']['type'] == 'witness_v0_keyhash' assert decode['vout'][outnum1]['scriptPubKey']['addresses']",
"/ 10**8][0] for i, o in enumerate(decode['vout']): if i ==",
"the funding output peers = l1.rpc.listpeers()['peers'] assert(len(peers) == 1 and",
"password l1.daemon.opts.pop(\"encrypted-hsm\") l1.daemon.start(stdin=slave_fd, wait_for_initialized=True) assert node_id == l1.rpc.getinfo()[\"id\"] l1.stop() #",
"\"\"\"Test the deprecated old-style: txprepare {destination} {satoshi} {feerate} {minconf} \"\"\"",
"amount) with pytest.raises(RpcError): l1.rpc.withdraw(waddr, 'not an amount') with pytest.raises(RpcError): l1.rpc.withdraw(waddr,",
"l1.rpc.withdraw('BC13W508D6QEJXTDG4Y5R3ZARVARY0C5XW7KN40WF2', 2 * amount) # Invalid program length for witness",
"l1.rpc.withdraw('tb1qrp33g0q5c5txsp9arysrx4k6zdkfs4nce4xj0gdcccefvpysxf3pjxtptv', 2 * amount) # Should have 6 outputs available.",
"node_factory.get_node(may_fail=True) addr = chainparams['example_addr'] # Add some funds to withdraw",
"set \\'satoshi\\' field.'): l1.rpc.call('txprepare', [addr]) with pytest.raises(RpcError, match=r'Could not parse",
"'feerate': '2000perkw'}) l1.rpc.call('txprepare', {'destination': addr, 'satoshi': Millisatoshi(amount * 100)}) def",
"into the db to check that outputs were added assert",
"an additional two of them were marked as spent assert",
"Object type with pytest.raises(RpcError, match=r'Need set \\'outputs\\' field.'): l1.rpc.call('txprepare', {'destination':",
"len(l1.rpc.listfunds()['outputs']) == 10 - len(decode['vin']) + 1) # Change address",
"output['satoshis'] == '1000000000msat') # ... and all other output should",
"= node_factory.get_node(1) l1.fundwallet(10**8) for i in range(100): addr = l1.rpc.newaddr()[\"bech32\"]",
"Decimal(0.0002) assert decode['vout'][0]['scriptPubKey']['type'] == 'witness_v0_keyhash' assert decode['vout'][0]['scriptPubKey']['addresses'] == [addr] #",
"are gone, but change output has arrived. wait_for(lambda: len(l1.rpc.listfunds()['outputs']) ==",
"fixtures import * # noqa: F401,F403 from fixtures import TEST_NETWORK",
"restore the same wallet with another password l1.daemon.opts.update({\"encrypted-hsm\": None}) l1.daemon.start(stdin=slave_fd,",
"# And finally test that we can also decrypt if",
"[addr, 'slow']) with pytest.raises(RpcError, match=r'Need set \\'satoshi\\' field.'): l1.rpc.call('txprepare', [addr])",
"== prep3['txid'] # 4 inputs, 1 outputs. assert len(decode['vin']) ==",
"l2, l3 = node_factory.get_nodes(3) l1.fundwallet(10**6) # We should now have",
"without telling it explicitly \"\"\" # Previous runs with same",
"a null column # and crashed the daemon for accessing",
"# Test we can encrypt it offline cmd_line[1] = \"encrypt\"",
"* 6) / 10**8 - Decimal(0.0002) assert decode['vout'][0]['scriptPubKey']['type'] == 'witness_v0_keyhash'",
"'bcrt1qw508d6qejxtdg4y5r3zarvary0c5xw7kygt080' with pytest.raises(RpcError): l1.rpc.withdraw('xx1qw508d6qejxtdg4y5r3zarvary0c5xw7kxpjzsx', 2 * amount) with pytest.raises(RpcError): l1.rpc.withdraw('tb1pw508d6qejxtdg4y5r3zarvary0c5xw7kdl9fad',",
"Millisatoshi(amount * 100), None, 1]) l1.rpc.call('txprepare', [addr, Millisatoshi(amount * 100)])",
"utxos = [utxo[\"txid\"] + \":\" + str(utxo[\"output\"]) for utxo in",
"key derivation.\") def test_hsmtool_secret_decryption(node_factory): l1 = node_factory.get_node() password = \"<PASSWORD>\"",
"nLockTime for withdrawal transactions. Marked flaky \"just in case\" as",
"{minconf} \"\"\" amount = 10**4 l1 = node_factory.get_node(options={'allow-deprecated-apis': True}) addr",
"== 'deposit' and output['satoshis'] == '1000000000msat') # ... and all",
"10**8 - Decimal(0.0002) assert decode['vout'][0]['scriptPubKey']['type'] == 'witness_v0_keyhash' assert decode['vout'][0]['scriptPubKey']['addresses'] ==",
"== 0 def test_withdraw_nlocktime(node_factory): \"\"\" Test that we don't set",
"subprocess import time import unittest @unittest.skipIf(TEST_NETWORK != 'regtest', \"Test relies",
"amount / 10**8) bitcoind.generate_block(1) wait_for(lambda: [o['status'] for o in l1.rpc.listfunds()['outputs']]",
"status=2')[0]['c'] == 6 # Simple test for withdrawal to P2WSH",
"i in range(9): outputs.append({l1.rpc.newaddr()['bech32']: Millisatoshi(amount * 100)}) prep = l1.rpc.txprepare(outputs=outputs)",
"amount / 10**8 + 0.01) bitcoind.generate_block(1) wait_for(lambda: len(l1.rpc.listfunds()['outputs']) == 10)",
"and it should have an annotation on the output reading",
"to be accepted. If the current height is smaller than",
"to. output = only_one(l1.rpc.listfunds()['outputs']) assert output['address'] == addr @unittest.skipIf(not COMPAT,",
"with pytest.raises(RpcError): l1.rpc.withdraw(waddr, 'not an amount') with pytest.raises(RpcError): l1.rpc.withdraw(waddr, -amount)",
"and key derivation.\") def test_hsm_secret_encryption(node_factory): l1 = node_factory.get_node(may_fail=True) # May",
"range(10): l1.bitcoin.rpc.sendtoaddress(addr, amount / 10**8 + 0.01) bitcoind.generate_block(1) wait_for(lambda: len(l1.rpc.listfunds()['outputs'])",
"assert decode['vout'][0]['value'] > Decimal(amount * 6) / 10**8 - Decimal(0.0002)",
"status=2')[0]['c'] == 8 # failure testing for invalid SegWit addresses,",
"changeidx = 0 if types[0] == 'deposit' else 1 fundidx",
"test_minconf_withdraw(node_factory, bitcoind): \"\"\"Issue 2518: ensure that ridiculous confirmation levels don't",
"pytest.raises(RpcError): l1.rpc.withdraw(waddr, 'not an amount') with pytest.raises(RpcError): l1.rpc.withdraw(waddr, -amount) with",
"== addr # Send all our money to a P2WPKH",
"with pytest.raises(RpcError): l1.rpc.withdraw('tb1pw508d6qejxtdg4y5r3zarvary0c5xw7kdl9fad', 2 * amount) with pytest.raises(RpcError): l1.rpc.withdraw('tb1qw508d6qejxtdg4y5r3zarvary0c5xw7kxxxxxx', 2",
"= out['output'] assert(idx in [0, 1] and out['value'] == 10**6)",
"2 * amount) # Invalid program length for witness version",
"6 outputs available. assert l1.db_query('SELECT COUNT(*) as c FROM outputs",
"This should fail, can't even afford fee. with pytest.raises(RpcError, match=r'Cannot",
"in o: types.append(o['type']) else: types.append(None) assert(set([None]) == set(types)) ########################################################################## #",
"Test we cannot start the same wallet without specifying --encrypted-hsm",
"for i, o in enumerate(decode['vout']) if o['value'] == Decimal(amount *",
"amount) # Make sure bitcoind received the withdrawal unspent =",
"* 100), 'slow', 1]) l1.rpc.call('txprepare', [addr, Millisatoshi(amount * 100), 'normal'])",
"be an amount in satoshis or all, not .*'): l1.rpc.call('txprepare',",
"prep['txid'] # All 10 inputs assert len(decode['vin']) == 10 #",
"assert(l1.daemon.is_in_log(\"Wrong password for encrypted hsm_secret.\")) # Test we can restore",
"utxo in vins def test_minconf_withdraw(node_factory, bitcoind): \"\"\"Issue 2518: ensure that",
"== 'witness_v0_keyhash' assert decode['vout'][0]['scriptPubKey']['addresses'] == [addr] l1.rpc.txdiscard(prep4['txid']) # Try passing",
"prep2['txid'] # 6 inputs, 1 outputs. assert len(decode['vin']) == 6",
"for i in range(10): l1.bitcoin.rpc.sendtoaddress(addr, amount / 10**8 + 0.01)",
"len(decode['vin']) + 1) # Change address should appear in listfunds()",
"funds from previous runs. l1 = node_factory.get_node(random_hsm=True) addr = l1.rpc.newaddr()['bech32']",
"[l1]) # Check that there are no unconfirmed outputs (change",
"# This should fail, can't even afford fee. with pytest.raises(RpcError,",
"= l1.rpc.txprepare([{addr: 'all'}]) decode = bitcoind.rpc.decoderawtransaction(prep4['unsigned_tx']) assert decode['txid'] == prep4['txid']",
"assert l1.daemon.is_in_log('wallet: reserved output {}/{} reset to available'.format(i['txid'], i['vout'])) prep",
"* 1000)}]) decode = bitcoind.rpc.decoderawtransaction(prep['unsigned_tx']) assert decode['txid'] == prep['txid'] #",
"test_addfunds_from_block(node_factory, bitcoind): \"\"\"Send funds to the daemon without telling it",
"2 assert decode['vout'][1]['value'] == Decimal(amount * 3.5) / 10**8 assert",
"node_id == l1.rpc.getinfo()[\"id\"] l1.stop() # Test we can encrypt it",
"Previous runs with same bitcoind can leave funds! l1 =",
"== 2 # Now send some money to l2. #",
"= l1.rpc.newaddr()[\"bech32\"] tx = l1.rpc.withdraw(addr, 10**3)[\"tx\"] nlocktime = node_factory.bitcoind.rpc.decoderawtransaction(tx)[\"locktime\"] tip",
"continue if 'type' in o: types.append(o['type']) else: types.append(None) assert(set([None]) ==",
"ordering by blockheight and txindex, so that order should be",
"and key derivation.\") def test_hsmtool_secret_decryption(node_factory): l1 = node_factory.get_node() password =",
"outputs. assert len(decode['vin']) == 6 assert len(decode['vout']) == 1 if",
"\"\"\" Test that we eventually fuzz nLockTime for withdrawal transactions.",
"bitcoind.generate_block(1) wait_for(lambda: len(l1.rpc.listfunds()['outputs']) == 10) # Reach around into the",
"set(types)) ########################################################################## # Let's now open a channel. The opener",
"= l1.rpc.newaddr()['bech32'] # Add some funds to withdraw later for",
"pytest.raises(RpcError): l1.rpc.withdraw('tb1prp33g0q5c5txsp9arysrx4k6zdkfs4nce4xj0gdcccefvpysxf3qsm03tq', 2 * amount) with pytest.raises(RpcError): l1.rpc.withdraw('tb1qrp33g0q5c5txsp9arysrx4k6zdkfs4nce4xj0gdcccefvpysxf3qxxxxxx', 2 *",
"# Change address should appear in listfunds() assert decode['vout'][changenum]['scriptPubKey']['addresses'][0] in",
"Decimal(amount * 10) / 10**8 - Decimal(0.0003) assert decode['vout'][0]['scriptPubKey']['type'] ==",
"l1 = node_factory.get_node(1) l1.fundwallet(10**8) for i in range(100): addr =",
"transaction'): l1.rpc.withdraw(waddr, 'all') # Add some funds to withdraw for",
"chainparams['feeoutput']): if decode['vout'][i - 1]['value'] == Decimal('0.01500100'): outnum1 = i",
"use termios in `lightningd`. master_fd, slave_fd = os.openpty() # Test",
"bitcoind.generate_block(1) l1.daemon.wait_for_log('Owning output .* txid {} CONFIRMED'. format(withdraw[\"txid\"])) decoded =",
"{} CONFIRMED'. format(withdraw[\"txid\"])) decoded = bitcoind.rpc.decoderawtransaction(withdraw[\"tx\"]) tip = node_factory.bitcoind.rpc.getblockcount() assert",
"= l1.rpc.txprepare([{addr: Millisatoshi(amount * 3.5 * 1000)}], utxos=utxos) decode =",
"HRP character out of range with pytest.raises(RpcError): l1.rpc.withdraw(' 1nwldj5', 2",
"withdrawal to self. l1.rpc.withdraw(l1.rpc.newaddr('bech32')['bech32'], 'all', minconf=0) bitcoind.generate_block(1) assert l1.db_query('SELECT COUNT(*)",
"= \"encrypt\" subprocess.check_call(cmd_line) # Now we need to pass the",
"i, o in enumerate(decode['vout']) if o['value'] == Decimal(amount * 3)",
"= i - 1 else: changenum = i - 1",
"was a reorg. Wait. wait_for(lambda: [o['status'] for o in l1.rpc.listfunds()['outputs']]",
"types[fundidx] == 'channel_funding') # And check the channel annotation on",
"* 3 * 500 - 100000)}]) decode = bitcoind.rpc.decoderawtransaction(prep5['unsigned_tx']) assert",
"'all', minconf=0) bitcoind.generate_block(1) assert l1.db_query('SELECT COUNT(*) as c FROM outputs",
"specifying --encrypted-hsm l1.daemon.opts.pop(\"encrypted-hsm\") with pytest.raises(subprocess.CalledProcessError, match=r'returned non-zero exit status 1'):",
"100)]) # Object type with pytest.raises(RpcError, match=r'Need set \\'outputs\\' field.'):",
"... and it should have an annotation on the output",
"< Decimal(amount * 6) / 10**8 assert decode['vout'][0]['value'] > Decimal(amount",
"taken assert decode['vout'][0]['value'] < Decimal(amount * 10) / 10**8 assert",
"public key\") id = l1.rpc.getinfo()[\"id\"] l1.stop() # Test we cannot",
"def test_withdraw_nlocktime_fuzz(node_factory, bitcoind): \"\"\" Test that we eventually fuzz nLockTime",
"decode['vout'][0]['scriptPubKey']['type'] == 'witness_v0_keyhash' assert decode['vout'][0]['scriptPubKey']['addresses'] == [addr] # If I",
"key\") id = l1.rpc.getinfo()[\"id\"] l1.stop() # Test we cannot start",
"assert(len(peers) == 1 and len(peers[0]['channels']) == 1) scid = peers[0]['channels'][0]['short_channel_id']",
"correct utxos are included assert len(decode['vin']) == 4 vins =",
"loop is used to check fuzz.\") def test_withdraw_nlocktime_fuzz(node_factory, bitcoind): \"\"\"",
"discard twice. with pytest.raises(RpcError, match=r'not an unreleased txid'): l1.rpc.txdiscard(prep['txid']) #",
"bitcoind): l1, l2, l3 = node_factory.get_nodes(3) l1.fundwallet(10**6) # We should",
"will also work if we simply kill it. l1.restart(clean=False) #",
"'unconfirmed') # It should also match the funding txid: assert(outputs[0]['txid']",
"100), None, 1]) l1.rpc.call('txprepare', [addr, Millisatoshi(amount * 100)]) # Object",
"amount) bitcoind.generate_block(1) # Make sure l2 received the withdrawal. wait_for(lambda:",
"bitcoind.rpc.decoderawtransaction(prep['unsigned_tx']) assert decode['txid'] == prep['txid'] # 4 inputs, 2 outputs",
"for i, o in enumerate(decode['vout']): if i == outnum: assert",
"Confirm the channel and check that the output changed to",
"prompt and key derivation.\") def test_hsm_secret_encryption(node_factory): l1 = node_factory.get_node(may_fail=True) #",
"if o['value'] == Decimal(amount * 3) / 10**8][0] for i,",
"key derivation.\") def test_hsm_secret_encryption(node_factory): l1 = node_factory.get_node(may_fail=True) # May fail",
"# Now we need to pass the encrypted-hsm startup option",
"decode['vout'][1]['scriptPubKey']['addresses'] == [addr] # Discard prep4 and get all funds",
"2 * amount) # Invalid witness version with pytest.raises(RpcError): l1.rpc.withdraw('BC13W508D6QEJXTDG4Y5R3ZARVARY0C5XW7KN40WF2',",
"Simple test for withdrawal to P2WPKH # Address from: https://bc-2.jp/tools/bech32demo/index.html",
"outputs were added assert l1.db_query('SELECT COUNT(*) as c FROM outputs",
"10**8 assert decode['vout'][0]['value'] > Decimal(amount * 6) / 10**8 -",
"# 6 inputs, 1 outputs. assert len(decode['vin']) == 6 assert",
"c FROM outputs WHERE status=0')[0]['c'] == 0 # This should",
"0 if decoded[\"locktime\"] < tip: return else: raise Exception(\"No transaction",
"It goes backwards in blockchain just in case there was",
"None}) l1.daemon.start(stdin=slave_fd, wait_for_initialized=False) l1.daemon.wait_for_log(r'The hsm_secret is encrypted') os.write(master_fd, password.encode(\"utf-8\")) l1.daemon.wait_for_log(\"Server",
"== 7) # Array type with pytest.raises(RpcError, match=r'.* should be",
"Test that we don't set the nLockTime to 0 for",
"= l1.rpc.txsend(prep['txid']) # Cannot discard after send! with pytest.raises(RpcError, match=r'not",
"idx: continue if 'type' in o: types.append(o['type']) else: types.append(None) assert(set([None])",
"== 1 and len(peers[0]['channels']) == 1) scid = peers[0]['channels'][0]['short_channel_id'] assert(txs[1]['outputs'][fundidx]['channel']",
"withdraw later for i in range(10): l1.bitcoin.rpc.sendtoaddress(addr, amount / 10**8",
"ensure that ridiculous confirmation levels don't overflow The number of",
"bitcoind.rpc.sendtoaddress(addr, 0.1) bitcoind.generate_block(1) wait_for(lambda: len(l1.rpc.listfunds()['outputs']) == 1) outputs = l1.db_query('SELECT",
"* 1000)}]) out = l1.rpc.txsend(prep['txid']) # Cannot discard after send!",
"from decimal import Decimal from fixtures import * # noqa:",
"version with pytest.raises(RpcError): l1.rpc.withdraw('BC13W508D6QEJXTDG4Y5R3ZARVARY0C5XW7KN40WF2', 2 * amount) # Invalid program",
"master_fd, slave_fd = os.openpty() l1.daemon.start(stdin=slave_fd, stderr=subprocess.STDOUT, wait_for_initialized=False) l1.daemon.wait_for_log(r'The hsm_secret is",
"the db to check that outputs were added assert l1.db_query('SELECT",
"assert decode['txid'] == prep4['txid'] # 10 inputs, 1 outputs. assert",
"test for withdrawal to P2WPKH # Address from: https://bc-2.jp/tools/bech32demo/index.html waddr",
"Discard prep4 and get all funds again l1.rpc.txdiscard(prep5['txid']) with pytest.raises(RpcError,",
"to use termios in `lightningd`. master_fd, slave_fd = os.openpty() #",
"will forget all about it. l1.restart() # It goes backwards",
"same wallet with another password l1.daemon.opts.update({\"encrypted-hsm\": None}) l1.daemon.start(stdin=slave_fd, stderr=subprocess.STDOUT, wait_for_initialized=False)",
"tip: return else: raise Exception(\"No transaction with fuzzed nLockTime !\")",
"l1.rpc.listfunds()[\"outputs\"]][:4] withdrawal = l1.rpc.withdraw(waddr, 2 * amount, utxos=utxos) decode =",
"- 1 else: changenum = i - 1 assert decode['vout'][outnum1]['scriptPubKey']['type']",
"= node_factory.get_node(random_hsm=True) addr = l1.rpc.newaddr()['bech32'] # Add some funds to",
"wallet without specifying --encrypted-hsm l1.daemon.opts.pop(\"encrypted-hsm\") with pytest.raises(subprocess.CalledProcessError, match=r'returned non-zero exit",
".* txid {} CONFIRMED'. format(withdraw[\"txid\"])) decoded = bitcoind.rpc.decoderawtransaction(withdraw[\"tx\"]) tip =",
"= l1.rpc.txprepare(outputs=[{addr: Millisatoshi(amount * 3 * 1000)}]) decode = bitcoind.rpc.decoderawtransaction(prep['unsigned_tx'])",
"for withdrawal transactions. Marked flaky \"just in case\" as we",
"the maxheight parameter to a positive small number. \"\"\" amount",
"not parse destination address.*'): l1.rpc.call('txprepare', [Millisatoshi(amount * 100), 'slow', 1])",
"l1.rpc.getinfo()[\"id\"] l1.stop() # Test we cannot start the same wallet",
"'slow', 1]) l1.rpc.call('txprepare', [addr, Millisatoshi(amount * 100), 'slow', 1]) l1.rpc.call('txprepare',",
"startup option l1.stop() with pytest.raises(subprocess.CalledProcessError, match=r'returned non-zero exit status 1'):",
"len(l1.rpc.listfunds()['outputs']) == 1) outputs = [] for i in range(9):",
"= l1.rpc.fundchannel(l2.info['id'], 10**5) # We should have one output available,",
"status 1'): subprocess.check_call(l1.daemon.cmd_line) l1.daemon.opts.update({\"encrypted-hsm\": None}) master_fd, slave_fd = os.openpty() l1.daemon.start(stdin=slave_fd,",
"in `lightningd`. master_fd, slave_fd = os.openpty() # Encrypt the master",
"in l1.rpc.listfunds()['outputs']: assert o['status'] == 'confirmed' # Now make sure",
"Don't get any funds from previous runs. l1 = node_factory.get_node(random_hsm=True)",
"= bitcoind.rpc.decoderawtransaction(prep5['unsigned_tx']) assert decode['txid'] == prep5['txid'] # 4 inputs, 3",
"or all, not .*'): l1.rpc.call('txprepare', [addr, 'slow']) with pytest.raises(RpcError, match=r'Need",
"the same wallet with another password l1.daemon.opts.update({\"encrypted-hsm\": None}) l1.daemon.start(stdin=slave_fd, stderr=subprocess.STDOUT,",
"= l1.rpc.txprepare([{addr: Millisatoshi(amount * 3 * 1000)}, {addr: 'all'}]) prep5",
"positive small number. \"\"\" amount = 1000000 # Don't get",
"'normal']) l1.rpc.call('txprepare', [addr, Millisatoshi(amount * 100), None, 1]) l1.rpc.call('txprepare', [addr,",
"utxo in vins # We should have a change output,",
"Decimal(amount * 6) / 10**8 assert decode['vout'][0]['value'] > Decimal(amount *",
"to a P2WPKH address this time. addr = l1.rpc.newaddr(\"bech32\")['bech32'] l1.rpc.withdraw(addr,",
"unconfirmed channel def test_fundchannel_listtransaction(node_factory, bitcoind): l1, l2 = node_factory.get_nodes(2) l1.fundwallet(10**6)",
"Simple test for withdrawal to P2WSH # Address from: https://bc-2.jp/tools/bech32demo/index.html",
"reading 'deposit' txs = l1.rpc.listtransactions()['transactions'] assert(len(txs) == 1) tx =",
"fundidx = 1 - changeidx assert(types[changeidx] == 'deposit' and types[fundidx]",
"if chainparams['feeoutput'] else 2 assert decode['vout'][1]['value'] == Decimal(amount * 3.5)",
"peers[0]['channels'][0]['short_channel_id'] assert(txs[1]['outputs'][fundidx]['channel'] == scid) @unittest.skipIf(VALGRIND, \"It does not play well",
"# Try passing in a utxo set utxos = [utxo[\"txid\"]",
"c FROM outputs WHERE status=0')[0]['c'] == 1 l1.rpc.withdraw(waddr, 'all', minconf=0)",
"in blockchain just in case there was a reorg. Wait.",
"== 1) outputs = l2.db_query('SELECT value FROM outputs WHERE status=0;')",
"test_deprecated_txprepare(node_factory, bitcoind): \"\"\"Test the deprecated old-style: txprepare {destination} {satoshi} {feerate}",
"10**6) # ... and it should have an annotation on",
"l1.rpc.withdraw('xx1qw508d6qejxtdg4y5r3zarvary0c5xw7kxpjzsx', 2 * amount) with pytest.raises(RpcError): l1.rpc.withdraw('tb1pw508d6qejxtdg4y5r3zarvary0c5xw7kdl9fad', 2 * amount)",
"runs. l1 = node_factory.get_node(random_hsm=True) l2 = node_factory.get_node(random_hsm=True) addr = l1.rpc.newaddr()['bech32']",
"null txs = l1.rpc.listtransactions()['transactions'] tx = [t for t in",
"node_factory.get_node(random_hsm=True) addr = chainparams['example_addr'] # Add some funds to withdraw",
"Let's now open a channel. The opener should get the",
"assert decode['vout'][0]['value'] > Decimal(amount * 4) / 10**8 - Decimal(0.0002)",
"in regtest\") def test_withdraw(node_factory, bitcoind): amount = 1000000 # Don't",
"from pyln.client import RpcError, Millisatoshi from utils import ( only_one,",
"10) prep = l1.rpc.txprepare(outputs=[{addr: Millisatoshi(amount * 3 * 1000)}]) decode",
"set the nLockTime to 0 for withdrawal transactions. \"\"\" l1",
"twice. with pytest.raises(RpcError, match=r'not an unreleased txid'): l1.rpc.txdiscard(prep['txid']) # Discard",
"Millisatoshi(amount * 100), 'normal']) l1.rpc.call('txprepare', [addr, Millisatoshi(amount * 100), None,",
"with another password l1.daemon.opts.update({\"encrypted-hsm\": None}) l1.daemon.start(stdin=slave_fd, stderr=subprocess.STDOUT, wait_for_initialized=False) l1.daemon.wait_for_log(r'The hsm_secret",
"1 l1.rpc.withdraw(waddr, 'all', minconf=0) assert l1.db_query('SELECT COUNT(*) as c FROM",
"1 assert decode['vout'][outnum1]['scriptPubKey']['type'] == 'witness_v0_keyhash' assert decode['vout'][outnum1]['scriptPubKey']['addresses'] == [addr] assert",
"* 100) out = l1.rpc.withdraw(waddr, 2 * amount) # Make",
"amount) # No separator character with pytest.raises(RpcError): l1.rpc.withdraw('pzry9x0s0muk', 2 *",
"All 10 inputs assert len(decode['vin']) == 10 @unittest.skipIf(TEST_NETWORK != 'regtest',",
"some money to l2. # lightningd uses P2SH-P2WPKH waddr =",
"need to simulate a terminal to use termios in `lightningd`.",
"in enumerate(decode['vout']): if i == outnum: assert o['scriptPubKey']['type'] == 'witness_v0_keyhash'",
"nlocktime > 0 and nlocktime <= tip @flaky @unittest.skipIf(VALGRIND, \"A",
"wait_for(lambda: len(l1.rpc.listfunds()['outputs']) == 10) prep = l1.rpc.txprepare(outputs=[{addr: Millisatoshi(amount * 3",
"c FROM outputs WHERE status=2')[0]['c'] == 4 # Simple test",
"as c FROM outputs WHERE status=0')[0]['c'] == 10 waddr =",
"pytest import subprocess import time import unittest @unittest.skipIf(TEST_NETWORK != 'regtest',",
"finally test that we can also decrypt if encrypted with",
"key password = \"<PASSWORD>\" # We need to simulate a",
"time. addr = l1.rpc.newaddr(\"bech32\")['bech32'] l1.rpc.withdraw(addr, \"all\") bitcoind.generate_block(1) time.sleep(1) # The",
"test_withdraw_nlocktime(node_factory): \"\"\" Test that we don't set the nLockTime to",
"waddr = 'bcrt1qw508d6qejxtdg4y5r3zarvary0c5xw7kygt080' with pytest.raises(RpcError): l1.rpc.withdraw('xx1qw508d6qejxtdg4y5r3zarvary0c5xw7kxpjzsx', 2 * amount) with",
"well with prompt and key derivation.\") def test_hsm_secret_encryption(node_factory): l1 =",
"l1.rpc.listfunds()['outputs'] assert(len(outputs) == 1 and outputs[0]['status'] == 'unconfirmed') # It",
"fixtures import TEST_NETWORK from flaky import flaky # noqa: F401",
"pytest.raises(RpcError): l1.rpc.withdraw('1pzry9x0s0muk', 2 * amount) # Invalid witness version with",
"10**8) bitcoind.generate_block(1) wait_for(lambda: [o['status'] for o in l1.rpc.listfunds()['outputs']] == ['confirmed']",
"'channel_funding') # And check the channel annotation on the funding",
"are compiled only with experimental features\") def test_transaction_annotations(node_factory, bitcoind): l1,",
"== l1.rpc.getinfo()[\"id\"] l1.stop() # Test we can encrypt it offline",
"match=r'Need set \\'outputs\\' field.'): l1.rpc.call('txprepare', {'destination': addr, 'feerate': 'slow'}) with",
"['witness_v0_keyhash', 'fee'] # Now prepare one with no change. prep2",
"tx = txs[0] output = tx['outputs'][idx] assert(output['type'] == 'deposit' and",
"number of confirmations we wrap around and just select everything.",
"an unreleased txid'): l1.rpc.txdiscard(prep['txid']) prep = l1.rpc.txprepare([{addr: 'all'}]) decode =",
"same password l1.daemon.start(stdin=slave_fd, wait_for_initialized=False) l1.daemon.wait_for_log(r'The hsm_secret is encrypted') os.write(master_fd, password.encode(\"utf-8\"))",
"character out of range with pytest.raises(RpcError): l1.rpc.withdraw(' 1nwldj5', 2 *",
"will be paid. assert decode['vout'][0]['value'] < Decimal(amount * 6) /",
"assert decode['vout'][0]['value'] < Decimal(amount * 10) / 10**8 assert decode['vout'][0]['value']",
"all satoshi. The count of outputs can\\'t be more than",
"in utxos: assert utxo in vins # We should have",
"assert o['status'] == 'confirmed' # Now make sure two of",
"== 2 * amount # Now make sure an additional",
"if t['hash'] == txid][0] assert tx['blockheight'] == 0 def test_withdraw_nlocktime(node_factory):",
"== 3 if chainparams['feeoutput'] else 2 assert decode['vout'][1]['value'] == Decimal(amount",
"can't use a wrong password ! cmd_line = [\"tools/hsmtool\", \"decrypt\",",
"no change. prep2 = l1.rpc.txprepare([{addr: 'all'}]) decode = bitcoind.rpc.decoderawtransaction(prep2['unsigned_tx']) assert",
"== 10 # This will also work if we simply",
"in range(10): l1.bitcoin.rpc.sendtoaddress(addr, amount / 10**8 + 0.01) bitcoind.generate_block(1) wait_for(lambda:",
"withdrawal = l1.rpc.withdraw(waddr, 2 * amount, utxos=utxos) decode = bitcoind.rpc.decoderawtransaction(withdrawal['tx'])",
"== 4 assert len(decode['vout']) == 4 if chainparams['feeoutput'] else 3",
"with pytest.raises(subprocess.CalledProcessError, match=r'returned non-zero exit status 1'): subprocess.check_call(l1.daemon.cmd_line) l1.daemon.opts.update({\"encrypted-hsm\": None})",
"WHERE status=0;') assert only_one(outputs)['value'] == 2 * amount # Now",
"== 1 and outputs[0]['status'] == 'confirmed') # We should have",
"bitcoind.rpc.decoderawtransaction(withdrawal['tx']) assert decode['txid'] == withdrawal['txid'] # Check that correct utxos",
"l1.db_query('SELECT COUNT(*) as c FROM outputs WHERE status=0')[0]['c'] == 10",
"change. prep2 = l1.rpc.txprepare([{addr: 'all'}]) decode = bitcoind.rpc.decoderawtransaction(prep2['unsigned_tx']) assert decode['txid']",
"else: assert False # Those spent outputs are gone, but",
"Check that there are no unconfirmed outputs (change should be",
"l1.db_query('SELECT COUNT(*) as c FROM outputs WHERE status=0')[0]['c'] == 6",
"import time import unittest @unittest.skipIf(TEST_NETWORK != 'regtest', \"Test relies on",
"a positive small number. \"\"\" amount = 1000000 # Don't",
"node_factory.get_node(may_fail=True) # May fail when started without key password =",
"pytest.raises(RpcError, match=r'Need set \\'outputs\\' field.'): l1.rpc.call('txprepare', {'satoshi': Millisatoshi(amount * 100),",
"l1.rpc.call('txprepare', [addr, 'slow']) with pytest.raises(RpcError, match=r'Need set \\'satoshi\\' field.'): l1.rpc.call('txprepare',",
"1000)}]) out = l1.rpc.txsend(prep['txid']) # Cannot discard after send! with",
"pytest.raises(RpcError, match=r'Cannot afford transaction'): l1.rpc.withdraw(waddr, amount * 100) out =",
"l1.rpc.txdiscard(prep['txid']) wait_for(lambda: prep['txid'] in bitcoind.rpc.getrawmempool()) # Signed tx should have",
"listfunds() assert decode['vout'][changenum]['scriptPubKey']['addresses'][0] in [f['address'] for f in l1.rpc.listfunds()['outputs']] def",
"len(decode['vin']) == 10 @unittest.skipIf(TEST_NETWORK != 'regtest', \"Fee outputs throw off",
"0 (per BIP141) with pytest.raises(RpcError): l1.rpc.withdraw('BC1QR508D6QEJXTDG4Y5R3ZARVARYV98GJ9P', 2 * amount) #",
"len(decode['vout']) == 2 if not chainparams['feeoutput'] else 3 # One",
"amount) with pytest.raises(RpcError): l1.rpc.withdraw('tb1qw508d6qejxtdg4y5r3zarvary0c5xw7kxxxxxx', 2 * amount) l1.rpc.withdraw(waddr, 2 *",
"the nLockTime to 0 for withdrawal transactions. \"\"\" l1 =",
"We need to simulate a terminal to use termios in",
"l1.rpc.getinfo()[\"id\"] l1.stop() # We can't use a wrong password !",
"as c FROM outputs WHERE status=2')[0]['c'] == 2 # Now",
"output. for i in decode['vin']: assert l1.daemon.is_in_log('wallet: reserved output {}/{}",
"should also match the funding txid: assert(outputs[0]['txid'] == fundingtx['txid']) #",
"outnum2 = i - 1 else: changenum = i -",
"2 * amount) with pytest.raises(RpcError): l1.rpc.withdraw('tb1qw508d6qejxtdg4y5r3zarvary0c5xw7kxxxxxx', 2 * amount) l1.rpc.withdraw(waddr,",
"FROM outputs WHERE status=0;') assert only_one(outputs)['value'] == 10000000 # The",
"Test we cannot restore the same wallet with another password",
"assert decode['txid'] == prep['txid'] # 4 inputs, 2 outputs (3",
"= [i for i, o in enumerate(decode['vout']) if o['value'] ==",
"it. l1.restart(clean=False) # It goes backwards in blockchain just in",
"outputs WHERE status=2')[0]['c'] == 8 # failure testing for invalid",
"available. assert l1.db_query('SELECT COUNT(*) as c FROM outputs WHERE status=0')[0]['c']",
"txindex, so that order should be ok) txs = l1.rpc.listtransactions()['transactions']",
"l1.fundwallet(10**6) l1.connect(l2) txid = l1.rpc.fundchannel(l2.info['id'], 10**5)['txid'] # next call warned",
"all about it. l1.restart() # It goes backwards in blockchain",
"COUNT(*) as c FROM outputs WHERE status=0')[0]['c'] == 10 waddr",
"confirmed) for o in l1.rpc.listfunds()['outputs']: assert o['status'] == 'confirmed' #",
"outputs WHERE status=0')[0]['c'] == 6 # Test withdrawal to self.",
"confirmations is used to compute a maximum height that is",
"Send all our money to a P2WPKH address this time.",
"# noqa: F401,F403 from fixtures import TEST_NETWORK from flaky import",
"0.1) bitcoind.generate_block(1) wait_for(lambda: len(l1.rpc.listfunds()['outputs']) == 1) outputs = l1.db_query('SELECT value",
"l1.daemon.opts.pop(\"encrypted-hsm\") l1.daemon.start(stdin=slave_fd, wait_for_initialized=True) assert node_id == l1.rpc.getinfo()[\"id\"] l1.stop() # Test",
"have an annotation on the output reading 'deposit' txs =",
"subprocess.check_call(l1.daemon.cmd_line) l1.daemon.opts.update({\"encrypted-hsm\": None}) master_fd, slave_fd = os.openpty() l1.daemon.start(stdin=slave_fd, stderr=subprocess.STDOUT, wait_for_initialized=False)",
"Address from: https://bc-2.jp/tools/bech32demo/index.html waddr = 'bcrt1qw508d6qejxtdg4y5r3zarvary0c5xw7kygt080' with pytest.raises(RpcError): l1.rpc.withdraw('xx1qw508d6qejxtdg4y5r3zarvary0c5xw7kxpjzsx', 2",
"[i for i, o in enumerate(decode['vout']) if o['value'] == Decimal(amount",
"tx['outputs'][idx] assert(output['type'] == 'deposit' and output['satoshis'] == '1000000000msat') # ...",
"unspent if u['txid'] == out['txid']] assert(withdrawal[0]['amount'] == Decimal('0.02')) l1.bitcoin.generate_block(1) sync_blockheight(l1.bitcoin,",
"with hsmtool cmd_line[3] = password[:-1] subprocess.check_call(cmd_line) # Then test we",
"channel annotation on the funding output peers = l1.rpc.listpeers()['peers'] assert(len(peers)",
"== 'confirmed') out = outputs[0] idx = out['output'] assert(idx in",
"as c FROM outputs WHERE status=0')[0]['c'] == 0 # This",
"bitcoind.generate_block(1) assert l1.db_query('SELECT COUNT(*) as c FROM outputs WHERE status=0')[0]['c']",
"the deprecated old-style: txprepare {destination} {satoshi} {feerate} {minconf} \"\"\" amount",
"l1.rpc.withdraw(' 1nwldj5', 2 * amount) # overall max length exceeded",
"case\" as we fuzz from 0 to 100 with a",
"TEST_NETWORK, \"hsm_secret\") # We need to simulate a terminal to",
"with a 10% probability. \"\"\" l1 = node_factory.get_node(1) l1.fundwallet(10**8) for",
"to withdraw some (making sure we collect multiple inputs) with",
"< Decimal(amount * 10) / 10**8 assert decode['vout'][0]['value'] > Decimal(amount",
"TEST_NETWORK from flaky import flaky # noqa: F401 from pyln.client",
"u in unspent if u['txid'] == out['txid']] assert(withdrawal[0]['amount'] == Decimal('0.02'))",
"db to check that outputs were added assert l1.db_query('SELECT COUNT(*)",
"= only_one(l1.rpc.listfunds()['outputs']) assert output['address'] == addr # Send all our",
"l1.stop() # We can't use a wrong password ! cmd_line",
"assert(withdrawal[0]['amount'] == Decimal('0.02')) l1.bitcoin.generate_block(1) sync_blockheight(l1.bitcoin, [l1]) # Check that there",
"import os import pytest import subprocess import time import unittest",
"with pytest.raises(RpcError, match=r'Cannot afford transaction'): l1.rpc.withdraw(waddr, amount * 100) out",
"* amount) l1.rpc.withdraw(waddr, 2 * amount) bitcoind.generate_block(1) # Now make",
"= [u for u in unspent if u['txid'] == out['txid']]",
"l1.bitcoin.generate_block(1) sync_blockheight(l1.bitcoin, [l1]) # Check that there are no unconfirmed",
"None}) master_fd, slave_fd = os.openpty() l1.daemon.start(stdin=slave_fd, stderr=subprocess.STDOUT, wait_for_initialized=False) l1.daemon.wait_for_log(r'The hsm_secret",
"FROM outputs WHERE status=2')[0]['c'] == 2 # Now send some",
"# Mixed case with pytest.raises(RpcError): l1.rpc.withdraw('tb1qrp33g0q5c5txsp9arysrx4k6zdkfs4nce4xj0gdcccefvpysxf3q0sL5k7', 2 * amount) #",
"fundingtx = l1.rpc.fundchannel(l2.info['id'], 10**5) # We should have one output",
"CONFIRMED'. format(withdraw[\"txid\"])) decoded = bitcoind.rpc.decoderawtransaction(withdraw[\"tx\"]) tip = node_factory.bitcoind.rpc.getblockcount() assert decoded[\"locktime\"]",
"wait_for(lambda: len(l1.rpc.listfunds()['outputs']) == 1) outputs = l1.db_query('SELECT value FROM outputs",
"output available, and it should be unconfirmed outputs = l1.rpc.listfunds()['outputs']",
"wrong pass\"] with pytest.raises(subprocess.CalledProcessError): subprocess.check_call(cmd_line) # Decrypt it with hsmtool",
"500 - 100000)}]) decode = bitcoind.rpc.decoderawtransaction(prep5['unsigned_tx']) assert decode['txid'] == prep5['txid']",
"o in l1.rpc.listfunds()['outputs']] == ['confirmed'] * 10) prep = l1.rpc.txprepare([{addr:",
"type with pytest.raises(RpcError, match=r'.* should be an amount in satoshis",
"= 1000000 l1 = node_factory.get_node(may_fail=True) addr = chainparams['example_addr'] # Add",
"i - 1 else: changenum = i - 1 assert",
"i in range(5): bitcoind.rpc.sendtoaddress(l1.rpc.newaddr()['bech32'], amount / 10**8) bitcoind.rpc.sendtoaddress(l1.rpc.newaddr('p2sh-segwit')['p2sh-segwit'], amount /",
"/ 10**8 - Decimal(0.0002) assert decode['vout'][0]['scriptPubKey']['type'] == 'witness_v0_keyhash' assert decode['vout'][0]['scriptPubKey']['addresses']",
"have same txid decode = bitcoind.rpc.decoderawtransaction(out['tx']) assert decode['txid'] == prep['txid']",
"* amount) bitcoind.generate_block(1) # Now make sure additional two of",
"outputs WHERE status=0;') assert only_one(outputs)['value'] == 10000000 # The address",
"outputs WHERE status=0')[0]['c'] == 1 l1.rpc.withdraw(waddr, 'all', minconf=0) assert l1.db_query('SELECT",
"and p2sh for i in range(5): bitcoind.rpc.sendtoaddress(l1.rpc.newaddr()['bech32'], amount / 10**8)",
"be paid. assert decode['vout'][0]['value'] < Decimal(amount * 6) / 10**8",
"'all'}]) decode = bitcoind.rpc.decoderawtransaction(prep['unsigned_tx']) assert decode['txid'] == prep['txid'] # All",
"changed to confirmed bitcoind.generate_block(3) sync_blockheight(bitcoind, [l1, l2]) outputs = l1.rpc.listfunds()['outputs']",
"{}/{} reset to available'.format(i['txid'], i['vout'])) prep = l1.rpc.txprepare([{addr: 'all'}]) decode",
"key\") node_id = l1.rpc.getinfo()[\"id\"] l1.stop() # We can't use a",
"utxo set utxos = [utxo[\"txid\"] + \":\" + str(utxo[\"output\"]) for",
"spent outputs are gone, but change output has arrived. wait_for(lambda:",
"scid) @unittest.skipIf(VALGRIND, \"It does not play well with prompt and",
"= l1.rpc.txprepare([{addr: 'all'}]) decode = bitcoind.rpc.decoderawtransaction(prep3['unsigned_tx']) assert decode['txid'] == prep3['txid']",
"just select everything. The fix is to clamp the maxheight",
"Test withdrawal to self. l1.rpc.withdraw(l1.rpc.newaddr('bech32')['bech32'], 'all', minconf=0) bitcoind.generate_block(1) assert l1.db_query('SELECT",
"* 100)}) prep = l1.rpc.txprepare(outputs=outputs) l1.rpc.txdiscard(prep['txid']) def test_txprepare(node_factory, bitcoind, chainparams):",
"password l1.daemon.start(stdin=slave_fd, wait_for_initialized=False) l1.daemon.wait_for_log(r'The hsm_secret is encrypted') os.write(master_fd, password.encode(\"utf-8\")) l1.daemon.wait_for_log(\"Server",
"One output will be correct. outnum = [i for i,",
"utxo in utxos: assert utxo in vins # We should",
"len(decode['vin']) == 4 assert len(decode['vout']) == 2 if not chainparams['feeoutput']",
"'witness_v0_keyhash' assert o['scriptPubKey']['addresses'] == [addr] else: assert o['scriptPubKey']['type'] in ['witness_v0_keyhash',",
"'all'}]) prep5 = l1.rpc.txprepare([{addr: Millisatoshi(amount * 3 * 500 +",
"prep5['txid'] # Check that correct utxos are included assert len(decode['vin'])",
"l2.rpc.newaddr('bech32')['bech32'] l1.rpc.withdraw(waddr, 2 * amount) bitcoind.generate_block(1) # Make sure l2",
"= l1.rpc.getinfo()[\"id\"] l1.stop() # We can't use a wrong password",
"be unconfirmed outputs = l1.rpc.listfunds()['outputs'] assert(len(outputs) == 1 and outputs[0]['status']",
"== 6 # Test withdrawal to self. l1.rpc.withdraw(l1.rpc.newaddr('bech32')['bech32'], 'all', minconf=0)",
"If I cancel the first one, I can get those",
"\"all\") bitcoind.generate_block(1) time.sleep(1) # The address we detect must match",
"correct. for i in range(3 + chainparams['feeoutput']): if decode['vout'][i -",
"is encrypted') os.write(master_fd, password.encode(\"utf-8\")) l1.daemon.wait_for_log(\"Server started with public key\") assert",
"status=0')[0]['c'] == 1 l1.rpc.withdraw(waddr, 'all', minconf=0) assert l1.db_query('SELECT COUNT(*) as",
"play well with prompt and key derivation.\") def test_hsmtool_secret_decryption(node_factory): l1",
"1}) l1.rpc.call('txprepare', {'destination': addr, 'satoshi': Millisatoshi(amount * 100), 'feerate': '2000perkw'})",
"assert discard['txid'] == prep['txid'] assert discard['unsigned_tx'] == prep['unsigned_tx'] prep3 =",
"range(7): l1.fundwallet(10**8) bitcoind.generate_block(1) sync_blockheight(bitcoind, [l1]) wait_for(lambda: len(l1.rpc.listfunds()['outputs']) == 7) #",
"1000)}, {addr: 'all'}]) prep5 = l1.rpc.txprepare([{addr: Millisatoshi(amount * 3 *",
"= l1.rpc.listfunds()['outputs'] assert(len(outputs) == 1 and outputs[0]['status'] == 'confirmed') #",
"outputs = [] for i in range(9): outputs.append({l1.rpc.newaddr()['bech32']: Millisatoshi(amount *",
"\"decrypt\", hsm_path, \"A wrong pass\"] with pytest.raises(subprocess.CalledProcessError): subprocess.check_call(cmd_line) # Decrypt",
"10 assert len(decode['vout']) == 1 if not chainparams['feeoutput'] else 2",
"== 10) # Reach around into the db to check",
"bitcoind.rpc.decoderawtransaction(prep4['unsigned_tx']) assert decode['txid'] == prep4['txid'] # 10 inputs, 1 outputs.",
"bitcoind.generate_block(1) wait_for(lambda: len(l1.rpc.listfunds()['outputs']) == 10) # Try passing in a",
"decoded = bitcoind.rpc.decoderawtransaction(withdraw[\"tx\"]) tip = node_factory.bitcoind.rpc.getblockcount() assert decoded[\"locktime\"] > 0",
"without specifying --encrypted-hsm l1.daemon.opts.pop(\"encrypted-hsm\") with pytest.raises(subprocess.CalledProcessError, match=r'returned non-zero exit status",
"decode = bitcoind.rpc.decoderawtransaction(prep5['unsigned_tx']) assert decode['txid'] == prep5['txid'] # Check that",
"for i in range(3 + chainparams['feeoutput']): if decode['vout'][i - 1]['value']",
"match=r'this destination wants all satoshi. The count of outputs can\\'t",
"feerate='normal', minconf=9999999) def test_addfunds_from_block(node_factory, bitcoind): \"\"\"Send funds to the daemon",
"= l1.rpc.txprepare(outputs=outputs) l1.rpc.txdiscard(prep['txid']) def test_txprepare(node_factory, bitcoind, chainparams): amount = 1000000",
"addr, 'satoshi': Millisatoshi(amount * 100)}) def test_txprepare_multi(node_factory, bitcoind): amount =",
"amount / 10**8) bitcoind.rpc.sendtoaddress(l1.rpc.newaddr('p2sh-segwit')['p2sh-segwit'], amount / 10**8) bitcoind.generate_block(1) wait_for(lambda: [o['status']",
"assert decode['txid'] == prep5['txid'] # 4 inputs, 3 outputs(include change).",
"l1.fundwallet(10**8) for i in range(100): addr = l1.rpc.newaddr()[\"bech32\"] withdraw =",
"== out['txid']] assert(withdrawal[0]['amount'] == Decimal('0.02')) l1.bitcoin.generate_block(1) sync_blockheight(l1.bitcoin, [l1]) # Check",
"# Discard prep4 and get all funds again l1.rpc.txdiscard(prep5['txid']) with",
"started with public key\") assert id == l1.rpc.getinfo()[\"id\"] @unittest.skipIf(VALGRIND, \"It",
"All 10 inputs assert len(decode['vin']) == 10 # L1 will",
"May fail when started without key password = \"<PASSWORD>\" #",
"= l1.rpc.newaddr()['bech32'] bitcoind.rpc.sendtoaddress(addr, 0.1) bitcoind.generate_block(1) wait_for(lambda: len(l1.rpc.listfunds()['outputs']) == 1) outputs",
"withdraw for i in range(10): l1.bitcoin.rpc.sendtoaddress(addr, amount / 10**8 +",
"with pytest.raises(RpcError): l1.rpc.withdraw(' 1nwldj5', 2 * amount) # overall max",
"100), 'normal']) l1.rpc.call('txprepare', [addr, Millisatoshi(amount * 100), None, 1]) l1.rpc.call('txprepare',",
"os.write(master_fd, password[2:].encode(\"utf-8\")) assert(l1.daemon.proc.wait() == 1) assert(l1.daemon.is_in_log(\"Wrong password for encrypted hsm_secret.\"))",
"* amount) with pytest.raises(RpcError): l1.rpc.withdraw('tb1pw508d6qejxtdg4y5r3zarvary0c5xw7kdl9fad', 2 * amount) with pytest.raises(RpcError):",
"compute a maximum height that is to be accepted. If",
"Now prepare one with no change. prep2 = l1.rpc.txprepare([{addr: 'all'}])",
"== [addr] # Cannot discard twice. with pytest.raises(RpcError, match=r'not an",
"# We should have one output available, and it should",
"wrong password ! cmd_line = [\"tools/hsmtool\", \"decrypt\", hsm_path, \"A wrong",
"test_transaction_annotations(node_factory, bitcoind): l1, l2, l3 = node_factory.get_nodes(3) l1.fundwallet(10**6) # We",
"decode['vout'][1]['value'] == Decimal(amount * 3) / 10**8: changenum = 0",
"the same password l1.daemon.start(stdin=slave_fd, wait_for_initialized=False) l1.daemon.wait_for_log(r'The hsm_secret is encrypted') os.write(master_fd,",
"in range(100): addr = l1.rpc.newaddr()[\"bech32\"] withdraw = l1.rpc.withdraw(addr, 10**3) bitcoind.generate_block(1)",
"l1.rpc.withdraw('pzry9x0s0muk', 2 * amount) # Empty HRP with pytest.raises(RpcError): l1.rpc.withdraw('1pzry9x0s0muk',",
"no unconfirmed outputs (change should be confirmed) for o in",
"unittest @unittest.skipIf(TEST_NETWORK != 'regtest', \"Test relies on a number of",
"outputs. discard = l1.rpc.txdiscard(prep['txid']) assert discard['txid'] == prep['txid'] assert discard['unsigned_tx']",
"COMPAT=1\") def test_deprecated_txprepare(node_factory, bitcoind): \"\"\"Test the deprecated old-style: txprepare {destination}",
"opener should get the funding transaction # annotated as channel",
"available, and it should be unconfirmed outputs = l1.rpc.listfunds()['outputs'] assert(len(outputs)",
"that ridiculous confirmation levels don't overflow The number of confirmations",
"Millisatoshi(amount * 100), 'feerate': '2000perkw'}) l1.rpc.call('txprepare', {'destination': addr, 'satoshi': Millisatoshi(amount",
"annotations types = [] for i, o in enumerate(tx['outputs']): if",
"now have a transaction that gave us the funds in",
"'all') # Add some funds to withdraw for i in",
"def test_transaction_annotations(node_factory, bitcoind): l1, l2, l3 = node_factory.get_nodes(3) l1.fundwallet(10**6) #",
"prep = l1.rpc.txprepare(outputs=outputs) l1.rpc.txdiscard(prep['txid']) def test_txprepare(node_factory, bitcoind, chainparams): amount =",
"Address from: https://bc-2.jp/tools/bech32demo/index.html waddr = 'bcrt1qrp33g0q5c5txsp9arysrx4k6zdkfs4nce4xj0gdcccefvpysxf3qzf4jry' with pytest.raises(RpcError): l1.rpc.withdraw('xx1qrp33g0q5c5txsp9arysrx4k6zdkfs4nce4xj0gdcccefvpysxf3q0sl5k7', 2",
"= bitcoind.rpc.decoderawtransaction(prep2['unsigned_tx']) assert decode['txid'] == prep2['txid'] # 6 inputs, 1",
"sure two of them were marked as spent assert l1.db_query('SELECT",
"are included assert len(decode['vin']) == 4 vins = [\"{}:{}\".format(v['txid'], v['vout'])",
"[addr] l1.rpc.txdiscard(prep4['txid']) # Try passing in a utxo set utxos",
"txs = l1.rpc.listtransactions()['transactions'] tx = [t for t in txs",
"l1.rpc.withdraw('tb1qw508d6qejxtdg4y5r3zarvary0c5xw7kxxxxxx', 2 * amount) l1.rpc.withdraw(waddr, 2 * amount) bitcoind.generate_block(1) #",
"assert decode['vout'][0]['scriptPubKey']['addresses'] == [addr] # If I cancel the first",
"i - 1 elif decode['vout'][i - 1]['value'] == Decimal('0.01499900'): outnum2",
"decode['vout'][0]['scriptPubKey']['addresses'] == [addr] l1.rpc.txdiscard(prep4['txid']) # Try passing in a utxo",
"\"\"\" amount = 10**4 l1 = node_factory.get_node(options={'allow-deprecated-apis': True}) addr =",
"outputs WHERE status=2')[0]['c'] == 6 # Simple test for withdrawal",
"l2.db_query('SELECT value FROM outputs WHERE status=0;') assert only_one(outputs)['value'] == 2",
"if decode['vout'][i - 1]['value'] == Decimal('0.01500100'): outnum1 = i -",
"- 100000)}]) decode = bitcoind.rpc.decoderawtransaction(prep5['unsigned_tx']) assert decode['txid'] == prep5['txid'] #",
"txprepare {destination} {satoshi} {feerate} {minconf} \"\"\" amount = 10**4 l1",
"in enumerate(decode['vout']) if o['value'] == Decimal(amount * 3) / 10**8][0]",
"= [] for i in range(9): outputs.append({l1.rpc.newaddr()['bech32']: Millisatoshi(amount * 100)})",
"'1000000000msat') # ... and all other output should be change,",
"to available'.format(i['txid'], i['vout'])) prep = l1.rpc.txprepare([{addr: 'all'}]) decode = bitcoind.rpc.decoderawtransaction(prep['unsigned_tx'])",
"l1 = node_factory.get_node(random_hsm=True) addr = chainparams['example_addr'] # Add some funds",
"len(l1.rpc.listfunds()['outputs']) == 10) # Reach around into the db to",
"wait_for_initialized=False) l1.daemon.wait_for_log(r'The hsm_secret is encrypted') os.write(master_fd, password[2:].encode(\"utf-8\")) assert(l1.daemon.proc.wait() == 1)",
"time.sleep(1) # The address we detect must match what was",
"l1.rpc.newaddr(\"bech32\")['bech32'] l1.rpc.withdraw(addr, \"all\") bitcoind.generate_block(1) time.sleep(1) # The address we detect",
"== 6 assert len(decode['vout']) == 1 if not chainparams['feeoutput'] else",
"withdrawal transactions. \"\"\" l1 = node_factory.get_node(1) l1.fundwallet(10**4) addr = l1.rpc.newaddr()[\"bech32\"]",
"hsm_secret is encrypted') os.write(master_fd, password.encode(\"utf-8\")) l1.daemon.wait_for_log(\"Server started with public key\")",
"= bitcoind.rpc.decoderawtransaction(withdrawal['tx']) assert decode['txid'] == withdrawal['txid'] # Check that correct",
"tx = l1.rpc.withdraw(addr, 10**3)[\"tx\"] nlocktime = node_factory.bitcoind.rpc.decoderawtransaction(tx)[\"locktime\"] tip = node_factory.bitcoind.rpc.getblockcount()",
"from utils import ( only_one, wait_for, sync_blockheight, EXPERIMENTAL_FEATURES, COMPAT, VALGRIND",
"node_factory.get_node(options={'allow-deprecated-apis': True}) addr = l1.rpc.newaddr()['bech32'] for i in range(7): l1.fundwallet(10**8)",
"len(decode['vin']) == 6 assert len(decode['vout']) == 1 if not chainparams['feeoutput']",
"wait_for_initialized=True) assert node_id == l1.rpc.getinfo()[\"id\"] # this test does a",
"without key password = \"<PASSWORD>\" # We need to simulate",
"assert len(decode['vin']) == 6 assert len(decode['vout']) == 1 if not",
"(change should be confirmed) for o in l1.rpc.listfunds()['outputs']: assert o['status']",
"# Non-zero padding in 8-to-5 conversion with pytest.raises(RpcError): l1.rpc.withdraw('tb1qrp33g0q5c5txsp9arysrx4k6zdkfs4nce4xj0gdcccefvpysxf3pjxtptv', 2",
"testing for invalid SegWit addresses, from BIP173 # HRP character",
"= only_one(l1.rpc.listfunds()['outputs']) assert output['address'] == addr @unittest.skipIf(not COMPAT, \"needs COMPAT=1\")",
"the funds in the # transactions table... outputs = l1.rpc.listfunds()['outputs']",
"'witness_v0_keyhash' def test_txsend(node_factory, bitcoind, chainparams): amount = 1000000 l1 =",
"/ 10**8) bitcoind.generate_block(1) wait_for(lambda: len(l1.rpc.listfunds()['outputs']) == 10) prep = l1.rpc.txprepare([{addr:",
"# Decrypt it with hsmtool cmd_line[3] = password[:-1] subprocess.check_call(cmd_line) #",
"l1.db_query('SELECT COUNT(*) as c FROM outputs WHERE status=2')[0]['c'] == 8",
"status=0;') assert only_one(outputs)['value'] == 10000000 # The address we detect",
"import RpcError, Millisatoshi from utils import ( only_one, wait_for, sync_blockheight,",
"# ... and all other output should be change, and",
"prep['txid'] assert discard['unsigned_tx'] == prep['unsigned_tx'] prep3 = l1.rpc.txprepare([{addr: 'all'}]) decode",
"['confirmed'] * 10) prep = l1.rpc.txprepare([{addr: 'all'}]) decode = bitcoind.rpc.decoderawtransaction(prep['unsigned_tx'])",
"that outputs were added assert l1.db_query('SELECT COUNT(*) as c FROM",
"\"encrypt\" subprocess.check_call(cmd_line) # Now we need to pass the encrypted-hsm",
"l1.rpc.withdraw('tb1qrp33g0q5c5txsp9arysrx4k6zdkfs4nce4xj0gdcccefvpysxf3qxxxxxx', 2 * amount) l1.rpc.withdraw(waddr, 2 * amount) bitcoind.generate_block(1) #",
"= l1.rpc.listtransactions()['transactions'] assert(len(txs) == 1) tx = txs[0] output =",
"we detect must match what was paid to. output =",
"as spent assert l1.db_query('SELECT COUNT(*) as c FROM outputs WHERE",
"with pytest.raises(RpcError, match=r'.* should be an amount in satoshis or",
"* 3.5 * 1000)}], utxos=utxos) decode = bitcoind.rpc.decoderawtransaction(prep5['unsigned_tx']) assert decode['txid']",
"in decode['vin']: assert l1.daemon.is_in_log('wallet: reserved output {}/{} reset to available'.format(i['txid'],",
"l1 = node_factory.get_node(random_hsm=True) addr = l1.rpc.newaddr()['bech32'] # Add some funds",
"1) scid = peers[0]['channels'][0]['short_channel_id'] assert(txs[1]['outputs'][fundidx]['channel'] == scid) @unittest.skipIf(VALGRIND, \"It does",
"l1.rpc.withdraw(waddr, 2 * amount) # Make sure bitcoind received the",
"\"\"\"Send funds to the daemon without telling it explicitly \"\"\"",
"{addr: Millisatoshi(amount * 3 * 500 - 100000)}]) decode =",
"not chainparams['feeoutput'] else 2 # Some fees will be paid.",
"bitcoind.rpc.decoderawtransaction(withdraw[\"tx\"]) tip = node_factory.bitcoind.rpc.getblockcount() assert decoded[\"locktime\"] > 0 if decoded[\"locktime\"]",
"subprocess.check_call(cmd_line) # Decrypt it with hsmtool cmd_line[3] = password[:-1] subprocess.check_call(cmd_line)",
"= l1.rpc.listfunds()['outputs'] assert(len(outputs) == 1 and outputs[0]['status'] == 'confirmed') out",
"match=r'returned non-zero exit status 1'): subprocess.check_call(l1.daemon.cmd_line) # Test we cannot",
"[] for i, o in enumerate(tx['outputs']): if i == idx:",
"set utxos = [utxo[\"txid\"] + \":\" + str(utxo[\"output\"]) for utxo",
"if decode['vout'][0]['value'] == Decimal(amount * 3) / 10**8: changenum =",
"cannot restore the same wallet with another password l1.daemon.opts.update({\"encrypted-hsm\": None})",
"blockchain just in case there was a reorg. Wait. wait_for(lambda:",
"valid only in regtest\") def test_withdraw(node_factory, bitcoind): amount = 1000000",
"cannot start the same wallet without specifying --encrypted-hsm l1.daemon.opts.pop(\"encrypted-hsm\") with",
"[addr, Millisatoshi(amount * 100), 'normal']) l1.rpc.call('txprepare', [addr, Millisatoshi(amount * 100),",
"Decimal('0.01500100'): outnum1 = i - 1 elif decode['vout'][i - 1]['value']",
"l1.rpc.newaddr()['bech32'] # Add some funds to withdraw later for i",
"height that is to be accepted. If the current height",
"changeidx assert(types[changeidx] == 'deposit' and types[fundidx] == 'channel_funding') # And",
"bitcoind.rpc.sendtoaddress(l1.rpc.newaddr()['bech32'], amount / 10**8) bitcoind.rpc.sendtoaddress(l1.rpc.newaddr('p2sh-segwit')['p2sh-segwit'], amount / 10**8) bitcoind.generate_block(1) wait_for(lambda:",
"order should be ok) txs = l1.rpc.listtransactions()['transactions'] assert(len(txs) == 2",
"2 * amount) # No separator character with pytest.raises(RpcError): l1.rpc.withdraw('pzry9x0s0muk',",
"100), 'slow', 1]) l1.rpc.call('txprepare', [addr, Millisatoshi(amount * 100), 'slow', 1])",
"output will be correct. for i in range(3 + chainparams['feeoutput']):",
"addr, 'satoshi': Millisatoshi(amount * 100), 'feerate': '2000perkw', 'minconf': 1}) l1.rpc.call('txprepare',",
"\"It does not play well with prompt and key derivation.\")",
"[0, 1] and out['value'] == 10**6) # ... and it",
"[addr] assert decode['vout'][changenum]['scriptPubKey']['type'] == 'witness_v0_keyhash' def test_txsend(node_factory, bitcoind, chainparams): amount",
"more than 1'): prep5 = l1.rpc.txprepare([{addr: Millisatoshi(amount * 3 *",
"We should have a change output, so this is exact",
"# Make sure l2 received the withdrawal. wait_for(lambda: len(l2.rpc.listfunds()['outputs']) ==",
"outputs (change should be confirmed) for o in l1.rpc.listfunds()['outputs']: assert",
"l1.rpc.withdraw(l1.rpc.newaddr('bech32')['bech32'], 'all', minconf=0) bitcoind.generate_block(1) assert l1.db_query('SELECT COUNT(*) as c FROM",
"outputs WHERE status=2')[0]['c'] == 2 # Now send some money",
"if 'type' in o: types.append(o['type']) else: types.append(None) assert(set([None]) == set(types))",
"transactions table... outputs = l1.rpc.listfunds()['outputs'] assert(len(outputs) == 1 and outputs[0]['status']",
"tx # (we are ordering by blockheight and txindex, so",
"count of outputs can\\'t be more than 1'): prep5 =",
"reorg. Wait. wait_for(lambda: [o['status'] for o in l1.rpc.listfunds()['outputs']] == ['confirmed']",
"== 'witness_v0_keyhash' assert decode['vout'][outnum2]['scriptPubKey']['addresses'] == [addr] assert decode['vout'][changenum]['scriptPubKey']['type'] == 'witness_v0_keyhash'",
"without password l1.daemon.opts.pop(\"encrypted-hsm\") l1.daemon.start(stdin=slave_fd, wait_for_initialized=True) assert node_id == l1.rpc.getinfo()[\"id\"] l1.stop()",
"output = only_one(l1.rpc.listfunds()['outputs']) assert output['address'] == addr @unittest.skipIf(not COMPAT, \"needs",
"* amount) # Should have 6 outputs available. assert l1.db_query('SELECT",
"* amount # Now make sure an additional two of",
"l1 = node_factory.get_node(random_hsm=True) l2 = node_factory.get_node(random_hsm=True) addr = l1.rpc.newaddr()['bech32'] #",
"l1.rpc.listfunds()['outputs'] assert(len(outputs) == 1 and outputs[0]['status'] == 'confirmed') out =",
"c FROM outputs WHERE status=0')[0]['c'] == 10 waddr = l1.bitcoin.rpc.getnewaddress()",
"assert decode['txid'] == prep['txid'] # All 10 inputs assert len(decode['vin'])",
"bitcoind.generate_block(1) # Change output should appear. if decode['vout'][0]['value'] == Decimal(amount",
"assert decode['vout'][outnum2]['scriptPubKey']['type'] == 'witness_v0_keyhash' assert decode['vout'][outnum2]['scriptPubKey']['addresses'] == [addr] assert decode['vout'][changenum]['scriptPubKey']['type']",
"== 6 # Simple test for withdrawal to P2WSH #",
"of example addresses valid only in regtest\") def test_withdraw(node_factory, bitcoind):",
"annotated as channel open and deposit. l1.connect(l2) fundingtx = l1.rpc.fundchannel(l2.info['id'],",
"l1.stop() with pytest.raises(subprocess.CalledProcessError, match=r'returned non-zero exit status 1'): subprocess.check_call(l1.daemon.cmd_line) l1.daemon.opts.update({\"encrypted-hsm\":",
"bitcoind): \"\"\"Test the deprecated old-style: txprepare {destination} {satoshi} {feerate} {minconf}",
"Decimal(amount * 6) / 10**8 - Decimal(0.0002) assert decode['vout'][0]['scriptPubKey']['type'] ==",
"for o in l1.rpc.listfunds()['outputs']] == ['confirmed'] * 10) # It",
"node_factory.get_node(random_hsm=True) l2 = node_factory.get_node(random_hsm=True) addr = l1.rpc.newaddr()['bech32'] # Add some",
"len(decode['vin']) == 4 assert len(decode['vout']) == 4 if chainparams['feeoutput'] else",
"tip = node_factory.bitcoind.rpc.getblockcount() assert nlocktime > 0 and nlocktime <=",
"available'.format(i['txid'], i['vout'])) prep = l1.rpc.txprepare([{addr: 'all'}]) decode = bitcoind.rpc.decoderawtransaction(prep['unsigned_tx']) assert",
"what was paid to. output = only_one(l1.rpc.listfunds()['outputs']) assert output['address'] ==",
"decode['vout'][0]['value'] < Decimal(amount * 6) / 10**8 assert decode['vout'][0]['value'] >",
"* 100)}) def test_txprepare_multi(node_factory, bitcoind): amount = 10000000 l1 =",
"was paid to. output = only_one(l1.rpc.listfunds()['outputs']) assert output['address'] == addr",
"# The address we detect must match what was paid",
"'all'}]) decode = bitcoind.rpc.decoderawtransaction(prep3['unsigned_tx']) assert decode['txid'] == prep3['txid'] # 4",
"output {}/{} reset to available'.format(i['txid'], i['vout'])) prep = l1.rpc.txprepare([{addr: 'all'}])",
"with experimental features\") def test_transaction_annotations(node_factory, bitcoind): l1, l2, l3 =",
"else 1 fundidx = 1 - changeidx assert(types[changeidx] == 'deposit'",
"== prep['txid'] # 4 inputs, 2 outputs (3 if we",
"bitcoind.generate_block(1) wait_for(lambda: [o['status'] for o in l1.rpc.listfunds()['outputs']] == ['confirmed'] *",
"in range(7): l1.fundwallet(10**8) bitcoind.generate_block(1) sync_blockheight(bitcoind, [l1]) wait_for(lambda: len(l1.rpc.listfunds()['outputs']) == 7)",
"assert(len(txs) == 2 and txs[1]['hash'] == fundingtx['txid']) # Check the",
"txs[1]['hash'] == fundingtx['txid']) # Check the annotated types types =",
"outputs WHERE status=0')[0]['c'] == 0 # This should fail, can't",
"i['vout'])) prep = l1.rpc.txprepare([{addr: 'all'}]) decode = bitcoind.rpc.decoderawtransaction(prep['unsigned_tx']) assert decode['txid']",
"all other output should be change, and have no annotations",
"annotation on the output reading 'deposit' txs = l1.rpc.listtransactions()['transactions'] assert(len(txs)",
"have no annotations types = [] for i, o in",
"password.encode(\"utf-8\")) l1.daemon.wait_for_log(\"Server started with public key\") assert node_id == l1.rpc.getinfo()[\"id\"]",
"outputs WHERE status=0;') assert only_one(outputs)['value'] == 2 * amount #",
"== prep['txid'] assert discard['unsigned_tx'] == prep['unsigned_tx'] prep3 = l1.rpc.txprepare([{addr: 'all'}])",
"# Cannot discard twice. with pytest.raises(RpcError, match=r'not an unreleased txid'):",
"= l1.rpc.txprepare([{addr: Millisatoshi(amount * 3 * 500 + 100000)}, {addr:",
"that the output changed to confirmed bitcoind.generate_block(3) sync_blockheight(bitcoind, [l1, l2])",
"prompt and key derivation.\") def test_hsmtool_secret_decryption(node_factory): l1 = node_factory.get_node() password",
"a fee output). assert len(decode['vin']) == 4 assert len(decode['vout']) ==",
"funds to withdraw later for i in range(10): l1.bitcoin.rpc.sendtoaddress(addr, amount",
"if chainparams['feeoutput'] else 3 # One output will be correct.",
"outputs = l1.db_query('SELECT value FROM outputs WHERE status=0;') assert only_one(outputs)['value']",
"with pytest.raises(RpcError, match=r'Need set \\'outputs\\' field.'): l1.rpc.call('txprepare', {'destination': addr, 'feerate':",
"also match the funding txid: assert(outputs[0]['txid'] == fundingtx['txid']) # Confirm",
"else 2 # Some fees will be paid. assert decode['vout'][0]['value']",
"password = \"<PASSWORD>\" # We need to simulate a terminal",
"10**8 assert decode['vout'][0]['value'] > Decimal(amount * 10) / 10**8 -",
"2 * amount) with pytest.raises(RpcError): l1.rpc.withdraw('tb1pw508d6qejxtdg4y5r3zarvary0c5xw7kdl9fad', 2 * amount) with",
"* 1000)}], utxos=utxos) decode = bitcoind.rpc.decoderawtransaction(prep5['unsigned_tx']) assert decode['txid'] == prep5['txid']",
"accessing random memory or null txs = l1.rpc.listtransactions()['transactions'] tx =",
"> Decimal(amount * 10) / 10**8 - Decimal(0.0003) assert decode['vout'][0]['scriptPubKey']['type']",
"== 10000000 # The address we detect must match what",
"bitcoind.rpc.sendtoaddress(l1.rpc.newaddr('p2sh-segwit')['p2sh-segwit'], amount / 10**8) bitcoind.generate_block(1) wait_for(lambda: [o['status'] for o in",
"assert decode['vout'][0]['scriptPubKey']['addresses'] == [addr] l1.rpc.txdiscard(prep4['txid']) # Try passing in a",
"slave_fd = os.openpty() # Test we can encrypt an already-existing",
"as we fuzz from 0 to 100 with a 10%",
"10% probability. \"\"\" l1 = node_factory.get_node(1) l1.fundwallet(10**8) for i in",
"and len(peers[0]['channels']) == 1) scid = peers[0]['channels'][0]['short_channel_id'] assert(txs[1]['outputs'][fundidx]['channel'] == scid)",
"fail, can't even afford fee. with pytest.raises(RpcError, match=r'Cannot afford transaction'):",
"check the channel annotation on the funding output peers =",
"l1.rpc.call('txprepare', [addr, Millisatoshi(amount * 100), None, 1]) l1.rpc.call('txprepare', [addr, Millisatoshi(amount",
"reserved output {}/{} reset to available'.format(i['txid'], i['vout'])) prep = l1.rpc.txprepare([{addr:",
"types = [] for i, o in enumerate(tx['outputs']): if i",
"> 0 if decoded[\"locktime\"] < tip: return else: raise Exception(\"No",
"# Array type with pytest.raises(RpcError, match=r'.* should be an amount",
"== Decimal(amount * 3) / 10**8][0] for i, o in",
"bitcoind.rpc.decoderawtransaction(prep['unsigned_tx']) assert decode['txid'] == prep['txid'] # All 10 inputs assert",
"# Test we can encrypt an already-existing and not encrypted",
"10**5)['txid'] # next call warned about SQL Accessing a null",
"== addr @unittest.skipIf(not COMPAT, \"needs COMPAT=1\") def test_deprecated_txprepare(node_factory, bitcoind): \"\"\"Test",
"offline cmd_line[1] = \"encrypt\" subprocess.check_call(cmd_line) # Now we need to",
"and outputs[0]['status'] == 'confirmed') out = outputs[0] idx = out['output']",
"assert(len(outputs) == 1 and outputs[0]['status'] == 'confirmed') out = outputs[0]",
"it with hsmtool cmd_line[3] = password[:-1] subprocess.check_call(cmd_line) # Then test",
"fee output). assert len(decode['vin']) == 4 assert len(decode['vout']) == 2",
"Now send some money to l2. # lightningd uses P2SH-P2WPKH",
"with public key\") id = l1.rpc.getinfo()[\"id\"] l1.stop() # Test we",
"* # noqa: F401,F403 from fixtures import TEST_NETWORK from flaky",
"[addr] # Discard prep4 and get all funds again l1.rpc.txdiscard(prep5['txid'])",
"utxos=utxos) decode = bitcoind.rpc.decoderawtransaction(withdrawal['tx']) assert decode['txid'] == withdrawal['txid'] # Check",
"additional two of them were marked as spent assert l1.db_query('SELECT",
"accepted. If the current height is smaller than the number",
"one should be the funding tx # (we are ordering",
"started with public key\") id = l1.rpc.getinfo()[\"id\"] l1.stop() # Test",
"It should have logged this for each output. for i",
"100)}) prep = l1.rpc.txprepare(outputs=outputs) l1.rpc.txdiscard(prep['txid']) def test_txprepare(node_factory, bitcoind, chainparams): amount",
"prep5['txid'] # 4 inputs, 3 outputs(include change). assert len(decode['vin']) ==",
"for o in l1.rpc.listfunds()['outputs']] == ['confirmed'] * 10) with pytest.raises(RpcError,",
"bitcoind.generate_block(1) # Make sure l2 received the withdrawal. wait_for(lambda: len(l2.rpc.listfunds()['outputs'])",
"os.openpty() # Test we can encrypt an already-existing and not",
"'slow']) with pytest.raises(RpcError, match=r'Need set \\'satoshi\\' field.'): l1.rpc.call('txprepare', [addr]) with",
"amount = 10**4 l1 = node_factory.get_node(options={'allow-deprecated-apis': True}) addr = l1.rpc.newaddr()['bech32']",
"channel def test_fundchannel_listtransaction(node_factory, bitcoind): l1, l2 = node_factory.get_nodes(2) l1.fundwallet(10**6) l1.connect(l2)",
"assert decoded[\"locktime\"] > 0 if decoded[\"locktime\"] < tip: return else:",
"to confirmed bitcoind.generate_block(3) sync_blockheight(bitcoind, [l1, l2]) outputs = l1.rpc.listfunds()['outputs'] assert(len(outputs)",
"= 'bcrt1qrp33g0q5c5txsp9arysrx4k6zdkfs4nce4xj0gdcccefvpysxf3qzf4jry' with pytest.raises(RpcError): l1.rpc.withdraw('xx1qrp33g0q5c5txsp9arysrx4k6zdkfs4nce4xj0gdcccefvpysxf3q0sl5k7', 2 * amount) with pytest.raises(RpcError):",
"prep['txid'] # 4 inputs, 2 outputs (3 if we have",
"!= 'regtest', \"Test relies on a number of example addresses",
"a terminal to use termios in `lightningd`. master_fd, slave_fd =",
"id == l1.rpc.getinfo()[\"id\"] @unittest.skipIf(VALGRIND, \"It does not play well with",
"i, o in enumerate(decode['vout']): if i == outnum: assert o['scriptPubKey']['type']",
"# Some fees will be paid. assert decode['vout'][0]['value'] < Decimal(amount",
"4 assert len(decode['vout']) == 1 if not chainparams['feeoutput'] else 2",
"l1.fundwallet(10**4) addr = l1.rpc.newaddr()[\"bech32\"] tx = l1.rpc.withdraw(addr, 10**3)[\"tx\"] nlocktime =",
"change output, so this is exact assert len(decode['vout']) == 3",
"case there was a reorg. Wait. wait_for(lambda: [o['status'] for o",
"output should be change, and have no annotations types =",
"Decimal(0.0003) assert decode['vout'][0]['scriptPubKey']['type'] == 'witness_v0_keyhash' assert decode['vout'][0]['scriptPubKey']['addresses'] == [addr] l1.rpc.txdiscard(prep4['txid'])",
"4 outputs. discard = l1.rpc.txdiscard(prep['txid']) assert discard['txid'] == prep['txid'] assert",
"[addr] # If I cancel the first one, I can",
"clamp the maxheight parameter to a positive small number. \"\"\"",
"withdrawal to P2WSH # Address from: https://bc-2.jp/tools/bech32demo/index.html waddr = 'bcrt1qrp33g0q5c5txsp9arysrx4k6zdkfs4nce4xj0gdcccefvpysxf3qzf4jry'",
"3.5) / 10**8 assert decode['vout'][1]['scriptPubKey']['type'] == 'witness_v0_keyhash' assert decode['vout'][1]['scriptPubKey']['addresses'] ==",
"should be change, and have no annotations types = []",
"previous runs. l1 = node_factory.get_node(random_hsm=True) addr = l1.rpc.newaddr()['bech32'] # Add",
"hsm_secret.\")) # Test we can restore the same wallet with",
"inputs, 1 outputs. assert len(decode['vin']) == 6 assert len(decode['vout']) ==",
"FROM outputs WHERE status=0')[0]['c'] == 6 # Test withdrawal to",
"l1.rpc.listfunds()[\"outputs\"]][:4] prep5 = l1.rpc.txprepare([{addr: Millisatoshi(amount * 3.5 * 1000)}], utxos=utxos)",
"outputs WHERE status=0')[0]['c'] == 10 waddr = l1.bitcoin.rpc.getnewaddress() # Now",
"must match what was paid to. output = only_one(l1.rpc.listfunds()['outputs']) assert",
"4 assert len(decode['vout']) == 2 if not chainparams['feeoutput'] else 3",
"# this test does a 'listtransactions' on a yet unconfirmed",
"wait_for(lambda: [o['status'] for o in l1.rpc.listfunds()['outputs']] == ['confirmed'] * 10)",
"# And check the channel annotation on the funding output",
"assert decode['vout'][0]['value'] < Decimal(amount * 4) / 10**8 assert decode['vout'][0]['value']",
"1]['value'] == Decimal('0.01499900'): outnum2 = i - 1 else: changenum",
"# Change output should appear. if decode['vout'][0]['value'] == Decimal(amount *",
"assert(len(outputs) == 1 and outputs[0]['status'] == 'confirmed') # We should",
"witness version with pytest.raises(RpcError): l1.rpc.withdraw('BC13W508D6QEJXTDG4Y5R3ZARVARY0C5XW7KN40WF2', 2 * amount) # Invalid",
"l1.rpc.withdraw(waddr, -amount) with pytest.raises(RpcError, match=r'Cannot afford transaction'): l1.rpc.withdraw(waddr, amount *",
"Now make sure an additional two of them were marked",
"Now we need to pass the encrypted-hsm startup option l1.stop()",
"assert nlocktime > 0 and nlocktime <= tip @flaky @unittest.skipIf(VALGRIND,",
"assert(txs[1]['outputs'][fundidx]['channel'] == scid) @unittest.skipIf(VALGRIND, \"It does not play well with",
"# All 10 inputs assert len(decode['vin']) == 10 # L1",
"= 1000000 # Don't get any funds from previous runs.",
"amount / 10**8) bitcoind.generate_block(1) wait_for(lambda: len(l1.rpc.listfunds()['outputs']) == 1) outputs =",
"== set(types)) ########################################################################## # Let's now open a channel. The",
"amount) # Invalid program length for witness version 0 (per",
"decode['vin']: assert l1.daemon.is_in_log('wallet: reserved output {}/{} reset to available'.format(i['txid'], i['vout']))",
"assert output['address'] == addr # Send all our money to",
"the # transactions table... outputs = l1.rpc.listfunds()['outputs'] assert(len(outputs) == 1",
"pytest.raises(RpcError): l1.rpc.withdraw('an84characterslonghumanreadablepartthatcontainsthenumber1andtheexcludedcharactersbio1569pvx', 2 * amount) # No separator character with",
"number of confirmations is used to compute a maximum height",
"with pytest.raises(RpcError): l1.rpc.withdraw('not an address', amount) with pytest.raises(RpcError): l1.rpc.withdraw(waddr, 'not",
"\\'outputs\\' field.'): l1.rpc.call('txprepare', {'destination': addr, 'feerate': 'slow'}) with pytest.raises(RpcError, match=r'Need",
"assert(outputs[0]['txid'] == fundingtx['txid']) # Confirm the channel and check that",
"0.01) bitcoind.generate_block(1) wait_for(lambda: len(l1.rpc.listfunds()['outputs']) == 10) # Reach around into",
"outnum: assert o['scriptPubKey']['type'] == 'witness_v0_keyhash' assert o['scriptPubKey']['addresses'] == [addr] else:",
"3 # One output will be correct. outnum = [i",
"decode['vout'][0]['scriptPubKey']['type'] == 'witness_v0_keyhash' assert decode['vout'][0]['scriptPubKey']['addresses'] == [addr] # Cannot discard",
"decode['vout'][changenum]['scriptPubKey']['type'] == 'witness_v0_keyhash' def test_txsend(node_factory, bitcoind, chainparams): amount = 1000000",
"# Some fees will be taken assert decode['vout'][0]['value'] < Decimal(amount",
"case with pytest.raises(RpcError): l1.rpc.withdraw('tb1qrp33g0q5c5txsp9arysrx4k6zdkfs4nce4xj0gdcccefvpysxf3q0sL5k7', 2 * amount) # Non-zero padding",
"fundingtx['txid']) # Confirm the channel and check that the output",
"# This will also work if we simply kill it.",
"txs = l1.rpc.listtransactions()['transactions'] assert(len(txs) == 1) tx = txs[0] output",
"around and just select everything. The fix is to clamp",
"{'destination': addr, 'satoshi': Millisatoshi(amount * 100), 'feerate': '2000perkw', 'minconf': 1})",
"wait_for(lambda: len(l1.rpc.listfunds()['outputs']) == 10 - len(decode['vin']) + 1) # Change",
"spend all inputs. l1.rpc.txdiscard(prep2['txid']) l1.rpc.txdiscard(prep3['txid']) prep4 = l1.rpc.txprepare([{addr: 'all'}]) decode",
"2 * amount) bitcoind.generate_block(1) # Make sure l2 received the",
"not chainparams['feeoutput'] else 2 # Some fees will be taken",
"should have logged this for each output. for i in",
"chainparams['feeoutput'] else 3 # One output will be correct. outnum",
"bitcoind received the withdrawal unspent = l1.bitcoin.rpc.listunspent(0) withdrawal = [u",
"have a fee output). assert len(decode['vin']) == 4 assert len(decode['vout'])",
"not .*'): l1.rpc.call('txprepare', [addr, 'slow']) with pytest.raises(RpcError, match=r'Need set \\'satoshi\\'",
"that we eventually fuzz nLockTime for withdrawal transactions. Marked flaky",
"bitcoind.generate_block(1) # Now make sure additional two of them were",
"be accepted. If the current height is smaller than the",
"should have a change output, so this is exact assert",
"changenum = 1 elif decode['vout'][1]['value'] == Decimal(amount * 3) /",
"waddr = 'bcrt1qrp33g0q5c5txsp9arysrx4k6zdkfs4nce4xj0gdcccefvpysxf3qzf4jry' with pytest.raises(RpcError): l1.rpc.withdraw('xx1qrp33g0q5c5txsp9arysrx4k6zdkfs4nce4xj0gdcccefvpysxf3q0sl5k7', 2 * amount) with",
"other output should be change, and have no annotations types",
"\"\"\" amount = 1000000 # Don't get any funds from",
"those first 4 outputs. discard = l1.rpc.txdiscard(prep['txid']) assert discard['txid'] ==",
"funds to the daemon without telling it explicitly \"\"\" #",
"with pytest.raises(subprocess.CalledProcessError): subprocess.check_call(cmd_line) # Decrypt it with hsmtool cmd_line[3] =",
"decode['txid'] == prep4['txid'] # 10 inputs, 1 outputs. assert len(decode['vin'])",
"key\") assert node_id == l1.rpc.getinfo()[\"id\"] l1.stop() # And finally test",
"that is to be accepted. If the current height is",
"10**8][0] for i, o in enumerate(decode['vout']): if i == outnum:",
"assert False # Those spent outputs are gone, but change",
"that there are no unconfirmed outputs (change should be confirmed)",
"len(l1.rpc.listfunds()['outputs']) == 10) with pytest.raises(RpcError): l1.rpc.withdraw(destination=addr, satoshi=10000, feerate='normal', minconf=9999999) def",
"= l1.rpc.withdraw(waddr, 2 * amount) # Make sure bitcoind received",
"10**8) bitcoind.rpc.sendtoaddress(l1.rpc.newaddr('p2sh-segwit')['p2sh-segwit'], amount / 10**8) bitcoind.generate_block(1) wait_for(lambda: [o['status'] for o",
"c FROM outputs WHERE status=0')[0]['c'] == 6 # Test withdrawal",
"Should have 6 outputs available. assert l1.db_query('SELECT COUNT(*) as c",
"enumerate(decode['vout']): if i == outnum: assert o['scriptPubKey']['type'] == 'witness_v0_keyhash' assert",
"now spend all inputs. l1.rpc.txdiscard(prep2['txid']) l1.rpc.txdiscard(prep3['txid']) prep4 = l1.rpc.txprepare([{addr: 'all'}])",
"== 1 l1.rpc.withdraw(waddr, 'all', minconf=0) assert l1.db_query('SELECT COUNT(*) as c",
"# transactions table... outputs = l1.rpc.listfunds()['outputs'] assert(len(outputs) == 1 and",
"l1.daemon.start(stdin=slave_fd, wait_for_initialized=True) assert node_id == l1.rpc.getinfo()[\"id\"] # this test does",
"/ 10**8) bitcoind.rpc.sendtoaddress(l1.rpc.newaddr('p2sh-segwit')['p2sh-segwit'], amount / 10**8) bitcoind.generate_block(1) wait_for(lambda: len(l1.rpc.listfunds()['outputs']) ==",
"both bech32 and p2sh for i in range(5): bitcoind.rpc.sendtoaddress(l1.rpc.newaddr()['bech32'], amount",
"table... outputs = l1.rpc.listfunds()['outputs'] assert(len(outputs) == 1 and outputs[0]['status'] ==",
"l1.daemon.start(stdin=slave_fd, wait_for_initialized=True) assert node_id == l1.rpc.getinfo()[\"id\"] l1.stop() # Test we",
"SegWit addresses, from BIP173 # HRP character out of range",
"Try passing in a utxo set utxos = [utxo[\"txid\"] +",
"= node_factory.get_node(random_hsm=True) addr = chainparams['example_addr'] # Add some funds to",
"# Previous runs with same bitcoind can leave funds! l1",
"i in range(10): l1.bitcoin.rpc.sendtoaddress(addr, amount / 10**8 + 0.01) bitcoind.generate_block(1)",
"were added assert l1.db_query('SELECT COUNT(*) as c FROM outputs WHERE",
"[utxo[\"txid\"] + \":\" + str(utxo[\"output\"]) for utxo in l1.rpc.listfunds()[\"outputs\"]][:4] prep5",
"we can restore the same wallet with the same password",
"withdrawal to P2WPKH # Address from: https://bc-2.jp/tools/bech32demo/index.html waddr = 'bcrt1qw508d6qejxtdg4y5r3zarvary0c5xw7kygt080'",
"WHERE status=2')[0]['c'] == 4 # Simple test for withdrawal to",
"and outputs[0]['status'] == 'confirmed') # We should have 2 transactions,",
"assert decode['vout'][outnum2]['scriptPubKey']['addresses'] == [addr] assert decode['vout'][changenum]['scriptPubKey']['type'] == 'witness_v0_keyhash' def test_txsend(node_factory,",
"10**8: changenum = 1 elif decode['vout'][1]['value'] == Decimal(amount * 3)",
"# We can't use a wrong password ! cmd_line =",
"utxos are included assert len(decode['vin']) == 4 vins = [\"{}:{}\".format(v['txid'],",
"True}) addr = l1.rpc.newaddr()['bech32'] for i in range(7): l1.fundwallet(10**8) bitcoind.generate_block(1)",
"'deposit' txs = l1.rpc.listtransactions()['transactions'] assert(len(txs) == 1) tx = txs[0]",
"[addr] else: assert o['scriptPubKey']['type'] in ['witness_v0_keyhash', 'fee'] # Now prepare",
"['confirmed'] * 10) # It should have logged this for",
"the current height is smaller than the number of confirmations",
"transactions. Marked flaky \"just in case\" as we fuzz from",
"Millisatoshi(amount * 100)}) def test_txprepare_multi(node_factory, bitcoind): amount = 10000000 l1",
"for invalid SegWit addresses, from BIP173 # HRP character out",
"* 10) prep = l1.rpc.txprepare([{addr: 'all'}]) decode = bitcoind.rpc.decoderawtransaction(prep['unsigned_tx']) assert",
"10) # Try passing in a utxo set utxos =",
"Those spent outputs are gone, but change output has arrived.",
"= node_factory.get_node(may_fail=True) addr = chainparams['example_addr'] # Add some funds to",
"# We should have 2 transactions, the second one should",
"to P2WPKH # Address from: https://bc-2.jp/tools/bech32demo/index.html waddr = 'bcrt1qw508d6qejxtdg4y5r3zarvary0c5xw7kygt080' with",
"for i in range(7): l1.fundwallet(10**8) bitcoind.generate_block(1) sync_blockheight(bitcoind, [l1]) wait_for(lambda: len(l1.rpc.listfunds()['outputs'])",
"== 10 @unittest.skipIf(TEST_NETWORK != 'regtest', \"Fee outputs throw off our",
"10000000 l1 = node_factory.get_node(random_hsm=True) bitcoind.rpc.sendtoaddress(l1.rpc.newaddr()['bech32'], amount / 10**8) bitcoind.generate_block(1) wait_for(lambda:",
"bech32 and p2sh for i in range(5): bitcoind.rpc.sendtoaddress(l1.rpc.newaddr()['bech32'], amount /",
"== 1) outputs = [] for i in range(9): outputs.append({l1.rpc.newaddr()['bech32']:",
"it explicitly \"\"\" # Previous runs with same bitcoind can",
"node_factory.get_node(1) l1.fundwallet(10**4) addr = l1.rpc.newaddr()[\"bech32\"] tx = l1.rpc.withdraw(addr, 10**3)[\"tx\"] nlocktime",
"'regtest', \"Fee outputs throw off our output matching logic\") @unittest.skipIf(not",
"'satoshi': Millisatoshi(amount * 100), 'feerate': '2000perkw'}) l1.rpc.call('txprepare', {'destination': addr, 'satoshi':",
"for u in unspent if u['txid'] == out['txid']] assert(withdrawal[0]['amount'] ==",
"node_id == l1.rpc.getinfo()[\"id\"] l1.stop() # And finally test that we",
"# Object type with pytest.raises(RpcError, match=r'Need set \\'outputs\\' field.'): l1.rpc.call('txprepare',",
"\"decrypt\" subprocess.check_call(cmd_line) l1.daemon.opts.pop(\"encrypted-hsm\") l1.daemon.start(stdin=slave_fd, wait_for_initialized=True) assert node_id == l1.rpc.getinfo()[\"id\"] #",
"= l1.rpc.newaddr()['bech32'] for i in range(7): l1.fundwallet(10**8) bitcoind.generate_block(1) sync_blockheight(bitcoind, [l1])",
"prep['unsigned_tx'] prep3 = l1.rpc.txprepare([{addr: 'all'}]) decode = bitcoind.rpc.decoderawtransaction(prep3['unsigned_tx']) assert decode['txid']",
"@unittest.skipIf(TEST_NETWORK != 'regtest', \"Fee outputs throw off our output matching",
"of range with pytest.raises(RpcError): l1.rpc.withdraw(' 1nwldj5', 2 * amount) #",
"# Cannot discard after send! with pytest.raises(RpcError, match=r'not an unreleased",
"l1.daemon.opts.pop(\"encrypted-hsm\") with pytest.raises(subprocess.CalledProcessError, match=r'returned non-zero exit status 1'): subprocess.check_call(l1.daemon.cmd_line) #",
"but change output has arrived. wait_for(lambda: len(l1.rpc.listfunds()['outputs']) == 10 -",
"10**8 - Decimal(0.0003) assert decode['vout'][0]['scriptPubKey']['type'] == 'witness_v0_keyhash' assert decode['vout'][0]['scriptPubKey']['addresses'] ==",
"bitcoind.rpc.decoderawtransaction(prep2['unsigned_tx']) assert decode['txid'] == prep2['txid'] # 6 inputs, 1 outputs.",
"we collect multiple inputs) with pytest.raises(RpcError): l1.rpc.withdraw('not an address', amount)",
"of them were marked as spent assert l1.db_query('SELECT COUNT(*) as",
"to clamp the maxheight parameter to a positive small number.",
"started without key password = \"<PASSWORD>\" # We need to",
"* amount) # Make sure bitcoind received the withdrawal unspent",
"os.openpty() # Encrypt the master seed l1.stop() l1.daemon.opts.update({\"encrypted-hsm\": None}) l1.daemon.start(stdin=slave_fd,",
"0.01) bitcoind.generate_block(1) wait_for(lambda: len(l1.rpc.listfunds()['outputs']) == 10) with pytest.raises(RpcError): l1.rpc.withdraw(destination=addr, satoshi=10000,",
"addr = l1.rpc.newaddr()['bech32'] for i in range(7): l1.fundwallet(10**8) bitcoind.generate_block(1) sync_blockheight(bitcoind,",
"l1.daemon.is_in_log('wallet: reserved output {}/{} reset to available'.format(i['txid'], i['vout'])) prep =",
"l1.connect(l2) txid = l1.rpc.fundchannel(l2.info['id'], 10**5)['txid'] # next call warned about",
"(per BIP141) with pytest.raises(RpcError): l1.rpc.withdraw('BC1QR508D6QEJXTDG4Y5R3ZARVARYV98GJ9P', 2 * amount) # Mixed",
"= l1.rpc.listtransactions()['transactions'] tx = [t for t in txs if",
"txid][0] assert tx['blockheight'] == 0 def test_withdraw_nlocktime(node_factory): \"\"\" Test that",
"1]) l1.rpc.call('txprepare', [addr, Millisatoshi(amount * 100), 'normal']) l1.rpc.call('txprepare', [addr, Millisatoshi(amount",
"key\") assert id == l1.rpc.getinfo()[\"id\"] @unittest.skipIf(VALGRIND, \"It does not play",
"assert len(decode['vin']) == 10 assert len(decode['vout']) == 1 if not",
"vins def test_minconf_withdraw(node_factory, bitcoind): \"\"\"Issue 2518: ensure that ridiculous confirmation",
"assert o['scriptPubKey']['type'] == 'witness_v0_keyhash' assert o['scriptPubKey']['addresses'] == [addr] else: assert",
"== Decimal('0.01500100'): outnum1 = i - 1 elif decode['vout'][i -",
"test_txprepare_restart(node_factory, bitcoind, chainparams): amount = 1000000 l1 = node_factory.get_node(may_fail=True) addr",
"wait_for(lambda: len(l2.rpc.listfunds()['outputs']) == 1) outputs = l2.db_query('SELECT value FROM outputs",
"== prep4['txid'] # 10 inputs, 1 outputs. assert len(decode['vin']) ==",
"value FROM outputs WHERE status=0;') assert only_one(outputs)['value'] == 2 *",
"l1.rpc.call('txprepare', [Millisatoshi(amount * 100), 'slow', 1]) l1.rpc.call('txprepare', [addr, Millisatoshi(amount *",
"== 'confirmed' # Now make sure two of them were",
"inputs, 2 outputs (3 if we have a fee output).",
"= l1.rpc.txprepare([{addr: Millisatoshi(amount * 3 * 1000)}]) out = l1.rpc.txsend(prep['txid'])",
"from fixtures import TEST_NETWORK from flaky import flaky # noqa:",
"== l1.rpc.getinfo()[\"id\"] @unittest.skipIf(VALGRIND, \"It does not play well with prompt",
"i - 1 assert decode['vout'][outnum1]['scriptPubKey']['type'] == 'witness_v0_keyhash' assert decode['vout'][outnum1]['scriptPubKey']['addresses'] ==",
"bitcoind.rpc.decoderawtransaction(out['tx']) assert decode['txid'] == prep['txid'] bitcoind.generate_block(1) # Change output should",
"addr = l1.rpc.newaddr()[\"bech32\"] withdraw = l1.rpc.withdraw(addr, 10**3) bitcoind.generate_block(1) l1.daemon.wait_for_log('Owning output",
"l1.rpc.withdraw('tb1prp33g0q5c5txsp9arysrx4k6zdkfs4nce4xj0gdcccefvpysxf3qsm03tq', 2 * amount) with pytest.raises(RpcError): l1.rpc.withdraw('tb1qrp33g0q5c5txsp9arysrx4k6zdkfs4nce4xj0gdcccefvpysxf3qxxxxxx', 2 * amount)",
"sync_blockheight, EXPERIMENTAL_FEATURES, COMPAT, VALGRIND ) import os import pytest import",
"= bitcoind.rpc.decoderawtransaction(withdraw[\"tx\"]) tip = node_factory.bitcoind.rpc.getblockcount() assert decoded[\"locktime\"] > 0 if",
"encrypt it offline cmd_line[1] = \"encrypt\" subprocess.check_call(cmd_line) # Now we",
"paid to. output = only_one(l1.rpc.listfunds()['outputs']) assert output['address'] == addr @unittest.skipIf(not",
"= bitcoind.rpc.decoderawtransaction(out['tx']) assert decode['txid'] == prep['txid'] bitcoind.generate_block(1) # Change output",
"l1.rpc.fundchannel(l2.info['id'], 10**5)['txid'] # next call warned about SQL Accessing a",
"10 inputs, 1 outputs. assert len(decode['vin']) == 10 assert len(decode['vout'])",
"current height is smaller than the number of confirmations we",
"an amount in satoshis or all, not .*'): l1.rpc.call('txprepare', [addr,",
"== 1) assert(l1.daemon.is_in_log(\"Wrong password for encrypted hsm_secret.\")) # Test we",
"any funds from previous runs. l1 = node_factory.get_node(random_hsm=True) addr =",
"assert decode['vout'][changenum]['scriptPubKey']['type'] == 'witness_v0_keyhash' def test_txsend(node_factory, bitcoind, chainparams): amount =",
"make sure additional two of them were marked as spent",
"with pytest.raises(RpcError): l1.rpc.withdraw('an84characterslonghumanreadablepartthatcontainsthenumber1andtheexcludedcharactersbio1569pvx', 2 * amount) # No separator character",
"decode = bitcoind.rpc.decoderawtransaction(out['tx']) assert decode['txid'] == prep['txid'] bitcoind.generate_block(1) # Change",
"txid decode = bitcoind.rpc.decoderawtransaction(out['tx']) assert decode['txid'] == prep['txid'] bitcoind.generate_block(1) #",
"assert(len(outputs) == 1 and outputs[0]['status'] == 'unconfirmed') # It should",
"slave_fd = os.openpty() # Encrypt the master seed l1.stop() l1.daemon.opts.update({\"encrypted-hsm\":",
"in case there was a reorg. Wait. wait_for(lambda: [o['status'] for",
"WHERE status=0')[0]['c'] == 0 # This should fail, can't even",
"termios in `lightningd`. master_fd, slave_fd = os.openpty() # Test we",
"amount / 10**8) bitcoind.generate_block(1) wait_for(lambda: len(l1.rpc.listfunds()['outputs']) == 10) prep =",
"== prep5['txid'] # 4 inputs, 3 outputs(include change). assert len(decode['vin'])",
"# noqa: F401 from pyln.client import RpcError, Millisatoshi from utils",
"Millisatoshi(amount * 3 * 500 + 100000)}, {addr: Millisatoshi(amount *",
"decode = bitcoind.rpc.decoderawtransaction(withdrawal['tx']) assert decode['txid'] == withdrawal['txid'] # Check that",
"o in enumerate(decode['vout']) if o['value'] == Decimal(amount * 3) /",
") import os import pytest import subprocess import time import",
"annotations which are compiled only with experimental features\") def test_transaction_annotations(node_factory,",
"is encrypted') os.write(master_fd, password[2:].encode(\"utf-8\")) assert(l1.daemon.proc.wait() == 1) assert(l1.daemon.is_in_log(\"Wrong password for",
"cmd_line[1] = \"encrypt\" subprocess.check_call(cmd_line) # Now we need to pass",
"any funds from previous runs. l1 = node_factory.get_node(random_hsm=True) l2 =",
"vins # We should have a change output, so this",
"i, o in enumerate(tx['outputs']): if i == idx: continue if",
"withdrawal. wait_for(lambda: len(l2.rpc.listfunds()['outputs']) == 1) outputs = l2.db_query('SELECT value FROM",
"COUNT(*) as c FROM outputs WHERE status=0')[0]['c'] == 0 #",
"if we simply kill it. l1.restart(clean=False) # It goes backwards",
"chainparams['example_addr'] # Add some funds to withdraw later: both bech32",
"to check that outputs were added assert l1.db_query('SELECT COUNT(*) as",
"6) / 10**8 - Decimal(0.0002) assert decode['vout'][0]['scriptPubKey']['type'] == 'witness_v0_keyhash' assert",
"no annotations types = [] for i, o in enumerate(tx['outputs']):",
"'not an amount') with pytest.raises(RpcError): l1.rpc.withdraw(waddr, -amount) with pytest.raises(RpcError, match=r'Cannot",
"decode['vout'][0]['value'] < Decimal(amount * 10) / 10**8 assert decode['vout'][0]['value'] >",
"\"<PASSWORD>\" hsm_path = os.path.join(l1.daemon.lightning_dir, TEST_NETWORK, \"hsm_secret\") # We need to",
"wait_for(lambda: len(l1.rpc.listfunds()['outputs']) == 10) # Reach around into the db",
"* 3) / 10**8][0] for i, o in enumerate(decode['vout']): if",
"= 10**4 l1 = node_factory.get_node(options={'allow-deprecated-apis': True}) addr = l1.rpc.newaddr()['bech32'] for",
"exact assert len(decode['vout']) == 3 if chainparams['feeoutput'] else 2 assert",
"100 with a 10% probability. \"\"\" l1 = node_factory.get_node(1) l1.fundwallet(10**8)",
"stderr=subprocess.STDOUT, wait_for_initialized=False) l1.daemon.wait_for_log(r'The hsm_secret is encrypted') os.write(master_fd, password.encode(\"utf-8\")) l1.daemon.wait_for_log(\"Server started",
"l1.rpc.withdraw(addr, 10**3) bitcoind.generate_block(1) l1.daemon.wait_for_log('Owning output .* txid {} CONFIRMED'. format(withdraw[\"txid\"]))",
"= l1.rpc.withdraw(addr, 10**3) bitcoind.generate_block(1) l1.daemon.wait_for_log('Owning output .* txid {} CONFIRMED'.",
"== txid][0] assert tx['blockheight'] == 0 def test_withdraw_nlocktime(node_factory): \"\"\" Test",
"decode['vout'][outnum1]['scriptPubKey']['addresses'] == [addr] assert decode['vout'][outnum2]['scriptPubKey']['type'] == 'witness_v0_keyhash' assert decode['vout'][outnum2]['scriptPubKey']['addresses'] ==",
"= node_factory.get_node(random_hsm=True) l2 = node_factory.get_node(random_hsm=True) addr = l1.rpc.newaddr()['bech32'] # Add",
"uses P2SH-P2WPKH waddr = l2.rpc.newaddr('bech32')['bech32'] l1.rpc.withdraw(waddr, 2 * amount) bitcoind.generate_block(1)",
"from BIP173 # HRP character out of range with pytest.raises(RpcError):",
"o['scriptPubKey']['type'] == 'witness_v0_keyhash' assert o['scriptPubKey']['addresses'] == [addr] else: assert o['scriptPubKey']['type']",
"an amount') with pytest.raises(RpcError): l1.rpc.withdraw(waddr, -amount) with pytest.raises(RpcError, match=r'Cannot afford",
"we wrap around and just select everything. The fix is",
"amount) # Empty HRP with pytest.raises(RpcError): l1.rpc.withdraw('1pzry9x0s0muk', 2 * amount)",
"will be correct. for i in range(3 + chainparams['feeoutput']): if",
"to the daemon without telling it explicitly \"\"\" # Previous",
"2 * amount) # Make sure bitcoind received the withdrawal",
"l2 = node_factory.get_node(random_hsm=True) addr = l1.rpc.newaddr()['bech32'] # Add some funds",
"one output available, and it should be unconfirmed outputs =",
"addr @unittest.skipIf(not COMPAT, \"needs COMPAT=1\") def test_deprecated_txprepare(node_factory, bitcoind): \"\"\"Test the",
"should be unconfirmed outputs = l1.rpc.listfunds()['outputs'] assert(len(outputs) == 1 and",
"= node_factory.get_node(1) l1.fundwallet(10**4) addr = l1.rpc.newaddr()[\"bech32\"] tx = l1.rpc.withdraw(addr, 10**3)[\"tx\"]",
"'2000perkw', 'minconf': 1}) l1.rpc.call('txprepare', {'destination': addr, 'satoshi': Millisatoshi(amount * 100),",
"for o in txs[1]['outputs']] changeidx = 0 if types[0] ==",
"pytest.raises(RpcError, match=r'.* should be an amount in satoshis or all,",
"chainparams['feeoutput'] else 2 # Some fees will be paid. assert",
"'deposit' and output['satoshis'] == '1000000000msat') # ... and all other",
"1]) l1.rpc.call('txprepare', [addr, Millisatoshi(amount * 100), 'slow', 1]) l1.rpc.call('txprepare', [addr,",
"with pytest.raises(RpcError, match=r'not an unreleased txid'): l1.rpc.txdiscard(prep['txid']) prep = l1.rpc.txprepare([{addr:",
"{feerate} {minconf} \"\"\" amount = 10**4 l1 = node_factory.get_node(options={'allow-deprecated-apis': True})",
"10 waddr = l1.bitcoin.rpc.getnewaddress() # Now attempt to withdraw some",
"utxo in utxos: assert utxo in vins def test_minconf_withdraw(node_factory, bitcoind):",
"amount, utxos=utxos) decode = bitcoind.rpc.decoderawtransaction(withdrawal['tx']) assert decode['txid'] == withdrawal['txid'] #",
"wallet with another password l1.daemon.opts.update({\"encrypted-hsm\": None}) l1.daemon.start(stdin=slave_fd, stderr=subprocess.STDOUT, wait_for_initialized=False) l1.daemon.wait_for_log(r'The",
"== prep['txid'] bitcoind.generate_block(1) # Change output should appear. if decode['vout'][0]['value']",
"# Address from: https://bc-2.jp/tools/bech32demo/index.html waddr = 'bcrt1qw508d6qejxtdg4y5r3zarvary0c5xw7kygt080' with pytest.raises(RpcError): l1.rpc.withdraw('xx1qw508d6qejxtdg4y5r3zarvary0c5xw7kxpjzsx',",
"= [\"{}:{}\".format(v['txid'], v['vout']) for v in decode['vin']] for utxo in",
"l1 = node_factory.get_node(may_fail=True) addr = chainparams['example_addr'] # Add some funds",
"nlocktime = node_factory.bitcoind.rpc.decoderawtransaction(tx)[\"locktime\"] tip = node_factory.bitcoind.rpc.getblockcount() assert nlocktime > 0",
"amount) l1.rpc.withdraw(waddr, 2 * amount) bitcoind.generate_block(1) # Now make sure",
"l1.rpc.txprepare([{addr: 'all'}]) decode = bitcoind.rpc.decoderawtransaction(prep3['unsigned_tx']) assert decode['txid'] == prep3['txid'] #",
"= bitcoind.rpc.decoderawtransaction(prep['unsigned_tx']) assert decode['txid'] == prep['txid'] # All 10 inputs",
"assert len(decode['vout']) == 4 if chainparams['feeoutput'] else 3 # One",
"\"\"\" l1 = node_factory.get_node(1) l1.fundwallet(10**8) for i in range(100): addr",
"with pytest.raises(RpcError): l1.rpc.withdraw(destination=addr, satoshi=10000, feerate='normal', minconf=9999999) def test_addfunds_from_block(node_factory, bitcoind): \"\"\"Send",
"kill it. l1.restart(clean=False) # It goes backwards in blockchain just",
"and deposit. l1.connect(l2) fundingtx = l1.rpc.fundchannel(l2.info['id'], 10**5) # We should",
"2 * amount, utxos=utxos) decode = bitcoind.rpc.decoderawtransaction(withdrawal['tx']) assert decode['txid'] ==",
"out = l1.rpc.txsend(prep['txid']) # Cannot discard after send! with pytest.raises(RpcError,",
"SQL Accessing a null column # and crashed the daemon",
"and just select everything. The fix is to clamp the",
"Signed tx should have same txid decode = bitcoind.rpc.decoderawtransaction(out['tx']) assert",
"# We need to simulate a terminal to use termios",
"# HRP character out of range with pytest.raises(RpcError): l1.rpc.withdraw(' 1nwldj5',",
"6) / 10**8 assert decode['vout'][0]['value'] > Decimal(amount * 6) /",
"[addr, Millisatoshi(amount * 100)]) # Object type with pytest.raises(RpcError, match=r'Need",
"* 3 * 1000)}]) decode = bitcoind.rpc.decoderawtransaction(prep['unsigned_tx']) assert decode['txid'] ==",
"for witness version 0 (per BIP141) with pytest.raises(RpcError): l1.rpc.withdraw('BC1QR508D6QEJXTDG4Y5R3ZARVARYV98GJ9P', 2",
"1) outputs = l1.db_query('SELECT value FROM outputs WHERE status=0;') assert",
"from previous runs. l1 = node_factory.get_node(random_hsm=True) addr = l1.rpc.newaddr()['bech32'] #",
"Empty HRP with pytest.raises(RpcError): l1.rpc.withdraw('1pzry9x0s0muk', 2 * amount) # Invalid",
"10 # This will also work if we simply kill",
"len(decode['vin']) == 10 assert len(decode['vout']) == 1 if not chainparams['feeoutput']",
"l1.rpc.txprepare([{addr: Millisatoshi(amount * 3 * 1000)}, {addr: 'all'}]) prep5 =",
"10**8 + 0.01) bitcoind.generate_block(1) wait_for(lambda: len(l1.rpc.listfunds()['outputs']) == 10) # Try",
"== 1 and outputs[0]['status'] == 'confirmed') out = outputs[0] idx",
"+ 0.01) bitcoind.generate_block(1) wait_for(lambda: len(l1.rpc.listfunds()['outputs']) == 10) with pytest.raises(RpcError): l1.rpc.withdraw(destination=addr,",
"If the current height is smaller than the number of",
"0 for withdrawal transactions. \"\"\" l1 = node_factory.get_node(1) l1.fundwallet(10**4) addr",
"pytest.raises(RpcError, match=r'not an unreleased txid'): l1.rpc.txdiscard(prep['txid']) prep = l1.rpc.txprepare([{addr: 'all'}])",
"for utxo in l1.rpc.listfunds()[\"outputs\"]][:4] withdrawal = l1.rpc.withdraw(waddr, 2 * amount,",
"* 100), 'slow', 1]) l1.rpc.call('txprepare', [addr, Millisatoshi(amount * 100), 'slow',",
"destination wants all satoshi. The count of outputs can\\'t be",
"# Those spent outputs are gone, but change output has",
"[addr, Millisatoshi(amount * 100), 'slow', 1]) l1.rpc.call('txprepare', [addr, Millisatoshi(amount *",
"master seed l1.stop() l1.daemon.opts.update({\"encrypted-hsm\": None}) l1.daemon.start(stdin=slave_fd, wait_for_initialized=False) l1.daemon.wait_for_log(r'The hsm_secret is",
"* 1000)}, {addr: 'all'}]) prep5 = l1.rpc.txprepare([{addr: Millisatoshi(amount * 3",
"* amount) with pytest.raises(RpcError): l1.rpc.withdraw('tb1qrp33g0q5c5txsp9arysrx4k6zdkfs4nce4xj0gdcccefvpysxf3qxxxxxx', 2 * amount) l1.rpc.withdraw(waddr, 2",
"well with prompt and key derivation.\") def test_hsmtool_secret_decryption(node_factory): l1 =",
"for withdrawal transactions. \"\"\" l1 = node_factory.get_node(1) l1.fundwallet(10**4) addr =",
"/ 10**8: changenum = 1 elif decode['vout'][1]['value'] == Decimal(amount *",
"prep['txid'] # All 10 inputs assert len(decode['vin']) == 10 @unittest.skipIf(TEST_NETWORK",
"# Now attempt to withdraw some (making sure we collect",
"Millisatoshi(amount * 100)}) prep = l1.rpc.txprepare(outputs=outputs) l1.rpc.txdiscard(prep['txid']) def test_txprepare(node_factory, bitcoind,",
"# One output will be correct. outnum = [i for",
"warned about SQL Accessing a null column # and crashed",
"minconf=0) bitcoind.generate_block(1) assert l1.db_query('SELECT COUNT(*) as c FROM outputs WHERE",
"output = tx['outputs'][idx] assert(output['type'] == 'deposit' and output['satoshis'] == '1000000000msat')",
"WHERE status=0')[0]['c'] == 1 l1.rpc.withdraw(waddr, 'all', minconf=0) assert l1.db_query('SELECT COUNT(*)",
"Millisatoshi(amount * 100), 'feerate': '10perkw', 'minconf': 2}) l1.rpc.call('txprepare', {'destination': addr,",
"included assert len(decode['vin']) == 4 vins = [\"{}:{}\".format(v['txid'], v['vout']) for",
"afford transaction'): l1.rpc.withdraw(waddr, 'all') # Add some funds to withdraw",
"some funds to withdraw for i in range(10): l1.bitcoin.rpc.sendtoaddress(addr, amount",
"1]['value'] == Decimal('0.01500100'): outnum1 = i - 1 elif decode['vout'][i",
"status=0;') assert only_one(outputs)['value'] == 2 * amount # Now make",
"already-existing and not encrypted hsm_secret l1.stop() l1.daemon.opts.update({\"encrypted-hsm\": None}) l1.daemon.start(stdin=slave_fd, wait_for_initialized=False)",
"addr = l1.rpc.newaddr()['bech32'] bitcoind.rpc.sendtoaddress(addr, 0.1) bitcoind.generate_block(1) wait_for(lambda: len(l1.rpc.listfunds()['outputs']) == 1)",
"# No separator character with pytest.raises(RpcError): l1.rpc.withdraw('pzry9x0s0muk', 2 * amount)",
"WHERE status=2')[0]['c'] == 8 # failure testing for invalid SegWit",
"10 inputs assert len(decode['vin']) == 10 # L1 will forget",
"it offline cmd_line[1] = \"encrypt\" subprocess.check_call(cmd_line) # Now we need",
"a maximum height that is to be accepted. If the",
"match=r'Cannot afford transaction'): l1.rpc.withdraw(waddr, amount * 100) out = l1.rpc.withdraw(waddr,",
"= 10000000 l1 = node_factory.get_node(random_hsm=True) bitcoind.rpc.sendtoaddress(l1.rpc.newaddr()['bech32'], amount / 10**8) bitcoind.generate_block(1)",
"off our output matching logic\") @unittest.skipIf(not EXPERIMENTAL_FEATURES, \"Tests annotations which",
"Test we can restore the same wallet with the same",
"100)}) def test_txprepare_multi(node_factory, bitcoind): amount = 10000000 l1 = node_factory.get_node(random_hsm=True)",
"match=r'not an unreleased txid'): l1.rpc.txdiscard(prep['txid']) prep = l1.rpc.txprepare([{addr: 'all'}]) decode",
"[addr] # Cannot discard twice. with pytest.raises(RpcError, match=r'not an unreleased",
"/ 10**8) bitcoind.generate_block(1) wait_for(lambda: len(l1.rpc.listfunds()['outputs']) == 10) prep = l1.rpc.txprepare(outputs=[{addr:",
"\"<PASSWORD>\" # We need to simulate a terminal to use",
"* 100), 'feerate': '2000perkw'}) l1.rpc.call('txprepare', {'destination': addr, 'satoshi': Millisatoshi(amount *",
"fee. with pytest.raises(RpcError, match=r'Cannot afford transaction'): l1.rpc.withdraw(waddr, 'all') # Add",
"########################################################################## # Let's now open a channel. The opener should",
"random memory or null txs = l1.rpc.listtransactions()['transactions'] tx = [t",
"wait_for_initialized=True) assert node_id == l1.rpc.getinfo()[\"id\"] l1.stop() # Test we can",
"transaction that gave us the funds in the # transactions",
"3 * 500 + 100000)}, {addr: Millisatoshi(amount * 3 *",
"in l1.rpc.listfunds()[\"outputs\"]][:4] withdrawal = l1.rpc.withdraw(waddr, 2 * amount, utxos=utxos) decode",
"assert decode['txid'] == prep2['txid'] # 6 inputs, 1 outputs. assert",
"l1.rpc.withdraw(waddr, 'all', minconf=0) assert l1.db_query('SELECT COUNT(*) as c FROM outputs",
"We can't use a wrong password ! cmd_line = [\"tools/hsmtool\",",
"are ordering by blockheight and txindex, so that order should",
"to l2. # lightningd uses P2SH-P2WPKH waddr = l2.rpc.newaddr('bech32')['bech32'] l1.rpc.withdraw(waddr,",
"address this time. addr = l1.rpc.newaddr(\"bech32\")['bech32'] l1.rpc.withdraw(addr, \"all\") bitcoind.generate_block(1) time.sleep(1)",
"== 1 if not chainparams['feeoutput'] else 2 # Some fees",
"7) # Array type with pytest.raises(RpcError, match=r'.* should be an",
"pytest.raises(RpcError): l1.rpc.withdraw('tb1qw508d6qejxtdg4y5r3zarvary0c5xw7kxxxxxx', 2 * amount) l1.rpc.withdraw(waddr, 2 * amount) bitcoind.generate_block(1)",
"l1.rpc.listfunds()['outputs']] == ['confirmed'] * 10) with pytest.raises(RpcError, match=r'not an unreleased",
"inputs assert len(decode['vin']) == 10 @unittest.skipIf(TEST_NETWORK != 'regtest', \"Fee outputs",
"only_one(l1.rpc.listfunds()['outputs']) assert output['address'] == addr @unittest.skipIf(not COMPAT, \"needs COMPAT=1\") def",
"around into the db to check that outputs were added",
"bitcoind, chainparams): amount = 1000000 l1 = node_factory.get_node(may_fail=True) addr =",
"from flaky import flaky # noqa: F401 from pyln.client import",
"for each output. for i in decode['vin']: assert l1.daemon.is_in_log('wallet: reserved",
"hsm_path, \"A wrong pass\"] with pytest.raises(subprocess.CalledProcessError): subprocess.check_call(cmd_line) # Decrypt it",
"the annotated types types = [o['type'] for o in txs[1]['outputs']]",
"for f in l1.rpc.listfunds()['outputs']] def test_txprepare_restart(node_factory, bitcoind, chainparams): amount =",
"l1 = node_factory.get_node(options={'allow-deprecated-apis': True}) addr = l1.rpc.newaddr()['bech32'] for i in",
"derivation.\") def test_hsmtool_secret_decryption(node_factory): l1 = node_factory.get_node() password = \"<PASSWORD>\" hsm_path",
"'confirmed' # Now make sure two of them were marked",
"l1.rpc.newaddr()['bech32'] for i in range(7): l1.fundwallet(10**8) bitcoind.generate_block(1) sync_blockheight(bitcoind, [l1]) wait_for(lambda:",
"1] and out['value'] == 10**6) # ... and it should",
"\"Tests annotations which are compiled only with experimental features\") def",
"taken assert decode['vout'][0]['value'] < Decimal(amount * 4) / 10**8 assert",
"len(decode['vin']) == 10 # L1 will forget all about it.",
"# 4 inputs, 3 outputs(include change). assert len(decode['vin']) == 4",
"l1.daemon.opts.update({\"encrypted-hsm\": None}) master_fd, slave_fd = os.openpty() l1.daemon.start(stdin=slave_fd, stderr=subprocess.STDOUT, wait_for_initialized=False) l1.daemon.wait_for_log(r'The",
"can\\'t be more than 1'): prep5 = l1.rpc.txprepare([{addr: Millisatoshi(amount *",
"- 1 assert decode['vout'][outnum1]['scriptPubKey']['type'] == 'witness_v0_keyhash' assert decode['vout'][outnum1]['scriptPubKey']['addresses'] == [addr]",
"withdrawal['txid'] # Check that correct utxos are included assert len(decode['vin'])",
"money to l2. # lightningd uses P2SH-P2WPKH waddr = l2.rpc.newaddr('bech32')['bech32']",
"And check the channel annotation on the funding output peers",
"== 'deposit' else 1 fundidx = 1 - changeidx assert(types[changeidx]",
"/ 10**8 assert decode['vout'][0]['value'] > Decimal(amount * 4) / 10**8",
"* 3 * 1000)}, {addr: 'all'}]) prep5 = l1.rpc.txprepare([{addr: Millisatoshi(amount",
"funds in the # transactions table... outputs = l1.rpc.listfunds()['outputs'] assert(len(outputs)",
"'2000perkw'}) l1.rpc.call('txprepare', {'destination': addr, 'satoshi': Millisatoshi(amount * 100)}) def test_txprepare_multi(node_factory,",
"amount / 10**8) bitcoind.rpc.sendtoaddress(l1.rpc.newaddr('p2sh-segwit')['p2sh-segwit'], amount / 10**8) bitcoind.generate_block(1) wait_for(lambda: len(l1.rpc.listfunds()['outputs'])",
"output). assert len(decode['vin']) == 4 assert len(decode['vout']) == 2 if",
"test_txprepare(node_factory, bitcoind, chainparams): amount = 1000000 l1 = node_factory.get_node(random_hsm=True) addr",
"will be correct. outnum = [i for i, o in",
"transaction # annotated as channel open and deposit. l1.connect(l2) fundingtx",
"funds to withdraw later: both bech32 and p2sh for i",
"will be taken assert decode['vout'][0]['value'] < Decimal(amount * 4) /",
"assert decode['vout'][1]['value'] == Decimal(amount * 3.5) / 10**8 assert decode['vout'][1]['scriptPubKey']['type']",
"== 2 if not chainparams['feeoutput'] else 3 # One output",
"output, so this is exact assert len(decode['vout']) == 3 if",
"1) tx = txs[0] output = tx['outputs'][idx] assert(output['type'] == 'deposit'",
"range(5): bitcoind.rpc.sendtoaddress(l1.rpc.newaddr()['bech32'], amount / 10**8) bitcoind.rpc.sendtoaddress(l1.rpc.newaddr('p2sh-segwit')['p2sh-segwit'], amount / 10**8) bitcoind.generate_block(1)",
"Test that we eventually fuzz nLockTime for withdrawal transactions. Marked",
"should be an amount in satoshis or all, not .*'):",
"version 0 (per BIP141) with pytest.raises(RpcError): l1.rpc.withdraw('BC1QR508D6QEJXTDG4Y5R3ZARVARYV98GJ9P', 2 * amount)",
"l1.rpc.withdraw(addr, 10**3)[\"tx\"] nlocktime = node_factory.bitcoind.rpc.decoderawtransaction(tx)[\"locktime\"] tip = node_factory.bitcoind.rpc.getblockcount() assert nlocktime",
"== 1) tx = txs[0] output = tx['outputs'][idx] assert(output['type'] ==",
"conversion with pytest.raises(RpcError): l1.rpc.withdraw('tb1qrp33g0q5c5txsp9arysrx4k6zdkfs4nce4xj0gdcccefvpysxf3pjxtptv', 2 * amount) # Should have",
"that order should be ok) txs = l1.rpc.listtransactions()['transactions'] assert(len(txs) ==",
"prep4 = l1.rpc.txprepare([{addr: 'all'}]) decode = bitcoind.rpc.decoderawtransaction(prep4['unsigned_tx']) assert decode['txid'] ==",
"l1.rpc.txprepare([{addr: Millisatoshi(amount * 3.5 * 1000)}], utxos=utxos) decode = bitcoind.rpc.decoderawtransaction(prep5['unsigned_tx'])",
"(making sure we collect multiple inputs) with pytest.raises(RpcError): l1.rpc.withdraw('not an",
"The opener should get the funding transaction # annotated as",
"== 0 # This should fail, can't even afford fee.",
"[addr, Millisatoshi(amount * 100), None, 1]) l1.rpc.call('txprepare', [addr, Millisatoshi(amount *",
"this is exact assert len(decode['vout']) == 3 if chainparams['feeoutput'] else",
"'minconf': 1}) l1.rpc.call('txprepare', {'destination': addr, 'satoshi': Millisatoshi(amount * 100), 'feerate':",
"inputs assert len(decode['vin']) == 10 # L1 will forget all",
"txs = l1.rpc.listtransactions()['transactions'] assert(len(txs) == 2 and txs[1]['hash'] == fundingtx['txid'])",
"out = l1.rpc.withdraw(waddr, 2 * amount) # Make sure bitcoind",
"== 10) prep = l1.rpc.txprepare([{addr: Millisatoshi(amount * 3 * 1000)}])",
"be taken assert decode['vout'][0]['value'] < Decimal(amount * 10) / 10**8",
"should have 2 transactions, the second one should be the",
"only in regtest\") def test_withdraw(node_factory, bitcoind): amount = 1000000 #",
"decode = bitcoind.rpc.decoderawtransaction(prep['unsigned_tx']) assert decode['txid'] == prep['txid'] # 4 inputs,",
"only with experimental features\") def test_transaction_annotations(node_factory, bitcoind): l1, l2, l3",
"* 3 * 1000)}]) out = l1.rpc.txsend(prep['txid']) # Cannot discard",
"l2 = node_factory.get_nodes(2) l1.fundwallet(10**6) l1.connect(l2) txid = l1.rpc.fundchannel(l2.info['id'], 10**5)['txid'] #",
"t in txs if t['hash'] == txid][0] assert tx['blockheight'] ==",
"FROM outputs WHERE status=0')[0]['c'] == 1 l1.rpc.withdraw(waddr, 'all', minconf=0) assert",
"for i in decode['vin']: assert l1.daemon.is_in_log('wallet: reserved output {}/{} reset",
"amount) # Should have 6 outputs available. assert l1.db_query('SELECT COUNT(*)",
"get any funds from previous runs. l1 = node_factory.get_node(random_hsm=True) addr",
"exceeded with pytest.raises(RpcError): l1.rpc.withdraw('an84characterslonghumanreadablepartthatcontainsthenumber1andtheexcludedcharactersbio1569pvx', 2 * amount) # No separator",
"explicitly \"\"\" # Previous runs with same bitcoind can leave",
"discard['txid'] == prep['txid'] assert discard['unsigned_tx'] == prep['unsigned_tx'] prep3 = l1.rpc.txprepare([{addr:",
"'witness_v0_keyhash' assert decode['vout'][1]['scriptPubKey']['addresses'] == [addr] # Discard prep4 and get",
"2 * amount) l1.rpc.withdraw(waddr, 2 * amount) bitcoind.generate_block(1) # Now",
"should fail, can't even afford fee. with pytest.raises(RpcError, match=r'Cannot afford",
"Add some funds to withdraw for i in range(10): l1.bitcoin.rpc.sendtoaddress(addr,",
"10 # L1 will forget all about it. l1.restart() #",
"be taken assert decode['vout'][0]['value'] < Decimal(amount * 4) / 10**8",
"1000000 l1 = node_factory.get_node(may_fail=True) addr = chainparams['example_addr'] # Add some",
"def test_txprepare_restart(node_factory, bitcoind, chainparams): amount = 1000000 l1 = node_factory.get_node(may_fail=True)",
"node_id = l1.rpc.getinfo()[\"id\"] l1.stop() # We can't use a wrong",
"== [addr] l1.rpc.txdiscard(prep4['txid']) # Try passing in a utxo set",
"all funds again l1.rpc.txdiscard(prep5['txid']) with pytest.raises(RpcError, match=r'this destination wants all",
"4 if chainparams['feeoutput'] else 3 # One output will be",
"were marked as spent assert l1.db_query('SELECT COUNT(*) as c FROM",
"== 'witness_v0_keyhash' assert decode['vout'][0]['scriptPubKey']['addresses'] == [addr] # Cannot discard twice.",
"l1.rpc.txdiscard(prep['txid']) assert discard['txid'] == prep['txid'] assert discard['unsigned_tx'] == prep['unsigned_tx'] prep3",
"l1.rpc.txprepare([{addr: Millisatoshi(amount * 3 * 500 + 100000)}, {addr: Millisatoshi(amount",
"need to pass the encrypted-hsm startup option l1.stop() with pytest.raises(subprocess.CalledProcessError,",
"tx should have same txid decode = bitcoind.rpc.decoderawtransaction(out['tx']) assert decode['txid']",
"decode['txid'] == prep['txid'] bitcoind.generate_block(1) # Change output should appear. if",
"* 100), 'normal']) l1.rpc.call('txprepare', [addr, Millisatoshi(amount * 100), None, 1])",
"3 if chainparams['feeoutput'] else 2 assert decode['vout'][1]['value'] == Decimal(amount *",
"* amount, utxos=utxos) decode = bitcoind.rpc.decoderawtransaction(withdrawal['tx']) assert decode['txid'] == withdrawal['txid']",
"from 0 to 100 with a 10% probability. \"\"\" l1",
"we eventually fuzz nLockTime for withdrawal transactions. Marked flaky \"just",
"pytest.raises(RpcError): l1.rpc.withdraw(' 1nwldj5', 2 * amount) # overall max length",
"c FROM outputs WHERE status=2')[0]['c'] == 6 # Simple test",
"probability. \"\"\" l1 = node_factory.get_node(1) l1.fundwallet(10**8) for i in range(100):",
"== prep2['txid'] # 6 inputs, 1 outputs. assert len(decode['vin']) ==",
"scid = peers[0]['channels'][0]['short_channel_id'] assert(txs[1]['outputs'][fundidx]['channel'] == scid) @unittest.skipIf(VALGRIND, \"It does not",
"forget all about it. l1.restart() # It goes backwards in",
"to withdraw later for i in range(10): l1.bitcoin.rpc.sendtoaddress(addr, amount /",
"assert(types[changeidx] == 'deposit' and types[fundidx] == 'channel_funding') # And check",
"of confirmations we wrap around and just select everything. The",
"= bitcoind.rpc.decoderawtransaction(prep['unsigned_tx']) assert decode['txid'] == prep['txid'] # 4 inputs, 2",
"0 else: assert False # Those spent outputs are gone,",
"enumerate(tx['outputs']): if i == idx: continue if 'type' in o:",
"value FROM outputs WHERE status=0;') assert only_one(outputs)['value'] == 10000000 #",
"bitcoind, chainparams): amount = 1000000 l1 = node_factory.get_node(random_hsm=True) addr =",
"with pytest.raises(RpcError, match=r'Cannot afford transaction'): l1.rpc.withdraw(waddr, 'all') # Add some",
"l1.rpc.listtransactions()['transactions'] assert(len(txs) == 2 and txs[1]['hash'] == fundingtx['txid']) # Check",
"match what was paid to. output = only_one(l1.rpc.listfunds()['outputs']) assert output['address']",
"transaction'): l1.rpc.withdraw(waddr, amount * 100) out = l1.rpc.withdraw(waddr, 2 *",
"pytest.raises(RpcError, match=r'Could not parse destination address.*'): l1.rpc.call('txprepare', [Millisatoshi(amount * 100),",
"< tip: return else: raise Exception(\"No transaction with fuzzed nLockTime",
"1]) l1.rpc.call('txprepare', [addr, Millisatoshi(amount * 100)]) # Object type with",
"should now have a transaction that gave us the funds",
"Cannot discard after send! with pytest.raises(RpcError, match=r'not an unreleased txid'):",
"10) # It should have logged this for each output.",
"bitcoind.rpc.decoderawtransaction(prep3['unsigned_tx']) assert decode['txid'] == prep3['txid'] # 4 inputs, 1 outputs.",
"* amount) bitcoind.generate_block(1) # Make sure l2 received the withdrawal.",
"l1.daemon.wait_for_log(\"Server started with public key\") id = l1.rpc.getinfo()[\"id\"] l1.stop() #",
"satoshi=10000, feerate='normal', minconf=9999999) def test_addfunds_from_block(node_factory, bitcoind): \"\"\"Send funds to the",
"just in case there was a reorg. Wait. wait_for(lambda: [o['status']",
"be the funding tx # (we are ordering by blockheight",
"def test_addfunds_from_block(node_factory, bitcoind): \"\"\"Send funds to the daemon without telling",
"I cancel the first one, I can get those first",
"decrypt if encrypted with hsmtool cmd_line[1] = \"decrypt\" subprocess.check_call(cmd_line) l1.daemon.opts.pop(\"encrypted-hsm\")",
"== Decimal(amount * 3) / 10**8: changenum = 0 else:",
"with pytest.raises(RpcError, match=r'Need set \\'satoshi\\' field.'): l1.rpc.call('txprepare', [addr]) with pytest.raises(RpcError,",
"/ 10**8 assert decode['vout'][1]['scriptPubKey']['type'] == 'witness_v0_keyhash' assert decode['vout'][1]['scriptPubKey']['addresses'] == [addr]",
"use termios in `lightningd`. master_fd, slave_fd = os.openpty() # Encrypt",
"# and crashed the daemon for accessing random memory or",
"3 * 500 - 100000)}]) decode = bitcoind.rpc.decoderawtransaction(prep5['unsigned_tx']) assert decode['txid']",
"it. l1.restart() # It goes backwards in blockchain just in",
"tx = [t for t in txs if t['hash'] ==",
"later: both bech32 and p2sh for i in range(5): bitcoind.rpc.sendtoaddress(l1.rpc.newaddr()['bech32'],",
"10**8) bitcoind.rpc.sendtoaddress(l1.rpc.newaddr('p2sh-segwit')['p2sh-segwit'], amount / 10**8) bitcoind.generate_block(1) wait_for(lambda: len(l1.rpc.listfunds()['outputs']) == 10)",
"assert decode['vout'][1]['scriptPubKey']['type'] == 'witness_v0_keyhash' assert decode['vout'][1]['scriptPubKey']['addresses'] == [addr] # Discard",
"outputs[0]['status'] == 'confirmed') out = outputs[0] idx = out['output'] assert(idx",
"funds! l1 = node_factory.get_node(random_hsm=True) addr = l1.rpc.newaddr()['bech32'] bitcoind.rpc.sendtoaddress(addr, 0.1) bitcoind.generate_block(1)",
"bitcoind.generate_block(1) time.sleep(1) # The address we detect must match what",
"2 * amount) # Mixed case with pytest.raises(RpcError): l1.rpc.withdraw('tb1qrp33g0q5c5txsp9arysrx4k6zdkfs4nce4xj0gdcccefvpysxf3q0sL5k7', 2",
"[o['status'] for o in l1.rpc.listfunds()['outputs']] == ['confirmed'] * 10) #",
"test_fundchannel_listtransaction(node_factory, bitcoind): l1, l2 = node_factory.get_nodes(2) l1.fundwallet(10**6) l1.connect(l2) txid =",
"even afford fee. with pytest.raises(RpcError, match=r'Cannot afford transaction'): l1.rpc.withdraw(waddr, 'all')",
"== ['confirmed'] * 10) prep = l1.rpc.txprepare([{addr: 'all'}]) decode =",
"Wait. wait_for(lambda: [o['status'] for o in l1.rpc.listfunds()['outputs']] == ['confirmed'] *",
"and txs[1]['hash'] == fundingtx['txid']) # Check the annotated types types",
"l1.fundwallet(10**6) # We should now have a transaction that gave",
"a 'listtransactions' on a yet unconfirmed channel def test_fundchannel_listtransaction(node_factory, bitcoind):",
"and out['value'] == 10**6) # ... and it should have",
"0 if types[0] == 'deposit' else 1 fundidx = 1",
"outputs = l2.db_query('SELECT value FROM outputs WHERE status=0;') assert only_one(outputs)['value']",
"pass\"] with pytest.raises(subprocess.CalledProcessError): subprocess.check_call(cmd_line) # Decrypt it with hsmtool cmd_line[3]",
"== 10 # L1 will forget all about it. l1.restart()",
"status=0')[0]['c'] == 6 # Test withdrawal to self. l1.rpc.withdraw(l1.rpc.newaddr('bech32')['bech32'], 'all',",
"decode['txid'] == prep5['txid'] # 4 inputs, 3 outputs(include change). assert",
"encrypted') os.write(master_fd, password.encode(\"utf-8\")) l1.daemon.wait_for_log(\"Server started with public key\") assert id",
"seed l1.stop() l1.daemon.opts.update({\"encrypted-hsm\": None}) l1.daemon.start(stdin=slave_fd, wait_for_initialized=False) l1.daemon.wait_for_log(r'The hsm_secret is encrypted')",
"old-style: txprepare {destination} {satoshi} {feerate} {minconf} \"\"\" amount = 10**4",
"used to compute a maximum height that is to be",
"output .* txid {} CONFIRMED'. format(withdraw[\"txid\"])) decoded = bitcoind.rpc.decoderawtransaction(withdraw[\"tx\"]) tip",
"Now make sure additional two of them were marked as",
"* amount) with pytest.raises(RpcError): l1.rpc.withdraw('tb1prp33g0q5c5txsp9arysrx4k6zdkfs4nce4xj0gdcccefvpysxf3qsm03tq', 2 * amount) with pytest.raises(RpcError):",
"(3 if we have a fee output). assert len(decode['vin']) ==",
"# May fail when started without key password = \"<PASSWORD>\"",
"10**8 assert decode['vout'][1]['scriptPubKey']['type'] == 'witness_v0_keyhash' assert decode['vout'][1]['scriptPubKey']['addresses'] == [addr] #",
"[] for i in range(9): outputs.append({l1.rpc.newaddr()['bech32']: Millisatoshi(amount * 100)}) prep",
"send! with pytest.raises(RpcError, match=r'not an unreleased txid'): l1.rpc.txdiscard(prep['txid']) wait_for(lambda: prep['txid']",
"confirmed bitcoind.generate_block(3) sync_blockheight(bitcoind, [l1, l2]) outputs = l1.rpc.listfunds()['outputs'] assert(len(outputs) ==",
"can't even afford fee. with pytest.raises(RpcError, match=r'Cannot afford transaction'): l1.rpc.withdraw(waddr,",
"prep3['txid'] # 4 inputs, 1 outputs. assert len(decode['vin']) == 4",
"be confirmed) for o in l1.rpc.listfunds()['outputs']: assert o['status'] == 'confirmed'",
"decoded[\"locktime\"] < tip: return else: raise Exception(\"No transaction with fuzzed",
"3.5 * 1000)}], utxos=utxos) decode = bitcoind.rpc.decoderawtransaction(prep5['unsigned_tx']) assert decode['txid'] ==",
"funding output peers = l1.rpc.listpeers()['peers'] assert(len(peers) == 1 and len(peers[0]['channels'])",
"= outputs[0] idx = out['output'] assert(idx in [0, 1] and",
"'witness_v0_keyhash' assert decode['vout'][outnum2]['scriptPubKey']['addresses'] == [addr] assert decode['vout'][changenum]['scriptPubKey']['type'] == 'witness_v0_keyhash' def",
"# Now prepare one with no change. prep2 = l1.rpc.txprepare([{addr:",
"FROM outputs WHERE status=0;') assert only_one(outputs)['value'] == 2 * amount",
"logic\") @unittest.skipIf(not EXPERIMENTAL_FEATURES, \"Tests annotations which are compiled only with",
"for withdrawal to P2WPKH # Address from: https://bc-2.jp/tools/bech32demo/index.html waddr =",
"decode['vout'][changenum]['scriptPubKey']['addresses'][0] in [f['address'] for f in l1.rpc.listfunds()['outputs']] def test_txprepare_restart(node_factory, bitcoind,",
"id = l1.rpc.getinfo()[\"id\"] l1.stop() # Test we cannot start the",
"bitcoind.generate_block(3) sync_blockheight(bitcoind, [l1, l2]) outputs = l1.rpc.listfunds()['outputs'] assert(len(outputs) == 1",
"decode['vout'][0]['scriptPubKey']['addresses'] == [addr] # Cannot discard twice. with pytest.raises(RpcError, match=r'not",
"with pytest.raises(RpcError): l1.rpc.withdraw('BC1QR508D6QEJXTDG4Y5R3ZARVARYV98GJ9P', 2 * amount) # Mixed case with",
"6 # Test withdrawal to self. l1.rpc.withdraw(l1.rpc.newaddr('bech32')['bech32'], 'all', minconf=0) bitcoind.generate_block(1)",
"1000000 l1 = node_factory.get_node(random_hsm=True) addr = chainparams['example_addr'] # Add some",
"o in enumerate(tx['outputs']): if i == idx: continue if 'type'",
"amount = 1000000 # Don't get any funds from previous",
"Non-zero padding in 8-to-5 conversion with pytest.raises(RpcError): l1.rpc.withdraw('tb1qrp33g0q5c5txsp9arysrx4k6zdkfs4nce4xj0gdcccefvpysxf3pjxtptv', 2 *",
"[u for u in unspent if u['txid'] == out['txid']] assert(withdrawal[0]['amount']",
"10 - len(decode['vin']) + 1) # Change address should appear",
"[o['status'] for o in l1.rpc.listfunds()['outputs']] == ['confirmed'] * 10) prep",
"l2 received the withdrawal. wait_for(lambda: len(l2.rpc.listfunds()['outputs']) == 1) outputs =",
"addresses valid only in regtest\") def test_withdraw(node_factory, bitcoind): amount =",
"0 def test_withdraw_nlocktime(node_factory): \"\"\" Test that we don't set the",
"started with public key\") node_id = l1.rpc.getinfo()[\"id\"] l1.stop() # We",
"password.encode(\"utf-8\")) l1.daemon.wait_for_log(\"Server started with public key\") node_id = l1.rpc.getinfo()[\"id\"] l1.stop()",
"RpcError, Millisatoshi from utils import ( only_one, wait_for, sync_blockheight, EXPERIMENTAL_FEATURES,",
"type with pytest.raises(RpcError, match=r'Need set \\'outputs\\' field.'): l1.rpc.call('txprepare', {'destination': addr,",
"should have same txid decode = bitcoind.rpc.decoderawtransaction(out['tx']) assert decode['txid'] ==",
"utxos: assert utxo in vins def test_minconf_withdraw(node_factory, bitcoind): \"\"\"Issue 2518:",
"o in l1.rpc.listfunds()['outputs']] == ['confirmed'] * 10) # It should",
"amount) # Mixed case with pytest.raises(RpcError): l1.rpc.withdraw('tb1qrp33g0q5c5txsp9arysrx4k6zdkfs4nce4xj0gdcccefvpysxf3q0sL5k7', 2 * amount)",
"[\"tools/hsmtool\", \"decrypt\", hsm_path, \"A wrong pass\"] with pytest.raises(subprocess.CalledProcessError): subprocess.check_call(cmd_line) #",
"decode['txid'] == prep5['txid'] # Check that correct utxos are included",
"bitcoind.rpc.decoderawtransaction(prep5['unsigned_tx']) assert decode['txid'] == prep5['txid'] # 4 inputs, 3 outputs(include",
"amount') with pytest.raises(RpcError): l1.rpc.withdraw(waddr, -amount) with pytest.raises(RpcError, match=r'Cannot afford transaction'):",
"pytest.raises(subprocess.CalledProcessError, match=r'returned non-zero exit status 1'): subprocess.check_call(l1.daemon.cmd_line) l1.daemon.opts.update({\"encrypted-hsm\": None}) master_fd,",
"node_factory.get_node() password = \"<PASSWORD>\" hsm_path = os.path.join(l1.daemon.lightning_dir, TEST_NETWORK, \"hsm_secret\") #",
"in decode['vin']] for utxo in utxos: assert utxo in vins",
"outputs[0] idx = out['output'] assert(idx in [0, 1] and out['value']",
"== outnum: assert o['scriptPubKey']['type'] == 'witness_v0_keyhash' assert o['scriptPubKey']['addresses'] == [addr]",
"first one, I can get those first 4 outputs. discard",
"decode['txid'] == prep3['txid'] # 4 inputs, 1 outputs. assert len(decode['vin'])",
"utxo in l1.rpc.listfunds()[\"outputs\"]][:4] prep5 = l1.rpc.txprepare([{addr: Millisatoshi(amount * 3.5 *",
"assert decode['vout'][0]['scriptPubKey']['type'] == 'witness_v0_keyhash' assert decode['vout'][0]['scriptPubKey']['addresses'] == [addr] l1.rpc.txdiscard(prep4['txid']) #",
"in the # transactions table... outputs = l1.rpc.listfunds()['outputs'] assert(len(outputs) ==",
"for utxo in utxos: assert utxo in vins def test_minconf_withdraw(node_factory,",
"l1.rpc.listfunds()['outputs']] == ['confirmed'] * 10) # It should have logged",
"1000000 # Don't get any funds from previous runs. l1",
"* 100), None, 1]) l1.rpc.call('txprepare', [addr, Millisatoshi(amount * 100)]) #",
"decode = bitcoind.rpc.decoderawtransaction(prep3['unsigned_tx']) assert decode['txid'] == prep3['txid'] # 4 inputs,",
"def test_deprecated_txprepare(node_factory, bitcoind): \"\"\"Test the deprecated old-style: txprepare {destination} {satoshi}",
"Test we can encrypt it offline cmd_line[1] = \"encrypt\" subprocess.check_call(cmd_line)",
"witness version 0 (per BIP141) with pytest.raises(RpcError): l1.rpc.withdraw('BC1QR508D6QEJXTDG4Y5R3ZARVARYV98GJ9P', 2 *",
"be change, and have no annotations types = [] for",
"addr = chainparams['example_addr'] # Add some funds to withdraw later:",
"l1 = node_factory.get_node(random_hsm=True) addr = l1.rpc.newaddr()['bech32'] bitcoind.rpc.sendtoaddress(addr, 0.1) bitcoind.generate_block(1) wait_for(lambda:",
"@unittest.skipIf(VALGRIND, \"A big loop is used to check fuzz.\") def",
"2 # Some fees will be paid. assert decode['vout'][0]['value'] <",
"minconf=9999999) def test_addfunds_from_block(node_factory, bitcoind): \"\"\"Send funds to the daemon without",
"# Add some funds to withdraw for i in range(10):",
"# Address from: https://bc-2.jp/tools/bech32demo/index.html waddr = 'bcrt1qrp33g0q5c5txsp9arysrx4k6zdkfs4nce4xj0gdcccefvpysxf3qzf4jry' with pytest.raises(RpcError): l1.rpc.withdraw('xx1qrp33g0q5c5txsp9arysrx4k6zdkfs4nce4xj0gdcccefvpysxf3q0sl5k7',",
"about SQL Accessing a null column # and crashed the",
"# One output will be correct. for i in range(3",
"bitcoind): \"\"\"Issue 2518: ensure that ridiculous confirmation levels don't overflow",
"* amount) with pytest.raises(RpcError): l1.rpc.withdraw('tb1qw508d6qejxtdg4y5r3zarvary0c5xw7kxxxxxx', 2 * amount) l1.rpc.withdraw(waddr, 2",
"= node_factory.get_node(options={'allow-deprecated-apis': True}) addr = l1.rpc.newaddr()['bech32'] for i in range(7):",
"2 and txs[1]['hash'] == fundingtx['txid']) # Check the annotated types",
"Millisatoshi(amount * 100)]) # Object type with pytest.raises(RpcError, match=r'Need set",
"telling it explicitly \"\"\" # Previous runs with same bitcoind",
"invalid SegWit addresses, from BIP173 # HRP character out of",
"1 - changeidx assert(types[changeidx] == 'deposit' and types[fundidx] == 'channel_funding')",
"# Invalid program length for witness version 0 (per BIP141)",
"I can get those first 4 outputs. discard = l1.rpc.txdiscard(prep['txid'])",
"i in range(7): l1.fundwallet(10**8) bitcoind.generate_block(1) sync_blockheight(bitcoind, [l1]) wait_for(lambda: len(l1.rpc.listfunds()['outputs']) ==",
"with pytest.raises(RpcError, match=r'not an unreleased txid'): l1.rpc.txdiscard(prep['txid']) # Discard everything,",
"It should also match the funding txid: assert(outputs[0]['txid'] == fundingtx['txid'])",
"l1.rpc.txprepare([{addr: 'all'}]) decode = bitcoind.rpc.decoderawtransaction(prep2['unsigned_tx']) assert decode['txid'] == prep2['txid'] #",
"os.write(master_fd, password.encode(\"utf-8\")) l1.daemon.wait_for_log(\"Server started with public key\") node_id = l1.rpc.getinfo()[\"id\"]",
"simply kill it. l1.restart(clean=False) # It goes backwards in blockchain",
"= l1.rpc.listpeers()['peers'] assert(len(peers) == 1 and len(peers[0]['channels']) == 1) scid",
"it without password l1.daemon.opts.pop(\"encrypted-hsm\") l1.daemon.start(stdin=slave_fd, wait_for_initialized=True) assert node_id == l1.rpc.getinfo()[\"id\"]",
"== 10) with pytest.raises(RpcError): l1.rpc.withdraw(destination=addr, satoshi=10000, feerate='normal', minconf=9999999) def test_addfunds_from_block(node_factory,",
"and types[fundidx] == 'channel_funding') # And check the channel annotation",
"def test_txsend(node_factory, bitcoind, chainparams): amount = 1000000 l1 = node_factory.get_node(random_hsm=True)",
"txid'): l1.rpc.txdiscard(prep['txid']) wait_for(lambda: prep['txid'] in bitcoind.rpc.getrawmempool()) # Signed tx should",
"1'): subprocess.check_call(l1.daemon.cmd_line) l1.daemon.opts.update({\"encrypted-hsm\": None}) master_fd, slave_fd = os.openpty() l1.daemon.start(stdin=slave_fd, stderr=subprocess.STDOUT,",
"WHERE status=2')[0]['c'] == 2 # Now send some money to",
"* amount) # Invalid witness version with pytest.raises(RpcError): l1.rpc.withdraw('BC13W508D6QEJXTDG4Y5R3ZARVARY0C5XW7KN40WF2', 2",
"l1.rpc.txprepare(outputs=outputs) l1.rpc.txdiscard(prep['txid']) def test_txprepare(node_factory, bitcoind, chainparams): amount = 1000000 l1",
"\"just in case\" as we fuzz from 0 to 100",
"wait_for(lambda: len(l1.rpc.listfunds()['outputs']) == 10) prep = l1.rpc.txprepare([{addr: Millisatoshi(amount * 3",
"fix is to clamp the maxheight parameter to a positive",
"open and deposit. l1.connect(l2) fundingtx = l1.rpc.fundchannel(l2.info['id'], 10**5) # We",
"assert node_id == l1.rpc.getinfo()[\"id\"] l1.stop() # And finally test that",
"can restore the same wallet with the same password l1.daemon.start(stdin=slave_fd,",
"l1.rpc.txdiscard(prep['txid']) def test_txprepare(node_factory, bitcoind, chainparams): amount = 1000000 l1 =",
"- len(decode['vin']) + 1) # Change address should appear in",
"decode = bitcoind.rpc.decoderawtransaction(prep5['unsigned_tx']) assert decode['txid'] == prep5['txid'] # 4 inputs,",
"'type' in o: types.append(o['type']) else: types.append(None) assert(set([None]) == set(types)) ##########################################################################",
"# 10 inputs, 1 outputs. assert len(decode['vin']) == 10 assert",
"# L1 will forget all about it. l1.restart() # It",
"with prompt and key derivation.\") def test_hsmtool_secret_decryption(node_factory): l1 = node_factory.get_node()",
"# Don't get any funds from previous runs. l1 =",
"4 vins = [\"{}:{}\".format(v['txid'], v['vout']) for v in decode['vin']] for",
"Decimal(amount * 3) / 10**8: changenum = 1 elif decode['vout'][1]['value']",
"types types = [o['type'] for o in txs[1]['outputs']] changeidx =",
"* amount) # Non-zero padding in 8-to-5 conversion with pytest.raises(RpcError):",
"assert decode['txid'] == prep['txid'] bitcoind.generate_block(1) # Change output should appear.",
"is encrypted') os.write(master_fd, password.encode(\"utf-8\")) l1.daemon.wait_for_log(\"Server started with public key\") node_id",
"public key\") assert node_id == l1.rpc.getinfo()[\"id\"] l1.stop() # And finally",
"simulate a terminal to use termios in `lightningd`. master_fd, slave_fd",
"match=r'.* should be an amount in satoshis or all, not",
"Now make sure two of them were marked as spent",
"10**8) bitcoind.generate_block(1) wait_for(lambda: len(l1.rpc.listfunds()['outputs']) == 1) outputs = [] for",
"l1.bitcoin.rpc.getnewaddress() # Now attempt to withdraw some (making sure we",
"len(l2.rpc.listfunds()['outputs']) == 1) outputs = l2.db_query('SELECT value FROM outputs WHERE",
"also decrypt if encrypted with hsmtool cmd_line[1] = \"decrypt\" subprocess.check_call(cmd_line)",
"and nlocktime <= tip @flaky @unittest.skipIf(VALGRIND, \"A big loop is",
"# It should have logged this for each output. for",
"later for i in range(10): l1.bitcoin.rpc.sendtoaddress(addr, amount / 10**8 +",
"field.'): l1.rpc.call('txprepare', [addr]) with pytest.raises(RpcError, match=r'Could not parse destination address.*'):",
"separator character with pytest.raises(RpcError): l1.rpc.withdraw('pzry9x0s0muk', 2 * amount) # Empty",
"And finally test that we can also decrypt if encrypted",
"Invalid program length for witness version 0 (per BIP141) with",
"in l1.rpc.listfunds()['outputs']] == ['confirmed'] * 10) prep = l1.rpc.txprepare([{addr: 'all'}])",
"if types[0] == 'deposit' else 1 fundidx = 1 -",
"l1.rpc.withdraw(waddr, 'not an amount') with pytest.raises(RpcError): l1.rpc.withdraw(waddr, -amount) with pytest.raises(RpcError,",
"and have no annotations types = [] for i, o",
"stderr=subprocess.STDOUT, wait_for_initialized=False) l1.daemon.wait_for_log(r'The hsm_secret is encrypted') os.write(master_fd, password[2:].encode(\"utf-8\")) assert(l1.daemon.proc.wait() ==",
"Decimal('0.01499900'): outnum2 = i - 1 else: changenum = i",
"wrap around and just select everything. The fix is to",
"send some money to l2. # lightningd uses P2SH-P2WPKH waddr",
"The count of outputs can\\'t be more than 1'): prep5",
"marked as spent assert l1.db_query('SELECT COUNT(*) as c FROM outputs",
"work if we simply kill it. l1.restart(clean=False) # It goes",
"== fundingtx['txid']) # Check the annotated types types = [o['type']",
"* 500 + 100000)}, {addr: Millisatoshi(amount * 3 * 500",
"collect multiple inputs) with pytest.raises(RpcError): l1.rpc.withdraw('not an address', amount) with",
"length exceeded with pytest.raises(RpcError): l1.rpc.withdraw('an84characterslonghumanreadablepartthatcontainsthenumber1andtheexcludedcharactersbio1569pvx', 2 * amount) # No",
"COMPAT, VALGRIND ) import os import pytest import subprocess import",
"/ 10**8 + 0.01) bitcoind.generate_block(1) wait_for(lambda: len(l1.rpc.listfunds()['outputs']) == 10) #",
"prepare one with no change. prep2 = l1.rpc.txprepare([{addr: 'all'}]) decode",
"o in l1.rpc.listfunds()['outputs']: assert o['status'] == 'confirmed' # Now make",
"also work if we simply kill it. l1.restart(clean=False) # It",
"address', amount) with pytest.raises(RpcError): l1.rpc.withdraw(waddr, 'not an amount') with pytest.raises(RpcError):",
"confirmation levels don't overflow The number of confirmations is used",
"sure we collect multiple inputs) with pytest.raises(RpcError): l1.rpc.withdraw('not an address',",
"def test_fundchannel_listtransaction(node_factory, bitcoind): l1, l2 = node_factory.get_nodes(2) l1.fundwallet(10**6) l1.connect(l2) txid",
"with pytest.raises(RpcError): l1.rpc.withdraw('tb1qrp33g0q5c5txsp9arysrx4k6zdkfs4nce4xj0gdcccefvpysxf3pjxtptv', 2 * amount) # Should have 6",
"one, I can get those first 4 outputs. discard =",
"l1.rpc.listpeers()['peers'] assert(len(peers) == 1 and len(peers[0]['channels']) == 1) scid =",
"parameter to a positive small number. \"\"\" amount = 1000000",
"correct. outnum = [i for i, o in enumerate(decode['vout']) if",
"assert len(decode['vin']) == 10 @unittest.skipIf(TEST_NETWORK != 'regtest', \"Fee outputs throw",
"big loop is used to check fuzz.\") def test_withdraw_nlocktime_fuzz(node_factory, bitcoind):",
"100) out = l1.rpc.withdraw(waddr, 2 * amount) # Make sure",
"test_withdraw_nlocktime_fuzz(node_factory, bitcoind): \"\"\" Test that we eventually fuzz nLockTime for",
"10 inputs assert len(decode['vin']) == 10 # This will also",
"does a 'listtransactions' on a yet unconfirmed channel def test_fundchannel_listtransaction(node_factory,",
"This will also work if we simply kill it. l1.restart(clean=False)",
"# next call warned about SQL Accessing a null column",
"Mixed case with pytest.raises(RpcError): l1.rpc.withdraw('tb1qrp33g0q5c5txsp9arysrx4k6zdkfs4nce4xj0gdcccefvpysxf3q0sL5k7', 2 * amount) # Non-zero",
"# 4 inputs, 2 outputs (3 if we have a",
"[o['status'] for o in l1.rpc.listfunds()['outputs']] == ['confirmed'] * 10) with",
"now open a channel. The opener should get the funding",
"with pytest.raises(subprocess.CalledProcessError, match=r'returned non-zero exit status 1'): subprocess.check_call(l1.daemon.cmd_line) # Test",
"2 * amount) with pytest.raises(RpcError): l1.rpc.withdraw('tb1prp33g0q5c5txsp9arysrx4k6zdkfs4nce4xj0gdcccefvpysxf3qsm03tq', 2 * amount) with",
"Millisatoshi(amount * 3 * 1000)}, {addr: 'all'}]) prep5 = l1.rpc.txprepare([{addr:",
"len(l1.rpc.listfunds()['outputs']) == 10) prep = l1.rpc.txprepare([{addr: Millisatoshi(amount * 3 *",
"check fuzz.\") def test_withdraw_nlocktime_fuzz(node_factory, bitcoind): \"\"\" Test that we eventually",
"l1.rpc.call('txprepare', [addr, Millisatoshi(amount * 100), 'normal']) l1.rpc.call('txprepare', [addr, Millisatoshi(amount *",
"noqa: F401,F403 from fixtures import TEST_NETWORK from flaky import flaky",
"10) prep = l1.rpc.txprepare([{addr: Millisatoshi(amount * 3 * 1000)}]) out",
"* amount) # Mixed case with pytest.raises(RpcError): l1.rpc.withdraw('tb1qrp33g0q5c5txsp9arysrx4k6zdkfs4nce4xj0gdcccefvpysxf3q0sL5k7', 2 *",
"we cannot start the same wallet without specifying --encrypted-hsm l1.daemon.opts.pop(\"encrypted-hsm\")",
"and crashed the daemon for accessing random memory or null",
"money to a P2WPKH address this time. addr = l1.rpc.newaddr(\"bech32\")['bech32']",
"== 'deposit' and types[fundidx] == 'channel_funding') # And check the",
"addr, 'feerate': 'slow'}) with pytest.raises(RpcError, match=r'Need set \\'outputs\\' field.'): l1.rpc.call('txprepare',",
"waddr = l1.bitcoin.rpc.getnewaddress() # Now attempt to withdraw some (making",
"'deposit' and types[fundidx] == 'channel_funding') # And check the channel",
"crashed the daemon for accessing random memory or null txs",
"and all other output should be change, and have no",
"bitcoind.generate_block(1) sync_blockheight(bitcoind, [l1]) wait_for(lambda: len(l1.rpc.listfunds()['outputs']) == 7) # Array type",
"all, not .*'): l1.rpc.call('txprepare', [addr, 'slow']) with pytest.raises(RpcError, match=r'Need set",
"we should now spend all inputs. l1.rpc.txdiscard(prep2['txid']) l1.rpc.txdiscard(prep3['txid']) prep4 =",
"changenum = i - 1 assert decode['vout'][outnum1]['scriptPubKey']['type'] == 'witness_v0_keyhash' assert",
"Reach around into the db to check that outputs were",
"Marked flaky \"just in case\" as we fuzz from 0",
"prep['txid'] bitcoind.generate_block(1) # Change output should appear. if decode['vout'][0]['value'] ==",
"l1.restart(clean=False) # It goes backwards in blockchain just in case",
"open a channel. The opener should get the funding transaction",
"== prep['unsigned_tx'] prep3 = l1.rpc.txprepare([{addr: 'all'}]) decode = bitcoind.rpc.decoderawtransaction(prep3['unsigned_tx']) assert",
"amount) with pytest.raises(RpcError): l1.rpc.withdraw('tb1pw508d6qejxtdg4y5r3zarvary0c5xw7kdl9fad', 2 * amount) with pytest.raises(RpcError): l1.rpc.withdraw('tb1qw508d6qejxtdg4y5r3zarvary0c5xw7kxxxxxx',",
"discard['unsigned_tx'] == prep['unsigned_tx'] prep3 = l1.rpc.txprepare([{addr: 'all'}]) decode = bitcoind.rpc.decoderawtransaction(prep3['unsigned_tx'])",
"< Decimal(amount * 4) / 10**8 assert decode['vout'][0]['value'] > Decimal(amount",
"[f['address'] for f in l1.rpc.listfunds()['outputs']] def test_txprepare_restart(node_factory, bitcoind, chainparams): amount",
"test_withdraw(node_factory, bitcoind): amount = 1000000 # Don't get any funds",
"that we can also decrypt if encrypted with hsmtool cmd_line[1]",
"fees will be taken assert decode['vout'][0]['value'] < Decimal(amount * 4)",
"in range(9): outputs.append({l1.rpc.newaddr()['bech32']: Millisatoshi(amount * 100)}) prep = l1.rpc.txprepare(outputs=outputs) l1.rpc.txdiscard(prep['txid'])",
"= l1.rpc.txprepare([{addr: 'all'}]) decode = bitcoind.rpc.decoderawtransaction(prep['unsigned_tx']) assert decode['txid'] == prep['txid']",
"pytest.raises(RpcError): l1.rpc.withdraw(destination=addr, satoshi=10000, feerate='normal', minconf=9999999) def test_addfunds_from_block(node_factory, bitcoind): \"\"\"Send funds",
"== prep['txid'] # All 10 inputs assert len(decode['vin']) == 10",
"all inputs. l1.rpc.txdiscard(prep2['txid']) l1.rpc.txdiscard(prep3['txid']) prep4 = l1.rpc.txprepare([{addr: 'all'}]) decode =",
"features\") def test_transaction_annotations(node_factory, bitcoind): l1, l2, l3 = node_factory.get_nodes(3) l1.fundwallet(10**6)",
"some funds to withdraw later for i in range(10): l1.bitcoin.rpc.sendtoaddress(addr,",
"FROM outputs WHERE status=2')[0]['c'] == 6 # Simple test for",
"if not chainparams['feeoutput'] else 2 # Some fees will be",
"Check the annotated types types = [o['type'] for o in",
"an address', amount) with pytest.raises(RpcError): l1.rpc.withdraw(waddr, 'not an amount') with",
"\\'satoshi\\' field.'): l1.rpc.call('txprepare', [addr]) with pytest.raises(RpcError, match=r'Could not parse destination",
"and output['satoshis'] == '1000000000msat') # ... and all other output",
"daemon without telling it explicitly \"\"\" # Previous runs with",
"= l1.rpc.getinfo()[\"id\"] l1.stop() # Test we cannot start the same",
"P2SH-P2WPKH waddr = l2.rpc.newaddr('bech32')['bech32'] l1.rpc.withdraw(waddr, 2 * amount) bitcoind.generate_block(1) #",
"\":\" + str(utxo[\"output\"]) for utxo in l1.rpc.listfunds()[\"outputs\"]][:4] withdrawal = l1.rpc.withdraw(waddr,",
"discard after send! with pytest.raises(RpcError, match=r'not an unreleased txid'): l1.rpc.txdiscard(prep['txid'])",
"output reading 'deposit' txs = l1.rpc.listtransactions()['transactions'] assert(len(txs) == 1) tx",
"l1.rpc.getinfo()[\"id\"] l1.stop() # Test we can encrypt it offline cmd_line[1]",
"100), 'feerate': '2000perkw'}) l1.rpc.call('txprepare', {'destination': addr, 'satoshi': Millisatoshi(amount * 100)})",
"bitcoind.generate_block(1) wait_for(lambda: len(l1.rpc.listfunds()['outputs']) == 10) prep = l1.rpc.txprepare(outputs=[{addr: Millisatoshi(amount *",
"'witness_v0_keyhash' assert decode['vout'][0]['scriptPubKey']['addresses'] == [addr] # Cannot discard twice. with",
"be more than 1'): prep5 = l1.rpc.txprepare([{addr: Millisatoshi(amount * 3",
"= l1.bitcoin.rpc.getnewaddress() # Now attempt to withdraw some (making sure",
"multiple inputs) with pytest.raises(RpcError): l1.rpc.withdraw('not an address', amount) with pytest.raises(RpcError):",
"l1.daemon.wait_for_log(\"Server started with public key\") assert id == l1.rpc.getinfo()[\"id\"] @unittest.skipIf(VALGRIND,",
"in listfunds() assert decode['vout'][changenum]['scriptPubKey']['addresses'][0] in [f['address'] for f in l1.rpc.listfunds()['outputs']]",
"l1 = node_factory.get_node(random_hsm=True) bitcoind.rpc.sendtoaddress(l1.rpc.newaddr()['bech32'], amount / 10**8) bitcoind.generate_block(1) wait_for(lambda: len(l1.rpc.listfunds()['outputs'])",
"is smaller than the number of confirmations we wrap around",
"outputs(include change). assert len(decode['vin']) == 4 assert len(decode['vout']) == 4",
"* amount) # No separator character with pytest.raises(RpcError): l1.rpc.withdraw('pzry9x0s0muk', 2",
"l1.db_query('SELECT value FROM outputs WHERE status=0;') assert only_one(outputs)['value'] == 10000000",
"l1.rpc.call('txprepare', [addr, Millisatoshi(amount * 100)]) # Object type with pytest.raises(RpcError,",
"# Now make sure two of them were marked as",
"= tx['outputs'][idx] assert(output['type'] == 'deposit' and output['satoshis'] == '1000000000msat') #",
"start it without password l1.daemon.opts.pop(\"encrypted-hsm\") l1.daemon.start(stdin=slave_fd, wait_for_initialized=True) assert node_id ==",
"status=2')[0]['c'] == 2 # Now send some money to l2.",
"withdraw later: both bech32 and p2sh for i in range(5):",
"= l1.db_query('SELECT value FROM outputs WHERE status=0;') assert only_one(outputs)['value'] ==",
"for o in l1.rpc.listfunds()['outputs']] == ['confirmed'] * 10) prep =",
"the daemon for accessing random memory or null txs =",
"a yet unconfirmed channel def test_fundchannel_listtransaction(node_factory, bitcoind): l1, l2 =",
"l1.rpc.call('txprepare', {'destination': addr, 'feerate': 'slow'}) with pytest.raises(RpcError, match=r'Need set \\'outputs\\'",
"a number of example addresses valid only in regtest\") def",
"experimental features\") def test_transaction_annotations(node_factory, bitcoind): l1, l2, l3 = node_factory.get_nodes(3)",
"slave_fd = os.openpty() l1.daemon.start(stdin=slave_fd, stderr=subprocess.STDOUT, wait_for_initialized=False) l1.daemon.wait_for_log(r'The hsm_secret is encrypted')",
"we simply kill it. l1.restart(clean=False) # It goes backwards in",
"l1.rpc.withdraw(waddr, 2 * amount) bitcoind.generate_block(1) # Now make sure additional",
"8 # failure testing for invalid SegWit addresses, from BIP173",
"assert decode['txid'] == withdrawal['txid'] # Check that correct utxos are",
"100), 'slow', 1]) l1.rpc.call('txprepare', [addr, Millisatoshi(amount * 100), 'normal']) l1.rpc.call('txprepare',",
"that gave us the funds in the # transactions table...",
"should now spend all inputs. l1.rpc.txdiscard(prep2['txid']) l1.rpc.txdiscard(prep3['txid']) prep4 = l1.rpc.txprepare([{addr:",
"should be the funding tx # (we are ordering by",
"- 1]['value'] == Decimal('0.01499900'): outnum2 = i - 1 else:",
"'fee'] # Now prepare one with no change. prep2 =",
"10) with pytest.raises(RpcError, match=r'not an unreleased txid'): l1.rpc.txdiscard(prep['txid']) prep =",
"== Decimal(amount * 3.5) / 10**8 assert decode['vout'][1]['scriptPubKey']['type'] == 'witness_v0_keyhash'",
"1 and outputs[0]['status'] == 'confirmed') out = outputs[0] idx =",
"l1.rpc.call('txprepare', {'satoshi': Millisatoshi(amount * 100), 'feerate': '10perkw', 'minconf': 2}) l1.rpc.call('txprepare',",
"noqa: F401 from pyln.client import RpcError, Millisatoshi from utils import",
"1000)}], utxos=utxos) decode = bitcoind.rpc.decoderawtransaction(prep5['unsigned_tx']) assert decode['txid'] == prep5['txid'] #",
"changenum = 0 else: assert False # Those spent outputs",
"or null txs = l1.rpc.listtransactions()['transactions'] tx = [t for t",
"10) # Reach around into the db to check that",
"assert decode['vout'][0]['scriptPubKey']['addresses'] == [addr] # Cannot discard twice. with pytest.raises(RpcError,",
"# Reach around into the db to check that outputs",
"\"A wrong pass\"] with pytest.raises(subprocess.CalledProcessError): subprocess.check_call(cmd_line) # Decrypt it with",
"elif decode['vout'][i - 1]['value'] == Decimal('0.01499900'): outnum2 = i -",
"with no change. prep2 = l1.rpc.txprepare([{addr: 'all'}]) decode = bitcoind.rpc.decoderawtransaction(prep2['unsigned_tx'])",
"@unittest.skipIf(not EXPERIMENTAL_FEATURES, \"Tests annotations which are compiled only with experimental",
"2 * amount) bitcoind.generate_block(1) # Now make sure additional two",
"# Check that correct utxos are included assert len(decode['vin']) ==",
"time import unittest @unittest.skipIf(TEST_NETWORK != 'regtest', \"Test relies on a",
"!= 'regtest', \"Fee outputs throw off our output matching logic\")",
"10) / 10**8 assert decode['vout'][0]['value'] > Decimal(amount * 10) /",
"l1.rpc.txdiscard(prep4['txid']) # Try passing in a utxo set utxos =",
"runs with same bitcoind can leave funds! l1 = node_factory.get_node(random_hsm=True)",
"have a transaction that gave us the funds in the",
"= node_factory.get_node(random_hsm=True) addr = l1.rpc.newaddr()['bech32'] bitcoind.rpc.sendtoaddress(addr, 0.1) bitcoind.generate_block(1) wait_for(lambda: len(l1.rpc.listfunds()['outputs'])",
"gave us the funds in the # transactions table... outputs",
"password[:-1] subprocess.check_call(cmd_line) # Then test we can now start it",
"1 outputs. assert len(decode['vin']) == 4 assert len(decode['vout']) == 1",
"Decimal(amount * 4) / 10**8 assert decode['vout'][0]['value'] > Decimal(amount *",
"bitcoind): l1, l2 = node_factory.get_nodes(2) l1.fundwallet(10**6) l1.connect(l2) txid = l1.rpc.fundchannel(l2.info['id'],",
"appear in listfunds() assert decode['vout'][changenum]['scriptPubKey']['addresses'][0] in [f['address'] for f in",
"utxos=utxos) decode = bitcoind.rpc.decoderawtransaction(prep5['unsigned_tx']) assert decode['txid'] == prep5['txid'] # Check",
"amount = 1000000 l1 = node_factory.get_node(random_hsm=True) addr = chainparams['example_addr'] #",
"> Decimal(amount * 4) / 10**8 - Decimal(0.0002) assert decode['vout'][0]['scriptPubKey']['type']",
"to self. l1.rpc.withdraw(l1.rpc.newaddr('bech32')['bech32'], 'all', minconf=0) bitcoind.generate_block(1) assert l1.db_query('SELECT COUNT(*) as",
"== ['confirmed'] * 10) # It should have logged this",
"10) with pytest.raises(RpcError): l1.rpc.withdraw(destination=addr, satoshi=10000, feerate='normal', minconf=9999999) def test_addfunds_from_block(node_factory, bitcoind):",
"l1.rpc.listfunds()['outputs'] assert(len(outputs) == 1 and outputs[0]['status'] == 'confirmed') # We",
"# We should now have a transaction that gave us",
"import pytest import subprocess import time import unittest @unittest.skipIf(TEST_NETWORK !=",
"small number. \"\"\" amount = 1000000 # Don't get any",
"bitcoind.rpc.decoderawtransaction(prep5['unsigned_tx']) assert decode['txid'] == prep5['txid'] # Check that correct utxos",
"l1.daemon.wait_for_log(\"Server started with public key\") node_id = l1.rpc.getinfo()[\"id\"] l1.stop() #",
"l1.daemon.opts.update({\"encrypted-hsm\": None}) l1.daemon.start(stdin=slave_fd, stderr=subprocess.STDOUT, wait_for_initialized=False) l1.daemon.wait_for_log(r'The hsm_secret is encrypted') os.write(master_fd,",
"the second one should be the funding tx # (we",
"Change output should appear. if decode['vout'][0]['value'] == Decimal(amount * 3)",
"annotation on the funding output peers = l1.rpc.listpeers()['peers'] assert(len(peers) ==",
"wait_for(lambda: len(l1.rpc.listfunds()['outputs']) == 1) outputs = [] for i in",
"6 # Simple test for withdrawal to P2WSH # Address",
"decode['vout'][i - 1]['value'] == Decimal('0.01500100'): outnum1 = i - 1",
"the same wallet without specifying --encrypted-hsm l1.daemon.opts.pop(\"encrypted-hsm\") with pytest.raises(subprocess.CalledProcessError, match=r'returned",
"previous runs. l1 = node_factory.get_node(random_hsm=True) l2 = node_factory.get_node(random_hsm=True) addr =",
"l1.stop() # And finally test that we can also decrypt",
"= node_factory.bitcoind.rpc.getblockcount() assert nlocktime > 0 and nlocktime <= tip",
"# (we are ordering by blockheight and txindex, so that",
"with pytest.raises(RpcError): l1.rpc.withdraw('tb1qrp33g0q5c5txsp9arysrx4k6zdkfs4nce4xj0gdcccefvpysxf3qxxxxxx', 2 * amount) l1.rpc.withdraw(waddr, 2 * amount)",
"<= tip @flaky @unittest.skipIf(VALGRIND, \"A big loop is used to",
"Millisatoshi(amount * 3 * 1000)}]) out = l1.rpc.txsend(prep['txid']) # Cannot",
"== 10 waddr = l1.bitcoin.rpc.getnewaddress() # Now attempt to withdraw",
"/ 10**8: changenum = 0 else: assert False # Those",
"= l1.rpc.txdiscard(prep['txid']) assert discard['txid'] == prep['txid'] assert discard['unsigned_tx'] == prep['unsigned_tx']",
"== 4 assert len(decode['vout']) == 1 if not chainparams['feeoutput'] else",
"change output has arrived. wait_for(lambda: len(l1.rpc.listfunds()['outputs']) == 10 - len(decode['vin'])",
"amount * 100) out = l1.rpc.withdraw(waddr, 2 * amount) #",
"l1.rpc.withdraw(waddr, 2 * amount, utxos=utxos) decode = bitcoind.rpc.decoderawtransaction(withdrawal['tx']) assert decode['txid']",
"# Encrypt the master seed l1.stop() l1.daemon.opts.update({\"encrypted-hsm\": None}) l1.daemon.start(stdin=slave_fd, wait_for_initialized=False)",
"prep = l1.rpc.txprepare([{addr: Millisatoshi(amount * 3 * 1000)}]) out =",
"bitcoind.rpc.getrawmempool()) # Signed tx should have same txid decode =",
"Check that correct utxos are included assert len(decode['vin']) == 4",
"from fixtures import * # noqa: F401,F403 from fixtures import",
"one with no change. prep2 = l1.rpc.txprepare([{addr: 'all'}]) decode =",
"pytest.raises(RpcError, match=r'not an unreleased txid'): l1.rpc.txdiscard(prep['txid']) # Discard everything, we",
"there are no unconfirmed outputs (change should be confirmed) for",
"BIP141) with pytest.raises(RpcError): l1.rpc.withdraw('BC1QR508D6QEJXTDG4Y5R3ZARVARYV98GJ9P', 2 * amount) # Mixed case",
"bitcoind.rpc.sendtoaddress(l1.rpc.newaddr()['bech32'], amount / 10**8) bitcoind.generate_block(1) wait_for(lambda: len(l1.rpc.listfunds()['outputs']) == 1) outputs",
"= 'bcrt1qw508d6qejxtdg4y5r3zarvary0c5xw7kygt080' with pytest.raises(RpcError): l1.rpc.withdraw('xx1qw508d6qejxtdg4y5r3zarvary0c5xw7kxpjzsx', 2 * amount) with pytest.raises(RpcError):",
"should be ok) txs = l1.rpc.listtransactions()['transactions'] assert(len(txs) == 2 and",
"we cannot restore the same wallet with another password l1.daemon.opts.update({\"encrypted-hsm\":",
"should have one output available, and it should be unconfirmed",
"o['status'] == 'confirmed' # Now make sure two of them",
"decode['vout'][0]['value'] < Decimal(amount * 4) / 10**8 assert decode['vout'][0]['value'] >",
"Decimal(amount * 4) / 10**8 - Decimal(0.0002) assert decode['vout'][0]['scriptPubKey']['type'] ==",
"{'destination': addr, 'satoshi': Millisatoshi(amount * 100)}) def test_txprepare_multi(node_factory, bitcoind): amount",
"{'satoshi': Millisatoshi(amount * 100), 'feerate': '10perkw', 'minconf': 2}) l1.rpc.call('txprepare', {'destination':",
"chainparams): amount = 1000000 l1 = node_factory.get_node(random_hsm=True) addr = chainparams['example_addr']",
"{satoshi} {feerate} {minconf} \"\"\" amount = 10**4 l1 = node_factory.get_node(options={'allow-deprecated-apis':",
"unreleased txid'): l1.rpc.txdiscard(prep['txid']) wait_for(lambda: prep['txid'] in bitcoind.rpc.getrawmempool()) # Signed tx",
"wait_for(lambda: len(l1.rpc.listfunds()['outputs']) == 7) # Array type with pytest.raises(RpcError, match=r'.*",
"with pytest.raises(RpcError): l1.rpc.withdraw('tb1qrp33g0q5c5txsp9arysrx4k6zdkfs4nce4xj0gdcccefvpysxf3q0sL5k7', 2 * amount) # Non-zero padding in",
"for encrypted hsm_secret.\")) # Test we can restore the same",
"1) outputs = l2.db_query('SELECT value FROM outputs WHERE status=0;') assert",
"'feerate': '2000perkw', 'minconf': 1}) l1.rpc.call('txprepare', {'destination': addr, 'satoshi': Millisatoshi(amount *",
"* 10) with pytest.raises(RpcError, match=r'not an unreleased txid'): l1.rpc.txdiscard(prep['txid']) prep",
"@unittest.skipIf(TEST_NETWORK != 'regtest', \"Test relies on a number of example",
"everything, we should now spend all inputs. l1.rpc.txdiscard(prep2['txid']) l1.rpc.txdiscard(prep3['txid']) prep4",
"10**8 assert decode['vout'][0]['value'] > Decimal(amount * 4) / 10**8 -",
"for i, o in enumerate(tx['outputs']): if i == idx: continue",
"them were marked as spent assert l1.db_query('SELECT COUNT(*) as c",
"l2]) outputs = l1.rpc.listfunds()['outputs'] assert(len(outputs) == 1 and outputs[0]['status'] ==",
"[addr] assert decode['vout'][outnum2]['scriptPubKey']['type'] == 'witness_v0_keyhash' assert decode['vout'][outnum2]['scriptPubKey']['addresses'] == [addr] assert",
"Then test we can now start it without password l1.daemon.opts.pop(\"encrypted-hsm\")",
"3) / 10**8][0] for i, o in enumerate(decode['vout']): if i",
"== 'witness_v0_keyhash' assert decode['vout'][1]['scriptPubKey']['addresses'] == [addr] # Discard prep4 and",
"hsm_path = os.path.join(l1.daemon.lightning_dir, TEST_NETWORK, \"hsm_secret\") # We need to simulate",
"with pytest.raises(RpcError): l1.rpc.withdraw('xx1qrp33g0q5c5txsp9arysrx4k6zdkfs4nce4xj0gdcccefvpysxf3q0sl5k7', 2 * amount) with pytest.raises(RpcError): l1.rpc.withdraw('tb1prp33g0q5c5txsp9arysrx4k6zdkfs4nce4xj0gdcccefvpysxf3qsm03tq', 2",
"password[2:].encode(\"utf-8\")) assert(l1.daemon.proc.wait() == 1) assert(l1.daemon.is_in_log(\"Wrong password for encrypted hsm_secret.\")) #",
"idx = out['output'] assert(idx in [0, 1] and out['value'] ==",
"10**8) bitcoind.generate_block(1) wait_for(lambda: len(l1.rpc.listfunds()['outputs']) == 10) prep = l1.rpc.txprepare(outputs=[{addr: Millisatoshi(amount",
"range(3 + chainparams['feeoutput']): if decode['vout'][i - 1]['value'] == Decimal('0.01500100'): outnum1",
"range(9): outputs.append({l1.rpc.newaddr()['bech32']: Millisatoshi(amount * 100)}) prep = l1.rpc.txprepare(outputs=outputs) l1.rpc.txdiscard(prep['txid']) def",
"1) # Change address should appear in listfunds() assert decode['vout'][changenum]['scriptPubKey']['addresses'][0]",
"= password[:-1] subprocess.check_call(cmd_line) # Then test we can now start",
"to withdraw later: both bech32 and p2sh for i in",
"txid {} CONFIRMED'. format(withdraw[\"txid\"])) decoded = bitcoind.rpc.decoderawtransaction(withdraw[\"tx\"]) tip = node_factory.bitcoind.rpc.getblockcount()",
"import TEST_NETWORK from flaky import flaky # noqa: F401 from",
"F401,F403 from fixtures import TEST_NETWORK from flaky import flaky #",
"assert len(decode['vin']) == 4 assert len(decode['vout']) == 4 if chainparams['feeoutput']",
"VALGRIND ) import os import pytest import subprocess import time",
"# Let's now open a channel. The opener should get",
"is exact assert len(decode['vout']) == 3 if chainparams['feeoutput'] else 2",
"# It should also match the funding txid: assert(outputs[0]['txid'] ==",
"assert(len(txs) == 1) tx = txs[0] output = tx['outputs'][idx] assert(output['type']",
"1'): subprocess.check_call(l1.daemon.cmd_line) # Test we cannot restore the same wallet",
"match=r'Cannot afford transaction'): l1.rpc.withdraw(waddr, 'all') # Add some funds to",
"def test_hsmtool_secret_decryption(node_factory): l1 = node_factory.get_node() password = \"<PASSWORD>\" hsm_path =",
"matching logic\") @unittest.skipIf(not EXPERIMENTAL_FEATURES, \"Tests annotations which are compiled only",
"unconfirmed outputs = l1.rpc.listfunds()['outputs'] assert(len(outputs) == 1 and outputs[0]['status'] ==",
"0.01) bitcoind.generate_block(1) wait_for(lambda: len(l1.rpc.listfunds()['outputs']) == 10) # Try passing in",
"l1.rpc.withdraw(waddr, amount * 100) out = l1.rpc.withdraw(waddr, 2 * amount)",
"only_one(outputs)['value'] == 10000000 # The address we detect must match",
"# If I cancel the first one, I can get",
"3 * 1000)}, {addr: 'all'}]) prep5 = l1.rpc.txprepare([{addr: Millisatoshi(amount *",
"a reorg. Wait. wait_for(lambda: [o['status'] for o in l1.rpc.listfunds()['outputs']] ==",
"null column # and crashed the daemon for accessing random",
"cancel the first one, I can get those first 4",
"amount # Now make sure an additional two of them",
"bitcoind.generate_block(1) wait_for(lambda: len(l1.rpc.listfunds()['outputs']) == 10) prep = l1.rpc.txprepare([{addr: Millisatoshi(amount *",
"Encrypt the master seed l1.stop() l1.daemon.opts.update({\"encrypted-hsm\": None}) l1.daemon.start(stdin=slave_fd, wait_for_initialized=False) l1.daemon.wait_for_log(r'The",
"== 8 # failure testing for invalid SegWit addresses, from",
"inputs, 1 outputs. assert len(decode['vin']) == 10 assert len(decode['vout']) ==",
"10**8 + 0.01) bitcoind.generate_block(1) wait_for(lambda: len(l1.rpc.listfunds()['outputs']) == 10) # Reach",
"l1.rpc.txdiscard(prep2['txid']) l1.rpc.txdiscard(prep3['txid']) prep4 = l1.rpc.txprepare([{addr: 'all'}]) decode = bitcoind.rpc.decoderawtransaction(prep4['unsigned_tx']) assert",
"the channel and check that the output changed to confirmed",
"10 @unittest.skipIf(TEST_NETWORK != 'regtest', \"Fee outputs throw off our output",
"node_factory.bitcoind.rpc.decoderawtransaction(tx)[\"locktime\"] tip = node_factory.bitcoind.rpc.getblockcount() assert nlocktime > 0 and nlocktime",
"in `lightningd`. master_fd, slave_fd = os.openpty() # Test we can",
"amount in satoshis or all, not .*'): l1.rpc.call('txprepare', [addr, 'slow'])",
"F401 from pyln.client import RpcError, Millisatoshi from utils import (",
"def test_minconf_withdraw(node_factory, bitcoind): \"\"\"Issue 2518: ensure that ridiculous confirmation levels",
"== 'witness_v0_keyhash' assert o['scriptPubKey']['addresses'] == [addr] else: assert o['scriptPubKey']['type'] in",
"have a change output, so this is exact assert len(decode['vout'])",
"node_factory.get_nodes(3) l1.fundwallet(10**6) # We should now have a transaction that",
"> 0 and nlocktime <= tip @flaky @unittest.skipIf(VALGRIND, \"A big",
"Test we can encrypt an already-existing and not encrypted hsm_secret",
"Millisatoshi from utils import ( only_one, wait_for, sync_blockheight, EXPERIMENTAL_FEATURES, COMPAT,",
"exit status 1'): subprocess.check_call(l1.daemon.cmd_line) # Test we cannot restore the",
"'deposit' else 1 fundidx = 1 - changeidx assert(types[changeidx] ==",
"COUNT(*) as c FROM outputs WHERE status=0')[0]['c'] == 1 l1.rpc.withdraw(waddr,",
"o: types.append(o['type']) else: types.append(None) assert(set([None]) == set(types)) ########################################################################## # Let's",
"= os.openpty() l1.daemon.start(stdin=slave_fd, stderr=subprocess.STDOUT, wait_for_initialized=False) l1.daemon.wait_for_log(r'The hsm_secret is encrypted') os.write(master_fd,",
"t['hash'] == txid][0] assert tx['blockheight'] == 0 def test_withdraw_nlocktime(node_factory): \"\"\"",
"be correct. outnum = [i for i, o in enumerate(decode['vout'])",
"== 1 and outputs[0]['status'] == 'unconfirmed') # It should also",
"Make sure bitcoind received the withdrawal unspent = l1.bitcoin.rpc.listunspent(0) withdrawal",
"10**8 + 0.01) bitcoind.generate_block(1) wait_for(lambda: len(l1.rpc.listfunds()['outputs']) == 10) with pytest.raises(RpcError):",
"peers = l1.rpc.listpeers()['peers'] assert(len(peers) == 1 and len(peers[0]['channels']) == 1)",
"# Simple test for withdrawal to P2WPKH # Address from:",
"Decimal from fixtures import * # noqa: F401,F403 from fixtures",
"outnum1 = i - 1 elif decode['vout'][i - 1]['value'] ==",
"i == outnum: assert o['scriptPubKey']['type'] == 'witness_v0_keyhash' assert o['scriptPubKey']['addresses'] ==",
"txid = l1.rpc.fundchannel(l2.info['id'], 10**5)['txid'] # next call warned about SQL",
"v in decode['vin']] for utxo in utxos: assert utxo in",
"l1.rpc.getinfo()[\"id\"] l1.stop() # And finally test that we can also",
"txs if t['hash'] == txid][0] assert tx['blockheight'] == 0 def",
"== 4 assert len(decode['vout']) == 2 if not chainparams['feeoutput'] else",
"prep['txid'] in bitcoind.rpc.getrawmempool()) # Signed tx should have same txid",
"assert tx['blockheight'] == 0 def test_withdraw_nlocktime(node_factory): \"\"\" Test that we",
"l1.rpc.call('txprepare', {'destination': addr, 'satoshi': Millisatoshi(amount * 100), 'feerate': '2000perkw', 'minconf':",
"* 3.5) / 10**8 assert decode['vout'][1]['scriptPubKey']['type'] == 'witness_v0_keyhash' assert decode['vout'][1]['scriptPubKey']['addresses']",
"\"\"\" l1 = node_factory.get_node(1) l1.fundwallet(10**4) addr = l1.rpc.newaddr()[\"bech32\"] tx =",
"than 1'): prep5 = l1.rpc.txprepare([{addr: Millisatoshi(amount * 3 * 1000)},",
"should appear in listfunds() assert decode['vout'][changenum]['scriptPubKey']['addresses'][0] in [f['address'] for f",
"= l2.rpc.newaddr('bech32')['bech32'] l1.rpc.withdraw(waddr, 2 * amount) bitcoind.generate_block(1) # Make sure",
"this for each output. for i in decode['vin']: assert l1.daemon.is_in_log('wallet:",
"in bitcoind.rpc.getrawmempool()) # Signed tx should have same txid decode",
"flaky \"just in case\" as we fuzz from 0 to",
"assert decode['vout'][0]['scriptPubKey']['type'] == 'witness_v0_keyhash' assert decode['vout'][0]['scriptPubKey']['addresses'] == [addr] # If",
"and check that the output changed to confirmed bitcoind.generate_block(3) sync_blockheight(bitcoind,",
"+ chainparams['feeoutput']): if decode['vout'][i - 1]['value'] == Decimal('0.01500100'): outnum1 =",
"assert only_one(outputs)['value'] == 2 * amount # Now make sure",
"from: https://bc-2.jp/tools/bech32demo/index.html waddr = 'bcrt1qrp33g0q5c5txsp9arysrx4k6zdkfs4nce4xj0gdcccefvpysxf3qzf4jry' with pytest.raises(RpcError): l1.rpc.withdraw('xx1qrp33g0q5c5txsp9arysrx4k6zdkfs4nce4xj0gdcccefvpysxf3q0sl5k7', 2 *",
"else: types.append(None) assert(set([None]) == set(types)) ########################################################################## # Let's now open",
"@flaky @unittest.skipIf(VALGRIND, \"A big loop is used to check fuzz.\")",
"# It goes backwards in blockchain just in case there",
"l1.stop() # Test we can encrypt it offline cmd_line[1] =",
"o in txs[1]['outputs']] changeidx = 0 if types[0] == 'deposit'",
"about it. l1.restart() # It goes backwards in blockchain just",
"bitcoind.generate_block(1) wait_for(lambda: len(l1.rpc.listfunds()['outputs']) == 1) outputs = l1.db_query('SELECT value FROM",
"# Simple test for withdrawal to P2WSH # Address from:",
"100), 'feerate': '2000perkw', 'minconf': 1}) l1.rpc.call('txprepare', {'destination': addr, 'satoshi': Millisatoshi(amount",
"the funding transaction # annotated as channel open and deposit.",
"Some fees will be taken assert decode['vout'][0]['value'] < Decimal(amount *",
"transactions. \"\"\" l1 = node_factory.get_node(1) l1.fundwallet(10**4) addr = l1.rpc.newaddr()[\"bech32\"] tx",
"flaky import flaky # noqa: F401 from pyln.client import RpcError,",
"inputs assert len(decode['vin']) == 10 # This will also work",
"status=2')[0]['c'] == 4 # Simple test for withdrawal to P2WPKH",
"l1.db_query('SELECT COUNT(*) as c FROM outputs WHERE status=2')[0]['c'] == 4",
"* 4) / 10**8 assert decode['vout'][0]['value'] > Decimal(amount * 4)",
"len(decode['vin']) == 4 vins = [\"{}:{}\".format(v['txid'], v['vout']) for v in",
"amount) with pytest.raises(RpcError): l1.rpc.withdraw('tb1qrp33g0q5c5txsp9arysrx4k6zdkfs4nce4xj0gdcccefvpysxf3qxxxxxx', 2 * amount) l1.rpc.withdraw(waddr, 2 *",
"in 8-to-5 conversion with pytest.raises(RpcError): l1.rpc.withdraw('tb1qrp33g0q5c5txsp9arysrx4k6zdkfs4nce4xj0gdcccefvpysxf3pjxtptv', 2 * amount) #",
"password = \"<PASSWORD>\" hsm_path = os.path.join(l1.daemon.lightning_dir, TEST_NETWORK, \"hsm_secret\") # We",
"as c FROM outputs WHERE status=2')[0]['c'] == 8 # failure",
"with pytest.raises(RpcError, match=r'Could not parse destination address.*'): l1.rpc.call('txprepare', [Millisatoshi(amount *",
"the withdrawal unspent = l1.bitcoin.rpc.listunspent(0) withdrawal = [u for u",
"amount) bitcoind.generate_block(1) # Now make sure additional two of them",
"Millisatoshi(amount * 3 * 1000)}]) decode = bitcoind.rpc.decoderawtransaction(prep['unsigned_tx']) assert decode['txid']",
"prep5 = l1.rpc.txprepare([{addr: Millisatoshi(amount * 3 * 500 + 100000)},",
"output will be correct. outnum = [i for i, o",
"Some fees will be paid. assert decode['vout'][0]['value'] < Decimal(amount *",
"start the same wallet without specifying --encrypted-hsm l1.daemon.opts.pop(\"encrypted-hsm\") with pytest.raises(subprocess.CalledProcessError,",
"we can encrypt an already-existing and not encrypted hsm_secret l1.stop()",
"to withdraw for i in range(10): l1.bitcoin.rpc.sendtoaddress(addr, amount / 10**8",
"WHERE status=0;') assert only_one(outputs)['value'] == 10000000 # The address we",
"have 2 transactions, the second one should be the funding",
"COUNT(*) as c FROM outputs WHERE status=2')[0]['c'] == 4 #",
"unreleased txid'): l1.rpc.txdiscard(prep['txid']) # Discard everything, we should now spend",
"types[0] == 'deposit' else 1 fundidx = 1 - changeidx",
"prep = l1.rpc.txprepare(outputs=[{addr: Millisatoshi(amount * 3 * 1000)}]) decode =",
"assert decode['vout'][0]['value'] < Decimal(amount * 6) / 10**8 assert decode['vout'][0]['value']",
"# lightningd uses P2SH-P2WPKH waddr = l2.rpc.newaddr('bech32')['bech32'] l1.rpc.withdraw(waddr, 2 *",
"2 * amount # Now make sure an additional two",
"this test does a 'listtransactions' on a yet unconfirmed channel",
"by blockheight and txindex, so that order should be ok)",
"4) / 10**8 assert decode['vout'][0]['value'] > Decimal(amount * 4) /",
"which are compiled only with experimental features\") def test_transaction_annotations(node_factory, bitcoind):",
"paid. assert decode['vout'][0]['value'] < Decimal(amount * 6) / 10**8 assert",
"to a positive small number. \"\"\" amount = 1000000 #",
"public key\") node_id = l1.rpc.getinfo()[\"id\"] l1.stop() # We can't use",
"pyln.client import RpcError, Millisatoshi from utils import ( only_one, wait_for,",
"/ 10**8) bitcoind.generate_block(1) wait_for(lambda: [o['status'] for o in l1.rpc.listfunds()['outputs']] ==",
"derivation.\") def test_hsm_secret_encryption(node_factory): l1 = node_factory.get_node(may_fail=True) # May fail when",
"have logged this for each output. for i in decode['vin']:",
"funding txid: assert(outputs[0]['txid'] == fundingtx['txid']) # Confirm the channel and",
"started with public key\") assert node_id == l1.rpc.getinfo()[\"id\"] l1.stop() #",
"str(utxo[\"output\"]) for utxo in l1.rpc.listfunds()[\"outputs\"]][:4] prep5 = l1.rpc.txprepare([{addr: Millisatoshi(amount *",
"character with pytest.raises(RpcError): l1.rpc.withdraw('pzry9x0s0muk', 2 * amount) # Empty HRP",
"outputs WHERE status=2')[0]['c'] == 4 # Simple test for withdrawal",
"reset to available'.format(i['txid'], i['vout'])) prep = l1.rpc.txprepare([{addr: 'all'}]) decode =",
"on the output reading 'deposit' txs = l1.rpc.listtransactions()['transactions'] assert(len(txs) ==",
"an annotation on the output reading 'deposit' txs = l1.rpc.listtransactions()['transactions']",
"transactions, the second one should be the funding tx #",
"# Now make sure additional two of them were marked",
"arrived. wait_for(lambda: len(l1.rpc.listfunds()['outputs']) == 10 - len(decode['vin']) + 1) #",
"not play well with prompt and key derivation.\") def test_hsm_secret_encryption(node_factory):",
"l1.bitcoin.rpc.listunspent(0) withdrawal = [u for u in unspent if u['txid']",
"= l1.rpc.txprepare([{addr: 'all'}]) decode = bitcoind.rpc.decoderawtransaction(prep2['unsigned_tx']) assert decode['txid'] == prep2['txid']",
"= node_factory.get_node(random_hsm=True) bitcoind.rpc.sendtoaddress(l1.rpc.newaddr()['bech32'], amount / 10**8) bitcoind.generate_block(1) wait_for(lambda: len(l1.rpc.listfunds()['outputs']) ==",
"l1.rpc.withdraw('tb1pw508d6qejxtdg4y5r3zarvary0c5xw7kdl9fad', 2 * amount) with pytest.raises(RpcError): l1.rpc.withdraw('tb1qw508d6qejxtdg4y5r3zarvary0c5xw7kxxxxxx', 2 * amount)",
"txid'): l1.rpc.txdiscard(prep['txid']) prep = l1.rpc.txprepare([{addr: 'all'}]) decode = bitcoind.rpc.decoderawtransaction(prep['unsigned_tx']) assert",
"`lightningd`. master_fd, slave_fd = os.openpty() # Test we can encrypt",
"* 10) # It should have logged this for each",
"2 # Now send some money to l2. # lightningd",
"We should now have a transaction that gave us the",
"pytest.raises(RpcError): l1.rpc.withdraw('BC1QR508D6QEJXTDG4Y5R3ZARVARYV98GJ9P', 2 * amount) # Mixed case with pytest.raises(RpcError):",
"assert o['scriptPubKey']['type'] in ['witness_v0_keyhash', 'fee'] # Now prepare one with",
"assert len(decode['vin']) == 4 assert len(decode['vout']) == 1 if not",
"l1.daemon.wait_for_log(r'The hsm_secret is encrypted') os.write(master_fd, password.encode(\"utf-8\")) l1.daemon.wait_for_log(\"Server started with public",
"1 outputs. assert len(decode['vin']) == 6 assert len(decode['vout']) == 1",
"l1.rpc.listtransactions()['transactions'] assert(len(txs) == 1) tx = txs[0] output = tx['outputs'][idx]",
"out['output'] assert(idx in [0, 1] and out['value'] == 10**6) #",
"* 100), 'feerate': '2000perkw', 'minconf': 1}) l1.rpc.call('txprepare', {'destination': addr, 'satoshi':",
"password ! cmd_line = [\"tools/hsmtool\", \"decrypt\", hsm_path, \"A wrong pass\"]",
"l1.rpc.listtransactions()['transactions'] tx = [t for t in txs if t['hash']",
"i == idx: continue if 'type' in o: types.append(o['type']) else:",
"[addr]) with pytest.raises(RpcError, match=r'Could not parse destination address.*'): l1.rpc.call('txprepare', [Millisatoshi(amount",
"node_factory.get_nodes(2) l1.fundwallet(10**6) l1.connect(l2) txid = l1.rpc.fundchannel(l2.info['id'], 10**5)['txid'] # next call",
"== 10 assert len(decode['vout']) == 1 if not chainparams['feeoutput'] else",
"# Should have 6 outputs available. assert l1.db_query('SELECT COUNT(*) as",
"[l1]) wait_for(lambda: len(l1.rpc.listfunds()['outputs']) == 7) # Array type with pytest.raises(RpcError,",
"else 2 # Some fees will be taken assert decode['vout'][0]['value']",
"if decoded[\"locktime\"] < tip: return else: raise Exception(\"No transaction with",
"== scid) @unittest.skipIf(VALGRIND, \"It does not play well with prompt",
"o in enumerate(decode['vout']): if i == outnum: assert o['scriptPubKey']['type'] ==",
"import unittest @unittest.skipIf(TEST_NETWORK != 'regtest', \"Test relies on a number",
"as c FROM outputs WHERE status=0')[0]['c'] == 6 # Test",
"assert only_one(outputs)['value'] == 10000000 # The address we detect must",
"= [utxo[\"txid\"] + \":\" + str(utxo[\"output\"]) for utxo in l1.rpc.listfunds()[\"outputs\"]][:4]",
"utxo in l1.rpc.listfunds()[\"outputs\"]][:4] withdrawal = l1.rpc.withdraw(waddr, 2 * amount, utxos=utxos)",
"'all'}]) decode = bitcoind.rpc.decoderawtransaction(prep2['unsigned_tx']) assert decode['txid'] == prep2['txid'] # 6",
"decode['vout'][0]['value'] == Decimal(amount * 3) / 10**8: changenum = 1",
"pytest.raises(RpcError): l1.rpc.withdraw(waddr, -amount) with pytest.raises(RpcError, match=r'Cannot afford transaction'): l1.rpc.withdraw(waddr, amount",
"https://bc-2.jp/tools/bech32demo/index.html waddr = 'bcrt1qrp33g0q5c5txsp9arysrx4k6zdkfs4nce4xj0gdcccefvpysxf3qzf4jry' with pytest.raises(RpcError): l1.rpc.withdraw('xx1qrp33g0q5c5txsp9arysrx4k6zdkfs4nce4xj0gdcccefvpysxf3q0sl5k7', 2 * amount)",
"outputs[0]['status'] == 'confirmed') # We should have 2 transactions, the",
"inputs, 1 outputs. assert len(decode['vin']) == 4 assert len(decode['vout']) ==",
"for utxo in l1.rpc.listfunds()[\"outputs\"]][:4] prep5 = l1.rpc.txprepare([{addr: Millisatoshi(amount * 3.5",
"non-zero exit status 1'): subprocess.check_call(l1.daemon.cmd_line) # Test we cannot restore",
"same wallet without specifying --encrypted-hsm l1.daemon.opts.pop(\"encrypted-hsm\") with pytest.raises(subprocess.CalledProcessError, match=r'returned non-zero",
"channel. The opener should get the funding transaction # annotated",
"nlocktime <= tip @flaky @unittest.skipIf(VALGRIND, \"A big loop is used",
"1 else: changenum = i - 1 assert decode['vout'][outnum1]['scriptPubKey']['type'] ==",
"decode['txid'] == prep['txid'] # 4 inputs, 2 outputs (3 if",
"funding tx # (we are ordering by blockheight and txindex,",
"\"\"\"Issue 2518: ensure that ridiculous confirmation levels don't overflow The",
"if not chainparams['feeoutput'] else 3 # One output will be",
"pytest.raises(RpcError, match=r'Cannot afford transaction'): l1.rpc.withdraw(waddr, 'all') # Add some funds",
"amount = 10000000 l1 = node_factory.get_node(random_hsm=True) bitcoind.rpc.sendtoaddress(l1.rpc.newaddr()['bech32'], amount / 10**8)",
"in txs[1]['outputs']] changeidx = 0 if types[0] == 'deposit' else",
"os.path.join(l1.daemon.lightning_dir, TEST_NETWORK, \"hsm_secret\") # We need to simulate a terminal",
"status=0')[0]['c'] == 10 waddr = l1.bitcoin.rpc.getnewaddress() # Now attempt to",
"l1.rpc.withdraw(destination=addr, satoshi=10000, feerate='normal', minconf=9999999) def test_addfunds_from_block(node_factory, bitcoind): \"\"\"Send funds to",
"FROM outputs WHERE status=0')[0]['c'] == 0 # This should fail,",
"addr = l1.rpc.newaddr()[\"bech32\"] tx = l1.rpc.withdraw(addr, 10**3)[\"tx\"] nlocktime = node_factory.bitcoind.rpc.decoderawtransaction(tx)[\"locktime\"]",
"l1.rpc.txdiscard(prep3['txid']) prep4 = l1.rpc.txprepare([{addr: 'all'}]) decode = bitcoind.rpc.decoderawtransaction(prep4['unsigned_tx']) assert decode['txid']",
"\"\"\" Test that we don't set the nLockTime to 0",
"bitcoind.rpc.sendtoaddress(l1.rpc.newaddr('p2sh-segwit')['p2sh-segwit'], amount / 10**8) bitcoind.generate_block(1) wait_for(lambda: len(l1.rpc.listfunds()['outputs']) == 10) prep",
"is encrypted') os.write(master_fd, password.encode(\"utf-8\")) l1.daemon.wait_for_log(\"Server started with public key\") id",
"get the funding transaction # annotated as channel open and",
"is used to check fuzz.\") def test_withdraw_nlocktime_fuzz(node_factory, bitcoind): \"\"\" Test",
"prep = l1.rpc.txprepare([{addr: 'all'}]) decode = bitcoind.rpc.decoderawtransaction(prep['unsigned_tx']) assert decode['txid'] ==",
"= os.openpty() # Test we can encrypt an already-existing and",
"== 'unconfirmed') # It should also match the funding txid:",
"Millisatoshi(amount * 100), 'feerate': '2000perkw', 'minconf': 1}) l1.rpc.call('txprepare', {'destination': addr,",
"== l1.rpc.getinfo()[\"id\"] l1.stop() # And finally test that we can",
"assert len(decode['vin']) == 10 # L1 will forget all about",
"subprocess.check_call(cmd_line) # Then test we can now start it without",
"len(l1.rpc.listfunds()['outputs']) == 10) # Try passing in a utxo set",
"* amount) # Invalid program length for witness version 0",
"# 4 inputs, 1 outputs. assert len(decode['vin']) == 4 assert",
"# Check the annotated types types = [o['type'] for o",
"elif decode['vout'][1]['value'] == Decimal(amount * 3) / 10**8: changenum =",
"HRP with pytest.raises(RpcError): l1.rpc.withdraw('1pzry9x0s0muk', 2 * amount) # Invalid witness",
"def test_txprepare(node_factory, bitcoind, chainparams): amount = 1000000 l1 = node_factory.get_node(random_hsm=True)",
"FROM outputs WHERE status=2')[0]['c'] == 4 # Simple test for",
"on a number of example addresses valid only in regtest\")",
"everything. The fix is to clamp the maxheight parameter to",
"'witness_v0_keyhash' assert decode['vout'][0]['scriptPubKey']['addresses'] == [addr] # If I cancel the",
"Decimal(amount * 3) / 10**8][0] for i, o in enumerate(decode['vout']):",
"l1.rpc.withdraw('xx1qrp33g0q5c5txsp9arysrx4k6zdkfs4nce4xj0gdcccefvpysxf3q0sl5k7', 2 * amount) with pytest.raises(RpcError): l1.rpc.withdraw('tb1prp33g0q5c5txsp9arysrx4k6zdkfs4nce4xj0gdcccefvpysxf3qsm03tq', 2 * amount)",
"l1.rpc.call('txprepare', {'destination': addr, 'satoshi': Millisatoshi(amount * 100)}) def test_txprepare_multi(node_factory, bitcoind):",
"\"Fee outputs throw off our output matching logic\") @unittest.skipIf(not EXPERIMENTAL_FEATURES,",
"len(decode['vout']) == 4 if chainparams['feeoutput'] else 3 # One output",
"4 inputs, 2 outputs (3 if we have a fee",
"assert(output['type'] == 'deposit' and output['satoshis'] == '1000000000msat') # ... and",
"2 * amount) with pytest.raises(RpcError): l1.rpc.withdraw('tb1qrp33g0q5c5txsp9arysrx4k6zdkfs4nce4xj0gdcccefvpysxf3qxxxxxx', 2 * amount) l1.rpc.withdraw(waddr,",
"withdraw = l1.rpc.withdraw(addr, 10**3) bitcoind.generate_block(1) l1.daemon.wait_for_log('Owning output .* txid {}",
"l1.rpc.fundchannel(l2.info['id'], 10**5) # We should have one output available, and",
"number of example addresses valid only in regtest\") def test_withdraw(node_factory,",
"= chainparams['example_addr'] # Add some funds to withdraw later: both",
"same bitcoind can leave funds! l1 = node_factory.get_node(random_hsm=True) addr =",
"* amount) # overall max length exceeded with pytest.raises(RpcError): l1.rpc.withdraw('an84characterslonghumanreadablepartthatcontainsthenumber1andtheexcludedcharactersbio1569pvx',",
"COUNT(*) as c FROM outputs WHERE status=2')[0]['c'] == 6 #",
"l1.daemon.opts.pop(\"encrypted-hsm\") l1.daemon.start(stdin=slave_fd, wait_for_initialized=True) assert node_id == l1.rpc.getinfo()[\"id\"] # this test",
"= os.openpty() # Encrypt the master seed l1.stop() l1.daemon.opts.update({\"encrypted-hsm\": None})",
"l1.rpc.txdiscard(prep['txid']) # Discard everything, we should now spend all inputs.",
"withdrawal unspent = l1.bitcoin.rpc.listunspent(0) withdrawal = [u for u in",
"padding in 8-to-5 conversion with pytest.raises(RpcError): l1.rpc.withdraw('tb1qrp33g0q5c5txsp9arysrx4k6zdkfs4nce4xj0gdcccefvpysxf3pjxtptv', 2 * amount)",
"One output will be correct. for i in range(3 +",
"fuzz.\") def test_withdraw_nlocktime_fuzz(node_factory, bitcoind): \"\"\" Test that we eventually fuzz",
"'bcrt1qrp33g0q5c5txsp9arysrx4k6zdkfs4nce4xj0gdcccefvpysxf3qzf4jry' with pytest.raises(RpcError): l1.rpc.withdraw('xx1qrp33g0q5c5txsp9arysrx4k6zdkfs4nce4xj0gdcccefvpysxf3q0sl5k7', 2 * amount) with pytest.raises(RpcError): l1.rpc.withdraw('tb1prp33g0q5c5txsp9arysrx4k6zdkfs4nce4xj0gdcccefvpysxf3qsm03tq',",
"1'): prep5 = l1.rpc.txprepare([{addr: Millisatoshi(amount * 3 * 1000)}, {addr:",
"== 10) # Try passing in a utxo set utxos",
"/ 10**8 assert decode['vout'][0]['value'] > Decimal(amount * 10) / 10**8",
"o['value'] == Decimal(amount * 3) / 10**8][0] for i, o",
"@unittest.skipIf(VALGRIND, \"It does not play well with prompt and key",
"node_factory.get_node(random_hsm=True) bitcoind.rpc.sendtoaddress(l1.rpc.newaddr()['bech32'], amount / 10**8) bitcoind.generate_block(1) wait_for(lambda: len(l1.rpc.listfunds()['outputs']) == 1)",
"assert decode['vout'][outnum1]['scriptPubKey']['addresses'] == [addr] assert decode['vout'][outnum2]['scriptPubKey']['type'] == 'witness_v0_keyhash' assert decode['vout'][outnum2]['scriptPubKey']['addresses']",
"l1.rpc.listfunds()['outputs']: assert o['status'] == 'confirmed' # Now make sure two",
"output['address'] == addr @unittest.skipIf(not COMPAT, \"needs COMPAT=1\") def test_deprecated_txprepare(node_factory, bitcoind):",
"same txid decode = bitcoind.rpc.decoderawtransaction(out['tx']) assert decode['txid'] == prep['txid'] bitcoind.generate_block(1)",
"= 1 - changeidx assert(types[changeidx] == 'deposit' and types[fundidx] ==",
"subprocess.check_call(l1.daemon.cmd_line) # Test we cannot restore the same wallet with",
"[l1, l2]) outputs = l1.rpc.listfunds()['outputs'] assert(len(outputs) == 1 and outputs[0]['status']",
"node_factory.get_node(1) l1.fundwallet(10**8) for i in range(100): addr = l1.rpc.newaddr()[\"bech32\"] withdraw",
"c FROM outputs WHERE status=2')[0]['c'] == 8 # failure testing",
"with pytest.raises(RpcError, match=r'Need set \\'outputs\\' field.'): l1.rpc.call('txprepare', {'satoshi': Millisatoshi(amount *",
"enumerate(decode['vout']) if o['value'] == Decimal(amount * 3) / 10**8][0] for",
"Millisatoshi(amount * 3 * 500 - 100000)}]) decode = bitcoind.rpc.decoderawtransaction(prep5['unsigned_tx'])",
"l1.rpc.newaddr()[\"bech32\"] tx = l1.rpc.withdraw(addr, 10**3)[\"tx\"] nlocktime = node_factory.bitcoind.rpc.decoderawtransaction(tx)[\"locktime\"] tip =",
"# Discard everything, we should now spend all inputs. l1.rpc.txdiscard(prep2['txid'])",
"os import pytest import subprocess import time import unittest @unittest.skipIf(TEST_NETWORK",
"outputs (3 if we have a fee output). assert len(decode['vin'])",
"{'destination': addr, 'feerate': 'slow'}) with pytest.raises(RpcError, match=r'Need set \\'outputs\\' field.'):",
"use a wrong password ! cmd_line = [\"tools/hsmtool\", \"decrypt\", hsm_path,",
"== 2 and txs[1]['hash'] == fundingtx['txid']) # Check the annotated",
"withdrawal transactions. Marked flaky \"just in case\" as we fuzz",
"hsmtool cmd_line[1] = \"decrypt\" subprocess.check_call(cmd_line) l1.daemon.opts.pop(\"encrypted-hsm\") l1.daemon.start(stdin=slave_fd, wait_for_initialized=True) assert node_id",
"- Decimal(0.0002) assert decode['vout'][0]['scriptPubKey']['type'] == 'witness_v0_keyhash' assert decode['vout'][0]['scriptPubKey']['addresses'] == [addr]",
"encrypted') os.write(master_fd, password[2:].encode(\"utf-8\")) assert(l1.daemon.proc.wait() == 1) assert(l1.daemon.is_in_log(\"Wrong password for encrypted",
"Make sure l2 received the withdrawal. wait_for(lambda: len(l2.rpc.listfunds()['outputs']) == 1)",
"assert o['scriptPubKey']['addresses'] == [addr] else: assert o['scriptPubKey']['type'] in ['witness_v0_keyhash', 'fee']",
"The number of confirmations is used to compute a maximum",
"# failure testing for invalid SegWit addresses, from BIP173 #",
"3) / 10**8: changenum = 0 else: assert False #",
"column # and crashed the daemon for accessing random memory",
"match=r'not an unreleased txid'): l1.rpc.txdiscard(prep['txid']) # Discard everything, we should",
"l1.daemon.start(stdin=slave_fd, stderr=subprocess.STDOUT, wait_for_initialized=False) l1.daemon.wait_for_log(r'The hsm_secret is encrypted') os.write(master_fd, password.encode(\"utf-8\")) l1.daemon.wait_for_log(\"Server",
"call warned about SQL Accessing a null column # and",
"inputs, 3 outputs(include change). assert len(decode['vin']) == 4 assert len(decode['vout'])",
"We should have one output available, and it should be",
"assert decode['txid'] == prep5['txid'] # Check that correct utxos are",
"- 1]['value'] == Decimal('0.01500100'): outnum1 = i - 1 elif",
"The fix is to clamp the maxheight parameter to a",
"10**8) bitcoind.generate_block(1) wait_for(lambda: len(l1.rpc.listfunds()['outputs']) == 10) prep = l1.rpc.txprepare([{addr: Millisatoshi(amount",
"COUNT(*) as c FROM outputs WHERE status=0')[0]['c'] == 6 #",
"== withdrawal['txid'] # Check that correct utxos are included assert",
"import * # noqa: F401,F403 from fixtures import TEST_NETWORK from",
"sure l2 received the withdrawal. wait_for(lambda: len(l2.rpc.listfunds()['outputs']) == 1) outputs",
"10) / 10**8 - Decimal(0.0003) assert decode['vout'][0]['scriptPubKey']['type'] == 'witness_v0_keyhash' assert",
"to P2WSH # Address from: https://bc-2.jp/tools/bech32demo/index.html waddr = 'bcrt1qrp33g0q5c5txsp9arysrx4k6zdkfs4nce4xj0gdcccefvpysxf3qzf4jry' with",
"10**4 l1 = node_factory.get_node(options={'allow-deprecated-apis': True}) addr = l1.rpc.newaddr()['bech32'] for i",
"l1.rpc.txprepare([{addr: Millisatoshi(amount * 3 * 1000)}]) out = l1.rpc.txsend(prep['txid']) #",
"pytest.raises(subprocess.CalledProcessError, match=r'returned non-zero exit status 1'): subprocess.check_call(l1.daemon.cmd_line) # Test we",
"in l1.rpc.listfunds()[\"outputs\"]][:4] prep5 = l1.rpc.txprepare([{addr: Millisatoshi(amount * 3.5 * 1000)}],",
"== ['confirmed'] * 10) with pytest.raises(RpcError, match=r'not an unreleased txid'):",
"the funding tx # (we are ordering by blockheight and",
"l1.daemon.wait_for_log('Owning output .* txid {} CONFIRMED'. format(withdraw[\"txid\"])) decoded = bitcoind.rpc.decoderawtransaction(withdraw[\"tx\"])",
"pytest.raises(RpcError, match=r'this destination wants all satoshi. The count of outputs",
"== idx: continue if 'type' in o: types.append(o['type']) else: types.append(None)",
"encrypted-hsm startup option l1.stop() with pytest.raises(subprocess.CalledProcessError, match=r'returned non-zero exit status",
"pytest.raises(RpcError): l1.rpc.withdraw('tb1qrp33g0q5c5txsp9arysrx4k6zdkfs4nce4xj0gdcccefvpysxf3q0sL5k7', 2 * amount) # Non-zero padding in 8-to-5",
"# Confirm the channel and check that the output changed",
"the encrypted-hsm startup option l1.stop() with pytest.raises(subprocess.CalledProcessError, match=r'returned non-zero exit",
"bitcoind): \"\"\" Test that we eventually fuzz nLockTime for withdrawal",
"+ 100000)}, {addr: Millisatoshi(amount * 3 * 500 - 100000)}])",
"satoshi. The count of outputs can\\'t be more than 1'):",
"# Empty HRP with pytest.raises(RpcError): l1.rpc.withdraw('1pzry9x0s0muk', 2 * amount) #",
"match=r'Need set \\'satoshi\\' field.'): l1.rpc.call('txprepare', [addr]) with pytest.raises(RpcError, match=r'Could not",
"# Test we cannot start the same wallet without specifying",
"Decimal(amount * 3.5) / 10**8 assert decode['vout'][1]['scriptPubKey']['type'] == 'witness_v0_keyhash' assert",
"channel and check that the output changed to confirmed bitcoind.generate_block(3)",
"test_hsmtool_secret_decryption(node_factory): l1 = node_factory.get_node() password = \"<PASSWORD>\" hsm_path = os.path.join(l1.daemon.lightning_dir,",
"hsm_secret l1.stop() l1.daemon.opts.update({\"encrypted-hsm\": None}) l1.daemon.start(stdin=slave_fd, wait_for_initialized=False) l1.daemon.wait_for_log(r'The hsm_secret is encrypted')",
"destination address.*'): l1.rpc.call('txprepare', [Millisatoshi(amount * 100), 'slow', 1]) l1.rpc.call('txprepare', [addr,",
"f in l1.rpc.listfunds()['outputs']] def test_txprepare_restart(node_factory, bitcoind, chainparams): amount = 1000000",
"2 if not chainparams['feeoutput'] else 3 # One output will",
"inputs. l1.rpc.txdiscard(prep2['txid']) l1.rpc.txdiscard(prep3['txid']) prep4 = l1.rpc.txprepare([{addr: 'all'}]) decode = bitcoind.rpc.decoderawtransaction(prep4['unsigned_tx'])",
".*'): l1.rpc.call('txprepare', [addr, 'slow']) with pytest.raises(RpcError, match=r'Need set \\'satoshi\\' field.'):",
"range(100): addr = l1.rpc.newaddr()[\"bech32\"] withdraw = l1.rpc.withdraw(addr, 10**3) bitcoind.generate_block(1) l1.daemon.wait_for_log('Owning",
"format(withdraw[\"txid\"])) decoded = bitcoind.rpc.decoderawtransaction(withdraw[\"tx\"]) tip = node_factory.bitcoind.rpc.getblockcount() assert decoded[\"locktime\"] >",
"3 outputs(include change). assert len(decode['vin']) == 4 assert len(decode['vout']) ==",
"test for withdrawal to P2WSH # Address from: https://bc-2.jp/tools/bech32demo/index.html waddr",
"a channel. The opener should get the funding transaction #",
"output matching logic\") @unittest.skipIf(not EXPERIMENTAL_FEATURES, \"Tests annotations which are compiled",
"sure an additional two of them were marked as spent",
"should be confirmed) for o in l1.rpc.listfunds()['outputs']: assert o['status'] ==",
"this time. addr = l1.rpc.newaddr(\"bech32\")['bech32'] l1.rpc.withdraw(addr, \"all\") bitcoind.generate_block(1) time.sleep(1) #",
"1 elif decode['vout'][i - 1]['value'] == Decimal('0.01499900'): outnum2 = i",
"0 # This should fail, can't even afford fee. with",
"bitcoind): \"\"\"Send funds to the daemon without telling it explicitly",
"for utxo in utxos: assert utxo in vins # We",
"daemon for accessing random memory or null txs = l1.rpc.listtransactions()['transactions']",
"def test_withdraw(node_factory, bitcoind): amount = 1000000 # Don't get any",
"== 10**6) # ... and it should have an annotation",
"0 and nlocktime <= tip @flaky @unittest.skipIf(VALGRIND, \"A big loop",
"# Then test we can now start it without password",
"Decimal(amount * 10) / 10**8 assert decode['vout'][0]['value'] > Decimal(amount *",
"match=r'Could not parse destination address.*'): l1.rpc.call('txprepare', [Millisatoshi(amount * 100), 'slow',",
"import subprocess import time import unittest @unittest.skipIf(TEST_NETWORK != 'regtest', \"Test",
"l1.rpc.txsend(prep['txid']) # Cannot discard after send! with pytest.raises(RpcError, match=r'not an",
"BIP173 # HRP character out of range with pytest.raises(RpcError): l1.rpc.withdraw('",
"unconfirmed outputs (change should be confirmed) for o in l1.rpc.listfunds()['outputs']:",
"assert l1.db_query('SELECT COUNT(*) as c FROM outputs WHERE status=2')[0]['c'] ==",
"\":\" + str(utxo[\"output\"]) for utxo in l1.rpc.listfunds()[\"outputs\"]][:4] prep5 = l1.rpc.txprepare([{addr:",
"are no unconfirmed outputs (change should be confirmed) for o",
"* amount) # Empty HRP with pytest.raises(RpcError): l1.rpc.withdraw('1pzry9x0s0muk', 2 *",
"logged this for each output. for i in decode['vin']: assert",
"afford fee. with pytest.raises(RpcError, match=r'Cannot afford transaction'): l1.rpc.withdraw(waddr, 'all') #",
"len(decode['vin']) == 4 assert len(decode['vout']) == 1 if not chainparams['feeoutput']",
"# Check that there are no unconfirmed outputs (change should",
"= 0 else: assert False # Those spent outputs are",
"test does a 'listtransactions' on a yet unconfirmed channel def",
"... and all other output should be change, and have",
"pytest.raises(RpcError): l1.rpc.withdraw('tb1pw508d6qejxtdg4y5r3zarvary0c5xw7kdl9fad', 2 * amount) with pytest.raises(RpcError): l1.rpc.withdraw('tb1qw508d6qejxtdg4y5r3zarvary0c5xw7kxxxxxx', 2 *",
"assert output['address'] == addr @unittest.skipIf(not COMPAT, \"needs COMPAT=1\") def test_deprecated_txprepare(node_factory,",
"unreleased txid'): l1.rpc.txdiscard(prep['txid']) prep = l1.rpc.txprepare([{addr: 'all'}]) decode = bitcoind.rpc.decoderawtransaction(prep['unsigned_tx'])",
"when started without key password = \"<PASSWORD>\" # We need",
"in l1.rpc.listfunds()['outputs']] def test_txprepare_restart(node_factory, bitcoind, chainparams): amount = 1000000 l1",
"encrypted with hsmtool cmd_line[1] = \"decrypt\" subprocess.check_call(cmd_line) l1.daemon.opts.pop(\"encrypted-hsm\") l1.daemon.start(stdin=slave_fd, wait_for_initialized=True)",
"False # Those spent outputs are gone, but change output",
"# Test withdrawal to self. l1.rpc.withdraw(l1.rpc.newaddr('bech32')['bech32'], 'all', minconf=0) bitcoind.generate_block(1) assert",
"P2WSH # Address from: https://bc-2.jp/tools/bech32demo/index.html waddr = 'bcrt1qrp33g0q5c5txsp9arysrx4k6zdkfs4nce4xj0gdcccefvpysxf3qzf4jry' with pytest.raises(RpcError):",
"not encrypted hsm_secret l1.stop() l1.daemon.opts.update({\"encrypted-hsm\": None}) l1.daemon.start(stdin=slave_fd, wait_for_initialized=False) l1.daemon.wait_for_log(r'The hsm_secret",
"100000)}]) decode = bitcoind.rpc.decoderawtransaction(prep5['unsigned_tx']) assert decode['txid'] == prep5['txid'] # 4",
"1 if not chainparams['feeoutput'] else 2 # Some fees will",
"# All 10 inputs assert len(decode['vin']) == 10 # This",
"backwards in blockchain just in case there was a reorg.",
"l1.rpc.listfunds()['outputs']] def test_txprepare_restart(node_factory, bitcoind, chainparams): amount = 1000000 l1 =",
"again l1.rpc.txdiscard(prep5['txid']) with pytest.raises(RpcError, match=r'this destination wants all satoshi. The",
"l1.rpc.call('txprepare', [addr, Millisatoshi(amount * 100), 'slow', 1]) l1.rpc.call('txprepare', [addr, Millisatoshi(amount",
"l3 = node_factory.get_nodes(3) l1.fundwallet(10**6) # We should now have a",
"the output reading 'deposit' txs = l1.rpc.listtransactions()['transactions'] assert(len(txs) == 1)",
"10**3) bitcoind.generate_block(1) l1.daemon.wait_for_log('Owning output .* txid {} CONFIRMED'. format(withdraw[\"txid\"])) decoded",
"amount) # Invalid witness version with pytest.raises(RpcError): l1.rpc.withdraw('BC13W508D6QEJXTDG4Y5R3ZARVARY0C5XW7KN40WF2', 2 *",
"WHERE status=0')[0]['c'] == 6 # Test withdrawal to self. l1.rpc.withdraw(l1.rpc.newaddr('bech32')['bech32'],",
"outputs can\\'t be more than 1'): prep5 = l1.rpc.txprepare([{addr: Millisatoshi(amount",
"The address we detect must match what was paid to.",
"Change address should appear in listfunds() assert decode['vout'][changenum]['scriptPubKey']['addresses'][0] in [f['address']",
"10**3)[\"tx\"] nlocktime = node_factory.bitcoind.rpc.decoderawtransaction(tx)[\"locktime\"] tip = node_factory.bitcoind.rpc.getblockcount() assert nlocktime >",
"l1.db_query('SELECT COUNT(*) as c FROM outputs WHERE status=0')[0]['c'] == 0",
"== 4 vins = [\"{}:{}\".format(v['txid'], v['vout']) for v in decode['vin']]",
"address.*'): l1.rpc.call('txprepare', [Millisatoshi(amount * 100), 'slow', 1]) l1.rpc.call('txprepare', [addr, Millisatoshi(amount",
"attempt to withdraw some (making sure we collect multiple inputs)",
"we have a fee output). assert len(decode['vin']) == 4 assert",
"runs. l1 = node_factory.get_node(random_hsm=True) addr = l1.rpc.newaddr()['bech32'] # Add some",
"our money to a P2WPKH address this time. addr ="
] |
[
"transfer=cn.TRANSFER_DEFAULT, other_transfer=None, is_difference_frac=False, is_differenced=False, is_center_colorbar=True, is_compress=False, parms=PlotParms(), **kwargs): \"\"\" Constructs",
"self._plotSiglvlDF(transfer=transfer, other_transfer=other_transfer, max_siglvl=max_siglvl) self._plotTransferCompare(df_plot, heat_range = [COLORBAR_MIN, COLORBAR_MAX], ordered_mutations=self.cofraction.ordered_mutations, transfer=transfer,",
"considered :return pd.DataFrame: row index and columns are mutations \"\"\"",
"Matplotlib.Axes ax: :param PlotParms parms: Parameters for the plot :param",
"is_differenced: Computes the difference in count fractions :param dict kwargs:",
"if is_differenced: df = self.cofraction.makeCofractionDifferencedDF( transfer=transfer, other_transfer=other_transfer, threshold_frac=threshold_frac) else: df",
"parms[cn.PLT_XAXISTICKTOP] = True else: parms[cn.PLT_XAXISTICKTOP] = False if idx ==",
"0 values :return pd.DataFrame: columns, rows are mutations \"\"\" if",
"v) # Do the plot if not cn.PLT_FIGSIZE in parms:",
"ax.set_xlabel(self._mutation_column, fontsize=FONTSIZE_LABEL) if parms.isTrue(cn.PLT_LEGEND): ax.legend(loc=(1,2)) #ax.legend() if is_plot: plt.show() return",
"= genome_correlation.makeSiglvlDF(df_binary_rows, df_other=df_binary_columns) return df_matrix def _plotSiglvlDF(self, transfer=cn.TRANSFER_DEFAULT, other_transfer=None, max_siglvl=MAX_SIGLVL):",
"correlation significance levels. :param bool is_time_lag: construct time lag subplots",
"df_binary_rows = makeDF(transfer) df_binary_columns = makeDF(other_transfer) df_matrix = genome_correlation.makeSiglvlDF(df_binary_rows, df_other=df_binary_columns)",
"other_transfer=None, min_fraction=MIN_FRACTION): \"\"\" Creates a significance level matrix for mutations.",
":param bool is_center_colorbar: center the colorbar in the plot :param",
"\"%s Mutations\" % SPECIES[self._species] xpos = int(len(df_plot)*0.5) ypos = MAX_LINES",
"as cn from microbepy.common.dataframe_sorter import DataframeSorter from microbepy.common.isolate import Isolate",
"two transfers. :param pd.DataFrame df_plot: index and columns are mutations;",
":return pd.DataFrame: mutations, mutations, values are -log10 significance level \"\"\"",
"is_unit_fraction: round fraction to 1 :param bool is_cluster_mutations: Group similar",
"row=mutation, col=line + transfer, value is fraction \"\"\" permitted_mutations =",
"how='all', inplace=True) df.dropna(axis=1, how='all', inplace=True) is_include_missing_mutations = False else: is_include_missing_mutations",
"the heatmap. :param bool is_time_lag: construct time lag subplots :param",
"transfers, value is data_frame \"\"\" NCOLS = 3 plot_pos =",
"is_unit_fraction=False, is_plot=None, ax=None, permitted_mutations=None): \"\"\" Does a stacked bar plot",
"other_transfer=other_transfer) sorter = DataframeSorter(df_matrix) df_sort = sorter.orderBoth() # df_transformed =",
"= makeLabel(other_transfer, self._mutation_column) parms[cn.PLT_YLABEL] = makeLabel( transfer, self._mutation_column) ax.text(xpos, ypos,",
"= [] for idx, transfer in enumerate(transfers): parms[cn.PLT_YTICKLABELS] = True",
"seaborn as sns COLORS = ['red', 'green', 'blue'] SPECIES =",
"are -log10 significance level \"\"\" df_matrix = self._makeMutationSiglvlMatrix(transfer=transfer, other_transfer=other_transfer) sorter",
"\"\"\"Provides plots of mutations for Isolates and Lines.\"\"\" from microbepy.common",
"Lines\" else: label = \"Fraction\" ax.set_ylabel(label , fontsize=FONTSIZE_LABEL) if parms.isTrue(cn.PLT_XLABEL):",
"else: cb = fig.colorbar(plot, cmap='jet') cb.ax.tick_params(labelsize=parms.fontsize_label) row_labels = df_plot.columns.tolist() col_labels",
"_plotTransfers(self, funcDF, is_time_lag, parms=PlotParms(), **kwargs): \"\"\" Does a subplots of",
"level :return dict: key is pair of transfers, value is",
"directive :param bool is_include_missing_mutations: \"\"\" def makeLabel(transfer, column, is_include_column=False): if",
"= True else: parms[cn.PLT_YLABEL] = False if idx < num_transfers",
"util_data from microbepy.plot.mutation_cofraction import MutationCofraction from microbepy.plot.util_plot import PlotParms import",
":return pd.DataFrame: columns, rows are mutations \"\"\" df_plot = self._plotSiglvlDF(transfer=transfer,",
"else v) self._plotTransferCompare(df, transfer=transfer, other_transfer=other_transfer, ordered_columns=self.cofraction.ordered_mutations, is_center_colorbar=True, fig=fig, ax=ax, parms=parms,",
"other_transfer=other_transfer, is_center_colorbar=is_center_colorbar, **kwargs) return df_plot def plotCofraction(self, threshold_frac=THRESHOLD_FRAC, transfer=cn.TRANSFER_DEFAULT, other_transfer=None,",
"other_transfer=other_transfer) df = df.applymap(lambda v: np.nan if v == 0",
"parms=PlotParms(), **kwargs): \"\"\" Does a subplots of the fraction of",
"numpy as np import pandas as pd import seaborn as",
"in the plot :param float, float: values on the heatmap",
"is_plot = False else: is_plot = True if idx in",
"Lines. \"\"\" def __init__(self, mutation_column=cn.GGENE_ID, species=None, is_plot=True): \"\"\" :param str",
"= df_line.applymap( lambda v: 0 if np.isnan(v) else v) df_binary",
"1.0 COLORBAR_MAX = 4.0 class MutationLinePlot(object): \"\"\" Plot mutations by",
"is_plot=False, ax=axes[idx], permitted_mutations=permitted_mutations, is_unit_fraction=is_unit_fraction) df[cn.TRANSFER] = transfer dfs.append(df) if self._is_plot:",
"\"\"\" Constructs a heatmap of the mutation coocurrence significance levels.",
"else: parms[cn.PLT_YLABEL] = False if idx < num_transfers - 1:",
"inplace=True) is_include_missing_mutations = False else: is_include_missing_mutations = True ordered_columns =",
"result[pair] = df return result def plotSiglvl(self, max_siglvl=MAX_SIGLVL, transfer=cn.TRANSFER_DEFAULT, other_transfer=None,",
"import genome_correlation from microbepy.data.model_data_provider import ModelDataProvider from microbepy.data import util_data",
"new_labels = np.repeat(\"\", len(labels)) ax.set_yticklabels(new_labels) if cn.PLT_TITLE in parms: title",
"plotCofractions(self, is_time_lag=False, threshold_frac=THRESHOLD_FRAC, is_difference_frac=False, is_differenced=False, is_compress=False, parms=PlotParms(), **kwargs): \"\"\" Does",
"plot if not cn.PLT_FIGSIZE in parms: parms[cn.PLT_FIGSIZE] = (12, 8)",
"= True else: parms[cn.PLT_COLORBAR] = False transfer = pair[0] other_transfer",
"fractions :param bool is_compress: Eliminate rows/columns with 0 values :return",
":param bool is_compress: Eliminate rows/columns with 0 values :return pd.DataFrame:",
"= (12, 8) if ax is None: ax = df_plot.plot(kind='bar',",
"else: df = self.cofraction.makeCofractionDF(transfer=transfer, is_difference_frac=is_difference_frac, other_transfer=other_transfer) if is_compress: df.dropna(axis=0, how='all',",
"inplace=True) return df # return self._plotTransfers(funcDF, is_time_lag, parms=parms, heat_range=[0, 1.0],",
"self.cofraction.ordered_mutations transfers = self.cofraction.transfers num_transfers = len(transfers) fig, axes =",
"df.fillna(0) # Set up for plots nrows = 2 if",
"= -np.log10(max_siglvl) df_plot = df_transformed.applymap( lambda v: np.nan if v",
"a subplots of the fraction of lines in which mutations",
":param int transfer: :param float max_siglvl: :return pd.DataFrame: mutations, mutations,",
"if ordered_columns is None: ordered_columns = list(set(df_plot.columns.tolist()).union( df_plot.index)) # Do",
"label def setValue(a_dict, key, default): if not key in a_dict.keys():",
"a significance level matrix for mutations. :param int transfer: transfer",
"**kwargs) return df def _plotTransferCompare(self, df_plot, heat_range, ordered_columns=None, is_center_colorbar=True, transfer=cn.TRANSFER_DEFAULT,",
"self._is_plot: plt.show() return pd.concat(dfs) def plotLine(self, transfer, parms=PlotParms(is_initialize=False), is_unit_fraction=False, is_plot=None,",
"heatmap comparing values for mutations from two transfers. :param pd.DataFrame",
"from microbepy.data import util_data from microbepy.plot.mutation_cofraction import MutationCofraction from microbepy.plot.util_plot",
"parms[cn.PLT_TITLE] = \"%d\" % transfer else: parms[cn.PLT_TITLE] = \"%s, %d\"",
"as plt import numpy as np import pandas as pd",
"height cbaxes = fig.add_axes([.45, 0.2, 0.01, 0.5]) cb = fig.colorbar(plot,",
"from microbepy.common.isolate import Isolate from microbepy.common import util from microbepy.correlation",
"0.01, 0.5]) cb = fig.colorbar(plot, cax = cbaxes, cmap='jet') cb.ax.tick_params(labelsize=parms.fontsize_label)",
"[COLORBAR_MIN, COLORBAR_MAX], **kwargs) def _plotTransfers(self, funcDF, is_time_lag, parms=PlotParms(), **kwargs): \"\"\"",
"= 0.2 MAX_SIGLVL = 0.01 COLORBAR_MIN = 1.0 COLORBAR_MAX =",
"parms.setTrueIfAbsent(cn.PLT_XLABEL) parms.setTrueIfAbsent(cn.PLT_XTICKLABELS) # df_plot = self.cofraction.makeLineDF( permitted_mutations=permitted_mutations, transfer=transfer) if is_unit_fraction:",
"#ax.legend() if is_plot: plt.show() return df_plot def _makeMutationSiglvlMatrix(self, transfer=cn.TRANSFER_DEFAULT, other_transfer=None,",
"else 0) return df_binary.transpose() # if other_transfer is None: other_transfer",
"9 MIN_FRACTION = 0.25 THRESHOLD_FRAC = 0.2 MAX_SIGLVL = 0.01",
"a stacked bar plot of mutation frequency by line with",
"fontsize=FONTSIZE_LABEL) if parms.isTrue(cn.PLT_LEGEND): ax.legend(loc=(1,2)) #ax.legend() if is_plot: plt.show() return df_plot",
"species self.cofraction = MutationCofraction(species=self._species, mutation_column=mutation_column) def plotTransfers(self, parms=PlotParms(is_initialize=False), is_unit_fraction =",
"4.0 class MutationLinePlot(object): \"\"\" Plot mutations by occurrences within Lines.",
"significance levels. :param bool is_time_lag: construct time lag subplots :param",
"columns are mutations \"\"\" def makeDF(transfer): df_line = self.cofraction.makeLineDF(transfer=transfer) df_binary",
"df = self.cofraction.makeCofractionDF(transfer=transfer, is_difference_frac=is_difference_frac, other_transfer=other_transfer, **kwargs) df = df.applymap(lambda v:",
"max_siglvl=max_siglvl) self._plotTransferCompare(df_plot, heat_range = [COLORBAR_MIN, COLORBAR_MAX], ordered_mutations=self.cofraction.ordered_mutations, transfer=transfer, other_transfer=other_transfer, is_center_colorbar=is_center_colorbar,",
"= df.fillna(0) # Set up for plots nrows = 2",
"ordered_columns rows = df_plot.index.tolist() columns = df_plot.columns.tolist() mutations = df_plot.columns.tolist()",
"MIN_FRACTION = 0.25 THRESHOLD_FRAC = 0.2 MAX_SIGLVL = 0.01 COLORBAR_MIN",
"which mutations co-occur. :param bool is_time_lag: construct time lag subplots",
"**kwargs): \"\"\" Does a subplots of mutation correlation significance levels.",
"to use and how they are ordered if None, then",
"np.nan if v < threshold_frac else v) if is_compress: df.dropna(axis=0,",
":] = np.nan df_plot = df_plot.reindex(extended_ordered_columns) df_plot = df_plot[extended_ordered_columns] rows",
"ordered_columns: order in which columns appear :param bool is_center_colorbar: center",
"in parms: parms[cn.PLT_FIGSIZE] = (12, 8) if ax is None:",
"if parms.isTrue(cn.PLT_LEGEND): ax.legend(loc=(1,2)) #ax.legend() if is_plot: plt.show() return df_plot def",
":param bool is_plot: \"\"\" self._mutation_column = mutation_column self._is_plot = is_plot",
"new_labels = np.repeat(\"\", len(labels)) ax.set_xticklabels(new_labels) if parms.isFalse(cn.PLT_YTICKLABELS): labels = ax.get_yticklabels()",
"df.dropna(axis=1, how='all', inplace=True) is_include_missing_mutations = False else: is_include_missing_mutations = True",
"MutationCofraction from microbepy.plot.util_plot import PlotParms import matplotlib.pyplot as plt import",
"(transfer, column) else: label = \"%d\" % transfer return label",
"transfers = self.cofraction.transfers if is_time_lag: pairs = [p for p",
"parms.isTrue(cn.PLT_XLABEL): ax.set_xlabel(self._mutation_column, fontsize=FONTSIZE_LABEL) if parms.isTrue(cn.PLT_LEGEND): ax.legend(loc=(1,2)) #ax.legend() if is_plot: plt.show()",
"which columns appear :param bool is_center_colorbar: center the colorbar in",
"fraction to 1 :param bool is_cluster_mutations: Group similar mutations together",
"mutation frequency by line with colors :params int transfer: :params",
"return result def plotSiglvl(self, max_siglvl=MAX_SIGLVL, transfer=cn.TRANSFER_DEFAULT, other_transfer=None, is_center_colorbar = True,",
"label = \"%d-%s\" % (transfer, column) else: label = \"%d\"",
"self._makeMutationSiglvlMatrix(transfer=transfer, other_transfer=other_transfer) sorter = DataframeSorter(df_matrix) df_sort = sorter.orderBoth() # df_transformed",
"rows/columns with 0 values :return pd.DataFrame: columns, rows are mutations",
"in parms: parms[cn.PLT_COLORBAR] = True if other_transfer is None: other_transfer",
"the mutation coocurrence significance levels. :param float max_siglvl: maximum significance",
"1.0 if v > min_fraction else 0) return df_binary.transpose() #",
"mutations, mutations, values are -log10 significance level \"\"\" df_matrix =",
"plotTransfers(self, parms=PlotParms(is_initialize=False), is_unit_fraction = False, is_cluster_mutations=True): \"\"\" Does a stacked",
"sorter = DataframeSorter(df_matrix) df_sort = sorter.orderBoth() # df_transformed = df_sort.applymap(lambda",
"COLORBAR_MAX = 4.0 class MutationLinePlot(object): \"\"\" Plot mutations by occurrences",
"df.dropna(axis=0, how='all', inplace=True) df.dropna(axis=1, how='all', inplace=True) is_include_missing_mutations = False else:",
"**kwargs): \"\"\" Constructs a heatmap of the mutation coocurrence fractions.",
"is pair of transfers, value is data_frame \"\"\" NCOLS =",
":param bool is_unit_fraction: round fraction to 1 :param bool is_cluster_mutations:",
"df def _plotTransferCompare(self, df_plot, heat_range, ordered_columns=None, is_center_colorbar=True, transfer=cn.TRANSFER_DEFAULT, other_transfer=None, ax=None,",
"transfers. :param pd.DataFrame df_plot: index and columns are mutations; values",
"microbepy.common.dataframe_sorter import DataframeSorter from microbepy.common.isolate import Isolate from microbepy.common import",
"lambda v: np.nan if v < ubound else v) sorter",
"0.2, 0.01, 0.5]) cb = fig.colorbar(plot, cax = cbaxes, cmap='jet')",
"df_plot.columns.tolist() else: extended_ordered_columns = ordered_columns rows = df_plot.index.tolist() columns =",
"other_transfer: Allow comparisons across time :param Matplotlib.Axes ax: :param PlotParms",
"is_center_colorbar: # Colorbar positions: left, bottom, width, height cbaxes =",
"= sorter.orderBoth() # df_transformed = df_sort.applymap(lambda v: np.log10(v)) df_transformed =",
"comparing values for mutations from two transfers. :param pd.DataFrame df_plot:",
"True else: parms[cn.PLT_XAXISTICKTOP] = False if idx == 4: parms[cn.PLT_COLORBAR]",
"fig=fig, ax=ax, parms=parms, is_plot=is_plot, **kwargs) result[pair] = df return result",
"Eliminate rows/columns with 0 values :return pd.DataFrame: columns, rows are",
"is None: if fig is None: fig = plt.figure(figsize=parms[cn.PLT_FIGSIZE]) ax",
"bool is_differenced: Computes the difference in count fractions :param bool",
":param int other_transfer: Allow comparisons across time :param Matplotlib.Axes ax:",
"cn from microbepy.common.dataframe_sorter import DataframeSorter from microbepy.common.isolate import Isolate from",
"import util from microbepy.correlation import genome_correlation from microbepy.data.model_data_provider import ModelDataProvider",
"= len(transfers) fig, axes = plt.subplots(nrows=num_transfers, ncols=1) dfs = []",
"3 ax.text(xpos, ypos, title, fontsize=FONTSIZE_TITLE) ax.set_ylim([0, MAX_LINES]) if parms.isTrue(cn.PLT_YLABEL): if",
"ax.get_yticklabels() new_labels = np.repeat(\"\", len(labels)) ax.set_yticklabels(new_labels) if cn.PLT_TITLE in parms:",
"= df_plot.reindex(extended_ordered_columns) df_plot = df_plot[extended_ordered_columns] rows = df_plot.columns.tolist() columns =",
"zip(transfers[:-1], transfers[:-1])] # # Calculate the column order df =",
"**kwargs): \"\"\" Constructs a heatmap of the mutation coocurrence significance",
"parms.isFalse(cn.PLT_XTICKLABELS): labels = ax.get_xticklabels() new_labels = np.repeat(\"\", len(labels)) ax.set_xticklabels(new_labels) if",
"def makeDF(transfer): df_line = self.cofraction.makeLineDF(transfer=transfer) df_binary = df_line.applymap( lambda v:",
"PlotParms parms: :params Axis ax: axis to use in plot",
"def __init__(self, mutation_column=cn.GGENE_ID, species=None, is_plot=True): \"\"\" :param str mutation_column: :param",
"\"MMP\", None: \"both\"} FONTSIZE_TITLE = 16 FONTSIZE_LABEL = 8 MAX_LINES",
"self._species = species self.cofraction = MutationCofraction(species=self._species, mutation_column=mutation_column) def plotTransfers(self, parms=PlotParms(is_initialize=False),",
"parms=parms, heat_range = [COLORBAR_MIN, COLORBAR_MAX], **kwargs) def _plotTransfers(self, funcDF, is_time_lag,",
"are mutations \"\"\" df_plot = self._plotSiglvlDF(transfer=transfer, other_transfer=other_transfer, max_siglvl=max_siglvl) self._plotTransferCompare(df_plot, heat_range",
"Set up plot information parms[cn.PLT_XLABEL] = \"\" setValue(parms, cn.PLT_COLORBAR, True)",
"Parameters for the plot :param bool is_plot: Overrides constructor plotting",
"matrix for mutations. :param int transfer: transfer time for row",
"count fractions :param bool is_compress: Eliminate rows/columns with 0 values",
"df_other=df_binary_columns) return df_matrix def _plotSiglvlDF(self, transfer=cn.TRANSFER_DEFAULT, other_transfer=None, max_siglvl=MAX_SIGLVL): \"\"\" Constructs",
"v) self._plotTransferCompare(df, transfer=transfer, other_transfer=other_transfer, ordered_columns=self.cofraction.ordered_mutations, is_center_colorbar=True, fig=fig, ax=ax, parms=parms, is_plot=is_plot,",
"transfer # df_binary_rows = makeDF(transfer) df_binary_columns = makeDF(other_transfer) df_matrix =",
"threshold_frac else v) else: df = self.cofraction.makeCofractionDF(transfer=transfer, is_difference_frac=is_difference_frac, other_transfer=other_transfer, **kwargs)",
"is_difference_frac=False, is_differenced=False, is_center_colorbar=True, is_compress=False, parms=PlotParms(), **kwargs): \"\"\" Constructs a heatmap",
"= fig.add_subplot(1, 1, 1) # Order the columns if is_include_missing_mutations:",
"ax.set_yticklabels(col_labels, fontsize=parms.fontsize_label) #parms[cn.PLT_YLABEL] = \"\" parms.do(is_plot=False) if is_plot: parms[cn.PLT_YLABEL] =",
"(self._species, transfer) if idx == 0: parms[cn.PLT_YLABEL] = True else:",
"fontsize=FONTSIZE_TITLE) ax.set_ylim([0, MAX_LINES]) if parms.isTrue(cn.PLT_YLABEL): if is_unit_fraction: label = \"No.",
"= 16 FONTSIZE_LABEL = 8 MAX_LINES = 9 MIN_FRACTION =",
"self._mutation_column) ax.text(xpos, ypos, xlabel, fontsize=parms.fontsize_label) # # Construct the plot",
"is_plot = self._is_plot elif not self._is_plot: is_plot = self._is_plot if",
"parms: parms[cn.PLT_FIGSIZE] = (12, 8) if ax is None: ax",
"mutation mutations over transfers. :param Function funcDF: has kwargs transfer,",
"is data_frame \"\"\" def funcDF(transfer, other_transfer): if is_differenced: df =",
"of transfers, value is data_frame \"\"\" NCOLS = 3 plot_pos",
"if is_plot is None: is_plot = self._is_plot elif not self._is_plot:",
"cbaxes = fig.add_axes([.45, 0.2, 0.01, 0.5]) cb = fig.colorbar(plot, cax",
"row_labels = df_plot.columns.tolist() col_labels = df_plot.index.tolist() if parms.isTrue(cn.PLT_XAXISTICKTOP): ax.xaxis.tick_top() ax.set_xticks(np.arange(0.5,",
"transfers. :param bool is_unit_fraction: round fraction to 1 :param bool",
"if fig is None: fig = plt.figure(figsize=parms[cn.PLT_FIGSIZE]) ax = fig.add_subplot(1,",
"8 MAX_LINES = 9 MIN_FRACTION = 0.25 THRESHOLD_FRAC = 0.2",
"= 9 MIN_FRACTION = 0.25 THRESHOLD_FRAC = 0.2 MAX_SIGLVL =",
"plotLine(self, transfer, parms=PlotParms(is_initialize=False), is_unit_fraction=False, is_plot=None, ax=None, permitted_mutations=None): \"\"\" Does a",
"and Lines.\"\"\" from microbepy.common import constants as cn from microbepy.common.dataframe_sorter",
"xpos = 1.05*len(columns) ypos = -0.05*len(rows) parms[cn.PLT_XLABEL] = \"\" xlabel",
"time lag subplots :param bool is_differenced: Computes the difference in",
"to 1 :return pd.DataFrame: row=mutation, col=line, value is fraction \"\"\"",
"parms=parms, transfer=transfer, other_transfer=other_transfer, is_center_colorbar=is_center_colorbar, is_include_missing_mutations=is_include_missing_mutations, **kwargs) return df def _plotTransferCompare(self,",
":param float min_fraction: minimum fractional occurrence of a mutation within",
"the heatmap :param list-str ordered_columns: order in which columns appear",
"df_sort = sorter.orderBoth() # df_transformed = df_sort.applymap(lambda v: np.log10(v)) df_transformed",
"makeLabel(transfer, self._mutation_column) xpos = -3 ypos = 0.5*len(rows) ypos =",
"pd.DataFrame: row index and columns are mutations \"\"\" def makeDF(transfer):",
"cn.PLT_COLORBAR, True) xpos = 1.05*len(columns) ypos = -0.05*len(rows) parms[cn.PLT_XLABEL] =",
"how they are ordered if None, then use alphabetical order",
":param int transfer: Transfer for which plot is done :param",
"threshold_frac=THRESHOLD_FRAC, is_difference_frac=False, is_differenced=False, is_compress=False, parms=PlotParms(), **kwargs): \"\"\" Does a subplots",
"level \"\"\" df_matrix = self._makeMutationSiglvlMatrix(transfer=transfer, other_transfer=other_transfer) sorter = DataframeSorter(df_matrix) df_sort",
"pair of transfers, value is data_frame \"\"\" def funcDF(transfer, other_transfer):",
"kwargs: non-transfer parameters passed to next level :return dict: key",
"ax: :param PlotParms parms: Parameters for the plot :param bool",
"col_labels = df_plot.index.tolist() if parms.isTrue(cn.PLT_XAXISTICKTOP): ax.xaxis.tick_top() ax.set_xticks(np.arange(0.5, len(row_labels))) ax.set_xticklabels(row_labels, rotation=90,",
":param int transfer: transfer time for row mutations :param int",
"= np.repeat(\"\", len(labels)) ax.set_yticklabels(new_labels) if cn.PLT_TITLE in parms: title =",
"self._is_plot = is_plot self._species = species self.cofraction = MutationCofraction(species=self._species, mutation_column=mutation_column)",
"bar plot of mutation frequency for all transfers. :param bool",
"1 :return pd.DataFrame: row=mutation, col=line, value is fraction \"\"\" if",
"for the plot :param bool is_plot: Overrides constructor plotting directive",
"parms[cn.PLT_COLORBAR] = True if other_transfer is None: other_transfer = transfer",
"= mutation_column self._is_plot = is_plot self._species = species self.cofraction =",
"df_binary_columns = makeDF(other_transfer) df_matrix = genome_correlation.makeSiglvlDF(df_binary_rows, df_other=df_binary_columns) return df_matrix def",
"= \"\" parms.do(is_plot=False) if is_plot: parms[cn.PLT_YLABEL] = \"\" parms.do(is_plot=False) ylabel",
"Does a subplots of the fraction of lines in which",
"lambda v: 1 if v> MIN_FRACTION else v) # Do",
"heatmap. :param int transfer: :param float max_siglvl: :return pd.DataFrame: mutations,",
"if is_plot: parms[cn.PLT_YLABEL] = \"\" parms.do(is_plot=False) ylabel = makeLabel(transfer, self._mutation_column)",
"MAX_LINES - 3 ax.text(xpos, ypos, title, fontsize=FONTSIZE_TITLE) ax.set_ylim([0, MAX_LINES]) if",
"Constructs a heatmap of the mutation coocurrence fractions. :param int",
"df_plot.columns.tolist() mutations = df_plot.columns.tolist() # Set up plot information parms[cn.PLT_XLABEL]",
"transfer: :param int other_transfer: Allow comparisons across time :param Matplotlib.Axes",
"with 0 values :return pd.DataFrame: columns, rows are mutations \"\"\"",
"v) df_binary = df_line.applymap( lambda v: 1.0 if v >",
"return label def setValue(a_dict, key, default): if not key in",
"= self._plotSiglvlDF(transfer=transfer, other_transfer=other_transfer, max_siglvl=max_siglvl) self._plotTransferCompare(df_plot, heat_range = [COLORBAR_MIN, COLORBAR_MAX], ordered_mutations=self.cofraction.ordered_mutations,",
"\"\"\" self._mutation_column = mutation_column self._is_plot = is_plot self._species = species",
"float, float: values on the heatmap range :param int transfer:",
"plots nrows = 2 if (len(pairs) == 4) else 3",
"enumerate(transfers): parms[cn.PLT_YTICKLABELS] = True if self._species is None: parms[cn.PLT_TITLE] =",
"in which mutations co-occur. :param bool is_time_lag: construct time lag",
"self.plotLine(transfer, parms=parms, is_plot=False, ax=axes[idx], permitted_mutations=permitted_mutations, is_unit_fraction=is_unit_fraction) df[cn.TRANSFER] = transfer dfs.append(df)",
"ordered_columns=ordered_columns, parms=parms, transfer=transfer, other_transfer=other_transfer, is_center_colorbar=is_center_colorbar, is_include_missing_mutations=is_include_missing_mutations, **kwargs) return df def",
"xlabel, fontsize=parms.fontsize_label) # # Construct the plot plot = ax.pcolor(df_plot,",
"16 FONTSIZE_LABEL = 8 MAX_LINES = 9 MIN_FRACTION = 0.25",
"= df_plot.columns.tolist() # Set up plot information parms[cn.PLT_XLABEL] = \"\"",
"< len(pairs): is_plot = False else: is_plot = True if",
"COLORBAR_MAX], **kwargs) def _plotTransfers(self, funcDF, is_time_lag, parms=PlotParms(), **kwargs): \"\"\" Does",
"Plot mutations by occurrences within Lines. \"\"\" def __init__(self, mutation_column=cn.GGENE_ID,",
"coocurrence fractions. :param int transfer: Transfer for which plot is",
"Computes the difference in count fractions :param dict kwargs: non-transfer",
"in enumerate(pairs): idx += 1 ax = fig.add_subplot(nrows, NCOLS, plot_pos[idx])",
"of the fraction of lines in which mutations co-occur. :param",
"in count fractions :param bool is_compress: Eliminate rows/columns with 0",
"the dataframe used for heatmap. :param int transfer: :param float",
"Do the plot if not cn.PLT_COLORBAR in parms: parms[cn.PLT_COLORBAR] =",
"values are -log10 significance level \"\"\" df_matrix = self._makeMutationSiglvlMatrix(transfer=transfer, other_transfer=other_transfer)",
"[1, 2, 5]: parms[cn.PLT_XAXISTICKTOP] = True else: parms[cn.PLT_XAXISTICKTOP] = False",
"a_dict.keys(): a_dict[key] = default # if is_plot is None: is_plot",
"other_transfer is None: other_transfer = transfer if ax is None:",
"is_center_colorbar=True, is_compress=False, parms=PlotParms(), **kwargs): \"\"\" Constructs a heatmap of the",
"float max_siglvl: maximum significance level :return pd.DataFrame: columns, rows are",
"= self.cofraction.makeCofractionDF(transfer=transfer, is_difference_frac=is_difference_frac, other_transfer=other_transfer) if is_compress: df.dropna(axis=0, how='all', inplace=True) df.dropna(axis=1,",
"for idx, transfer in enumerate(transfers): parms[cn.PLT_YTICKLABELS] = True if self._species",
"def funcDF(transfer, other_transfer): if is_differenced: df = self.cofraction.makeCofractionDifferencedDF( transfer=transfer, other_transfer=other_transfer,",
"if v> MIN_FRACTION else v) # Do the plot if",
"extended_ordered_columns = ordered_columns rows = df_plot.index.tolist() columns = df_plot.columns.tolist() mutations",
"+ transfer, value is fraction \"\"\" permitted_mutations = self.cofraction.ordered_mutations transfers",
"if parms.isTrue(cn.PLT_XLABEL): ax.set_xlabel(self._mutation_column, fontsize=FONTSIZE_LABEL) if parms.isTrue(cn.PLT_LEGEND): ax.legend(loc=(1,2)) #ax.legend() if is_plot:",
":param bool is_time_lag: construct time lag subplots :param bool is_differenced:",
"implicit label if parms.isFalse(cn.PLT_XTICKLABELS): labels = ax.get_xticklabels() new_labels = np.repeat(\"\",",
"df.dropna(axis=1, how='all', inplace=True) return df # return self._plotTransfers(funcDF, is_time_lag, parms=parms,",
"funcDF(transfer=cn.TRANSFER_1000G, other_transfer=cn.TRANSFER_1000G) df = df.fillna(0) # Set up for plots",
"data_frame \"\"\" def funcDF(transfer, other_transfer): return self._plotSiglvlDF(transfer=transfer, max_siglvl=max_siglvl, other_transfer=other_transfer) #",
"%d\" % (self._species, transfer) if idx == 0: parms[cn.PLT_YLABEL] =",
"is_time_lag: construct time lag subplots :param bool is_differenced: Computes the",
"= self.cofraction.makeLineDF(transfer=transfer) df_binary = df_line.applymap( lambda v: 0 if np.isnan(v)",
"be considered :return pd.DataFrame: row index and columns are mutations",
"= 8 MAX_LINES = 9 MIN_FRACTION = 0.25 THRESHOLD_FRAC =",
"= ax.get_xticklabels() new_labels = np.repeat(\"\", len(labels)) ax.set_xticklabels(new_labels) if parms.isFalse(cn.PLT_YTICKLABELS): labels",
"parameters passed to next level :return dict: key is pair",
"from microbepy.plot.util_plot import PlotParms import matplotlib.pyplot as plt import numpy",
"% SPECIES[self._species] xpos = int(len(df_plot)*0.5) ypos = MAX_LINES - 3",
"list(set(df_plot.columns.tolist()).union( df_plot.index)) # Do the plot if not cn.PLT_COLORBAR in",
"df.applymap(lambda v: np.nan if np.abs(v) < threshold_frac else v) else:",
"np.log10(v)) df_transformed = df_transformed.applymap(lambda v: -v) ubound = -np.log10(max_siglvl) df_plot",
"is_plot: parms[cn.PLT_YLABEL] = \"\" parms.do(is_plot=False) ylabel = makeLabel(transfer, self._mutation_column) xpos",
"= self.cofraction.makeCofractionDifferencedDF( threshold_frac=threshold_frac, transfer=transfer, other_transfer=other_transfer, **kwargs) df = df.applymap(lambda v:",
"cn.PLT_TITLE in parms: title = parms[cn.PLT_TITLE] else: title = \"%s",
"# # Calculate the column order df = funcDF(transfer=cn.TRANSFER_1000G, other_transfer=cn.TRANSFER_1000G)",
"df_transformed = df_transformed.applymap(lambda v: -v) ubound = -np.log10(max_siglvl) df_plot =",
"Does a subplots of mutation mutations over transfers. :param Function",
"parms=parms, heat_range=[0, 1.0], **kwargs) def plotSiglvls(self, is_time_lag=False, max_siglvl=MAX_SIGLVL, parms=PlotParms(), **kwargs):",
"pd.DataFrame: columns, rows are mutations \"\"\" df_plot = self._plotSiglvlDF(transfer=transfer, other_transfer=other_transfer,",
"p in zip(transfers[:-1], transfers[:-1])] # # Calculate the column order",
"= makeDF(other_transfer) df_matrix = genome_correlation.makeSiglvlDF(df_binary_rows, df_other=df_binary_columns) return df_matrix def _plotSiglvlDF(self,",
"with colors :params int transfer: :params PlotParms parms: :params Axis",
"frequency by line with colors :params int transfer: :params PlotParms",
"def plotCofractions(self, is_time_lag=False, threshold_frac=THRESHOLD_FRAC, is_difference_frac=False, is_differenced=False, is_compress=False, parms=PlotParms(), **kwargs): \"\"\"",
"as columns and index; values are used in the heatmap.",
"ax = fig.add_subplot(1, 1, 1) # Order the columns if",
"else: df_plot.plot(kind='bar', stacked=True, legend=None, ax=ax, figsize=parms[cn.PLT_FIGSIZE]) ax.set_xlabel(\"\", fontsize=FONTSIZE_LABEL) # Eliminate",
"ordered_columns=None, is_center_colorbar=True, transfer=cn.TRANSFER_DEFAULT, other_transfer=None, ax=None, fig=None, is_include_missing_mutations=True, parms=PlotParms(), is_plot=None): \"\"\"",
"rows are mutations \"\"\" if is_differenced: df = self.cofraction.makeCofractionDifferencedDF( threshold_frac=threshold_frac,",
"is_unit_fraction: round non-zero fraction to 1 :return pd.DataFrame: row=mutation, col=line,",
"self.cofraction.ordered_mutations self._plotTransferCompare(df, heat_range=[0, 1.0], ordered_columns=ordered_columns, parms=parms, transfer=transfer, other_transfer=other_transfer, is_center_colorbar=is_center_colorbar, is_include_missing_mutations=is_include_missing_mutations,",
"fractions. :param int transfer: Transfer for which plot is done",
"are mutations; values are plotted on the heatmap :param list-str",
"= set(ordered_columns).difference(columns) extended_ordered_columns = list(ordered_columns) extended_ordered_columns.extend( set(columns).difference(ordered_columns)) for col in",
"parms[cn.PLT_LEGEND] = True parms[cn.PLT_XLABEL] = True parms[cn.PLT_XTICKLABELS] = True df",
"max_siglvl: maximum significance level :return pd.DataFrame: columns, rows are mutations",
"= np.nan df_plot.loc[col, :] = np.nan df_plot = df_plot.reindex(extended_ordered_columns) df_plot",
"subplots of the fraction of lines in which mutations co-occur.",
"parms[cn.PLT_XTICKLABELS] = True df = self.plotLine(transfer, parms=parms, is_plot=False, ax=axes[idx], permitted_mutations=permitted_mutations,",
"df_line = self.cofraction.makeLineDF(transfer=transfer) df_binary = df_line.applymap( lambda v: 0 if",
"return self._plotSiglvlDF(transfer=transfer, max_siglvl=max_siglvl, other_transfer=other_transfer) # return self._plotTransfers(funcDF, is_time_lag, parms=parms, heat_range",
"plot_pos = {1:1, 2:3, 3:4, 4:6} NPLOTS = 6 transfers",
"False parms[cn.PLT_XLABEL] = False parms[cn.PLT_XTICKLABELS] = False else: parms[cn.PLT_LEGEND] =",
"line for it to be considered :return pd.DataFrame: row index",
"int other_transfer: Allow comparisons across time :param Matplotlib.Axes ax: :param",
"within Lines. \"\"\" def __init__(self, mutation_column=cn.GGENE_ID, species=None, is_plot=True): \"\"\" :param",
"if parms.isFalse(cn.PLT_YTICKLABELS): labels = ax.get_yticklabels() new_labels = np.repeat(\"\", len(labels)) ax.set_yticklabels(new_labels)",
"transfer=transfer, other_transfer=other_transfer, ordered_columns=self.cofraction.ordered_mutations, is_center_colorbar=True, fig=fig, ax=ax, parms=parms, is_plot=is_plot, **kwargs) result[pair]",
"df = df.fillna(0) # Set up for plots nrows =",
"is_compress=False, parms=PlotParms(), **kwargs): \"\"\" Constructs a heatmap of the mutation",
"= df_transformed.applymap( lambda v: np.nan if v < ubound else",
"bool is_compress: Eliminate rows/columns with 0 values :return pd.DataFrame: columns,",
"is_center_colorbar: center the colorbar in the plot :param float, float:",
"rows are mutations \"\"\" df_plot = self._plotSiglvlDF(transfer=transfer, other_transfer=other_transfer, max_siglvl=max_siglvl) self._plotTransferCompare(df_plot,",
":return pd.DataFrame: row=mutation, col=line + transfer, value is fraction \"\"\"",
"ax=ax, parms=parms, is_plot=is_plot, **kwargs) result[pair] = df return result def",
"1, 1) # Order the columns if is_include_missing_mutations: columns =",
"other_transfer: transfer time for column mutations :param float min_fraction: minimum",
"bool is_differenced: Computes the difference in count fractions :param dict",
"if parms.isTrue(cn.PLT_YLABEL): if is_unit_fraction: label = \"No. Lines\" else: label",
"heat_range, ordered_columns=None, is_center_colorbar=True, transfer=cn.TRANSFER_DEFAULT, other_transfer=None, ax=None, fig=None, is_include_missing_mutations=True, parms=PlotParms(), is_plot=None):",
"= self.cofraction.transfers if is_time_lag: pairs = [p for p in",
"other_transfer=other_transfer, ordered_columns=self.cofraction.ordered_mutations, is_center_colorbar=True, fig=fig, ax=ax, parms=parms, is_plot=is_plot, **kwargs) result[pair] =",
"mutations \"\"\" def makeDF(transfer): df_line = self.cofraction.makeLineDF(transfer=transfer) df_binary = df_line.applymap(",
"is_compress=False, parms=PlotParms(), **kwargs): \"\"\" Does a subplots of the fraction",
"self._plotSiglvlDF(transfer=transfer, max_siglvl=max_siglvl, other_transfer=other_transfer) # return self._plotTransfers(funcDF, is_time_lag, parms=parms, heat_range =",
"THRESHOLD_FRAC = 0.2 MAX_SIGLVL = 0.01 COLORBAR_MIN = 1.0 COLORBAR_MAX",
"fig = plt.figure(figsize=parms[cn.PLT_FIGSIZE]) ax = fig.add_subplot(1, 1, 1) # Order",
"{1:1, 2:3, 3:4, 4:6} NPLOTS = 6 transfers = self.cofraction.transfers",
"= self.cofraction.makeCofractionDF(transfer=transfer, is_difference_frac=is_difference_frac, other_transfer=other_transfer, **kwargs) df = df.applymap(lambda v: np.nan",
"is_differenced: Computes the difference in count fractions :param bool is_compress:",
"Does a stacked bar plot of mutation frequency by line",
"self._plotTransfers(funcDF, is_time_lag, parms=parms, heat_range = [COLORBAR_MIN, COLORBAR_MAX], **kwargs) def _plotTransfers(self,",
"Group similar mutations together :return pd.DataFrame: row=mutation, col=line + transfer,",
"ordered_mutations=self.cofraction.ordered_mutations, transfer=transfer, other_transfer=other_transfer, is_center_colorbar=is_center_colorbar, **kwargs) return df_plot def plotCofraction(self, threshold_frac=THRESHOLD_FRAC,",
"= transfer if ax is None: if fig is None:",
"df = df.applymap(lambda v: np.nan if v == 0 else",
"species=None, is_plot=True): \"\"\" :param str mutation_column: :param bool is_plot: \"\"\"",
"missing_columns: df_plot[col] = np.nan df_plot.loc[col, :] = np.nan df_plot =",
"column, is_include_column=False): if is_include_column: label = \"%d-%s\" % (transfer, column)",
"\"\"\" Creates a significance level matrix for mutations. :param int",
"makeDF(transfer): df_line = self.cofraction.makeLineDF(transfer=transfer) df_binary = df_line.applymap( lambda v: 0",
"= {cn.SPECIES_MIX_DVH: \"DVH\", cn.SPECIES_MIX_MMP: \"MMP\", None: \"both\"} FONTSIZE_TITLE = 16",
"transfer=cn.TRANSFER_DEFAULT, other_transfer=None, max_siglvl=MAX_SIGLVL): \"\"\" Constructs a the dataframe used for",
"row mutations :param int other_transfer: transfer time for column mutations",
"transfer=cn.TRANSFER_DEFAULT, other_transfer=None, ax=None, fig=None, is_include_missing_mutations=True, parms=PlotParms(), is_plot=None): \"\"\" Constructs a",
"v == 0 else v) self._plotTransferCompare(df, transfer=transfer, other_transfer=other_transfer, ordered_columns=self.cofraction.ordered_mutations, is_center_colorbar=True,",
"self._is_plot parms.setTrueIfAbsent(cn.PLT_XLABEL) parms.setTrueIfAbsent(cn.PLT_XTICKLABELS) # df_plot = self.cofraction.makeLineDF( permitted_mutations=permitted_mutations, transfer=transfer) if",
"df # return self._plotTransfers(funcDF, is_time_lag, parms=parms, heat_range=[0, 1.0], **kwargs) def",
"fractions :param dict kwargs: non-transfer parameters passed to next level",
"fontsize=FONTSIZE_LABEL) # Eliminate implicit label if parms.isFalse(cn.PLT_XTICKLABELS): labels = ax.get_xticklabels()",
"is_difference_frac=is_difference_frac, other_transfer=other_transfer, **kwargs) df = df.applymap(lambda v: np.nan if v",
"if ax is None: if fig is None: fig =",
"for p in zip(transfers[:-1], transfers[:-1])] # # Calculate the column",
"max_siglvl=MAX_SIGLVL, parms=PlotParms(), **kwargs): \"\"\" Does a subplots of mutation correlation",
"parms[cn.PLT_FIGSIZE] = (12, 8) if ax is None: ax =",
"is_time_lag, parms=PlotParms(), **kwargs): \"\"\" Does a subplots of mutation mutations",
"None: fig = plt.figure(figsize=parms[cn.PLT_FIGSIZE]) ax = fig.add_subplot(1, 1, 1) #",
"self._is_plot if ordered_columns is None: ordered_columns = list(set(df_plot.columns.tolist()).union( df_plot.index)) #",
"transfer, value is fraction \"\"\" permitted_mutations = self.cofraction.ordered_mutations transfers =",
"values for mutations from two transfers. :param pd.DataFrame df_plot: index",
"Function funcDF: has kwargs transfer, other_transfer; returns a dataframe of",
"# df_binary_rows = makeDF(transfer) df_binary_columns = makeDF(other_transfer) df_matrix = genome_correlation.makeSiglvlDF(df_binary_rows,",
"row=mutation, col=line, value is fraction \"\"\" if is_plot is None:",
"pandas as pd import seaborn as sns COLORS = ['red',",
"% transfer else: parms[cn.PLT_TITLE] = \"%s, %d\" % (self._species, transfer)",
"% (transfer, column) else: label = \"%d\" % transfer return",
"= plt.subplots(nrows=num_transfers, ncols=1) dfs = [] for idx, transfer in",
"fontsize=parms.fontsize_label) #parms[cn.PLT_YLABEL] = \"\" parms.do(is_plot=False) if is_plot: parms[cn.PLT_YLABEL] = \"\"",
"util from microbepy.correlation import genome_correlation from microbepy.data.model_data_provider import ModelDataProvider from",
"cmap='jet', vmin=heat_range[0], vmax=heat_range[1]) if parms.isTrue(cn.PLT_COLORBAR): if is_center_colorbar: # Colorbar positions:",
"ypos = -0.05*len(rows) parms[cn.PLT_XLABEL] = \"\" xlabel = makeLabel(other_transfer, self._mutation_column)",
"ax.text(xpos, ypos, title, fontsize=FONTSIZE_TITLE) ax.set_ylim([0, MAX_LINES]) if parms.isTrue(cn.PLT_YLABEL): if is_unit_fraction:",
"np.repeat(\"\", len(labels)) ax.set_yticklabels(new_labels) if cn.PLT_TITLE in parms: title = parms[cn.PLT_TITLE]",
"is_center_colorbar=True, transfer=cn.TRANSFER_DEFAULT, other_transfer=None, ax=None, fig=None, is_include_missing_mutations=True, parms=PlotParms(), is_plot=None): \"\"\" Constructs",
"parms.isTrue(cn.PLT_YLABEL): if is_unit_fraction: label = \"No. Lines\" else: label =",
"= transfer # df_binary_rows = makeDF(transfer) df_binary_columns = makeDF(other_transfer) df_matrix",
"is_center_colorbar=is_center_colorbar, is_include_missing_mutations=is_include_missing_mutations, **kwargs) return df def _plotTransferCompare(self, df_plot, heat_range, ordered_columns=None,",
"1 ax = fig.add_subplot(nrows, NCOLS, plot_pos[idx]) if idx < len(pairs):",
":params int transfer: :params PlotParms parms: :params Axis ax: axis",
"parms[cn.PLT_LEGEND] = False parms[cn.PLT_XLABEL] = False parms[cn.PLT_XTICKLABELS] = False else:",
"ax.xaxis.tick_top() ax.set_xticks(np.arange(0.5, len(row_labels))) ax.set_xticklabels(row_labels, rotation=90, fontsize=parms.fontsize_label) ax.set_yticks(np.arange(0.5, len(col_labels))) ax.set_yticklabels(col_labels, fontsize=parms.fontsize_label)",
"3:4, 4:6} NPLOTS = 6 transfers = self.cofraction.transfers if is_time_lag:",
"value is data_frame \"\"\" def funcDF(transfer, other_transfer): if is_differenced: df",
"idx == 4: parms[cn.PLT_COLORBAR] = True else: parms[cn.PLT_COLORBAR] = False",
"COLORS = ['red', 'green', 'blue'] SPECIES = {cn.SPECIES_MIX_DVH: \"DVH\", cn.SPECIES_MIX_MMP:",
"= True parms[cn.PLT_XTICKLABELS] = True df = self.plotLine(transfer, parms=parms, is_plot=False,",
"fig.colorbar(plot, cax = cbaxes, cmap='jet') cb.ax.tick_params(labelsize=parms.fontsize_label) else: cb = fig.colorbar(plot,",
"Allow comparisons across time :param Matplotlib.Axes ax: :param PlotParms parms:",
"is_center_colorbar = True, **kwargs): \"\"\" Constructs a heatmap of the",
"= funcDF(transfer=transfer, other_transfer=other_transfer) df = df.applymap(lambda v: np.nan if v",
"False else: parms[cn.PLT_LEGEND] = True parms[cn.PLT_XLABEL] = True parms[cn.PLT_XTICKLABELS] =",
"return df_plot def _makeMutationSiglvlMatrix(self, transfer=cn.TRANSFER_DEFAULT, other_transfer=None, min_fraction=MIN_FRACTION): \"\"\" Creates a",
"df_line.applymap( lambda v: 1.0 if v > min_fraction else 0)",
"Colorbar positions: left, bottom, width, height cbaxes = fig.add_axes([.45, 0.2,",
"if is_center_colorbar: # Colorbar positions: left, bottom, width, height cbaxes",
"dataframe used for heatmap. :param int transfer: :param float max_siglvl:",
"is_time_lag, parms=parms, heat_range=[0, 1.0], **kwargs) def plotSiglvls(self, is_time_lag=False, max_siglvl=MAX_SIGLVL, parms=PlotParms(),",
"True else: parms[cn.PLT_COLORBAR] = False transfer = pair[0] other_transfer =",
"self._plotTransferCompare(df, transfer=transfer, other_transfer=other_transfer, ordered_columns=self.cofraction.ordered_mutations, is_center_colorbar=True, fig=fig, ax=ax, parms=parms, is_plot=is_plot, **kwargs)",
"self.cofraction.makeLineDF( permitted_mutations=permitted_mutations, transfer=transfer) if is_unit_fraction: df_plot = df_plot.applymap( lambda v:",
"as pd import seaborn as sns COLORS = ['red', 'green',",
"for plots nrows = 2 if (len(pairs) == 4) else",
"else: parms[cn.PLT_COLORBAR] = False transfer = pair[0] other_transfer = pair[1]",
"is_unit_fraction = False, is_cluster_mutations=True): \"\"\" Does a stacked bar plot",
"ax.set_xticks(np.arange(0.5, len(row_labels))) ax.set_xticklabels(row_labels, rotation=90, fontsize=parms.fontsize_label) ax.set_yticks(np.arange(0.5, len(col_labels))) ax.set_yticklabels(col_labels, fontsize=parms.fontsize_label) #parms[cn.PLT_YLABEL]",
"is_plot is None: is_plot = self._is_plot parms.setTrueIfAbsent(cn.PLT_XLABEL) parms.setTrueIfAbsent(cn.PLT_XTICKLABELS) # df_plot",
"np.nan df_plot.loc[col, :] = np.nan df_plot = df_plot.reindex(extended_ordered_columns) df_plot =",
"heatmap. :param bool is_time_lag: construct time lag subplots :param dict",
"plot information parms[cn.PLT_XLABEL] = \"\" setValue(parms, cn.PLT_COLORBAR, True) xpos =",
"None: if fig is None: fig = plt.figure(figsize=parms[cn.PLT_FIGSIZE]) ax =",
"= ax.pcolor(df_plot, cmap='jet', vmin=heat_range[0], vmax=heat_range[1]) if parms.isTrue(cn.PLT_COLORBAR): if is_center_colorbar: #",
"0.5]) cb = fig.colorbar(plot, cax = cbaxes, cmap='jet') cb.ax.tick_params(labelsize=parms.fontsize_label) else:",
"= int(len(df_plot)*0.5) ypos = MAX_LINES - 3 ax.text(xpos, ypos, title,",
"== 4) else 3 fig = plt.figure(figsize=parms[cn.PLT_FIGSIZE]) result = {}",
"values on the heatmap range :param int transfer: :param int",
"= True else: parms[cn.PLT_XAXISTICKTOP] = False if idx == 4:",
"len(row_labels))) ax.set_xticklabels(row_labels, rotation=90, fontsize=parms.fontsize_label) ax.set_yticks(np.arange(0.5, len(col_labels))) ax.set_yticklabels(col_labels, fontsize=parms.fontsize_label) #parms[cn.PLT_YLABEL] =",
"MAX_LINES]) if parms.isTrue(cn.PLT_YLABEL): if is_unit_fraction: label = \"No. Lines\" else:",
"\"\"\" Constructs a heatmap of the mutation coocurrence fractions. :param",
"FONTSIZE_TITLE = 16 FONTSIZE_LABEL = 8 MAX_LINES = 9 MIN_FRACTION",
"\"\"\" Plot mutations by occurrences within Lines. \"\"\" def __init__(self,",
"transfer, parms=PlotParms(is_initialize=False), is_unit_fraction=False, is_plot=None, ax=None, permitted_mutations=None): \"\"\" Does a stacked",
"fraction \"\"\" permitted_mutations = self.cofraction.ordered_mutations transfers = self.cofraction.transfers num_transfers =",
"df = funcDF(transfer=transfer, other_transfer=other_transfer) df = df.applymap(lambda v: np.nan if",
"df_plot.plot(kind='bar', stacked=True, legend=None, ax=ax, figsize=parms[cn.PLT_FIGSIZE]) ax.set_xlabel(\"\", fontsize=FONTSIZE_LABEL) # Eliminate implicit",
"is_include_missing_mutations = False else: is_include_missing_mutations = True ordered_columns = self.cofraction.ordered_mutations",
"ax.text(xpos, ypos, xlabel, fontsize=parms.fontsize_label) # # Construct the plot plot",
"heat_range=[0, 1.0], **kwargs) def plotSiglvls(self, is_time_lag=False, max_siglvl=MAX_SIGLVL, parms=PlotParms(), **kwargs): \"\"\"",
"parms.setTrueIfAbsent(cn.PLT_XTICKLABELS) # df_plot = self.cofraction.makeLineDF( permitted_mutations=permitted_mutations, transfer=transfer) if is_unit_fraction: df_plot",
"a subplots of mutation correlation significance levels. :param bool is_time_lag:",
"the difference in count fractions :param bool is_compress: Eliminate rows/columns",
"transfers, value is data_frame \"\"\" def funcDF(transfer, other_transfer): if is_differenced:",
"max_siglvl=MAX_SIGLVL, transfer=cn.TRANSFER_DEFAULT, other_transfer=None, is_center_colorbar = True, **kwargs): \"\"\" Constructs a",
"of a mutation within a line for it to be",
"if is_compress: df.dropna(axis=0, how='all', inplace=True) df.dropna(axis=1, how='all', inplace=True) is_include_missing_mutations =",
"= df_plot.plot(kind='bar', stacked=True, figsize=parms[cn.PLT_FIGSIZE], legend=None) else: df_plot.plot(kind='bar', stacked=True, legend=None, ax=ax,",
"cax = cbaxes, cmap='jet') cb.ax.tick_params(labelsize=parms.fontsize_label) else: cb = fig.colorbar(plot, cmap='jet')",
"plotting directive :param bool is_include_missing_mutations: \"\"\" def makeLabel(transfer, column, is_include_column=False):",
"is_unit_fraction=is_unit_fraction) df[cn.TRANSFER] = transfer dfs.append(df) if self._is_plot: plt.show() return pd.concat(dfs)",
"\"\"\" Does a stacked bar plot of mutation frequency for",
"on the heatmap range :param int transfer: :param int other_transfer:",
"for mutations. :param int transfer: transfer time for row mutations",
":return pd.DataFrame: columns, rows are mutations \"\"\" if is_differenced: df",
"len(col_labels))) ax.set_yticklabels(col_labels, fontsize=parms.fontsize_label) #parms[cn.PLT_YLABEL] = \"\" parms.do(is_plot=False) if is_plot: parms[cn.PLT_YLABEL]",
"mutation coocurrence fractions. :param int transfer: Transfer for which plot",
"# Order the columns if is_include_missing_mutations: columns = df_plot.columns.tolist() missing_columns",
":param int other_transfer: transfer time for column mutations :param float",
"plotted on the heatmap :param list-str ordered_columns: order in which",
"significance level \"\"\" df_matrix = self._makeMutationSiglvlMatrix(transfer=transfer, other_transfer=other_transfer) sorter = DataframeSorter(df_matrix)",
"transfer dfs.append(df) if self._is_plot: plt.show() return pd.concat(dfs) def plotLine(self, transfer,",
"\"%d\" % transfer return label def setValue(a_dict, key, default): if",
"if parms.isTrue(cn.PLT_COLORBAR): if is_center_colorbar: # Colorbar positions: left, bottom, width,",
"False transfer = pair[0] other_transfer = pair[1] df = funcDF(transfer=transfer,",
"constructor plotting directive :param bool is_include_missing_mutations: \"\"\" def makeLabel(transfer, column,",
"= df_plot.columns.tolist() else: extended_ordered_columns = ordered_columns rows = df_plot.index.tolist() columns",
"ypos = -1 ax.set_ylabel(ylabel, fontsize=parms.fontsize_label, x=xpos, y=ypos) #plt.show() parms.do(is_plot=is_plot) else:",
"= True, **kwargs): \"\"\" Constructs a heatmap of the mutation",
"a stacked bar plot of mutation frequency for all transfers.",
"difference in count fractions :param dict kwargs: non-transfer parameters passed",
"rows = df_plot.columns.tolist() columns = df_plot.columns.tolist() else: extended_ordered_columns = ordered_columns",
"True else: parms[cn.PLT_YLABEL] = False if idx < num_transfers -",
"= 2 if (len(pairs) == 4) else 3 fig =",
"v > min_fraction else 0) return df_binary.transpose() # if other_transfer",
"ax: axis to use in plot :param list-str permitted_mutations: to",
"df = df.applymap(lambda v: np.nan if np.abs(v) < threshold_frac else",
"True df = self.plotLine(transfer, parms=parms, is_plot=False, ax=axes[idx], permitted_mutations=permitted_mutations, is_unit_fraction=is_unit_fraction) df[cn.TRANSFER]",
"transfer: :params PlotParms parms: :params Axis ax: axis to use",
"\"\"\" Does a subplots of mutation correlation significance levels. :param",
"\"\"\" NCOLS = 3 plot_pos = {1:1, 2:3, 3:4, 4:6}",
"parms: Parameters for the plot :param bool is_plot: Overrides constructor",
"over transfers. :param Function funcDF: has kwargs transfer, other_transfer; returns",
"parms: parms[cn.PLT_COLORBAR] = True if other_transfer is None: other_transfer =",
"0: parms[cn.PLT_YLABEL] = True else: parms[cn.PLT_YLABEL] = False if idx",
"labels = ax.get_xticklabels() new_labels = np.repeat(\"\", len(labels)) ax.set_xticklabels(new_labels) if parms.isFalse(cn.PLT_YTICKLABELS):",
"column) else: label = \"%d\" % transfer return label def",
"cn.PLT_FIGSIZE in parms: parms[cn.PLT_FIGSIZE] = (12, 8) if ax is",
"False else: is_plot = True if idx in [1, 2,",
"threshold_frac else v) if is_compress: df.dropna(axis=0, how='all', inplace=True) df.dropna(axis=1, how='all',",
"to 1 :param bool is_cluster_mutations: Group similar mutations together :return",
"has kwargs transfer, other_transfer; returns a dataframe of mutations as",
"transfer=transfer, other_transfer=other_transfer, threshold_frac=threshold_frac) else: df = self.cofraction.makeCofractionDF(transfer=transfer, is_difference_frac=is_difference_frac, other_transfer=other_transfer) if",
"if np.abs(v) < threshold_frac else v) else: df = self.cofraction.makeCofractionDF(transfer=transfer,",
"PlotParms import matplotlib.pyplot as plt import numpy as np import",
"key in a_dict.keys(): a_dict[key] = default # if is_plot is",
"if not cn.PLT_COLORBAR in parms: parms[cn.PLT_COLORBAR] = True if other_transfer",
"mutations = df_plot.columns.tolist() # Set up plot information parms[cn.PLT_XLABEL] =",
"cn.PLT_COLORBAR in parms: parms[cn.PLT_COLORBAR] = True if other_transfer is None:",
"other_transfer = pair[1] df = funcDF(transfer=transfer, other_transfer=other_transfer) df = df.applymap(lambda",
":param bool is_include_missing_mutations: \"\"\" def makeLabel(transfer, column, is_include_column=False): if is_include_column:",
"is None: is_plot = self._is_plot parms.setTrueIfAbsent(cn.PLT_XLABEL) parms.setTrueIfAbsent(cn.PLT_XTICKLABELS) # df_plot =",
"of mutation frequency by line with colors :params int transfer:",
"dataframe of mutations as columns and index; values are used",
"= fig.colorbar(plot, cax = cbaxes, cmap='jet') cb.ax.tick_params(labelsize=parms.fontsize_label) else: cb =",
"= {1:1, 2:3, 3:4, 4:6} NPLOTS = 6 transfers =",
"not cn.PLT_COLORBAR in parms: parms[cn.PLT_COLORBAR] = True if other_transfer is",
"mutations over transfers. :param Function funcDF: has kwargs transfer, other_transfer;",
"\"\"\" if is_plot is None: is_plot = self._is_plot parms.setTrueIfAbsent(cn.PLT_XLABEL) parms.setTrueIfAbsent(cn.PLT_XTICKLABELS)",
"not cn.PLT_FIGSIZE in parms: parms[cn.PLT_FIGSIZE] = (12, 8) if ax",
"= 3 plot_pos = {1:1, 2:3, 3:4, 4:6} NPLOTS =",
"4) else 3 fig = plt.figure(figsize=parms[cn.PLT_FIGSIZE]) result = {} for",
"False else: is_include_missing_mutations = True ordered_columns = self.cofraction.ordered_mutations self._plotTransferCompare(df, heat_range=[0,",
"# Eliminate implicit label if parms.isFalse(cn.PLT_XTICKLABELS): labels = ax.get_xticklabels() new_labels",
"df_plot[col] = np.nan df_plot.loc[col, :] = np.nan df_plot = df_plot.reindex(extended_ordered_columns)",
"label if parms.isFalse(cn.PLT_XTICKLABELS): labels = ax.get_xticklabels() new_labels = np.repeat(\"\", len(labels))",
"\"\"\" df_plot = self._plotSiglvlDF(transfer=transfer, other_transfer=other_transfer, max_siglvl=max_siglvl) self._plotTransferCompare(df_plot, heat_range = [COLORBAR_MIN,",
"{} for idx, pair in enumerate(pairs): idx += 1 ax",
"[] for idx, transfer in enumerate(transfers): parms[cn.PLT_YTICKLABELS] = True if",
"parms=parms, is_plot=is_plot, **kwargs) result[pair] = df return result def plotSiglvl(self,",
"is_include_column: label = \"%d-%s\" % (transfer, column) else: label =",
"the difference in count fractions :param dict kwargs: non-transfer parameters",
"transfer, other_transfer; returns a dataframe of mutations as columns and",
"Constructs a heatmap of the mutation coocurrence significance levels. :param",
"is None: parms[cn.PLT_TITLE] = \"%d\" % transfer else: parms[cn.PLT_TITLE] =",
"None: is_plot = self._is_plot parms.setTrueIfAbsent(cn.PLT_XLABEL) parms.setTrueIfAbsent(cn.PLT_XTICKLABELS) # df_plot = self.cofraction.makeLineDF(",
"together :return pd.DataFrame: row=mutation, col=line + transfer, value is fraction",
"bool is_cluster_mutations: Group similar mutations together :return pd.DataFrame: row=mutation, col=line",
"in plot :param list-str permitted_mutations: to use and how they",
"data_frame \"\"\" def funcDF(transfer, other_transfer): if is_differenced: df = self.cofraction.makeCofractionDifferencedDF(",
"6 transfers = self.cofraction.transfers if is_time_lag: pairs = [p for",
"= MutationCofraction(species=self._species, mutation_column=mutation_column) def plotTransfers(self, parms=PlotParms(is_initialize=False), is_unit_fraction = False, is_cluster_mutations=True):",
"v: np.nan if np.abs(v) < threshold_frac else v) else: df",
"for it to be considered :return pd.DataFrame: row index and",
"from microbepy.common.dataframe_sorter import DataframeSorter from microbepy.common.isolate import Isolate from microbepy.common",
"Creates a significance level matrix for mutations. :param int transfer:",
"\"\"\" def makeDF(transfer): df_line = self.cofraction.makeLineDF(transfer=transfer) df_binary = df_line.applymap( lambda",
"= fig.add_subplot(nrows, NCOLS, plot_pos[idx]) if idx < len(pairs): is_plot =",
"parms.isTrue(cn.PLT_XAXISTICKTOP): ax.xaxis.tick_top() ax.set_xticks(np.arange(0.5, len(row_labels))) ax.set_xticklabels(row_labels, rotation=90, fontsize=parms.fontsize_label) ax.set_yticks(np.arange(0.5, len(col_labels))) ax.set_yticklabels(col_labels,",
"if cn.PLT_TITLE in parms: title = parms[cn.PLT_TITLE] else: title =",
"transfers, value is data_frame \"\"\" def funcDF(transfer, other_transfer): return self._plotSiglvlDF(transfer=transfer,",
"occurrence of a mutation within a line for it to",
"True if self._species is None: parms[cn.PLT_TITLE] = \"%d\" % transfer",
"is data_frame \"\"\" NCOLS = 3 plot_pos = {1:1, 2:3,",
"in parms: title = parms[cn.PLT_TITLE] else: title = \"%s Mutations\"",
"the plot if not cn.PLT_FIGSIZE in parms: parms[cn.PLT_FIGSIZE] = (12,",
"threshold_frac=threshold_frac) else: df = self.cofraction.makeCofractionDF(transfer=transfer, is_difference_frac=is_difference_frac, other_transfer=other_transfer) if is_compress: df.dropna(axis=0,",
"= df_plot.columns.tolist() mutations = df_plot.columns.tolist() # Set up plot information",
"is_plot=True): \"\"\" :param str mutation_column: :param bool is_plot: \"\"\" self._mutation_column",
"of mutation mutations over transfers. :param Function funcDF: has kwargs",
"mutation coocurrence significance levels. :param float max_siglvl: maximum significance level",
"import PlotParms import matplotlib.pyplot as plt import numpy as np",
"transfer=transfer) if is_unit_fraction: df_plot = df_plot.applymap( lambda v: 1 if",
"other_transfer = transfer if ax is None: if fig is",
"class MutationLinePlot(object): \"\"\" Plot mutations by occurrences within Lines. \"\"\"",
"are mutations \"\"\" def makeDF(transfer): df_line = self.cofraction.makeLineDF(transfer=transfer) df_binary =",
"np.isnan(v) else v) df_binary = df_line.applymap( lambda v: 1.0 if",
"df[cn.TRANSFER] = transfer dfs.append(df) if self._is_plot: plt.show() return pd.concat(dfs) def",
"row index and columns are mutations \"\"\" def makeDF(transfer): df_line",
"title = parms[cn.PLT_TITLE] else: title = \"%s Mutations\" % SPECIES[self._species]",
"colorbar in the plot :param float, float: values on the",
"Construct the plot plot = ax.pcolor(df_plot, cmap='jet', vmin=heat_range[0], vmax=heat_range[1]) if",
"int other_transfer: transfer time for column mutations :param float min_fraction:",
"plot :param float, float: values on the heatmap range :param",
"0.2 MAX_SIGLVL = 0.01 COLORBAR_MIN = 1.0 COLORBAR_MAX = 4.0",
"a heatmap comparing values for mutations from two transfers. :param",
"= False else: parms[cn.PLT_LEGEND] = True parms[cn.PLT_XLABEL] = True parms[cn.PLT_XTICKLABELS]",
"Do the plot if not cn.PLT_FIGSIZE in parms: parms[cn.PLT_FIGSIZE] =",
"None: \"both\"} FONTSIZE_TITLE = 16 FONTSIZE_LABEL = 8 MAX_LINES =",
"0 if np.isnan(v) else v) df_binary = df_line.applymap( lambda v:",
"v: np.nan if v < ubound else v) sorter =",
"plot_pos[idx]) if idx < len(pairs): is_plot = False else: is_plot",
"of mutation correlation significance levels. :param bool is_time_lag: construct time",
"# if other_transfer is None: other_transfer = transfer # df_binary_rows",
"self._plotTransferCompare(df_plot, heat_range = [COLORBAR_MIN, COLORBAR_MAX], ordered_mutations=self.cofraction.ordered_mutations, transfer=transfer, other_transfer=other_transfer, is_center_colorbar=is_center_colorbar, **kwargs)",
"v) else: df = self.cofraction.makeCofractionDF(transfer=transfer, is_difference_frac=is_difference_frac, other_transfer=other_transfer, **kwargs) df =",
"= df_plot.index.tolist() columns = df_plot.columns.tolist() mutations = df_plot.columns.tolist() # Set",
"is_plot=is_plot, **kwargs) result[pair] = df return result def plotSiglvl(self, max_siglvl=MAX_SIGLVL,",
"import numpy as np import pandas as pd import seaborn",
"result = {} for idx, pair in enumerate(pairs): idx +=",
"if other_transfer is None: other_transfer = transfer if ax is",
"= list(ordered_columns) extended_ordered_columns.extend( set(columns).difference(ordered_columns)) for col in missing_columns: df_plot[col] =",
"are mutations \"\"\" if is_differenced: df = self.cofraction.makeCofractionDifferencedDF( threshold_frac=threshold_frac, transfer=transfer,",
"in zip(transfers[:-1], transfers[:-1])] # # Calculate the column order df",
"**kwargs) df = df.applymap(lambda v: np.nan if v < threshold_frac",
"[p for p in zip(transfers[:-1], transfers[1:])] else: pairs = [p",
"done :param bool is_differenced: Computes the difference in count fractions",
"other_transfer): if is_differenced: df = self.cofraction.makeCofractionDifferencedDF( transfer=transfer, other_transfer=other_transfer, threshold_frac=threshold_frac) else:",
"is_time_lag: construct time lag subplots :param dict kwargs: non-transfer parameters",
"plt.figure(figsize=parms[cn.PLT_FIGSIZE]) result = {} for idx, pair in enumerate(pairs): idx",
"are plotted on the heatmap :param list-str ordered_columns: order in",
"= list(set(df_plot.columns.tolist()).union( df_plot.index)) # Do the plot if not cn.PLT_COLORBAR",
"parms[cn.PLT_COLORBAR] = True else: parms[cn.PLT_COLORBAR] = False transfer = pair[0]",
"if idx < len(pairs): is_plot = False else: is_plot =",
"non-zero fraction to 1 :return pd.DataFrame: row=mutation, col=line, value is",
"is_differenced: df = self.cofraction.makeCofractionDifferencedDF( threshold_frac=threshold_frac, transfer=transfer, other_transfer=other_transfer, **kwargs) df =",
"is_plot=None, ax=None, permitted_mutations=None): \"\"\" Does a stacked bar plot of",
"fig, axes = plt.subplots(nrows=num_transfers, ncols=1) dfs = [] for idx,",
"is_include_missing_mutations: \"\"\" def makeLabel(transfer, column, is_include_column=False): if is_include_column: label =",
"# Construct the plot plot = ax.pcolor(df_plot, cmap='jet', vmin=heat_range[0], vmax=heat_range[1])",
"def _plotSiglvlDF(self, transfer=cn.TRANSFER_DEFAULT, other_transfer=None, max_siglvl=MAX_SIGLVL): \"\"\" Constructs a the dataframe",
"= pair[1] df = funcDF(transfer=transfer, other_transfer=other_transfer) df = df.applymap(lambda v:",
":param str mutation_column: :param bool is_plot: \"\"\" self._mutation_column = mutation_column",
"= DataframeSorter(df_plot) df_plot = sorter.deleteNanRowsAndColumns() return df_plot def plotCofractions(self, is_time_lag=False,",
"if v == 0 else v) self._plotTransferCompare(df, transfer=transfer, other_transfer=other_transfer, ordered_columns=self.cofraction.ordered_mutations,",
"df = self.cofraction.makeCofractionDF(transfer=transfer, is_difference_frac=is_difference_frac, other_transfer=other_transfer) if is_compress: df.dropna(axis=0, how='all', inplace=True)",
"bool is_unit_fraction: round fraction to 1 :param bool is_cluster_mutations: Group",
"is_time_lag=False, max_siglvl=MAX_SIGLVL, parms=PlotParms(), **kwargs): \"\"\" Does a subplots of mutation",
"min_fraction else 0) return df_binary.transpose() # if other_transfer is None:",
"plt.subplots(nrows=num_transfers, ncols=1) dfs = [] for idx, transfer in enumerate(transfers):",
"ax.set_yticklabels(new_labels) if cn.PLT_TITLE in parms: title = parms[cn.PLT_TITLE] else: title",
"return pd.concat(dfs) def plotLine(self, transfer, parms=PlotParms(is_initialize=False), is_unit_fraction=False, is_plot=None, ax=None, permitted_mutations=None):",
"df_transformed.applymap( lambda v: np.nan if v < ubound else v)",
"if v < threshold_frac else v) if is_compress: df.dropna(axis=0, how='all',",
"heat_range = [COLORBAR_MIN, COLORBAR_MAX], ordered_mutations=self.cofraction.ordered_mutations, transfer=transfer, other_transfer=other_transfer, is_center_colorbar=is_center_colorbar, **kwargs) return",
"of mutations for Isolates and Lines.\"\"\" from microbepy.common import constants",
"to next level :return dict: key is pair of transfers,",
"\"\"\" Does a subplots of the fraction of lines in",
"order :param bool is_unit_fraction: round non-zero fraction to 1 :return",
"df_plot[extended_ordered_columns] rows = df_plot.columns.tolist() columns = df_plot.columns.tolist() else: extended_ordered_columns =",
"= self._makeMutationSiglvlMatrix(transfer=transfer, other_transfer=other_transfer) sorter = DataframeSorter(df_matrix) df_sort = sorter.orderBoth() #",
"title = \"%s Mutations\" % SPECIES[self._species] xpos = int(len(df_plot)*0.5) ypos",
"idx < len(pairs): is_plot = False else: is_plot = True",
"df_transformed.applymap(lambda v: -v) ubound = -np.log10(max_siglvl) df_plot = df_transformed.applymap( lambda",
"from microbepy.correlation import genome_correlation from microbepy.data.model_data_provider import ModelDataProvider from microbepy.data",
"is_include_column=False): if is_include_column: label = \"%d-%s\" % (transfer, column) else:",
"for idx, pair in enumerate(pairs): idx += 1 ax =",
"v: 0 if np.isnan(v) else v) df_binary = df_line.applymap( lambda",
"fig.add_subplot(nrows, NCOLS, plot_pos[idx]) if idx < len(pairs): is_plot = False",
"labels = ax.get_yticklabels() new_labels = np.repeat(\"\", len(labels)) ax.set_yticklabels(new_labels) if cn.PLT_TITLE",
"v: 1 if v> MIN_FRACTION else v) # Do the",
"is pair of transfers, value is data_frame \"\"\" def funcDF(transfer,",
"int transfer: :param float max_siglvl: :return pd.DataFrame: mutations, mutations, values",
"None: other_transfer = transfer if ax is None: if fig",
"column mutations :param float min_fraction: minimum fractional occurrence of a",
"mutations :param int other_transfer: transfer time for column mutations :param",
"within a line for it to be considered :return pd.DataFrame:",
"if self._species is None: parms[cn.PLT_TITLE] = \"%d\" % transfer else:",
"np.abs(v) < threshold_frac else v) else: df = self.cofraction.makeCofractionDF(transfer=transfer, is_difference_frac=is_difference_frac,",
"False if idx < num_transfers - 1: parms[cn.PLT_LEGEND] = False",
"= 0.01 COLORBAR_MIN = 1.0 COLORBAR_MAX = 4.0 class MutationLinePlot(object):",
"Order the columns if is_include_missing_mutations: columns = df_plot.columns.tolist() missing_columns =",
"\"both\"} FONTSIZE_TITLE = 16 FONTSIZE_LABEL = 8 MAX_LINES = 9",
"from microbepy.data.model_data_provider import ModelDataProvider from microbepy.data import util_data from microbepy.plot.mutation_cofraction",
"else: df = self.cofraction.makeCofractionDF(transfer=transfer, is_difference_frac=is_difference_frac, other_transfer=other_transfer, **kwargs) df = df.applymap(lambda",
"microbepy.plot.util_plot import PlotParms import matplotlib.pyplot as plt import numpy as",
"\"\"\" def makeLabel(transfer, column, is_include_column=False): if is_include_column: label = \"%d-%s\"",
"idx == 0: parms[cn.PLT_YLABEL] = True else: parms[cn.PLT_YLABEL] = False",
"= fig.add_axes([.45, 0.2, 0.01, 0.5]) cb = fig.colorbar(plot, cax =",
"enumerate(pairs): idx += 1 ax = fig.add_subplot(nrows, NCOLS, plot_pos[idx]) if",
"label = \"%d\" % transfer return label def setValue(a_dict, key,",
"other_transfer=other_transfer) if is_compress: df.dropna(axis=0, how='all', inplace=True) df.dropna(axis=1, how='all', inplace=True) return",
"else v) if is_compress: df.dropna(axis=0, how='all', inplace=True) df.dropna(axis=1, how='all', inplace=True)",
"0) return df_binary.transpose() # if other_transfer is None: other_transfer =",
"= \"%d\" % transfer else: parms[cn.PLT_TITLE] = \"%s, %d\" %",
"construct time lag subplots :param dict kwargs: non-transfer parameters passed",
"min_fraction: minimum fractional occurrence of a mutation within a line",
":param bool is_differenced: Computes the difference in count fractions :param",
"heatmap :param list-str ordered_columns: order in which columns appear :param",
"coocurrence significance levels. :param float max_siglvl: maximum significance level :return",
"heatmap range :param int transfer: :param int other_transfer: Allow comparisons",
"\"\" parms.do(is_plot=False) ylabel = makeLabel(transfer, self._mutation_column) xpos = -3 ypos",
"= \"%d\" % transfer return label def setValue(a_dict, key, default):",
"parms.isTrue(cn.PLT_LEGEND): ax.legend(loc=(1,2)) #ax.legend() if is_plot: plt.show() return df_plot def _makeMutationSiglvlMatrix(self,",
"cb = fig.colorbar(plot, cax = cbaxes, cmap='jet') cb.ax.tick_params(labelsize=parms.fontsize_label) else: cb",
"\"\"\" df_matrix = self._makeMutationSiglvlMatrix(transfer=transfer, other_transfer=other_transfer) sorter = DataframeSorter(df_matrix) df_sort =",
"= funcDF(transfer=cn.TRANSFER_1000G, other_transfer=cn.TRANSFER_1000G) df = df.fillna(0) # Set up for",
"None, then use alphabetical order :param bool is_unit_fraction: round non-zero",
"MAX_SIGLVL = 0.01 COLORBAR_MIN = 1.0 COLORBAR_MAX = 4.0 class",
"is_differenced=False, is_center_colorbar=True, is_compress=False, parms=PlotParms(), **kwargs): \"\"\" Constructs a heatmap of",
"= -3 ypos = 0.5*len(rows) ypos = -1 ax.set_ylabel(ylabel, fontsize=parms.fontsize_label,",
"None: other_transfer = transfer # df_binary_rows = makeDF(transfer) df_binary_columns =",
"title, fontsize=FONTSIZE_TITLE) ax.set_ylim([0, MAX_LINES]) if parms.isTrue(cn.PLT_YLABEL): if is_unit_fraction: label =",
"in which columns appear :param bool is_center_colorbar: center the colorbar",
"bottom, width, height cbaxes = fig.add_axes([.45, 0.2, 0.01, 0.5]) cb",
"levels. :param bool is_time_lag: construct time lag subplots :param dict",
"Does a stacked bar plot of mutation frequency for all",
"mutation_column self._is_plot = is_plot self._species = species self.cofraction = MutationCofraction(species=self._species,",
"xlabel = makeLabel(other_transfer, self._mutation_column) parms[cn.PLT_YLABEL] = makeLabel( transfer, self._mutation_column) ax.text(xpos,",
"df_plot def plotCofraction(self, threshold_frac=THRESHOLD_FRAC, transfer=cn.TRANSFER_DEFAULT, other_transfer=None, is_difference_frac=False, is_differenced=False, is_center_colorbar=True, is_compress=False,",
"cn.SPECIES_MIX_MMP: \"MMP\", None: \"both\"} FONTSIZE_TITLE = 16 FONTSIZE_LABEL = 8",
"stacked bar plot of mutation frequency for all transfers. :param",
"list(ordered_columns) extended_ordered_columns.extend( set(columns).difference(ordered_columns)) for col in missing_columns: df_plot[col] = np.nan",
"= True if idx in [1, 2, 5]: parms[cn.PLT_XAXISTICKTOP] =",
"Axis ax: axis to use in plot :param list-str permitted_mutations:",
"= is_plot self._species = species self.cofraction = MutationCofraction(species=self._species, mutation_column=mutation_column) def",
"df_line.applymap( lambda v: 0 if np.isnan(v) else v) df_binary =",
"bool is_center_colorbar: center the colorbar in the plot :param float,",
"v: np.log10(v)) df_transformed = df_transformed.applymap(lambda v: -v) ubound = -np.log10(max_siglvl)",
"are used in the heatmap. :param bool is_time_lag: construct time",
"def _makeMutationSiglvlMatrix(self, transfer=cn.TRANSFER_DEFAULT, other_transfer=None, min_fraction=MIN_FRACTION): \"\"\" Creates a significance level",
"COLORBAR_MIN = 1.0 COLORBAR_MAX = 4.0 class MutationLinePlot(object): \"\"\" Plot",
"True) xpos = 1.05*len(columns) ypos = -0.05*len(rows) parms[cn.PLT_XLABEL] = \"\"",
"# Set up for plots nrows = 2 if (len(pairs)",
"set(ordered_columns).difference(columns) extended_ordered_columns = list(ordered_columns) extended_ordered_columns.extend( set(columns).difference(ordered_columns)) for col in missing_columns:",
"p in zip(transfers[:-1], transfers[1:])] else: pairs = [p for p",
"None: parms[cn.PLT_TITLE] = \"%d\" % transfer else: parms[cn.PLT_TITLE] = \"%s,",
"(12, 8) if ax is None: ax = df_plot.plot(kind='bar', stacked=True,",
"from microbepy.plot.mutation_cofraction import MutationCofraction from microbepy.plot.util_plot import PlotParms import matplotlib.pyplot",
"-0.05*len(rows) parms[cn.PLT_XLABEL] = \"\" xlabel = makeLabel(other_transfer, self._mutation_column) parms[cn.PLT_YLABEL] =",
"parms[cn.PLT_YLABEL] = False if idx < num_transfers - 1: parms[cn.PLT_LEGEND]",
"0.01 COLORBAR_MIN = 1.0 COLORBAR_MAX = 4.0 class MutationLinePlot(object): \"\"\"",
"ax.pcolor(df_plot, cmap='jet', vmin=heat_range[0], vmax=heat_range[1]) if parms.isTrue(cn.PLT_COLORBAR): if is_center_colorbar: # Colorbar",
"df_plot.columns.tolist() # Set up plot information parms[cn.PLT_XLABEL] = \"\" setValue(parms,",
"- 3 ax.text(xpos, ypos, title, fontsize=FONTSIZE_TITLE) ax.set_ylim([0, MAX_LINES]) if parms.isTrue(cn.PLT_YLABEL):",
"in a_dict.keys(): a_dict[key] = default # if is_plot is None:",
"mutations. :param int transfer: transfer time for row mutations :param",
"as np import pandas as pd import seaborn as sns",
"idx in [1, 2, 5]: parms[cn.PLT_XAXISTICKTOP] = True else: parms[cn.PLT_XAXISTICKTOP]",
"len(pairs): is_plot = False else: is_plot = True if idx",
"transfer=cn.TRANSFER_DEFAULT, other_transfer=None, min_fraction=MIN_FRACTION): \"\"\" Creates a significance level matrix for",
"other_transfer; returns a dataframe of mutations as columns and index;",
"return self._plotTransfers(funcDF, is_time_lag, parms=parms, heat_range = [COLORBAR_MIN, COLORBAR_MAX], **kwargs) def",
"= plt.figure(figsize=parms[cn.PLT_FIGSIZE]) result = {} for idx, pair in enumerate(pairs):",
"-3 ypos = 0.5*len(rows) ypos = -1 ax.set_ylabel(ylabel, fontsize=parms.fontsize_label, x=xpos,",
"None: ax = df_plot.plot(kind='bar', stacked=True, figsize=parms[cn.PLT_FIGSIZE], legend=None) else: df_plot.plot(kind='bar', stacked=True,",
"- 1: parms[cn.PLT_LEGEND] = False parms[cn.PLT_XLABEL] = False parms[cn.PLT_XTICKLABELS] =",
"permitted_mutations=None): \"\"\" Does a stacked bar plot of mutation frequency",
"\"\"\" def funcDF(transfer, other_transfer): if is_differenced: df = self.cofraction.makeCofractionDifferencedDF( transfer=transfer,",
"other_transfer=other_transfer, threshold_frac=threshold_frac) else: df = self.cofraction.makeCofractionDF(transfer=transfer, is_difference_frac=is_difference_frac, other_transfer=other_transfer) if is_compress:",
"from two transfers. :param pd.DataFrame df_plot: index and columns are",
"mutations co-occur. :param bool is_time_lag: construct time lag subplots :param",
"else v) df_binary = df_line.applymap( lambda v: 1.0 if v",
"df_plot = df_plot.reindex(extended_ordered_columns) df_plot = df_plot[extended_ordered_columns] rows = df_plot.columns.tolist() columns",
"threshold_frac=THRESHOLD_FRAC, transfer=cn.TRANSFER_DEFAULT, other_transfer=None, is_difference_frac=False, is_differenced=False, is_center_colorbar=True, is_compress=False, parms=PlotParms(), **kwargs): \"\"\"",
"ax.set_xlabel(\"\", fontsize=FONTSIZE_LABEL) # Eliminate implicit label if parms.isFalse(cn.PLT_XTICKLABELS): labels =",
"mutation_column=cn.GGENE_ID, species=None, is_plot=True): \"\"\" :param str mutation_column: :param bool is_plot:",
"= default # if is_plot is None: is_plot = self._is_plot",
"zip(transfers[:-1], transfers[1:])] else: pairs = [p for p in zip(transfers[:-1],",
"parms=PlotParms(is_initialize=False), is_unit_fraction = False, is_cluster_mutations=True): \"\"\" Does a stacked bar",
"df.applymap(lambda v: np.nan if v < threshold_frac else v) if",
"is done :param bool is_differenced: Computes the difference in count",
"transfer=transfer, other_transfer=other_transfer, is_center_colorbar=is_center_colorbar, is_include_missing_mutations=is_include_missing_mutations, **kwargs) return df def _plotTransferCompare(self, df_plot,",
"df_plot.index)) # Do the plot if not cn.PLT_COLORBAR in parms:",
"Does a subplots of mutation correlation significance levels. :param bool",
"funcDF, is_time_lag, parms=PlotParms(), **kwargs): \"\"\" Does a subplots of mutation",
"the plot if not cn.PLT_COLORBAR in parms: parms[cn.PLT_COLORBAR] = True",
"dict: key is pair of transfers, value is data_frame \"\"\"",
":param bool is_unit_fraction: round non-zero fraction to 1 :return pd.DataFrame:",
":param pd.DataFrame df_plot: index and columns are mutations; values are",
"axes = plt.subplots(nrows=num_transfers, ncols=1) dfs = [] for idx, transfer",
"pd.DataFrame df_plot: index and columns are mutations; values are plotted",
"len(transfers) fig, axes = plt.subplots(nrows=num_transfers, ncols=1) dfs = [] for",
":param list-str permitted_mutations: to use and how they are ordered",
"other_transfer is None: other_transfer = transfer # df_binary_rows = makeDF(transfer)",
"plot of mutation frequency for all transfers. :param bool is_unit_fraction:",
"df = funcDF(transfer=cn.TRANSFER_1000G, other_transfer=cn.TRANSFER_1000G) df = df.fillna(0) # Set up",
"= [p for p in zip(transfers[:-1], transfers[1:])] else: pairs =",
"elif not self._is_plot: is_plot = self._is_plot if ordered_columns is None:",
"for Isolates and Lines.\"\"\" from microbepy.common import constants as cn",
"mutations :param float min_fraction: minimum fractional occurrence of a mutation",
"= True if self._species is None: parms[cn.PLT_TITLE] = \"%d\" %",
"= True df = self.plotLine(transfer, parms=parms, is_plot=False, ax=axes[idx], permitted_mutations=permitted_mutations, is_unit_fraction=is_unit_fraction)",
"= cbaxes, cmap='jet') cb.ax.tick_params(labelsize=parms.fontsize_label) else: cb = fig.colorbar(plot, cmap='jet') cb.ax.tick_params(labelsize=parms.fontsize_label)",
"heatmap of the mutation coocurrence significance levels. :param float max_siglvl:",
"time for column mutations :param float min_fraction: minimum fractional occurrence",
"pd.DataFrame: columns, rows are mutations \"\"\" if is_differenced: df =",
"mutation correlation significance levels. :param bool is_time_lag: construct time lag",
"other_transfer=other_transfer, max_siglvl=max_siglvl) self._plotTransferCompare(df_plot, heat_range = [COLORBAR_MIN, COLORBAR_MAX], ordered_mutations=self.cofraction.ordered_mutations, transfer=transfer, other_transfer=other_transfer,",
"df_plot.plot(kind='bar', stacked=True, figsize=parms[cn.PLT_FIGSIZE], legend=None) else: df_plot.plot(kind='bar', stacked=True, legend=None, ax=ax, figsize=parms[cn.PLT_FIGSIZE])",
"= False transfer = pair[0] other_transfer = pair[1] df =",
"else: extended_ordered_columns = ordered_columns rows = df_plot.index.tolist() columns = df_plot.columns.tolist()",
"self.cofraction.makeCofractionDF(transfer=transfer, is_difference_frac=is_difference_frac, other_transfer=other_transfer, **kwargs) df = df.applymap(lambda v: np.nan if",
"microbepy.common.isolate import Isolate from microbepy.common import util from microbepy.correlation import",
"and columns are mutations; values are plotted on the heatmap",
"transfers = self.cofraction.transfers num_transfers = len(transfers) fig, axes = plt.subplots(nrows=num_transfers,",
"= sorter.deleteNanRowsAndColumns() return df_plot def plotCofractions(self, is_time_lag=False, threshold_frac=THRESHOLD_FRAC, is_difference_frac=False, is_differenced=False,",
"import constants as cn from microbepy.common.dataframe_sorter import DataframeSorter from microbepy.common.isolate",
"= \"Fraction\" ax.set_ylabel(label , fontsize=FONTSIZE_LABEL) if parms.isTrue(cn.PLT_XLABEL): ax.set_xlabel(self._mutation_column, fontsize=FONTSIZE_LABEL) if",
"for heatmap. :param int transfer: :param float max_siglvl: :return pd.DataFrame:",
"other_transfer=other_transfer, **kwargs) df = df.applymap(lambda v: np.nan if v <",
"'green', 'blue'] SPECIES = {cn.SPECIES_MIX_DVH: \"DVH\", cn.SPECIES_MIX_MMP: \"MMP\", None: \"both\"}",
"maximum significance level :return pd.DataFrame: columns, rows are mutations \"\"\"",
"is_plot is None: is_plot = self._is_plot elif not self._is_plot: is_plot",
"significance levels. :param float max_siglvl: maximum significance level :return pd.DataFrame:",
"the columns if is_include_missing_mutations: columns = df_plot.columns.tolist() missing_columns = set(ordered_columns).difference(columns)",
"key is pair of transfers, value is data_frame \"\"\" def",
"parms[cn.PLT_XLABEL] = False parms[cn.PLT_XTICKLABELS] = False else: parms[cn.PLT_LEGEND] = True",
"pair[0] other_transfer = pair[1] df = funcDF(transfer=transfer, other_transfer=other_transfer) df =",
"import seaborn as sns COLORS = ['red', 'green', 'blue'] SPECIES",
"Constructs a the dataframe used for heatmap. :param int transfer:",
"3 plot_pos = {1:1, 2:3, 3:4, 4:6} NPLOTS = 6",
"by occurrences within Lines. \"\"\" def __init__(self, mutation_column=cn.GGENE_ID, species=None, is_plot=True):",
"= DataframeSorter(df_matrix) df_sort = sorter.orderBoth() # df_transformed = df_sort.applymap(lambda v:",
"plt import numpy as np import pandas as pd import",
"if is_include_column: label = \"%d-%s\" % (transfer, column) else: label",
"the plot plot = ax.pcolor(df_plot, cmap='jet', vmin=heat_range[0], vmax=heat_range[1]) if parms.isTrue(cn.PLT_COLORBAR):",
"if is_unit_fraction: df_plot = df_plot.applymap( lambda v: 1 if v>",
"df_plot = df_plot[extended_ordered_columns] rows = df_plot.columns.tolist() columns = df_plot.columns.tolist() else:",
"if other_transfer is None: other_transfer = transfer # df_binary_rows =",
"pair in enumerate(pairs): idx += 1 ax = fig.add_subplot(nrows, NCOLS,",
"ax.set_yticks(np.arange(0.5, len(col_labels))) ax.set_yticklabels(col_labels, fontsize=parms.fontsize_label) #parms[cn.PLT_YLABEL] = \"\" parms.do(is_plot=False) if is_plot:",
"plt.show() return pd.concat(dfs) def plotLine(self, transfer, parms=PlotParms(is_initialize=False), is_unit_fraction=False, is_plot=None, ax=None,",
"max_siglvl: :return pd.DataFrame: mutations, mutations, values are -log10 significance level",
"is None: ordered_columns = list(set(df_plot.columns.tolist()).union( df_plot.index)) # Do the plot",
"round fraction to 1 :param bool is_cluster_mutations: Group similar mutations",
"idx += 1 ax = fig.add_subplot(nrows, NCOLS, plot_pos[idx]) if idx",
"#parms[cn.PLT_YLABEL] = \"\" parms.do(is_plot=False) if is_plot: parms[cn.PLT_YLABEL] = \"\" parms.do(is_plot=False)",
"stacked=True, legend=None, ax=ax, figsize=parms[cn.PLT_FIGSIZE]) ax.set_xlabel(\"\", fontsize=FONTSIZE_LABEL) # Eliminate implicit label",
"missing_columns = set(ordered_columns).difference(columns) extended_ordered_columns = list(ordered_columns) extended_ordered_columns.extend( set(columns).difference(ordered_columns)) for col",
"__init__(self, mutation_column=cn.GGENE_ID, species=None, is_plot=True): \"\"\" :param str mutation_column: :param bool",
"is None: ax = df_plot.plot(kind='bar', stacked=True, figsize=parms[cn.PLT_FIGSIZE], legend=None) else: df_plot.plot(kind='bar',",
"Lines.\"\"\" from microbepy.common import constants as cn from microbepy.common.dataframe_sorter import",
"makeDF(transfer) df_binary_columns = makeDF(other_transfer) df_matrix = genome_correlation.makeSiglvlDF(df_binary_rows, df_other=df_binary_columns) return df_matrix",
"returns a dataframe of mutations as columns and index; values",
"in the heatmap. :param bool is_time_lag: construct time lag subplots",
"False if idx == 4: parms[cn.PLT_COLORBAR] = True else: parms[cn.PLT_COLORBAR]",
"plt.show() return df_plot def _makeMutationSiglvlMatrix(self, transfer=cn.TRANSFER_DEFAULT, other_transfer=None, min_fraction=MIN_FRACTION): \"\"\" Creates",
"if not cn.PLT_FIGSIZE in parms: parms[cn.PLT_FIGSIZE] = (12, 8) if",
"mutations \"\"\" if is_differenced: df = self.cofraction.makeCofractionDifferencedDF( threshold_frac=threshold_frac, transfer=transfer, other_transfer=other_transfer,",
"transfer = pair[0] other_transfer = pair[1] df = funcDF(transfer=transfer, other_transfer=other_transfer)",
"= 4.0 class MutationLinePlot(object): \"\"\" Plot mutations by occurrences within",
"v: 1.0 if v > min_fraction else 0) return df_binary.transpose()",
"other_transfer=other_transfer, is_center_colorbar=is_center_colorbar, is_include_missing_mutations=is_include_missing_mutations, **kwargs) return df def _plotTransferCompare(self, df_plot, heat_range,",
"difference in count fractions :param bool is_compress: Eliminate rows/columns with",
"threshold_frac=threshold_frac, transfer=transfer, other_transfer=other_transfer, **kwargs) df = df.applymap(lambda v: np.nan if",
"microbepy.data.model_data_provider import ModelDataProvider from microbepy.data import util_data from microbepy.plot.mutation_cofraction import",
"= \"%s Mutations\" % SPECIES[self._species] xpos = int(len(df_plot)*0.5) ypos =",
"NCOLS = 3 plot_pos = {1:1, 2:3, 3:4, 4:6} NPLOTS",
"= makeDF(transfer) df_binary_columns = makeDF(other_transfer) df_matrix = genome_correlation.makeSiglvlDF(df_binary_rows, df_other=df_binary_columns) return",
"bool is_unit_fraction: round non-zero fraction to 1 :return pd.DataFrame: row=mutation,",
"\"\" parms.do(is_plot=False) if is_plot: parms[cn.PLT_YLABEL] = \"\" parms.do(is_plot=False) ylabel =",
"pairs = [p for p in zip(transfers[:-1], transfers[1:])] else: pairs",
"value is data_frame \"\"\" NCOLS = 3 plot_pos = {1:1,",
"Overrides constructor plotting directive :param bool is_include_missing_mutations: \"\"\" def makeLabel(transfer,",
"columns = df_plot.columns.tolist() mutations = df_plot.columns.tolist() # Set up plot",
"if np.isnan(v) else v) df_binary = df_line.applymap( lambda v: 1.0",
"the fraction of lines in which mutations co-occur. :param bool",
"columns = df_plot.columns.tolist() missing_columns = set(ordered_columns).difference(columns) extended_ordered_columns = list(ordered_columns) extended_ordered_columns.extend(",
"= df_plot.index.tolist() if parms.isTrue(cn.PLT_XAXISTICKTOP): ax.xaxis.tick_top() ax.set_xticks(np.arange(0.5, len(row_labels))) ax.set_xticklabels(row_labels, rotation=90, fontsize=parms.fontsize_label)",
"for which plot is done :param bool is_differenced: Computes the",
"fontsize=parms.fontsize_label) ax.set_yticks(np.arange(0.5, len(col_labels))) ax.set_yticklabels(col_labels, fontsize=parms.fontsize_label) #parms[cn.PLT_YLABEL] = \"\" parms.do(is_plot=False) if",
"index and columns are mutations \"\"\" def makeDF(transfer): df_line =",
"transfer return label def setValue(a_dict, key, default): if not key",
"all transfers. :param bool is_unit_fraction: round fraction to 1 :param",
"is_plot=None): \"\"\" Constructs a heatmap comparing values for mutations from",
"mutation within a line for it to be considered :return",
":param bool is_cluster_mutations: Group similar mutations together :return pd.DataFrame: row=mutation,",
"the plot :param bool is_plot: Overrides constructor plotting directive :param",
"def makeLabel(transfer, column, is_include_column=False): if is_include_column: label = \"%d-%s\" %",
"if idx < num_transfers - 1: parms[cn.PLT_LEGEND] = False parms[cn.PLT_XLABEL]",
"if is_time_lag: pairs = [p for p in zip(transfers[:-1], transfers[1:])]",
"self.cofraction.transfers if is_time_lag: pairs = [p for p in zip(transfers[:-1],",
"== 0: parms[cn.PLT_YLABEL] = True else: parms[cn.PLT_YLABEL] = False if",
"False parms[cn.PLT_XTICKLABELS] = False else: parms[cn.PLT_LEGEND] = True parms[cn.PLT_XLABEL] =",
"columns are mutations; values are plotted on the heatmap :param",
"True, **kwargs): \"\"\" Constructs a heatmap of the mutation coocurrence",
"level matrix for mutations. :param int transfer: transfer time for",
"+= 1 ax = fig.add_subplot(nrows, NCOLS, plot_pos[idx]) if idx <",
"is_time_lag, parms=parms, heat_range = [COLORBAR_MIN, COLORBAR_MAX], **kwargs) def _plotTransfers(self, funcDF,",
"parms=PlotParms(), **kwargs): \"\"\" Does a subplots of mutation correlation significance",
"else: is_include_missing_mutations = True ordered_columns = self.cofraction.ordered_mutations self._plotTransferCompare(df, heat_range=[0, 1.0],",
"is_compress: df.dropna(axis=0, how='all', inplace=True) df.dropna(axis=1, how='all', inplace=True) is_include_missing_mutations = False",
"COLORBAR_MAX], ordered_mutations=self.cofraction.ordered_mutations, transfer=transfer, other_transfer=other_transfer, is_center_colorbar=is_center_colorbar, **kwargs) return df_plot def plotCofraction(self,",
"df_plot, heat_range, ordered_columns=None, is_center_colorbar=True, transfer=cn.TRANSFER_DEFAULT, other_transfer=None, ax=None, fig=None, is_include_missing_mutations=True, parms=PlotParms(),",
"ypos, xlabel, fontsize=parms.fontsize_label) # # Construct the plot plot =",
"df = df.applymap(lambda v: np.nan if v < threshold_frac else",
"sorter = DataframeSorter(df_plot) df_plot = sorter.deleteNanRowsAndColumns() return df_plot def plotCofractions(self,",
"parms: :params Axis ax: axis to use in plot :param",
"values :return pd.DataFrame: columns, rows are mutations \"\"\" if is_differenced:",
"genome_correlation from microbepy.data.model_data_provider import ModelDataProvider from microbepy.data import util_data from",
"ax.set_ylabel(label , fontsize=FONTSIZE_LABEL) if parms.isTrue(cn.PLT_XLABEL): ax.set_xlabel(self._mutation_column, fontsize=FONTSIZE_LABEL) if parms.isTrue(cn.PLT_LEGEND): ax.legend(loc=(1,2))",
"= 6 transfers = self.cofraction.transfers if is_time_lag: pairs = [p",
"MutationCofraction(species=self._species, mutation_column=mutation_column) def plotTransfers(self, parms=PlotParms(is_initialize=False), is_unit_fraction = False, is_cluster_mutations=True): \"\"\"",
"genome_correlation.makeSiglvlDF(df_binary_rows, df_other=df_binary_columns) return df_matrix def _plotSiglvlDF(self, transfer=cn.TRANSFER_DEFAULT, other_transfer=None, max_siglvl=MAX_SIGLVL): \"\"\"",
"df_plot.loc[col, :] = np.nan df_plot = df_plot.reindex(extended_ordered_columns) df_plot = df_plot[extended_ordered_columns]",
"for row mutations :param int other_transfer: transfer time for column",
"other_transfer=other_transfer) # return self._plotTransfers(funcDF, is_time_lag, parms=parms, heat_range = [COLORBAR_MIN, COLORBAR_MAX],",
"values are plotted on the heatmap :param list-str ordered_columns: order",
"funcDF(transfer, other_transfer): return self._plotSiglvlDF(transfer=transfer, max_siglvl=max_siglvl, other_transfer=other_transfer) # return self._plotTransfers(funcDF, is_time_lag,",
"time :param Matplotlib.Axes ax: :param PlotParms parms: Parameters for the",
"df.applymap(lambda v: np.nan if v == 0 else v) self._plotTransferCompare(df,",
"line with colors :params int transfer: :params PlotParms parms: :params",
"it to be considered :return pd.DataFrame: row index and columns",
"stacked bar plot of mutation frequency by line with colors",
"information parms[cn.PLT_XLABEL] = \"\" setValue(parms, cn.PLT_COLORBAR, True) xpos = 1.05*len(columns)",
"is_plot: \"\"\" self._mutation_column = mutation_column self._is_plot = is_plot self._species =",
"float max_siglvl: :return pd.DataFrame: mutations, mutations, values are -log10 significance",
"Computes the difference in count fractions :param bool is_compress: Eliminate",
"plot :param list-str permitted_mutations: to use and how they are",
"other_transfer=None, ax=None, fig=None, is_include_missing_mutations=True, parms=PlotParms(), is_plot=None): \"\"\" Constructs a heatmap",
"is_plot: Overrides constructor plotting directive :param bool is_include_missing_mutations: \"\"\" def",
"import pandas as pd import seaborn as sns COLORS =",
"df_matrix = self._makeMutationSiglvlMatrix(transfer=transfer, other_transfer=other_transfer) sorter = DataframeSorter(df_matrix) df_sort = sorter.orderBoth()",
"= self._is_plot elif not self._is_plot: is_plot = self._is_plot if ordered_columns",
"df = self.cofraction.makeCofractionDifferencedDF( threshold_frac=threshold_frac, transfer=transfer, other_transfer=other_transfer, **kwargs) df = df.applymap(lambda",
"transfer=cn.TRANSFER_DEFAULT, other_transfer=None, is_center_colorbar = True, **kwargs): \"\"\" Constructs a heatmap",
"heat_range=[0, 1.0], ordered_columns=ordered_columns, parms=parms, transfer=transfer, other_transfer=other_transfer, is_center_colorbar=is_center_colorbar, is_include_missing_mutations=is_include_missing_mutations, **kwargs) return",
"\"%s, %d\" % (self._species, transfer) if idx == 0: parms[cn.PLT_YLABEL]",
"stacked=True, figsize=parms[cn.PLT_FIGSIZE], legend=None) else: df_plot.plot(kind='bar', stacked=True, legend=None, ax=ax, figsize=parms[cn.PLT_FIGSIZE]) ax.set_xlabel(\"\",",
"is None: other_transfer = transfer # df_binary_rows = makeDF(transfer) df_binary_columns",
"from microbepy.common import util from microbepy.correlation import genome_correlation from microbepy.data.model_data_provider",
"value is fraction \"\"\" permitted_mutations = self.cofraction.ordered_mutations transfers = self.cofraction.transfers",
"return self._plotTransfers(funcDF, is_time_lag, parms=parms, heat_range=[0, 1.0], **kwargs) def plotSiglvls(self, is_time_lag=False,",
"inplace=True) df.dropna(axis=1, how='all', inplace=True) is_include_missing_mutations = False else: is_include_missing_mutations =",
"is_time_lag: pairs = [p for p in zip(transfers[:-1], transfers[1:])] else:",
"is_differenced=False, is_compress=False, parms=PlotParms(), **kwargs): \"\"\" Does a subplots of the",
"ordered_columns = self.cofraction.ordered_mutations self._plotTransferCompare(df, heat_range=[0, 1.0], ordered_columns=ordered_columns, parms=parms, transfer=transfer, other_transfer=other_transfer,",
"self._is_plot: is_plot = self._is_plot if ordered_columns is None: ordered_columns =",
"True parms[cn.PLT_XTICKLABELS] = True df = self.plotLine(transfer, parms=parms, is_plot=False, ax=axes[idx],",
"a mutation within a line for it to be considered",
"axis to use in plot :param list-str permitted_mutations: to use",
"# Set up plot information parms[cn.PLT_XLABEL] = \"\" setValue(parms, cn.PLT_COLORBAR,",
":param float max_siglvl: maximum significance level :return pd.DataFrame: columns, rows",
"v: np.nan if v == 0 else v) self._plotTransferCompare(df, transfer=transfer,",
"is_include_missing_mutations=True, parms=PlotParms(), is_plot=None): \"\"\" Constructs a heatmap comparing values for",
"and columns are mutations \"\"\" def makeDF(transfer): df_line = self.cofraction.makeLineDF(transfer=transfer)",
"mutations as columns and index; values are used in the",
"nrows = 2 if (len(pairs) == 4) else 3 fig",
"NPLOTS = 6 transfers = self.cofraction.transfers if is_time_lag: pairs =",
"ax = fig.add_subplot(nrows, NCOLS, plot_pos[idx]) if idx < len(pairs): is_plot",
"plotSiglvl(self, max_siglvl=MAX_SIGLVL, transfer=cn.TRANSFER_DEFAULT, other_transfer=None, is_center_colorbar = True, **kwargs): \"\"\" Constructs",
":return pd.DataFrame: row index and columns are mutations \"\"\" def",
"subplots of mutation correlation significance levels. :param bool is_time_lag: construct",
"then use alphabetical order :param bool is_unit_fraction: round non-zero fraction",
":return dict: key is pair of transfers, value is data_frame",
"= True parms[cn.PLT_XLABEL] = True parms[cn.PLT_XTICKLABELS] = True df =",
"else v) # Do the plot if not cn.PLT_FIGSIZE in",
"4: parms[cn.PLT_COLORBAR] = True else: parms[cn.PLT_COLORBAR] = False transfer =",
"Transfer for which plot is done :param bool is_differenced: Computes",
"co-occur. :param bool is_time_lag: construct time lag subplots :param bool",
"result def plotSiglvl(self, max_siglvl=MAX_SIGLVL, transfer=cn.TRANSFER_DEFAULT, other_transfer=None, is_center_colorbar = True, **kwargs):",
"# df_transformed = df_sort.applymap(lambda v: np.log10(v)) df_transformed = df_transformed.applymap(lambda v:",
"figsize=parms[cn.PLT_FIGSIZE]) ax.set_xlabel(\"\", fontsize=FONTSIZE_LABEL) # Eliminate implicit label if parms.isFalse(cn.PLT_XTICKLABELS): labels",
"setValue(parms, cn.PLT_COLORBAR, True) xpos = 1.05*len(columns) ypos = -0.05*len(rows) parms[cn.PLT_XLABEL]",
"df_binary = df_line.applymap( lambda v: 1.0 if v > min_fraction",
"data_frame \"\"\" NCOLS = 3 plot_pos = {1:1, 2:3, 3:4,",
"fontsize=parms.fontsize_label) # # Construct the plot plot = ax.pcolor(df_plot, cmap='jet',",
":params Axis ax: axis to use in plot :param list-str",
"2, 5]: parms[cn.PLT_XAXISTICKTOP] = True else: parms[cn.PLT_XAXISTICKTOP] = False if",
"pair[1] df = funcDF(transfer=transfer, other_transfer=other_transfer) df = df.applymap(lambda v: np.nan",
"a_dict[key] = default # if is_plot is None: is_plot =",
"to be considered :return pd.DataFrame: row index and columns are",
"mutations from two transfers. :param pd.DataFrame df_plot: index and columns",
"v: -v) ubound = -np.log10(max_siglvl) df_plot = df_transformed.applymap( lambda v:",
"else: is_plot = True if idx in [1, 2, 5]:",
"legend=None, ax=ax, figsize=parms[cn.PLT_FIGSIZE]) ax.set_xlabel(\"\", fontsize=FONTSIZE_LABEL) # Eliminate implicit label if",
"makeDF(other_transfer) df_matrix = genome_correlation.makeSiglvlDF(df_binary_rows, df_other=df_binary_columns) return df_matrix def _plotSiglvlDF(self, transfer=cn.TRANSFER_DEFAULT,",
"values are used in the heatmap. :param bool is_time_lag: construct",
"bool is_plot: \"\"\" self._mutation_column = mutation_column self._is_plot = is_plot self._species",
"left, bottom, width, height cbaxes = fig.add_axes([.45, 0.2, 0.01, 0.5])",
"index and columns are mutations; values are plotted on the",
"self.cofraction.makeCofractionDF(transfer=transfer, is_difference_frac=is_difference_frac, other_transfer=other_transfer) if is_compress: df.dropna(axis=0, how='all', inplace=True) df.dropna(axis=1, how='all',",
"appear :param bool is_center_colorbar: center the colorbar in the plot",
"if ax is None: ax = df_plot.plot(kind='bar', stacked=True, figsize=parms[cn.PLT_FIGSIZE], legend=None)",
"col=line, value is fraction \"\"\" if is_plot is None: is_plot",
"_makeMutationSiglvlMatrix(self, transfer=cn.TRANSFER_DEFAULT, other_transfer=None, min_fraction=MIN_FRACTION): \"\"\" Creates a significance level matrix",
"is_plot = True if idx in [1, 2, 5]: parms[cn.PLT_XAXISTICKTOP]",
"is_plot self._species = species self.cofraction = MutationCofraction(species=self._species, mutation_column=mutation_column) def plotTransfers(self,",
"ax.set_ylim([0, MAX_LINES]) if parms.isTrue(cn.PLT_YLABEL): if is_unit_fraction: label = \"No. Lines\"",
"is_include_missing_mutations=is_include_missing_mutations, **kwargs) return df def _plotTransferCompare(self, df_plot, heat_range, ordered_columns=None, is_center_colorbar=True,",
"0.25 THRESHOLD_FRAC = 0.2 MAX_SIGLVL = 0.01 COLORBAR_MIN = 1.0",
"other_transfer=None, max_siglvl=MAX_SIGLVL): \"\"\" Constructs a the dataframe used for heatmap.",
"parms.isFalse(cn.PLT_YTICKLABELS): labels = ax.get_yticklabels() new_labels = np.repeat(\"\", len(labels)) ax.set_yticklabels(new_labels) if",
"= self.cofraction.makeLineDF( permitted_mutations=permitted_mutations, transfer=transfer) if is_unit_fraction: df_plot = df_plot.applymap( lambda",
"df.dropna(axis=0, how='all', inplace=True) df.dropna(axis=1, how='all', inplace=True) return df # return",
"= 1.05*len(columns) ypos = -0.05*len(rows) parms[cn.PLT_XLABEL] = \"\" xlabel =",
"2:3, 3:4, 4:6} NPLOTS = 6 transfers = self.cofraction.transfers if",
"-np.log10(max_siglvl) df_plot = df_transformed.applymap( lambda v: np.nan if v <",
"int transfer: transfer time for row mutations :param int other_transfer:",
"# Colorbar positions: left, bottom, width, height cbaxes = fig.add_axes([.45,",
"cb.ax.tick_params(labelsize=parms.fontsize_label) else: cb = fig.colorbar(plot, cmap='jet') cb.ax.tick_params(labelsize=parms.fontsize_label) row_labels = df_plot.columns.tolist()",
"= [p for p in zip(transfers[:-1], transfers[:-1])] # # Calculate",
"transfer else: parms[cn.PLT_TITLE] = \"%s, %d\" % (self._species, transfer) if",
"= False parms[cn.PLT_XTICKLABELS] = False else: parms[cn.PLT_LEGEND] = True parms[cn.PLT_XLABEL]",
"sorter.orderBoth() # df_transformed = df_sort.applymap(lambda v: np.log10(v)) df_transformed = df_transformed.applymap(lambda",
"microbepy.data import util_data from microbepy.plot.mutation_cofraction import MutationCofraction from microbepy.plot.util_plot import",
"def plotSiglvls(self, is_time_lag=False, max_siglvl=MAX_SIGLVL, parms=PlotParms(), **kwargs): \"\"\" Does a subplots",
"def _plotTransferCompare(self, df_plot, heat_range, ordered_columns=None, is_center_colorbar=True, transfer=cn.TRANSFER_DEFAULT, other_transfer=None, ax=None, fig=None,",
"= True ordered_columns = self.cofraction.ordered_mutations self._plotTransferCompare(df, heat_range=[0, 1.0], ordered_columns=ordered_columns, parms=parms,",
"if idx == 4: parms[cn.PLT_COLORBAR] = True else: parms[cn.PLT_COLORBAR] =",
"\"\"\" :param str mutation_column: :param bool is_plot: \"\"\" self._mutation_column =",
"in missing_columns: df_plot[col] = np.nan df_plot.loc[col, :] = np.nan df_plot",
"idx < num_transfers - 1: parms[cn.PLT_LEGEND] = False parms[cn.PLT_XLABEL] =",
"dfs = [] for idx, transfer in enumerate(transfers): parms[cn.PLT_YTICKLABELS] =",
"import DataframeSorter from microbepy.common.isolate import Isolate from microbepy.common import util",
"col in missing_columns: df_plot[col] = np.nan df_plot.loc[col, :] = np.nan",
"funcDF(transfer=transfer, other_transfer=other_transfer) df = df.applymap(lambda v: np.nan if v ==",
"is_differenced: df = self.cofraction.makeCofractionDifferencedDF( transfer=transfer, other_transfer=other_transfer, threshold_frac=threshold_frac) else: df =",
"mutation frequency for all transfers. :param bool is_unit_fraction: round fraction",
"= df_sort.applymap(lambda v: np.log10(v)) df_transformed = df_transformed.applymap(lambda v: -v) ubound",
"parms=PlotParms(is_initialize=False), is_unit_fraction=False, is_plot=None, ax=None, permitted_mutations=None): \"\"\" Does a stacked bar",
"float min_fraction: minimum fractional occurrence of a mutation within a",
"= fig.colorbar(plot, cmap='jet') cb.ax.tick_params(labelsize=parms.fontsize_label) row_labels = df_plot.columns.tolist() col_labels = df_plot.index.tolist()",
"makeLabel(transfer, column, is_include_column=False): if is_include_column: label = \"%d-%s\" % (transfer,",
"in enumerate(transfers): parms[cn.PLT_YTICKLABELS] = True if self._species is None: parms[cn.PLT_TITLE]",
"df_binary.transpose() # if other_transfer is None: other_transfer = transfer #",
"= self._is_plot parms.setTrueIfAbsent(cn.PLT_XLABEL) parms.setTrueIfAbsent(cn.PLT_XTICKLABELS) # df_plot = self.cofraction.makeLineDF( permitted_mutations=permitted_mutations, transfer=transfer)",
"up plot information parms[cn.PLT_XLABEL] = \"\" setValue(parms, cn.PLT_COLORBAR, True) xpos",
"(len(pairs) == 4) else 3 fig = plt.figure(figsize=parms[cn.PLT_FIGSIZE]) result =",
"\"%d-%s\" % (transfer, column) else: label = \"%d\" % transfer",
"used in the heatmap. :param bool is_time_lag: construct time lag",
"int(len(df_plot)*0.5) ypos = MAX_LINES - 3 ax.text(xpos, ypos, title, fontsize=FONTSIZE_TITLE)",
"_plotTransferCompare(self, df_plot, heat_range, ordered_columns=None, is_center_colorbar=True, transfer=cn.TRANSFER_DEFAULT, other_transfer=None, ax=None, fig=None, is_include_missing_mutations=True,",
"time for row mutations :param int other_transfer: transfer time for",
"which plot is done :param bool is_differenced: Computes the difference",
"if self._is_plot: plt.show() return pd.concat(dfs) def plotLine(self, transfer, parms=PlotParms(is_initialize=False), is_unit_fraction=False,",
"**kwargs) return df_plot def plotCofraction(self, threshold_frac=THRESHOLD_FRAC, transfer=cn.TRANSFER_DEFAULT, other_transfer=None, is_difference_frac=False, is_differenced=False,",
"parms[cn.PLT_YLABEL] = True else: parms[cn.PLT_YLABEL] = False if idx <",
"= \"\" setValue(parms, cn.PLT_COLORBAR, True) xpos = 1.05*len(columns) ypos =",
"MIN_FRACTION else v) # Do the plot if not cn.PLT_FIGSIZE",
"are ordered if None, then use alphabetical order :param bool",
"FONTSIZE_LABEL = 8 MAX_LINES = 9 MIN_FRACTION = 0.25 THRESHOLD_FRAC",
"SPECIES[self._species] xpos = int(len(df_plot)*0.5) ypos = MAX_LINES - 3 ax.text(xpos,",
"0 else v) self._plotTransferCompare(df, transfer=transfer, other_transfer=other_transfer, ordered_columns=self.cofraction.ordered_mutations, is_center_colorbar=True, fig=fig, ax=ax,",
"str mutation_column: :param bool is_plot: \"\"\" self._mutation_column = mutation_column self._is_plot",
"legend=None) else: df_plot.plot(kind='bar', stacked=True, legend=None, ax=ax, figsize=parms[cn.PLT_FIGSIZE]) ax.set_xlabel(\"\", fontsize=FONTSIZE_LABEL) #",
"# Calculate the column order df = funcDF(transfer=cn.TRANSFER_1000G, other_transfer=cn.TRANSFER_1000G) df",
"-log10 significance level \"\"\" df_matrix = self._makeMutationSiglvlMatrix(transfer=transfer, other_transfer=other_transfer) sorter =",
"plot plot = ax.pcolor(df_plot, cmap='jet', vmin=heat_range[0], vmax=heat_range[1]) if parms.isTrue(cn.PLT_COLORBAR): if",
"cb.ax.tick_params(labelsize=parms.fontsize_label) row_labels = df_plot.columns.tolist() col_labels = df_plot.index.tolist() if parms.isTrue(cn.PLT_XAXISTICKTOP): ax.xaxis.tick_top()",
"transfer time for row mutations :param int other_transfer: transfer time",
"lag subplots :param bool is_differenced: Computes the difference in count",
"= ax.get_yticklabels() new_labels = np.repeat(\"\", len(labels)) ax.set_yticklabels(new_labels) if cn.PLT_TITLE in",
"ax=None, fig=None, is_include_missing_mutations=True, parms=PlotParms(), is_plot=None): \"\"\" Constructs a heatmap comparing",
"import Isolate from microbepy.common import util from microbepy.correlation import genome_correlation",
"self._plotTransferCompare(df, heat_range=[0, 1.0], ordered_columns=ordered_columns, parms=parms, transfer=transfer, other_transfer=other_transfer, is_center_colorbar=is_center_colorbar, is_include_missing_mutations=is_include_missing_mutations, **kwargs)",
"on the heatmap :param list-str ordered_columns: order in which columns",
"value is fraction \"\"\" if is_plot is None: is_plot =",
"for p in zip(transfers[:-1], transfers[1:])] else: pairs = [p for",
"['red', 'green', 'blue'] SPECIES = {cn.SPECIES_MIX_DVH: \"DVH\", cn.SPECIES_MIX_MMP: \"MMP\", None:",
"df return result def plotSiglvl(self, max_siglvl=MAX_SIGLVL, transfer=cn.TRANSFER_DEFAULT, other_transfer=None, is_center_colorbar =",
"how='all', inplace=True) is_include_missing_mutations = False else: is_include_missing_mutations = True ordered_columns",
"parms=PlotParms(), **kwargs): \"\"\" Constructs a heatmap of the mutation coocurrence",
"label = \"No. Lines\" else: label = \"Fraction\" ax.set_ylabel(label ,",
"significance level :return pd.DataFrame: columns, rows are mutations \"\"\" df_plot",
"= self.cofraction.ordered_mutations transfers = self.cofraction.transfers num_transfers = len(transfers) fig, axes",
"df_matrix = genome_correlation.makeSiglvlDF(df_binary_rows, df_other=df_binary_columns) return df_matrix def _plotSiglvlDF(self, transfer=cn.TRANSFER_DEFAULT, other_transfer=None,",
"parms[cn.PLT_TITLE] = \"%s, %d\" % (self._species, transfer) if idx ==",
"= False if idx == 4: parms[cn.PLT_COLORBAR] = True else:",
"of transfers, value is data_frame \"\"\" def funcDF(transfer, other_transfer): return",
"df_transformed = df_sort.applymap(lambda v: np.log10(v)) df_transformed = df_transformed.applymap(lambda v: -v)",
"= species self.cofraction = MutationCofraction(species=self._species, mutation_column=mutation_column) def plotTransfers(self, parms=PlotParms(is_initialize=False), is_unit_fraction",
"transfer in enumerate(transfers): parms[cn.PLT_YTICKLABELS] = True if self._species is None:",
"constants as cn from microbepy.common.dataframe_sorter import DataframeSorter from microbepy.common.isolate import",
"pairs = [p for p in zip(transfers[:-1], transfers[:-1])] # #",
"if None, then use alphabetical order :param bool is_unit_fraction: round",
"def plotTransfers(self, parms=PlotParms(is_initialize=False), is_unit_fraction = False, is_cluster_mutations=True): \"\"\" Does a",
":param PlotParms parms: Parameters for the plot :param bool is_plot:",
"self._mutation_column) parms[cn.PLT_YLABEL] = makeLabel( transfer, self._mutation_column) ax.text(xpos, ypos, xlabel, fontsize=parms.fontsize_label)",
"import MutationCofraction from microbepy.plot.util_plot import PlotParms import matplotlib.pyplot as plt",
"if (len(pairs) == 4) else 3 fig = plt.figure(figsize=parms[cn.PLT_FIGSIZE]) result",
"transfer if ax is None: if fig is None: fig",
"\"\"\" Constructs a the dataframe used for heatmap. :param int",
"bool is_time_lag: construct time lag subplots :param bool is_differenced: Computes",
"subplots of mutation mutations over transfers. :param Function funcDF: has",
"\"\"\" Constructs a heatmap comparing values for mutations from two",
"pd.DataFrame: mutations, mutations, values are -log10 significance level \"\"\" df_matrix",
"else: label = \"Fraction\" ax.set_ylabel(label , fontsize=FONTSIZE_LABEL) if parms.isTrue(cn.PLT_XLABEL): ax.set_xlabel(self._mutation_column,",
"is_time_lag=False, threshold_frac=THRESHOLD_FRAC, is_difference_frac=False, is_differenced=False, is_compress=False, parms=PlotParms(), **kwargs): \"\"\" Does a",
"else: parms[cn.PLT_LEGEND] = True parms[cn.PLT_XLABEL] = True parms[cn.PLT_XTICKLABELS] = True",
"transfer) if idx == 0: parms[cn.PLT_YLABEL] = True else: parms[cn.PLT_YLABEL]",
"len(labels)) ax.set_xticklabels(new_labels) if parms.isFalse(cn.PLT_YTICKLABELS): labels = ax.get_yticklabels() new_labels = np.repeat(\"\",",
"setValue(a_dict, key, default): if not key in a_dict.keys(): a_dict[key] =",
"self._mutation_column = mutation_column self._is_plot = is_plot self._species = species self.cofraction",
"df_plot = self._plotSiglvlDF(transfer=transfer, other_transfer=other_transfer, max_siglvl=max_siglvl) self._plotTransferCompare(df_plot, heat_range = [COLORBAR_MIN, COLORBAR_MAX],",
"else: pairs = [p for p in zip(transfers[:-1], transfers[:-1])] #",
"= pair[0] other_transfer = pair[1] df = funcDF(transfer=transfer, other_transfer=other_transfer) df",
"pd.DataFrame: row=mutation, col=line + transfer, value is fraction \"\"\" permitted_mutations",
":param bool is_plot: Overrides constructor plotting directive :param bool is_include_missing_mutations:",
"is None: fig = plt.figure(figsize=parms[cn.PLT_FIGSIZE]) ax = fig.add_subplot(1, 1, 1)",
"columns, rows are mutations \"\"\" if is_differenced: df = self.cofraction.makeCofractionDifferencedDF(",
"use alphabetical order :param bool is_unit_fraction: round non-zero fraction to",
"df_plot = sorter.deleteNanRowsAndColumns() return df_plot def plotCofractions(self, is_time_lag=False, threshold_frac=THRESHOLD_FRAC, is_difference_frac=False,",
"funcDF(transfer, other_transfer): if is_differenced: df = self.cofraction.makeCofractionDifferencedDF( transfer=transfer, other_transfer=other_transfer, threshold_frac=threshold_frac)",
"= parms[cn.PLT_TITLE] else: title = \"%s Mutations\" % SPECIES[self._species] xpos",
"else v) else: df = self.cofraction.makeCofractionDF(transfer=transfer, is_difference_frac=is_difference_frac, other_transfer=other_transfer, **kwargs) df",
"< ubound else v) sorter = DataframeSorter(df_plot) df_plot = sorter.deleteNanRowsAndColumns()",
"minimum fractional occurrence of a mutation within a line for",
"time lag subplots :param dict kwargs: non-transfer parameters passed to",
"# return self._plotTransfers(funcDF, is_time_lag, parms=parms, heat_range=[0, 1.0], **kwargs) def plotSiglvls(self,",
"ax=None, permitted_mutations=None): \"\"\" Does a stacked bar plot of mutation",
"Eliminate implicit label if parms.isFalse(cn.PLT_XTICKLABELS): labels = ax.get_xticklabels() new_labels =",
"2 if (len(pairs) == 4) else 3 fig = plt.figure(figsize=parms[cn.PLT_FIGSIZE])",
"mutation_column=mutation_column) def plotTransfers(self, parms=PlotParms(is_initialize=False), is_unit_fraction = False, is_cluster_mutations=True): \"\"\" Does",
"= -0.05*len(rows) parms[cn.PLT_XLABEL] = \"\" xlabel = makeLabel(other_transfer, self._mutation_column) parms[cn.PLT_YLABEL]",
"= self.cofraction.makeCofractionDifferencedDF( transfer=transfer, other_transfer=other_transfer, threshold_frac=threshold_frac) else: df = self.cofraction.makeCofractionDF(transfer=transfer, is_difference_frac=is_difference_frac,",
"self.cofraction.makeCofractionDifferencedDF( transfer=transfer, other_transfer=other_transfer, threshold_frac=threshold_frac) else: df = self.cofraction.makeCofractionDF(transfer=transfer, is_difference_frac=is_difference_frac, other_transfer=other_transfer)",
"dict kwargs: non-transfer parameters passed to next level :return dict:",
"cb = fig.colorbar(plot, cmap='jet') cb.ax.tick_params(labelsize=parms.fontsize_label) row_labels = df_plot.columns.tolist() col_labels =",
"1.0], **kwargs) def plotSiglvls(self, is_time_lag=False, max_siglvl=MAX_SIGLVL, parms=PlotParms(), **kwargs): \"\"\" Does",
"8) if ax is None: ax = df_plot.plot(kind='bar', stacked=True, figsize=parms[cn.PLT_FIGSIZE],",
"**kwargs) result[pair] = df return result def plotSiglvl(self, max_siglvl=MAX_SIGLVL, transfer=cn.TRANSFER_DEFAULT,",
"def _plotTransfers(self, funcDF, is_time_lag, parms=PlotParms(), **kwargs): \"\"\" Does a subplots",
"Mutations\" % SPECIES[self._species] xpos = int(len(df_plot)*0.5) ypos = MAX_LINES -",
"parms[cn.PLT_XTICKLABELS] = False else: parms[cn.PLT_LEGEND] = True parms[cn.PLT_XLABEL] = True",
"\"No. Lines\" else: label = \"Fraction\" ax.set_ylabel(label , fontsize=FONTSIZE_LABEL) if",
"= df_line.applymap( lambda v: 1.0 if v > min_fraction else",
"= transfer dfs.append(df) if self._is_plot: plt.show() return pd.concat(dfs) def plotLine(self,",
"Set up for plots nrows = 2 if (len(pairs) ==",
"v < ubound else v) sorter = DataframeSorter(df_plot) df_plot =",
"matplotlib.pyplot as plt import numpy as np import pandas as",
"of mutations as columns and index; values are used in",
"ordered if None, then use alphabetical order :param bool is_unit_fraction:",
"cmap='jet') cb.ax.tick_params(labelsize=parms.fontsize_label) else: cb = fig.colorbar(plot, cmap='jet') cb.ax.tick_params(labelsize=parms.fontsize_label) row_labels =",
"num_transfers = len(transfers) fig, axes = plt.subplots(nrows=num_transfers, ncols=1) dfs =",
"None: is_plot = self._is_plot elif not self._is_plot: is_plot = self._is_plot",
"bool is_plot: Overrides constructor plotting directive :param bool is_include_missing_mutations: \"\"\"",
"5]: parms[cn.PLT_XAXISTICKTOP] = True else: parms[cn.PLT_XAXISTICKTOP] = False if idx",
"-v) ubound = -np.log10(max_siglvl) df_plot = df_transformed.applymap( lambda v: np.nan",
"Isolate from microbepy.common import util from microbepy.correlation import genome_correlation from",
"is data_frame \"\"\" def funcDF(transfer, other_transfer): return self._plotSiglvlDF(transfer=transfer, max_siglvl=max_siglvl, other_transfer=other_transfer)",
"not key in a_dict.keys(): a_dict[key] = default # if is_plot",
"and how they are ordered if None, then use alphabetical",
"transfer=transfer, other_transfer=other_transfer, **kwargs) df = df.applymap(lambda v: np.nan if np.abs(v)",
"[p for p in zip(transfers[:-1], transfers[:-1])] # # Calculate the",
"permitted_mutations = self.cofraction.ordered_mutations transfers = self.cofraction.transfers num_transfers = len(transfers) fig,",
"bool is_time_lag: construct time lag subplots :param dict kwargs: non-transfer",
"df_plot.index.tolist() columns = df_plot.columns.tolist() mutations = df_plot.columns.tolist() # Set up",
"0.5*len(rows) ypos = -1 ax.set_ylabel(ylabel, fontsize=parms.fontsize_label, x=xpos, y=ypos) #plt.show() parms.do(is_plot=is_plot)",
"columns and index; values are used in the heatmap. :param",
"# df_plot = self.cofraction.makeLineDF( permitted_mutations=permitted_mutations, transfer=transfer) if is_unit_fraction: df_plot =",
":param Matplotlib.Axes ax: :param PlotParms parms: Parameters for the plot",
"= {} for idx, pair in enumerate(pairs): idx += 1",
"= \"No. Lines\" else: label = \"Fraction\" ax.set_ylabel(label , fontsize=FONTSIZE_LABEL)",
"df = self.cofraction.makeCofractionDifferencedDF( transfer=transfer, other_transfer=other_transfer, threshold_frac=threshold_frac) else: df = self.cofraction.makeCofractionDF(transfer=transfer,",
"is_unit_fraction: df_plot = df_plot.applymap( lambda v: 1 if v> MIN_FRACTION",
"is None: other_transfer = transfer if ax is None: if",
"= df_plot.columns.tolist() columns = df_plot.columns.tolist() else: extended_ordered_columns = ordered_columns rows",
"\"%d\" % transfer else: parms[cn.PLT_TITLE] = \"%s, %d\" % (self._species,",
"**kwargs): \"\"\" Does a subplots of the fraction of lines",
"heat_range = [COLORBAR_MIN, COLORBAR_MAX], **kwargs) def _plotTransfers(self, funcDF, is_time_lag, parms=PlotParms(),",
"frequency for all transfers. :param bool is_unit_fraction: round fraction to",
"pd.concat(dfs) def plotLine(self, transfer, parms=PlotParms(is_initialize=False), is_unit_fraction=False, is_plot=None, ax=None, permitted_mutations=None): \"\"\"",
"permitted_mutations: to use and how they are ordered if None,",
"inplace=True) df.dropna(axis=1, how='all', inplace=True) return df # return self._plotTransfers(funcDF, is_time_lag,",
"lambda v: 1.0 if v > min_fraction else 0) return",
"**kwargs) def plotSiglvls(self, is_time_lag=False, max_siglvl=MAX_SIGLVL, parms=PlotParms(), **kwargs): \"\"\" Does a",
"np.nan if np.abs(v) < threshold_frac else v) else: df =",
"xpos = int(len(df_plot)*0.5) ypos = MAX_LINES - 3 ax.text(xpos, ypos,",
"lines in which mutations co-occur. :param bool is_time_lag: construct time",
"use and how they are ordered if None, then use",
"other_transfer=None, is_center_colorbar = True, **kwargs): \"\"\" Constructs a heatmap of",
"microbepy.plot.mutation_cofraction import MutationCofraction from microbepy.plot.util_plot import PlotParms import matplotlib.pyplot as",
"= \"\" parms.do(is_plot=False) ylabel = makeLabel(transfer, self._mutation_column) xpos = -3",
"construct time lag subplots :param bool is_differenced: Computes the difference",
"transfer: transfer time for row mutations :param int other_transfer: transfer",
"a dataframe of mutations as columns and index; values are",
"<filename>microbepy/plot/mutation_plot.py \"\"\"Provides plots of mutations for Isolates and Lines.\"\"\" from",
"else: title = \"%s Mutations\" % SPECIES[self._species] xpos = int(len(df_plot)*0.5)",
"return df_plot def plotCofractions(self, is_time_lag=False, threshold_frac=THRESHOLD_FRAC, is_difference_frac=False, is_differenced=False, is_compress=False, parms=PlotParms(),",
"count fractions :param dict kwargs: non-transfer parameters passed to next",
"parms[cn.PLT_XLABEL] = \"\" setValue(parms, cn.PLT_COLORBAR, True) xpos = 1.05*len(columns) ypos",
"idx, transfer in enumerate(transfers): parms[cn.PLT_YTICKLABELS] = True if self._species is",
"up for plots nrows = 2 if (len(pairs) == 4)",
"if idx == 0: parms[cn.PLT_YLABEL] = True else: parms[cn.PLT_YLABEL] =",
"# # Construct the plot plot = ax.pcolor(df_plot, cmap='jet', vmin=heat_range[0],",
"= df.applymap(lambda v: np.nan if np.abs(v) < threshold_frac else v)",
"= 0.5*len(rows) ypos = -1 ax.set_ylabel(ylabel, fontsize=parms.fontsize_label, x=xpos, y=ypos) #plt.show()",
"mutation_column: :param bool is_plot: \"\"\" self._mutation_column = mutation_column self._is_plot =",
"if idx in [1, 2, 5]: parms[cn.PLT_XAXISTICKTOP] = True else:",
"= True if other_transfer is None: other_transfer = transfer if",
"== 4: parms[cn.PLT_COLORBAR] = True else: parms[cn.PLT_COLORBAR] = False transfer",
"key is pair of transfers, value is data_frame \"\"\" NCOLS",
"min_fraction=MIN_FRACTION): \"\"\" Creates a significance level matrix for mutations. :param",
"1.05*len(columns) ypos = -0.05*len(rows) parms[cn.PLT_XLABEL] = \"\" xlabel = makeLabel(other_transfer,",
"df_sort.applymap(lambda v: np.log10(v)) df_transformed = df_transformed.applymap(lambda v: -v) ubound =",
"other_transfer=cn.TRANSFER_1000G) df = df.fillna(0) # Set up for plots nrows",
"else: parms[cn.PLT_TITLE] = \"%s, %d\" % (self._species, transfer) if idx",
"PlotParms parms: Parameters for the plot :param bool is_plot: Overrides",
"fig.add_subplot(1, 1, 1) # Order the columns if is_include_missing_mutations: columns",
"else 3 fig = plt.figure(figsize=parms[cn.PLT_FIGSIZE]) result = {} for idx,",
"is_plot = self._is_plot if ordered_columns is None: ordered_columns = list(set(df_plot.columns.tolist()).union(",
"= df.applymap(lambda v: np.nan if v == 0 else v)",
"is None: is_plot = self._is_plot elif not self._is_plot: is_plot =",
"rotation=90, fontsize=parms.fontsize_label) ax.set_yticks(np.arange(0.5, len(col_labels))) ax.set_yticklabels(col_labels, fontsize=parms.fontsize_label) #parms[cn.PLT_YLABEL] = \"\" parms.do(is_plot=False)",
"= np.nan df_plot = df_plot.reindex(extended_ordered_columns) df_plot = df_plot[extended_ordered_columns] rows =",
"\"\"\" def funcDF(transfer, other_transfer): return self._plotSiglvlDF(transfer=transfer, max_siglvl=max_siglvl, other_transfer=other_transfer) # return",
"'blue'] SPECIES = {cn.SPECIES_MIX_DVH: \"DVH\", cn.SPECIES_MIX_MMP: \"MMP\", None: \"both\"} FONTSIZE_TITLE",
"makeLabel( transfer, self._mutation_column) ax.text(xpos, ypos, xlabel, fontsize=parms.fontsize_label) # # Construct",
"not self._is_plot: is_plot = self._is_plot if ordered_columns is None: ordered_columns",
"lag subplots :param dict kwargs: non-transfer parameters passed to next",
"for column mutations :param float min_fraction: minimum fractional occurrence of",
"**kwargs) df = df.applymap(lambda v: np.nan if np.abs(v) < threshold_frac",
"return df def _plotTransferCompare(self, df_plot, heat_range, ordered_columns=None, is_center_colorbar=True, transfer=cn.TRANSFER_DEFAULT, other_transfer=None,",
"cbaxes, cmap='jet') cb.ax.tick_params(labelsize=parms.fontsize_label) else: cb = fig.colorbar(plot, cmap='jet') cb.ax.tick_params(labelsize=parms.fontsize_label) row_labels",
"else: parms[cn.PLT_XAXISTICKTOP] = False if idx == 4: parms[cn.PLT_COLORBAR] =",
"for col in missing_columns: df_plot[col] = np.nan df_plot.loc[col, :] =",
"== 0 else v) self._plotTransferCompare(df, transfer=transfer, other_transfer=other_transfer, ordered_columns=self.cofraction.ordered_mutations, is_center_colorbar=True, fig=fig,",
"1: parms[cn.PLT_LEGEND] = False parms[cn.PLT_XLABEL] = False parms[cn.PLT_XTICKLABELS] = False",
"parms[cn.PLT_YLABEL] = makeLabel( transfer, self._mutation_column) ax.text(xpos, ypos, xlabel, fontsize=parms.fontsize_label) #",
"[COLORBAR_MIN, COLORBAR_MAX], ordered_mutations=self.cofraction.ordered_mutations, transfer=transfer, other_transfer=other_transfer, is_center_colorbar=is_center_colorbar, **kwargs) return df_plot def",
"transfer=transfer, other_transfer=other_transfer, is_center_colorbar=is_center_colorbar, **kwargs) return df_plot def plotCofraction(self, threshold_frac=THRESHOLD_FRAC, transfer=cn.TRANSFER_DEFAULT,",
"dfs.append(df) if self._is_plot: plt.show() return pd.concat(dfs) def plotLine(self, transfer, parms=PlotParms(is_initialize=False),",
"from microbepy.common import constants as cn from microbepy.common.dataframe_sorter import DataframeSorter",
"\"\"\" Does a subplots of mutation mutations over transfers. :param",
"ax=ax, figsize=parms[cn.PLT_FIGSIZE]) ax.set_xlabel(\"\", fontsize=FONTSIZE_LABEL) # Eliminate implicit label if parms.isFalse(cn.PLT_XTICKLABELS):",
"import util_data from microbepy.plot.mutation_cofraction import MutationCofraction from microbepy.plot.util_plot import PlotParms",
"ax.legend(loc=(1,2)) #ax.legend() if is_plot: plt.show() return df_plot def _makeMutationSiglvlMatrix(self, transfer=cn.TRANSFER_DEFAULT,",
"v < threshold_frac else v) if is_compress: df.dropna(axis=0, how='all', inplace=True)",
"self._mutation_column) xpos = -3 ypos = 0.5*len(rows) ypos = -1",
"round non-zero fraction to 1 :return pd.DataFrame: row=mutation, col=line, value",
"ubound = -np.log10(max_siglvl) df_plot = df_transformed.applymap( lambda v: np.nan if",
"df_plot = self.cofraction.makeLineDF( permitted_mutations=permitted_mutations, transfer=transfer) if is_unit_fraction: df_plot = df_plot.applymap(",
"of transfers, value is data_frame \"\"\" def funcDF(transfer, other_transfer): if",
"return df_binary.transpose() # if other_transfer is None: other_transfer = transfer",
"df_plot.columns.tolist() missing_columns = set(ordered_columns).difference(columns) extended_ordered_columns = list(ordered_columns) extended_ordered_columns.extend( set(columns).difference(ordered_columns)) for",
"\"\"\" Does a stacked bar plot of mutation frequency by",
"ubound else v) sorter = DataframeSorter(df_plot) df_plot = sorter.deleteNanRowsAndColumns() return",
"= ordered_columns rows = df_plot.index.tolist() columns = df_plot.columns.tolist() mutations =",
"DataframeSorter(df_plot) df_plot = sorter.deleteNanRowsAndColumns() return df_plot def plotCofractions(self, is_time_lag=False, threshold_frac=THRESHOLD_FRAC,",
"extended_ordered_columns.extend( set(columns).difference(ordered_columns)) for col in missing_columns: df_plot[col] = np.nan df_plot.loc[col,",
"columns if is_include_missing_mutations: columns = df_plot.columns.tolist() missing_columns = set(ordered_columns).difference(columns) extended_ordered_columns",
"rows = df_plot.index.tolist() columns = df_plot.columns.tolist() mutations = df_plot.columns.tolist() #",
"colors :params int transfer: :params PlotParms parms: :params Axis ax:",
"\"\"\" permitted_mutations = self.cofraction.ordered_mutations transfers = self.cofraction.transfers num_transfers = len(transfers)",
"4:6} NPLOTS = 6 transfers = self.cofraction.transfers if is_time_lag: pairs",
"True ordered_columns = self.cofraction.ordered_mutations self._plotTransferCompare(df, heat_range=[0, 1.0], ordered_columns=ordered_columns, parms=parms, transfer=transfer,",
"ax.set_xticklabels(new_labels) if parms.isFalse(cn.PLT_YTICKLABELS): labels = ax.get_yticklabels() new_labels = np.repeat(\"\", len(labels))",
"= \"%s, %d\" % (self._species, transfer) if idx == 0:",
"fraction \"\"\" if is_plot is None: is_plot = self._is_plot parms.setTrueIfAbsent(cn.PLT_XLABEL)",
"ordered_columns = list(set(df_plot.columns.tolist()).union( df_plot.index)) # Do the plot if not",
"df_plot.index.tolist() if parms.isTrue(cn.PLT_XAXISTICKTOP): ax.xaxis.tick_top() ax.set_xticks(np.arange(0.5, len(row_labels))) ax.set_xticklabels(row_labels, rotation=90, fontsize=parms.fontsize_label) ax.set_yticks(np.arange(0.5,",
"1) # Order the columns if is_include_missing_mutations: columns = df_plot.columns.tolist()",
"= \"\" xlabel = makeLabel(other_transfer, self._mutation_column) parms[cn.PLT_YLABEL] = makeLabel( transfer,",
"if is_unit_fraction: label = \"No. Lines\" else: label = \"Fraction\"",
"1.0], ordered_columns=ordered_columns, parms=parms, transfer=transfer, other_transfer=other_transfer, is_center_colorbar=is_center_colorbar, is_include_missing_mutations=is_include_missing_mutations, **kwargs) return df",
"pair of transfers, value is data_frame \"\"\" NCOLS = 3",
"if v < ubound else v) sorter = DataframeSorter(df_plot) df_plot",
"is_center_colorbar=True, fig=fig, ax=ax, parms=parms, is_plot=is_plot, **kwargs) result[pair] = df return",
"# return self._plotTransfers(funcDF, is_time_lag, parms=parms, heat_range = [COLORBAR_MIN, COLORBAR_MAX], **kwargs)",
"parms[cn.PLT_XLABEL] = \"\" xlabel = makeLabel(other_transfer, self._mutation_column) parms[cn.PLT_YLABEL] = makeLabel(",
"fig is None: fig = plt.figure(figsize=parms[cn.PLT_FIGSIZE]) ax = fig.add_subplot(1, 1,",
"plot = ax.pcolor(df_plot, cmap='jet', vmin=heat_range[0], vmax=heat_range[1]) if parms.isTrue(cn.PLT_COLORBAR): if is_center_colorbar:",
"transfer time for column mutations :param float min_fraction: minimum fractional",
"# Do the plot if not cn.PLT_COLORBAR in parms: parms[cn.PLT_COLORBAR]",
"permitted_mutations=permitted_mutations, transfer=transfer) if is_unit_fraction: df_plot = df_plot.applymap( lambda v: 1",
"other_transfer = transfer # df_binary_rows = makeDF(transfer) df_binary_columns = makeDF(other_transfer)",
"\"\"\" if is_differenced: df = self.cofraction.makeCofractionDifferencedDF( threshold_frac=threshold_frac, transfer=transfer, other_transfer=other_transfer, **kwargs)",
"transfers. :param Function funcDF: has kwargs transfer, other_transfer; returns a",
"fig.colorbar(plot, cmap='jet') cb.ax.tick_params(labelsize=parms.fontsize_label) row_labels = df_plot.columns.tolist() col_labels = df_plot.index.tolist() if",
"False, is_cluster_mutations=True): \"\"\" Does a stacked bar plot of mutation",
"how='all', inplace=True) return df # return self._plotTransfers(funcDF, is_time_lag, parms=parms, heat_range=[0,",
"is_plot = self._is_plot parms.setTrueIfAbsent(cn.PLT_XLABEL) parms.setTrueIfAbsent(cn.PLT_XTICKLABELS) # df_plot = self.cofraction.makeLineDF( permitted_mutations=permitted_mutations,",
"= self._is_plot if ordered_columns is None: ordered_columns = list(set(df_plot.columns.tolist()).union( df_plot.index))",
"order df = funcDF(transfer=cn.TRANSFER_1000G, other_transfer=cn.TRANSFER_1000G) df = df.fillna(0) # Set",
"df_matrix def _plotSiglvlDF(self, transfer=cn.TRANSFER_DEFAULT, other_transfer=None, max_siglvl=MAX_SIGLVL): \"\"\" Constructs a the",
"parms[cn.PLT_COLORBAR] = False transfer = pair[0] other_transfer = pair[1] df",
"ax is None: ax = df_plot.plot(kind='bar', stacked=True, figsize=parms[cn.PLT_FIGSIZE], legend=None) else:",
"num_transfers - 1: parms[cn.PLT_LEGEND] = False parms[cn.PLT_XLABEL] = False parms[cn.PLT_XTICKLABELS]",
"df_plot.columns.tolist() col_labels = df_plot.index.tolist() if parms.isTrue(cn.PLT_XAXISTICKTOP): ax.xaxis.tick_top() ax.set_xticks(np.arange(0.5, len(row_labels))) ax.set_xticklabels(row_labels,",
"df_plot.applymap( lambda v: 1 if v> MIN_FRACTION else v) #",
"in count fractions :param dict kwargs: non-transfer parameters passed to",
"% (self._species, transfer) if idx == 0: parms[cn.PLT_YLABEL] = True",
"subplots :param bool is_differenced: Computes the difference in count fractions",
"= makeLabel( transfer, self._mutation_column) ax.text(xpos, ypos, xlabel, fontsize=parms.fontsize_label) # #",
"self.cofraction = MutationCofraction(species=self._species, mutation_column=mutation_column) def plotTransfers(self, parms=PlotParms(is_initialize=False), is_unit_fraction = False,",
"significance level matrix for mutations. :param int transfer: transfer time",
"xpos = -3 ypos = 0.5*len(rows) ypos = -1 ax.set_ylabel(ylabel,",
"col=line + transfer, value is fraction \"\"\" permitted_mutations = self.cofraction.ordered_mutations",
"if not key in a_dict.keys(): a_dict[key] = default # if",
"v) sorter = DataframeSorter(df_plot) df_plot = sorter.deleteNanRowsAndColumns() return df_plot def",
"ypos = MAX_LINES - 3 ax.text(xpos, ypos, title, fontsize=FONTSIZE_TITLE) ax.set_ylim([0,",
"the mutation coocurrence fractions. :param int transfer: Transfer for which",
"= False else: is_include_missing_mutations = True ordered_columns = self.cofraction.ordered_mutations self._plotTransferCompare(df,",
"= self.cofraction.transfers num_transfers = len(transfers) fig, axes = plt.subplots(nrows=num_transfers, ncols=1)",
"columns appear :param bool is_center_colorbar: center the colorbar in the",
"in [1, 2, 5]: parms[cn.PLT_XAXISTICKTOP] = True else: parms[cn.PLT_XAXISTICKTOP] =",
"df_binary = df_line.applymap( lambda v: 0 if np.isnan(v) else v)",
"parms[cn.PLT_XAXISTICKTOP] = False if idx == 4: parms[cn.PLT_COLORBAR] = True",
"columns = df_plot.columns.tolist() else: extended_ordered_columns = ordered_columns rows = df_plot.index.tolist()",
"is_plot: plt.show() return df_plot def _makeMutationSiglvlMatrix(self, transfer=cn.TRANSFER_DEFAULT, other_transfer=None, min_fraction=MIN_FRACTION): \"\"\"",
"the column order df = funcDF(transfer=cn.TRANSFER_1000G, other_transfer=cn.TRANSFER_1000G) df = df.fillna(0)",
"ModelDataProvider from microbepy.data import util_data from microbepy.plot.mutation_cofraction import MutationCofraction from",
"is_compress: Eliminate rows/columns with 0 values :return pd.DataFrame: columns, rows",
":param dict kwargs: non-transfer parameters passed to next level :return",
"bool is_include_missing_mutations: \"\"\" def makeLabel(transfer, column, is_include_column=False): if is_include_column: label",
"DataframeSorter(df_matrix) df_sort = sorter.orderBoth() # df_transformed = df_sort.applymap(lambda v: np.log10(v))",
"across time :param Matplotlib.Axes ax: :param PlotParms parms: Parameters for",
"\"\" xlabel = makeLabel(other_transfer, self._mutation_column) parms[cn.PLT_YLABEL] = makeLabel( transfer, self._mutation_column)",
"df = self.plotLine(transfer, parms=parms, is_plot=False, ax=axes[idx], permitted_mutations=permitted_mutations, is_unit_fraction=is_unit_fraction) df[cn.TRANSFER] =",
"plotSiglvls(self, is_time_lag=False, max_siglvl=MAX_SIGLVL, parms=PlotParms(), **kwargs): \"\"\" Does a subplots of",
"non-transfer parameters passed to next level :return dict: key is",
"used for heatmap. :param int transfer: :param float max_siglvl: :return",
"# Do the plot if not cn.PLT_FIGSIZE in parms: parms[cn.PLT_FIGSIZE]",
"permitted_mutations=permitted_mutations, is_unit_fraction=is_unit_fraction) df[cn.TRANSFER] = transfer dfs.append(df) if self._is_plot: plt.show() return",
"figsize=parms[cn.PLT_FIGSIZE], legend=None) else: df_plot.plot(kind='bar', stacked=True, legend=None, ax=ax, figsize=parms[cn.PLT_FIGSIZE]) ax.set_xlabel(\"\", fontsize=FONTSIZE_LABEL)",
"self.cofraction.makeCofractionDifferencedDF( threshold_frac=threshold_frac, transfer=transfer, other_transfer=other_transfer, **kwargs) df = df.applymap(lambda v: np.nan",
"is_include_missing_mutations = True ordered_columns = self.cofraction.ordered_mutations self._plotTransferCompare(df, heat_range=[0, 1.0], ordered_columns=ordered_columns,",
"> min_fraction else 0) return df_binary.transpose() # if other_transfer is",
"a line for it to be considered :return pd.DataFrame: row",
"transfer: :param float max_siglvl: :return pd.DataFrame: mutations, mutations, values are",
"= self.plotLine(transfer, parms=parms, is_plot=False, ax=axes[idx], permitted_mutations=permitted_mutations, is_unit_fraction=is_unit_fraction) df[cn.TRANSFER] = transfer",
"v> MIN_FRACTION else v) # Do the plot if not",
"def plotLine(self, transfer, parms=PlotParms(is_initialize=False), is_unit_fraction=False, is_plot=None, ax=None, permitted_mutations=None): \"\"\" Does",
"import matplotlib.pyplot as plt import numpy as np import pandas",
"of lines in which mutations co-occur. :param bool is_time_lag: construct",
"fig=None, is_include_missing_mutations=True, parms=PlotParms(), is_plot=None): \"\"\" Constructs a heatmap comparing values",
"is_cluster_mutations: Group similar mutations together :return pd.DataFrame: row=mutation, col=line +",
"they are ordered if None, then use alphabetical order :param",
"is_difference_frac=is_difference_frac, other_transfer=other_transfer) if is_compress: df.dropna(axis=0, how='all', inplace=True) df.dropna(axis=1, how='all', inplace=True)",
"1 :param bool is_cluster_mutations: Group similar mutations together :return pd.DataFrame:",
"v: np.nan if v < threshold_frac else v) if is_compress:",
"for mutations from two transfers. :param pd.DataFrame df_plot: index and",
"True parms[cn.PLT_XLABEL] = True parms[cn.PLT_XTICKLABELS] = True df = self.plotLine(transfer,",
"= df_plot.applymap( lambda v: 1 if v> MIN_FRACTION else v)",
"range :param int transfer: :param int other_transfer: Allow comparisons across",
"idx, pair in enumerate(pairs): idx += 1 ax = fig.add_subplot(nrows,",
"positions: left, bottom, width, height cbaxes = fig.add_axes([.45, 0.2, 0.01,",
"a the dataframe used for heatmap. :param int transfer: :param",
"sorter.deleteNanRowsAndColumns() return df_plot def plotCofractions(self, is_time_lag=False, threshold_frac=THRESHOLD_FRAC, is_difference_frac=False, is_differenced=False, is_compress=False,",
"len(labels)) ax.set_yticklabels(new_labels) if cn.PLT_TITLE in parms: title = parms[cn.PLT_TITLE] else:",
"self._plotTransfers(funcDF, is_time_lag, parms=parms, heat_range=[0, 1.0], **kwargs) def plotSiglvls(self, is_time_lag=False, max_siglvl=MAX_SIGLVL,",
"if is_plot is None: is_plot = self._is_plot parms.setTrueIfAbsent(cn.PLT_XLABEL) parms.setTrueIfAbsent(cn.PLT_XTICKLABELS) #",
"level :return pd.DataFrame: columns, rows are mutations \"\"\" df_plot =",
"= df return result def plotSiglvl(self, max_siglvl=MAX_SIGLVL, transfer=cn.TRANSFER_DEFAULT, other_transfer=None, is_center_colorbar",
"self.cofraction.transfers num_transfers = len(transfers) fig, axes = plt.subplots(nrows=num_transfers, ncols=1) dfs",
"self.cofraction.makeLineDF(transfer=transfer) df_binary = df_line.applymap( lambda v: 0 if np.isnan(v) else",
"fig.add_axes([.45, 0.2, 0.01, 0.5]) cb = fig.colorbar(plot, cax = cbaxes,",
"the heatmap range :param int transfer: :param int other_transfer: Allow",
"3 fig = plt.figure(figsize=parms[cn.PLT_FIGSIZE]) result = {} for idx, pair",
"if is_compress: df.dropna(axis=0, how='all', inplace=True) df.dropna(axis=1, how='all', inplace=True) return df",
"parms.do(is_plot=False) if is_plot: parms[cn.PLT_YLABEL] = \"\" parms.do(is_plot=False) ylabel = makeLabel(transfer,",
"**kwargs): \"\"\" Does a subplots of mutation mutations over transfers.",
"MutationLinePlot(object): \"\"\" Plot mutations by occurrences within Lines. \"\"\" def",
"df_plot = df_transformed.applymap( lambda v: np.nan if v < ubound",
"= np.repeat(\"\", len(labels)) ax.set_xticklabels(new_labels) if parms.isFalse(cn.PLT_YTICKLABELS): labels = ax.get_yticklabels() new_labels",
"of the mutation coocurrence fractions. :param int transfer: Transfer for",
"plot :param bool is_plot: Overrides constructor plotting directive :param bool",
"a subplots of mutation mutations over transfers. :param Function funcDF:",
"np.nan if v == 0 else v) self._plotTransferCompare(df, transfer=transfer, other_transfer=other_transfer,",
"None: ordered_columns = list(set(df_plot.columns.tolist()).union( df_plot.index)) # Do the plot if",
"funcDF: has kwargs transfer, other_transfer; returns a dataframe of mutations",
"float: values on the heatmap range :param int transfer: :param",
"if is_plot: plt.show() return df_plot def _makeMutationSiglvlMatrix(self, transfer=cn.TRANSFER_DEFAULT, other_transfer=None, min_fraction=MIN_FRACTION):",
"microbepy.common import constants as cn from microbepy.common.dataframe_sorter import DataframeSorter from",
"int transfer: :params PlotParms parms: :params Axis ax: axis to",
"parms[cn.PLT_YTICKLABELS] = True if self._species is None: parms[cn.PLT_TITLE] = \"%d\"",
"= [COLORBAR_MIN, COLORBAR_MAX], **kwargs) def _plotTransfers(self, funcDF, is_time_lag, parms=PlotParms(), **kwargs):",
"other_transfer=None, is_difference_frac=False, is_differenced=False, is_center_colorbar=True, is_compress=False, parms=PlotParms(), **kwargs): \"\"\" Constructs a",
":param list-str ordered_columns: order in which columns appear :param bool",
"kwargs transfer, other_transfer; returns a dataframe of mutations as columns",
"plots of mutations for Isolates and Lines.\"\"\" from microbepy.common import",
"MAX_LINES = 9 MIN_FRACTION = 0.25 THRESHOLD_FRAC = 0.2 MAX_SIGLVL",
"else v) sorter = DataframeSorter(df_plot) df_plot = sorter.deleteNanRowsAndColumns() return df_plot",
"is_difference_frac=False, is_differenced=False, is_compress=False, parms=PlotParms(), **kwargs): \"\"\" Does a subplots of",
"\"Fraction\" ax.set_ylabel(label , fontsize=FONTSIZE_LABEL) if parms.isTrue(cn.PLT_XLABEL): ax.set_xlabel(self._mutation_column, fontsize=FONTSIZE_LABEL) if parms.isTrue(cn.PLT_LEGEND):",
"int transfer: Transfer for which plot is done :param bool",
"< threshold_frac else v) if is_compress: df.dropna(axis=0, how='all', inplace=True) df.dropna(axis=1,",
"pd import seaborn as sns COLORS = ['red', 'green', 'blue']",
"parms[cn.PLT_TITLE] else: title = \"%s Mutations\" % SPECIES[self._species] xpos =",
"parms=parms, is_plot=False, ax=axes[idx], permitted_mutations=permitted_mutations, is_unit_fraction=is_unit_fraction) df[cn.TRANSFER] = transfer dfs.append(df) if",
":return pd.DataFrame: row=mutation, col=line, value is fraction \"\"\" if is_plot",
"ylabel = makeLabel(transfer, self._mutation_column) xpos = -3 ypos = 0.5*len(rows)",
"vmax=heat_range[1]) if parms.isTrue(cn.PLT_COLORBAR): if is_center_colorbar: # Colorbar positions: left, bottom,",
"comparisons across time :param Matplotlib.Axes ax: :param PlotParms parms: Parameters",
"how='all', inplace=True) df.dropna(axis=1, how='all', inplace=True) return df # return self._plotTransfers(funcDF,",
"np.repeat(\"\", len(labels)) ax.set_xticklabels(new_labels) if parms.isFalse(cn.PLT_YTICKLABELS): labels = ax.get_yticklabels() new_labels =",
"mutations by occurrences within Lines. \"\"\" def __init__(self, mutation_column=cn.GGENE_ID, species=None,",
"microbepy.correlation import genome_correlation from microbepy.data.model_data_provider import ModelDataProvider from microbepy.data import",
"as sns COLORS = ['red', 'green', 'blue'] SPECIES = {cn.SPECIES_MIX_DVH:",
"transfer, self._mutation_column) ax.text(xpos, ypos, xlabel, fontsize=parms.fontsize_label) # # Construct the",
"return df_plot def plotCofraction(self, threshold_frac=THRESHOLD_FRAC, transfer=cn.TRANSFER_DEFAULT, other_transfer=None, is_difference_frac=False, is_differenced=False, is_center_colorbar=True,",
"= 1.0 COLORBAR_MAX = 4.0 class MutationLinePlot(object): \"\"\" Plot mutations",
":param int transfer: :param int other_transfer: Allow comparisons across time",
"fraction to 1 :return pd.DataFrame: row=mutation, col=line, value is fraction",
"label = \"Fraction\" ax.set_ylabel(label , fontsize=FONTSIZE_LABEL) if parms.isTrue(cn.PLT_XLABEL): ax.set_xlabel(self._mutation_column, fontsize=FONTSIZE_LABEL)",
"SPECIES = {cn.SPECIES_MIX_DVH: \"DVH\", cn.SPECIES_MIX_MMP: \"MMP\", None: \"both\"} FONTSIZE_TITLE =",
"ax = df_plot.plot(kind='bar', stacked=True, figsize=parms[cn.PLT_FIGSIZE], legend=None) else: df_plot.plot(kind='bar', stacked=True, legend=None,",
"default): if not key in a_dict.keys(): a_dict[key] = default #",
"ax=axes[idx], permitted_mutations=permitted_mutations, is_unit_fraction=is_unit_fraction) df[cn.TRANSFER] = transfer dfs.append(df) if self._is_plot: plt.show()",
"return df_matrix def _plotSiglvlDF(self, transfer=cn.TRANSFER_DEFAULT, other_transfer=None, max_siglvl=MAX_SIGLVL): \"\"\" Constructs a",
"plot if not cn.PLT_COLORBAR in parms: parms[cn.PLT_COLORBAR] = True if",
"if v > min_fraction else 0) return df_binary.transpose() # if",
"to use in plot :param list-str permitted_mutations: to use and",
"a heatmap of the mutation coocurrence significance levels. :param float",
"int transfer: :param int other_transfer: Allow comparisons across time :param",
"fontsize=FONTSIZE_LABEL) if parms.isTrue(cn.PLT_XLABEL): ax.set_xlabel(self._mutation_column, fontsize=FONTSIZE_LABEL) if parms.isTrue(cn.PLT_LEGEND): ax.legend(loc=(1,2)) #ax.legend() if",
"occurrences within Lines. \"\"\" def __init__(self, mutation_column=cn.GGENE_ID, species=None, is_plot=True): \"\"\"",
"Constructs a heatmap comparing values for mutations from two transfers.",
"subplots :param dict kwargs: non-transfer parameters passed to next level",
"def funcDF(transfer, other_transfer): return self._plotSiglvlDF(transfer=transfer, max_siglvl=max_siglvl, other_transfer=other_transfer) # return self._plotTransfers(funcDF,",
"% transfer return label def setValue(a_dict, key, default): if not",
"transfer: Transfer for which plot is done :param bool is_differenced:",
"mutations \"\"\" df_plot = self._plotSiglvlDF(transfer=transfer, other_transfer=other_transfer, max_siglvl=max_siglvl) self._plotTransferCompare(df_plot, heat_range =",
":param float, float: values on the heatmap range :param int",
"transfers[1:])] else: pairs = [p for p in zip(transfers[:-1], transfers[:-1])]",
"default # if is_plot is None: is_plot = self._is_plot elif",
"# if is_plot is None: is_plot = self._is_plot elif not",
"= False, is_cluster_mutations=True): \"\"\" Does a stacked bar plot of",
"if parms.isFalse(cn.PLT_XTICKLABELS): labels = ax.get_xticklabels() new_labels = np.repeat(\"\", len(labels)) ax.set_xticklabels(new_labels)",
"= 0.25 THRESHOLD_FRAC = 0.2 MAX_SIGLVL = 0.01 COLORBAR_MIN =",
"= ['red', 'green', 'blue'] SPECIES = {cn.SPECIES_MIX_DVH: \"DVH\", cn.SPECIES_MIX_MMP: \"MMP\",",
":param bool is_time_lag: construct time lag subplots :param dict kwargs:",
"levels. :param float max_siglvl: maximum significance level :return pd.DataFrame: columns,",
"cmap='jet') cb.ax.tick_params(labelsize=parms.fontsize_label) row_labels = df_plot.columns.tolist() col_labels = df_plot.index.tolist() if parms.isTrue(cn.PLT_XAXISTICKTOP):",
"= MAX_LINES - 3 ax.text(xpos, ypos, title, fontsize=FONTSIZE_TITLE) ax.set_ylim([0, MAX_LINES])",
"of the mutation coocurrence significance levels. :param float max_siglvl: maximum",
"= -1 ax.set_ylabel(ylabel, fontsize=parms.fontsize_label, x=xpos, y=ypos) #plt.show() parms.do(is_plot=is_plot) else: parms.do(is_plot=is_plot)",
":param float max_siglvl: :return pd.DataFrame: mutations, mutations, values are -log10",
"index; values are used in the heatmap. :param bool is_time_lag:",
"return df # return self._plotTransfers(funcDF, is_time_lag, parms=parms, heat_range=[0, 1.0], **kwargs)",
"if parms.isTrue(cn.PLT_XAXISTICKTOP): ax.xaxis.tick_top() ax.set_xticks(np.arange(0.5, len(row_labels))) ax.set_xticklabels(row_labels, rotation=90, fontsize=parms.fontsize_label) ax.set_yticks(np.arange(0.5, len(col_labels)))",
"ordered_columns=self.cofraction.ordered_mutations, is_center_colorbar=True, fig=fig, ax=ax, parms=parms, is_plot=is_plot, **kwargs) result[pair] = df",
"= False if idx < num_transfers - 1: parms[cn.PLT_LEGEND] =",
"Isolates and Lines.\"\"\" from microbepy.common import constants as cn from",
"extended_ordered_columns = list(ordered_columns) extended_ordered_columns.extend( set(columns).difference(ordered_columns)) for col in missing_columns: df_plot[col]",
"plot of mutation frequency by line with colors :params int",
"and index; values are used in the heatmap. :param bool",
"= df_plot.columns.tolist() missing_columns = set(ordered_columns).difference(columns) extended_ordered_columns = list(ordered_columns) extended_ordered_columns.extend( set(columns).difference(ordered_columns))",
"= df_plot.columns.tolist() col_labels = df_plot.index.tolist() if parms.isTrue(cn.PLT_XAXISTICKTOP): ax.xaxis.tick_top() ax.set_xticks(np.arange(0.5, len(row_labels)))",
"= plt.figure(figsize=parms[cn.PLT_FIGSIZE]) ax = fig.add_subplot(1, 1, 1) # Order the",
"_plotSiglvlDF(self, transfer=cn.TRANSFER_DEFAULT, other_transfer=None, max_siglvl=MAX_SIGLVL): \"\"\" Constructs a the dataframe used",
"def setValue(a_dict, key, default): if not key in a_dict.keys(): a_dict[key]",
"by line with colors :params int transfer: :params PlotParms parms:",
"df_plot: index and columns are mutations; values are plotted on",
"the colorbar in the plot :param float, float: values on",
"if is_differenced: df = self.cofraction.makeCofractionDifferencedDF( threshold_frac=threshold_frac, transfer=transfer, other_transfer=other_transfer, **kwargs) df",
"plotCofraction(self, threshold_frac=THRESHOLD_FRAC, transfer=cn.TRANSFER_DEFAULT, other_transfer=None, is_difference_frac=False, is_differenced=False, is_center_colorbar=True, is_compress=False, parms=PlotParms(), **kwargs):",
"columns, rows are mutations \"\"\" df_plot = self._plotSiglvlDF(transfer=transfer, other_transfer=other_transfer, max_siglvl=max_siglvl)",
"mutations for Isolates and Lines.\"\"\" from microbepy.common import constants as",
"if is_include_missing_mutations: columns = df_plot.columns.tolist() missing_columns = set(ordered_columns).difference(columns) extended_ordered_columns =",
"< num_transfers - 1: parms[cn.PLT_LEGEND] = False parms[cn.PLT_XLABEL] = False",
"other_transfer=other_transfer, **kwargs) df = df.applymap(lambda v: np.nan if np.abs(v) <",
"list-str ordered_columns: order in which columns appear :param bool is_center_colorbar:",
"= makeLabel(transfer, self._mutation_column) xpos = -3 ypos = 0.5*len(rows) ypos",
"np.nan if v < ubound else v) sorter = DataframeSorter(df_plot)",
"self._is_plot elif not self._is_plot: is_plot = self._is_plot if ordered_columns is",
"NCOLS, plot_pos[idx]) if idx < len(pairs): is_plot = False else:",
"similar mutations together :return pd.DataFrame: row=mutation, col=line + transfer, value",
"transfers[:-1])] # # Calculate the column order df = funcDF(transfer=cn.TRANSFER_1000G,",
"= df.applymap(lambda v: np.nan if v < threshold_frac else v)",
"fraction of lines in which mutations co-occur. :param bool is_time_lag:",
"plot is done :param bool is_differenced: Computes the difference in",
", fontsize=FONTSIZE_LABEL) if parms.isTrue(cn.PLT_XLABEL): ax.set_xlabel(self._mutation_column, fontsize=FONTSIZE_LABEL) if parms.isTrue(cn.PLT_LEGEND): ax.legend(loc=(1,2)) #ax.legend()",
"set(columns).difference(ordered_columns)) for col in missing_columns: df_plot[col] = np.nan df_plot.loc[col, :]",
"**kwargs) def _plotTransfers(self, funcDF, is_time_lag, parms=PlotParms(), **kwargs): \"\"\" Does a",
"fig = plt.figure(figsize=parms[cn.PLT_FIGSIZE]) result = {} for idx, pair in",
"np.nan df_plot = df_plot.reindex(extended_ordered_columns) df_plot = df_plot[extended_ordered_columns] rows = df_plot.columns.tolist()",
"\"\"\" def __init__(self, mutation_column=cn.GGENE_ID, species=None, is_plot=True): \"\"\" :param str mutation_column:",
"df_plot def plotCofractions(self, is_time_lag=False, threshold_frac=THRESHOLD_FRAC, is_difference_frac=False, is_differenced=False, is_compress=False, parms=PlotParms(), **kwargs):",
"ncols=1) dfs = [] for idx, transfer in enumerate(transfers): parms[cn.PLT_YTICKLABELS]",
"microbepy.common import util from microbepy.correlation import genome_correlation from microbepy.data.model_data_provider import",
"is_center_colorbar=is_center_colorbar, **kwargs) return df_plot def plotCofraction(self, threshold_frac=THRESHOLD_FRAC, transfer=cn.TRANSFER_DEFAULT, other_transfer=None, is_difference_frac=False,",
"else: label = \"%d\" % transfer return label def setValue(a_dict,",
"df_plot.reindex(extended_ordered_columns) df_plot = df_plot[extended_ordered_columns] rows = df_plot.columns.tolist() columns = df_plot.columns.tolist()",
"parms.do(is_plot=False) ylabel = makeLabel(transfer, self._mutation_column) xpos = -3 ypos =",
"def plotSiglvl(self, max_siglvl=MAX_SIGLVL, transfer=cn.TRANSFER_DEFAULT, other_transfer=None, is_center_colorbar = True, **kwargs): \"\"\"",
"center the colorbar in the plot :param float, float: values",
"vmin=heat_range[0], vmax=heat_range[1]) if parms.isTrue(cn.PLT_COLORBAR): if is_center_colorbar: # Colorbar positions: left,",
"DataframeSorter from microbepy.common.isolate import Isolate from microbepy.common import util from",
"is fraction \"\"\" permitted_mutations = self.cofraction.ordered_mutations transfers = self.cofraction.transfers num_transfers",
"ax is None: if fig is None: fig = plt.figure(figsize=parms[cn.PLT_FIGSIZE])",
"the plot :param float, float: values on the heatmap range",
"makeLabel(other_transfer, self._mutation_column) parms[cn.PLT_YLABEL] = makeLabel( transfer, self._mutation_column) ax.text(xpos, ypos, xlabel,",
"sns COLORS = ['red', 'green', 'blue'] SPECIES = {cn.SPECIES_MIX_DVH: \"DVH\",",
"mutations, values are -log10 significance level \"\"\" df_matrix = self._makeMutationSiglvlMatrix(transfer=transfer,",
"ypos = 0.5*len(rows) ypos = -1 ax.set_ylabel(ylabel, fontsize=parms.fontsize_label, x=xpos, y=ypos)",
"ax.get_xticklabels() new_labels = np.repeat(\"\", len(labels)) ax.set_xticklabels(new_labels) if parms.isFalse(cn.PLT_YTICKLABELS): labels =",
"use in plot :param list-str permitted_mutations: to use and how",
"ordered_columns is None: ordered_columns = list(set(df_plot.columns.tolist()).union( df_plot.index)) # Do the",
"= df_transformed.applymap(lambda v: -v) ubound = -np.log10(max_siglvl) df_plot = df_transformed.applymap(",
"list-str permitted_mutations: to use and how they are ordered if",
"key, default): if not key in a_dict.keys(): a_dict[key] = default",
"1 if v> MIN_FRACTION else v) # Do the plot",
"parms: title = parms[cn.PLT_TITLE] else: title = \"%s Mutations\" %",
"column order df = funcDF(transfer=cn.TRANSFER_1000G, other_transfer=cn.TRANSFER_1000G) df = df.fillna(0) #",
"def plotCofraction(self, threshold_frac=THRESHOLD_FRAC, transfer=cn.TRANSFER_DEFAULT, other_transfer=None, is_difference_frac=False, is_differenced=False, is_center_colorbar=True, is_compress=False, parms=PlotParms(),",
"is fraction \"\"\" if is_plot is None: is_plot = self._is_plot",
"Calculate the column order df = funcDF(transfer=cn.TRANSFER_1000G, other_transfer=cn.TRANSFER_1000G) df =",
"= self.cofraction.ordered_mutations self._plotTransferCompare(df, heat_range=[0, 1.0], ordered_columns=ordered_columns, parms=parms, transfer=transfer, other_transfer=other_transfer, is_center_colorbar=is_center_colorbar,",
"True if other_transfer is None: other_transfer = transfer if ax",
"parms[cn.PLT_XLABEL] = True parms[cn.PLT_XTICKLABELS] = True df = self.plotLine(transfer, parms=parms,",
":params PlotParms parms: :params Axis ax: axis to use in",
"width, height cbaxes = fig.add_axes([.45, 0.2, 0.01, 0.5]) cb =",
"= [COLORBAR_MIN, COLORBAR_MAX], ordered_mutations=self.cofraction.ordered_mutations, transfer=transfer, other_transfer=other_transfer, is_center_colorbar=is_center_colorbar, **kwargs) return df_plot",
"heatmap of the mutation coocurrence fractions. :param int transfer: Transfer",
"fractional occurrence of a mutation within a line for it",
"self._species is None: parms[cn.PLT_TITLE] = \"%d\" % transfer else: parms[cn.PLT_TITLE]",
"other_transfer): return self._plotSiglvlDF(transfer=transfer, max_siglvl=max_siglvl, other_transfer=other_transfer) # return self._plotTransfers(funcDF, is_time_lag, parms=parms,",
"df_plot def _makeMutationSiglvlMatrix(self, transfer=cn.TRANSFER_DEFAULT, other_transfer=None, min_fraction=MIN_FRACTION): \"\"\" Creates a significance",
"max_siglvl=MAX_SIGLVL): \"\"\" Constructs a the dataframe used for heatmap. :param",
"bar plot of mutation frequency by line with colors :params",
"df_plot = df_plot.applymap( lambda v: 1 if v> MIN_FRACTION else",
"a heatmap of the mutation coocurrence fractions. :param int transfer:",
"= \"%d-%s\" % (transfer, column) else: label = \"%d\" %",
"= False else: is_plot = True if idx in [1,",
"order in which columns appear :param bool is_center_colorbar: center the",
"plt.figure(figsize=parms[cn.PLT_FIGSIZE]) ax = fig.add_subplot(1, 1, 1) # Order the columns",
"is_compress: df.dropna(axis=0, how='all', inplace=True) df.dropna(axis=1, how='all', inplace=True) return df #",
"parms=PlotParms(), **kwargs): \"\"\" Does a subplots of mutation mutations over",
"np import pandas as pd import seaborn as sns COLORS",
"df_plot.columns.tolist() columns = df_plot.columns.tolist() else: extended_ordered_columns = ordered_columns rows =",
":param Function funcDF: has kwargs transfer, other_transfer; returns a dataframe",
"pd.DataFrame: row=mutation, col=line, value is fraction \"\"\" if is_plot is",
"\"\" setValue(parms, cn.PLT_COLORBAR, True) xpos = 1.05*len(columns) ypos = -0.05*len(rows)",
"for all transfers. :param bool is_unit_fraction: round fraction to 1",
"value is data_frame \"\"\" def funcDF(transfer, other_transfer): return self._plotSiglvlDF(transfer=transfer, max_siglvl=max_siglvl,",
"alphabetical order :param bool is_unit_fraction: round non-zero fraction to 1",
"parms=PlotParms(), is_plot=None): \"\"\" Constructs a heatmap comparing values for mutations",
"v) if is_compress: df.dropna(axis=0, how='all', inplace=True) df.dropna(axis=1, how='all', inplace=True) is_include_missing_mutations",
"lambda v: 0 if np.isnan(v) else v) df_binary = df_line.applymap(",
"of mutation frequency for all transfers. :param bool is_unit_fraction: round",
"< threshold_frac else v) else: df = self.cofraction.makeCofractionDF(transfer=transfer, is_difference_frac=is_difference_frac, other_transfer=other_transfer,",
"ax.set_xticklabels(row_labels, rotation=90, fontsize=parms.fontsize_label) ax.set_yticks(np.arange(0.5, len(col_labels))) ax.set_yticklabels(col_labels, fontsize=parms.fontsize_label) #parms[cn.PLT_YLABEL] = \"\"",
"is_include_missing_mutations: columns = df_plot.columns.tolist() missing_columns = set(ordered_columns).difference(columns) extended_ordered_columns = list(ordered_columns)",
"is_cluster_mutations=True): \"\"\" Does a stacked bar plot of mutation frequency",
"next level :return dict: key is pair of transfers, value",
"import ModelDataProvider from microbepy.data import util_data from microbepy.plot.mutation_cofraction import MutationCofraction",
"= False parms[cn.PLT_XLABEL] = False parms[cn.PLT_XTICKLABELS] = False else: parms[cn.PLT_LEGEND]",
"\"DVH\", cn.SPECIES_MIX_MMP: \"MMP\", None: \"both\"} FONTSIZE_TITLE = 16 FONTSIZE_LABEL =",
"is_unit_fraction: label = \"No. Lines\" else: label = \"Fraction\" ax.set_ylabel(label",
"in zip(transfers[:-1], transfers[1:])] else: pairs = [p for p in",
"mutations; values are plotted on the heatmap :param list-str ordered_columns:",
"ypos, title, fontsize=FONTSIZE_TITLE) ax.set_ylim([0, MAX_LINES]) if parms.isTrue(cn.PLT_YLABEL): if is_unit_fraction: label",
"{cn.SPECIES_MIX_DVH: \"DVH\", cn.SPECIES_MIX_MMP: \"MMP\", None: \"both\"} FONTSIZE_TITLE = 16 FONTSIZE_LABEL",
"parms[cn.PLT_YLABEL] = \"\" parms.do(is_plot=False) ylabel = makeLabel(transfer, self._mutation_column) xpos =",
"= df_plot[extended_ordered_columns] rows = df_plot.columns.tolist() columns = df_plot.columns.tolist() else: extended_ordered_columns",
"parms.isTrue(cn.PLT_COLORBAR): if is_center_colorbar: # Colorbar positions: left, bottom, width, height",
"passed to next level :return dict: key is pair of",
"mutations together :return pd.DataFrame: row=mutation, col=line + transfer, value is",
"max_siglvl=max_siglvl, other_transfer=other_transfer) # return self._plotTransfers(funcDF, is_time_lag, parms=parms, heat_range = [COLORBAR_MIN,",
"True if idx in [1, 2, 5]: parms[cn.PLT_XAXISTICKTOP] = True"
] |
[
"[0, 128, 0], [128, 128, 0], [0, 0, 128], [120,",
"from scipy.misc import imread from args import get_args import matplotlib.pyplot",
"2.0 (the \"License\"); # you may not use this file",
"'encoded/') for filename in os.listdir(data_dir+'SegmentationClass/'): if os.path.isdir(data_dir+'SegmentationClass/' + filename): continue",
"os.path.exists(data_dir+'JPEGImages/'+line+'.jpg'): ti.write(data_dir+'JPEGImages/'+line+'.jpg' + '\\n') assert (os.path.isfile(data_dir+'SegmentationClass/encoded/'+line + '.npy')), \"No matching",
"os.path.isdir(data_dir+'SegmentationClass/' + filename): continue label = imread(data_dir+'SegmentationClass/' + filename).astype('float32') label",
"new_label[np.where( (label.astype(np.int32) == cls_to_clr_map[i]).all(axis=2))] = i return new_label # this",
"0], [192, 0, 0], [64, 128, 0], [192, 128, 0],",
"= open('train_label.txt', 'w') vi = open('val_image.txt', 'w') vl = open('val_label.txt',",
"of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless",
"lines: if os.path.exists(data_dir+'JPEGImages/'+line+'.jpg'): ti.write(data_dir+'JPEGImages/'+line+'.jpg' + '\\n') assert (os.path.isfile(data_dir+'SegmentationClass/encoded/'+line + '.npy')),",
"+ filename.split('.')[0] + '.npy', label) generate_path_files(args.data_dir, args.train_file, args.val_file) if __name__",
"data_dir train_text_file = open(train_file, \"r\") lines = [line[:-1] for line",
"vi = open('val_image.txt', 'w') vl = open('val_label.txt', 'w') rootdir =",
"+ '.npy', label) generate_path_files(args.data_dir, args.train_file, args.val_file) if __name__ == '__main__':",
"0], [0, 0, 128], [120, 0, 128], [0, 128, 128],",
"128], [64, 128, 128], [192, 128, 128], [0, 64, 0],",
"as validation set. data-dir = dataset directory Usage: python dataset_utils.py",
"os.makedirs(data_dir+'SegmentationClass/' + 'encoded/') for filename in os.listdir(data_dir+'SegmentationClass/'): if os.path.isdir(data_dir+'SegmentationClass/' +",
"use this file except in compliance with the License. #",
"in 3-dim(h,w,c) and in BGR fromat read from cv2 '''",
"np.zeros((h, w, 1), dtype=np.int32) cls_to_clr_map = get_color() for i in",
"label = encode_label(label) np.save(data_dir+'SegmentationClass/' + 'encoded/' + filename.split('.')[0] + '.npy',",
"os from scipy.misc import imread from args import get_args import",
"the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required",
"License. # You may obtain a copy of the License",
"if os.path.exists(data_dir+'JPEGImages/'+line+'.jpg'): ti.write(data_dir+'JPEGImages/'+line+'.jpg' + '\\n') assert (os.path.isfile(data_dir+'SegmentationClass/encoded/'+line + '.npy')), \"No",
"label file for image : \" + line + '.jpg'",
"this method should generate train-image.txt and train-label.txt def generate_path_files(data_dir, train_file,",
"args.data_dir if not os.path.exists(data_dir+'SegmentationClass/' + 'encoded/'): os.makedirs(data_dir+'SegmentationClass/' + 'encoded/') for",
"# Copyright (c) 2017 Sony Corporation. All Rights Reserved. #",
"under the License is distributed on an \"AS IS\" BASIS,",
"train-image.txt and train-label.txt def generate_path_files(data_dir, train_file, val_file): ti = open('train_image.txt',",
"64, 128], [224, 224, 192]]) def encode_label(label): ''' Converting pixel",
"== cls_to_clr_map[i]).all(axis=2))] = 255 else: new_label[np.where( (label.astype(np.int32) == cls_to_clr_map[i]).all(axis=2))] =",
"License for the specific language governing permissions and # limitations",
"image : \" + line + '.jpg' vl.write(data_dir+'SegmentationClass/encoded/'+line + '.npy'",
"Reserved. # # Licensed under the Apache License, Version 2.0",
"return new_label # this method should generate train-image.txt and train-label.txt",
"as training set. val-file = txt file containing randomly selected",
"Sony Corporation. All Rights Reserved. # # Licensed under the",
"(c) 2017 Sony Corporation. All Rights Reserved. # # Licensed",
"as np import os from scipy.misc import imread from args",
"train-file = txt file containing randomly selected image filenames to",
"0, 128], [64, 128, 128], [192, 128, 128], [0, 64,",
"from args import get_args import matplotlib.pyplot as plt def get_color():",
"in lines: if os.path.exists(data_dir+'JPEGImages/'+line+'.jpg'): ti.write(data_dir+'JPEGImages/'+line+'.jpg' + '\\n') assert (os.path.isfile(data_dir+'SegmentationClass/encoded/'+line +",
"in compliance with the License. # You may obtain a",
"software # distributed under the License is distributed on an",
"'.npy', label) generate_path_files(args.data_dir, args.train_file, args.val_file) if __name__ == '__main__': main()",
"governing permissions and # limitations under the License. import numpy",
"[0, 64, 0], [128, 64, 0], [0, 192, 0], [128,",
"+ line + '.jpg' tl.write(data_dir+'SegmentationClass/encoded/'+line + '.npy' + '\\n') val_text_file",
"continue label = imread(data_dir+'SegmentationClass/' + filename).astype('float32') label = encode_label(label) np.save(data_dir+'SegmentationClass/'",
"for line in train_text_file] for line in lines: if os.path.exists(data_dir+'JPEGImages/'+line+'.jpg'):",
"+ filename).astype('float32') label = encode_label(label) np.save(data_dir+'SegmentationClass/' + 'encoded/' + filename.split('.')[0]",
"= [line[:-1] for line in train_text_file] for line in lines:",
"numpy as np import os from scipy.misc import imread from",
"filename in os.listdir(data_dir+'SegmentationClass/'): if os.path.isdir(data_dir+'SegmentationClass/' + filename): continue label =",
"3-dim(h,w,c) and in BGR fromat read from cv2 ''' h,",
"if os.path.isdir(data_dir+'SegmentationClass/' + filename): continue label = imread(data_dir+'SegmentationClass/' + filename).astype('float32')",
"taken as validation set. data-dir = dataset directory Usage: python",
"line in train_text_file] for line in lines: if os.path.exists(data_dir+'JPEGImages/'+line+'.jpg'): ti.write(data_dir+'JPEGImages/'+line+'.jpg'",
"== cls_to_clr_map[i]).all(axis=2))]=i print(np.where((label.astype(np.int32) == [120, 0, 128]).all(axis=2))) if i ==",
"ti.close() tl.close() vi.close() vl.close() def main(): ''' Arguments: train-file =",
"open(val_file, \"r\") lines = [line[:-1] for line in val_text_file] for",
"data-dir = dataset directory Usage: python dataset_utils.py --train-file=\"\" --val-file=\"\" --data_dir=\"\"",
"cls_to_clr_map[i])[:,:,0]] = i #new_label[np.argwhere((label.astype(np.int32) == cls_to_clr_map[i]).all(axis=2))]=i print(np.where((label.astype(np.int32) == [120, 0,",
"image : \" + line + '.jpg' tl.write(data_dir+'SegmentationClass/encoded/'+line + '.npy'",
"if not os.path.exists(data_dir+'SegmentationClass/' + 'encoded/'): os.makedirs(data_dir+'SegmentationClass/' + 'encoded/') for filename",
"= open('train_image.txt', 'w') tl = open('train_label.txt', 'w') vi = open('val_image.txt',",
"for i in range(cls_to_clr_map.shape[0]): #new_label[(label == cls_to_clr_map[i])[:,:,0]] = i #new_label[np.argwhere((label.astype(np.int32)",
"OF ANY KIND, either express or implied. # See the",
"WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.",
"128], [64, 0, 0], [192, 0, 0], [64, 128, 0],",
"if os.path.exists(data_dir+'JPEGImages/'+line+'.jpg'): vi.write(data_dir+'JPEGImages/'+line+'.jpg' + '\\n') assert (os.path.isfile(data_dir+'SegmentationClass/encoded/'+line + '.npy')), \"No",
"and # limitations under the License. import numpy as np",
"ANY KIND, either express or implied. # See the License",
"See the License for the specific language governing permissions and",
"[128, 192, 0], [0, 64, 128], [224, 224, 192]]) def",
"= txt file containing randomly selected image filenames to be",
"data_dir = args.data_dir if not os.path.exists(data_dir+'SegmentationClass/' + 'encoded/'): os.makedirs(data_dir+'SegmentationClass/' +",
"the License. # You may obtain a copy of the",
"at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable",
"for the specific language governing permissions and # limitations under",
"to in writing, software # distributed under the License is",
"''' h, w, c = label.shape new_label = np.zeros((h, w,",
"[0, 128, 128], [128, 128, 128], [64, 0, 0], [192,",
"# See the License for the specific language governing permissions",
"be taken as validation set. data-dir = dataset directory Usage:",
"or agreed to in writing, software # distributed under the",
"i == 21: new_label[np.where( (label.astype(np.int32) == cls_to_clr_map[i]).all(axis=2))] = 255 else:",
"required by applicable law or agreed to in writing, software",
"training set. val-file = txt file containing randomly selected image",
"BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either",
"np import os from scipy.misc import imread from args import",
"import matplotlib.pyplot as plt def get_color(): # RGB format return",
"cls_to_clr_map[i]).all(axis=2))]=i print(np.where((label.astype(np.int32) == [120, 0, 128]).all(axis=2))) if i == 21:",
"\" + line + '.jpg' vl.write(data_dir+'SegmentationClass/encoded/'+line + '.npy' + '\\n')",
"with the License. # You may obtain a copy of",
"get_args import matplotlib.pyplot as plt def get_color(): # RGB format",
"label in 3-dim(h,w,c) and in BGR fromat read from cv2",
"vl = open('val_label.txt', 'w') rootdir = data_dir train_text_file = open(train_file,",
"label.shape new_label = np.zeros((h, w, 1), dtype=np.int32) cls_to_clr_map = get_color()",
"dataset directory Usage: python dataset_utils.py --train-file=\"\" --val-file=\"\" --data_dir=\"\" ''' args",
"'w') vl = open('val_label.txt', 'w') rootdir = data_dir train_text_file =",
"range(cls_to_clr_map.shape[0]): #new_label[(label == cls_to_clr_map[i])[:,:,0]] = i #new_label[np.argwhere((label.astype(np.int32) == cls_to_clr_map[i]).all(axis=2))]=i print(np.where((label.astype(np.int32)",
"generate train-image.txt and train-label.txt def generate_path_files(data_dir, train_file, val_file): ti =",
"compliance with the License. # You may obtain a copy",
"All Rights Reserved. # # Licensed under the Apache License,",
"agreed to in writing, software # distributed under the License",
"that the input label in 3-dim(h,w,c) and in BGR fromat",
"== cls_to_clr_map[i]).all(axis=2))] = i return new_label # this method should",
"distributed under the License is distributed on an \"AS IS\"",
"permissions and # limitations under the License. import numpy as",
"0, 128], [192, 0, 128], [64, 128, 128], [192, 128,",
"= get_args() data_dir = args.data_dir if not os.path.exists(data_dir+'SegmentationClass/' + 'encoded/'):",
"21: new_label[np.where( (label.astype(np.int32) == cls_to_clr_map[i]).all(axis=2))] = 255 else: new_label[np.where( (label.astype(np.int32)",
"for image : \" + line + '.jpg' tl.write(data_dir+'SegmentationClass/encoded/'+line +",
"express or implied. # See the License for the specific",
"0, 0], [128, 0, 0], [0, 128, 0], [128, 128,",
"except in compliance with the License. # You may obtain",
"def get_color(): # RGB format return np.array([[0, 0, 0], [128,",
"python dataset_utils.py --train-file=\"\" --val-file=\"\" --data_dir=\"\" ''' args = get_args() data_dir",
"Licensed under the Apache License, Version 2.0 (the \"License\"); #",
"not use this file except in compliance with the License.",
"= imread(data_dir+'SegmentationClass/' + filename).astype('float32') label = encode_label(label) np.save(data_dir+'SegmentationClass/' + 'encoded/'",
"filenames to be taken as validation set. data-dir = dataset",
"writing, software # distributed under the License is distributed on",
"you may not use this file except in compliance with",
"0], [128, 128, 0], [0, 0, 128], [120, 0, 128],",
"[128, 64, 0], [0, 192, 0], [128, 192, 0], [0,",
"# Licensed under the Apache License, Version 2.0 (the \"License\");",
"--val-file=\"\" --data_dir=\"\" ''' args = get_args() data_dir = args.data_dir if",
"np.save(data_dir+'SegmentationClass/' + 'encoded/' + filename.split('.')[0] + '.npy', label) generate_path_files(args.data_dir, args.train_file,",
"0], [0, 64, 128], [224, 224, 192]]) def encode_label(label): '''",
"file for image : \" + line + '.jpg' vl.write(data_dir+'SegmentationClass/encoded/'+line",
"'encoded/'): os.makedirs(data_dir+'SegmentationClass/' + 'encoded/') for filename in os.listdir(data_dir+'SegmentationClass/'): if os.path.isdir(data_dir+'SegmentationClass/'",
"192]]) def encode_label(label): ''' Converting pixel values to corresponding class",
"randomly selected image filenames to be taken as validation set.",
"+ '.npy')), \"No matching label file for image : \"",
"CONDITIONS OF ANY KIND, either express or implied. # See",
"128], [224, 224, 192]]) def encode_label(label): ''' Converting pixel values",
"is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES",
"w, 1), dtype=np.int32) cls_to_clr_map = get_color() for i in range(cls_to_clr_map.shape[0]):",
"get_color() for i in range(cls_to_clr_map.shape[0]): #new_label[(label == cls_to_clr_map[i])[:,:,0]] = i",
"image filenames to be taken as validation set. data-dir =",
"and in BGR fromat read from cv2 ''' h, w,",
"0, 128], [120, 0, 128], [0, 128, 128], [128, 128,",
"encode_label(label): ''' Converting pixel values to corresponding class numbers. Assuming",
"[192, 128, 128], [0, 64, 0], [128, 64, 0], [0,",
"128, 0], [128, 128, 0], [0, 0, 128], [120, 0,",
"Assuming that the input label in 3-dim(h,w,c) and in BGR",
"'.npy' + '\\n') val_text_file = open(val_file, \"r\") lines = [line[:-1]",
"#new_label[(label == cls_to_clr_map[i])[:,:,0]] = i #new_label[np.argwhere((label.astype(np.int32) == cls_to_clr_map[i]).all(axis=2))]=i print(np.where((label.astype(np.int32) ==",
"generate_path_files(data_dir, train_file, val_file): ti = open('train_image.txt', 'w') tl = open('train_label.txt',",
"= label.shape new_label = np.zeros((h, w, 1), dtype=np.int32) cls_to_clr_map =",
"'\\n') ti.close() tl.close() vi.close() vl.close() def main(): ''' Arguments: train-file",
"1), dtype=np.int32) cls_to_clr_map = get_color() for i in range(cls_to_clr_map.shape[0]): #new_label[(label",
"rootdir = data_dir train_text_file = open(train_file, \"r\") lines = [line[:-1]",
"(os.path.isfile(data_dir+'SegmentationClass/encoded/'+line + '.npy')), \"No matching label file for image :",
"64, 0], [128, 64, 0], [0, 192, 0], [128, 192,",
"OR CONDITIONS OF ANY KIND, either express or implied. #",
"filename.split('.')[0] + '.npy', label) generate_path_files(args.data_dir, args.train_file, args.val_file) if __name__ ==",
"filename): continue label = imread(data_dir+'SegmentationClass/' + filename).astype('float32') label = encode_label(label)",
"new_label = np.zeros((h, w, 1), dtype=np.int32) cls_to_clr_map = get_color() for",
"[192, 0, 0], [64, 128, 0], [192, 128, 0], [64,",
"open(train_file, \"r\") lines = [line[:-1] for line in train_text_file] for",
"the License is distributed on an \"AS IS\" BASIS, #",
"dtype=np.int32) cls_to_clr_map = get_color() for i in range(cls_to_clr_map.shape[0]): #new_label[(label ==",
"validation set. data-dir = dataset directory Usage: python dataset_utils.py --train-file=\"\"",
"BGR fromat read from cv2 ''' h, w, c =",
"format return np.array([[0, 0, 0], [128, 0, 0], [0, 128,",
"cls_to_clr_map[i]).all(axis=2))] = 255 else: new_label[np.where( (label.astype(np.int32) == cls_to_clr_map[i]).all(axis=2))] = i",
"main(): ''' Arguments: train-file = txt file containing randomly selected",
"if i == 21: new_label[np.where( (label.astype(np.int32) == cls_to_clr_map[i]).all(axis=2))] = 255",
"file for image : \" + line + '.jpg' tl.write(data_dir+'SegmentationClass/encoded/'+line",
"\"r\") lines = [line[:-1] for line in val_text_file] for line",
"cls_to_clr_map[i]).all(axis=2))] = i return new_label # this method should generate",
"= [line[:-1] for line in val_text_file] for line in lines:",
"ti.write(data_dir+'JPEGImages/'+line+'.jpg' + '\\n') assert (os.path.isfile(data_dir+'SegmentationClass/encoded/'+line + '.npy')), \"No matching label",
"law or agreed to in writing, software # distributed under",
"method should generate train-image.txt and train-label.txt def generate_path_files(data_dir, train_file, val_file):",
"cv2 ''' h, w, c = label.shape new_label = np.zeros((h,",
"''' Converting pixel values to corresponding class numbers. Assuming that",
"to corresponding class numbers. Assuming that the input label in",
"'w') tl = open('train_label.txt', 'w') vi = open('val_image.txt', 'w') vl",
"= open(train_file, \"r\") lines = [line[:-1] for line in train_text_file]",
": \" + line + '.jpg' tl.write(data_dir+'SegmentationClass/encoded/'+line + '.npy' +",
"vl.write(data_dir+'SegmentationClass/encoded/'+line + '.npy' + '\\n') ti.close() tl.close() vi.close() vl.close() def",
"under the License. import numpy as np import os from",
"== 21: new_label[np.where( (label.astype(np.int32) == cls_to_clr_map[i]).all(axis=2))] = 255 else: new_label[np.where(",
"128, 128], [128, 128, 128], [64, 0, 0], [192, 0,",
"0], [128, 64, 0], [0, 192, 0], [128, 192, 0],",
"[120, 0, 128]).all(axis=2))) if i == 21: new_label[np.where( (label.astype(np.int32) ==",
"in lines: if os.path.exists(data_dir+'JPEGImages/'+line+'.jpg'): vi.write(data_dir+'JPEGImages/'+line+'.jpg' + '\\n') assert (os.path.isfile(data_dir+'SegmentationClass/encoded/'+line +",
"may obtain a copy of the License at # #",
"128], [120, 0, 128], [0, 128, 128], [128, 128, 128],",
"+ 'encoded/' + filename.split('.')[0] + '.npy', label) generate_path_files(args.data_dir, args.train_file, args.val_file)",
"plt def get_color(): # RGB format return np.array([[0, 0, 0],",
"64, 0], [0, 192, 0], [128, 192, 0], [0, 64,",
"IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,",
"taken as training set. val-file = txt file containing randomly",
"192, 0], [0, 64, 128], [224, 224, 192]]) def encode_label(label):",
"from cv2 ''' h, w, c = label.shape new_label =",
"# this method should generate train-image.txt and train-label.txt def generate_path_files(data_dir,",
"vi.close() vl.close() def main(): ''' Arguments: train-file = txt file",
"may not use this file except in compliance with the",
"== [120, 0, 128]).all(axis=2))) if i == 21: new_label[np.where( (label.astype(np.int32)",
"numbers. Assuming that the input label in 3-dim(h,w,c) and in",
"[64, 128, 128], [192, 128, 128], [0, 64, 0], [128,",
"'.npy' + '\\n') ti.close() tl.close() vi.close() vl.close() def main(): '''",
"224, 192]]) def encode_label(label): ''' Converting pixel values to corresponding",
"WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or",
"0], [64, 0, 128], [192, 0, 128], [64, 128, 128],",
"this file except in compliance with the License. # You",
"'.npy')), \"No matching label file for image : \" +",
"line in lines: if os.path.exists(data_dir+'JPEGImages/'+line+'.jpg'): vi.write(data_dir+'JPEGImages/'+line+'.jpg' + '\\n') assert (os.path.isfile(data_dir+'SegmentationClass/encoded/'+line",
"\"No matching label file for image : \" + line",
"filenames to be taken as training set. val-file = txt",
"# # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law",
"[64, 128, 0], [192, 128, 0], [64, 0, 128], [192,",
"tl.write(data_dir+'SegmentationClass/encoded/'+line + '.npy' + '\\n') val_text_file = open(val_file, \"r\") lines",
"= i #new_label[np.argwhere((label.astype(np.int32) == cls_to_clr_map[i]).all(axis=2))]=i print(np.where((label.astype(np.int32) == [120, 0, 128]).all(axis=2)))",
"[64, 0, 0], [192, 0, 0], [64, 128, 0], [192,",
"for line in lines: if os.path.exists(data_dir+'JPEGImages/'+line+'.jpg'): vi.write(data_dir+'JPEGImages/'+line+'.jpg' + '\\n') assert",
"# # Licensed under the Apache License, Version 2.0 (the",
"dataset_utils.py --train-file=\"\" --val-file=\"\" --data_dir=\"\" ''' args = get_args() data_dir =",
"file except in compliance with the License. # You may",
"on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS",
"set. val-file = txt file containing randomly selected image filenames",
"128], [0, 64, 0], [128, 64, 0], [0, 192, 0],",
"line in lines: if os.path.exists(data_dir+'JPEGImages/'+line+'.jpg'): ti.write(data_dir+'JPEGImages/'+line+'.jpg' + '\\n') assert (os.path.isfile(data_dir+'SegmentationClass/encoded/'+line",
"containing randomly selected image filenames to be taken as validation",
"limitations under the License. import numpy as np import os",
"corresponding class numbers. Assuming that the input label in 3-dim(h,w,c)",
"# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express",
"[0, 0, 128], [120, 0, 128], [0, 128, 128], [128,",
"Usage: python dataset_utils.py --train-file=\"\" --val-file=\"\" --data_dir=\"\" ''' args = get_args()",
"imread(data_dir+'SegmentationClass/' + filename).astype('float32') label = encode_label(label) np.save(data_dir+'SegmentationClass/' + 'encoded/' +",
"[224, 224, 192]]) def encode_label(label): ''' Converting pixel values to",
"the input label in 3-dim(h,w,c) and in BGR fromat read",
"class numbers. Assuming that the input label in 3-dim(h,w,c) and",
"--data_dir=\"\" ''' args = get_args() data_dir = args.data_dir if not",
"set. data-dir = dataset directory Usage: python dataset_utils.py --train-file=\"\" --val-file=\"\"",
"RGB format return np.array([[0, 0, 0], [128, 0, 0], [0,",
"for line in val_text_file] for line in lines: if os.path.exists(data_dir+'JPEGImages/'+line+'.jpg'):",
"= args.data_dir if not os.path.exists(data_dir+'SegmentationClass/' + 'encoded/'): os.makedirs(data_dir+'SegmentationClass/' + 'encoded/')",
"directory Usage: python dataset_utils.py --train-file=\"\" --val-file=\"\" --data_dir=\"\" ''' args =",
"language governing permissions and # limitations under the License. import",
"encode_label(label) np.save(data_dir+'SegmentationClass/' + 'encoded/' + filename.split('.')[0] + '.npy', label) generate_path_files(args.data_dir,",
"0, 128], [0, 128, 128], [128, 128, 128], [64, 0,",
"get_args() data_dir = args.data_dir if not os.path.exists(data_dir+'SegmentationClass/' + 'encoded/'): os.makedirs(data_dir+'SegmentationClass/'",
"http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed",
"read from cv2 ''' h, w, c = label.shape new_label",
"= get_color() for i in range(cls_to_clr_map.shape[0]): #new_label[(label == cls_to_clr_map[i])[:,:,0]] =",
"128, 128], [64, 0, 0], [192, 0, 0], [64, 128,",
"line + '.jpg' tl.write(data_dir+'SegmentationClass/encoded/'+line + '.npy' + '\\n') val_text_file =",
"be taken as training set. val-file = txt file containing",
"import os from scipy.misc import imread from args import get_args",
"new_label[np.where( (label.astype(np.int32) == cls_to_clr_map[i]).all(axis=2))] = 255 else: new_label[np.where( (label.astype(np.int32) ==",
"or implied. # See the License for the specific language",
"+ '.npy' + '\\n') val_text_file = open(val_file, \"r\") lines =",
"Rights Reserved. # # Licensed under the Apache License, Version",
"ti = open('train_image.txt', 'w') tl = open('train_label.txt', 'w') vi =",
"0, 128]).all(axis=2))) if i == 21: new_label[np.where( (label.astype(np.int32) == cls_to_clr_map[i]).all(axis=2))]",
"KIND, either express or implied. # See the License for",
"specific language governing permissions and # limitations under the License.",
"0], [64, 128, 0], [192, 128, 0], [64, 0, 128],",
"line + '.jpg' vl.write(data_dir+'SegmentationClass/encoded/'+line + '.npy' + '\\n') ti.close() tl.close()",
"lines = [line[:-1] for line in val_text_file] for line in",
"+ 'encoded/') for filename in os.listdir(data_dir+'SegmentationClass/'): if os.path.isdir(data_dir+'SegmentationClass/' + filename):",
"'w') rootdir = data_dir train_text_file = open(train_file, \"r\") lines =",
"License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by",
"0, 0], [64, 128, 0], [192, 128, 0], [64, 0,",
"open('val_label.txt', 'w') rootdir = data_dir train_text_file = open(train_file, \"r\") lines",
"in train_text_file] for line in lines: if os.path.exists(data_dir+'JPEGImages/'+line+'.jpg'): ti.write(data_dir+'JPEGImages/'+line+'.jpg' +",
"def generate_path_files(data_dir, train_file, val_file): ti = open('train_image.txt', 'w') tl =",
"'\\n') assert (os.path.isfile(data_dir+'SegmentationClass/encoded/'+line + '.npy')), \"No matching label file for",
"train_text_file] for line in lines: if os.path.exists(data_dir+'JPEGImages/'+line+'.jpg'): ti.write(data_dir+'JPEGImages/'+line+'.jpg' + '\\n')",
"(the \"License\"); # you may not use this file except",
"# you may not use this file except in compliance",
"containing randomly selected image filenames to be taken as training",
"new_label # this method should generate train-image.txt and train-label.txt def",
"'\\n') val_text_file = open(val_file, \"r\") lines = [line[:-1] for line",
"assert (os.path.isfile(data_dir+'SegmentationClass/encoded/'+line + '.npy')), \"No matching label file for image",
"128, 128], [0, 64, 0], [128, 64, 0], [0, 192,",
": \" + line + '.jpg' vl.write(data_dir+'SegmentationClass/encoded/'+line + '.npy' +",
"[64, 0, 128], [192, 0, 128], [64, 128, 128], [192,",
"in val_text_file] for line in lines: if os.path.exists(data_dir+'JPEGImages/'+line+'.jpg'): vi.write(data_dir+'JPEGImages/'+line+'.jpg' +",
"# # Unless required by applicable law or agreed to",
"train_file, val_file): ti = open('train_image.txt', 'w') tl = open('train_label.txt', 'w')",
"get_color(): # RGB format return np.array([[0, 0, 0], [128, 0,",
"i in range(cls_to_clr_map.shape[0]): #new_label[(label == cls_to_clr_map[i])[:,:,0]] = i #new_label[np.argwhere((label.astype(np.int32) ==",
"'w') vi = open('val_image.txt', 'w') vl = open('val_label.txt', 'w') rootdir",
"obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0",
"0], [128, 192, 0], [0, 64, 128], [224, 224, 192]])",
"Copyright (c) 2017 Sony Corporation. All Rights Reserved. # #",
"Version 2.0 (the \"License\"); # you may not use this",
"= np.zeros((h, w, 1), dtype=np.int32) cls_to_clr_map = get_color() for i",
"import imread from args import get_args import matplotlib.pyplot as plt",
"the License. import numpy as np import os from scipy.misc",
"and train-label.txt def generate_path_files(data_dir, train_file, val_file): ti = open('train_image.txt', 'w')",
"128]).all(axis=2))) if i == 21: new_label[np.where( (label.astype(np.int32) == cls_to_clr_map[i]).all(axis=2))] =",
"= i return new_label # this method should generate train-image.txt",
"[0, 192, 0], [128, 192, 0], [0, 64, 128], [224,",
"def encode_label(label): ''' Converting pixel values to corresponding class numbers.",
"w, c = label.shape new_label = np.zeros((h, w, 1), dtype=np.int32)",
"lines: if os.path.exists(data_dir+'JPEGImages/'+line+'.jpg'): vi.write(data_dir+'JPEGImages/'+line+'.jpg' + '\\n') assert (os.path.isfile(data_dir+'SegmentationClass/encoded/'+line + '.npy')),",
"tl = open('train_label.txt', 'w') vi = open('val_image.txt', 'w') vl =",
"implied. # See the License for the specific language governing",
"under the Apache License, Version 2.0 (the \"License\"); # you",
"import get_args import matplotlib.pyplot as plt def get_color(): # RGB",
"128, 128], [192, 128, 128], [0, 64, 0], [128, 64,",
"def main(): ''' Arguments: train-file = txt file containing randomly",
"2017 Sony Corporation. All Rights Reserved. # # Licensed under",
"open('train_image.txt', 'w') tl = open('train_label.txt', 'w') vi = open('val_image.txt', 'w')",
"i return new_label # this method should generate train-image.txt and",
"= open('val_image.txt', 'w') vl = open('val_label.txt', 'w') rootdir = data_dir",
"by applicable law or agreed to in writing, software #",
"''' Arguments: train-file = txt file containing randomly selected image",
"[192, 0, 128], [64, 128, 128], [192, 128, 128], [0,",
"<filename>semantic-segmentation/deeplabv3plus/dataset_utils.py # Copyright (c) 2017 Sony Corporation. All Rights Reserved.",
"(label.astype(np.int32) == cls_to_clr_map[i]).all(axis=2))] = i return new_label # this method",
"[120, 0, 128], [0, 128, 128], [128, 128, 128], [64,",
"args = get_args() data_dir = args.data_dir if not os.path.exists(data_dir+'SegmentationClass/' +",
"+ '.jpg' vl.write(data_dir+'SegmentationClass/encoded/'+line + '.npy' + '\\n') ti.close() tl.close() vi.close()",
"randomly selected image filenames to be taken as training set.",
"line in val_text_file] for line in lines: if os.path.exists(data_dir+'JPEGImages/'+line+'.jpg'): vi.write(data_dir+'JPEGImages/'+line+'.jpg'",
"(label.astype(np.int32) == cls_to_clr_map[i]).all(axis=2))] = 255 else: new_label[np.where( (label.astype(np.int32) == cls_to_clr_map[i]).all(axis=2))]",
"0], [192, 128, 0], [64, 0, 128], [192, 0, 128],",
"== cls_to_clr_map[i])[:,:,0]] = i #new_label[np.argwhere((label.astype(np.int32) == cls_to_clr_map[i]).all(axis=2))]=i print(np.where((label.astype(np.int32) == [120,",
"[128, 0, 0], [0, 128, 0], [128, 128, 0], [0,",
"val_text_file] for line in lines: if os.path.exists(data_dir+'JPEGImages/'+line+'.jpg'): vi.write(data_dir+'JPEGImages/'+line+'.jpg' + '\\n')",
"+ '.jpg' tl.write(data_dir+'SegmentationClass/encoded/'+line + '.npy' + '\\n') val_text_file = open(val_file,",
"--train-file=\"\" --val-file=\"\" --data_dir=\"\" ''' args = get_args() data_dir = args.data_dir",
"[line[:-1] for line in val_text_file] for line in lines: if",
"import numpy as np import os from scipy.misc import imread",
"open('val_image.txt', 'w') vl = open('val_label.txt', 'w') rootdir = data_dir train_text_file",
"in os.listdir(data_dir+'SegmentationClass/'): if os.path.isdir(data_dir+'SegmentationClass/' + filename): continue label = imread(data_dir+'SegmentationClass/'",
"128], [192, 128, 128], [0, 64, 0], [128, 64, 0],",
"train-label.txt def generate_path_files(data_dir, train_file, val_file): ti = open('train_image.txt', 'w') tl",
"#new_label[np.argwhere((label.astype(np.int32) == cls_to_clr_map[i]).all(axis=2))]=i print(np.where((label.astype(np.int32) == [120, 0, 128]).all(axis=2))) if i",
"[128, 128, 128], [64, 0, 0], [192, 0, 0], [64,",
"= encode_label(label) np.save(data_dir+'SegmentationClass/' + 'encoded/' + filename.split('.')[0] + '.npy', label)",
"+ 'encoded/'): os.makedirs(data_dir+'SegmentationClass/' + 'encoded/') for filename in os.listdir(data_dir+'SegmentationClass/'): if",
"an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF",
"'encoded/' + filename.split('.')[0] + '.npy', label) generate_path_files(args.data_dir, args.train_file, args.val_file) if",
"Unless required by applicable law or agreed to in writing,",
"vl.close() def main(): ''' Arguments: train-file = txt file containing",
"the specific language governing permissions and # limitations under the",
"# limitations under the License. import numpy as np import",
"os.path.exists(data_dir+'JPEGImages/'+line+'.jpg'): vi.write(data_dir+'JPEGImages/'+line+'.jpg' + '\\n') assert (os.path.isfile(data_dir+'SegmentationClass/encoded/'+line + '.npy')), \"No matching",
"255 else: new_label[np.where( (label.astype(np.int32) == cls_to_clr_map[i]).all(axis=2))] = i return new_label",
"selected image filenames to be taken as training set. val-file",
"applicable law or agreed to in writing, software # distributed",
"0], [128, 0, 0], [0, 128, 0], [128, 128, 0],",
"val_text_file = open(val_file, \"r\") lines = [line[:-1] for line in",
"imread from args import get_args import matplotlib.pyplot as plt def",
"= 255 else: new_label[np.where( (label.astype(np.int32) == cls_to_clr_map[i]).all(axis=2))] = i return",
"Converting pixel values to corresponding class numbers. Assuming that the",
"in writing, software # distributed under the License is distributed",
"val_file): ti = open('train_image.txt', 'w') tl = open('train_label.txt', 'w') vi",
"for line in lines: if os.path.exists(data_dir+'JPEGImages/'+line+'.jpg'): ti.write(data_dir+'JPEGImages/'+line+'.jpg' + '\\n') assert",
"'.jpg' vl.write(data_dir+'SegmentationClass/encoded/'+line + '.npy' + '\\n') ti.close() tl.close() vi.close() vl.close()",
"os.path.exists(data_dir+'SegmentationClass/' + 'encoded/'): os.makedirs(data_dir+'SegmentationClass/' + 'encoded/') for filename in os.listdir(data_dir+'SegmentationClass/'):",
"0], [0, 192, 0], [128, 192, 0], [0, 64, 128],",
"+ '\\n') ti.close() tl.close() vi.close() vl.close() def main(): ''' Arguments:",
"\"r\") lines = [line[:-1] for line in train_text_file] for line",
"License is distributed on an \"AS IS\" BASIS, # WITHOUT",
"in range(cls_to_clr_map.shape[0]): #new_label[(label == cls_to_clr_map[i])[:,:,0]] = i #new_label[np.argwhere((label.astype(np.int32) == cls_to_clr_map[i]).all(axis=2))]=i",
"c = label.shape new_label = np.zeros((h, w, 1), dtype=np.int32) cls_to_clr_map",
"License, Version 2.0 (the \"License\"); # you may not use",
"# You may obtain a copy of the License at",
"128], [0, 128, 128], [128, 128, 128], [64, 0, 0],",
"+ '\\n') assert (os.path.isfile(data_dir+'SegmentationClass/encoded/'+line + '.npy')), \"No matching label file",
"= open(val_file, \"r\") lines = [line[:-1] for line in val_text_file]",
"+ '\\n') val_text_file = open(val_file, \"r\") lines = [line[:-1] for",
"copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # #",
"[192, 128, 0], [64, 0, 128], [192, 0, 128], [64,",
"[line[:-1] for line in train_text_file] for line in lines: if",
"128, 0], [64, 0, 128], [192, 0, 128], [64, 128,",
"i #new_label[np.argwhere((label.astype(np.int32) == cls_to_clr_map[i]).all(axis=2))]=i print(np.where((label.astype(np.int32) == [120, 0, 128]).all(axis=2))) if",
"in BGR fromat read from cv2 ''' h, w, c",
"val-file = txt file containing randomly selected image filenames to",
"the License for the specific language governing permissions and #",
"Apache License, Version 2.0 (the \"License\"); # you may not",
"scipy.misc import imread from args import get_args import matplotlib.pyplot as",
"fromat read from cv2 ''' h, w, c = label.shape",
"= dataset directory Usage: python dataset_utils.py --train-file=\"\" --val-file=\"\" --data_dir=\"\" '''",
"either express or implied. # See the License for the",
"[128, 128, 0], [0, 0, 128], [120, 0, 128], [0,",
"not os.path.exists(data_dir+'SegmentationClass/' + 'encoded/'): os.makedirs(data_dir+'SegmentationClass/' + 'encoded/') for filename in",
"filename).astype('float32') label = encode_label(label) np.save(data_dir+'SegmentationClass/' + 'encoded/' + filename.split('.')[0] +",
"# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or",
"+ filename): continue label = imread(data_dir+'SegmentationClass/' + filename).astype('float32') label =",
"Corporation. All Rights Reserved. # # Licensed under the Apache",
"License. import numpy as np import os from scipy.misc import",
"cls_to_clr_map = get_color() for i in range(cls_to_clr_map.shape[0]): #new_label[(label == cls_to_clr_map[i])[:,:,0]]",
"for image : \" + line + '.jpg' vl.write(data_dir+'SegmentationClass/encoded/'+line +",
"values to corresponding class numbers. Assuming that the input label",
"h, w, c = label.shape new_label = np.zeros((h, w, 1),",
"matplotlib.pyplot as plt def get_color(): # RGB format return np.array([[0,",
"to be taken as validation set. data-dir = dataset directory",
"''' args = get_args() data_dir = args.data_dir if not os.path.exists(data_dir+'SegmentationClass/'",
"matching label file for image : \" + line +",
"# RGB format return np.array([[0, 0, 0], [128, 0, 0],",
"[0, 64, 128], [224, 224, 192]]) def encode_label(label): ''' Converting",
"lines = [line[:-1] for line in train_text_file] for line in",
"should generate train-image.txt and train-label.txt def generate_path_files(data_dir, train_file, val_file): ti",
"vi.write(data_dir+'JPEGImages/'+line+'.jpg' + '\\n') assert (os.path.isfile(data_dir+'SegmentationClass/encoded/'+line + '.npy')), \"No matching label",
"+ line + '.jpg' vl.write(data_dir+'SegmentationClass/encoded/'+line + '.npy' + '\\n') ti.close()",
"Arguments: train-file = txt file containing randomly selected image filenames",
"= open('val_label.txt', 'w') rootdir = data_dir train_text_file = open(train_file, \"r\")",
"a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 #",
"to be taken as training set. val-file = txt file",
"0], [0, 128, 0], [128, 128, 0], [0, 0, 128],",
"open('train_label.txt', 'w') vi = open('val_image.txt', 'w') vl = open('val_label.txt', 'w')",
"+ '.npy' + '\\n') ti.close() tl.close() vi.close() vl.close() def main():",
"= data_dir train_text_file = open(train_file, \"r\") lines = [line[:-1] for",
"args import get_args import matplotlib.pyplot as plt def get_color(): #",
"tl.close() vi.close() vl.close() def main(): ''' Arguments: train-file = txt",
"'.jpg' tl.write(data_dir+'SegmentationClass/encoded/'+line + '.npy' + '\\n') val_text_file = open(val_file, \"r\")",
"128, 0], [192, 128, 0], [64, 0, 128], [192, 0,",
"\"License\"); # you may not use this file except in",
"distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR",
"label = imread(data_dir+'SegmentationClass/' + filename).astype('float32') label = encode_label(label) np.save(data_dir+'SegmentationClass/' +",
"file containing randomly selected image filenames to be taken as",
"selected image filenames to be taken as validation set. data-dir",
"128], [128, 128, 128], [64, 0, 0], [192, 0, 0],",
"print(np.where((label.astype(np.int32) == [120, 0, 128]).all(axis=2))) if i == 21: new_label[np.where(",
"# distributed under the License is distributed on an \"AS",
"os.listdir(data_dir+'SegmentationClass/'): if os.path.isdir(data_dir+'SegmentationClass/' + filename): continue label = imread(data_dir+'SegmentationClass/' +",
"# Unless required by applicable law or agreed to in",
"image filenames to be taken as training set. val-file =",
"128, 0], [0, 0, 128], [120, 0, 128], [0, 128,",
"as plt def get_color(): # RGB format return np.array([[0, 0,",
"\"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY",
"0, 0], [0, 128, 0], [128, 128, 0], [0, 0,",
"192, 0], [128, 192, 0], [0, 64, 128], [224, 224,",
"input label in 3-dim(h,w,c) and in BGR fromat read from",
"for filename in os.listdir(data_dir+'SegmentationClass/'): if os.path.isdir(data_dir+'SegmentationClass/' + filename): continue label",
"else: new_label[np.where( (label.astype(np.int32) == cls_to_clr_map[i]).all(axis=2))] = i return new_label #",
"txt file containing randomly selected image filenames to be taken",
"You may obtain a copy of the License at #",
"128], [192, 0, 128], [64, 128, 128], [192, 128, 128],",
"train_text_file = open(train_file, \"r\") lines = [line[:-1] for line in",
"return np.array([[0, 0, 0], [128, 0, 0], [0, 128, 0],",
"\" + line + '.jpg' tl.write(data_dir+'SegmentationClass/encoded/'+line + '.npy' + '\\n')",
"the Apache License, Version 2.0 (the \"License\"); # you may",
"0, 0], [192, 0, 0], [64, 128, 0], [192, 128,",
"np.array([[0, 0, 0], [128, 0, 0], [0, 128, 0], [128,",
"pixel values to corresponding class numbers. Assuming that the input"
] |
[
"args, so that it's saved in checkpoints args.source_lang, args.target_lang =",
"MultiprocessingTrainer(args, model) # Load the latest checkpoint if one is",
"+ ' | valid loss {:2.2f} | valid ppl {:3.2f}'",
"training in {:.1f} seconds'.format(train_meter.sum)) # Generate on test set and",
"in sample) loss = trainer.valid_step(sample, criterion) loss_meter.update(loss, ntokens) t.set_postfix(loss='{:.2f}'.format(loss_meter.avg)) val_loss",
"set and compute BLEU score for beam in [1, 5,",
"> args.min_lr and epoch <= max_epoch: # train for one",
"batch_size=None, max_tokens=args.max_tokens, max_positions=args.max_positions) loss_meter = AverageMeter() desc = '| epoch",
"| valid loss {:2.2f} | valid ppl {:3.2f}' .format(val_loss, math.pow(2,",
"for s in sample) loss = trainer.valid_step(sample, criterion) loss_meter.update(loss, ntokens)",
"from fairseq.progress_bar import progress_bar from fairseq.sequence_generator import SequenceGenerator def main():",
"Generate on test set and compute BLEU score for beam",
"gnorm_meter.avg)) def validate(args, epoch, trainer, criterion, dataset, subset, ngpus): \"\"\"Evaluate",
"trainer.get_lr() with progress_bar(itr, desc, leave=False) as t: for i, sample",
"max_tokens=args.max_tokens, max_positions=args.max_positions) loss_meter = AverageMeter() desc = '| epoch {:03d}",
"rights # can be found in the PATENTS file in",
"+= ' | s/checkpoint {:7d} | words/s {:6d} | words/batch",
"type=int, metavar='N', help='maximum number of tokens in a batch') dataset_args.add_argument('--batch-size',",
"' | train loss {:2.2f} | train ppl {:3.2f}' fmt",
"batch_offset = 0 train_meter.stop() print('| done training in {:.1f} seconds'.format(train_meter.sum))",
"# words per second clip_meter = AverageMeter() # % of",
"> 0 else None)) print('| Test on {} with beam={}:",
"= options.add_dataset_args(parser) dataset_args.add_argument('--max-tokens', default=0, type=int, metavar='N', help='maximum number of tokens",
"help='batch size for validation set') dataset_args.add_argument('--train-subset', default='train', metavar='SPLIT', choices=['train', 'valid',",
"help='maximum number of tokens in a batch') dataset_args.add_argument('--batch-size', default=32, type=int,",
"for validation set') dataset_args.add_argument('--train-subset', default='train', metavar='SPLIT', choices=['train', 'valid', 'test'], help='data",
"% of updates clipped gnorm_meter = AverageMeter() # gradient norm",
"updates clipped gnorm_meter = AverageMeter() # gradient norm desc =",
"0, val_loss, validation_script=args.valid_script) # only use first validation loss to",
"= AverageMeter() bsz_meter = AverageMeter() # sentences per batch wpb_meter",
"args.max_tokens to infinity(same as setting to None) if args.max_tokens ==",
"desc = '| epoch {:03d}'.format(epoch) lr = trainer.get_lr() with progress_bar(itr,",
"trainer.train_step(sample, criterion) ntokens = sum(s['ntokens'] for s in sample) src_size",
"= '| epoch {:03d} | valid on \\'{}\\' subset'.format(epoch, subset)",
"epoch += 1 batch_offset = 0 train_meter.stop() print('| done training",
"loss_meter = AverageMeter() bsz_meter = AverageMeter() # sentences per batch",
"t: for i, sample in data.skip_group_enumerator(t, num_gpus, batch_offset): loss, grad_norm",
"calculation wps_meter.reset() if args.save_interval > 0 and (i + 1)",
"same directory. # import collections import os import torch import",
"| train loss {:2.2f} | train ppl {:3.2f}' fmt +=",
"% args.save_interval == 0: trainer.save_checkpoint(args, epoch, i + 1) fmt",
"help='path to external validation script (optional).') options.add_optimization_args(parser) options.add_checkpoint_args(parser) options.add_model_args(parser) args",
"math.pow(2, loss_meter.avg), round(wps_meter.elapsed_time), round(wps_meter.avg), round(wpb_meter.avg), round(bsz_meter.avg), lr, clip_meter.avg * 100,",
"= data.load_with_check(args.data, args.source_lang, args.target_lang) if args.source_lang is None or args.target_lang",
"[{}] dictionary: {} types'.format(dataset.src, len(dataset.src_dict))) print('| [{}] dictionary: {} types'.format(dataset.dst,",
"not torch.cuda.is_available(): raise NotImplementedError('Training on CPU is not supported') num_gpus",
"one is available epoch, batch_offset = trainer.load_checkpoint(os.path.join(args.save_dir, args.restore_file)) # Train",
"AverageMeter() # gradient norm desc = '| epoch {:03d}'.format(epoch) lr",
"dataset_args.add_argument('--batch-size', default=32, type=int, metavar='N', help='batch size') dataset_args.add_argument('--test-batch-size', default=32, type=int, metavar='N',",
"if i == 0: # ignore the first mini-batch in",
"loss, grad_norm = trainer.train_step(sample, criterion) ntokens = sum(s['ntokens'] for s",
"trainer, criterion, dataset, subset, ngpus): \"\"\"Evaluate the model on the",
"beam_size=beam) if torch.cuda.is_available(): translator.cuda() scorer = bleu.Scorer(dataset.dst_dict.pad(), dataset.dst_dict.eos(), dataset.dst_dict.unk()) itr",
"print(args) if args.no_progress_bar: progress_bar.enabled = False progress_bar.print_interval = args.log_interval if",
"CPU is not supported') num_gpus = torch.cuda.device_count() print('| using {}",
"in data.skip_group_enumerator(t, num_gpus, batch_offset): loss, grad_norm = trainer.train_step(sample, criterion) ntokens",
"learning schedule lr = trainer.lr_step(val_loss, epoch) epoch += 1 batch_offset",
"or math.inf lr = trainer.get_lr() train_meter = StopwatchMeter() train_meter.start() while",
"args.no_save: # save checkpoint trainer.save_checkpoint(args, epoch, 0, val_loss, validation_script=args.valid_script) #",
"fairseq.meters import AverageMeter, StopwatchMeter, TimeMeter from fairseq.multiprocessing_trainer import MultiprocessingTrainer from",
"the LICENSE file in # the root directory of this",
"s/checkpoint {:7d} | words/s {:6d} | words/batch {:6d}' fmt +=",
"size') dataset_args.add_argument('--test-batch-size', default=32, type=int, metavar='N', help='batch size for test set')",
"epoch {:03d}'.format(epoch) lr = trainer.get_lr() with progress_bar(itr, desc, leave=False) as",
"help='data subset to use for training (train, valid, test)') dataset_args.add_argument('--valid-subset',",
"found in the PATENTS file in the same directory. #",
"# All rights reserved. # # This source code is",
"save checkpoint trainer.save_checkpoint(args, epoch, 0, val_loss, validation_script=args.valid_script) # only use",
"= utils.build_model(args, dataset) criterion = utils.build_criterion(args, dataset) # Start multiprocessing",
"and compute BLEU score for beam in [1, 5, 10,",
"val_loss def score_test(args, model, dataset, subset, beam, cuda_device): \"\"\"Evaluate the",
"patent rights # can be found in the PATENTS file",
"type=int, metavar='N', help='batch size for test set') dataset_args.add_argument('--valid-batch-size', default=32, type=int,",
"subset ' 'to use for testing (train, valid, test)') dataset_args.add_argument('--valid-script',",
"first mini-batch in words-per-second calculation wps_meter.reset() if args.save_interval > 0",
"type=int, metavar='N', help='batch size') dataset_args.add_argument('--test-batch-size', default=32, type=int, metavar='N', help='batch size",
"options, utils from fairseq.meters import AverageMeter, StopwatchMeter, TimeMeter from fairseq.multiprocessing_trainer",
"else 0) gnorm_meter.update(grad_norm) t.set_postfix(collections.OrderedDict([ ('loss', '{:.2f} ({:.2f})'.format(loss, loss_meter.avg)), ('wps', '{:5d}'.format(round(wps_meter.avg))),",
"dictionary: {} types'.format(dataset.src, len(dataset.src_dict))) print('| [{}] dictionary: {} types'.format(dataset.dst, len(dataset.dst_dict)))",
"\"\"\"Evaluate the model on the test set and return the",
"this source tree. An additional grant of patent rights #",
"licensed under the license found in the LICENSE file in",
"valid, valid1,test, test1)') dataset_args.add_argument('--test-subset', default='test', metavar='SPLIT', help='comma separated list ofdata",
"size for test set') dataset_args.add_argument('--valid-batch-size', default=32, type=int, metavar='N', help='batch size",
"| lr {:0.6f} | clip {:3.0f}% | gnorm {:.4f}' t.write(fmt.format(loss_meter.avg,",
"GPU = {})'.format(num_gpus, args.max_tokens)) # Build model print('| model {}'.format(args.arch))",
"SequenceGenerator([model], dataset.dst_dict, beam_size=beam) if torch.cuda.is_available(): translator.cuda() scorer = bleu.Scorer(dataset.dst_dict.pad(), dataset.dst_dict.eos(),",
"= MultiprocessingTrainer(args, model) # Load the latest checkpoint if one",
"lr = trainer.get_lr() train_meter = StopwatchMeter() train_meter.start() while lr >",
"for training (train, valid, test)') dataset_args.add_argument('--valid-subset', default='valid', metavar='SPLIT', help='comma separated",
"{:3.0f}% | gnorm {:.4f}' t.write(fmt.format(loss_meter.avg, math.pow(2, loss_meter.avg), round(wps_meter.elapsed_time), round(wps_meter.avg), round(wpb_meter.avg),",
"cuda_device): \"\"\"Evaluate the model on the test set and return",
"from fairseq.multiprocessing_trainer import MultiprocessingTrainer from fairseq.progress_bar import progress_bar from fairseq.sequence_generator",
"{} {} examples'.format(args.data, split, len(dataset.splits[split]))) if not torch.cuda.is_available(): raise NotImplementedError('Training",
"enumerate(args.valid_subset.split(',')): val_loss = validate(args, epoch, trainer, criterion, dataset, subset, num_gpus)",
"use for training (train, valid, test)') dataset_args.add_argument('--valid-subset', default='valid', metavar='SPLIT', help='comma",
"on CPU is not supported') num_gpus = torch.cuda.device_count() print('| using",
"and return the BLEU scorer.\"\"\" translator = SequenceGenerator([model], dataset.dst_dict, beam_size=beam)",
"if not args.no_save: # save checkpoint trainer.save_checkpoint(args, epoch, 0, val_loss,",
"sum(s['ntokens'] for s in sample) src_size = sum(s['src_tokens'].size(0) for s",
"desc, leave=False) as t: for _, sample in data.skip_group_enumerator(t, ngpus):",
"learning rate return val_loss def score_test(args, model, dataset, subset, beam,",
"scorer = bleu.Scorer(dataset.dst_dict.pad(), dataset.dst_dict.eos(), dataset.dst_dict.unk()) itr = dataset.dataloader(subset, batch_size=4, max_positions=args.max_positions)",
"# evaluate on validate set for k, subset in enumerate(args.valid_subset.split(',')):",
"to use for training (train, valid, test)') dataset_args.add_argument('--valid-subset', default='valid', metavar='SPLIT',",
"default='test', metavar='SPLIT', help='comma separated list ofdata subset ' 'to use",
"using {} GPUs (with max tokens per GPU = {})'.format(num_gpus,",
"loss_meter.update(loss, ntokens) bsz_meter.update(src_size) wpb_meter.update(ntokens) wps_meter.update(ntokens) clip_meter.update(1 if grad_norm > args.clip_norm",
"validate(args, epoch, trainer, criterion, dataset, subset, ngpus): \"\"\"Evaluate the model",
"the root directory of this source tree. An additional grant",
"print('| [{}] dictionary: {} types'.format(dataset.dst, len(dataset.dst_dict))) for split in dataset.splits:",
"# Generate on test set and compute BLEU score for",
"len(dataset.dst_dict))) for split in dataset.splits: print('| {} {} {} examples'.format(args.data,",
"test)') dataset_args.add_argument('--valid-script', nargs='+', metavar='PATH', help='path to external validation script (optional).')",
"seconds'.format(train_meter.sum)) # Generate on test set and compute BLEU score",
"data.load_with_check(args.data, args.source_lang, args.target_lang) if args.source_lang is None or args.target_lang is",
"score for beam in [1, 5, 10, 20]: for subset",
"on {} with beam={}: {}'.format(subset, beam, scorer.result_string())) # Stop multiprocessing",
"_, ref, hypos in translator.generate_batched_itr(itr, cuda_device=cuda_device): scorer.add(ref.int().cpu(), hypos[0]['tokens'].int().cpu()) return scorer",
"the model on the test set and return the BLEU",
"{} {} {} examples'.format(args.data, split, len(dataset.splits[split]))) if not torch.cuda.is_available(): raise",
"| clip {:3.0f}% | gnorm {:.4f}' t.write(fmt.format(loss_meter.avg, math.pow(2, loss_meter.avg), round(wps_meter.elapsed_time),",
"batch_offset = trainer.load_checkpoint(os.path.join(args.save_dir, args.restore_file)) # Train until the learning rate",
"_, sample in data.skip_group_enumerator(t, ngpus): ntokens = sum(s['ntokens'] for s",
"torch import math from fairseq import bleu, data, options, utils",
"not os.path.exists(args.save_dir): os.makedirs(args.save_dir) torch.manual_seed(args.seed) # Setting args.max_tokens to infinity(same as",
"the validation set and return the average loss.\"\"\" itr =",
"options.add_model_args(parser) args = utils.parse_args_and_arch(parser) print(args) if args.no_progress_bar: progress_bar.enabled = False",
"{:6d} | words/batch {:6d}' fmt += ' | bsz {:5d}",
"| words/batch {:6d}' fmt += ' | bsz {:5d} |",
"# sentences per batch wpb_meter = AverageMeter() # words per",
"Load dataset dataset = data.load_with_check(args.data, args.source_lang, args.target_lang) if args.source_lang is",
"MultiprocessingTrainer from fairseq.progress_bar import progress_bar from fairseq.sequence_generator import SequenceGenerator def",
"valid, test)') dataset_args.add_argument('--valid-script', nargs='+', metavar='PATH', help='path to external validation script",
"batch wpb_meter = AverageMeter() # words per batch wps_meter =",
"if args.no_progress_bar: progress_bar.enabled = False progress_bar.print_interval = args.log_interval if not",
"set and return the BLEU scorer.\"\"\" translator = SequenceGenerator([model], dataset.dst_dict,",
"(train, valid, test)') dataset_args.add_argument('--valid-script', nargs='+', metavar='PATH', help='path to external validation",
"is None: # record inferred languages in args, so that",
"dataset_args.add_argument('--valid-subset', default='valid', metavar='SPLIT', help='comma separated list ofdata subsets ' '",
"'to use for testing (train, valid, test)') dataset_args.add_argument('--valid-script', nargs='+', metavar='PATH',",
"ppl {:3.2f}' fmt += ' | s/checkpoint {:7d} | words/s",
"| valid on \\'{}\\' subset'.format(epoch, subset) with progress_bar(itr, desc, leave=False)",
"{:.4f}' t.write(fmt.format(loss_meter.avg, math.pow(2, loss_meter.avg), round(wps_meter.elapsed_time), round(wps_meter.avg), round(wpb_meter.avg), round(bsz_meter.avg), lr, clip_meter.avg",
"desc = '| epoch {:03d} | valid on \\'{}\\' subset'.format(epoch,",
"\"\"\"Evaluate the model on the validation set and return the",
"words per second clip_meter = AverageMeter() # % of updates",
"An additional grant of patent rights # can be found",
"0: trainer.save_checkpoint(args, epoch, i + 1) fmt = desc +",
"set and return the average loss.\"\"\" itr = dataset.dataloader(subset, batch_size=None,",
"test set and return the BLEU scorer.\"\"\" translator = SequenceGenerator([model],",
"_, _, ref, hypos in translator.generate_batched_itr(itr, cuda_device=cuda_device): scorer.add(ref.int().cpu(), hypos[0]['tokens'].int().cpu()) return",
"words-per-second calculation wps_meter.reset() if args.save_interval > 0 and (i +",
"batch_size=4, max_positions=args.max_positions) for _, _, ref, hypos in translator.generate_batched_itr(itr, cuda_device=cuda_device):",
"the PATENTS file in the same directory. # import collections",
"(with max tokens per GPU = {})'.format(num_gpus, args.max_tokens)) # Build",
"' to use for validation (train, valid, valid1,test, test1)') dataset_args.add_argument('--test-subset',",
"on the test set and return the BLEU scorer.\"\"\" translator",
"found in the LICENSE file in # the root directory",
"epoch train(args, epoch, batch_offset, trainer, criterion, dataset, num_gpus) # evaluate",
"file in # the root directory of this source tree.",
"one epoch train(args, epoch, batch_offset, trainer, criterion, dataset, num_gpus) #",
"as t: for _, sample in data.skip_group_enumerator(t, ngpus): ntokens =",
"{:5d} | lr {:0.6f} | clip {:3.0f}% | gnorm {:.4f}'",
"for test set') dataset_args.add_argument('--valid-batch-size', default=32, type=int, metavar='N', help='batch size for",
"the learning rate return val_loss def score_test(args, model, dataset, subset,",
"args.restore_file)) # Train until the learning rate gets too small",
"= dataset.dataloader(subset, batch_size=None, max_tokens=args.max_tokens, max_positions=args.max_positions) loss_meter = AverageMeter() desc =",
"Inc. # All rights reserved. # # This source code",
"infinity(same as setting to None) if args.max_tokens == 0: args.max_tokens",
"of updates clipped gnorm_meter = AverageMeter() # gradient norm desc",
"subsets ' ' to use for validation (train, valid, valid1,test,",
"inferred languages in args, so that it's saved in checkpoints",
"cuda_device=cuda_device): scorer.add(ref.int().cpu(), hypos[0]['tokens'].int().cpu()) return scorer if __name__ == '__main__': main()",
"to None) if args.max_tokens == 0: args.max_tokens = None #",
"metavar='SPLIT', help='comma separated list ofdata subset ' 'to use for",
"max_epoch = args.max_epoch or math.inf lr = trainer.get_lr() train_meter =",
"help='comma separated list ofdata subset ' 'to use for testing",
"loss_meter.avg)), ('wps', '{:5d}'.format(round(wps_meter.avg))), ('wpb', '{:5d}'.format(round(wpb_meter.avg))), ('bsz', '{:5d}'.format(round(bsz_meter.avg))), ('lr', lr), ('clip',",
"'test'], help='data subset to use for training (train, valid, test)')",
"# import collections import os import torch import math from",
"beam in [1, 5, 10, 20]: for subset in args.test_subset.split(','):",
"trainer.stop() def train(args, epoch, batch_offset, trainer, criterion, dataset, num_gpus): \"\"\"Train",
"dictionary: {} types'.format(dataset.dst, len(dataset.dst_dict))) for split in dataset.splits: print('| {}",
"val_loss = loss_meter.avg t.write(desc + ' | valid loss {:2.2f}",
"# % of updates clipped gnorm_meter = AverageMeter() # gradient",
"AverageMeter, StopwatchMeter, TimeMeter from fairseq.multiprocessing_trainer import MultiprocessingTrainer from fairseq.progress_bar import",
"as t: for i, sample in data.skip_group_enumerator(t, num_gpus, batch_offset): loss,",
"(train, valid, valid1,test, test1)') dataset_args.add_argument('--test-subset', default='test', metavar='SPLIT', help='comma separated list",
"words/s {:6d} | words/batch {:6d}' fmt += ' | bsz",
"split, len(dataset.splits[split]))) if not torch.cuda.is_available(): raise NotImplementedError('Training on CPU is",
"compute BLEU score for beam in [1, 5, 10, 20]:",
"cuda_device=(0 if num_gpus > 0 else None)) print('| Test on",
"progress_bar.print_interval = args.log_interval if not os.path.exists(args.save_dir): os.makedirs(args.save_dir) torch.manual_seed(args.seed) # Setting",
"sentences per batch wpb_meter = AverageMeter() # words per batch",
"('wps', '{:5d}'.format(round(wps_meter.avg))), ('wpb', '{:5d}'.format(round(wpb_meter.avg))), ('bsz', '{:5d}'.format(round(bsz_meter.avg))), ('lr', lr), ('clip', '{:3.0f}%'.format(clip_meter.avg",
"fairseq.multiprocessing_trainer import MultiprocessingTrainer from fairseq.progress_bar import progress_bar from fairseq.sequence_generator import",
"lr, clip_meter.avg * 100, gnorm_meter.avg)) def validate(args, epoch, trainer, criterion,",
"code is licensed under the license found in the LICENSE",
"epoch, i + 1) fmt = desc + ' |",
"main(): parser = options.get_parser('Trainer') dataset_args = options.add_dataset_args(parser) dataset_args.add_argument('--max-tokens', default=0, type=int,",
"in sample) loss_meter.update(loss, ntokens) bsz_meter.update(src_size) wpb_meter.update(ntokens) wps_meter.update(ntokens) clip_meter.update(1 if grad_norm",
"valid loss {:2.2f} | valid ppl {:3.2f}' .format(val_loss, math.pow(2, val_loss)))",
"num_gpus) if k == 0: if not args.no_save: # save",
"+ ' | train loss {:2.2f} | train ppl {:3.2f}'",
"epoch, batch_offset, trainer, criterion, dataset, num_gpus): \"\"\"Train the model for",
"args.source_lang, args.target_lang) if args.source_lang is None or args.target_lang is None:",
"= validate(args, epoch, trainer, criterion, dataset, subset, num_gpus) if k",
"# gradient norm desc = '| epoch {:03d}'.format(epoch) lr =",
"batch_offset, trainer, criterion, dataset, num_gpus) # evaluate on validate set",
"model on the test set and return the BLEU scorer.\"\"\"",
"args.clip_norm else 0) gnorm_meter.update(grad_norm) t.set_postfix(collections.OrderedDict([ ('loss', '{:.2f} ({:.2f})'.format(loss, loss_meter.avg)), ('wps',",
"5, 10, 20]: for subset in args.test_subset.split(','): scorer = score_test(args,",
"sample in data.skip_group_enumerator(t, ngpus): ntokens = sum(s['ntokens'] for s in",
"directory of this source tree. An additional grant of patent",
"{})'.format(num_gpus, args.max_tokens)) # Build model print('| model {}'.format(args.arch)) model =",
"epoch, 0, val_loss, validation_script=args.valid_script) # only use first validation loss",
"epoch, batch_offset, trainer, criterion, dataset, num_gpus) # evaluate on validate",
"multiprocessing trainer.stop() def train(args, epoch, batch_offset, trainer, criterion, dataset, num_gpus):",
"set') dataset_args.add_argument('--train-subset', default='train', metavar='SPLIT', choices=['train', 'valid', 'test'], help='data subset to",
"checkpoints args.source_lang, args.target_lang = dataset.src, dataset.dst print('| [{}] dictionary: {}",
"in words-per-second calculation wps_meter.reset() if args.save_interval > 0 and (i",
"('clip', '{:3.0f}%'.format(clip_meter.avg * 100)), ('gnorm', '{:.4f}'.format(gnorm_meter.avg)), ])) if i ==",
"metavar='PATH', help='path to external validation script (optional).') options.add_optimization_args(parser) options.add_checkpoint_args(parser) options.add_model_args(parser)",
"test set and compute BLEU score for beam in [1,",
"= trainer.load_checkpoint(os.path.join(args.save_dir, args.restore_file)) # Train until the learning rate gets",
"| s/checkpoint {:7d} | words/s {:6d} | words/batch {:6d}' fmt",
"in data.skip_group_enumerator(t, ngpus): ntokens = sum(s['ntokens'] for s in sample)",
"criterion, dataset, subset, num_gpus) if k == 0: if not",
"dataset, num_gpus): \"\"\"Train the model for one epoch.\"\"\" itr =",
"ntokens) t.set_postfix(loss='{:.2f}'.format(loss_meter.avg)) val_loss = loss_meter.avg t.write(desc + ' | valid",
"grad_norm > args.clip_norm else 0) gnorm_meter.update(grad_norm) t.set_postfix(collections.OrderedDict([ ('loss', '{:.2f} ({:.2f})'.format(loss,",
"and return the average loss.\"\"\" itr = dataset.dataloader(subset, batch_size=None, max_tokens=args.max_tokens,",
"dataset_args = options.add_dataset_args(parser) dataset_args.add_argument('--max-tokens', default=0, type=int, metavar='N', help='maximum number of",
"scorer.\"\"\" translator = SequenceGenerator([model], dataset.dst_dict, beam_size=beam) if torch.cuda.is_available(): translator.cuda() scorer",
"'| epoch {:03d}'.format(epoch) lr = trainer.get_lr() with progress_bar(itr, desc, leave=False)",
"# Build model print('| model {}'.format(args.arch)) model = utils.build_model(args, dataset)",
"types'.format(dataset.dst, len(dataset.dst_dict))) for split in dataset.splits: print('| {} {} {}",
"use first validation loss to update the learning schedule lr",
"subset, beam, cuda_device): \"\"\"Evaluate the model on the test set",
"t.set_postfix(collections.OrderedDict([ ('loss', '{:.2f} ({:.2f})'.format(loss, loss_meter.avg)), ('wps', '{:5d}'.format(round(wps_meter.avg))), ('wpb', '{:5d}'.format(round(wpb_meter.avg))), ('bsz',",
"in the LICENSE file in # the root directory of",
"{} examples'.format(args.data, split, len(dataset.splits[split]))) if not torch.cuda.is_available(): raise NotImplementedError('Training on",
"train_meter = StopwatchMeter() train_meter.start() while lr > args.min_lr and epoch",
"else None)) print('| Test on {} with beam={}: {}'.format(subset, beam,",
"dataset.dataloader(args.train_subset, batch_size=args.batch_size, test_batch_size=args.test_batch_size, valid_batch_size=args.valid_batch_size, num_workers=args.workers, max_tokens=args.max_tokens, seed=args.seed, epoch=epoch, max_positions=args.max_positions, sample_without_replacement=args.sample_without_replacement)",
"({:.2f})'.format(loss, loss_meter.avg)), ('wps', '{:5d}'.format(round(wps_meter.avg))), ('wpb', '{:5d}'.format(round(wpb_meter.avg))), ('bsz', '{:5d}'.format(round(bsz_meter.avg))), ('lr', lr),",
"subset, beam, cuda_device=(0 if num_gpus > 0 else None)) print('|",
"and (i + 1) % args.save_interval == 0: trainer.save_checkpoint(args, epoch,",
"{} types'.format(dataset.dst, len(dataset.dst_dict))) for split in dataset.splits: print('| {} {}",
"subset in args.test_subset.split(','): scorer = score_test(args, trainer.get_model(), dataset, subset, beam,",
"list ofdata subset ' 'to use for testing (train, valid,",
"def score_test(args, model, dataset, subset, beam, cuda_device): \"\"\"Evaluate the model",
"itr = dataset.dataloader(args.train_subset, batch_size=args.batch_size, test_batch_size=args.test_batch_size, valid_batch_size=args.valid_batch_size, num_workers=args.workers, max_tokens=args.max_tokens, seed=args.seed, epoch=epoch,",
"= False progress_bar.print_interval = args.log_interval if not os.path.exists(args.save_dir): os.makedirs(args.save_dir) torch.manual_seed(args.seed)",
"This source code is licensed under the license found in",
"i + 1) fmt = desc + ' | train",
"if torch.cuda.is_available(): translator.cuda() scorer = bleu.Scorer(dataset.dst_dict.pad(), dataset.dst_dict.eos(), dataset.dst_dict.unk()) itr =",
"options.add_checkpoint_args(parser) options.add_model_args(parser) args = utils.parse_args_and_arch(parser) print(args) if args.no_progress_bar: progress_bar.enabled =",
"leave=False) as t: for i, sample in data.skip_group_enumerator(t, num_gpus, batch_offset):",
"= bleu.Scorer(dataset.dst_dict.pad(), dataset.dst_dict.eos(), dataset.dst_dict.unk()) itr = dataset.dataloader(subset, batch_size=4, max_positions=args.max_positions) for",
"for one epoch train(args, epoch, batch_offset, trainer, criterion, dataset, num_gpus)",
"sum(s['src_tokens'].size(0) for s in sample) loss_meter.update(loss, ntokens) bsz_meter.update(src_size) wpb_meter.update(ntokens) wps_meter.update(ntokens)",
"dataset = data.load_with_check(args.data, args.source_lang, args.target_lang) if args.source_lang is None or",
"'| epoch {:03d} | valid on \\'{}\\' subset'.format(epoch, subset) with",
"# Stop multiprocessing trainer.stop() def train(args, epoch, batch_offset, trainer, criterion,",
"clip_meter.avg * 100, gnorm_meter.avg)) def validate(args, epoch, trainer, criterion, dataset,",
"epoch.\"\"\" itr = dataset.dataloader(args.train_subset, batch_size=args.batch_size, test_batch_size=args.test_batch_size, valid_batch_size=args.valid_batch_size, num_workers=args.workers, max_tokens=args.max_tokens, seed=args.seed,",
"epoch <= max_epoch: # train for one epoch train(args, epoch,",
"trainer, criterion, dataset, subset, num_gpus) if k == 0: if",
"'{:.2f} ({:.2f})'.format(loss, loss_meter.avg)), ('wps', '{:5d}'.format(round(wps_meter.avg))), ('wpb', '{:5d}'.format(round(wpb_meter.avg))), ('bsz', '{:5d}'.format(round(bsz_meter.avg))), ('lr',",
"sample in data.skip_group_enumerator(t, num_gpus, batch_offset): loss, grad_norm = trainer.train_step(sample, criterion)",
"size for validation set') dataset_args.add_argument('--train-subset', default='train', metavar='SPLIT', choices=['train', 'valid', 'test'],",
"args.max_epoch or math.inf lr = trainer.get_lr() train_meter = StopwatchMeter() train_meter.start()",
"print('| Test on {} with beam={}: {}'.format(subset, beam, scorer.result_string())) #",
"= None # Load dataset dataset = data.load_with_check(args.data, args.source_lang, args.target_lang)",
"valid_batch_size=args.valid_batch_size, num_workers=args.workers, max_tokens=args.max_tokens, seed=args.seed, epoch=epoch, max_positions=args.max_positions, sample_without_replacement=args.sample_without_replacement) loss_meter = AverageMeter()",
"norm desc = '| epoch {:03d}'.format(epoch) lr = trainer.get_lr() with",
"the latest checkpoint if one is available epoch, batch_offset =",
"None max_epoch = args.max_epoch or math.inf lr = trainer.get_lr() train_meter",
"with progress_bar(itr, desc, leave=False) as t: for _, sample in",
"{:6d}' fmt += ' | bsz {:5d} | lr {:0.6f}",
"t: for _, sample in data.skip_group_enumerator(t, ngpus): ntokens = sum(s['ntokens']",
"to infinity(same as setting to None) if args.max_tokens == 0:",
"number of tokens in a batch') dataset_args.add_argument('--batch-size', default=32, type=int, metavar='N',",
"under the license found in the LICENSE file in #",
"options.get_parser('Trainer') dataset_args = options.add_dataset_args(parser) dataset_args.add_argument('--max-tokens', default=0, type=int, metavar='N', help='maximum number",
"import bleu, data, options, utils from fairseq.meters import AverageMeter, StopwatchMeter,",
"Build model print('| model {}'.format(args.arch)) model = utils.build_model(args, dataset) criterion",
"ignore the first mini-batch in words-per-second calculation wps_meter.reset() if args.save_interval",
"dataset_args.add_argument('--test-batch-size', default=32, type=int, metavar='N', help='batch size for test set') dataset_args.add_argument('--valid-batch-size',",
"in the PATENTS file in the same directory. # import",
"dataset.dst_dict.unk()) itr = dataset.dataloader(subset, batch_size=4, max_positions=args.max_positions) for _, _, ref,",
"print('| {} {} {} examples'.format(args.data, split, len(dataset.splits[split]))) if not torch.cuda.is_available():",
"dataset.dst_dict, beam_size=beam) if torch.cuda.is_available(): translator.cuda() scorer = bleu.Scorer(dataset.dst_dict.pad(), dataset.dst_dict.eos(), dataset.dst_dict.unk())",
"is not supported') num_gpus = torch.cuda.device_count() print('| using {} GPUs",
"wps_meter.reset() if args.save_interval > 0 and (i + 1) %",
"utils.build_model(args, dataset) criterion = utils.build_criterion(args, dataset) # Start multiprocessing trainer",
"PATENTS file in the same directory. # import collections import",
"== 0: # ignore the first mini-batch in words-per-second calculation",
"| gnorm {:.4f}' t.write(fmt.format(loss_meter.avg, math.pow(2, loss_meter.avg), round(wps_meter.elapsed_time), round(wps_meter.avg), round(wpb_meter.avg), round(bsz_meter.avg),",
"multiprocessing trainer = MultiprocessingTrainer(args, model) # Load the latest checkpoint",
"nargs='+', metavar='PATH', help='path to external validation script (optional).') options.add_optimization_args(parser) options.add_checkpoint_args(parser)",
"only use first validation loss to update the learning schedule",
"dataset, num_gpus) # evaluate on validate set for k, subset",
"test_batch_size=args.test_batch_size, valid_batch_size=args.valid_batch_size, num_workers=args.workers, max_tokens=args.max_tokens, seed=args.seed, epoch=epoch, max_positions=args.max_positions, sample_without_replacement=args.sample_without_replacement) loss_meter =",
"print('| done training in {:.1f} seconds'.format(train_meter.sum)) # Generate on test",
"in checkpoints args.source_lang, args.target_lang = dataset.src, dataset.dst print('| [{}] dictionary:",
"loss.\"\"\" itr = dataset.dataloader(subset, batch_size=None, max_tokens=args.max_tokens, max_positions=args.max_positions) loss_meter = AverageMeter()",
"translator.generate_batched_itr(itr, cuda_device=cuda_device): scorer.add(ref.int().cpu(), hypos[0]['tokens'].int().cpu()) return scorer if __name__ == '__main__':",
"sample_without_replacement=args.sample_without_replacement) loss_meter = AverageMeter() bsz_meter = AverageMeter() # sentences per",
"| valid ppl {:3.2f}' .format(val_loss, math.pow(2, val_loss))) # update and",
"for split in dataset.splits: print('| {} {} {} examples'.format(args.data, split,",
"default=32, type=int, metavar='N', help='batch size for test set') dataset_args.add_argument('--valid-batch-size', default=32,",
"= AverageMeter() # % of updates clipped gnorm_meter = AverageMeter()",
"bsz_meter.update(src_size) wpb_meter.update(ntokens) wps_meter.update(ntokens) clip_meter.update(1 if grad_norm > args.clip_norm else 0)",
"dataset.splits: print('| {} {} {} examples'.format(args.data, split, len(dataset.splits[split]))) if not",
"training (train, valid, test)') dataset_args.add_argument('--valid-subset', default='valid', metavar='SPLIT', help='comma separated list",
"valid on \\'{}\\' subset'.format(epoch, subset) with progress_bar(itr, desc, leave=False) as",
"dataset_args.add_argument('--valid-script', nargs='+', metavar='PATH', help='path to external validation script (optional).') options.add_optimization_args(parser)",
"can be found in the PATENTS file in the same",
"dataset) criterion = utils.build_criterion(args, dataset) # Start multiprocessing trainer =",
"num_gpus = torch.cuda.device_count() print('| using {} GPUs (with max tokens",
"= {})'.format(num_gpus, args.max_tokens)) # Build model print('| model {}'.format(args.arch)) model",
"os.makedirs(args.save_dir) torch.manual_seed(args.seed) # Setting args.max_tokens to infinity(same as setting to",
"not supported') num_gpus = torch.cuda.device_count() print('| using {} GPUs (with",
"data.skip_group_enumerator(t, ngpus): ntokens = sum(s['ntokens'] for s in sample) loss",
"metavar='SPLIT', choices=['train', 'valid', 'test'], help='data subset to use for training",
"separated list ofdata subsets ' ' to use for validation",
"len(dataset.splits[split]))) if not torch.cuda.is_available(): raise NotImplementedError('Training on CPU is not",
"0 and (i + 1) % args.save_interval == 0: trainer.save_checkpoint(args,",
"dataset.dataloader(subset, batch_size=None, max_tokens=args.max_tokens, max_positions=args.max_positions) loss_meter = AverageMeter() desc = '|",
"t.write(fmt.format(loss_meter.avg, math.pow(2, loss_meter.avg), round(wps_meter.elapsed_time), round(wps_meter.avg), round(wpb_meter.avg), round(bsz_meter.avg), lr, clip_meter.avg *",
"for testing (train, valid, test)') dataset_args.add_argument('--valid-script', nargs='+', metavar='PATH', help='path to",
"too small val_loss = None max_epoch = args.max_epoch or math.inf",
"default=32, type=int, metavar='N', help='batch size') dataset_args.add_argument('--test-batch-size', default=32, type=int, metavar='N', help='batch",
"AverageMeter() # sentences per batch wpb_meter = AverageMeter() # words",
"{} types'.format(dataset.src, len(dataset.src_dict))) print('| [{}] dictionary: {} types'.format(dataset.dst, len(dataset.dst_dict))) for",
"is licensed under the license found in the LICENSE file",
"validate(args, epoch, trainer, criterion, dataset, subset, num_gpus) if k ==",
"[1, 5, 10, 20]: for subset in args.test_subset.split(','): scorer =",
"rate return val_loss def score_test(args, model, dataset, subset, beam, cuda_device):",
"Setting args.max_tokens to infinity(same as setting to None) if args.max_tokens",
"data.skip_group_enumerator(t, num_gpus, batch_offset): loss, grad_norm = trainer.train_step(sample, criterion) ntokens =",
"dataset.dst_dict.eos(), dataset.dst_dict.unk()) itr = dataset.dataloader(subset, batch_size=4, max_positions=args.max_positions) for _, _,",
"hypos in translator.generate_batched_itr(itr, cuda_device=cuda_device): scorer.add(ref.int().cpu(), hypos[0]['tokens'].int().cpu()) return scorer if __name__",
"additional grant of patent rights # can be found in",
"batch_offset, trainer, criterion, dataset, num_gpus): \"\"\"Train the model for one",
"def validate(args, epoch, trainer, criterion, dataset, subset, ngpus): \"\"\"Evaluate the",
"script (optional).') options.add_optimization_args(parser) options.add_checkpoint_args(parser) options.add_model_args(parser) args = utils.parse_args_and_arch(parser) print(args) if",
"= desc + ' | train loss {:2.2f} | train",
"All rights reserved. # # This source code is licensed",
"TimeMeter() # words per second clip_meter = AverageMeter() # %",
"'{:3.0f}%'.format(clip_meter.avg * 100)), ('gnorm', '{:.4f}'.format(gnorm_meter.avg)), ])) if i == 0:",
"model = utils.build_model(args, dataset) criterion = utils.build_criterion(args, dataset) # Start",
"subset'.format(epoch, subset) with progress_bar(itr, desc, leave=False) as t: for _,",
"until the learning rate gets too small val_loss = None",
"leave=False) as t: for _, sample in data.skip_group_enumerator(t, ngpus): ntokens",
"ntokens = sum(s['ntokens'] for s in sample) src_size = sum(s['src_tokens'].size(0)",
"learning rate gets too small val_loss = None max_epoch =",
"100, gnorm_meter.avg)) def validate(args, epoch, trainer, criterion, dataset, subset, ngpus):",
"[{}] dictionary: {} types'.format(dataset.dst, len(dataset.dst_dict))) for split in dataset.splits: print('|",
"fmt += ' | s/checkpoint {:7d} | words/s {:6d} |",
"of this source tree. An additional grant of patent rights",
"torch.cuda.is_available(): translator.cuda() scorer = bleu.Scorer(dataset.dst_dict.pad(), dataset.dst_dict.eos(), dataset.dst_dict.unk()) itr = dataset.dataloader(subset,",
"ref, hypos in translator.generate_batched_itr(itr, cuda_device=cuda_device): scorer.add(ref.int().cpu(), hypos[0]['tokens'].int().cpu()) return scorer if",
"args.save_interval > 0 and (i + 1) % args.save_interval ==",
"math.inf lr = trainer.get_lr() train_meter = StopwatchMeter() train_meter.start() while lr",
"AverageMeter() # % of updates clipped gnorm_meter = AverageMeter() #",
"rights reserved. # # This source code is licensed under",
"lr {:0.6f} | clip {:3.0f}% | gnorm {:.4f}' t.write(fmt.format(loss_meter.avg, math.pow(2,",
"subset, num_gpus) if k == 0: if not args.no_save: #",
"val_loss = None max_epoch = args.max_epoch or math.inf lr =",
"utils.parse_args_and_arch(parser) print(args) if args.no_progress_bar: progress_bar.enabled = False progress_bar.print_interval = args.log_interval",
"collections import os import torch import math from fairseq import",
"= sum(s['src_tokens'].size(0) for s in sample) loss_meter.update(loss, ntokens) bsz_meter.update(src_size) wpb_meter.update(ntokens)",
"validation_script=args.valid_script) # only use first validation loss to update the",
"schedule lr = trainer.lr_step(val_loss, epoch) epoch += 1 batch_offset =",
"valid1,test, test1)') dataset_args.add_argument('--test-subset', default='test', metavar='SPLIT', help='comma separated list ofdata subset",
"AverageMeter() bsz_meter = AverageMeter() # sentences per batch wpb_meter =",
"sample) loss = trainer.valid_step(sample, criterion) loss_meter.update(loss, ntokens) t.set_postfix(loss='{:.2f}'.format(loss_meter.avg)) val_loss =",
"Copyright (c) 2017-present, Facebook, Inc. # All rights reserved. #",
"math.pow(2, val_loss))) # update and return the learning rate return",
"it's saved in checkpoints args.source_lang, args.target_lang = dataset.src, dataset.dst print('|",
"args.log_interval if not os.path.exists(args.save_dir): os.makedirs(args.save_dir) torch.manual_seed(args.seed) # Setting args.max_tokens to",
"{:2.2f} | valid ppl {:3.2f}' .format(val_loss, math.pow(2, val_loss))) # update",
"batch wps_meter = TimeMeter() # words per second clip_meter =",
"in [1, 5, 10, 20]: for subset in args.test_subset.split(','): scorer",
"Test on {} with beam={}: {}'.format(subset, beam, scorer.result_string())) # Stop",
"checkpoint trainer.save_checkpoint(args, epoch, 0, val_loss, validation_script=args.valid_script) # only use first",
"# record inferred languages in args, so that it's saved",
"grad_norm = trainer.train_step(sample, criterion) ntokens = sum(s['ntokens'] for s in",
"('bsz', '{:5d}'.format(round(bsz_meter.avg))), ('lr', lr), ('clip', '{:3.0f}%'.format(clip_meter.avg * 100)), ('gnorm', '{:.4f}'.format(gnorm_meter.avg)),",
"while lr > args.min_lr and epoch <= max_epoch: # train",
"testing (train, valid, test)') dataset_args.add_argument('--valid-script', nargs='+', metavar='PATH', help='path to external",
"* 100)), ('gnorm', '{:.4f}'.format(gnorm_meter.avg)), ])) if i == 0: #",
"from fairseq import bleu, data, options, utils from fairseq.meters import",
"trainer.lr_step(val_loss, epoch) epoch += 1 batch_offset = 0 train_meter.stop() print('|",
"print('| model {}'.format(args.arch)) model = utils.build_model(args, dataset) criterion = utils.build_criterion(args,",
"of patent rights # can be found in the PATENTS",
"(optional).') options.add_optimization_args(parser) options.add_checkpoint_args(parser) options.add_model_args(parser) args = utils.parse_args_and_arch(parser) print(args) if args.no_progress_bar:",
"= dataset.dataloader(args.train_subset, batch_size=args.batch_size, test_batch_size=args.test_batch_size, valid_batch_size=args.valid_batch_size, num_workers=args.workers, max_tokens=args.max_tokens, seed=args.seed, epoch=epoch, max_positions=args.max_positions,",
"Facebook, Inc. # All rights reserved. # # This source",
"for i, sample in data.skip_group_enumerator(t, num_gpus, batch_offset): loss, grad_norm =",
"itr = dataset.dataloader(subset, batch_size=None, max_tokens=args.max_tokens, max_positions=args.max_positions) loss_meter = AverageMeter() desc",
"progress_bar(itr, desc, leave=False) as t: for i, sample in data.skip_group_enumerator(t,",
"gets too small val_loss = None max_epoch = args.max_epoch or",
"beam, cuda_device): \"\"\"Evaluate the model on the test set and",
"loss to update the learning schedule lr = trainer.lr_step(val_loss, epoch)",
"s in sample) loss_meter.update(loss, ntokens) bsz_meter.update(src_size) wpb_meter.update(ntokens) wps_meter.update(ntokens) clip_meter.update(1 if",
"{:2.2f} | train ppl {:3.2f}' fmt += ' | s/checkpoint",
"for validation (train, valid, valid1,test, test1)') dataset_args.add_argument('--test-subset', default='test', metavar='SPLIT', help='comma",
"= trainer.get_lr() train_meter = StopwatchMeter() train_meter.start() while lr > args.min_lr",
"{}'.format(args.arch)) model = utils.build_model(args, dataset) criterion = utils.build_criterion(args, dataset) #",
"len(dataset.src_dict))) print('| [{}] dictionary: {} types'.format(dataset.dst, len(dataset.dst_dict))) for split in",
"update and return the learning rate return val_loss def score_test(args,",
"of tokens in a batch') dataset_args.add_argument('--batch-size', default=32, type=int, metavar='N', help='batch",
"subset in enumerate(args.valid_subset.split(',')): val_loss = validate(args, epoch, trainer, criterion, dataset,",
"0: # ignore the first mini-batch in words-per-second calculation wps_meter.reset()",
"directory. # import collections import os import torch import math",
"round(wpb_meter.avg), round(bsz_meter.avg), lr, clip_meter.avg * 100, gnorm_meter.avg)) def validate(args, epoch,",
"criterion, dataset, subset, ngpus): \"\"\"Evaluate the model on the validation",
"on validate set for k, subset in enumerate(args.valid_subset.split(',')): val_loss =",
"criterion, dataset, num_gpus) # evaluate on validate set for k,",
"' 'to use for testing (train, valid, test)') dataset_args.add_argument('--valid-script', nargs='+',",
"return the BLEU scorer.\"\"\" translator = SequenceGenerator([model], dataset.dst_dict, beam_size=beam) if",
"if args.save_interval > 0 and (i + 1) % args.save_interval",
"use for validation (train, valid, valid1,test, test1)') dataset_args.add_argument('--test-subset', default='test', metavar='SPLIT',",
"model print('| model {}'.format(args.arch)) model = utils.build_model(args, dataset) criterion =",
"= args.log_interval if not os.path.exists(args.save_dir): os.makedirs(args.save_dir) torch.manual_seed(args.seed) # Setting args.max_tokens",
"progress_bar.enabled = False progress_bar.print_interval = args.log_interval if not os.path.exists(args.save_dir): os.makedirs(args.save_dir)",
"num_gpus, batch_offset): loss, grad_norm = trainer.train_step(sample, criterion) ntokens = sum(s['ntokens']",
"* 100, gnorm_meter.avg)) def validate(args, epoch, trainer, criterion, dataset, subset,",
"max_positions=args.max_positions) for _, _, ref, hypos in translator.generate_batched_itr(itr, cuda_device=cuda_device): scorer.add(ref.int().cpu(),",
"seed=args.seed, epoch=epoch, max_positions=args.max_positions, sample_without_replacement=args.sample_without_replacement) loss_meter = AverageMeter() bsz_meter = AverageMeter()",
"bleu, data, options, utils from fairseq.meters import AverageMeter, StopwatchMeter, TimeMeter",
"in enumerate(args.valid_subset.split(',')): val_loss = validate(args, epoch, trainer, criterion, dataset, subset,",
"> args.clip_norm else 0) gnorm_meter.update(grad_norm) t.set_postfix(collections.OrderedDict([ ('loss', '{:.2f} ({:.2f})'.format(loss, loss_meter.avg)),",
"import AverageMeter, StopwatchMeter, TimeMeter from fairseq.multiprocessing_trainer import MultiprocessingTrainer from fairseq.progress_bar",
"validation script (optional).') options.add_optimization_args(parser) options.add_checkpoint_args(parser) options.add_model_args(parser) args = utils.parse_args_and_arch(parser) print(args)",
"desc, leave=False) as t: for i, sample in data.skip_group_enumerator(t, num_gpus,",
"LICENSE file in # the root directory of this source",
"not args.no_save: # save checkpoint trainer.save_checkpoint(args, epoch, 0, val_loss, validation_script=args.valid_script)",
"from fairseq.meters import AverageMeter, StopwatchMeter, TimeMeter from fairseq.multiprocessing_trainer import MultiprocessingTrainer",
"args.max_tokens == 0: args.max_tokens = None # Load dataset dataset",
"trainer.get_model(), dataset, subset, beam, cuda_device=(0 if num_gpus > 0 else",
"in dataset.splits: print('| {} {} {} examples'.format(args.data, split, len(dataset.splits[split]))) if",
"t.write(desc + ' | valid loss {:2.2f} | valid ppl",
"ofdata subset ' 'to use for testing (train, valid, test)')",
"('loss', '{:.2f} ({:.2f})'.format(loss, loss_meter.avg)), ('wps', '{:5d}'.format(round(wps_meter.avg))), ('wpb', '{:5d}'.format(round(wpb_meter.avg))), ('bsz', '{:5d}'.format(round(bsz_meter.avg))),",
"in a batch') dataset_args.add_argument('--batch-size', default=32, type=int, metavar='N', help='batch size') dataset_args.add_argument('--test-batch-size',",
"val_loss))) # update and return the learning rate return val_loss",
"print('| using {} GPUs (with max tokens per GPU =",
"ntokens = sum(s['ntokens'] for s in sample) loss = trainer.valid_step(sample,",
"criterion) ntokens = sum(s['ntokens'] for s in sample) src_size =",
"args.test_subset.split(','): scorer = score_test(args, trainer.get_model(), dataset, subset, beam, cuda_device=(0 if",
"translator.cuda() scorer = bleu.Scorer(dataset.dst_dict.pad(), dataset.dst_dict.eos(), dataset.dst_dict.unk()) itr = dataset.dataloader(subset, batch_size=4,",
"mini-batch in words-per-second calculation wps_meter.reset() if args.save_interval > 0 and",
"])) if i == 0: # ignore the first mini-batch",
"loss = trainer.valid_step(sample, criterion) loss_meter.update(loss, ntokens) t.set_postfix(loss='{:.2f}'.format(loss_meter.avg)) val_loss = loss_meter.avg",
"AverageMeter() # words per batch wps_meter = TimeMeter() # words",
"os import torch import math from fairseq import bleu, data,",
"import math from fairseq import bleu, data, options, utils from",
"data, options, utils from fairseq.meters import AverageMeter, StopwatchMeter, TimeMeter from",
"dataset_args.add_argument('--max-tokens', default=0, type=int, metavar='N', help='maximum number of tokens in a",
"root directory of this source tree. An additional grant of",
"# Setting args.max_tokens to infinity(same as setting to None) if",
"'{:5d}'.format(round(wps_meter.avg))), ('wpb', '{:5d}'.format(round(wpb_meter.avg))), ('bsz', '{:5d}'.format(round(bsz_meter.avg))), ('lr', lr), ('clip', '{:3.0f}%'.format(clip_meter.avg *",
"' | s/checkpoint {:7d} | words/s {:6d} | words/batch {:6d}'",
"lr > args.min_lr and epoch <= max_epoch: # train for",
"types'.format(dataset.src, len(dataset.src_dict))) print('| [{}] dictionary: {} types'.format(dataset.dst, len(dataset.dst_dict))) for split",
"in sample) src_size = sum(s['src_tokens'].size(0) for s in sample) loss_meter.update(loss,",
"StopwatchMeter, TimeMeter from fairseq.multiprocessing_trainer import MultiprocessingTrainer from fairseq.progress_bar import progress_bar",
"list ofdata subsets ' ' to use for validation (train,",
"args.save_interval == 0: trainer.save_checkpoint(args, epoch, i + 1) fmt =",
"and epoch <= max_epoch: # train for one epoch train(args,",
"tokens per GPU = {})'.format(num_gpus, args.max_tokens)) # Build model print('|",
"scorer.result_string())) # Stop multiprocessing trainer.stop() def train(args, epoch, batch_offset, trainer,",
"dataset_args.add_argument('--train-subset', default='train', metavar='SPLIT', choices=['train', 'valid', 'test'], help='data subset to use",
"dataset dataset = data.load_with_check(args.data, args.source_lang, args.target_lang) if args.source_lang is None",
"num_gpus): \"\"\"Train the model for one epoch.\"\"\" itr = dataset.dataloader(args.train_subset,",
"<= max_epoch: # train for one epoch train(args, epoch, batch_offset,",
"max_positions=args.max_positions) loss_meter = AverageMeter() desc = '| epoch {:03d} |",
"wps_meter = TimeMeter() # words per second clip_meter = AverageMeter()",
"# can be found in the PATENTS file in the",
"None) if args.max_tokens == 0: args.max_tokens = None # Load",
"setting to None) if args.max_tokens == 0: args.max_tokens = None",
"default=32, type=int, metavar='N', help='batch size for validation set') dataset_args.add_argument('--train-subset', default='train',",
"dataset_args.add_argument('--valid-batch-size', default=32, type=int, metavar='N', help='batch size for validation set') dataset_args.add_argument('--train-subset',",
"+= ' | bsz {:5d} | lr {:0.6f} | clip",
"set') dataset_args.add_argument('--valid-batch-size', default=32, type=int, metavar='N', help='batch size for validation set')",
"record inferred languages in args, so that it's saved in",
"saved in checkpoints args.source_lang, args.target_lang = dataset.src, dataset.dst print('| [{}]",
"= AverageMeter() # words per batch wps_meter = TimeMeter() #",
"model) # Load the latest checkpoint if one is available",
"(i + 1) % args.save_interval == 0: trainer.save_checkpoint(args, epoch, i",
"loss {:2.2f} | train ppl {:3.2f}' fmt += ' |",
"loss_meter.avg t.write(desc + ' | valid loss {:2.2f} | valid",
"return the average loss.\"\"\" itr = dataset.dataloader(subset, batch_size=None, max_tokens=args.max_tokens, max_positions=args.max_positions)",
"if not torch.cuda.is_available(): raise NotImplementedError('Training on CPU is not supported')",
"with beam={}: {}'.format(subset, beam, scorer.result_string())) # Stop multiprocessing trainer.stop() def",
"subset to use for training (train, valid, test)') dataset_args.add_argument('--valid-subset', default='valid',",
"= StopwatchMeter() train_meter.start() while lr > args.min_lr and epoch <=",
"= trainer.lr_step(val_loss, epoch) epoch += 1 batch_offset = 0 train_meter.stop()",
"src_size = sum(s['src_tokens'].size(0) for s in sample) loss_meter.update(loss, ntokens) bsz_meter.update(src_size)",
"sample) src_size = sum(s['src_tokens'].size(0) for s in sample) loss_meter.update(loss, ntokens)",
"('gnorm', '{:.4f}'.format(gnorm_meter.avg)), ])) if i == 0: # ignore the",
"0 train_meter.stop() print('| done training in {:.1f} seconds'.format(train_meter.sum)) # Generate",
"if not os.path.exists(args.save_dir): os.makedirs(args.save_dir) torch.manual_seed(args.seed) # Setting args.max_tokens to infinity(same",
"per batch wps_meter = TimeMeter() # words per second clip_meter",
"# words per batch wps_meter = TimeMeter() # words per",
"train(args, epoch, batch_offset, trainer, criterion, dataset, num_gpus): \"\"\"Train the model",
"dataset.src, dataset.dst print('| [{}] dictionary: {} types'.format(dataset.src, len(dataset.src_dict))) print('| [{}]",
"lr = trainer.lr_step(val_loss, epoch) epoch += 1 batch_offset = 0",
"clip_meter = AverageMeter() # % of updates clipped gnorm_meter =",
"= dataset.dataloader(subset, batch_size=4, max_positions=args.max_positions) for _, _, ref, hypos in",
"source code is licensed under the license found in the",
"# update and return the learning rate return val_loss def",
"BLEU score for beam in [1, 5, 10, 20]: for",
"args.max_tokens = None # Load dataset dataset = data.load_with_check(args.data, args.source_lang,",
"i == 0: # ignore the first mini-batch in words-per-second",
"{:.1f} seconds'.format(train_meter.sum)) # Generate on test set and compute BLEU",
"as setting to None) if args.max_tokens == 0: args.max_tokens =",
"parser = options.get_parser('Trainer') dataset_args = options.add_dataset_args(parser) dataset_args.add_argument('--max-tokens', default=0, type=int, metavar='N',",
"model {}'.format(args.arch)) model = utils.build_model(args, dataset) criterion = utils.build_criterion(args, dataset)",
"to update the learning schedule lr = trainer.lr_step(val_loss, epoch) epoch",
"\"\"\"Train the model for one epoch.\"\"\" itr = dataset.dataloader(args.train_subset, batch_size=args.batch_size,",
"score_test(args, model, dataset, subset, beam, cuda_device): \"\"\"Evaluate the model on",
"num_gpus > 0 else None)) print('| Test on {} with",
"\\'{}\\' subset'.format(epoch, subset) with progress_bar(itr, desc, leave=False) as t: for",
"= None max_epoch = args.max_epoch or math.inf lr = trainer.get_lr()",
"metavar='N', help='batch size') dataset_args.add_argument('--test-batch-size', default=32, type=int, metavar='N', help='batch size for",
"100)), ('gnorm', '{:.4f}'.format(gnorm_meter.avg)), ])) if i == 0: # ignore",
"second clip_meter = AverageMeter() # % of updates clipped gnorm_meter",
"train_meter.start() while lr > args.min_lr and epoch <= max_epoch: #",
"dataset.dataloader(subset, batch_size=4, max_positions=args.max_positions) for _, _, ref, hypos in translator.generate_batched_itr(itr,",
"with progress_bar(itr, desc, leave=False) as t: for i, sample in",
"supported') num_gpus = torch.cuda.device_count() print('| using {} GPUs (with max",
"checkpoint if one is available epoch, batch_offset = trainer.load_checkpoint(os.path.join(args.save_dir, args.restore_file))",
"Train until the learning rate gets too small val_loss =",
"train ppl {:3.2f}' fmt += ' | s/checkpoint {:7d} |",
"the test set and return the BLEU scorer.\"\"\" translator =",
"desc + ' | train loss {:2.2f} | train ppl",
"languages in args, so that it's saved in checkpoints args.source_lang,",
"trainer, criterion, dataset, num_gpus) # evaluate on validate set for",
"max_epoch: # train for one epoch train(args, epoch, batch_offset, trainer,",
"= options.get_parser('Trainer') dataset_args = options.add_dataset_args(parser) dataset_args.add_argument('--max-tokens', default=0, type=int, metavar='N', help='maximum",
"if args.max_tokens == 0: args.max_tokens = None # Load dataset",
"' ' to use for validation (train, valid, valid1,test, test1)')",
"raise NotImplementedError('Training on CPU is not supported') num_gpus = torch.cuda.device_count()",
"clipped gnorm_meter = AverageMeter() # gradient norm desc = '|",
"gnorm_meter = AverageMeter() # gradient norm desc = '| epoch",
"args.target_lang) if args.source_lang is None or args.target_lang is None: #",
"= '| epoch {:03d}'.format(epoch) lr = trainer.get_lr() with progress_bar(itr, desc,",
"to external validation script (optional).') options.add_optimization_args(parser) options.add_checkpoint_args(parser) options.add_model_args(parser) args =",
"val_loss = validate(args, epoch, trainer, criterion, dataset, subset, num_gpus) if",
"latest checkpoint if one is available epoch, batch_offset = trainer.load_checkpoint(os.path.join(args.save_dir,",
"k, subset in enumerate(args.valid_subset.split(',')): val_loss = validate(args, epoch, trainer, criterion,",
"None)) print('| Test on {} with beam={}: {}'.format(subset, beam, scorer.result_string()))",
"{}'.format(subset, beam, scorer.result_string())) # Stop multiprocessing trainer.stop() def train(args, epoch,",
"import MultiprocessingTrainer from fairseq.progress_bar import progress_bar from fairseq.sequence_generator import SequenceGenerator",
"in translator.generate_batched_itr(itr, cuda_device=cuda_device): scorer.add(ref.int().cpu(), hypos[0]['tokens'].int().cpu()) return scorer if __name__ ==",
"trainer = MultiprocessingTrainer(args, model) # Load the latest checkpoint if",
"== 0: if not args.no_save: # save checkpoint trainer.save_checkpoint(args, epoch,",
"train(args, epoch, batch_offset, trainer, criterion, dataset, num_gpus) # evaluate on",
"None # Load dataset dataset = data.load_with_check(args.data, args.source_lang, args.target_lang) if",
"external validation script (optional).') options.add_optimization_args(parser) options.add_checkpoint_args(parser) options.add_model_args(parser) args = utils.parse_args_and_arch(parser)",
"10, 20]: for subset in args.test_subset.split(','): scorer = score_test(args, trainer.get_model(),",
"clip {:3.0f}% | gnorm {:.4f}' t.write(fmt.format(loss_meter.avg, math.pow(2, loss_meter.avg), round(wps_meter.elapsed_time), round(wps_meter.avg),",
"on the validation set and return the average loss.\"\"\" itr",
"def train(args, epoch, batch_offset, trainer, criterion, dataset, num_gpus): \"\"\"Train the",
"max tokens per GPU = {})'.format(num_gpus, args.max_tokens)) # Build model",
"' | valid loss {:2.2f} | valid ppl {:3.2f}' .format(val_loss,",
"if one is available epoch, batch_offset = trainer.load_checkpoint(os.path.join(args.save_dir, args.restore_file)) #",
"fairseq.progress_bar import progress_bar from fairseq.sequence_generator import SequenceGenerator def main(): parser",
"{:03d}'.format(epoch) lr = trainer.get_lr() with progress_bar(itr, desc, leave=False) as t:",
"ntokens) bsz_meter.update(src_size) wpb_meter.update(ntokens) wps_meter.update(ntokens) clip_meter.update(1 if grad_norm > args.clip_norm else",
"import torch import math from fairseq import bleu, data, options,",
"file in the same directory. # import collections import os",
"default=0, type=int, metavar='N', help='maximum number of tokens in a batch')",
"help='comma separated list ofdata subsets ' ' to use for",
"# train for one epoch train(args, epoch, batch_offset, trainer, criterion,",
"'{:.4f}'.format(gnorm_meter.avg)), ])) if i == 0: # ignore the first",
"ngpus): ntokens = sum(s['ntokens'] for s in sample) loss =",
"('lr', lr), ('clip', '{:3.0f}%'.format(clip_meter.avg * 100)), ('gnorm', '{:.4f}'.format(gnorm_meter.avg)), ])) if",
"import SequenceGenerator def main(): parser = options.get_parser('Trainer') dataset_args = options.add_dataset_args(parser)",
"in # the root directory of this source tree. An",
"loss_meter = AverageMeter() desc = '| epoch {:03d} | valid",
"epoch, batch_offset = trainer.load_checkpoint(os.path.join(args.save_dir, args.restore_file)) # Train until the learning",
"gnorm {:.4f}' t.write(fmt.format(loss_meter.avg, math.pow(2, loss_meter.avg), round(wps_meter.elapsed_time), round(wps_meter.avg), round(wpb_meter.avg), round(bsz_meter.avg), lr,",
"== 0: args.max_tokens = None # Load dataset dataset =",
"batch_size=args.batch_size, test_batch_size=args.test_batch_size, valid_batch_size=args.valid_batch_size, num_workers=args.workers, max_tokens=args.max_tokens, seed=args.seed, epoch=epoch, max_positions=args.max_positions, sample_without_replacement=args.sample_without_replacement) loss_meter",
"the learning schedule lr = trainer.lr_step(val_loss, epoch) epoch += 1",
"sum(s['ntokens'] for s in sample) loss = trainer.valid_step(sample, criterion) loss_meter.update(loss,",
"AverageMeter() desc = '| epoch {:03d} | valid on \\'{}\\'",
"{} GPUs (with max tokens per GPU = {})'.format(num_gpus, args.max_tokens))",
"source tree. An additional grant of patent rights # can",
"torch.manual_seed(args.seed) # Setting args.max_tokens to infinity(same as setting to None)",
"test)') dataset_args.add_argument('--valid-subset', default='valid', metavar='SPLIT', help='comma separated list ofdata subsets '",
"epoch=epoch, max_positions=args.max_positions, sample_without_replacement=args.sample_without_replacement) loss_meter = AverageMeter() bsz_meter = AverageMeter() #",
"if grad_norm > args.clip_norm else 0) gnorm_meter.update(grad_norm) t.set_postfix(collections.OrderedDict([ ('loss', '{:.2f}",
"# # This source code is licensed under the license",
"trainer, criterion, dataset, num_gpus): \"\"\"Train the model for one epoch.\"\"\"",
"words/batch {:6d}' fmt += ' | bsz {:5d} | lr",
"2017-present, Facebook, Inc. # All rights reserved. # # This",
"from fairseq.sequence_generator import SequenceGenerator def main(): parser = options.get_parser('Trainer') dataset_args",
"loss_meter.avg), round(wps_meter.elapsed_time), round(wps_meter.avg), round(wpb_meter.avg), round(bsz_meter.avg), lr, clip_meter.avg * 100, gnorm_meter.avg))",
"model, dataset, subset, beam, cuda_device): \"\"\"Evaluate the model on the",
"validation loss to update the learning schedule lr = trainer.lr_step(val_loss,",
"translator = SequenceGenerator([model], dataset.dst_dict, beam_size=beam) if torch.cuda.is_available(): translator.cuda() scorer =",
"= utils.parse_args_and_arch(parser) print(args) if args.no_progress_bar: progress_bar.enabled = False progress_bar.print_interval =",
"and return the learning rate return val_loss def score_test(args, model,",
"train loss {:2.2f} | train ppl {:3.2f}' fmt += '",
"epoch) epoch += 1 batch_offset = 0 train_meter.stop() print('| done",
"'valid', 'test'], help='data subset to use for training (train, valid,",
"dataset, subset, num_gpus) if k == 0: if not args.no_save:",
"the model for one epoch.\"\"\" itr = dataset.dataloader(args.train_subset, batch_size=args.batch_size, test_batch_size=args.test_batch_size,",
"'{:5d}'.format(round(bsz_meter.avg))), ('lr', lr), ('clip', '{:3.0f}%'.format(clip_meter.avg * 100)), ('gnorm', '{:.4f}'.format(gnorm_meter.avg)), ]))",
"1) % args.save_interval == 0: trainer.save_checkpoint(args, epoch, i + 1)",
"choices=['train', 'valid', 'test'], help='data subset to use for training (train,",
"args.source_lang, args.target_lang = dataset.src, dataset.dst print('| [{}] dictionary: {} types'.format(dataset.src,",
"set for k, subset in enumerate(args.valid_subset.split(',')): val_loss = validate(args, epoch,",
"dataset, subset, beam, cuda_device): \"\"\"Evaluate the model on the test",
"if k == 0: if not args.no_save: # save checkpoint",
"max_positions=args.max_positions, sample_without_replacement=args.sample_without_replacement) loss_meter = AverageMeter() bsz_meter = AverageMeter() # sentences",
"+ 1) % args.save_interval == 0: trainer.save_checkpoint(args, epoch, i +",
"' | bsz {:5d} | lr {:0.6f} | clip {:3.0f}%",
"is None or args.target_lang is None: # record inferred languages",
"ngpus): \"\"\"Evaluate the model on the validation set and return",
"(train, valid, test)') dataset_args.add_argument('--valid-subset', default='valid', metavar='SPLIT', help='comma separated list ofdata",
"rate gets too small val_loss = None max_epoch = args.max_epoch",
"Stop multiprocessing trainer.stop() def train(args, epoch, batch_offset, trainer, criterion, dataset,",
"= AverageMeter() # sentences per batch wpb_meter = AverageMeter() #",
"for s in sample) loss_meter.update(loss, ntokens) bsz_meter.update(src_size) wpb_meter.update(ntokens) wps_meter.update(ntokens) clip_meter.update(1",
"math from fairseq import bleu, data, options, utils from fairseq.meters",
"for subset in args.test_subset.split(','): scorer = score_test(args, trainer.get_model(), dataset, subset,",
"scorer = score_test(args, trainer.get_model(), dataset, subset, beam, cuda_device=(0 if num_gpus",
"lr = trainer.get_lr() with progress_bar(itr, desc, leave=False) as t: for",
"+= 1 batch_offset = 0 train_meter.stop() print('| done training in",
"utils from fairseq.meters import AverageMeter, StopwatchMeter, TimeMeter from fairseq.multiprocessing_trainer import",
"is available epoch, batch_offset = trainer.load_checkpoint(os.path.join(args.save_dir, args.restore_file)) # Train until",
"type=int, metavar='N', help='batch size for validation set') dataset_args.add_argument('--train-subset', default='train', metavar='SPLIT',",
"valid, test)') dataset_args.add_argument('--valid-subset', default='valid', metavar='SPLIT', help='comma separated list ofdata subsets",
"available epoch, batch_offset = trainer.load_checkpoint(os.path.join(args.save_dir, args.restore_file)) # Train until the",
"average loss.\"\"\" itr = dataset.dataloader(subset, batch_size=None, max_tokens=args.max_tokens, max_positions=args.max_positions) loss_meter =",
"for k, subset in enumerate(args.valid_subset.split(',')): val_loss = validate(args, epoch, trainer,",
"dataset.dst print('| [{}] dictionary: {} types'.format(dataset.src, len(dataset.src_dict))) print('| [{}] dictionary:",
"trainer.valid_step(sample, criterion) loss_meter.update(loss, ntokens) t.set_postfix(loss='{:.2f}'.format(loss_meter.avg)) val_loss = loss_meter.avg t.write(desc +",
"TimeMeter from fairseq.multiprocessing_trainer import MultiprocessingTrainer from fairseq.progress_bar import progress_bar from",
"default='train', metavar='SPLIT', choices=['train', 'valid', 'test'], help='data subset to use for",
"that it's saved in checkpoints args.source_lang, args.target_lang = dataset.src, dataset.dst",
"BLEU scorer.\"\"\" translator = SequenceGenerator([model], dataset.dst_dict, beam_size=beam) if torch.cuda.is_available(): translator.cuda()",
"metavar='N', help='batch size for validation set') dataset_args.add_argument('--train-subset', default='train', metavar='SPLIT', choices=['train',",
"fmt += ' | bsz {:5d} | lr {:0.6f} |",
"beam, cuda_device=(0 if num_gpus > 0 else None)) print('| Test",
"wps_meter.update(ntokens) clip_meter.update(1 if grad_norm > args.clip_norm else 0) gnorm_meter.update(grad_norm) t.set_postfix(collections.OrderedDict([",
"model for one epoch.\"\"\" itr = dataset.dataloader(args.train_subset, batch_size=args.batch_size, test_batch_size=args.test_batch_size, valid_batch_size=args.valid_batch_size,",
"= trainer.valid_step(sample, criterion) loss_meter.update(loss, ntokens) t.set_postfix(loss='{:.2f}'.format(loss_meter.avg)) val_loss = loss_meter.avg t.write(desc",
"the model on the validation set and return the average",
"| bsz {:5d} | lr {:0.6f} | clip {:3.0f}% |",
"StopwatchMeter() train_meter.start() while lr > args.min_lr and epoch <= max_epoch:",
"for one epoch.\"\"\" itr = dataset.dataloader(args.train_subset, batch_size=args.batch_size, test_batch_size=args.test_batch_size, valid_batch_size=args.valid_batch_size, num_workers=args.workers,",
"def main(): parser = options.get_parser('Trainer') dataset_args = options.add_dataset_args(parser) dataset_args.add_argument('--max-tokens', default=0,",
"'{:5d}'.format(round(wpb_meter.avg))), ('bsz', '{:5d}'.format(round(bsz_meter.avg))), ('lr', lr), ('clip', '{:3.0f}%'.format(clip_meter.avg * 100)), ('gnorm',",
"trainer.save_checkpoint(args, epoch, 0, val_loss, validation_script=args.valid_script) # only use first validation",
"Load the latest checkpoint if one is available epoch, batch_offset",
"import os import torch import math from fairseq import bleu,",
"subset, ngpus): \"\"\"Evaluate the model on the validation set and",
"ofdata subsets ' ' to use for validation (train, valid,",
"1 batch_offset = 0 train_meter.stop() print('| done training in {:.1f}",
"epoch {:03d} | valid on \\'{}\\' subset'.format(epoch, subset) with progress_bar(itr,",
"on \\'{}\\' subset'.format(epoch, subset) with progress_bar(itr, desc, leave=False) as t:",
"words per batch wps_meter = TimeMeter() # words per second",
"fairseq.sequence_generator import SequenceGenerator def main(): parser = options.get_parser('Trainer') dataset_args =",
"tree. An additional grant of patent rights # can be",
"split in dataset.splits: print('| {} {} {} examples'.format(args.data, split, len(dataset.splits[split])))",
"0) gnorm_meter.update(grad_norm) t.set_postfix(collections.OrderedDict([ ('loss', '{:.2f} ({:.2f})'.format(loss, loss_meter.avg)), ('wps', '{:5d}'.format(round(wps_meter.avg))), ('wpb',",
"test set') dataset_args.add_argument('--valid-batch-size', default=32, type=int, metavar='N', help='batch size for validation",
"help='batch size') dataset_args.add_argument('--test-batch-size', default=32, type=int, metavar='N', help='batch size for test",
"return the learning rate return val_loss def score_test(args, model, dataset,",
"args = utils.parse_args_and_arch(parser) print(args) if args.no_progress_bar: progress_bar.enabled = False progress_bar.print_interval",
"in args.test_subset.split(','): scorer = score_test(args, trainer.get_model(), dataset, subset, beam, cuda_device=(0",
"grant of patent rights # can be found in the",
"args.target_lang is None: # record inferred languages in args, so",
"criterion) loss_meter.update(loss, ntokens) t.set_postfix(loss='{:.2f}'.format(loss_meter.avg)) val_loss = loss_meter.avg t.write(desc + '",
"evaluate on validate set for k, subset in enumerate(args.valid_subset.split(',')): val_loss",
"wpb_meter = AverageMeter() # words per batch wps_meter = TimeMeter()",
"options.add_optimization_args(parser) options.add_checkpoint_args(parser) options.add_model_args(parser) args = utils.parse_args_and_arch(parser) print(args) if args.no_progress_bar: progress_bar.enabled",
"tokens in a batch') dataset_args.add_argument('--batch-size', default=32, type=int, metavar='N', help='batch size')",
"validate set for k, subset in enumerate(args.valid_subset.split(',')): val_loss = validate(args,",
"= 0 train_meter.stop() print('| done training in {:.1f} seconds'.format(train_meter.sum)) #",
"== 0: trainer.save_checkpoint(args, epoch, i + 1) fmt = desc",
"s in sample) loss = trainer.valid_step(sample, criterion) loss_meter.update(loss, ntokens) t.set_postfix(loss='{:.2f}'.format(loss_meter.avg))",
"criterion = utils.build_criterion(args, dataset) # Start multiprocessing trainer = MultiprocessingTrainer(args,",
"dataset, subset, ngpus): \"\"\"Evaluate the model on the validation set",
"NotImplementedError('Training on CPU is not supported') num_gpus = torch.cuda.device_count() print('|",
"validation (train, valid, valid1,test, test1)') dataset_args.add_argument('--test-subset', default='test', metavar='SPLIT', help='comma separated",
"utils.build_criterion(args, dataset) # Start multiprocessing trainer = MultiprocessingTrainer(args, model) #",
"| train ppl {:3.2f}' fmt += ' | s/checkpoint {:7d}",
"default='valid', metavar='SPLIT', help='comma separated list ofdata subsets ' ' to",
"Start multiprocessing trainer = MultiprocessingTrainer(args, model) # Load the latest",
"= sum(s['ntokens'] for s in sample) src_size = sum(s['src_tokens'].size(0) for",
"= score_test(args, trainer.get_model(), dataset, subset, beam, cuda_device=(0 if num_gpus >",
"clip_meter.update(1 if grad_norm > args.clip_norm else 0) gnorm_meter.update(grad_norm) t.set_postfix(collections.OrderedDict([ ('loss',",
"validation set and return the average loss.\"\"\" itr = dataset.dataloader(subset,",
"trainer.get_lr() train_meter = StopwatchMeter() train_meter.start() while lr > args.min_lr and",
"for s in sample) src_size = sum(s['src_tokens'].size(0) for s in",
"metavar='SPLIT', help='comma separated list ofdata subsets ' ' to use",
"progress_bar from fairseq.sequence_generator import SequenceGenerator def main(): parser = options.get_parser('Trainer')",
"# Load dataset dataset = data.load_with_check(args.data, args.source_lang, args.target_lang) if args.source_lang",
"subset) with progress_bar(itr, desc, leave=False) as t: for _, sample",
"num_gpus) # evaluate on validate set for k, subset in",
"for _, sample in data.skip_group_enumerator(t, ngpus): ntokens = sum(s['ntokens'] for",
"# Copyright (c) 2017-present, Facebook, Inc. # All rights reserved.",
"metavar='N', help='maximum number of tokens in a batch') dataset_args.add_argument('--batch-size', default=32,",
"loss {:2.2f} | valid ppl {:3.2f}' .format(val_loss, math.pow(2, val_loss))) #",
"import progress_bar from fairseq.sequence_generator import SequenceGenerator def main(): parser =",
"None or args.target_lang is None: # record inferred languages in",
"criterion, dataset, num_gpus): \"\"\"Train the model for one epoch.\"\"\" itr",
"= args.max_epoch or math.inf lr = trainer.get_lr() train_meter = StopwatchMeter()",
"the same directory. # import collections import os import torch",
"loss_meter.update(loss, ntokens) t.set_postfix(loss='{:.2f}'.format(loss_meter.avg)) val_loss = loss_meter.avg t.write(desc + ' |",
"0: if not args.no_save: # save checkpoint trainer.save_checkpoint(args, epoch, 0,",
"False progress_bar.print_interval = args.log_interval if not os.path.exists(args.save_dir): os.makedirs(args.save_dir) torch.manual_seed(args.seed) #",
"{} with beam={}: {}'.format(subset, beam, scorer.result_string())) # Stop multiprocessing trainer.stop()",
"val_loss, validation_script=args.valid_script) # only use first validation loss to update",
"epoch, trainer, criterion, dataset, subset, ngpus): \"\"\"Evaluate the model on",
"= sum(s['ntokens'] for s in sample) loss = trainer.valid_step(sample, criterion)",
"| words/s {:6d} | words/batch {:6d}' fmt += ' |",
"os.path.exists(args.save_dir): os.makedirs(args.save_dir) torch.manual_seed(args.seed) # Setting args.max_tokens to infinity(same as setting",
"args.max_tokens)) # Build model print('| model {}'.format(args.arch)) model = utils.build_model(args,",
"beam, scorer.result_string())) # Stop multiprocessing trainer.stop() def train(args, epoch, batch_offset,",
"progress_bar(itr, desc, leave=False) as t: for _, sample in data.skip_group_enumerator(t,",
"bsz {:5d} | lr {:0.6f} | clip {:3.0f}% | gnorm",
"# save checkpoint trainer.save_checkpoint(args, epoch, 0, val_loss, validation_script=args.valid_script) # only",
"None: # record inferred languages in args, so that it's",
"train for one epoch train(args, epoch, batch_offset, trainer, criterion, dataset,",
"the first mini-batch in words-per-second calculation wps_meter.reset() if args.save_interval >",
"batch') dataset_args.add_argument('--batch-size', default=32, type=int, metavar='N', help='batch size') dataset_args.add_argument('--test-batch-size', default=32, type=int,",
"round(bsz_meter.avg), lr, clip_meter.avg * 100, gnorm_meter.avg)) def validate(args, epoch, trainer,",
"args.no_progress_bar: progress_bar.enabled = False progress_bar.print_interval = args.log_interval if not os.path.exists(args.save_dir):",
"# This source code is licensed under the license found",
"# only use first validation loss to update the learning",
"torch.cuda.device_count() print('| using {} GPUs (with max tokens per GPU",
"model on the validation set and return the average loss.\"\"\"",
"done training in {:.1f} seconds'.format(train_meter.sum)) # Generate on test set",
"lr), ('clip', '{:3.0f}%'.format(clip_meter.avg * 100)), ('gnorm', '{:.4f}'.format(gnorm_meter.avg)), ])) if i",
"trainer.save_checkpoint(args, epoch, i + 1) fmt = desc + '",
"1) fmt = desc + ' | train loss {:2.2f}",
"args.target_lang = dataset.src, dataset.dst print('| [{}] dictionary: {} types'.format(dataset.src, len(dataset.src_dict)))",
"help='batch size for test set') dataset_args.add_argument('--valid-batch-size', default=32, type=int, metavar='N', help='batch",
"examples'.format(args.data, split, len(dataset.splits[split]))) if not torch.cuda.is_available(): raise NotImplementedError('Training on CPU",
"import collections import os import torch import math from fairseq",
"print('| [{}] dictionary: {} types'.format(dataset.src, len(dataset.src_dict))) print('| [{}] dictionary: {}",
"gnorm_meter.update(grad_norm) t.set_postfix(collections.OrderedDict([ ('loss', '{:.2f} ({:.2f})'.format(loss, loss_meter.avg)), ('wps', '{:5d}'.format(round(wps_meter.avg))), ('wpb', '{:5d}'.format(round(wpb_meter.avg))),",
"max_tokens=args.max_tokens, seed=args.seed, epoch=epoch, max_positions=args.max_positions, sample_without_replacement=args.sample_without_replacement) loss_meter = AverageMeter() bsz_meter =",
"per second clip_meter = AverageMeter() # % of updates clipped",
"args.min_lr and epoch <= max_epoch: # train for one epoch",
"round(wps_meter.elapsed_time), round(wps_meter.avg), round(wpb_meter.avg), round(bsz_meter.avg), lr, clip_meter.avg * 100, gnorm_meter.avg)) def",
"valid ppl {:3.2f}' .format(val_loss, math.pow(2, val_loss))) # update and return",
"bleu.Scorer(dataset.dst_dict.pad(), dataset.dst_dict.eos(), dataset.dst_dict.unk()) itr = dataset.dataloader(subset, batch_size=4, max_positions=args.max_positions) for _,",
"GPUs (with max tokens per GPU = {})'.format(num_gpus, args.max_tokens)) #",
"per batch wpb_meter = AverageMeter() # words per batch wps_meter",
"('wpb', '{:5d}'.format(round(wpb_meter.avg))), ('bsz', '{:5d}'.format(round(bsz_meter.avg))), ('lr', lr), ('clip', '{:3.0f}%'.format(clip_meter.avg * 100)),",
"the learning rate gets too small val_loss = None max_epoch",
"> 0 and (i + 1) % args.save_interval == 0:",
"to use for validation (train, valid, valid1,test, test1)') dataset_args.add_argument('--test-subset', default='test',",
"a batch') dataset_args.add_argument('--batch-size', default=32, type=int, metavar='N', help='batch size') dataset_args.add_argument('--test-batch-size', default=32,",
"batch_offset): loss, grad_norm = trainer.train_step(sample, criterion) ntokens = sum(s['ntokens'] for",
"SequenceGenerator def main(): parser = options.get_parser('Trainer') dataset_args = options.add_dataset_args(parser) dataset_args.add_argument('--max-tokens',",
"{:3.2f}' fmt += ' | s/checkpoint {:7d} | words/s {:6d}",
"args.source_lang is None or args.target_lang is None: # record inferred",
"if args.source_lang is None or args.target_lang is None: # record",
"train_meter.stop() print('| done training in {:.1f} seconds'.format(train_meter.sum)) # Generate on",
"{:03d} | valid on \\'{}\\' subset'.format(epoch, subset) with progress_bar(itr, desc,",
"torch.cuda.is_available(): raise NotImplementedError('Training on CPU is not supported') num_gpus =",
"= trainer.train_step(sample, criterion) ntokens = sum(s['ntokens'] for s in sample)",
"or args.target_lang is None: # record inferred languages in args,",
"return val_loss def score_test(args, model, dataset, subset, beam, cuda_device): \"\"\"Evaluate",
"if num_gpus > 0 else None)) print('| Test on {}",
"license found in the LICENSE file in # the root",
"(c) 2017-present, Facebook, Inc. # All rights reserved. # #",
"k == 0: if not args.no_save: # save checkpoint trainer.save_checkpoint(args,",
"bsz_meter = AverageMeter() # sentences per batch wpb_meter = AverageMeter()",
"validation set') dataset_args.add_argument('--train-subset', default='train', metavar='SPLIT', choices=['train', 'valid', 'test'], help='data subset",
"= dataset.src, dataset.dst print('| [{}] dictionary: {} types'.format(dataset.src, len(dataset.src_dict))) print('|",
"# Start multiprocessing trainer = MultiprocessingTrainer(args, model) # Load the",
"in {:.1f} seconds'.format(train_meter.sum)) # Generate on test set and compute",
"test1)') dataset_args.add_argument('--test-subset', default='test', metavar='SPLIT', help='comma separated list ofdata subset '",
"# Train until the learning rate gets too small val_loss",
"beam={}: {}'.format(subset, beam, scorer.result_string())) # Stop multiprocessing trainer.stop() def train(args,",
"dataset, subset, beam, cuda_device=(0 if num_gpus > 0 else None))",
"for _, _, ref, hypos in translator.generate_batched_itr(itr, cuda_device=cuda_device): scorer.add(ref.int().cpu(), hypos[0]['tokens'].int().cpu())",
"= torch.cuda.device_count() print('| using {} GPUs (with max tokens per",
"gradient norm desc = '| epoch {:03d}'.format(epoch) lr = trainer.get_lr()",
"fmt = desc + ' | train loss {:2.2f} |",
"per GPU = {})'.format(num_gpus, args.max_tokens)) # Build model print('| model",
"s in sample) src_size = sum(s['src_tokens'].size(0) for s in sample)",
"= trainer.get_lr() with progress_bar(itr, desc, leave=False) as t: for i,",
"# ignore the first mini-batch in words-per-second calculation wps_meter.reset() if",
"one epoch.\"\"\" itr = dataset.dataloader(args.train_subset, batch_size=args.batch_size, test_batch_size=args.test_batch_size, valid_batch_size=args.valid_batch_size, num_workers=args.workers, max_tokens=args.max_tokens,",
"sample) loss_meter.update(loss, ntokens) bsz_meter.update(src_size) wpb_meter.update(ntokens) wps_meter.update(ntokens) clip_meter.update(1 if grad_norm >",
"itr = dataset.dataloader(subset, batch_size=4, max_positions=args.max_positions) for _, _, ref, hypos",
"fairseq import bleu, data, options, utils from fairseq.meters import AverageMeter,",
"the average loss.\"\"\" itr = dataset.dataloader(subset, batch_size=None, max_tokens=args.max_tokens, max_positions=args.max_positions) loss_meter",
"separated list ofdata subset ' 'to use for testing (train,",
"small val_loss = None max_epoch = args.max_epoch or math.inf lr",
"{:0.6f} | clip {:3.0f}% | gnorm {:.4f}' t.write(fmt.format(loss_meter.avg, math.pow(2, loss_meter.avg),",
"dataset_args.add_argument('--test-subset', default='test', metavar='SPLIT', help='comma separated list ofdata subset ' 'to",
"for beam in [1, 5, 10, 20]: for subset in",
"= SequenceGenerator([model], dataset.dst_dict, beam_size=beam) if torch.cuda.is_available(): translator.cuda() scorer = bleu.Scorer(dataset.dst_dict.pad(),",
"be found in the PATENTS file in the same directory.",
"i, sample in data.skip_group_enumerator(t, num_gpus, batch_offset): loss, grad_norm = trainer.train_step(sample,",
"= loss_meter.avg t.write(desc + ' | valid loss {:2.2f} |",
"trainer.load_checkpoint(os.path.join(args.save_dir, args.restore_file)) # Train until the learning rate gets too",
"round(wps_meter.avg), round(wpb_meter.avg), round(bsz_meter.avg), lr, clip_meter.avg * 100, gnorm_meter.avg)) def validate(args,",
"ppl {:3.2f}' .format(val_loss, math.pow(2, val_loss))) # update and return the",
"metavar='N', help='batch size for test set') dataset_args.add_argument('--valid-batch-size', default=32, type=int, metavar='N',",
"dataset) # Start multiprocessing trainer = MultiprocessingTrainer(args, model) # Load",
"20]: for subset in args.test_subset.split(','): scorer = score_test(args, trainer.get_model(), dataset,",
"update the learning schedule lr = trainer.lr_step(val_loss, epoch) epoch +=",
"# Load the latest checkpoint if one is available epoch,",
"in args, so that it's saved in checkpoints args.source_lang, args.target_lang",
"wpb_meter.update(ntokens) wps_meter.update(ntokens) clip_meter.update(1 if grad_norm > args.clip_norm else 0) gnorm_meter.update(grad_norm)",
"in the same directory. # import collections import os import",
"on test set and compute BLEU score for beam in",
"the BLEU scorer.\"\"\" translator = SequenceGenerator([model], dataset.dst_dict, beam_size=beam) if torch.cuda.is_available():",
".format(val_loss, math.pow(2, val_loss))) # update and return the learning rate",
"0 else None)) print('| Test on {} with beam={}: {}'.format(subset,",
"0: args.max_tokens = None # Load dataset dataset = data.load_with_check(args.data,",
"score_test(args, trainer.get_model(), dataset, subset, beam, cuda_device=(0 if num_gpus > 0",
"{:7d} | words/s {:6d} | words/batch {:6d}' fmt += '",
"{:3.2f}' .format(val_loss, math.pow(2, val_loss))) # update and return the learning",
"= TimeMeter() # words per second clip_meter = AverageMeter() #",
"the license found in the LICENSE file in # the",
"= AverageMeter() desc = '| epoch {:03d} | valid on",
"first validation loss to update the learning schedule lr =",
"num_workers=args.workers, max_tokens=args.max_tokens, seed=args.seed, epoch=epoch, max_positions=args.max_positions, sample_without_replacement=args.sample_without_replacement) loss_meter = AverageMeter() bsz_meter",
"= AverageMeter() # gradient norm desc = '| epoch {:03d}'.format(epoch)",
"options.add_dataset_args(parser) dataset_args.add_argument('--max-tokens', default=0, type=int, metavar='N', help='maximum number of tokens in",
"= utils.build_criterion(args, dataset) # Start multiprocessing trainer = MultiprocessingTrainer(args, model)",
"# the root directory of this source tree. An additional",
"+ 1) fmt = desc + ' | train loss",
"reserved. # # This source code is licensed under the",
"epoch, trainer, criterion, dataset, subset, num_gpus) if k == 0:",
"so that it's saved in checkpoints args.source_lang, args.target_lang = dataset.src,",
"use for testing (train, valid, test)') dataset_args.add_argument('--valid-script', nargs='+', metavar='PATH', help='path",
"t.set_postfix(loss='{:.2f}'.format(loss_meter.avg)) val_loss = loss_meter.avg t.write(desc + ' | valid loss"
] |
[
"msg in getIterable(messages): if isinstance(msg, list): for elt in msg:",
"one or more message objects per message type. \"\"\" return",
"getIterable(messages): if isinstance(msg, list): for elt in msg: accum_time +=",
"raise Exception(\"Unknown type '\" + str(type(dict_or_list)) + \"'\") return iterable",
"accum_time = 0 for msg in getIterable(messages): if isinstance(msg, list):",
"not os.path.exists(fname): print(fname, \"not found.\") continue with open(fname) as fp:",
"x : x.getSource(), messages) def groupByX(grp_fn, messages): \"\"\" Returns a",
"- self.temp).total_seconds() self.temp = t_time def getIterable(dict_or_list): \"\"\" Returns an",
"'%Y-%m-%d %H:%M:%S,%f' class Message(object): \"\"\" Storage for the timing of",
"msg.isComplete(): temp[m_id] = msg return temp else: return messages def",
"processed. elif (command.startswith(\"processed,\")): m_id = command.split(\",\")[1] messages[m_id].processed(time) elif (command.startswith(\"worker done,\")):",
"ignore_incomplete: temp = {} for m_id in messages: msg =",
"and call frequency information for HAL messages. Hazen 5/18 \"\"\"",
"process in seconds. \"\"\" return self.processing_time def getQueuedTime(self): \"\"\" Return",
"queued time for a a collection of messages. \"\"\" accum_time",
"for m_id in messages: msg = messages[m_id] if msg.isComplete(): temp[m_id]",
"\"\"\" Returns an iterable given a dictionary of a list.",
"zero_time) # Message sent. elif (command.startswith(\"sent,\")): m_id = command.split(\",\")[1] messages[m_id].sent(time)",
"= msg return temp else: return messages def processingTime(messages): \"\"\"",
"self.created(zero_time) def created(self, time): t_time = self.parseTime(time) self.created_time = (self.temp",
"def processingTime(messages): \"\"\" Returns the total processing time for a",
"source = None, time = None, zero_time = None, **kwds):",
"for this message. \"\"\" return (self.processing_time != None) def parseTime(self,",
"= (self.temp - t_time).total_seconds() def getCreatedTime(self): \"\"\" Returns the time",
"= basename + \".out\" + ext if not os.path.exists(fname): print(fname,",
"{} for msg in getIterable(messages): # Ignore messages that we",
"type '\" + str(type(dict_or_list)) + \"'\") return iterable def groupByMsgType(messages):",
"elif (command.startswith(\"processed,\")): m_id = command.split(\",\")[1] messages[m_id].processed(time) elif (command.startswith(\"worker done,\")): m_id",
"t_time = self.parseTime(time) self.processing_time = (t_time - self.temp).total_seconds() def sent(self,",
"groupByMsgType(messages) print() print(\"All messages:\") for key in sorted(groups): grp =",
"this message. \"\"\" return (self.processing_time != None) def parseTime(self, time):",
"logTiming(basename, ignore_incomplete = False): \"\"\" Returns a dictionary of Message",
"Returns a dictionary keyed by the requested group. \"\"\" m_grp",
"the message was created relative to first time in the",
"This parses a log file series (i.e. log, log.1, log.2,",
"timing of a single message. \"\"\" def __init__(self, m_type =",
"messages. Hazen 5/18 \"\"\" from datetime import datetime import os",
"m_type, source = source, time = time, zero_time = zero_time)",
"messages def processingTime(messages): \"\"\" Returns the total processing time for",
"+= elt.getQueuedTime() else: accum_time += msg.getQueuedTime() return accum_time if (__name__",
"list. \"\"\" if isinstance(dict_or_list, dict): iterable = list(dict_or_list.values()) elif isinstance(dict_or_list,",
"by message source, with a list of one or more",
"queued. if (command.startswith(\"queued,\")): [m_id, source, m_type] = command.split(\",\")[1:] messages[m_id] =",
"message. \"\"\" return self.source def getType(self): \"\"\" Return the message",
"= self.parseTime(time) self.queued_time = (t_time - self.temp).total_seconds() self.temp = t_time",
"t_time).total_seconds() def getCreatedTime(self): \"\"\" Returns the time when the message",
"datetime.strptime(time, pattern) def processed(self, time): t_time = self.parseTime(time) self.processing_time =",
"def getType(self): \"\"\" Return the message type. \"\"\" return self.m_type",
"employed to process this message. \"\"\" return self.n_workers def getProcessingTime(self):",
"time in the log file in seconds. \"\"\" return self.created_time",
"\"\"\" return self.m_type def incNWorkers(self): self.n_workers += 1 def isComplete(self):",
"= groupByMsgType(messages) print() print(\"All messages:\") for key in sorted(groups): grp",
"zero_time = time # Message queued. if (command.startswith(\"queued,\")): [m_id, source,",
"self.queued_time def getSource(self): \"\"\" Returns the source of a message.",
"collection of messages. \"\"\" accum_time = 0 for msg in",
"source of a message. \"\"\" return self.source def getType(self): \"\"\"",
"of workers (QRunnables) that were employed to process this message.",
"= groups[key] print(key + \", {0:0d} counts, {1:.3f} seconds\".format(len(grp), processingTime(grp)))",
"= time, zero_time = zero_time) # Message sent. elif (command.startswith(\"sent,\")):",
"1 def isComplete(self): \"\"\" Returns true if we have all",
"class Message(object): \"\"\" Storage for the timing of a single",
"counts, {1:.3f} seconds\".format(len(grp), processingTime(grp))) print(\"Total queued time {0:.3f} seconds\".format(queuedTime(groups))) print(\"Total",
"time queued in seconds. \"\"\" return self.queued_time def getSource(self): \"\"\"",
"def created(self, time): t_time = self.parseTime(time) self.created_time = (self.temp -",
"a list of one or more message objects per message",
"have all the timing data for this message. \"\"\" return",
"m_grp def logTiming(basename, ignore_incomplete = False): \"\"\" Returns a dictionary",
"if isinstance(msg, list): for elt in msg: accum_time += elt.getProcessingTime()",
"timing data for this message. \"\"\" return (self.processing_time != None)",
"sent(self, time): t_time = self.parseTime(time) self.queued_time = (t_time - self.temp).total_seconds()",
"for msg in getIterable(messages): if isinstance(msg, list): for elt in",
"# Message sent. elif (command.startswith(\"sent,\")): m_id = command.split(\",\")[1] messages[m_id].sent(time) #",
"Ignore messages that we don't have all the timing for.",
"= command.split(\",\")[1:] messages[m_id] = Message(m_type = m_type, source = source,",
"m_type] = command.split(\",\")[1:] messages[m_id] = Message(m_type = m_type, source =",
"number of workers (QRunnables) that were employed to process this",
"seconds. \"\"\" return self.queued_time def getSource(self): \"\"\" Returns the source",
"the total queued time for a a collection of messages.",
"time = None, zero_time = None, **kwds): super().__init__(**kwds) self.created_time =",
"\".2\", \".1\", \"\"]: fname = basename + \".out\" + ext",
"= command.split(\",\")[1] messages[m_id].processed(time) elif (command.startswith(\"worker done,\")): m_id = command.split(\",\")[1] messages[m_id].incNWorkers()",
"__init__(self, m_type = None, source = None, time = None,",
"!= None) def parseTime(self, time): return datetime.strptime(time, pattern) def processed(self,",
"in [\".5\", \".4\", \".3\", \".2\", \".1\", \"\"]: fname = basename",
"zero_time is None: zero_time = time # Message queued. if",
"os.path.exists(fname): print(fname, \"not found.\") continue with open(fname) as fp: for",
"accum_time if (__name__ == \"__main__\"): import sys if (len(sys.argv) !=",
"message. \"\"\" return (self.processing_time != None) def parseTime(self, time): return",
"groupByX(lambda x : x.getSource(), messages) def groupByX(grp_fn, messages): \"\"\" Returns",
"processing time {0:.3f} seconds\".format(processingTime(groups))) print() print(\"Film messages:\") groups = groupByMsgType(groupBySource(messages)[\"film\"])",
"x : x.getType(), messages) def groupBySource(messages): \"\"\" Returns a dictionary",
"sent. elif (command.startswith(\"sent,\")): m_id = command.split(\",\")[1] messages[m_id].sent(time) # Message processed.",
"of a message. \"\"\" return self.source def getType(self): \"\"\" Return",
"a log file series (i.e. log, log.1, log.2, etc..) and",
"msg.getProcessingTime() return accum_time def queuedTime(messages): \"\"\" Returns the total queued",
"by the requested group. \"\"\" m_grp = {} for msg",
"isComplete(self): \"\"\" Returns true if we have all the timing",
"msg: accum_time += elt.getProcessingTime() else: accum_time += msg.getProcessingTime() return accum_time",
"self.processing_time = None self.queued_time = None self.source = source self.temp",
"log file in seconds. \"\"\" return self.created_time def getNWorkers(self): \"\"\"",
"except ValueError: continue if zero_time is None: zero_time = time",
"super().__init__(**kwds) self.created_time = None self.m_type = m_type self.n_workers = 0",
"have all the timing for. if not ignore_incomplete: temp =",
"# Message processed. elif (command.startswith(\"processed,\")): m_id = command.split(\",\")[1] messages[m_id].processed(time) elif",
"keyed by message type, with a list of one or",
"else: return messages def processingTime(messages): \"\"\" Returns the total processing",
"for msg in getIterable(messages): # Ignore messages that we don't",
"isinstance(dict_or_list, list): iterable = dict_or_list else: raise Exception(\"Unknown type '\"",
"for. if not ignore_incomplete: temp = {} for m_id in",
"\"\"\" Returns a dictionary keyed by message source, with a",
"self.temp).total_seconds() self.temp = t_time def getIterable(dict_or_list): \"\"\" Returns an iterable",
"accum_time += elt.getQueuedTime() else: accum_time += msg.getQueuedTime() return accum_time if",
"m_type = None, source = None, time = None, zero_time",
"time when the message was created relative to first time",
"Returns a dictionary keyed by message source, with a list",
"print(fname, \"not found.\") continue with open(fname) as fp: for line",
"total processing time for a collection of messages. \"\"\" accum_time",
"file series (i.e. log, log.1, log.2, etc..) and outputs timing",
"all the timing data for this message. \"\"\" return (self.processing_time",
"msg return temp else: return messages def processingTime(messages): \"\"\" Returns",
"have all the timing for. if msg.isComplete() or not ignore_incomplete:",
"print(\"All messages:\") for key in sorted(groups): grp = groups[key] print(key",
"message. \"\"\" return self.n_workers def getProcessingTime(self): \"\"\" Return time to",
"self.parseTime(time) self.processing_time = (t_time - self.temp).total_seconds() def sent(self, time): t_time",
"def getSource(self): \"\"\" Returns the source of a message. \"\"\"",
"we don't have all the timing for. if not ignore_incomplete:",
"in getIterable(messages): if isinstance(msg, list): for elt in msg: accum_time",
"seconds\".format(processingTime(groups))) print() print(\"Film messages:\") groups = groupByMsgType(groupBySource(messages)[\"film\"]) for key in",
"self.queued_time = None self.source = source self.temp = self.parseTime(time) self.created(zero_time)",
"for the timing of a single message. \"\"\" def __init__(self,",
"message type. \"\"\" return self.m_type def incNWorkers(self): self.n_workers += 1",
"#!/usr/bin/env python \"\"\" This parses a log file series (i.e.",
"= (t_time - self.temp).total_seconds() self.temp = t_time def getIterable(dict_or_list): \"\"\"",
"message source. \"\"\" return groupByX(lambda x : x.getSource(), messages) def",
"processingTime(messages): \"\"\" Returns the total processing time for a collection",
"process this message. \"\"\" return self.n_workers def getProcessingTime(self): \"\"\" Return",
"def queuedTime(messages): \"\"\" Returns the total queued time for a",
"more message objects per message type. \"\"\" return groupByX(lambda x",
"datetime import os pattern = '%Y-%m-%d %H:%M:%S,%f' class Message(object): \"\"\"",
"list): iterable = dict_or_list else: raise Exception(\"Unknown type '\" +",
"\"\"\" Returns the total processing time for a collection of",
"for a collection of messages. \"\"\" accum_time = 0 for",
"command.split(\",\")[1] messages[m_id].incNWorkers() # Ignore messages that we don't have all",
"processing time for a collection of messages. \"\"\" accum_time =",
"timing and call frequency information for HAL messages. Hazen 5/18",
"sorted(groups): grp = groups[key] print(key + \", {0:0d} counts, {1:.3f}",
"self.processing_time def getQueuedTime(self): \"\"\" Return time queued in seconds. \"\"\"",
"<gh_stars>0 #!/usr/bin/env python \"\"\" This parses a log file series",
"Message(object): \"\"\" Storage for the timing of a single message.",
"all the timing for. if not ignore_incomplete: temp = {}",
"self.temp = t_time def getIterable(dict_or_list): \"\"\" Returns an iterable given",
"ignore_incomplete = False): \"\"\" Returns a dictionary of Message objects",
"basename + \".out\" + ext if not os.path.exists(fname): print(fname, \"not",
"(t_time - self.temp).total_seconds() def sent(self, time): t_time = self.parseTime(time) self.queued_time",
"a dictionary keyed by message source, with a list of",
"the timing data for this message. \"\"\" return (self.processing_time !=",
"parseTime(self, time): return datetime.strptime(time, pattern) def processed(self, time): t_time =",
"the timing for. if msg.isComplete() or not ignore_incomplete: m_type =",
"Returns the source of a message. \"\"\" return self.source def",
"a dictionary of Message objects keyed by their ID number.",
"print() print(\"All messages:\") for key in sorted(groups): grp = groups[key]",
"self.m_type = m_type self.n_workers = 0 self.processing_time = None self.queued_time",
"this message. \"\"\" return self.n_workers def getProcessingTime(self): \"\"\" Return time",
"m_type self.n_workers = 0 self.processing_time = None self.queued_time = None",
"+ \".out\" + ext if not os.path.exists(fname): print(fname, \"not found.\")",
"Returns the total processing time for a collection of messages.",
"more message objects per message source. \"\"\" return groupByX(lambda x",
"Return the number of workers (QRunnables) that were employed to",
"zero_time = None messages = {} for ext in [\".5\",",
"(len(sys.argv) != 2): print(\"usage: <log file>\") exit() messages = logTiming(sys.argv[1])",
"time = time, zero_time = zero_time) # Message sent. elif",
"fp: try: [time, command] = map(lambda x: x.strip(), line.split(\":hal4000:INFO:\")) except",
"ID number. \"\"\" zero_time = None messages = {} for",
"of Message objects keyed by their ID number. \"\"\" zero_time",
"a dictionary keyed by message type, with a list of",
"\".1\", \"\"]: fname = basename + \".out\" + ext if",
"\"\"\" Return the message type. \"\"\" return self.m_type def incNWorkers(self):",
"(command.startswith(\"queued,\")): [m_id, source, m_type] = command.split(\",\")[1:] messages[m_id] = Message(m_type =",
"command.split(\",\")[1] messages[m_id].sent(time) # Message processed. elif (command.startswith(\"processed,\")): m_id = command.split(\",\")[1]",
"\"\"\" return groupByX(lambda x : x.getType(), messages) def groupBySource(messages): \"\"\"",
"in the log file in seconds. \"\"\" return self.created_time def",
"{} for m_id in messages: msg = messages[m_id] if msg.isComplete():",
"Return time queued in seconds. \"\"\" return self.queued_time def getSource(self):",
"iterable = dict_or_list else: raise Exception(\"Unknown type '\" + str(type(dict_or_list))",
"def getQueuedTime(self): \"\"\" Return time queued in seconds. \"\"\" return",
"Return the message type. \"\"\" return self.m_type def incNWorkers(self): self.n_workers",
"= source, time = time, zero_time = zero_time) # Message",
"+ \", {0:0d} counts, {1:.3f} seconds\".format(len(grp), processingTime(grp))) print(\"Total queued time",
"for a a collection of messages. \"\"\" accum_time = 0",
"= None self.source = source self.temp = self.parseTime(time) self.created(zero_time) def",
"= t_time def getIterable(dict_or_list): \"\"\" Returns an iterable given a",
"don't have all the timing for. if not ignore_incomplete: temp",
"dictionary keyed by the requested group. \"\"\" m_grp = {}",
"msg in getIterable(messages): # Ignore messages that we don't have",
"accum_time += msg.getProcessingTime() return accum_time def queuedTime(messages): \"\"\" Returns the",
"Message sent. elif (command.startswith(\"sent,\")): m_id = command.split(\",\")[1] messages[m_id].sent(time) # Message",
"return groupByX(lambda x : x.getSource(), messages) def groupByX(grp_fn, messages): \"\"\"",
"# Ignore messages that we don't have all the timing",
"def getIterable(dict_or_list): \"\"\" Returns an iterable given a dictionary of",
"self.created_time def getNWorkers(self): \"\"\" Return the number of workers (QRunnables)",
"m_grp = {} for msg in getIterable(messages): # Ignore messages",
"log file series (i.e. log, log.1, log.2, etc..) and outputs",
"incNWorkers(self): self.n_workers += 1 def isComplete(self): \"\"\" Returns true if",
"in seconds. \"\"\" return self.queued_time def getSource(self): \"\"\" Returns the",
"time): t_time = self.parseTime(time) self.processing_time = (t_time - self.temp).total_seconds() def",
"accum_time def queuedTime(messages): \"\"\" Returns the total queued time for",
"with a list of one or more message objects per",
"(command.startswith(\"sent,\")): m_id = command.split(\",\")[1] messages[m_id].sent(time) # Message processed. elif (command.startswith(\"processed,\")):",
"number. \"\"\" zero_time = None messages = {} for ext",
"def getCreatedTime(self): \"\"\" Returns the time when the message was",
"\"\"\" return self.processing_time def getQueuedTime(self): \"\"\" Return time queued in",
"to process in seconds. \"\"\" return self.processing_time def getQueuedTime(self): \"\"\"",
"= dict_or_list else: raise Exception(\"Unknown type '\" + str(type(dict_or_list)) +",
"accum_time += msg.getQueuedTime() return accum_time if (__name__ == \"__main__\"): import",
"to process this message. \"\"\" return self.n_workers def getProcessingTime(self): \"\"\"",
"getType(self): \"\"\" Return the message type. \"\"\" return self.m_type def",
"grp = groups[key] print(key + \", {0:0d} counts, {1:.3f} seconds\".format(len(grp),",
"\"\"]: fname = basename + \".out\" + ext if not",
"Returns the time when the message was created relative to",
"getQueuedTime(self): \"\"\" Return time queued in seconds. \"\"\" return self.queued_time",
"\"\"\" return self.queued_time def getSource(self): \"\"\" Returns the source of",
"\"\"\" Returns a dictionary keyed by the requested group. \"\"\"",
"{0:.3f} seconds\".format(queuedTime(groups))) print(\"Total processing time {0:.3f} seconds\".format(processingTime(groups))) print() print(\"Film messages:\")",
"= time # Message queued. if (command.startswith(\"queued,\")): [m_id, source, m_type]",
"elt in msg: accum_time += elt.getQueuedTime() else: accum_time += msg.getQueuedTime()",
"message type. \"\"\" return groupByX(lambda x : x.getType(), messages) def",
"elt.getQueuedTime() else: accum_time += msg.getQueuedTime() return accum_time if (__name__ ==",
"messages[m_id].incNWorkers() # Ignore messages that we don't have all the",
"dictionary of Message objects keyed by their ID number. \"\"\"",
"\"\"\" Storage for the timing of a single message. \"\"\"",
"time): return datetime.strptime(time, pattern) def processed(self, time): t_time = self.parseTime(time)",
"relative to first time in the log file in seconds.",
"fname = basename + \".out\" + ext if not os.path.exists(fname):",
"(__name__ == \"__main__\"): import sys if (len(sys.argv) != 2): print(\"usage:",
"keyed by the requested group. \"\"\" m_grp = {} for",
"msg: accum_time += elt.getQueuedTime() else: accum_time += msg.getQueuedTime() return accum_time",
"\"\"\" Returns a dictionary of Message objects keyed by their",
"a dictionary of a list. \"\"\" if isinstance(dict_or_list, dict): iterable",
"\"\"\" return groupByX(lambda x : x.getSource(), messages) def groupByX(grp_fn, messages):",
"= Message(m_type = m_type, source = source, time = time,",
"getProcessingTime(self): \"\"\" Return time to process in seconds. \"\"\" return",
"command.split(\",\")[1] messages[m_id].processed(time) elif (command.startswith(\"worker done,\")): m_id = command.split(\",\")[1] messages[m_id].incNWorkers() #",
"time {0:.3f} seconds\".format(processingTime(groups))) print() print(\"Film messages:\") groups = groupByMsgType(groupBySource(messages)[\"film\"]) for",
"= list(dict_or_list.values()) elif isinstance(dict_or_list, list): iterable = dict_or_list else: raise",
"str(type(dict_or_list)) + \"'\") return iterable def groupByMsgType(messages): \"\"\" Returns a",
"t_time = self.parseTime(time) self.queued_time = (t_time - self.temp).total_seconds() self.temp =",
"messages:\") for key in sorted(groups): grp = groups[key] print(key +",
"= m_type, source = source, time = time, zero_time =",
"if (len(sys.argv) != 2): print(\"usage: <log file>\") exit() messages =",
"[msg] return m_grp def logTiming(basename, ignore_incomplete = False): \"\"\" Returns",
"type, with a list of one or more message objects",
"from datetime import datetime import os pattern = '%Y-%m-%d %H:%M:%S,%f'",
"self.parseTime(time) self.created(zero_time) def created(self, time): t_time = self.parseTime(time) self.created_time =",
"in seconds. \"\"\" return self.created_time def getNWorkers(self): \"\"\" Return the",
"'\" + str(type(dict_or_list)) + \"'\") return iterable def groupByMsgType(messages): \"\"\"",
"messages. \"\"\" accum_time = 0 for msg in getIterable(messages): if",
"(QRunnables) that were employed to process this message. \"\"\" return",
"Message(m_type = m_type, source = source, time = time, zero_time",
"elif (command.startswith(\"sent,\")): m_id = command.split(\",\")[1] messages[m_id].sent(time) # Message processed. elif",
"accum_time += elt.getProcessingTime() else: accum_time += msg.getProcessingTime() return accum_time def",
"= None, **kwds): super().__init__(**kwds) self.created_time = None self.m_type = m_type",
"else: accum_time += msg.getProcessingTime() return accum_time def queuedTime(messages): \"\"\" Returns",
"= [msg] return m_grp def logTiming(basename, ignore_incomplete = False): \"\"\"",
"= groupByMsgType(groupBySource(messages)[\"film\"]) for key in sorted(groups): grp = groups[key] print(key",
"None, time = None, zero_time = None, **kwds): super().__init__(**kwds) self.created_time",
"return accum_time def queuedTime(messages): \"\"\" Returns the total queued time",
"= {} for ext in [\".5\", \".4\", \".3\", \".2\", \".1\",",
"timing for. if msg.isComplete() or not ignore_incomplete: m_type = grp_fn(msg)",
"with open(fname) as fp: for line in fp: try: [time,",
"\", {0:0d} counts, {1:.3f} seconds\".format(len(grp), processingTime(grp))) print(\"Total processing time {0:.3f}",
"m_id in messages: msg = messages[m_id] if msg.isComplete(): temp[m_id] =",
"the total processing time for a collection of messages. \"\"\"",
"time for a a collection of messages. \"\"\" accum_time =",
"x.getType(), messages) def groupBySource(messages): \"\"\" Returns a dictionary keyed by",
"def getNWorkers(self): \"\"\" Return the number of workers (QRunnables) that",
"or more message objects per message source. \"\"\" return groupByX(lambda",
"+ \"'\") return iterable def groupByMsgType(messages): \"\"\" Returns a dictionary",
"list of one or more message objects per message type.",
"for ext in [\".5\", \".4\", \".3\", \".2\", \".1\", \"\"]: fname",
"+= msg.getProcessingTime() return accum_time def queuedTime(messages): \"\"\" Returns the total",
"series (i.e. log, log.1, log.2, etc..) and outputs timing and",
": x.getType(), messages) def groupBySource(messages): \"\"\" Returns a dictionary keyed",
"by their ID number. \"\"\" zero_time = None messages =",
"if msg.isComplete(): temp[m_id] = msg return temp else: return messages",
"in m_grp: m_grp[m_type].append(msg) else: m_grp[m_type] = [msg] return m_grp def",
"self.source def getType(self): \"\"\" Return the message type. \"\"\" return",
"information for HAL messages. Hazen 5/18 \"\"\" from datetime import",
"in fp: try: [time, command] = map(lambda x: x.strip(), line.split(\":hal4000:INFO:\"))",
"msg.getQueuedTime() return accum_time if (__name__ == \"__main__\"): import sys if",
"return datetime.strptime(time, pattern) def processed(self, time): t_time = self.parseTime(time) self.processing_time",
"= '%Y-%m-%d %H:%M:%S,%f' class Message(object): \"\"\" Storage for the timing",
"\".out\" + ext if not os.path.exists(fname): print(fname, \"not found.\") continue",
"def getProcessingTime(self): \"\"\" Return time to process in seconds. \"\"\"",
"groups[key] print(key + \", {0:0d} counts, {1:.3f} seconds\".format(len(grp), processingTime(grp))) print(\"Total",
"= source self.temp = self.parseTime(time) self.created(zero_time) def created(self, time): t_time",
"that were employed to process this message. \"\"\" return self.n_workers",
"dictionary of a list. \"\"\" if isinstance(dict_or_list, dict): iterable =",
"requested group. \"\"\" m_grp = {} for msg in getIterable(messages):",
"(i.e. log, log.1, log.2, etc..) and outputs timing and call",
"- t_time).total_seconds() def getCreatedTime(self): \"\"\" Returns the time when the",
"the log file in seconds. \"\"\" return self.created_time def getNWorkers(self):",
"\"\"\" from datetime import datetime import os pattern = '%Y-%m-%d",
"time, zero_time = zero_time) # Message sent. elif (command.startswith(\"sent,\")): m_id",
"None self.source = source self.temp = self.parseTime(time) self.created(zero_time) def created(self,",
"in msg: accum_time += elt.getQueuedTime() else: accum_time += msg.getQueuedTime() return",
"outputs timing and call frequency information for HAL messages. Hazen",
"dictionary keyed by message type, with a list of one",
"return temp else: return messages def processingTime(messages): \"\"\" Returns the",
"messages[m_id] = Message(m_type = m_type, source = source, time =",
"\"\"\" Returns the source of a message. \"\"\" return self.source",
"None, source = None, time = None, zero_time = None,",
"m_type = grp_fn(msg) if m_type in m_grp: m_grp[m_type].append(msg) else: m_grp[m_type]",
"return iterable def groupByMsgType(messages): \"\"\" Returns a dictionary keyed by",
"def __init__(self, m_type = None, source = None, time =",
"import sys if (len(sys.argv) != 2): print(\"usage: <log file>\") exit()",
"line in fp: try: [time, command] = map(lambda x: x.strip(),",
"time {0:.3f} seconds\".format(queuedTime(groups))) print(\"Total processing time {0:.3f} seconds\".format(processingTime(groups))) print() print(\"Film",
"open(fname) as fp: for line in fp: try: [time, command]",
"workers (QRunnables) that were employed to process this message. \"\"\"",
"\", {0:0d} counts, {1:.3f} seconds\".format(len(grp), processingTime(grp))) print(\"Total queued time {0:.3f}",
"in getIterable(messages): # Ignore messages that we don't have all",
"messages) def groupBySource(messages): \"\"\" Returns a dictionary keyed by message",
"\".3\", \".2\", \".1\", \"\"]: fname = basename + \".out\" +",
"= (t_time - self.temp).total_seconds() def sent(self, time): t_time = self.parseTime(time)",
"of one or more message objects per message type. \"\"\"",
"the message type. \"\"\" return self.m_type def incNWorkers(self): self.n_workers +=",
"(self.processing_time != None) def parseTime(self, time): return datetime.strptime(time, pattern) def",
"Returns the total queued time for a a collection of",
"= map(lambda x: x.strip(), line.split(\":hal4000:INFO:\")) except ValueError: continue if zero_time",
"def processed(self, time): t_time = self.parseTime(time) self.processing_time = (t_time -",
"data for this message. \"\"\" return (self.processing_time != None) def",
"dict_or_list else: raise Exception(\"Unknown type '\" + str(type(dict_or_list)) + \"'\")",
"\"\"\" Returns the time when the message was created relative",
"true if we have all the timing data for this",
"one or more message objects per message source. \"\"\" return",
"self.n_workers = 0 self.processing_time = None self.queued_time = None self.source",
"\"\"\" return self.source def getType(self): \"\"\" Return the message type.",
"+ ext if not os.path.exists(fname): print(fname, \"not found.\") continue with",
"if (__name__ == \"__main__\"): import sys if (len(sys.argv) != 2):",
"pattern = '%Y-%m-%d %H:%M:%S,%f' class Message(object): \"\"\" Storage for the",
"+= msg.getQueuedTime() return accum_time if (__name__ == \"__main__\"): import sys",
"getSource(self): \"\"\" Returns the source of a message. \"\"\" return",
"\"'\") return iterable def groupByMsgType(messages): \"\"\" Returns a dictionary keyed",
"return self.processing_time def getQueuedTime(self): \"\"\" Return time queued in seconds.",
"queued time {0:.3f} seconds\".format(queuedTime(groups))) print(\"Total processing time {0:.3f} seconds\".format(processingTime(groups))) print()",
"m_id = command.split(\",\")[1] messages[m_id].incNWorkers() # Ignore messages that we don't",
"Returns a dictionary of Message objects keyed by their ID",
"= logTiming(sys.argv[1]) groups = groupByMsgType(messages) print() print(\"All messages:\") for key",
"None, **kwds): super().__init__(**kwds) self.created_time = None self.m_type = m_type self.n_workers",
"return accum_time if (__name__ == \"__main__\"): import sys if (len(sys.argv)",
"print(\"Total queued time {0:.3f} seconds\".format(queuedTime(groups))) print(\"Total processing time {0:.3f} seconds\".format(processingTime(groups)))",
"ValueError: continue if zero_time is None: zero_time = time #",
"a single message. \"\"\" def __init__(self, m_type = None, source",
"messages[m_id] if msg.isComplete(): temp[m_id] = msg return temp else: return",
"a a collection of messages. \"\"\" accum_time = 0 for",
"for elt in msg: accum_time += elt.getQueuedTime() else: accum_time +=",
"getIterable(dict_or_list): \"\"\" Returns an iterable given a dictionary of a",
"in seconds. \"\"\" return self.processing_time def getQueuedTime(self): \"\"\" Return time",
"list of one or more message objects per message source.",
"per message source. \"\"\" return groupByX(lambda x : x.getSource(), messages)",
"m_id = command.split(\",\")[1] messages[m_id].sent(time) # Message processed. elif (command.startswith(\"processed,\")): m_id",
"Message queued. if (command.startswith(\"queued,\")): [m_id, source, m_type] = command.split(\",\")[1:] messages[m_id]",
"import os pattern = '%Y-%m-%d %H:%M:%S,%f' class Message(object): \"\"\" Storage",
"self.created_time = None self.m_type = m_type self.n_workers = 0 self.processing_time",
"that we don't have all the timing for. if msg.isComplete()",
"= command.split(\",\")[1] messages[m_id].sent(time) # Message processed. elif (command.startswith(\"processed,\")): m_id =",
"list): for elt in msg: accum_time += elt.getProcessingTime() else: accum_time",
"done,\")): m_id = command.split(\",\")[1] messages[m_id].incNWorkers() # Ignore messages that we",
"elif (command.startswith(\"worker done,\")): m_id = command.split(\",\")[1] messages[m_id].incNWorkers() # Ignore messages",
"= m_type self.n_workers = 0 self.processing_time = None self.queued_time =",
"self.parseTime(time) self.queued_time = (t_time - self.temp).total_seconds() self.temp = t_time def",
"processingTime(grp))) print(\"Total queued time {0:.3f} seconds\".format(queuedTime(groups))) print(\"Total processing time {0:.3f}",
"{} for ext in [\".5\", \".4\", \".3\", \".2\", \".1\", \"\"]:",
"a message. \"\"\" return self.source def getType(self): \"\"\" Return the",
"2): print(\"usage: <log file>\") exit() messages = logTiming(sys.argv[1]) groups =",
"we have all the timing data for this message. \"\"\"",
"messages:\") groups = groupByMsgType(groupBySource(messages)[\"film\"]) for key in sorted(groups): grp =",
"groups = groupByMsgType(messages) print() print(\"All messages:\") for key in sorted(groups):",
"+ str(type(dict_or_list)) + \"'\") return iterable def groupByMsgType(messages): \"\"\" Returns",
"command] = map(lambda x: x.strip(), line.split(\":hal4000:INFO:\")) except ValueError: continue if",
"file>\") exit() messages = logTiming(sys.argv[1]) groups = groupByMsgType(messages) print() print(\"All",
"self.queued_time = (t_time - self.temp).total_seconds() self.temp = t_time def getIterable(dict_or_list):",
"\"\"\" Returns a dictionary keyed by message type, with a",
"messages): \"\"\" Returns a dictionary keyed by the requested group.",
"the requested group. \"\"\" m_grp = {} for msg in",
"return self.created_time def getNWorkers(self): \"\"\" Return the number of workers",
"time): t_time = self.parseTime(time) self.created_time = (self.temp - t_time).total_seconds() def",
"type. \"\"\" return groupByX(lambda x : x.getType(), messages) def groupBySource(messages):",
"None self.queued_time = None self.source = source self.temp = self.parseTime(time)",
"was created relative to first time in the log file",
"key in sorted(groups): grp = groups[key] print(key + \", {0:0d}",
"self.created_time = (self.temp - t_time).total_seconds() def getCreatedTime(self): \"\"\" Returns the",
"0 self.processing_time = None self.queued_time = None self.source = source",
"isinstance(dict_or_list, dict): iterable = list(dict_or_list.values()) elif isinstance(dict_or_list, list): iterable =",
"x.getSource(), messages) def groupByX(grp_fn, messages): \"\"\" Returns a dictionary keyed",
"return self.m_type def incNWorkers(self): self.n_workers += 1 def isComplete(self): \"\"\"",
"def isComplete(self): \"\"\" Returns true if we have all the",
"the timing of a single message. \"\"\" def __init__(self, m_type",
"self.n_workers def getProcessingTime(self): \"\"\" Return time to process in seconds.",
"return self.source def getType(self): \"\"\" Return the message type. \"\"\"",
"for HAL messages. Hazen 5/18 \"\"\" from datetime import datetime",
"time): t_time = self.parseTime(time) self.queued_time = (t_time - self.temp).total_seconds() self.temp",
"temp = {} for m_id in messages: msg = messages[m_id]",
"Storage for the timing of a single message. \"\"\" def",
"m_grp: m_grp[m_type].append(msg) else: m_grp[m_type] = [msg] return m_grp def logTiming(basename,",
"python \"\"\" This parses a log file series (i.e. log,",
"were employed to process this message. \"\"\" return self.n_workers def",
"= self.parseTime(time) self.processing_time = (t_time - self.temp).total_seconds() def sent(self, time):",
"m_id = command.split(\",\")[1] messages[m_id].processed(time) elif (command.startswith(\"worker done,\")): m_id = command.split(\",\")[1]",
"= False): \"\"\" Returns a dictionary of Message objects keyed",
"type. \"\"\" return self.m_type def incNWorkers(self): self.n_workers += 1 def",
"dict): iterable = list(dict_or_list.values()) elif isinstance(dict_or_list, list): iterable = dict_or_list",
"elif isinstance(dict_or_list, list): iterable = dict_or_list else: raise Exception(\"Unknown type",
"messages[m_id].sent(time) # Message processed. elif (command.startswith(\"processed,\")): m_id = command.split(\",\")[1] messages[m_id].processed(time)",
"def groupByMsgType(messages): \"\"\" Returns a dictionary keyed by message type,",
"def incNWorkers(self): self.n_workers += 1 def isComplete(self): \"\"\" Returns true",
"msg = messages[m_id] if msg.isComplete(): temp[m_id] = msg return temp",
"file in seconds. \"\"\" return self.created_time def getNWorkers(self): \"\"\" Return",
"import datetime import os pattern = '%Y-%m-%d %H:%M:%S,%f' class Message(object):",
"[time, command] = map(lambda x: x.strip(), line.split(\":hal4000:INFO:\")) except ValueError: continue",
"m_grp[m_type].append(msg) else: m_grp[m_type] = [msg] return m_grp def logTiming(basename, ignore_incomplete",
"\"\"\" This parses a log file series (i.e. log, log.1,",
"is None: zero_time = time # Message queued. if (command.startswith(\"queued,\")):",
"\"\"\" Return the number of workers (QRunnables) that were employed",
"groupByX(lambda x : x.getType(), messages) def groupBySource(messages): \"\"\" Returns a",
"fp: for line in fp: try: [time, command] = map(lambda",
"objects per message type. \"\"\" return groupByX(lambda x : x.getType(),",
"Message objects keyed by their ID number. \"\"\" zero_time =",
"log.2, etc..) and outputs timing and call frequency information for",
"- self.temp).total_seconds() def sent(self, time): t_time = self.parseTime(time) self.queued_time =",
"pattern) def processed(self, time): t_time = self.parseTime(time) self.processing_time = (t_time",
"zero_time = zero_time) # Message sent. elif (command.startswith(\"sent,\")): m_id =",
"def sent(self, time): t_time = self.parseTime(time) self.queued_time = (t_time -",
"self.source = source self.temp = self.parseTime(time) self.created(zero_time) def created(self, time):",
"\"\"\" return self.created_time def getNWorkers(self): \"\"\" Return the number of",
"= {} for msg in getIterable(messages): # Ignore messages that",
"print(\"Film messages:\") groups = groupByMsgType(groupBySource(messages)[\"film\"]) for key in sorted(groups): grp",
"x.strip(), line.split(\":hal4000:INFO:\")) except ValueError: continue if zero_time is None: zero_time",
"in sorted(groups): grp = groups[key] print(key + \", {0:0d} counts,",
"exit() messages = logTiming(sys.argv[1]) groups = groupByMsgType(messages) print() print(\"All messages:\")",
"when the message was created relative to first time in",
"found.\") continue with open(fname) as fp: for line in fp:",
"self.parseTime(time) self.created_time = (self.temp - t_time).total_seconds() def getCreatedTime(self): \"\"\" Returns",
"print(\"Total processing time {0:.3f} seconds\".format(processingTime(groups))) print() print(\"Film messages:\") groups =",
"t_time def getIterable(dict_or_list): \"\"\" Returns an iterable given a dictionary",
"message. \"\"\" def __init__(self, m_type = None, source = None,",
"<log file>\") exit() messages = logTiming(sys.argv[1]) groups = groupByMsgType(messages) print()",
"def groupByX(grp_fn, messages): \"\"\" Returns a dictionary keyed by the",
"+ \", {0:0d} counts, {1:.3f} seconds\".format(len(grp), processingTime(grp))) print(\"Total processing time",
"don't have all the timing for. if msg.isComplete() or not",
"source. \"\"\" return groupByX(lambda x : x.getSource(), messages) def groupByX(grp_fn,",
": x.getSource(), messages) def groupByX(grp_fn, messages): \"\"\" Returns a dictionary",
"None messages = {} for ext in [\".5\", \".4\", \".3\",",
"groupBySource(messages): \"\"\" Returns a dictionary keyed by message source, with",
"Message processed. elif (command.startswith(\"processed,\")): m_id = command.split(\",\")[1] messages[m_id].processed(time) elif (command.startswith(\"worker",
"by message type, with a list of one or more",
"if we have all the timing data for this message.",
"datetime import datetime import os pattern = '%Y-%m-%d %H:%M:%S,%f' class",
"t_time = self.parseTime(time) self.created_time = (self.temp - t_time).total_seconds() def getCreatedTime(self):",
"their ID number. \"\"\" zero_time = None messages = {}",
"os pattern = '%Y-%m-%d %H:%M:%S,%f' class Message(object): \"\"\" Storage for",
"(self.temp - t_time).total_seconds() def getCreatedTime(self): \"\"\" Returns the time when",
"if isinstance(msg, list): for elt in msg: accum_time += elt.getQueuedTime()",
"log, log.1, log.2, etc..) and outputs timing and call frequency",
"+= 1 def isComplete(self): \"\"\" Returns true if we have",
"keyed by their ID number. \"\"\" zero_time = None messages",
"Exception(\"Unknown type '\" + str(type(dict_or_list)) + \"'\") return iterable def",
"else: accum_time += msg.getQueuedTime() return accum_time if (__name__ == \"__main__\"):",
"grp_fn(msg) if m_type in m_grp: m_grp[m_type].append(msg) else: m_grp[m_type] = [msg]",
"print(key + \", {0:0d} counts, {1:.3f} seconds\".format(len(grp), processingTime(grp))) print(\"Total queued",
"iterable = list(dict_or_list.values()) elif isinstance(dict_or_list, list): iterable = dict_or_list else:",
"m_type in m_grp: m_grp[m_type].append(msg) else: m_grp[m_type] = [msg] return m_grp",
"messages = logTiming(sys.argv[1]) groups = groupByMsgType(messages) print() print(\"All messages:\") for",
"the time when the message was created relative to first",
"Returns an iterable given a dictionary of a list. \"\"\"",
"message type, with a list of one or more message",
"self.m_type def incNWorkers(self): self.n_workers += 1 def isComplete(self): \"\"\" Returns",
"of one or more message objects per message source. \"\"\"",
"\"\"\" return self.n_workers def getProcessingTime(self): \"\"\" Return time to process",
"= None, source = None, time = None, zero_time =",
"try: [time, command] = map(lambda x: x.strip(), line.split(\":hal4000:INFO:\")) except ValueError:",
"line.split(\":hal4000:INFO:\")) except ValueError: continue if zero_time is None: zero_time =",
"if isinstance(dict_or_list, dict): iterable = list(dict_or_list.values()) elif isinstance(dict_or_list, list): iterable",
"timing for. if not ignore_incomplete: temp = {} for m_id",
"Hazen 5/18 \"\"\" from datetime import datetime import os pattern",
"\"\"\" m_grp = {} for msg in getIterable(messages): # Ignore",
"getCreatedTime(self): \"\"\" Returns the time when the message was created",
"if msg.isComplete() or not ignore_incomplete: m_type = grp_fn(msg) if m_type",
"per message type. \"\"\" return groupByX(lambda x : x.getType(), messages)",
"first time in the log file in seconds. \"\"\" return",
"if (command.startswith(\"queued,\")): [m_id, source, m_type] = command.split(\",\")[1:] messages[m_id] = Message(m_type",
"source, with a list of one or more message objects",
"= None self.queued_time = None self.source = source self.temp =",
"= 0 self.processing_time = None self.queued_time = None self.source =",
"queued in seconds. \"\"\" return self.queued_time def getSource(self): \"\"\" Returns",
"command.split(\",\")[1:] messages[m_id] = Message(m_type = m_type, source = source, time",
"temp else: return messages def processingTime(messages): \"\"\" Returns the total",
"{0:0d} counts, {1:.3f} seconds\".format(len(grp), processingTime(grp))) print(\"Total queued time {0:.3f} seconds\".format(queuedTime(groups)))",
"HAL messages. Hazen 5/18 \"\"\" from datetime import datetime import",
"as fp: for line in fp: try: [time, command] =",
"elt.getProcessingTime() else: accum_time += msg.getProcessingTime() return accum_time def queuedTime(messages): \"\"\"",
"dictionary keyed by message source, with a list of one",
"== \"__main__\"): import sys if (len(sys.argv) != 2): print(\"usage: <log",
"group. \"\"\" m_grp = {} for msg in getIterable(messages): #",
"seconds\".format(len(grp), processingTime(grp))) print(\"Total queued time {0:.3f} seconds\".format(queuedTime(groups))) print(\"Total processing time",
"or not ignore_incomplete: m_type = grp_fn(msg) if m_type in m_grp:",
"isinstance(msg, list): for elt in msg: accum_time += elt.getQueuedTime() else:",
"[m_id, source, m_type] = command.split(\",\")[1:] messages[m_id] = Message(m_type = m_type,",
"5/18 \"\"\" from datetime import datetime import os pattern =",
"return self.n_workers def getProcessingTime(self): \"\"\" Return time to process in",
"the source of a message. \"\"\" return self.source def getType(self):",
"= messages[m_id] if msg.isComplete(): temp[m_id] = msg return temp else:",
"= self.parseTime(time) self.created_time = (self.temp - t_time).total_seconds() def getCreatedTime(self): \"\"\"",
"= None, time = None, zero_time = None, **kwds): super().__init__(**kwds)",
"None, zero_time = None, **kwds): super().__init__(**kwds) self.created_time = None self.m_type",
"all the timing for. if msg.isComplete() or not ignore_incomplete: m_type",
"return messages def processingTime(messages): \"\"\" Returns the total processing time",
"groups = groupByMsgType(groupBySource(messages)[\"film\"]) for key in sorted(groups): grp = groups[key]",
"msg.isComplete() or not ignore_incomplete: m_type = grp_fn(msg) if m_type in",
"and outputs timing and call frequency information for HAL messages.",
"single message. \"\"\" def __init__(self, m_type = None, source =",
"seconds. \"\"\" return self.processing_time def getQueuedTime(self): \"\"\" Return time queued",
"= None self.m_type = m_type self.n_workers = 0 self.processing_time =",
"seconds\".format(queuedTime(groups))) print(\"Total processing time {0:.3f} seconds\".format(processingTime(groups))) print() print(\"Film messages:\") groups",
"list): for elt in msg: accum_time += elt.getQueuedTime() else: accum_time",
"\"\"\" def __init__(self, m_type = None, source = None, time",
"a dictionary keyed by the requested group. \"\"\" m_grp =",
"\"__main__\"): import sys if (len(sys.argv) != 2): print(\"usage: <log file>\")",
"= None messages = {} for ext in [\".5\", \".4\",",
"def logTiming(basename, ignore_incomplete = False): \"\"\" Returns a dictionary of",
"parses a log file series (i.e. log, log.1, log.2, etc..)",
"\"\"\" if isinstance(dict_or_list, dict): iterable = list(dict_or_list.values()) elif isinstance(dict_or_list, list):",
"(command.startswith(\"processed,\")): m_id = command.split(\",\")[1] messages[m_id].processed(time) elif (command.startswith(\"worker done,\")): m_id =",
"messages[m_id].processed(time) elif (command.startswith(\"worker done,\")): m_id = command.split(\",\")[1] messages[m_id].incNWorkers() # Ignore",
"getIterable(messages): # Ignore messages that we don't have all the",
"False): \"\"\" Returns a dictionary of Message objects keyed by",
"message was created relative to first time in the log",
"return groupByX(lambda x : x.getType(), messages) def groupBySource(messages): \"\"\" Returns",
"return self.queued_time def getSource(self): \"\"\" Returns the source of a",
"None self.m_type = m_type self.n_workers = 0 self.processing_time = None",
"continue with open(fname) as fp: for line in fp: try:",
"for elt in msg: accum_time += elt.getProcessingTime() else: accum_time +=",
"if not ignore_incomplete: temp = {} for m_id in messages:",
"for line in fp: try: [time, command] = map(lambda x:",
"\"\"\" Returns the total queued time for a a collection",
"= 0 for msg in getIterable(messages): if isinstance(msg, list): for",
"self.n_workers += 1 def isComplete(self): \"\"\" Returns true if we",
"groupByX(grp_fn, messages): \"\"\" Returns a dictionary keyed by the requested",
"temp[m_id] = msg return temp else: return messages def processingTime(messages):",
"the number of workers (QRunnables) that were employed to process",
"objects per message source. \"\"\" return groupByX(lambda x : x.getSource(),",
"seconds. \"\"\" return self.created_time def getNWorkers(self): \"\"\" Return the number",
"of a list. \"\"\" if isinstance(dict_or_list, dict): iterable = list(dict_or_list.values())",
"continue if zero_time is None: zero_time = time # Message",
"list(dict_or_list.values()) elif isinstance(dict_or_list, list): iterable = dict_or_list else: raise Exception(\"Unknown",
"source, m_type] = command.split(\",\")[1:] messages[m_id] = Message(m_type = m_type, source",
"time # Message queued. if (command.startswith(\"queued,\")): [m_id, source, m_type] =",
"in messages: msg = messages[m_id] if msg.isComplete(): temp[m_id] = msg",
"{0:.3f} seconds\".format(processingTime(groups))) print() print(\"Film messages:\") groups = groupByMsgType(groupBySource(messages)[\"film\"]) for key",
"self.processing_time = (t_time - self.temp).total_seconds() def sent(self, time): t_time =",
"created relative to first time in the log file in",
"\"\"\" Return time to process in seconds. \"\"\" return self.processing_time",
"print(key + \", {0:0d} counts, {1:.3f} seconds\".format(len(grp), processingTime(grp))) print(\"Total processing",
"[\".5\", \".4\", \".3\", \".2\", \".1\", \"\"]: fname = basename +",
"= self.parseTime(time) self.created(zero_time) def created(self, time): t_time = self.parseTime(time) self.created_time",
"# Message queued. if (command.startswith(\"queued,\")): [m_id, source, m_type] = command.split(\",\")[1:]",
"isinstance(msg, list): for elt in msg: accum_time += elt.getProcessingTime() else:",
"etc..) and outputs timing and call frequency information for HAL",
"ext in [\".5\", \".4\", \".3\", \".2\", \".1\", \"\"]: fname =",
"{0:0d} counts, {1:.3f} seconds\".format(len(grp), processingTime(grp))) print(\"Total processing time {0:.3f} seconds\".format(processingTime(groups)))",
"message objects per message type. \"\"\" return groupByX(lambda x :",
"keyed by message source, with a list of one or",
"None: zero_time = time # Message queued. if (command.startswith(\"queued,\")): [m_id,",
"iterable def groupByMsgType(messages): \"\"\" Returns a dictionary keyed by message",
"return m_grp def logTiming(basename, ignore_incomplete = False): \"\"\" Returns a",
"ignore_incomplete: m_type = grp_fn(msg) if m_type in m_grp: m_grp[m_type].append(msg) else:",
"def groupBySource(messages): \"\"\" Returns a dictionary keyed by message source,",
"to first time in the log file in seconds. \"\"\"",
"messages that we don't have all the timing for. if",
"not ignore_incomplete: m_type = grp_fn(msg) if m_type in m_grp: m_grp[m_type].append(msg)",
"\"\"\" accum_time = 0 for msg in getIterable(messages): if isinstance(msg,",
"groupByMsgType(messages): \"\"\" Returns a dictionary keyed by message type, with",
"in msg: accum_time += elt.getProcessingTime() else: accum_time += msg.getProcessingTime() return",
"None) def parseTime(self, time): return datetime.strptime(time, pattern) def processed(self, time):",
"time to process in seconds. \"\"\" return self.processing_time def getQueuedTime(self):",
"source self.temp = self.parseTime(time) self.created(zero_time) def created(self, time): t_time =",
"source = source, time = time, zero_time = zero_time) #",
"self.temp = self.parseTime(time) self.created(zero_time) def created(self, time): t_time = self.parseTime(time)",
"we don't have all the timing for. if msg.isComplete() or",
"given a dictionary of a list. \"\"\" if isinstance(dict_or_list, dict):",
"%H:%M:%S,%f' class Message(object): \"\"\" Storage for the timing of a",
"(command.startswith(\"worker done,\")): m_id = command.split(\",\")[1] messages[m_id].incNWorkers() # Ignore messages that",
"\"\"\" Return time queued in seconds. \"\"\" return self.queued_time def",
"created(self, time): t_time = self.parseTime(time) self.created_time = (self.temp - t_time).total_seconds()",
"getNWorkers(self): \"\"\" Return the number of workers (QRunnables) that were",
"frequency information for HAL messages. Hazen 5/18 \"\"\" from datetime",
"processed(self, time): t_time = self.parseTime(time) self.processing_time = (t_time - self.temp).total_seconds()",
"or more message objects per message type. \"\"\" return groupByX(lambda",
"the timing for. if not ignore_incomplete: temp = {} for",
"if not os.path.exists(fname): print(fname, \"not found.\") continue with open(fname) as",
"Return time to process in seconds. \"\"\" return self.processing_time def",
"if zero_time is None: zero_time = time # Message queued.",
"\"\"\" return (self.processing_time != None) def parseTime(self, time): return datetime.strptime(time,",
"0 for msg in getIterable(messages): if isinstance(msg, list): for elt",
"of a single message. \"\"\" def __init__(self, m_type = None,",
"if m_type in m_grp: m_grp[m_type].append(msg) else: m_grp[m_type] = [msg] return",
"zero_time = None, **kwds): super().__init__(**kwds) self.created_time = None self.m_type =",
"ext if not os.path.exists(fname): print(fname, \"not found.\") continue with open(fname)",
"that we don't have all the timing for. if not",
"iterable given a dictionary of a list. \"\"\" if isinstance(dict_or_list,",
"= zero_time) # Message sent. elif (command.startswith(\"sent,\")): m_id = command.split(\",\")[1]",
"{1:.3f} seconds\".format(len(grp), processingTime(grp))) print(\"Total queued time {0:.3f} seconds\".format(queuedTime(groups))) print(\"Total processing",
"Returns true if we have all the timing data for",
"elt in msg: accum_time += elt.getProcessingTime() else: accum_time += msg.getProcessingTime()",
"call frequency information for HAL messages. Hazen 5/18 \"\"\" from",
"sys if (len(sys.argv) != 2): print(\"usage: <log file>\") exit() messages",
"objects keyed by their ID number. \"\"\" zero_time = None",
"a list. \"\"\" if isinstance(dict_or_list, dict): iterable = list(dict_or_list.values()) elif",
"Returns a dictionary keyed by message type, with a list",
"**kwds): super().__init__(**kwds) self.created_time = None self.m_type = m_type self.n_workers =",
"\"\"\" zero_time = None messages = {} for ext in",
"print() print(\"Film messages:\") groups = groupByMsgType(groupBySource(messages)[\"film\"]) for key in sorted(groups):",
"self.temp).total_seconds() def sent(self, time): t_time = self.parseTime(time) self.queued_time = (t_time",
"def parseTime(self, time): return datetime.strptime(time, pattern) def processed(self, time): t_time",
"log.1, log.2, etc..) and outputs timing and call frequency information",
"messages = {} for ext in [\".5\", \".4\", \".3\", \".2\",",
"time for a collection of messages. \"\"\" accum_time = 0",
"total queued time for a a collection of messages. \"\"\"",
"return (self.processing_time != None) def parseTime(self, time): return datetime.strptime(time, pattern)",
"x: x.strip(), line.split(\":hal4000:INFO:\")) except ValueError: continue if zero_time is None:",
"message objects per message source. \"\"\" return groupByX(lambda x :",
"= {} for m_id in messages: msg = messages[m_id] if",
"an iterable given a dictionary of a list. \"\"\" if",
"(t_time - self.temp).total_seconds() self.temp = t_time def getIterable(dict_or_list): \"\"\" Returns",
"groupByMsgType(groupBySource(messages)[\"film\"]) for key in sorted(groups): grp = groups[key] print(key +",
"\"not found.\") continue with open(fname) as fp: for line in",
"\"\"\" Returns true if we have all the timing data",
"else: raise Exception(\"Unknown type '\" + str(type(dict_or_list)) + \"'\") return",
"queuedTime(messages): \"\"\" Returns the total queued time for a a",
"print(\"usage: <log file>\") exit() messages = logTiming(sys.argv[1]) groups = groupByMsgType(messages)",
"for. if msg.isComplete() or not ignore_incomplete: m_type = grp_fn(msg) if",
"= command.split(\",\")[1] messages[m_id].incNWorkers() # Ignore messages that we don't have",
"message source, with a list of one or more message",
"for key in sorted(groups): grp = groups[key] print(key + \",",
"m_grp[m_type] = [msg] return m_grp def logTiming(basename, ignore_incomplete = False):",
"+= elt.getProcessingTime() else: accum_time += msg.getProcessingTime() return accum_time def queuedTime(messages):",
"logTiming(sys.argv[1]) groups = groupByMsgType(messages) print() print(\"All messages:\") for key in",
"\".4\", \".3\", \".2\", \".1\", \"\"]: fname = basename + \".out\"",
"a collection of messages. \"\"\" accum_time = 0 for msg",
"of messages. \"\"\" accum_time = 0 for msg in getIterable(messages):",
"map(lambda x: x.strip(), line.split(\":hal4000:INFO:\")) except ValueError: continue if zero_time is",
"not ignore_incomplete: temp = {} for m_id in messages: msg",
"messages: msg = messages[m_id] if msg.isComplete(): temp[m_id] = msg return",
"!= 2): print(\"usage: <log file>\") exit() messages = logTiming(sys.argv[1]) groups",
"else: m_grp[m_type] = [msg] return m_grp def logTiming(basename, ignore_incomplete =",
"messages) def groupByX(grp_fn, messages): \"\"\" Returns a dictionary keyed by",
"= None, zero_time = None, **kwds): super().__init__(**kwds) self.created_time = None",
"= grp_fn(msg) if m_type in m_grp: m_grp[m_type].append(msg) else: m_grp[m_type] =",
"source, time = time, zero_time = zero_time) # Message sent."
] |
[
"not exist in settings.' self.stdout.write(not_exist) return errors = self._jsonschema_errors if",
"json class Command(BaseCommand): can_import_settings = True @property def _jsonschema_exist(self): from",
"can_import_settings = True @property def _jsonschema_exist(self): from django.conf import settings",
"hasattr(settings, 'SIMPLE_JSONSCHEMA'): return False return True @property def _jsonschema_errors(self): from",
"not self._jsonschema_exist: not_exist = '[' + error('ERROR') + '] SIMPLE_JSONSCHEMA",
"+ error('ERROR') + '] schema of ' + str(e['url']) +",
"is not exist in settings.' self.stdout.write(not_exist) return errors = self._jsonschema_errors",
"def _jsonschema_exist(self): from django.conf import settings if not hasattr(settings, 'SIMPLE_JSONSCHEMA'):",
"settings if not hasattr(settings, 'SIMPLE_JSONSCHEMA'): return False return True @property",
"}) return errors def handle(self, *args, **options): success = termcolors.make_style(fg='green')",
"'schema': json.dumps(schema, indent=4, sort_keys=True) }) return errors def handle(self, *args,",
"schemas.items(): try: Draft4Validator.check_schema(schema) except SchemaError as e: errors.append({ 'url': url,",
"from jsonschema.exceptions import SchemaError import json class Command(BaseCommand): can_import_settings =",
"in settings.' self.stdout.write(not_exist) return errors = self._jsonschema_errors if len(errors): for",
"import termcolors from jsonschema import Draft4Validator from jsonschema.exceptions import SchemaError",
"self._jsonschema_exist: not_exist = '[' + error('ERROR') + '] SIMPLE_JSONSCHEMA is",
"from jsonschema import Draft4Validator from jsonschema.exceptions import SchemaError import json",
"+ '] schema of ' + str(e['url']) + ' is",
"e['error'].message) self.stdout.write('schema:\\n' + e['schema'] + '\\n') else: self.stdout.write('[' + success('SUCCESS')",
"+ str(e['url']) + ' is invalid.' self.stdout.write(title) self.stdout.write('path: ' +",
"def handle(self, *args, **options): success = termcolors.make_style(fg='green') error = termcolors.make_style(fg='red')",
"of ' + str(e['url']) + ' is invalid.' self.stdout.write(title) self.stdout.write('path:",
"_jsonschema_errors(self): from django.conf import settings errors = [] schemas =",
"False return True @property def _jsonschema_errors(self): from django.conf import settings",
"settings.SIMPLE_JSONSCHEMA for url, schema in schemas.items(): try: Draft4Validator.check_schema(schema) except SchemaError",
"' + str(e['url']) + ' is invalid.' self.stdout.write(title) self.stdout.write('path: '",
"url, schema in schemas.items(): try: Draft4Validator.check_schema(schema) except SchemaError as e:",
"Draft4Validator.check_schema(schema) except SchemaError as e: errors.append({ 'url': url, 'error': e,",
"return True @property def _jsonschema_errors(self): from django.conf import settings errors",
"'\\n') else: self.stdout.write('[' + success('SUCCESS') + '] All jsonschemas are",
"BaseCommand from django.utils import termcolors from jsonschema import Draft4Validator from",
"_jsonschema_exist(self): from django.conf import settings if not hasattr(settings, 'SIMPLE_JSONSCHEMA'): return",
"django.conf import settings errors = [] schemas = settings.SIMPLE_JSONSCHEMA for",
"exist in settings.' self.stdout.write(not_exist) return errors = self._jsonschema_errors if len(errors):",
"else: self.stdout.write('[' + success('SUCCESS') + '] All jsonschemas are OK.')",
"in schemas.items(): try: Draft4Validator.check_schema(schema) except SchemaError as e: errors.append({ 'url':",
"' + str(list(e['error'].path))) self.stdout.write('message: ' + e['error'].message) self.stdout.write('schema:\\n' + e['schema']",
"' + e['error'].message) self.stdout.write('schema:\\n' + e['schema'] + '\\n') else: self.stdout.write('['",
"self.stdout.write('schema:\\n' + e['schema'] + '\\n') else: self.stdout.write('[' + success('SUCCESS') +",
"import BaseCommand from django.utils import termcolors from jsonschema import Draft4Validator",
"errors.append({ 'url': url, 'error': e, 'schema': json.dumps(schema, indent=4, sort_keys=True) })",
"return errors = self._jsonschema_errors if len(errors): for e in errors:",
"str(list(e['error'].path))) self.stdout.write('message: ' + e['error'].message) self.stdout.write('schema:\\n' + e['schema'] + '\\n')",
"SIMPLE_JSONSCHEMA is not exist in settings.' self.stdout.write(not_exist) return errors =",
"def _jsonschema_errors(self): from django.conf import settings errors = [] schemas",
"+ str(list(e['error'].path))) self.stdout.write('message: ' + e['error'].message) self.stdout.write('schema:\\n' + e['schema'] +",
"if not hasattr(settings, 'SIMPLE_JSONSCHEMA'): return False return True @property def",
"jsonschema.exceptions import SchemaError import json class Command(BaseCommand): can_import_settings = True",
"self.stdout.write('path: ' + str(list(e['error'].path))) self.stdout.write('message: ' + e['error'].message) self.stdout.write('schema:\\n' +",
"django.conf import settings if not hasattr(settings, 'SIMPLE_JSONSCHEMA'): return False return",
"import Draft4Validator from jsonschema.exceptions import SchemaError import json class Command(BaseCommand):",
"except SchemaError as e: errors.append({ 'url': url, 'error': e, 'schema':",
"*args, **options): success = termcolors.make_style(fg='green') error = termcolors.make_style(fg='red') if not",
"invalid.' self.stdout.write(title) self.stdout.write('path: ' + str(list(e['error'].path))) self.stdout.write('message: ' + e['error'].message)",
"from django.core.management.base import BaseCommand from django.utils import termcolors from jsonschema",
"termcolors.make_style(fg='red') if not self._jsonschema_exist: not_exist = '[' + error('ERROR') +",
"json.dumps(schema, indent=4, sort_keys=True) }) return errors def handle(self, *args, **options):",
"error('ERROR') + '] SIMPLE_JSONSCHEMA is not exist in settings.' self.stdout.write(not_exist)",
"import settings errors = [] schemas = settings.SIMPLE_JSONSCHEMA for url,",
"[] schemas = settings.SIMPLE_JSONSCHEMA for url, schema in schemas.items(): try:",
"True @property def _jsonschema_errors(self): from django.conf import settings errors =",
"schema in schemas.items(): try: Draft4Validator.check_schema(schema) except SchemaError as e: errors.append({",
"django.utils import termcolors from jsonschema import Draft4Validator from jsonschema.exceptions import",
"jsonschema import Draft4Validator from jsonschema.exceptions import SchemaError import json class",
"@property def _jsonschema_exist(self): from django.conf import settings if not hasattr(settings,",
"**options): success = termcolors.make_style(fg='green') error = termcolors.make_style(fg='red') if not self._jsonschema_exist:",
"' is invalid.' self.stdout.write(title) self.stdout.write('path: ' + str(list(e['error'].path))) self.stdout.write('message: '",
"return False return True @property def _jsonschema_errors(self): from django.conf import",
"termcolors.make_style(fg='green') error = termcolors.make_style(fg='red') if not self._jsonschema_exist: not_exist = '['",
"settings errors = [] schemas = settings.SIMPLE_JSONSCHEMA for url, schema",
"import SchemaError import json class Command(BaseCommand): can_import_settings = True @property",
"= '[' + error('ERROR') + '] SIMPLE_JSONSCHEMA is not exist",
"= settings.SIMPLE_JSONSCHEMA for url, schema in schemas.items(): try: Draft4Validator.check_schema(schema) except",
"+ e['error'].message) self.stdout.write('schema:\\n' + e['schema'] + '\\n') else: self.stdout.write('[' +",
"if len(errors): for e in errors: title = '\\n[' +",
"class Command(BaseCommand): can_import_settings = True @property def _jsonschema_exist(self): from django.conf",
"len(errors): for e in errors: title = '\\n[' + error('ERROR')",
"errors def handle(self, *args, **options): success = termcolors.make_style(fg='green') error =",
"+ ' is invalid.' self.stdout.write(title) self.stdout.write('path: ' + str(list(e['error'].path))) self.stdout.write('message:",
"in errors: title = '\\n[' + error('ERROR') + '] schema",
"not hasattr(settings, 'SIMPLE_JSONSCHEMA'): return False return True @property def _jsonschema_errors(self):",
"= self._jsonschema_errors if len(errors): for e in errors: title =",
"import json class Command(BaseCommand): can_import_settings = True @property def _jsonschema_exist(self):",
"self._jsonschema_errors if len(errors): for e in errors: title = '\\n['",
"schemas = settings.SIMPLE_JSONSCHEMA for url, schema in schemas.items(): try: Draft4Validator.check_schema(schema)",
"errors: title = '\\n[' + error('ERROR') + '] schema of",
"import settings if not hasattr(settings, 'SIMPLE_JSONSCHEMA'): return False return True",
"'error': e, 'schema': json.dumps(schema, indent=4, sort_keys=True) }) return errors def",
"= '\\n[' + error('ERROR') + '] schema of ' +",
"'] schema of ' + str(e['url']) + ' is invalid.'",
"+ '\\n') else: self.stdout.write('[' + success('SUCCESS') + '] All jsonschemas",
"for e in errors: title = '\\n[' + error('ERROR') +",
"= [] schemas = settings.SIMPLE_JSONSCHEMA for url, schema in schemas.items():",
"self.stdout.write(not_exist) return errors = self._jsonschema_errors if len(errors): for e in",
"'[' + error('ERROR') + '] SIMPLE_JSONSCHEMA is not exist in",
"from django.conf import settings errors = [] schemas = settings.SIMPLE_JSONSCHEMA",
"SchemaError import json class Command(BaseCommand): can_import_settings = True @property def",
"termcolors from jsonschema import Draft4Validator from jsonschema.exceptions import SchemaError import",
"from django.conf import settings if not hasattr(settings, 'SIMPLE_JSONSCHEMA'): return False",
"for url, schema in schemas.items(): try: Draft4Validator.check_schema(schema) except SchemaError as",
"django.core.management.base import BaseCommand from django.utils import termcolors from jsonschema import",
"try: Draft4Validator.check_schema(schema) except SchemaError as e: errors.append({ 'url': url, 'error':",
"schema of ' + str(e['url']) + ' is invalid.' self.stdout.write(title)",
"'\\n[' + error('ERROR') + '] schema of ' + str(e['url'])",
"title = '\\n[' + error('ERROR') + '] schema of '",
"+ error('ERROR') + '] SIMPLE_JSONSCHEMA is not exist in settings.'",
"+ e['schema'] + '\\n') else: self.stdout.write('[' + success('SUCCESS') + ']",
"'SIMPLE_JSONSCHEMA'): return False return True @property def _jsonschema_errors(self): from django.conf",
"+ '] SIMPLE_JSONSCHEMA is not exist in settings.' self.stdout.write(not_exist) return",
"e in errors: title = '\\n[' + error('ERROR') + ']",
"as e: errors.append({ 'url': url, 'error': e, 'schema': json.dumps(schema, indent=4,",
"success = termcolors.make_style(fg='green') error = termcolors.make_style(fg='red') if not self._jsonschema_exist: not_exist",
"url, 'error': e, 'schema': json.dumps(schema, indent=4, sort_keys=True) }) return errors",
"is invalid.' self.stdout.write(title) self.stdout.write('path: ' + str(list(e['error'].path))) self.stdout.write('message: ' +",
"True @property def _jsonschema_exist(self): from django.conf import settings if not",
"not_exist = '[' + error('ERROR') + '] SIMPLE_JSONSCHEMA is not",
"= termcolors.make_style(fg='red') if not self._jsonschema_exist: not_exist = '[' + error('ERROR')",
"Draft4Validator from jsonschema.exceptions import SchemaError import json class Command(BaseCommand): can_import_settings",
"= True @property def _jsonschema_exist(self): from django.conf import settings if",
"sort_keys=True) }) return errors def handle(self, *args, **options): success =",
"errors = [] schemas = settings.SIMPLE_JSONSCHEMA for url, schema in",
"from django.utils import termcolors from jsonschema import Draft4Validator from jsonschema.exceptions",
"settings.' self.stdout.write(not_exist) return errors = self._jsonschema_errors if len(errors): for e",
"'] SIMPLE_JSONSCHEMA is not exist in settings.' self.stdout.write(not_exist) return errors",
"@property def _jsonschema_errors(self): from django.conf import settings errors = []",
"error = termcolors.make_style(fg='red') if not self._jsonschema_exist: not_exist = '[' +",
"if not self._jsonschema_exist: not_exist = '[' + error('ERROR') + ']",
"e, 'schema': json.dumps(schema, indent=4, sort_keys=True) }) return errors def handle(self,",
"indent=4, sort_keys=True) }) return errors def handle(self, *args, **options): success",
"self.stdout.write(title) self.stdout.write('path: ' + str(list(e['error'].path))) self.stdout.write('message: ' + e['error'].message) self.stdout.write('schema:\\n'",
"SchemaError as e: errors.append({ 'url': url, 'error': e, 'schema': json.dumps(schema,",
"errors = self._jsonschema_errors if len(errors): for e in errors: title",
"'url': url, 'error': e, 'schema': json.dumps(schema, indent=4, sort_keys=True) }) return",
"return errors def handle(self, *args, **options): success = termcolors.make_style(fg='green') error",
"str(e['url']) + ' is invalid.' self.stdout.write(title) self.stdout.write('path: ' + str(list(e['error'].path)))",
"handle(self, *args, **options): success = termcolors.make_style(fg='green') error = termcolors.make_style(fg='red') if",
"e['schema'] + '\\n') else: self.stdout.write('[' + success('SUCCESS') + '] All",
"= termcolors.make_style(fg='green') error = termcolors.make_style(fg='red') if not self._jsonschema_exist: not_exist =",
"self.stdout.write('message: ' + e['error'].message) self.stdout.write('schema:\\n' + e['schema'] + '\\n') else:",
"e: errors.append({ 'url': url, 'error': e, 'schema': json.dumps(schema, indent=4, sort_keys=True)",
"Command(BaseCommand): can_import_settings = True @property def _jsonschema_exist(self): from django.conf import",
"error('ERROR') + '] schema of ' + str(e['url']) + '"
] |
[
"showmax[i]) ss = ss.format(x[ii]) #\"%0.0f %s\" % (x[ii], showmax[i]) cv2.putText(z,ss,(int(xx[ii]),int((yy[ii]))),",
"= ss.format(x[ii]) #\"%0.0f %s\" % (x[ii], showmax[i]) cv2.putText(z,ss,(int(xx[ii]),int((yy[ii]))), cv2.FONT_HERSHEY_PLAIN,2,col) try:",
"imshow(root,args,kwargs): image = cv2.cvtColor(output_frame, cv2.COLOR_BGR2RGB) image = Image.fromarray(image) image =",
"has to be used to handle the UI as well.",
"h = max(left.shape[0], right.shape[0]) w = left.shape[1] + right.shape[1] hoff",
"data calculation functions, so it can be replaced in the",
"the UI as well. It just happens to be very",
"% (showmax_digits[i], showmax[i]) ss = ss.format(x[ii]) #\"%0.0f %s\" % (x[ii],",
"horizontally. \"\"\" h = max(left.shape[0], right.shape[0]) w = left.shape[1] +",
"else: r = combine(bg,z[:,:,0]) g = combine(bg,z[:,:,1]) b = combine(bg,z[:,:,2])",
"= (w-2*margin)*(x - x.min()) / (x.max() - x.min())+margin yy =",
"len(y) < 2: return n_plots = len(data) w = float(size[1])",
"if showmax[i]: col = (0,255,0) ii = np.argmax(-y) ss =",
"combine(bg[:,:,1],z[:,:,1]) b = combine(bg[:,:,2],z[:,:,2]) else: r = combine(bg,z[:,:,0]) g =",
"in P: for i in range(len(p)-1): cv2.line(z,tuple(p[i]),tuple(p[i+1]), (255,255,255),1) return z",
"alternative: for p in P: for i in range(len(p)-1): cv2.line(z,tuple(p[i]),tuple(p[i+1]),",
"y_] for x_, y_ in zip(xx,yy)],np.int32) i+=1 P.append(pts) except ValueError:",
"= (280,640),margin = 25,name = \"data\",labels=[], skip = [], showmax",
"+ i*h mx = max(yy) if labels: if labels[i]: for",
"= Image.fromarray(image) image = ImageTk.PhotoImage(image) return Tkinter.Label(root, image=kwargs).pack() #return cv2.imshow(*args,**kwargs)",
"try: pts = np.array([[x_, y_] for x_, y_ in zip(xx,yy)],np.int32)",
"very effective for our purposes. \"\"\" def resize(*args, **kwargs): return",
"P: for i in range(len(p)-1): cv2.line(z,tuple(p[i]),tuple(p[i+1]), (255,255,255),1) return z #cv2.imshow(name,z)",
"resize(*args, **kwargs): return cv2.resize(*args, **kwargs) def moveWindow(*args,**kwargs): return def imshow(root,args,kwargs):",
"\"\"\" h = max(left.shape[0], right.shape[0]) w = left.shape[1] + right.shape[1]",
"y_ in zip(xx,yy)],np.int32) i+=1 P.append(pts) except ValueError: pass #temporary \"\"\"",
"wd = int(bg.shape[1]/bg.shape[0]*h ) bg = cv2.resize(bg,(wd,int(h))) if len(bg.shape) ==",
"\"\"\" #hack-y alternative: for p in P: for i in",
"label_ndigits[i] ss = ss.format(x[ii]) cv2.putText(z,ss,(int(xx[ii]),int((i+1)*h)), cv2.FONT_HERSHEY_PLAIN,1,col) if showmax: if showmax[i]:",
"in P: cv2.polylines(z, [p], False, (255,255,255),1) \"\"\" #hack-y alternative: for",
"combine(bg,z[:,:,1]) b = combine(bg,z[:,:,2]) z = cv2.merge([r,g,b])[:,:-wd,] i = 0",
"= ss.format(x[ii]) cv2.putText(z,ss,(int(xx[ii]),int((i+1)*h)), cv2.FONT_HERSHEY_PLAIN,1,col) if showmax: if showmax[i]: col =",
"cv2.waitKey(*args,**kwargs) \"\"\" The rest of this file defines some GUI",
"None,label_ndigits = [], showmax_digits=[]): for x,y in data: if len(x)",
"3: r = combine(bg[:,:,0],z[:,:,0]) g = combine(bg[:,:,1],z[:,:,1]) b = combine(bg[:,:,2],z[:,:,2])",
"'{0:.%sf}' % label_ndigits[i] ss = ss.format(x[ii]) cv2.putText(z,ss,(int(xx[ii]),int((i+1)*h)), cv2.FONT_HERSHEY_PLAIN,1,col) if showmax:",
"with right on right comb[:left.shape[0],:left.shape[1]] = left comb[:right.shape[0],left.shape[1]:] = right",
"np.array(x) y = -np.array(y) xx = (w-2*margin)*(x - x.min()) /",
"isinstance(bg,np.ndarray): wd = int(bg.shape[1]/bg.shape[0]*h ) bg = cv2.resize(bg,(wd,int(h))) if len(bg.shape)",
"= combine(bg[:,:,0],z[:,:,0]) g = combine(bg[:,:,1],z[:,:,1]) b = combine(bg[:,:,2],z[:,:,2]) else: r",
"destroyWindow(*args,**kwargs): return cv2.destroyWindow(*args,**kwargs) def waitKey(*args,**kwargs): return cv2.waitKey(*args,**kwargs) \"\"\" The rest",
"- x.min()) / (x.max() - x.min())+margin yy = (h-2*margin)*(y -",
"cv2.polylines(z, [p], False, (255,255,255),1) \"\"\" #hack-y alternative: for p in",
"25,name = \"data\",labels=[], skip = [], showmax = [], bg",
"< 2 or len(y) < 2: return n_plots = len(data)",
"methods (displaying image frames, event handling, etc). If desired, an",
"time import numpy as np import Tkinter \"\"\" Wraps up",
"if len(x) < 2 or len(y) < 2: return n_plots",
"cv2.putText(z,ss,(int(xx[ii]),int((i+1)*h)), cv2.FONT_HERSHEY_PLAIN,1,col) if showmax: if showmax[i]: col = (0,255,0) ii",
"pass #temporary \"\"\" #Polylines seems to have some trouble rendering",
"return cv2.waitKey(*args,**kwargs) \"\"\" The rest of this file defines some",
"reason it has to be used to handle the UI",
"rest of this file defines some GUI plotting functionality. There",
"ss.format(x[ii]) #\"%0.0f %s\" % (x[ii], showmax[i]) cv2.putText(z,ss,(int(xx[ii]),int((yy[ii]))), cv2.FONT_HERSHEY_PLAIN,2,col) try: pts",
"alternative UI could be built and imported into get_pulse.py instead.",
"used to perform much of the data analysis, but there",
"just happens to be very effective for our purposes. \"\"\"",
"shape[0] = h shape[1] = w comb = np.zeros(tuple(shape),left.dtype) #",
"def plotXY(data,size = (280,640),margin = 25,name = \"data\",labels=[], skip =",
"waitKey(*args,**kwargs): return cv2.waitKey(*args,**kwargs) \"\"\" The rest of this file defines",
"ii%skip[i] == 0: col = (255,255,255) ss = '{0:.%sf}' %",
"right on right comb[:left.shape[0],:left.shape[1]] = left comb[:right.shape[0],left.shape[1]:] = right return",
"as np import Tkinter \"\"\" Wraps up some interfaces to",
"up some interfaces to opencv user interface methods (displaying image",
"showmax: if showmax[i]: col = (0,255,0) ii = np.argmax(-y) ss",
"= \"data\",labels=[], skip = [], showmax = [], bg =",
"shape = list(left.shape) shape[0] = h shape[1] = w comb",
"in the get_pulse.py application easily. \"\"\" def combine(left, right): \"\"\"Stack",
"i*h mx = max(yy) if labels: if labels[i]: for ii",
"= w comb = np.zeros(tuple(shape),left.dtype) # left will be on",
"if labels: if labels[i]: for ii in range(len(x)): if ii%skip[i]",
"skip = [], showmax = [], bg = None,label_ndigits =",
"so it can be replaced in the get_pulse.py application easily.",
"the get_pulse.py application easily. \"\"\" def combine(left, right): \"\"\"Stack images",
"built and imported into get_pulse.py instead. Opencv is used to",
"/ (x.max() - x.min())+margin yy = (h-2*margin)*(y - y.min()) /",
"p in P: cv2.polylines(z, [p], False, (255,255,255),1) \"\"\" #hack-y alternative:",
"x_, y_ in zip(xx,yy)],np.int32) i+=1 P.append(pts) except ValueError: pass #temporary",
"def destroyWindow(*args,**kwargs): return cv2.destroyWindow(*args,**kwargs) def waitKey(*args,**kwargs): return cv2.waitKey(*args,**kwargs) \"\"\" The",
"right return comb def plotXY(data,size = (280,640),margin = 25,name =",
"on right comb[:left.shape[0],:left.shape[1]] = left comb[:right.shape[0],left.shape[1]:] = right return comb",
"g = combine(bg[:,:,1],z[:,:,1]) b = combine(bg[:,:,2],z[:,:,2]) else: r = combine(bg,z[:,:,0])",
"trouble rendering multiple polys for some people for p in",
"= -np.array(y) xx = (w-2*margin)*(x - x.min()) / (x.max() -",
"cv2.FONT_HERSHEY_PLAIN,1,col) if showmax: if showmax[i]: col = (0,255,0) ii =",
"= float(size[1]) h = size[0]/float(n_plots) z = np.zeros((size[0],size[1],3)) if isinstance(bg,np.ndarray):",
"combine(bg,z[:,:,0]) g = combine(bg,z[:,:,1]) b = combine(bg,z[:,:,2]) z = cv2.merge([r,g,b])[:,:-wd,]",
"desired, an alternative UI could be built and imported into",
"x,y in data: x = np.array(x) y = -np.array(y) xx",
"labels[i]: for ii in range(len(x)): if ii%skip[i] == 0: col",
"on left, aligned top, with right on right comb[:left.shape[0],:left.shape[1]] =",
"shape[1] = w comb = np.zeros(tuple(shape),left.dtype) # left will be",
"= right return comb def plotXY(data,size = (280,640),margin = 25,name",
"for x,y in data: if len(x) < 2 or len(y)",
"perform much of the data analysis, but there is no",
"data: x = np.array(x) y = -np.array(y) xx = (w-2*margin)*(x",
"cv2.imshow(*args,**kwargs) def destroyWindow(*args,**kwargs): return cv2.destroyWindow(*args,**kwargs) def waitKey(*args,**kwargs): return cv2.waitKey(*args,**kwargs) \"\"\"",
"simple x-y data plots in python, but this application uses",
"def moveWindow(*args,**kwargs): return def imshow(root,args,kwargs): image = cv2.cvtColor(output_frame, cv2.COLOR_BGR2RGB) image",
"Wraps up some interfaces to opencv user interface methods (displaying",
"return Tkinter.Label(root, image=kwargs).pack() #return cv2.imshow(*args,**kwargs) def destroyWindow(*args,**kwargs): return cv2.destroyWindow(*args,**kwargs) def",
"z = np.zeros((size[0],size[1],3)) if isinstance(bg,np.ndarray): wd = int(bg.shape[1]/bg.shape[0]*h ) bg",
"= np.zeros((size[0],size[1],3)) if isinstance(bg,np.ndarray): wd = int(bg.shape[1]/bg.shape[0]*h ) bg =",
"[] for x,y in data: x = np.array(x) y =",
"range(len(x)): if ii%skip[i] == 0: col = (255,255,255) ss =",
"zip(xx,yy)],np.int32) i+=1 P.append(pts) except ValueError: pass #temporary \"\"\" #Polylines seems",
"= left.shape[0] shape = list(left.shape) shape[0] = h shape[1] =",
"in zip(xx,yy)],np.int32) i+=1 P.append(pts) except ValueError: pass #temporary \"\"\" #Polylines",
"= [] for x,y in data: x = np.array(x) y",
"for x_, y_ in zip(xx,yy)],np.int32) i+=1 P.append(pts) except ValueError: pass",
"independent of the data calculation functions, so it can be",
"b = combine(bg,z[:,:,2]) z = cv2.merge([r,g,b])[:,:-wd,] i = 0 P",
"but there is no reason it has to be used",
"be replaced in the get_pulse.py application easily. \"\"\" def combine(left,",
"data plots in python, but this application uses cv2.imshow to",
"and handle user interaction. This is entirely independent of the",
"ValueError: pass #temporary \"\"\" #Polylines seems to have some trouble",
"is no reason it has to be used to handle",
"size[0]/float(n_plots) z = np.zeros((size[0],size[1],3)) if isinstance(bg,np.ndarray): wd = int(bg.shape[1]/bg.shape[0]*h )",
"P.append(pts) except ValueError: pass #temporary \"\"\" #Polylines seems to have",
"# left will be on left, aligned top, with right",
"to perform much of the data analysis, but there is",
"2: return n_plots = len(data) w = float(size[1]) h =",
"cv2.COLOR_BGR2RGB) image = Image.fromarray(image) image = ImageTk.PhotoImage(image) return Tkinter.Label(root, image=kwargs).pack()",
"ImageTk.PhotoImage(image) return Tkinter.Label(root, image=kwargs).pack() #return cv2.imshow(*args,**kwargs) def destroyWindow(*args,**kwargs): return cv2.destroyWindow(*args,**kwargs)",
"0: col = (255,255,255) ss = '{0:.%sf}' % label_ndigits[i] ss",
"\"\"\" def resize(*args, **kwargs): return cv2.resize(*args, **kwargs) def moveWindow(*args,**kwargs): return",
"y.min()) / (y.max() - y.min())+margin + i*h mx = max(yy)",
"= np.array([[x_, y_] for x_, y_ in zip(xx,yy)],np.int32) i+=1 P.append(pts)",
"right comb[:left.shape[0],:left.shape[1]] = left comb[:right.shape[0],left.shape[1]:] = right return comb def",
"comb[:right.shape[0],left.shape[1]:] = right return comb def plotXY(data,size = (280,640),margin =",
"if ii%skip[i] == 0: col = (255,255,255) ss = '{0:.%sf}'",
"images horizontally. \"\"\" h = max(left.shape[0], right.shape[0]) w = left.shape[1]",
"labels: if labels[i]: for ii in range(len(x)): if ii%skip[i] ==",
"bg = cv2.resize(bg,(wd,int(h))) if len(bg.shape) == 3: r = combine(bg[:,:,0],z[:,:,0])",
"except ValueError: pass #temporary \"\"\" #Polylines seems to have some",
"False, (255,255,255),1) \"\"\" #hack-y alternative: for p in P: for",
"h shape[1] = w comb = np.zeros(tuple(shape),left.dtype) # left will",
"image=kwargs).pack() #return cv2.imshow(*args,**kwargs) def destroyWindow(*args,**kwargs): return cv2.destroyWindow(*args,**kwargs) def waitKey(*args,**kwargs): return",
"is used to perform much of the data analysis, but",
"or len(y) < 2: return n_plots = len(data) w =",
"plotting functionality. There are plenty of other ways to do",
"(x.max() - x.min())+margin yy = (h-2*margin)*(y - y.min()) / (y.max()",
"b = combine(bg[:,:,2],z[:,:,2]) else: r = combine(bg,z[:,:,0]) g = combine(bg,z[:,:,1])",
"image = Image.fromarray(image) image = ImageTk.PhotoImage(image) return Tkinter.Label(root, image=kwargs).pack() #return",
"np.zeros(tuple(shape),left.dtype) # left will be on left, aligned top, with",
"\"\"\"Stack images horizontally. \"\"\" h = max(left.shape[0], right.shape[0]) w =",
"= [], showmax_digits=[]): for x,y in data: if len(x) <",
"- x.min())+margin yy = (h-2*margin)*(y - y.min()) / (y.max() -",
"h = size[0]/float(n_plots) z = np.zeros((size[0],size[1],3)) if isinstance(bg,np.ndarray): wd =",
"numpy as np import Tkinter \"\"\" Wraps up some interfaces",
"but this application uses cv2.imshow to do real-time data plotting",
"it can be replaced in the get_pulse.py application easily. \"\"\"",
"functionality. There are plenty of other ways to do simple",
"are plenty of other ways to do simple x-y data",
"[], bg = None,label_ndigits = [], showmax_digits=[]): for x,y in",
"combine(bg[:,:,2],z[:,:,2]) else: r = combine(bg,z[:,:,0]) g = combine(bg,z[:,:,1]) b =",
"/ (y.max() - y.min())+margin + i*h mx = max(yy) if",
"\"\"\" #Polylines seems to have some trouble rendering multiple polys",
"xx = (w-2*margin)*(x - x.min()) / (x.max() - x.min())+margin yy",
"aligned top, with right on right comb[:left.shape[0],:left.shape[1]] = left comb[:right.shape[0],left.shape[1]:]",
"int(bg.shape[1]/bg.shape[0]*h ) bg = cv2.resize(bg,(wd,int(h))) if len(bg.shape) == 3: r",
"no reason it has to be used to handle the",
"%s\" % (x[ii], showmax[i]) cv2.putText(z,ss,(int(xx[ii]),int((yy[ii]))), cv2.FONT_HERSHEY_PLAIN,2,col) try: pts = np.array([[x_,",
"functions, so it can be replaced in the get_pulse.py application",
"showmax_digits=[]): for x,y in data: if len(x) < 2 or",
"i = 0 P = [] for x,y in data:",
"some interfaces to opencv user interface methods (displaying image frames,",
"to handle the UI as well. It just happens to",
"an alternative UI could be built and imported into get_pulse.py",
"moveWindow(*args,**kwargs): return def imshow(root,args,kwargs): image = cv2.cvtColor(output_frame, cv2.COLOR_BGR2RGB) image =",
"combine(bg[:,:,0],z[:,:,0]) g = combine(bg[:,:,1],z[:,:,1]) b = combine(bg[:,:,2],z[:,:,2]) else: r =",
"in data: if len(x) < 2 or len(y) < 2:",
"return comb def plotXY(data,size = (280,640),margin = 25,name = \"data\",labels=[],",
"== 3: r = combine(bg[:,:,0],z[:,:,0]) g = combine(bg[:,:,1],z[:,:,1]) b =",
"Image.fromarray(image) image = ImageTk.PhotoImage(image) return Tkinter.Label(root, image=kwargs).pack() #return cv2.imshow(*args,**kwargs) def",
"calculation functions, so it can be replaced in the get_pulse.py",
"(displaying image frames, event handling, etc). If desired, an alternative",
"to be used to handle the UI as well. It",
"there is no reason it has to be used to",
"= cv2.resize(bg,(wd,int(h))) if len(bg.shape) == 3: r = combine(bg[:,:,0],z[:,:,0]) g",
"cv2.FONT_HERSHEY_PLAIN,2,col) try: pts = np.array([[x_, y_] for x_, y_ in",
"cv2.destroyWindow(*args,**kwargs) def waitKey(*args,**kwargs): return cv2.waitKey(*args,**kwargs) \"\"\" The rest of this",
"UI as well. It just happens to be very effective",
"= cv2.cvtColor(output_frame, cv2.COLOR_BGR2RGB) image = Image.fromarray(image) image = ImageTk.PhotoImage(image) return",
"= (255,255,255) ss = '{0:.%sf}' % label_ndigits[i] ss = ss.format(x[ii])",
"plotXY(data,size = (280,640),margin = 25,name = \"data\",labels=[], skip = [],",
"It just happens to be very effective for our purposes.",
"g = combine(bg,z[:,:,1]) b = combine(bg,z[:,:,2]) z = cv2.merge([r,g,b])[:,:-wd,] i",
"plots in python, but this application uses cv2.imshow to do",
"np.argmax(-y) ss = '{0:.%sf} %s' % (showmax_digits[i], showmax[i]) ss =",
"people for p in P: cv2.polylines(z, [p], False, (255,255,255),1) \"\"\"",
"#return cv2.imshow(*args,**kwargs) def destroyWindow(*args,**kwargs): return cv2.destroyWindow(*args,**kwargs) def waitKey(*args,**kwargs): return cv2.waitKey(*args,**kwargs)",
"P = [] for x,y in data: x = np.array(x)",
"= max(left.shape[0], right.shape[0]) w = left.shape[1] + right.shape[1] hoff =",
"some GUI plotting functionality. There are plenty of other ways",
"**kwargs) def moveWindow(*args,**kwargs): return def imshow(root,args,kwargs): image = cv2.cvtColor(output_frame, cv2.COLOR_BGR2RGB)",
"(280,640),margin = 25,name = \"data\",labels=[], skip = [], showmax =",
"= cv2.merge([r,g,b])[:,:-wd,] i = 0 P = [] for x,y",
"for ii in range(len(x)): if ii%skip[i] == 0: col =",
"UI could be built and imported into get_pulse.py instead. Opencv",
"def combine(left, right): \"\"\"Stack images horizontally. \"\"\" h = max(left.shape[0],",
"to opencv user interface methods (displaying image frames, event handling,",
"combine(bg,z[:,:,2]) z = cv2.merge([r,g,b])[:,:-wd,] i = 0 P = []",
"= 25,name = \"data\",labels=[], skip = [], showmax = [],",
"ss.format(x[ii]) cv2.putText(z,ss,(int(xx[ii]),int((i+1)*h)), cv2.FONT_HERSHEY_PLAIN,1,col) if showmax: if showmax[i]: col = (0,255,0)",
"be on left, aligned top, with right on right comb[:left.shape[0],:left.shape[1]]",
"= [], showmax = [], bg = None,label_ndigits = [],",
"w = left.shape[1] + right.shape[1] hoff = left.shape[0] shape =",
"i+=1 P.append(pts) except ValueError: pass #temporary \"\"\" #Polylines seems to",
"combine(left, right): \"\"\"Stack images horizontally. \"\"\" h = max(left.shape[0], right.shape[0])",
"comb = np.zeros(tuple(shape),left.dtype) # left will be on left, aligned",
"python, but this application uses cv2.imshow to do real-time data",
"instead. Opencv is used to perform much of the data",
"import numpy as np import Tkinter \"\"\" Wraps up some",
"ss = ss.format(x[ii]) cv2.putText(z,ss,(int(xx[ii]),int((i+1)*h)), cv2.FONT_HERSHEY_PLAIN,1,col) if showmax: if showmax[i]: col",
"defines some GUI plotting functionality. There are plenty of other",
"= np.zeros(tuple(shape),left.dtype) # left will be on left, aligned top,",
"ss = '{0:.%sf}' % label_ndigits[i] ss = ss.format(x[ii]) cv2.putText(z,ss,(int(xx[ii]),int((i+1)*h)), cv2.FONT_HERSHEY_PLAIN,1,col)",
"return cv2.resize(*args, **kwargs) def moveWindow(*args,**kwargs): return def imshow(root,args,kwargs): image =",
"= '{0:.%sf}' % label_ndigits[i] ss = ss.format(x[ii]) cv2.putText(z,ss,(int(xx[ii]),int((i+1)*h)), cv2.FONT_HERSHEY_PLAIN,1,col) if",
"is entirely independent of the data calculation functions, so it",
"could be built and imported into get_pulse.py instead. Opencv is",
"imported into get_pulse.py instead. Opencv is used to perform much",
"have some trouble rendering multiple polys for some people for",
"data analysis, but there is no reason it has to",
"into get_pulse.py instead. Opencv is used to perform much of",
"len(data) w = float(size[1]) h = size[0]/float(n_plots) z = np.zeros((size[0],size[1],3))",
"handle the UI as well. It just happens to be",
"(w-2*margin)*(x - x.min()) / (x.max() - x.min())+margin yy = (h-2*margin)*(y",
"can be replaced in the get_pulse.py application easily. \"\"\" def",
"(255,255,255) ss = '{0:.%sf}' % label_ndigits[i] ss = ss.format(x[ii]) cv2.putText(z,ss,(int(xx[ii]),int((i+1)*h)),",
"hoff = left.shape[0] shape = list(left.shape) shape[0] = h shape[1]",
"def waitKey(*args,**kwargs): return cv2.waitKey(*args,**kwargs) \"\"\" The rest of this file",
"interaction. This is entirely independent of the data calculation functions,",
"get_pulse.py instead. Opencv is used to perform much of the",
"Tkinter.Label(root, image=kwargs).pack() #return cv2.imshow(*args,**kwargs) def destroyWindow(*args,**kwargs): return cv2.destroyWindow(*args,**kwargs) def waitKey(*args,**kwargs):",
"return def imshow(root,args,kwargs): image = cv2.cvtColor(output_frame, cv2.COLOR_BGR2RGB) image = Image.fromarray(image)",
"cv2.putText(z,ss,(int(xx[ii]),int((yy[ii]))), cv2.FONT_HERSHEY_PLAIN,2,col) try: pts = np.array([[x_, y_] for x_, y_",
"GUI plotting functionality. There are plenty of other ways to",
"import cv2, time import numpy as np import Tkinter \"\"\"",
"plenty of other ways to do simple x-y data plots",
"ii = np.argmax(-y) ss = '{0:.%sf} %s' % (showmax_digits[i], showmax[i])",
"interface methods (displaying image frames, event handling, etc). If desired,",
"0 P = [] for x,y in data: x =",
"to do simple x-y data plots in python, but this",
"Opencv is used to perform much of the data analysis,",
"r = combine(bg,z[:,:,0]) g = combine(bg,z[:,:,1]) b = combine(bg,z[:,:,2]) z",
"our purposes. \"\"\" def resize(*args, **kwargs): return cv2.resize(*args, **kwargs) def",
"rendering multiple polys for some people for p in P:",
"cv2.resize(*args, **kwargs) def moveWindow(*args,**kwargs): return def imshow(root,args,kwargs): image = cv2.cvtColor(output_frame,",
"do simple x-y data plots in python, but this application",
"#hack-y alternative: for p in P: for i in range(len(p)-1):",
"get_pulse.py application easily. \"\"\" def combine(left, right): \"\"\"Stack images horizontally.",
"the data analysis, but there is no reason it has",
"if showmax: if showmax[i]: col = (0,255,0) ii = np.argmax(-y)",
") bg = cv2.resize(bg,(wd,int(h))) if len(bg.shape) == 3: r =",
"y.min())+margin + i*h mx = max(yy) if labels: if labels[i]:",
"this file defines some GUI plotting functionality. There are plenty",
"= combine(bg,z[:,:,1]) b = combine(bg,z[:,:,2]) z = cv2.merge([r,g,b])[:,:-wd,] i =",
"#temporary \"\"\" #Polylines seems to have some trouble rendering multiple",
"comb def plotXY(data,size = (280,640),margin = 25,name = \"data\",labels=[], skip",
"[p], False, (255,255,255),1) \"\"\" #hack-y alternative: for p in P:",
"well. It just happens to be very effective for our",
"= int(bg.shape[1]/bg.shape[0]*h ) bg = cv2.resize(bg,(wd,int(h))) if len(bg.shape) == 3:",
"There are plenty of other ways to do simple x-y",
"cv2.cvtColor(output_frame, cv2.COLOR_BGR2RGB) image = Image.fromarray(image) image = ImageTk.PhotoImage(image) return Tkinter.Label(root,",
"% label_ndigits[i] ss = ss.format(x[ii]) cv2.putText(z,ss,(int(xx[ii]),int((i+1)*h)), cv2.FONT_HERSHEY_PLAIN,1,col) if showmax: if",
"The rest of this file defines some GUI plotting functionality.",
"polys for some people for p in P: cv2.polylines(z, [p],",
"def imshow(root,args,kwargs): image = cv2.cvtColor(output_frame, cv2.COLOR_BGR2RGB) image = Image.fromarray(image) image",
"image = cv2.cvtColor(output_frame, cv2.COLOR_BGR2RGB) image = Image.fromarray(image) image = ImageTk.PhotoImage(image)",
"If desired, an alternative UI could be built and imported",
"other ways to do simple x-y data plots in python,",
"some people for p in P: cv2.polylines(z, [p], False, (255,255,255),1)",
"w comb = np.zeros(tuple(shape),left.dtype) # left will be on left,",
"return n_plots = len(data) w = float(size[1]) h = size[0]/float(n_plots)",
"(y.max() - y.min())+margin + i*h mx = max(yy) if labels:",
"file defines some GUI plotting functionality. There are plenty of",
"import Tkinter \"\"\" Wraps up some interfaces to opencv user",
"= combine(bg,z[:,:,0]) g = combine(bg,z[:,:,1]) b = combine(bg,z[:,:,2]) z =",
"np import Tkinter \"\"\" Wraps up some interfaces to opencv",
"if labels[i]: for ii in range(len(x)): if ii%skip[i] == 0:",
"showmax[i]) cv2.putText(z,ss,(int(xx[ii]),int((yy[ii]))), cv2.FONT_HERSHEY_PLAIN,2,col) try: pts = np.array([[x_, y_] for x_,",
"\"data\",labels=[], skip = [], showmax = [], bg = None,label_ndigits",
"= size[0]/float(n_plots) z = np.zeros((size[0],size[1],3)) if isinstance(bg,np.ndarray): wd = int(bg.shape[1]/bg.shape[0]*h",
"(255,255,255),1) \"\"\" #hack-y alternative: for p in P: for i",
"col = (0,255,0) ii = np.argmax(-y) ss = '{0:.%sf} %s'",
"= left comb[:right.shape[0],left.shape[1]:] = right return comb def plotXY(data,size =",
"= 0 P = [] for x,y in data: x",
"easily. \"\"\" def combine(left, right): \"\"\"Stack images horizontally. \"\"\" h",
"image frames, event handling, etc). If desired, an alternative UI",
"list(left.shape) shape[0] = h shape[1] = w comb = np.zeros(tuple(shape),left.dtype)",
"len(bg.shape) == 3: r = combine(bg[:,:,0],z[:,:,0]) g = combine(bg[:,:,1],z[:,:,1]) b",
"(showmax_digits[i], showmax[i]) ss = ss.format(x[ii]) #\"%0.0f %s\" % (x[ii], showmax[i])",
"max(yy) if labels: if labels[i]: for ii in range(len(x)): if",
"-np.array(y) xx = (w-2*margin)*(x - x.min()) / (x.max() - x.min())+margin",
"pts = np.array([[x_, y_] for x_, y_ in zip(xx,yy)],np.int32) i+=1",
"\"\"\" The rest of this file defines some GUI plotting",
"for some people for p in P: cv2.polylines(z, [p], False,",
"= combine(bg,z[:,:,2]) z = cv2.merge([r,g,b])[:,:-wd,] i = 0 P =",
"== 0: col = (255,255,255) ss = '{0:.%sf}' % label_ndigits[i]",
"np.array([[x_, y_] for x_, y_ in zip(xx,yy)],np.int32) i+=1 P.append(pts) except",
"(0,255,0) ii = np.argmax(-y) ss = '{0:.%sf} %s' % (showmax_digits[i],",
"= ImageTk.PhotoImage(image) return Tkinter.Label(root, image=kwargs).pack() #return cv2.imshow(*args,**kwargs) def destroyWindow(*args,**kwargs): return",
"cv2.imshow to do real-time data plotting and handle user interaction.",
"left comb[:right.shape[0],left.shape[1]:] = right return comb def plotXY(data,size = (280,640),margin",
"np.zeros((size[0],size[1],3)) if isinstance(bg,np.ndarray): wd = int(bg.shape[1]/bg.shape[0]*h ) bg = cv2.resize(bg,(wd,int(h)))",
"= max(yy) if labels: if labels[i]: for ii in range(len(x)):",
"'{0:.%sf} %s' % (showmax_digits[i], showmax[i]) ss = ss.format(x[ii]) #\"%0.0f %s\"",
"#Polylines seems to have some trouble rendering multiple polys for",
"some trouble rendering multiple polys for some people for p",
"ways to do simple x-y data plots in python, but",
"data: if len(x) < 2 or len(y) < 2: return",
"max(left.shape[0], right.shape[0]) w = left.shape[1] + right.shape[1] hoff = left.shape[0]",
"w = float(size[1]) h = size[0]/float(n_plots) z = np.zeros((size[0],size[1],3)) if",
"[], showmax_digits=[]): for x,y in data: if len(x) < 2",
"of other ways to do simple x-y data plots in",
"x,y in data: if len(x) < 2 or len(y) <",
"handle user interaction. This is entirely independent of the data",
"user interface methods (displaying image frames, event handling, etc). If",
"for x,y in data: x = np.array(x) y = -np.array(y)",
"ii in range(len(x)): if ii%skip[i] == 0: col = (255,255,255)",
"image = ImageTk.PhotoImage(image) return Tkinter.Label(root, image=kwargs).pack() #return cv2.imshow(*args,**kwargs) def destroyWindow(*args,**kwargs):",
"and imported into get_pulse.py instead. Opencv is used to perform",
"it has to be used to handle the UI as",
"opencv user interface methods (displaying image frames, event handling, etc).",
"top, with right on right comb[:left.shape[0],:left.shape[1]] = left comb[:right.shape[0],left.shape[1]:] =",
"- y.min())+margin + i*h mx = max(yy) if labels: if",
"in python, but this application uses cv2.imshow to do real-time",
"= (h-2*margin)*(y - y.min()) / (y.max() - y.min())+margin + i*h",
"multiple polys for some people for p in P: cv2.polylines(z,",
"event handling, etc). If desired, an alternative UI could be",
"right.shape[1] hoff = left.shape[0] shape = list(left.shape) shape[0] = h",
"user interaction. This is entirely independent of the data calculation",
"showmax[i]: col = (0,255,0) ii = np.argmax(-y) ss = '{0:.%sf}",
"float(size[1]) h = size[0]/float(n_plots) z = np.zeros((size[0],size[1],3)) if isinstance(bg,np.ndarray): wd",
"= np.argmax(-y) ss = '{0:.%sf} %s' % (showmax_digits[i], showmax[i]) ss",
"(x[ii], showmax[i]) cv2.putText(z,ss,(int(xx[ii]),int((yy[ii]))), cv2.FONT_HERSHEY_PLAIN,2,col) try: pts = np.array([[x_, y_] for",
"left.shape[0] shape = list(left.shape) shape[0] = h shape[1] = w",
"left.shape[1] + right.shape[1] hoff = left.shape[0] shape = list(left.shape) shape[0]",
"be used to handle the UI as well. It just",
"seems to have some trouble rendering multiple polys for some",
"= [], bg = None,label_ndigits = [], showmax_digits=[]): for x,y",
"much of the data analysis, but there is no reason",
"This is entirely independent of the data calculation functions, so",
"2 or len(y) < 2: return n_plots = len(data) w",
"r = combine(bg[:,:,0],z[:,:,0]) g = combine(bg[:,:,1],z[:,:,1]) b = combine(bg[:,:,2],z[:,:,2]) else:",
"= (0,255,0) ii = np.argmax(-y) ss = '{0:.%sf} %s' %",
"mx = max(yy) if labels: if labels[i]: for ii in",
"if len(bg.shape) == 3: r = combine(bg[:,:,0],z[:,:,0]) g = combine(bg[:,:,1],z[:,:,1])",
"of this file defines some GUI plotting functionality. There are",
"in range(len(x)): if ii%skip[i] == 0: col = (255,255,255) ss",
"for p in P: cv2.polylines(z, [p], False, (255,255,255),1) \"\"\" #hack-y",
"[], showmax = [], bg = None,label_ndigits = [], showmax_digits=[]):",
"left will be on left, aligned top, with right on",
"of the data analysis, but there is no reason it",
"to have some trouble rendering multiple polys for some people",
"x.min()) / (x.max() - x.min())+margin yy = (h-2*margin)*(y - y.min())",
"p in P: for i in range(len(p)-1): cv2.line(z,tuple(p[i]),tuple(p[i+1]), (255,255,255),1) return",
"application easily. \"\"\" def combine(left, right): \"\"\"Stack images horizontally. \"\"\"",
"#\"%0.0f %s\" % (x[ii], showmax[i]) cv2.putText(z,ss,(int(xx[ii]),int((yy[ii]))), cv2.FONT_HERSHEY_PLAIN,2,col) try: pts =",
"P: cv2.polylines(z, [p], False, (255,255,255),1) \"\"\" #hack-y alternative: for p",
"purposes. \"\"\" def resize(*args, **kwargs): return cv2.resize(*args, **kwargs) def moveWindow(*args,**kwargs):",
"as well. It just happens to be very effective for",
"do real-time data plotting and handle user interaction. This is",
"will be on left, aligned top, with right on right",
"- y.min()) / (y.max() - y.min())+margin + i*h mx =",
"col = (255,255,255) ss = '{0:.%sf}' % label_ndigits[i] ss =",
"for our purposes. \"\"\" def resize(*args, **kwargs): return cv2.resize(*args, **kwargs)",
"def resize(*args, **kwargs): return cv2.resize(*args, **kwargs) def moveWindow(*args,**kwargs): return def",
"y = -np.array(y) xx = (w-2*margin)*(x - x.min()) / (x.max()",
"ss = '{0:.%sf} %s' % (showmax_digits[i], showmax[i]) ss = ss.format(x[ii])",
"< 2: return n_plots = len(data) w = float(size[1]) h",
"n_plots = len(data) w = float(size[1]) h = size[0]/float(n_plots) z",
"for p in P: for i in range(len(p)-1): cv2.line(z,tuple(p[i]),tuple(p[i+1]), (255,255,255),1)",
"= np.array(x) y = -np.array(y) xx = (w-2*margin)*(x - x.min())",
"= list(left.shape) shape[0] = h shape[1] = w comb =",
"to do real-time data plotting and handle user interaction. This",
"\"\"\" def combine(left, right): \"\"\"Stack images horizontally. \"\"\" h =",
"right.shape[0]) w = left.shape[1] + right.shape[1] hoff = left.shape[0] shape",
"analysis, but there is no reason it has to be",
"plotting and handle user interaction. This is entirely independent of",
"frames, event handling, etc). If desired, an alternative UI could",
"if isinstance(bg,np.ndarray): wd = int(bg.shape[1]/bg.shape[0]*h ) bg = cv2.resize(bg,(wd,int(h))) if",
"x = np.array(x) y = -np.array(y) xx = (w-2*margin)*(x -",
"\"\"\" Wraps up some interfaces to opencv user interface methods",
"return cv2.destroyWindow(*args,**kwargs) def waitKey(*args,**kwargs): return cv2.waitKey(*args,**kwargs) \"\"\" The rest of",
"in data: x = np.array(x) y = -np.array(y) xx =",
"x-y data plots in python, but this application uses cv2.imshow",
"x.min())+margin yy = (h-2*margin)*(y - y.min()) / (y.max() - y.min())+margin",
"etc). If desired, an alternative UI could be built and",
"left, aligned top, with right on right comb[:left.shape[0],:left.shape[1]] = left",
"%s' % (showmax_digits[i], showmax[i]) ss = ss.format(x[ii]) #\"%0.0f %s\" %",
"cv2.merge([r,g,b])[:,:-wd,] i = 0 P = [] for x,y in",
"application uses cv2.imshow to do real-time data plotting and handle",
"ss = ss.format(x[ii]) #\"%0.0f %s\" % (x[ii], showmax[i]) cv2.putText(z,ss,(int(xx[ii]),int((yy[ii]))), cv2.FONT_HERSHEY_PLAIN,2,col)",
"handling, etc). If desired, an alternative UI could be built",
"= combine(bg[:,:,2],z[:,:,2]) else: r = combine(bg,z[:,:,0]) g = combine(bg,z[:,:,1]) b",
"entirely independent of the data calculation functions, so it can",
"= combine(bg[:,:,1],z[:,:,1]) b = combine(bg[:,:,2],z[:,:,2]) else: r = combine(bg,z[:,:,0]) g",
"replaced in the get_pulse.py application easily. \"\"\" def combine(left, right):",
"= '{0:.%sf} %s' % (showmax_digits[i], showmax[i]) ss = ss.format(x[ii]) #\"%0.0f",
"+ right.shape[1] hoff = left.shape[0] shape = list(left.shape) shape[0] =",
"effective for our purposes. \"\"\" def resize(*args, **kwargs): return cv2.resize(*args,",
"= None,label_ndigits = [], showmax_digits=[]): for x,y in data: if",
"(h-2*margin)*(y - y.min()) / (y.max() - y.min())+margin + i*h mx",
"real-time data plotting and handle user interaction. This is entirely",
"interfaces to opencv user interface methods (displaying image frames, event",
"= len(data) w = float(size[1]) h = size[0]/float(n_plots) z =",
"data plotting and handle user interaction. This is entirely independent",
"happens to be very effective for our purposes. \"\"\" def",
"% (x[ii], showmax[i]) cv2.putText(z,ss,(int(xx[ii]),int((yy[ii]))), cv2.FONT_HERSHEY_PLAIN,2,col) try: pts = np.array([[x_, y_]",
"the data calculation functions, so it can be replaced in",
"= left.shape[1] + right.shape[1] hoff = left.shape[0] shape = list(left.shape)",
"comb[:left.shape[0],:left.shape[1]] = left comb[:right.shape[0],left.shape[1]:] = right return comb def plotXY(data,size",
"= h shape[1] = w comb = np.zeros(tuple(shape),left.dtype) # left",
"cv2.resize(bg,(wd,int(h))) if len(bg.shape) == 3: r = combine(bg[:,:,0],z[:,:,0]) g =",
"used to handle the UI as well. It just happens",
"bg = None,label_ndigits = [], showmax_digits=[]): for x,y in data:",
"be built and imported into get_pulse.py instead. Opencv is used",
"Tkinter \"\"\" Wraps up some interfaces to opencv user interface",
"uses cv2.imshow to do real-time data plotting and handle user",
"to be very effective for our purposes. \"\"\" def resize(*args,",
"len(x) < 2 or len(y) < 2: return n_plots =",
"**kwargs): return cv2.resize(*args, **kwargs) def moveWindow(*args,**kwargs): return def imshow(root,args,kwargs): image",
"z = cv2.merge([r,g,b])[:,:-wd,] i = 0 P = [] for",
"cv2, time import numpy as np import Tkinter \"\"\" Wraps",
"right): \"\"\"Stack images horizontally. \"\"\" h = max(left.shape[0], right.shape[0]) w",
"this application uses cv2.imshow to do real-time data plotting and",
"showmax = [], bg = None,label_ndigits = [], showmax_digits=[]): for",
"be very effective for our purposes. \"\"\" def resize(*args, **kwargs):",
"of the data calculation functions, so it can be replaced",
"yy = (h-2*margin)*(y - y.min()) / (y.max() - y.min())+margin +"
] |
[
"a training corpus, using one of the TaggerTrainers available. \"\"\"",
"# based on previous (nltk2) version by # <NAME>, <NAME>,",
"Templates ###################################################################### @jsontags.register_tag class Word(Feature): \"\"\" Feature which examines the",
"the positions where it might apply positions = tag_to_positions.get(rule.original_tag, [])",
"are created by learning rules from a training corpus, using",
"is also an unweighted measure (just counting the rules). This",
"try to apply rules at # positions that have the",
"def print_train_stats(): print(\"TEMPLATE STATISTICS (TRAIN) {0} templates, {1} rules)\".format( len(template_counts),",
"otherwise convenient Counter.most_common() unfortunately # does not break ties deterministically",
"Brill's transformational rule-based tagger. Brill taggers use an initial tagger",
"| {3:4d} {4:.3f} |{5:4d} {6:.3f} | {7:s}\".format( tid, testscore, testscore/tottestscores,",
"entire corpus (rather than all rules to a single sequence).",
"\"final: {finalerrors:5d} {finalacc:.4f} \".format(**train_stats)) weighted_testcounts = Counter() for (tid, score)",
"each tag to a list of the # indices of",
"({tokencount:7d} tokens) initial {initialerrors:5d} {initialacc:.4f} \" \"final: {finalerrors:5d} {finalacc:.4f} \".format(**train_stats))",
"order errors = [testing_stats['initialerrors']] for rule in self._rules: for tagged_tokens",
"use batch_tag() instead :param sequences: lists of token sequences (sentences,",
"nltkdemo18() + [ Template(Word([-1]), Pos([1])), Template(Pos([-1]), Word([1])), Template(Word([-1]), Word([0]), Pos([1])),",
"positions of tags that # were modified. for i in",
"often, Brill taggers are created by learning rules from a",
"later use :type training_stats: dict \"\"\" self._initial_tagger = initial_tagger self._rules",
"weighted by score) to the performance on the test set.",
"-1])), Template(Pos([1]), Word([0]), Word([1])), Template(Pos([1]), Word([0]), Word([-1])), Template(Pos([-1]), Word([-1]), Word([0])),",
":param statistic: name of statistic :type statistic: str :return: some",
"There is also an unweighted measure (just counting the rules).",
"for r in self._rules] train_stats = self.train_stats() trainscores = train_stats['rulescores']",
"dictionary of all available statistics if no name given :param",
"Template(Word([1])), Template(Word([-1])), Template(Pos([-1]), Pos([1])), Template(Pos([1]), Pos([2])), Template(Pos([-1]), Pos([-2])), Template(Pos([1])), Template(Pos([-1])),",
"\"\"\" Print the available template sets in this demo, with",
"tagger :type initial_tagger: TaggerI :param rules: An ordered list of",
"= Counter() for (tid, score) in zip(tids, trainscores): weighted_traincounts[tid] +=",
"inspect import sys # a bit of magic to get",
"used instead. There is also an unweighted measure (just counting",
"initial tagger (such as ``tag.DefaultTagger``) to assign an initial tag",
"list of strings :param gold: the gold standard :type gold:",
"ordered list of rule scores (one for each rule)) \"\"\"",
"implementation cannot.) \"\"\" return [ Template(Word([0]), Word([1]), Word([2])), Template(Word([-1]), Word([0]),",
"(just counting the rules). This is less informative, though, as",
"# det_tplsort() is for deterministic sorting; # the otherwise convenient",
"learning rules from a training corpus, using one of the",
"also an unweighted measure (just counting the rules). This is",
"return tagged_tokens def print_template_statistics(self, test_stats=None, printunused=True): \"\"\" Print a list",
"usedtpls] print(\"UNUSED TEMPLATES ({0})\".format(len(unused))) for (tid, tpl) in unused: print(\"{0:03d}",
"Word([-1])), Template(Pos([-1]), Word([-1]), Word([0])), Template(Pos([-1]), Word([0]), Word([1])), Template(Pos([-2]), Pos([-1])), Template(Pos([1]),",
"{finalerrors:5d} {finalacc:.4f} \".format(**train_stats)) weighted_testcounts = Counter() for (tid, score) in",
"the postagging task of the fntbl distribution http://www.cs.jhu.edu/~rflorian/fntbl/ (37 is",
"by applying each rule to the entire corpus (rather than",
"\"\"\" return [ Template(Word([0]), Word([1]), Word([2])), Template(Word([-1]), Word([0]), Word([1])), Template(Word([0]),",
") print(s) def print_unused_templates(): usedtpls = set(int(tid) for tid in",
"with the positions of tags that # were modified. for",
"\"\"\"@return: The given token's tag.\"\"\" return tokens[index][1] def nltkdemo18(): \"\"\"",
"# positions that have the desired original tag. for rule",
"individual tokens. These transformation rules are specified by the ``TagRule``",
"\"#ID | Score (test) | Score (train) | #Rules |",
"comparison with nltkdemo18) \"\"\" return nltkdemo18() + [ Template(Word([-1]), Pos([1])),",
"does not break ties deterministically # between python versions and",
"\"\"\" Feature which examines the text (word) of nearby tokens.",
"in this module templatesets = inspect.getmembers(sys.modules[__name__], inspect.isfunction) for (name, obj)",
"testing_stats['initialerrors'] = counterrors(tagged_tokenses) testing_stats['initialacc'] = 1 - testing_stats['initialerrors']/testing_stats['tokencount'] # Apply",
"\"\"\" :param initial_tagger: The initial tagger :type initial_tagger: TaggerI :param",
"{7:s}\".format( tid, testscore, testscore/tottestscores, weighted_traincounts[tid], weighted_traincounts[tid]/tottrainscores, template_counts[tid], template_counts[tid]/len(tids), Template.ALLTEMPLATES[int(tid)], )",
"Print a list of all templates, ranked according to efficiency.",
"tid not in usedtpls] print(\"UNUSED TEMPLATES ({0})\".format(len(unused))) for (tid, tpl)",
"tagger has learnt :return: the ordered list of transformation rules",
"rule in self._rules: # Find the positions where it might",
"ordered list of transformational rules to correct the tags of",
"times for N rules) -- usually you would not care",
"transformation rules that correct the initial tagging :rtype: list of",
"Pos([1])), Template(Word([-1])), Template(Word([1])), Template(Word([-2])), Template(Word([2])), Template(Word([-2, -1])), Template(Word([1, 2])), Template(Word([-3,",
"on the test set. If no test_stats, then statistics collected",
"list of strings :returns: tuple of (tagged_sequences, ordered list of",
"This is less informative, though, as many low-score rules will",
"list of transformation rules that this tagger has learnt :return:",
"s = \"{0:s} |{1:5d} {2:6.3f} | {3:4d} {4:.3f} |{5:4d} {6:.3f}",
"2, 3])), Template(Word([-3, -2, -1])), Template(Word([0]), Pos([2])), Template(Word([0]), Pos([-2])), Template(Word([0]),",
"Template(Pos([1]), Pos([2]), Word([1])) ] def brill24(): \"\"\" Return 24 templates",
"'nltk.tag.BrillTagger' def __init__(self, initial_tagger, rules, training_stats=None): \"\"\" :param initial_tagger: The",
"of the seminal TBL paper, Brill (1995) \"\"\" return [",
"-2, -1])), Template(Pos([1, 2, 3])), Template(Pos([-1]), Pos([1])), Template(Pos([-2]), Pos([-1])), Template(Pos([1]),",
"tokens. These transformation rules are specified by the ``TagRule`` interface.",
"@staticmethod def extract_property(tokens, index): \"\"\"@return: The given token's text.\"\"\" return",
"for each rule)) \"\"\" def counterrors(xs): return sum(t[1] != g[1]",
"weighted_traincounts[tid], weighted_traincounts[tid]/tottrainscores, template_counts[tid], template_counts[tid]/len(tids), Template.ALLTEMPLATES[int(tid)], ) print(s) def print_unused_templates(): usedtpls",
"Template(Word([0]), Word([-2])), Template(Word([1, 2])), Template(Word([-2, -1])), Template(Word([1, 2, 3])), Template(Word([-3,",
"each rule to the entire corpus (rather than all rules",
"* len(head), sep=\"\") train_tplscores = sorted(weighted_traincounts.items(), key=det_tplsort, reverse=True) for (tid,",
"no name given :param statistic: name of statistic :type statistic:",
"The initial tagger :type initial_tagger: TaggerI :param rules: An ordered",
"_training_stats) def rules(self): \"\"\" Return the ordered list of transformation",
"tpl) in unused: print(\"{0:03d} {1:s}\".format(tid, str(tpl))) if test_stats is None:",
"available template sets in this demo, with a short description\"",
"weighted_traincounts[tid] += score tottrainscores = sum(trainscores) # det_tplsort() is for",
"(1995) \"\"\" return [ Template(Pos([-1])), Template(Pos([1])), Template(Pos([-2])), Template(Pos([2])), Template(Pos([-2, -1])),",
"from the original nltk demo, in multi-feature syntax \"\"\" return",
"tottestscores = sum(testscores) head = \"#ID | Score (test) |",
"corpus, using one of the TaggerTrainers available. \"\"\" json_tag =",
"to the entire corpus, in order errors = [testing_stats['initialerrors']] for",
"sequence to a text; and then apply an ordered list",
"print(head, \"\\n\", \"-\" * len(head), sep=\"\") test_tplscores = sorted(weighted_testcounts.items(), key=det_tplsort,",
"Template(Word([0]), Word([-1]), Pos([-1])), Template(Word([0]), Word([1]), Pos([1])), ] def describe_template_sets(): \"\"\"",
"1])), Template(Word([0])), Template(Word([-1]), Pos([-1])), Template(Word([1]), Pos([1])), Template(Word([0]), Word([-1]), Pos([-1])), Template(Word([0]),",
"is after excluding a handful which do not condition on",
"print(\"TEST ({tokencount:7d} tokens) initial {initialerrors:5d} {initialacc:.4f} \" \"final: {finalerrors:5d} {finalacc:.4f}",
"= sum(testscores) head = \"#ID | Score (test) | Score",
"in zip(*pair)) testing_stats = {} testing_stats['tokencount'] = sum(len(t) for t",
"<http://nltk.org/> # For license information, see LICENSE.TXT from __future__ import",
"\"\"\" tids = [r.templateid for r in self._rules] train_stats =",
"2, 3])), Template(Pos([-1]), Pos([1])), Template(Word([-1])), Template(Word([1])), Template(Word([-2])), Template(Word([2])), Template(Word([-2, -1])),",
"Word([1]), Pos([1])), ] def describe_template_sets(): \"\"\" Print the available template",
"0])), Template(Word([0, 1])), Template(Word([0])), Template(Word([-1]), Pos([-1])), Template(Word([1]), Pos([1])), Template(Word([0]), Word([-1]),",
"the current nltk implementation cannot.) \"\"\" return [ Template(Word([0]), Word([1]),",
"None \"\"\" tids = [r.templateid for r in self._rules] train_stats",
"\" \"final: {finalerrors:5d} {finalacc:.4f} \".format(**train_stats)) head = \"#ID | Score",
"list of transformation rules that correct the initial tagging :rtype:",
"# Apply each rule to the entire corpus, in order",
"Pos([1])), Template(Word([0]), Pos([-1])), Template(Word([0])), Template(Word([-2])), Template(Word([2])), Template(Word([1])), Template(Word([-1])), Template(Pos([-1]), Pos([1])),",
"return [ Template(Pos([-1])), Template(Pos([1])), Template(Pos([-2])), Template(Pos([2])), Template(Pos([-2, -1])), Template(Pos([1, 2])),",
"all unused templates :type printunused: bool :return: None :rtype: None",
"batch_tag_incremental(self, sequences, gold): \"\"\" Tags by applying each rule to",
"Pos([2]), Word([1])) ] def brill24(): \"\"\" Return 24 templates of",
"Rules \"\"\" return self._rules def train_stats(self, statistic=None): \"\"\" Return a",
"Template(Word([0])), Template(Word([-1]), Pos([-1])), Template(Word([1]), Pos([1])), Template(Word([0]), Word([-1]), Pos([-1])), Template(Word([0]), Word([1]),",
"to be tagged :type sequences: list of list of strings",
"Template(Pos([1, 2])), Template(Pos([-3, -2, -1])), Template(Pos([-2, -1])), Template(Pos([1]), Word([0]), Word([1])),",
"sep=\"\") train_tplscores = sorted(weighted_traincounts.items(), key=det_tplsort, reverse=True) for (tid, trainscore) in",
"self._initial_tagger.tag(tokens) # Create a dictionary that maps each tag to",
"text; and then apply an ordered list of transformational rules",
"any index, so will traverse the entire corpus N times",
"= rule.apply(tagged_tokens, positions) # Update tag_to_positions with the positions of",
"testing_stats = {} testing_stats['tokencount'] = sum(len(t) for t in sequences)",
"# Copyright (C) 2001-2018 NLTK Project # Author: <NAME> <<EMAIL>>",
"a list of all unused templates :type printunused: bool :return:",
"(one for each rule)) \"\"\" def counterrors(xs): return sum(t[1] !=",
"#Rules | Template\" print(head, \"\\n\", \"-\" * len(head), sep=\"\") test_tplscores",
"initial {initialerrors:5d} {initialacc:.4f} \" \"final: {finalerrors:5d} {finalacc:.4f} \".format(**train_stats)) head =",
"# Brill Templates ###################################################################### @jsontags.register_tag class Word(Feature): \"\"\" Feature which",
"assign an initial tag sequence to a text; and then",
"(train) | #Rules | Template\" print(head, \"\\n\", \"-\" * len(head),",
"entire corpus, in order errors = [testing_stats['initialerrors']] for rule in",
"{2:6.3f} | {3:4d} {4:.3f} |{5:4d} {6:.3f} | {7:s}\".format( tid, testscore,",
"<NAME> <<EMAIL>> # based on previous (nltk2) version by #",
"printunused: bool :return: None :rtype: None \"\"\" tids = [r.templateid",
"task of the fntbl distribution http://www.cs.jhu.edu/~rflorian/fntbl/ (37 is after excluding",
"{finalacc:.4f} \".format(**train_stats)) head = \"#ID | Score (train) | #Rules",
"class Word(Feature): \"\"\" Feature which examines the text (word) of",
"zip(errors, errors[1:])] testing_stats['finalerrors'] = errors[-1] testing_stats['finalacc'] = 1 - testing_stats['finalerrors']/testing_stats['tokencount']",
"2])), Template(Pos([-3, -2, -1])), Template(Pos([1, 2, 3])), Template(Pos([-1]), Pos([1])), Template(Pos([-2]),",
"[testing_stats['initialerrors']] for rule in self._rules: for tagged_tokens in tagged_tokenses: rule.apply(tagged_tokens)",
"def print_unused_templates(): usedtpls = set(int(tid) for tid in tids) unused",
"\" \\ \"{0} train scores for {1} rules\".format(trainscores, tids) template_counts",
"= Counter() for (tid, score) in zip(tids, testscores): weighted_testcounts[tid] +=",
"Word([1]), Word([2])), Template(Word([-1]), Word([0]), Word([1])), Template(Word([0]), Word([-1])), Template(Word([0]), Word([1])), Template(Word([0]),",
"of transformation rules that correct the initial tagging :rtype: list",
"so will traverse the entire corpus N times for N",
"for i in changed: tag_to_positions[rule.original_tag].remove(i) tag_to_positions[rule.replacement_tag].add(i) return tagged_tokens def print_template_statistics(self,",
"fntbl distribution http://www.cs.jhu.edu/~rflorian/fntbl/ (37 is after excluding a handful which",
"scores for {1} rules\".format(trainscores, tids) template_counts = Counter(tids) weighted_traincounts =",
"tags of individual tokens. These transformation rules are specified by",
"def det_tplsort(tpl_value): return (tpl_value[1], repr(tpl_value[0])) def print_train_stats(): print(\"TEMPLATE STATISTICS (TRAIN)",
"print(\"{0:03d} {1:s}\".format(tid, str(tpl))) if test_stats is None: print_train_stats() else: print_testtrain_stats()",
"in zip(tids, trainscores): weighted_traincounts[tid] += score tottrainscores = sum(trainscores) #",
"\"describe_template_sets\": continue print(name, obj.__doc__, \"\\n\") ###################################################################### # The Brill Tagger",
"TEMPLATES ({0})\".format(len(unused))) for (tid, tpl) in unused: print(\"{0:03d} {1:s}\".format(tid, str(tpl)))",
"training corpus, using one of the TaggerTrainers available. \"\"\" json_tag",
"each rule)) \"\"\" def counterrors(xs): return sum(t[1] != g[1] for",
"nltk.tbl import Feature, Template from nltk import jsontags ###################################################################### #",
"Word([1])), Template(Word([-1]), Word([0]), Pos([1])), Template(Pos([-1]), Word([0]), Word([1])), Template(Pos([-1]), Word([0]), Pos([1])),",
"score tottrainscores = sum(trainscores) # det_tplsort() is for deterministic sorting;",
"TBL paper, Brill (1995) \"\"\" return [ Template(Pos([-1])), Template(Pos([1])), Template(Pos([-2])),",
":type initial_tagger: TaggerI :param rules: An ordered list of transformation",
"None :rtype: None \"\"\" tids = [r.templateid for r in",
"\"\"\" self._initial_tagger = initial_tagger self._rules = tuple(rules) self._training_stats = training_stats",
"def train_stats(self, statistic=None): \"\"\" Return a named statistic collected during",
"more often, Brill taggers are created by learning rules from",
"the available template sets in this demo, with a short",
"obj) in templatesets: if name == \"describe_template_sets\": continue print(name, obj.__doc__,",
"2, 3])), Template(Word([-1]), Word([1])), ] def nltkdemo18plus(): \"\"\" Return 18",
"numbers) :param printunused: if True, print a list of all",
"score tottestscores = sum(testscores) head = \"#ID | Score (test)",
"if statistic is None: return self._training_stats else: return self._training_stats.get(statistic) def",
"list of list of strings :returns: tuple of (tagged_sequences, ordered",
"def describe_template_sets(): \"\"\" Print the available template sets in this",
"with a short description\" \"\"\" import inspect import sys #",
"{initialacc:.4f} \" \"final: {finalerrors:5d} {finalacc:.4f} \".format(**train_stats)) head = \"#ID |",
"3])), Template(Pos([-1]), Pos([1])), Template(Word([-1])), Template(Word([1])), Template(Word([-2])), Template(Word([2])), Template(Word([-2, -1])), Template(Word([1,",
"print_train_stats() else: print_testtrain_stats() print() if printunused: print_unused_templates() print() def batch_tag_incremental(self,",
"Return 37 templates taken from the postagging task of the",
"deterministic sorting; # the otherwise convenient Counter.most_common() unfortunately # does",
"which do not condition on Pos[0]; fntbl can do that",
"print a list of all unused templates :type printunused: bool",
"templates, {1} rules)\".format( len(template_counts), len(tids)) ) print(\"TRAIN ({tokencount:7d} tokens) initial",
"for N rules) -- usually you would not care about",
"tag_to_positions with the positions of tags that # were modified.",
"applications) to be tagged :type sequences: list of list of",
"Template(Pos([1])), Template(Pos([-1])), Template(Pos([-2])), Template(Pos([2])), Template(Pos([1, 2, 3])), Template(Pos([1, 2])), Template(Pos([-3,",
"\"\"\" Return a named statistic collected during training, or a",
"a dictionary of all available statistics if no name given",
"the text (word) of nearby tokens. \"\"\" json_tag = 'nltk.tag.brill.Word'",
"Template(Pos([-3, -2, -1])), Template(Pos([1, 2, 3])), Template(Pos([-1]), Pos([1])), Template(Pos([-2]), Pos([-1])),",
"({tokencount:7d} tokens) initial {initialerrors:5d} {initialacc:.4f} \" \"final: {finalerrors:5d} {finalacc:.4f} \".format(**test_stats))",
"print_testtrain_stats(): testscores = test_stats['rulescores'] print(\"TEMPLATE STATISTICS (TEST AND TRAIN) ({0}",
"BrillTagger(TaggerI): \"\"\" Brill's transformational rule-based tagger. Brill taggers use an",
"2001-2018 NLTK Project # Author: <NAME> <<EMAIL>> # based on",
"transformational rules; but more often, Brill taggers are created by",
"Score (train) | #Rules | Template\" print(head, \"\\n\", \"-\" *",
"for pair in zip(xs, gold) for (t, g) in zip(*pair))",
":rtype: None \"\"\" tids = [r.templateid for r in self._rules]",
"(but usually a number) \"\"\" if statistic is None: return",
"about statistics for individual rules and thus use batch_tag() instead",
"corpus, in order errors = [testing_stats['initialerrors']] for rule in self._rules:",
"_rules, _training_stats) def rules(self): \"\"\" Return the ordered list of",
"cross-version tests def det_tplsort(tpl_value): return (tpl_value[1], repr(tpl_value[0])) def print_train_stats(): print(\"TEMPLATE",
"of transformational rules to correct the tags of individual tokens.",
"-- usually you would not care about statistics for individual",
"Find the positions where it might apply positions = tag_to_positions.get(rule.original_tag,",
"thus use batch_tag() instead :param sequences: lists of token sequences",
"additionally a few multi-feature ones (the motivation is easy comparison",
"apply positions = tag_to_positions.get(rule.original_tag, []) # Apply the rule at",
"Word([-1])), Template(Word([0]), Word([1])), Template(Word([0]), Word([2])), Template(Word([0]), Word([-2])), Template(Word([1, 2])), Template(Word([-2,",
"STATISTICS (TEST AND TRAIN) ({0} templates, {1} rules)\".format( len(template_counts), len(tids)),",
"testing_stats['sequencecount'] = len(sequences) tagged_tokenses = [self._initial_tagger.tag(tokens) for tokens in sequences]",
"a bit of magic to get all functions in this",
"def nltkdemo18plus(): \"\"\" Return 18 templates, from the original nltk",
"tag_to_positions[rule.replacement_tag].add(i) return tagged_tokens def print_template_statistics(self, test_stats=None, printunused=True): \"\"\" Print a",
"is None: print_train_stats() else: print_testtrain_stats() print() if printunused: print_unused_templates() print()",
"name == \"describe_template_sets\": continue print(name, obj.__doc__, \"\\n\") ###################################################################### # The",
"for rule in self._rules: # Find the positions where it",
"= 1 - testing_stats['initialerrors']/testing_stats['tokencount'] # Apply each rule to the",
"strings :param gold: the gold standard :type gold: list of",
"Template(Pos([-1]), Word([0]), Pos([1])), ] def fntbl37(): \"\"\" Return 37 templates",
"collected during testing :type test_stats: dict of str -> any",
"templates, {1} rules)\".format( len(template_counts), len(tids)), ) print(\"TEST ({tokencount:7d} tokens) initial",
"sets in this demo, with a short description\" \"\"\" import",
"for individual rules and thus use batch_tag() instead :param sequences:",
"Template(Word([1, 2])), Template(Word([-3, -2, -1])), Template(Word([1, 2, 3])), Template(Word([-1]), Word([1])),",
"\".format(**train_stats)) head = \"#ID | Score (train) | #Rules |",
"statistic: str :return: some statistic collected during training of this",
"initial_tagger self._rules = tuple(rules) self._training_stats = training_stats def encode_json_obj(self): return",
"{5}\".format( tid, trainscore, trainscore/tottrainscores, template_counts[tid], template_counts[tid]/len(tids), Template.ALLTEMPLATES[int(tid)], ) print(s) def",
"= training_stats def encode_json_obj(self): return self._initial_tagger, self._rules, self._training_stats @classmethod def",
"-1])), Template(Pos([1, 2])), Template(Pos([-3, -2, -1])), Template(Pos([1, 2, 3])), Template(Pos([-1]),",
"inefficient (does not build any index, so will traverse the",
"positions) # Update tag_to_positions with the positions of tags that",
"ranked according to efficiency. If test_stats is available, the templates",
"\".format(**test_stats)) print(\"TRAIN ({tokencount:7d} tokens) initial {initialerrors:5d} {initialacc:.4f} \" \"final: {finalerrors:5d}",
"are used instead. There is also an unweighted measure (just",
"(err0, err1) in zip(errors, errors[1:])] testing_stats['finalerrors'] = errors[-1] testing_stats['finalacc'] =",
"from collections import defaultdict, Counter from nltk.tag import TaggerI from",
"Template(Word([-1]), Pos([-1])), Template(Word([1]), Pos([1])), Template(Word([0]), Word([-1]), Pos([-1])), Template(Word([0]), Word([1]), Pos([1])),",
"python versions and will break cross-version tests def det_tplsort(tpl_value): return",
"Pos([1])), ] def fntbl37(): \"\"\" Return 37 templates taken from",
"from a training corpus, using one of the TaggerTrainers available.",
"testscores = test_stats['rulescores'] print(\"TEMPLATE STATISTICS (TEST AND TRAIN) ({0} templates,",
"sum(len(t) for t in sequences) testing_stats['sequencecount'] = len(sequences) tagged_tokenses =",
"according to their relative contribution (summed for all rules created",
"(name, obj) in templatesets: if name == \"describe_template_sets\": continue print(name,",
":type printunused: bool :return: None :rtype: None \"\"\" tids =",
"Tagger ###################################################################### @jsontags.register_tag class BrillTagger(TaggerI): \"\"\" Brill's transformational rule-based tagger.",
"@jsontags.register_tag class Pos(Feature): \"\"\" Feature which examines the tags of",
"Word([0]), Word([1])), Template(Pos([1]), Word([0]), Word([-1])), Template(Pos([-1]), Word([-1]), Word([0])), Template(Pos([-1]), Word([0]),",
"gold) for (t, g) in zip(*pair)) testing_stats = {} testing_stats['tokencount']",
"index): \"\"\"@return: The given token's text.\"\"\" return tokens[index][0] @jsontags.register_tag class",
"train scores for {1} rules\".format(trainscores, tids) template_counts = Counter(tids) weighted_traincounts",
"ordered list of transformation rules that correct the initial tagging",
"rule)) \"\"\" def counterrors(xs): return sum(t[1] != g[1] for pair",
"Template(Pos([-2])), Template(Pos([2])), Template(Pos([1, 2, 3])), Template(Pos([1, 2])), Template(Pos([-3, -2, -1])),",
"in zip(errors, errors[1:])] testing_stats['finalerrors'] = errors[-1] testing_stats['finalacc'] = 1 -",
"If no test_stats, then statistics collected during training are used",
"N rules) -- usually you would not care about statistics",
"a short description\" \"\"\" import inspect import sys # a",
"tids = [r.templateid for r in self._rules] train_stats = self.train_stats()",
"tag. tag_to_positions = defaultdict(set) for i, (token, tag) in enumerate(tagged_tokens):",
"entire corpus N times for N rules) -- usually you",
"gold: the gold standard :type gold: list of list of",
"] def fntbl37(): \"\"\" Return 37 templates taken from the",
"print_template_statistics(self, test_stats=None, printunused=True): \"\"\" Print a list of all templates,",
"for tid in tids) unused = [(tid, tpl) for (tid,",
"Inherit documentation from TaggerI # Run the initial tagger. tagged_tokens",
"= sorted(weighted_traincounts.items(), key=det_tplsort, reverse=True) for (tid, trainscore) in train_tplscores: s",
"reverse=True) for (tid, trainscore) in train_tplscores: s = \"{0} |",
"if no name given :param statistic: name of statistic :type",
"inspect.isfunction) for (name, obj) in templatesets: if name == \"describe_template_sets\":",
":param gold: the gold standard :type gold: list of list",
"unused templates :type printunused: bool :return: None :rtype: None \"\"\"",
"len(tids)) ) print(\"TRAIN ({tokencount:7d} tokens) initial {initialerrors:5d} {initialacc:.4f} \" \"final:",
"pair in zip(xs, gold) for (t, g) in zip(*pair)) testing_stats",
"available. \"\"\" json_tag = 'nltk.tag.BrillTagger' def __init__(self, initial_tagger, rules, training_stats=None):",
"Word([0]), Word([1])), Template(Word([0]), Word([-1])), Template(Word([0]), Word([1])), Template(Word([0]), Word([2])), Template(Word([0]), Word([-2])),",
"templatesets: if name == \"describe_template_sets\": continue print(name, obj.__doc__, \"\\n\") ######################################################################",
"tagger. tagged_tokens = self._initial_tagger.tag(tokens) # Create a dictionary that maps",
"statistics on the test set for individual rules. NOTE: This",
"= tuple(rules) self._training_stats = training_stats def encode_json_obj(self): return self._initial_tagger, self._rules,",
"# does not break ties deterministically # between python versions",
"multi-feature ones (the motivation is easy comparison with nltkdemo18) \"\"\"",
"this demo, with a short description\" \"\"\" import inspect import",
"as many low-score rules will appear towards end of training.",
"Template(Word([0]), Word([1])), Template(Word([0]), Word([2])), Template(Word([0]), Word([-2])), Template(Word([1, 2])), Template(Word([-2, -1])),",
"which examines the tags of nearby tokens. \"\"\" json_tag =",
"key=det_tplsort, reverse=True) for (tid, trainscore) in train_tplscores: s = \"{0}",
"be created directly, from an initial tagger and a list",
"-1])), Template(Pos([1, 2, 3])), Template(Pos([-1]), Pos([1])), Template(Pos([-2]), Pos([-1])), Template(Pos([1]), Pos([2])),",
"initial tagger :type initial_tagger: TaggerI :param rules: An ordered list",
"the ordered list of transformation rules that correct the initial",
"examines the text (word) of nearby tokens. \"\"\" json_tag =",
"def batch_tag_incremental(self, sequences, gold): \"\"\" Tags by applying each rule",
"are ranked according to their relative contribution (summed for all",
"tid, testscore, testscore/tottestscores, weighted_traincounts[tid], weighted_traincounts[tid]/tottrainscores, template_counts[tid], template_counts[tid]/len(tids), Template.ALLTEMPLATES[int(tid)], ) print(s)",
"jsontags ###################################################################### # Brill Templates ###################################################################### @jsontags.register_tag class Word(Feature): \"\"\"",
"then statistics collected during training are used instead. There is",
"str :return: some statistic collected during training of this tagger",
"created from a given template, weighted by score) to the",
"template_counts[tid], template_counts[tid]/len(tids), Template.ALLTEMPLATES[int(tid)], ) print(s) def print_testtrain_stats(): testscores = test_stats['rulescores']",
"= 'nltk.tag.BrillTagger' def __init__(self, initial_tagger, rules, training_stats=None): \"\"\" :param initial_tagger:",
"Template(Word([-1]), Pos([1])), Template(Pos([-1]), Word([1])), Template(Word([-1]), Word([0]), Pos([1])), Template(Pos([-1]), Word([0]), Word([1])),",
"would not care about statistics for individual rules and thus",
"trainscore/tottrainscores, template_counts[tid], template_counts[tid]/len(tids), Template.ALLTEMPLATES[int(tid)], ) print(s) def print_testtrain_stats(): testscores =",
"individual rules and thus use batch_tag() instead :param sequences: lists",
"i in changed: tag_to_positions[rule.original_tag].remove(i) tag_to_positions[rule.replacement_tag].add(i) return tagged_tokens def print_template_statistics(self, test_stats=None,",
"{finalacc:.4f} \".format(**train_stats)) weighted_testcounts = Counter() for (tid, score) in zip(tids,",
"= \"{0:s} |{1:5d} {2:6.3f} | {3:4d} {4:.3f} |{5:4d} {6:.3f} |",
"(such as ``tag.DefaultTagger``) to assign an initial tag sequence to",
"Pos(Feature): \"\"\" Feature which examines the tags of nearby tokens.",
"@jsontags.register_tag class Word(Feature): \"\"\" Feature which examines the text (word)",
"dictionary of statistics collected during testing :type test_stats: dict of",
"an initial tagger and a list of transformational rules; but",
"test_stats: dict of str -> any (but usually numbers) :param",
"if name == \"describe_template_sets\": continue print(name, obj.__doc__, \"\\n\") ###################################################################### #",
"Template(Pos([-2]), Pos([-1])), Template(Pos([1]), Pos([2])), Template(Pos([1]), Pos([2]), Word([1])) ] def brill24():",
"of str -> any (but usually numbers) :param printunused: if",
"|{3:4d} {4:.3f} | {5}\".format( tid, trainscore, trainscore/tottrainscores, template_counts[tid], template_counts[tid]/len(tids), Template.ALLTEMPLATES[int(tid)],",
"# indices of tokens that have that tag. tag_to_positions =",
"self._training_stats @classmethod def decode_json_obj(cls, obj): _initial_tagger, _rules, _training_stats = obj",
"3])), Template(Pos([-1]), Pos([1])), Template(Pos([-2]), Pos([-1])), Template(Pos([1]), Pos([2])), Template(Word([-1])), Template(Word([1])), Template(Word([-2])),",
"Language Toolkit: Transformation-based learning # # Copyright (C) 2001-2018 NLTK",
"training, for possible later use :type training_stats: dict \"\"\" self._initial_tagger",
"testscore) in test_tplscores: s = \"{0:s} |{1:5d} {2:6.3f} | {3:4d}",
"enumerate(tagged_tokens): tag_to_positions[tag].add(i) # Apply each rule, in order. Only try",
"collected during training, or a dictionary of all available statistics",
"print(\"TEMPLATE STATISTICS (TRAIN) {0} templates, {1} rules)\".format( len(template_counts), len(tids)) )",
"Counter() for (tid, score) in zip(tids, testscores): weighted_testcounts[tid] += score",
"statistics collected during training are used instead. There is also",
"rules are specified by the ``TagRule`` interface. Brill taggers can",
"the test set for individual rules. NOTE: This is inefficient",
"(tid, testscore) in test_tplscores: s = \"{0:s} |{1:5d} {2:6.3f} |",
":rtype: list of Rules \"\"\" return self._rules def train_stats(self, statistic=None):",
"testing_stats['initialacc'] = 1 - testing_stats['initialerrors']/testing_stats['tokencount'] # Apply each rule to",
"AND TRAIN) ({0} templates, {1} rules)\".format( len(template_counts), len(tids)), ) print(\"TEST",
"(TEST AND TRAIN) ({0} templates, {1} rules)\".format( len(template_counts), len(tids)), )",
"NOTE: This is inefficient (does not build any index, so",
"Template(Word([2])), Template(Word([-2, -1])), Template(Word([1, 2])), Template(Word([-3, -2, -1])), Template(Word([1, 2,",
"of tags that # were modified. for i in changed:",
"trainscore) in train_tplscores: s = \"{0} | {1:5d} {2:5.3f} |{3:4d}",
"the rule at those positions. changed = rule.apply(tagged_tokens, positions) #",
"enumerate(Template.ALLTEMPLATES) if tid not in usedtpls] print(\"UNUSED TEMPLATES ({0})\".format(len(unused))) for",
"err1) in zip(errors, errors[1:])] testing_stats['finalerrors'] = errors[-1] testing_stats['finalacc'] = 1",
"r in self._rules] train_stats = self.train_stats() trainscores = train_stats['rulescores'] assert",
":param printunused: if True, print a list of all unused",
"tokens that have that tag. tag_to_positions = defaultdict(set) for i,",
"initial {initialerrors:5d} {initialacc:.4f} \" \"final: {finalerrors:5d} {finalacc:.4f} \".format(**train_stats)) weighted_testcounts =",
"(C) 2001-2018 NLTK Project # Author: <NAME> <<EMAIL>> # based",
"of training. :param test_stats: dictionary of statistics collected during testing",
"from the original nltk demo, and additionally a few multi-feature",
"applying each rule to the entire corpus (rather than all",
"point is to collect statistics on the test set for",
"an initial tagger (such as ``tag.DefaultTagger``) to assign an initial",
"initial tagging :rtype: list of Rules \"\"\" return self._rules def",
"use an initial tagger (such as ``tag.DefaultTagger``) to assign an",
"Word([0]), Word([1])), Template(Pos([-2]), Pos([-1])), Template(Pos([1]), Pos([2])), Template(Pos([1]), Pos([2]), Word([1])) ]",
"in self._rules: # Find the positions where it might apply",
"tokens. \"\"\" json_tag = 'nltk.tag.brill.Pos' @staticmethod def extract_property(tokens, index): \"\"\"@return:",
"weighted_traincounts[tid]/tottrainscores, template_counts[tid], template_counts[tid]/len(tids), Template.ALLTEMPLATES[int(tid)], ) print(s) def print_unused_templates(): usedtpls =",
"positions. changed = rule.apply(tagged_tokens, positions) # Update tag_to_positions with the",
"def fntbl37(): \"\"\" Return 37 templates taken from the postagging",
"\"\"\" Return 24 templates of the seminal TBL paper, Brill",
"statistic: name of statistic :type statistic: str :return: some statistic",
"= test_stats['rulescores'] print(\"TEMPLATE STATISTICS (TEST AND TRAIN) ({0} templates, {1}",
"lists of token sequences (sentences, in some applications) to be",
"scores (one for each rule)) \"\"\" def counterrors(xs): return sum(t[1]",
"the original nltk demo, and additionally a few multi-feature ones",
"\"\"\" Return 37 templates taken from the postagging task of",
"# URL: <http://nltk.org/> # For license information, see LICENSE.TXT from",
"Word([2])), Template(Word([-1]), Word([0]), Word([1])), Template(Word([0]), Word([-1])), Template(Word([0]), Word([1])), Template(Word([0]), Word([2])),",
"test_stats=None, printunused=True): \"\"\" Print a list of all templates, ranked",
"for tagged_tokens in tagged_tokenses: rule.apply(tagged_tokens) errors.append(counterrors(tagged_tokenses)) testing_stats['rulescores'] = [err0 -",
"tagged_tokens def print_template_statistics(self, test_stats=None, printunused=True): \"\"\" Print a list of",
"def __init__(self, initial_tagger, rules, training_stats=None): \"\"\" :param initial_tagger: The initial",
"in zip(tids, testscores): weighted_testcounts[tid] += score tottestscores = sum(testscores) head",
"after excluding a handful which do not condition on Pos[0];",
"-1])), Template(Pos([1, 2, 3])), Template(Pos([-1]), Pos([1])), Template(Word([-1])), Template(Word([1])), Template(Word([-2])), Template(Word([2])),",
"a list of the # indices of tokens that have",
"tokens in sequences] testing_stats['initialerrors'] = counterrors(tagged_tokenses) testing_stats['initialacc'] = 1 -",
"None: print_train_stats() else: print_testtrain_stats() print() if printunused: print_unused_templates() print() def",
"but more often, Brill taggers are created by learning rules",
"decode_json_obj(cls, obj): _initial_tagger, _rules, _training_stats = obj return cls(_initial_tagger, _rules,",
"\"\"\" return self._rules def train_stats(self, statistic=None): \"\"\" Return a named",
"Template(Word([-2])), Template(Word([2])), Template(Word([1])), Template(Word([-1])), Template(Pos([-1]), Pos([1])), Template(Pos([1]), Pos([2])), Template(Pos([-1]), Pos([-2])),",
"Template(Word([-1, 0])), Template(Word([0, 1])), Template(Word([0])), Template(Word([-1]), Pos([-1])), Template(Word([1]), Pos([1])), Template(Word([0]),",
"for t in sequences) testing_stats['sequencecount'] = len(sequences) tagged_tokenses = [self._initial_tagger.tag(tokens)",
"Template(Pos([-1]), Word([0]), Word([1])), Template(Pos([-2]), Pos([-1])), Template(Pos([1]), Pos([2])), Template(Pos([1]), Pos([2]), Word([1]))",
"Word([-1]), Word([0])), Template(Pos([-1]), Word([0]), Word([1])), Template(Pos([-2]), Pos([-1])), Template(Pos([1]), Pos([2])), Template(Pos([1]),",
"= defaultdict(set) for i, (token, tag) in enumerate(tagged_tokens): tag_to_positions[tag].add(i) #",
"True, print a list of all unused templates :type printunused:",
"unused = [(tid, tpl) for (tid, tpl) in enumerate(Template.ALLTEMPLATES) if",
"of (tagged_sequences, ordered list of rule scores (one for each",
"demo, with a short description\" \"\"\" import inspect import sys",
"documentation from TaggerI # Run the initial tagger. tagged_tokens =",
"condition on Pos[0]; fntbl can do that but the current",
"functions in this module templatesets = inspect.getmembers(sys.modules[__name__], inspect.isfunction) for (name,",
"by score) to the performance on the test set. If",
":type rules: list(TagRule) :param training_stats: A dictionary of statistics collected",
"as ``tag.DefaultTagger``) to assign an initial tag sequence to a",
"URL: <http://nltk.org/> # For license information, see LICENSE.TXT from __future__",
"not condition on Pos[0]; fntbl can do that but the",
"Template(Pos([-1]), Pos([-2])), Template(Pos([1])), Template(Pos([-1])), Template(Pos([-2])), Template(Pos([2])), Template(Pos([1, 2, 3])), Template(Pos([1,",
"print(name, obj.__doc__, \"\\n\") ###################################################################### # The Brill Tagger ###################################################################### @jsontags.register_tag",
"given token's text.\"\"\" return tokens[index][0] @jsontags.register_tag class Pos(Feature): \"\"\" Feature",
"\"\\n\", \"-\" * len(head), sep=\"\") train_tplscores = sorted(weighted_traincounts.items(), key=det_tplsort, reverse=True)",
"templates of the seminal TBL paper, Brill (1995) \"\"\" return",
"unused: print(\"{0:03d} {1:s}\".format(tid, str(tpl))) if test_stats is None: print_train_stats() else:",
"of list of strings :param gold: the gold standard :type",
"{2:5.3f} |{3:4d} {4:.3f} | {5}\".format( tid, trainscore, trainscore/tottrainscores, template_counts[tid], template_counts[tid]/len(tids),",
"The Brill Tagger ###################################################################### @jsontags.register_tag class BrillTagger(TaggerI): \"\"\" Brill's transformational",
"Tags by applying each rule to the entire corpus (rather",
"The given token's text.\"\"\" return tokens[index][0] @jsontags.register_tag class Pos(Feature): \"\"\"",
"Template(Word([-2, -1])), Template(Word([1, 2, 3])), Template(Word([-3, -2, -1])), Template(Word([0]), Pos([2])),",
"Word([1])), Template(Word([0]), Word([-1])), Template(Word([0]), Word([1])), Template(Word([0]), Word([2])), Template(Word([0]), Word([-2])), Template(Word([1,",
"relative contribution (summed for all rules created from a given",
"inspect.getmembers(sys.modules[__name__], inspect.isfunction) for (name, obj) in templatesets: if name ==",
"to a single sequence). The point is to collect statistics",
"templates, from the original nltk demo, and additionally a few",
"learning # # Copyright (C) 2001-2018 NLTK Project # Author:",
"Pos([1])), ] def describe_template_sets(): \"\"\" Print the available template sets",
"return tokens[index][1] def nltkdemo18(): \"\"\" Return 18 templates, from the",
"(sentences, in some applications) to be tagged :type sequences: list",
"for all rules created from a given template, weighted by",
"tuple(rules) self._training_stats = training_stats def encode_json_obj(self): return self._initial_tagger, self._rules, self._training_stats",
"then apply an ordered list of transformational rules to correct",
"print(\"TRAIN ({tokencount:7d} tokens) initial {initialerrors:5d} {initialacc:.4f} \" \"final: {finalerrors:5d} {finalacc:.4f}",
"Template(Pos([2])), Template(Pos([1, 2, 3])), Template(Pos([1, 2])), Template(Pos([-3, -2, -1])), Template(Pos([-2,",
"``TagRule`` interface. Brill taggers can be created directly, from an",
"a list of transformational rules; but more often, Brill taggers",
"for (tid, tpl) in enumerate(Template.ALLTEMPLATES) if tid not in usedtpls]",
"maps each tag to a list of the # indices",
"\"\"\" def counterrors(xs): return sum(t[1] != g[1] for pair in",
"= {} testing_stats['tokencount'] = sum(len(t) for t in sequences) testing_stats['sequencecount']",
"tokens) initial {initialerrors:5d} {initialacc:.4f} \" \"final: {finalerrors:5d} {finalacc:.4f} \".format(**train_stats)) head",
"test_stats is available, the templates are ranked according to their",
"- err1 for (err0, err1) in zip(errors, errors[1:])] testing_stats['finalerrors'] =",
"= [self._initial_tagger.tag(tokens) for tokens in sequences] testing_stats['initialerrors'] = counterrors(tagged_tokenses) testing_stats['initialacc']",
"(tid, score) in zip(tids, trainscores): weighted_traincounts[tid] += score tottrainscores =",
"Word([0]), Pos([1])), ] def fntbl37(): \"\"\" Return 37 templates taken",
"3])), Template(Word([-3, -2, -1])), Template(Word([0]), Pos([2])), Template(Word([0]), Pos([-2])), Template(Word([0]), Pos([1])),",
"that tag. tag_to_positions = defaultdict(set) for i, (token, tag) in",
"|{1:5d} {2:6.3f} | {3:4d} {4:.3f} |{5:4d} {6:.3f} | {7:s}\".format( tid,",
"self._initial_tagger = initial_tagger self._rules = tuple(rules) self._training_stats = training_stats def",
"to efficiency. If test_stats is available, the templates are ranked",
"in this demo, with a short description\" \"\"\" import inspect",
") print(\"TRAIN ({tokencount:7d} tokens) initial {initialerrors:5d} {initialacc:.4f} \" \"final: {finalerrors:5d}",
"-2, -1])), Template(Pos([1, 2, 3])), Template(Pos([-1]), Pos([1])), Template(Word([-1])), Template(Word([1])), Template(Word([-2])),",
"specified by the ``TagRule`` interface. Brill taggers can be created",
"test set for individual rules. NOTE: This is inefficient (does",
"is None: return self._training_stats else: return self._training_stats.get(statistic) def tag(self, tokens):",
"gold): \"\"\" Tags by applying each rule to the entire",
"{6:.3f} | {7:s}\".format( tid, testscore, testscore/tottestscores, weighted_traincounts[tid], weighted_traincounts[tid]/tottrainscores, template_counts[tid], template_counts[tid]/len(tids),",
"Brill Tagger ###################################################################### @jsontags.register_tag class BrillTagger(TaggerI): \"\"\" Brill's transformational rule-based",
"Run the initial tagger. tagged_tokens = self._initial_tagger.tag(tokens) # Create a",
"current nltk implementation cannot.) \"\"\" return [ Template(Word([0]), Word([1]), Word([2])),",
"self._rules: # Find the positions where it might apply positions",
") print(\"TEST ({tokencount:7d} tokens) initial {initialerrors:5d} {initialacc:.4f} \" \"final: {finalerrors:5d}",
"a list of all templates, ranked according to efficiency. If",
"the initial tagger. tagged_tokens = self._initial_tagger.tag(tokens) # Create a dictionary",
"traverse the entire corpus N times for N rules) --",
"2, 3])), Template(Pos([-1]), Pos([1])), Template(Pos([-2]), Pos([-1])), Template(Pos([1]), Pos([2])), Template(Word([-1])), Template(Word([1])),",
"18 templates, from the original nltk demo, and additionally a",
"counterrors(tagged_tokenses) testing_stats['initialacc'] = 1 - testing_stats['initialerrors']/testing_stats['tokencount'] # Apply each rule",
"tagged_tokens in tagged_tokenses: rule.apply(tagged_tokens) errors.append(counterrors(tagged_tokenses)) testing_stats['rulescores'] = [err0 - err1",
"for (tid, score) in zip(tids, testscores): weighted_testcounts[tid] += score tottestscores",
"tagged_tokens = self._initial_tagger.tag(tokens) # Create a dictionary that maps each",
"Word([-2])), Template(Word([1, 2])), Template(Word([-2, -1])), Template(Word([1, 2, 3])), Template(Word([-3, -2,",
"+= score tottestscores = sum(testscores) head = \"#ID | Score",
"rules that should be used to correct the initial tagging.",
"in some applications) to be tagged :type sequences: list of",
"\" \"final: {finalerrors:5d} {finalacc:.4f} \".format(**train_stats)) weighted_testcounts = Counter() for (tid,",
":type gold: list of list of strings :returns: tuple of",
"len(tids), \"corrupt statistics: \" \\ \"{0} train scores for {1}",
"for i, (token, tag) in enumerate(tagged_tokens): tag_to_positions[tag].add(i) # Apply each",
"\"-\" * len(head), sep=\"\") train_tplscores = sorted(weighted_traincounts.items(), key=det_tplsort, reverse=True) for",
"in order errors = [testing_stats['initialerrors']] for rule in self._rules: for",
"of rule scores (one for each rule)) \"\"\" def counterrors(xs):",
"Score (test) | Score (train) | #Rules | Template\" print(head,",
"training_stats: dict \"\"\" self._initial_tagger = initial_tagger self._rules = tuple(rules) self._training_stats",
"to apply rules at # positions that have the desired",
"| Score (test) | Score (train) | #Rules | Template\"",
"the seminal TBL paper, Brill (1995) \"\"\" return [ Template(Pos([-1])),",
"len(template_counts), len(tids)) ) print(\"TRAIN ({tokencount:7d} tokens) initial {initialerrors:5d} {initialacc:.4f} \"",
"printunused: if True, print a list of all unused templates",
"in train_tplscores: s = \"{0} | {1:5d} {2:5.3f} |{3:4d} {4:.3f}",
"i, (token, tag) in enumerate(tagged_tokens): tag_to_positions[tag].add(i) # Apply each rule,",
"train_stats = self.train_stats() trainscores = train_stats['rulescores'] assert len(trainscores) == len(tids),",
"excluding a handful which do not condition on Pos[0]; fntbl",
"zip(xs, gold) for (t, g) in zip(*pair)) testing_stats = {}",
"return tokens[index][0] @jsontags.register_tag class Pos(Feature): \"\"\" Feature which examines the",
"this tagger has learnt :return: the ordered list of transformation",
":param sequences: lists of token sequences (sentences, in some applications)",
"a few multi-feature ones (the motivation is easy comparison with",
"the ``TagRule`` interface. Brill taggers can be created directly, from",
"TaggerI from nltk.tbl import Feature, Template from nltk import jsontags",
"Template(Pos([1])), Template(Pos([-2])), Template(Pos([2])), Template(Pos([-2, -1])), Template(Pos([1, 2])), Template(Pos([-3, -2, -1])),",
"from __future__ import print_function, division from collections import defaultdict, Counter",
"the # indices of tokens that have that tag. tag_to_positions",
"cls(_initial_tagger, _rules, _training_stats) def rules(self): \"\"\" Return the ordered list",
"self._training_stats = training_stats def encode_json_obj(self): return self._initial_tagger, self._rules, self._training_stats @classmethod",
"(t, g) in zip(*pair)) testing_stats = {} testing_stats['tokencount'] = sum(len(t)",
"(does not build any index, so will traverse the entire",
"list of the # indices of tokens that have that",
"were modified. for i in changed: tag_to_positions[rule.original_tag].remove(i) tag_to_positions[rule.replacement_tag].add(i) return tagged_tokens",
"= [err0 - err1 for (err0, err1) in zip(errors, errors[1:])]",
"in enumerate(tagged_tokens): tag_to_positions[tag].add(i) # Apply each rule, in order. Only",
"Feature which examines the text (word) of nearby tokens. \"\"\"",
"Pos([-1])), Template(Pos([1]), Pos([2])), Template(Word([-1])), Template(Word([1])), Template(Word([-2])), Template(Word([2])), Template(Word([-2, -1])), Template(Word([1,",
"statistic :type statistic: str :return: some statistic collected during training",
"positions = tag_to_positions.get(rule.original_tag, []) # Apply the rule at those",
"available, the templates are ranked according to their relative contribution",
"rules: An ordered list of transformation rules that should be",
"\"\"\" Return 18 templates, from the original nltk demo, and",
"dict of str -> any (but usually numbers) :param printunused:",
"of all available statistics if no name given :param statistic:",
"return self._initial_tagger, self._rules, self._training_stats @classmethod def decode_json_obj(cls, obj): _initial_tagger, _rules,",
"sequences) testing_stats['sequencecount'] = len(sequences) tagged_tokenses = [self._initial_tagger.tag(tokens) for tokens in",
"24 templates of the seminal TBL paper, Brill (1995) \"\"\"",
"Word(Feature): \"\"\" Feature which examines the text (word) of nearby",
"Pos([1])), Template(Pos([-1]), Word([1])), Template(Word([-1]), Word([0]), Pos([1])), Template(Pos([-1]), Word([0]), Word([1])), Template(Pos([-1]),",
"list of Rules \"\"\" return self._rules def train_stats(self, statistic=None): \"\"\"",
"that have that tag. tag_to_positions = defaultdict(set) for i, (token,",
"in usedtpls] print(\"UNUSED TEMPLATES ({0})\".format(len(unused))) for (tid, tpl) in unused:",
"a text; and then apply an ordered list of transformational",
"rules) -- usually you would not care about statistics for",
"coding: utf-8 -*- # Natural Language Toolkit: Transformation-based learning #",
"given token's tag.\"\"\" return tokens[index][1] def nltkdemo18(): \"\"\" Return 18",
"than all rules to a single sequence). The point is",
"(token, tag) in enumerate(tagged_tokens): tag_to_positions[tag].add(i) # Apply each rule, in",
"Word([0]), Pos([1])), Template(Pos([-1]), Word([0]), Word([1])), Template(Pos([-1]), Word([0]), Pos([1])), ] def",
"self._rules] train_stats = self.train_stats() trainscores = train_stats['rulescores'] assert len(trainscores) ==",
"has learnt :return: the ordered list of transformation rules that",
"of statistics collected during training, for possible later use :type",
"# the otherwise convenient Counter.most_common() unfortunately # does not break",
"initial tag sequence to a text; and then apply an",
"during training, or a dictionary of all available statistics if",
"rules that this tagger has learnt :return: the ordered list",
"Return 24 templates of the seminal TBL paper, Brill (1995)",
"{0} templates, {1} rules)\".format( len(template_counts), len(tids)) ) print(\"TRAIN ({tokencount:7d} tokens)",
"named statistic collected during training, or a dictionary of all",
"usually you would not care about statistics for individual rules",
"print(s) def print_unused_templates(): usedtpls = set(int(tid) for tid in tids)",
"<NAME>, <NAME> # URL: <http://nltk.org/> # For license information, see",
"if test_stats is None: print_train_stats() else: print_testtrain_stats() print() if printunused:",
"Update tag_to_positions with the positions of tags that # were",
"\"\"\" json_tag = 'nltk.tag.brill.Word' @staticmethod def extract_property(tokens, index): \"\"\"@return: The",
"Word([0]), Word([-1])), Template(Pos([-1]), Word([-1]), Word([0])), Template(Pos([-1]), Word([0]), Word([1])), Template(Pos([-2]), Pos([-1])),",
"\"\"\" json_tag = 'nltk.tag.brill.Pos' @staticmethod def extract_property(tokens, index): \"\"\"@return: The",
"during training of this tagger :rtype: any (but usually a",
"if printunused: print_unused_templates() print() def batch_tag_incremental(self, sequences, gold): \"\"\" Tags",
"rules)\".format( len(template_counts), len(tids)), ) print(\"TEST ({tokencount:7d} tokens) initial {initialerrors:5d} {initialacc:.4f}",
"the templates are ranked according to their relative contribution (summed",
"###################################################################### @jsontags.register_tag class BrillTagger(TaggerI): \"\"\" Brill's transformational rule-based tagger. Brill",
"These transformation rules are specified by the ``TagRule`` interface. Brill",
"correct the initial tagging. :type rules: list(TagRule) :param training_stats: A",
"def counterrors(xs): return sum(t[1] != g[1] for pair in zip(xs,",
"set for individual rules. NOTE: This is inefficient (does not",
"one of the TaggerTrainers available. \"\"\" json_tag = 'nltk.tag.BrillTagger' def",
"testing :type test_stats: dict of str -> any (but usually",
"Template(Pos([-1]), Pos([1])), Template(Pos([-2]), Pos([-1])), Template(Pos([1]), Pos([2])), Template(Word([-1])), Template(Word([1])), Template(Word([-2])), Template(Word([2])),",
"by # <NAME>, <NAME>, <NAME> # URL: <http://nltk.org/> # For",
"Template(Pos([1]), Pos([2])), Template(Word([-1])), Template(Word([1])), Template(Word([-2])), Template(Word([2])), Template(Word([-2, -1])), Template(Word([1, 2])),",
"import inspect import sys # a bit of magic to",
"fntbl37(): \"\"\" Return 37 templates taken from the postagging task",
"is available, the templates are ranked according to their relative",
"Template(Word([-1])), Template(Word([1])), Template(Word([-2])), Template(Word([2])), Template(Word([-2, -1])), Template(Word([1, 2])), Template(Word([-3, -2,",
"\"{0:s} |{1:5d} {2:6.3f} | {3:4d} {4:.3f} |{5:4d} {6:.3f} | {7:s}\".format(",
"_training_stats = obj return cls(_initial_tagger, _rules, _training_stats) def rules(self): \"\"\"",
"tagger (such as ``tag.DefaultTagger``) to assign an initial tag sequence",
"tag(self, tokens): # Inherit documentation from TaggerI # Run the",
"Template(Word([0]), Word([1]), Word([2])), Template(Word([-1]), Word([0]), Word([1])), Template(Word([0]), Word([-1])), Template(Word([0]), Word([1])),",
"statistic=None): \"\"\" Return a named statistic collected during training, or",
"for (name, obj) in templatesets: if name == \"describe_template_sets\": continue",
"return cls(_initial_tagger, _rules, _training_stats) def rules(self): \"\"\" Return the ordered",
"self._rules: for tagged_tokens in tagged_tokenses: rule.apply(tagged_tokens) errors.append(counterrors(tagged_tokenses)) testing_stats['rulescores'] = [err0",
"nltk implementation cannot.) \"\"\" return [ Template(Word([0]), Word([1]), Word([2])), Template(Word([-1]),",
"ties deterministically # between python versions and will break cross-version",
"(tpl_value[1], repr(tpl_value[0])) def print_train_stats(): print(\"TEMPLATE STATISTICS (TRAIN) {0} templates, {1}",
"for (tid, tpl) in unused: print(\"{0:03d} {1:s}\".format(tid, str(tpl))) if test_stats",
"list(TagRule) :param training_stats: A dictionary of statistics collected during training,",
"order. Only try to apply rules at # positions that",
"cannot.) \"\"\" return [ Template(Word([0]), Word([1]), Word([2])), Template(Word([-1]), Word([0]), Word([1])),",
"return self._training_stats else: return self._training_stats.get(statistic) def tag(self, tokens): # Inherit",
"rules will appear towards end of training. :param test_stats: dictionary",
"directly, from an initial tagger and a list of transformational",
"Template(Word([0])), Template(Word([-2])), Template(Word([2])), Template(Word([1])), Template(Word([-1])), Template(Pos([-1]), Pos([1])), Template(Pos([1]), Pos([2])), Template(Pos([-1]),",
"# Create a dictionary that maps each tag to a",
"rules)\".format( len(template_counts), len(tids)) ) print(\"TRAIN ({tokencount:7d} tokens) initial {initialerrors:5d} {initialacc:.4f}",
"for (t, g) in zip(*pair)) testing_stats = {} testing_stats['tokencount'] =",
"= train_stats['rulescores'] assert len(trainscores) == len(tids), \"corrupt statistics: \" \\",
"\"\"\" import inspect import sys # a bit of magic",
"sequences: lists of token sequences (sentences, in some applications) to",
"from nltk import jsontags ###################################################################### # Brill Templates ###################################################################### @jsontags.register_tag",
"repr(tpl_value[0])) def print_train_stats(): print(\"TEMPLATE STATISTICS (TRAIN) {0} templates, {1} rules)\".format(",
"can be created directly, from an initial tagger and a",
"zip(tids, trainscores): weighted_traincounts[tid] += score tottrainscores = sum(trainscores) # det_tplsort()",
"set(int(tid) for tid in tids) unused = [(tid, tpl) for",
"test set. If no test_stats, then statistics collected during training",
"= sorted(weighted_testcounts.items(), key=det_tplsort, reverse=True) for (tid, testscore) in test_tplscores: s",
"print(\"UNUSED TEMPLATES ({0})\".format(len(unused))) for (tid, tpl) in unused: print(\"{0:03d} {1:s}\".format(tid,",
"weighted_testcounts = Counter() for (tid, score) in zip(tids, testscores): weighted_testcounts[tid]",
"to correct the tags of individual tokens. These transformation rules",
"assert len(trainscores) == len(tids), \"corrupt statistics: \" \\ \"{0} train",
"Apply each rule, in order. Only try to apply rules",
"# between python versions and will break cross-version tests def",
"If test_stats is available, the templates are ranked according to",
"{finalacc:.4f} \".format(**test_stats)) print(\"TRAIN ({tokencount:7d} tokens) initial {initialerrors:5d} {initialacc:.4f} \" \"final:",
"print(head, \"\\n\", \"-\" * len(head), sep=\"\") train_tplscores = sorted(weighted_traincounts.items(), key=det_tplsort,",
"def print_template_statistics(self, test_stats=None, printunused=True): \"\"\" Print a list of all",
"_initial_tagger, _rules, _training_stats = obj return cls(_initial_tagger, _rules, _training_stats) def",
"'nltk.tag.brill.Word' @staticmethod def extract_property(tokens, index): \"\"\"@return: The given token's text.\"\"\"",
"positions that have the desired original tag. for rule in",
"rules at # positions that have the desired original tag.",
"s = \"{0} | {1:5d} {2:5.3f} |{3:4d} {4:.3f} | {5}\".format(",
"be used to correct the initial tagging. :type rules: list(TagRule)",
"] def nltkdemo18plus(): \"\"\" Return 18 templates, from the original",
"return [ Template(Word([0]), Word([1]), Word([2])), Template(Word([-1]), Word([0]), Word([1])), Template(Word([0]), Word([-1])),",
"that correct the initial tagging :rtype: list of Rules \"\"\"",
"# -*- coding: utf-8 -*- # Natural Language Toolkit: Transformation-based",
"self._initial_tagger, self._rules, self._training_stats @classmethod def decode_json_obj(cls, obj): _initial_tagger, _rules, _training_stats",
"Template(Word([-3, -2, -1])), Template(Word([0]), Pos([2])), Template(Word([0]), Pos([-2])), Template(Word([0]), Pos([1])), Template(Word([0]),",
"defaultdict(set) for i, (token, tag) in enumerate(tagged_tokens): tag_to_positions[tag].add(i) # Apply",
"of all templates, ranked according to efficiency. If test_stats is",
"training_stats=None): \"\"\" :param initial_tagger: The initial tagger :type initial_tagger: TaggerI",
"during testing :type test_stats: dict of str -> any (but",
"Template(Pos([-3, -2, -1])), Template(Pos([1, 2, 3])), Template(Pos([-1]), Pos([1])), Template(Word([-1])), Template(Word([1])),",
"tottrainscores = sum(trainscores) # det_tplsort() is for deterministic sorting; #",
"initial_tagger: The initial tagger :type initial_tagger: TaggerI :param rules: An",
"-2, -1])), Template(Word([1, 2, 3])), Template(Word([-1]), Word([1])), ] def nltkdemo18plus():",
") print(s) def print_testtrain_stats(): testscores = test_stats['rulescores'] print(\"TEMPLATE STATISTICS (TEST",
"Word([1])), Template(Word([0]), Word([2])), Template(Word([0]), Word([-2])), Template(Word([1, 2])), Template(Word([-2, -1])), Template(Word([1,",
"json_tag = 'nltk.tag.BrillTagger' def __init__(self, initial_tagger, rules, training_stats=None): \"\"\" :param",
"# The Brill Tagger ###################################################################### @jsontags.register_tag class BrillTagger(TaggerI): \"\"\" Brill's",
"rules, training_stats=None): \"\"\" :param initial_tagger: The initial tagger :type initial_tagger:",
"3])), Template(Pos([1, 2])), Template(Pos([-3, -2, -1])), Template(Pos([-2, -1])), Template(Pos([1]), Word([0]),",
"will traverse the entire corpus N times for N rules)",
"encode_json_obj(self): return self._initial_tagger, self._rules, self._training_stats @classmethod def decode_json_obj(cls, obj): _initial_tagger,",
"rule scores (one for each rule)) \"\"\" def counterrors(xs): return",
"bool :return: None :rtype: None \"\"\" tids = [r.templateid for",
"on previous (nltk2) version by # <NAME>, <NAME>, <NAME> #",
":return: some statistic collected during training of this tagger :rtype:",
"def print_testtrain_stats(): testscores = test_stats['rulescores'] print(\"TEMPLATE STATISTICS (TEST AND TRAIN)",
"have the desired original tag. for rule in self._rules: #",
"Pos([-2])), Template(Word([0]), Pos([1])), Template(Word([0]), Pos([-1])), Template(Word([0])), Template(Word([-2])), Template(Word([2])), Template(Word([1])), Template(Word([-1])),",
"the entire corpus N times for N rules) -- usually",
"print_testtrain_stats() print() if printunused: print_unused_templates() print() def batch_tag_incremental(self, sequences, gold):",
"usually a number) \"\"\" if statistic is None: return self._training_stats",
"examines the tags of nearby tokens. \"\"\" json_tag = 'nltk.tag.brill.Pos'",
"Brill taggers are created by learning rules from a training",
"use :type training_stats: dict \"\"\" self._initial_tagger = initial_tagger self._rules =",
"printunused: print_unused_templates() print() def batch_tag_incremental(self, sequences, gold): \"\"\" Tags by",
"brill24(): \"\"\" Return 24 templates of the seminal TBL paper,",
"modified. for i in changed: tag_to_positions[rule.original_tag].remove(i) tag_to_positions[rule.replacement_tag].add(i) return tagged_tokens def",
"\"\"\" return nltkdemo18() + [ Template(Word([-1]), Pos([1])), Template(Pos([-1]), Word([1])), Template(Word([-1]),",
"to the entire corpus (rather than all rules to a",
"obj return cls(_initial_tagger, _rules, _training_stats) def rules(self): \"\"\" Return the",
"handful which do not condition on Pos[0]; fntbl can do",
"rules that correct the initial tagging :rtype: list of Rules",
"\"\"\" Print a list of all templates, ranked according to",
"Author: <NAME> <<EMAIL>> # based on previous (nltk2) version by",
"magic to get all functions in this module templatesets =",
"have that tag. tag_to_positions = defaultdict(set) for i, (token, tag)",
"should be used to correct the initial tagging. :type rules:",
"score) to the performance on the test set. If no",
"to the performance on the test set. If no test_stats,",
"in enumerate(Template.ALLTEMPLATES) if tid not in usedtpls] print(\"UNUSED TEMPLATES ({0})\".format(len(unused)))",
"else: print_testtrain_stats() print() if printunused: print_unused_templates() print() def batch_tag_incremental(self, sequences,",
"break cross-version tests def det_tplsort(tpl_value): return (tpl_value[1], repr(tpl_value[0])) def print_train_stats():",
"between python versions and will break cross-version tests def det_tplsort(tpl_value):",
"available statistics if no name given :param statistic: name of",
"\"{0} | {1:5d} {2:5.3f} |{3:4d} {4:.3f} | {5}\".format( tid, trainscore,",
"in changed: tag_to_positions[rule.original_tag].remove(i) tag_to_positions[rule.replacement_tag].add(i) return tagged_tokens def print_template_statistics(self, test_stats=None, printunused=True):",
"in test_tplscores: s = \"{0:s} |{1:5d} {2:6.3f} | {3:4d} {4:.3f}",
"easy comparison with nltkdemo18) \"\"\" return nltkdemo18() + [ Template(Word([-1]),",
"statistic collected during training of this tagger :rtype: any (but",
"the entire corpus (rather than all rules to a single",
"zip(*pair)) testing_stats = {} testing_stats['tokencount'] = sum(len(t) for t in",
"for (tid, trainscore) in train_tplscores: s = \"{0} | {1:5d}",
"head = \"#ID | Score (test) | Score (train) |",
"= [testing_stats['initialerrors']] for rule in self._rules: for tagged_tokens in tagged_tokenses:",
"care about statistics for individual rules and thus use batch_tag()",
"of transformation rules that should be used to correct the",
"are specified by the ``TagRule`` interface. Brill taggers can be",
"get all functions in this module templatesets = inspect.getmembers(sys.modules[__name__], inspect.isfunction)",
"-2, -1])), Template(Word([0]), Pos([2])), Template(Word([0]), Pos([-2])), Template(Word([0]), Pos([1])), Template(Word([0]), Pos([-1])),",
"Word([1])), Template(Pos([-1]), Word([0]), Pos([1])), ] def fntbl37(): \"\"\" Return 37",
"+= score tottrainscores = sum(trainscores) # det_tplsort() is for deterministic",
"(TRAIN) {0} templates, {1} rules)\".format( len(template_counts), len(tids)) ) print(\"TRAIN ({tokencount:7d}",
"low-score rules will appear towards end of training. :param test_stats:",
"{initialacc:.4f} \" \"final: {finalerrors:5d} {finalacc:.4f} \".format(**test_stats)) print(\"TRAIN ({tokencount:7d} tokens) initial",
"print(\"TEMPLATE STATISTICS (TEST AND TRAIN) ({0} templates, {1} rules)\".format( len(template_counts),",
"@classmethod def decode_json_obj(cls, obj): _initial_tagger, _rules, _training_stats = obj return",
"(word) of nearby tokens. \"\"\" json_tag = 'nltk.tag.brill.Word' @staticmethod def",
"Template(Word([0, 1])), Template(Word([0])), Template(Word([-1]), Pos([-1])), Template(Word([1]), Pos([1])), Template(Word([0]), Word([-1]), Pos([-1])),",
"# Apply each rule, in order. Only try to apply",
"1 - testing_stats['initialerrors']/testing_stats['tokencount'] # Apply each rule to the entire",
"= \"#ID | Score (train) | #Rules | Template\" print(head,",
"standard :type gold: list of list of strings :returns: tuple",
"train_stats(self, statistic=None): \"\"\" Return a named statistic collected during training,",
"given template, weighted by score) to the performance on the",
"``tag.DefaultTagger``) to assign an initial tag sequence to a text;",
"rules; but more often, Brill taggers are created by learning",
"statistics: \" \\ \"{0} train scores for {1} rules\".format(trainscores, tids)",
"will appear towards end of training. :param test_stats: dictionary of",
"errors = [testing_stats['initialerrors']] for rule in self._rules: for tagged_tokens in",
"Brill Templates ###################################################################### @jsontags.register_tag class Word(Feature): \"\"\" Feature which examines",
"tokens. \"\"\" json_tag = 'nltk.tag.brill.Word' @staticmethod def extract_property(tokens, index): \"\"\"@return:",
"a named statistic collected during training, or a dictionary of",
"Word([1])), Template(Pos([1]), Word([0]), Word([-1])), Template(Pos([-1]), Word([-1]), Word([0])), Template(Pos([-1]), Word([0]), Word([1])),",
"json_tag = 'nltk.tag.brill.Pos' @staticmethod def extract_property(tokens, index): \"\"\"@return: The given",
"if True, print a list of all unused templates :type",
"that this tagger has learnt :return: the ordered list of",
"bit of magic to get all functions in this module",
"of tokens that have that tag. tag_to_positions = defaultdict(set) for",
"from nltk.tbl import Feature, Template from nltk import jsontags ######################################################################",
"version by # <NAME>, <NAME>, <NAME> # URL: <http://nltk.org/> #",
"nltk import jsontags ###################################################################### # Brill Templates ###################################################################### @jsontags.register_tag class",
"token's tag.\"\"\" return tokens[index][1] def nltkdemo18(): \"\"\" Return 18 templates,",
"to collect statistics on the test set for individual rules.",
"original nltk demo, and additionally a few multi-feature ones (the",
"###################################################################### # The Brill Tagger ###################################################################### @jsontags.register_tag class BrillTagger(TaggerI): \"\"\"",
"def extract_property(tokens, index): \"\"\"@return: The given token's tag.\"\"\" return tokens[index][1]",
"Template(Pos([1]), Pos([2])), Template(Pos([1]), Pos([2]), Word([1])) ] def brill24(): \"\"\" Return",
"Template(Pos([1]), Word([0]), Word([-1])), Template(Pos([-1]), Word([-1]), Word([0])), Template(Pos([-1]), Word([0]), Word([1])), Template(Pos([-2]),",
"class BrillTagger(TaggerI): \"\"\" Brill's transformational rule-based tagger. Brill taggers use",
"Create a dictionary that maps each tag to a list",
"unweighted measure (just counting the rules). This is less informative,",
"possible later use :type training_stats: dict \"\"\" self._initial_tagger = initial_tagger",
"Template(Pos([-1])), Template(Pos([-2])), Template(Pos([2])), Template(Pos([1, 2, 3])), Template(Pos([1, 2])), Template(Pos([-3, -2,",
"reverse=True) for (tid, testscore) in test_tplscores: s = \"{0:s} |{1:5d}",
"rule.apply(tagged_tokens) errors.append(counterrors(tagged_tokenses)) testing_stats['rulescores'] = [err0 - err1 for (err0, err1)",
"test_stats: dictionary of statistics collected during testing :type test_stats: dict",
"is less informative, though, as many low-score rules will appear",
"= sum(len(t) for t in sequences) testing_stats['sequencecount'] = len(sequences) tagged_tokenses",
"= [(tid, tpl) for (tid, tpl) in enumerate(Template.ALLTEMPLATES) if tid",
"| {5}\".format( tid, trainscore, trainscore/tottrainscores, template_counts[tid], template_counts[tid]/len(tids), Template.ALLTEMPLATES[int(tid)], ) print(s)",
"Brill taggers can be created directly, from an initial tagger",
"Template(Word([-2, -1])), Template(Word([1, 2])), Template(Word([-1, 0])), Template(Word([0, 1])), Template(Word([0])), Template(Word([-1]),",
"obj): _initial_tagger, _rules, _training_stats = obj return cls(_initial_tagger, _rules, _training_stats)",
"paper, Brill (1995) \"\"\" return [ Template(Pos([-1])), Template(Pos([1])), Template(Pos([-2])), Template(Pos([2])),",
"Word([-1]), Pos([-1])), Template(Word([0]), Word([1]), Pos([1])), ] def describe_template_sets(): \"\"\" Print",
"not break ties deterministically # between python versions and will",
"of nearby tokens. \"\"\" json_tag = 'nltk.tag.brill.Pos' @staticmethod def extract_property(tokens,",
"-1])), Template(Word([1, 2, 3])), Template(Word([-3, -2, -1])), Template(Word([0]), Pos([2])), Template(Word([0]),",
"TaggerTrainers available. \"\"\" json_tag = 'nltk.tag.BrillTagger' def __init__(self, initial_tagger, rules,",
"self._rules = tuple(rules) self._training_stats = training_stats def encode_json_obj(self): return self._initial_tagger,",
"statistics if no name given :param statistic: name of statistic",
"\"#ID | Score (train) | #Rules | Template\" print(head, \"\\n\",",
"original nltk demo, in multi-feature syntax \"\"\" return [ Template(Pos([-1])),",
"utf-8 -*- # Natural Language Toolkit: Transformation-based learning # #",
"tag_to_positions[tag].add(i) # Apply each rule, in order. Only try to",
"__init__(self, initial_tagger, rules, training_stats=None): \"\"\" :param initial_tagger: The initial tagger",
"this tagger :rtype: any (but usually a number) \"\"\" if",
"which examines the text (word) of nearby tokens. \"\"\" json_tag",
"in self._rules] train_stats = self.train_stats() trainscores = train_stats['rulescores'] assert len(trainscores)",
"at those positions. changed = rule.apply(tagged_tokens, positions) # Update tag_to_positions",
"rules and thus use batch_tag() instead :param sequences: lists of",
"Template(Pos([-1]), Word([-1]), Word([0])), Template(Pos([-1]), Word([0]), Word([1])), Template(Pos([-2]), Pos([-1])), Template(Pos([1]), Pos([2])),",
"print_train_stats(): print(\"TEMPLATE STATISTICS (TRAIN) {0} templates, {1} rules)\".format( len(template_counts), len(tids))",
"sum(trainscores) # det_tplsort() is for deterministic sorting; # the otherwise",
"the initial tagging. :type rules: list(TagRule) :param training_stats: A dictionary",
"print_unused_templates() print() def batch_tag_incremental(self, sequences, gold): \"\"\" Tags by applying",
"(tid, tpl) in enumerate(Template.ALLTEMPLATES) if tid not in usedtpls] print(\"UNUSED",
"seminal TBL paper, Brill (1995) \"\"\" return [ Template(Pos([-1])), Template(Pos([1])),",
"Template(Pos([1, 2, 3])), Template(Pos([-1]), Pos([1])), Template(Pos([-2]), Pos([-1])), Template(Pos([1]), Pos([2])), Template(Word([-1])),",
"return (tpl_value[1], repr(tpl_value[0])) def print_train_stats(): print(\"TEMPLATE STATISTICS (TRAIN) {0} templates,",
"of Rules \"\"\" return self._rules def train_stats(self, statistic=None): \"\"\" Return",
"all rules to a single sequence). The point is to",
"of statistic :type statistic: str :return: some statistic collected during",
"{4:.3f} | {5}\".format( tid, trainscore, trainscore/tottrainscores, template_counts[tid], template_counts[tid]/len(tids), Template.ALLTEMPLATES[int(tid)], )",
"in order. Only try to apply rules at # positions",
"len(tids)), ) print(\"TEST ({tokencount:7d} tokens) initial {initialerrors:5d} {initialacc:.4f} \" \"final:",
"Feature, Template from nltk import jsontags ###################################################################### # Brill Templates",
"Counter() for (tid, score) in zip(tids, trainscores): weighted_traincounts[tid] += score",
"positions where it might apply positions = tag_to_positions.get(rule.original_tag, []) #",
"Template.ALLTEMPLATES[int(tid)], ) print(s) def print_testtrain_stats(): testscores = test_stats['rulescores'] print(\"TEMPLATE STATISTICS",
"= 'nltk.tag.brill.Pos' @staticmethod def extract_property(tokens, index): \"\"\"@return: The given token's",
"test_stats['rulescores'] print(\"TEMPLATE STATISTICS (TEST AND TRAIN) ({0} templates, {1} rules)\".format(",
"] def describe_template_sets(): \"\"\" Print the available template sets in",
"this module templatesets = inspect.getmembers(sys.modules[__name__], inspect.isfunction) for (name, obj) in",
"[ Template(Pos([-1])), Template(Pos([1])), Template(Pos([-2])), Template(Pos([2])), Template(Pos([-2, -1])), Template(Pos([1, 2])), Template(Pos([-3,",
"to their relative contribution (summed for all rules created from",
"from an initial tagger and a list of transformational rules;",
"{initialacc:.4f} \" \"final: {finalerrors:5d} {finalacc:.4f} \".format(**train_stats)) weighted_testcounts = Counter() for",
"rule.apply(tagged_tokens, positions) # Update tag_to_positions with the positions of tags",
"#Rules | Template\" print(head, \"\\n\", \"-\" * len(head), sep=\"\") train_tplscores",
"Template(Word([-1]), Word([1])), ] def nltkdemo18plus(): \"\"\" Return 18 templates, from",
"gold: list of list of strings :returns: tuple of (tagged_sequences,",
"test_stats is None: print_train_stats() else: print_testtrain_stats() print() if printunused: print_unused_templates()",
"# Author: <NAME> <<EMAIL>> # based on previous (nltk2) version",
"For license information, see LICENSE.TXT from __future__ import print_function, division",
"description\" \"\"\" import inspect import sys # a bit of",
"\"\\n\") ###################################################################### # The Brill Tagger ###################################################################### @jsontags.register_tag class BrillTagger(TaggerI):",
"def rules(self): \"\"\" Return the ordered list of transformation rules",
"# Update tag_to_positions with the positions of tags that #",
"strings :returns: tuple of (tagged_sequences, ordered list of rule scores",
"({0} templates, {1} rules)\".format( len(template_counts), len(tids)), ) print(\"TEST ({tokencount:7d} tokens)",
"though, as many low-score rules will appear towards end of",
"The point is to collect statistics on the test set",
"in tagged_tokenses: rule.apply(tagged_tokens) errors.append(counterrors(tagged_tokenses)) testing_stats['rulescores'] = [err0 - err1 for",
"2])), Template(Pos([-3, -2, -1])), Template(Pos([1, 2, 3])), Template(Pos([-1]), Pos([1])), Template(Word([-1])),",
"-*- coding: utf-8 -*- # Natural Language Toolkit: Transformation-based learning",
"Pos([1])), Template(Pos([-2]), Pos([-1])), Template(Pos([1]), Pos([2])), Template(Word([-1])), Template(Word([1])), Template(Word([-2])), Template(Word([2])), Template(Word([-2,",
"and additionally a few multi-feature ones (the motivation is easy",
"of individual tokens. These transformation rules are specified by the",
"measure (just counting the rules). This is less informative, though,",
"nltkdemo18plus(): \"\"\" Return 18 templates, from the original nltk demo,",
"index, so will traverse the entire corpus N times for",
"and will break cross-version tests def det_tplsort(tpl_value): return (tpl_value[1], repr(tpl_value[0]))",
"instead :param sequences: lists of token sequences (sentences, in some",
"apply rules at # positions that have the desired original",
"= inspect.getmembers(sys.modules[__name__], inspect.isfunction) for (name, obj) in templatesets: if name",
"Word([0])), Template(Pos([-1]), Word([0]), Word([1])), Template(Pos([-2]), Pos([-1])), Template(Pos([1]), Pos([2])), Template(Pos([1]), Pos([2]),",
"[(tid, tpl) for (tid, tpl) in enumerate(Template.ALLTEMPLATES) if tid not",
"the tags of individual tokens. These transformation rules are specified",
"tpl) for (tid, tpl) in enumerate(Template.ALLTEMPLATES) if tid not in",
"indices of tokens that have that tag. tag_to_positions = defaultdict(set)",
"sum(t[1] != g[1] for pair in zip(xs, gold) for (t,",
"det_tplsort() is for deterministic sorting; # the otherwise convenient Counter.most_common()",
"3])), Template(Word([-1]), Word([1])), ] def nltkdemo18plus(): \"\"\" Return 18 templates,",
"that but the current nltk implementation cannot.) \"\"\" return [",
"= counterrors(tagged_tokenses) testing_stats['initialacc'] = 1 - testing_stats['initialerrors']/testing_stats['tokencount'] # Apply each",
"index): \"\"\"@return: The given token's tag.\"\"\" return tokens[index][1] def nltkdemo18():",
"Template(Word([0]), Word([1]), Pos([1])), ] def describe_template_sets(): \"\"\" Print the available",
":return: the ordered list of transformation rules that correct the",
"* len(head), sep=\"\") test_tplscores = sorted(weighted_testcounts.items(), key=det_tplsort, reverse=True) for (tid,",
"Template(Word([2])), Template(Word([1])), Template(Word([-1])), Template(Pos([-1]), Pos([1])), Template(Pos([1]), Pos([2])), Template(Pos([-1]), Pos([-2])), Template(Pos([1])),",
"-*- # Natural Language Toolkit: Transformation-based learning # # Copyright",
"[err0 - err1 for (err0, err1) in zip(errors, errors[1:])] testing_stats['finalerrors']",
"tagging :rtype: list of Rules \"\"\" return self._rules def train_stats(self,",
"list of transformation rules that should be used to correct",
"text.\"\"\" return tokens[index][0] @jsontags.register_tag class Pos(Feature): \"\"\" Feature which examines",
"all available statistics if no name given :param statistic: name",
"Template(Word([1])), Template(Word([-2])), Template(Word([2])), Template(Word([-2, -1])), Template(Word([1, 2])), Template(Word([-1, 0])), Template(Word([0,",
"unfortunately # does not break ties deterministically # between python",
"rules to a single sequence). The point is to collect",
"dictionary that maps each tag to a list of the",
"all rules created from a given template, weighted by score)",
"tag_to_positions = defaultdict(set) for i, (token, tag) in enumerate(tagged_tokens): tag_to_positions[tag].add(i)",
"Template(Word([0]), Word([-1])), Template(Word([0]), Word([1])), Template(Word([0]), Word([2])), Template(Word([0]), Word([-2])), Template(Word([1, 2])),",
"testing_stats['finalerrors'] = errors[-1] testing_stats['finalacc'] = 1 - testing_stats['finalerrors']/testing_stats['tokencount'] return (tagged_tokenses,",
"def extract_property(tokens, index): \"\"\"@return: The given token's text.\"\"\" return tokens[index][0]",
"at # positions that have the desired original tag. for",
"usually numbers) :param printunused: if True, print a list of",
"Template(Word([0]), Word([2])), Template(Word([0]), Word([-2])), Template(Word([1, 2])), Template(Word([-2, -1])), Template(Word([1, 2,",
"many low-score rules will appear towards end of training. :param",
"\"final: {finalerrors:5d} {finalacc:.4f} \".format(**test_stats)) print(\"TRAIN ({tokencount:7d} tokens) initial {initialerrors:5d} {initialacc:.4f}",
"some applications) to be tagged :type sequences: list of list",
"# Inherit documentation from TaggerI # Run the initial tagger.",
"tags that # were modified. for i in changed: tag_to_positions[rule.original_tag].remove(i)",
"LICENSE.TXT from __future__ import print_function, division from collections import defaultdict,",
"\"\"\" Brill's transformational rule-based tagger. Brill taggers use an initial",
"sorted(weighted_testcounts.items(), key=det_tplsort, reverse=True) for (tid, testscore) in test_tplscores: s =",
"\"\"\" Feature which examines the tags of nearby tokens. \"\"\"",
"= self._initial_tagger.tag(tokens) # Create a dictionary that maps each tag",
"== len(tids), \"corrupt statistics: \" \\ \"{0} train scores for",
"the initial tagging :rtype: list of Rules \"\"\" return self._rules",
"(the motivation is easy comparison with nltkdemo18) \"\"\" return nltkdemo18()",
"of transformational rules; but more often, Brill taggers are created",
"and a list of transformational rules; but more often, Brill",
"# <NAME>, <NAME>, <NAME> # URL: <http://nltk.org/> # For license",
"rules from a training corpus, using one of the TaggerTrainers",
"Pos([-1])), Template(Word([1]), Pos([1])), Template(Word([0]), Word([-1]), Pos([-1])), Template(Word([0]), Word([1]), Pos([1])), ]",
"Pos([2])), Template(Pos([-1]), Pos([-2])), Template(Pos([1])), Template(Pos([-1])), Template(Pos([-2])), Template(Pos([2])), Template(Pos([1, 2, 3])),",
"tid, trainscore, trainscore/tottrainscores, template_counts[tid], template_counts[tid]/len(tids), Template.ALLTEMPLATES[int(tid)], ) print(s) def print_testtrain_stats():",
"learnt :return: the ordered list of transformation rules that correct",
"transformation rules that this tagger has learnt :return: the ordered",
"str(tpl))) if test_stats is None: print_train_stats() else: print_testtrain_stats() print() if",
"Natural Language Toolkit: Transformation-based learning # # Copyright (C) 2001-2018",
"for (tid, score) in zip(tids, trainscores): weighted_traincounts[tid] += score tottrainscores",
"weighted_traincounts = Counter() for (tid, score) in zip(tids, trainscores): weighted_traincounts[tid]",
"list of list of strings :param gold: the gold standard",
"that # were modified. for i in changed: tag_to_positions[rule.original_tag].remove(i) tag_to_positions[rule.replacement_tag].add(i)",
"to correct the initial tagging. :type rules: list(TagRule) :param training_stats:",
"of statistics collected during testing :type test_stats: dict of str",
"instead. There is also an unweighted measure (just counting the",
"dictionary of statistics collected during training, for possible later use",
"desired original tag. for rule in self._rules: # Find the",
"a single sequence). The point is to collect statistics on",
"print_function, division from collections import defaultdict, Counter from nltk.tag import",
"list of transformational rules; but more often, Brill taggers are",
"ordered list of transformation rules that should be used to",
"!= g[1] for pair in zip(xs, gold) for (t, g)",
"testscore/tottestscores, weighted_traincounts[tid], weighted_traincounts[tid]/tottrainscores, template_counts[tid], template_counts[tid]/len(tids), Template.ALLTEMPLATES[int(tid)], ) print(s) def print_unused_templates():",
"(37 is after excluding a handful which do not condition",
"= 'nltk.tag.brill.Word' @staticmethod def extract_property(tokens, index): \"\"\"@return: The given token's",
"# Natural Language Toolkit: Transformation-based learning # # Copyright (C)",
"training_stats def encode_json_obj(self): return self._initial_tagger, self._rules, self._training_stats @classmethod def decode_json_obj(cls,",
"Template(Pos([-1]), Pos([1])), Template(Word([-1])), Template(Word([1])), Template(Word([-2])), Template(Word([2])), Template(Word([-2, -1])), Template(Word([1, 2])),",
"{initialerrors:5d} {initialacc:.4f} \" \"final: {finalerrors:5d} {finalacc:.4f} \".format(**test_stats)) print(\"TRAIN ({tokencount:7d} tokens)",
"\"{0} train scores for {1} rules\".format(trainscores, tids) template_counts = Counter(tids)",
"test_tplscores: s = \"{0:s} |{1:5d} {2:6.3f} | {3:4d} {4:.3f} |{5:4d}",
"performance on the test set. If no test_stats, then statistics",
"| Score (train) | #Rules | Template\" print(head, \"\\n\", \"-\"",
"def tag(self, tokens): # Inherit documentation from TaggerI # Run",
"testing_stats['tokencount'] = sum(len(t) for t in sequences) testing_stats['sequencecount'] = len(sequences)",
"or a dictionary of all available statistics if no name",
"original tag. for rule in self._rules: # Find the positions",
"Template(Pos([2])), Template(Pos([-2, -1])), Template(Pos([1, 2])), Template(Pos([-3, -2, -1])), Template(Pos([1, 2,",
"of nearby tokens. \"\"\" json_tag = 'nltk.tag.brill.Word' @staticmethod def extract_property(tokens,",
"Apply each rule to the entire corpus, in order errors",
"18 templates, from the original nltk demo, in multi-feature syntax",
"sum(testscores) head = \"#ID | Score (test) | Score (train)",
"{1} rules)\".format( len(template_counts), len(tids)), ) print(\"TEST ({tokencount:7d} tokens) initial {initialerrors:5d}",
"in self._rules: for tagged_tokens in tagged_tokenses: rule.apply(tagged_tokens) errors.append(counterrors(tagged_tokenses)) testing_stats['rulescores'] =",
"fntbl can do that but the current nltk implementation cannot.)",
"do not condition on Pos[0]; fntbl can do that but",
"test_tplscores = sorted(weighted_testcounts.items(), key=det_tplsort, reverse=True) for (tid, testscore) in test_tplscores:",
"during training, for possible later use :type training_stats: dict \"\"\"",
"Template(Word([-1]), Word([0]), Word([1])), Template(Word([0]), Word([-1])), Template(Word([0]), Word([1])), Template(Word([0]), Word([2])), Template(Word([0]),",
"Counter from nltk.tag import TaggerI from nltk.tbl import Feature, Template",
"list of all unused templates :type printunused: bool :return: None",
"Pos([-2])), Template(Pos([1])), Template(Pos([-1])), Template(Pos([-2])), Template(Pos([2])), Template(Pos([1, 2, 3])), Template(Pos([1, 2])),",
"2])), Template(Word([-2, -1])), Template(Word([1, 2, 3])), Template(Word([-3, -2, -1])), Template(Word([0]),",
"Template(Pos([-3, -2, -1])), Template(Pos([-2, -1])), Template(Pos([1]), Word([0]), Word([1])), Template(Pos([1]), Word([0]),",
"that have the desired original tag. for rule in self._rules:",
"t in sequences) testing_stats['sequencecount'] = len(sequences) tagged_tokenses = [self._initial_tagger.tag(tokens) for",
"from a given template, weighted by score) to the performance",
"tag sequence to a text; and then apply an ordered",
"a given template, weighted by score) to the performance on",
"score) in zip(tids, testscores): weighted_testcounts[tid] += score tottestscores = sum(testscores)",
":type sequences: list of list of strings :param gold: the",
"name given :param statistic: name of statistic :type statistic: str",
"Template(Pos([1, 2, 3])), Template(Pos([-1]), Pos([1])), Template(Word([-1])), Template(Word([1])), Template(Word([-2])), Template(Word([2])), Template(Word([-2,",
"changed = rule.apply(tagged_tokens, positions) # Update tag_to_positions with the positions",
"Template(Word([-2])), Template(Word([2])), Template(Word([-2, -1])), Template(Word([1, 2])), Template(Word([-1, 0])), Template(Word([0, 1])),",
"tokens[index][0] @jsontags.register_tag class Pos(Feature): \"\"\" Feature which examines the tags",
"Pos([1])), Template(Word([0]), Word([-1]), Pos([-1])), Template(Word([0]), Word([1]), Pos([1])), ] def describe_template_sets():",
"2])), Template(Word([-3, -2, -1])), Template(Word([1, 2, 3])), Template(Word([-1]), Word([1])), ]",
"appear towards end of training. :param test_stats: dictionary of statistics",
"deterministically # between python versions and will break cross-version tests",
"an ordered list of transformational rules to correct the tags",
"Template(Pos([-2, -1])), Template(Pos([1]), Word([0]), Word([1])), Template(Pos([1]), Word([0]), Word([-1])), Template(Pos([-1]), Word([-1]),",
"not in usedtpls] print(\"UNUSED TEMPLATES ({0})\".format(len(unused))) for (tid, tpl) in",
"nearby tokens. \"\"\" json_tag = 'nltk.tag.brill.Word' @staticmethod def extract_property(tokens, index):",
"det_tplsort(tpl_value): return (tpl_value[1], repr(tpl_value[0])) def print_train_stats(): print(\"TEMPLATE STATISTICS (TRAIN) {0}",
"self._training_stats else: return self._training_stats.get(statistic) def tag(self, tokens): # Inherit documentation",
"sequences] testing_stats['initialerrors'] = counterrors(tagged_tokenses) testing_stats['initialacc'] = 1 - testing_stats['initialerrors']/testing_stats['tokencount'] #",
"Template(Word([0]), Pos([-2])), Template(Word([0]), Pos([1])), Template(Word([0]), Pos([-1])), Template(Word([0])), Template(Word([-2])), Template(Word([2])), Template(Word([1])),",
"taggers use an initial tagger (such as ``tag.DefaultTagger``) to assign",
"tagged_tokenses: rule.apply(tagged_tokens) errors.append(counterrors(tagged_tokenses)) testing_stats['rulescores'] = [err0 - err1 for (err0,",
"Template(Word([1, 2])), Template(Word([-1, 0])), Template(Word([0, 1])), Template(Word([0])), Template(Word([-1]), Pos([-1])), Template(Word([1]),",
"zip(tids, testscores): weighted_testcounts[tid] += score tottestscores = sum(testscores) head =",
"tag.\"\"\" return tokens[index][1] def nltkdemo18(): \"\"\" Return 18 templates, from",
"towards end of training. :param test_stats: dictionary of statistics collected",
"sequences, gold): \"\"\" Tags by applying each rule to the",
"<<EMAIL>> # based on previous (nltk2) version by # <NAME>,",
"] def brill24(): \"\"\" Return 24 templates of the seminal",
"informative, though, as many low-score rules will appear towards end",
"<NAME>, <NAME>, <NAME> # URL: <http://nltk.org/> # For license information,",
"name of statistic :type statistic: str :return: some statistic collected",
"An ordered list of transformation rules that should be used",
"{4:.3f} |{5:4d} {6:.3f} | {7:s}\".format( tid, testscore, testscore/tottestscores, weighted_traincounts[tid], weighted_traincounts[tid]/tottrainscores,",
"Brill taggers use an initial tagger (such as ``tag.DefaultTagger``) to",
"efficiency. If test_stats is available, the templates are ranked according",
"usedtpls = set(int(tid) for tid in tids) unused = [(tid,",
"transformation rules that should be used to correct the initial",
"Copyright (C) 2001-2018 NLTK Project # Author: <NAME> <<EMAIL>> #",
"trainscores = train_stats['rulescores'] assert len(trainscores) == len(tids), \"corrupt statistics: \"",
"in sequences) testing_stats['sequencecount'] = len(sequences) tagged_tokenses = [self._initial_tagger.tag(tokens) for tokens",
"might apply positions = tag_to_positions.get(rule.original_tag, []) # Apply the rule",
"[self._initial_tagger.tag(tokens) for tokens in sequences] testing_stats['initialerrors'] = counterrors(tagged_tokenses) testing_stats['initialacc'] =",
"nltkdemo18) \"\"\" return nltkdemo18() + [ Template(Word([-1]), Pos([1])), Template(Pos([-1]), Word([1])),",
"printunused=True): \"\"\" Print a list of all templates, ranked according",
"= initial_tagger self._rules = tuple(rules) self._training_stats = training_stats def encode_json_obj(self):",
"return nltkdemo18() + [ Template(Word([-1]), Pos([1])), Template(Pos([-1]), Word([1])), Template(Word([-1]), Word([0]),",
"Template(Word([2])), Template(Word([-2, -1])), Template(Word([1, 2])), Template(Word([-1, 0])), Template(Word([0, 1])), Template(Word([0])),",
"of strings :param gold: the gold standard :type gold: list",
"= set(int(tid) for tid in tids) unused = [(tid, tpl)",
"TRAIN) ({0} templates, {1} rules)\".format( len(template_counts), len(tids)), ) print(\"TEST ({tokencount:7d}",
"tag_to_positions.get(rule.original_tag, []) # Apply the rule at those positions. changed",
"tagger. Brill taggers use an initial tagger (such as ``tag.DefaultTagger``)",
"rule to the entire corpus, in order errors = [testing_stats['initialerrors']]",
"token sequences (sentences, in some applications) to be tagged :type",
"(tid, score) in zip(tids, testscores): weighted_testcounts[tid] += score tottestscores =",
"testing_stats['initialerrors']/testing_stats['tokencount'] # Apply each rule to the entire corpus, in",
"Template(Word([0]), Pos([2])), Template(Word([0]), Pos([-2])), Template(Word([0]), Pos([1])), Template(Word([0]), Pos([-1])), Template(Word([0])), Template(Word([-2])),",
"and then apply an ordered list of transformational rules to",
"Pos([-1])), Template(Word([0])), Template(Word([-2])), Template(Word([2])), Template(Word([1])), Template(Word([-1])), Template(Pos([-1]), Pos([1])), Template(Pos([1]), Pos([2])),",
"(test) | Score (train) | #Rules | Template\" print(head, \"\\n\",",
"| {7:s}\".format( tid, testscore, testscore/tottestscores, weighted_traincounts[tid], weighted_traincounts[tid]/tottrainscores, template_counts[tid], template_counts[tid]/len(tids), Template.ALLTEMPLATES[int(tid)],",
"Return 18 templates, from the original nltk demo, and additionally",
":param test_stats: dictionary of statistics collected during testing :type test_stats:",
"all templates, ranked according to efficiency. If test_stats is available,",
"{3:4d} {4:.3f} |{5:4d} {6:.3f} | {7:s}\".format( tid, testscore, testscore/tottestscores, weighted_traincounts[tid],",
"in sequences] testing_stats['initialerrors'] = counterrors(tagged_tokenses) testing_stats['initialacc'] = 1 - testing_stats['initialerrors']/testing_stats['tokencount']",
"versions and will break cross-version tests def det_tplsort(tpl_value): return (tpl_value[1],",
"{} testing_stats['tokencount'] = sum(len(t) for t in sequences) testing_stats['sequencecount'] =",
"2, 3])), Template(Pos([1, 2])), Template(Pos([-3, -2, -1])), Template(Pos([-2, -1])), Template(Pos([1]),",
"statistic is None: return self._training_stats else: return self._training_stats.get(statistic) def tag(self,",
"with nltkdemo18) \"\"\" return nltkdemo18() + [ Template(Word([-1]), Pos([1])), Template(Pos([-1]),",
"template sets in this demo, with a short description\" \"\"\"",
"\"\"\" json_tag = 'nltk.tag.BrillTagger' def __init__(self, initial_tagger, rules, training_stats=None): \"\"\"",
"a handful which do not condition on Pos[0]; fntbl can",
"Template(Word([-1])), Template(Word([1])), Template(Word([-2])), Template(Word([2])), Template(Word([-2, -1])), Template(Word([1, 2])), Template(Word([-1, 0])),",
"\".format(**train_stats)) weighted_testcounts = Counter() for (tid, score) in zip(tids, testscores):",
"template_counts[tid]/len(tids), Template.ALLTEMPLATES[int(tid)], ) print(s) def print_unused_templates(): usedtpls = set(int(tid) for",
"templatesets = inspect.getmembers(sys.modules[__name__], inspect.isfunction) for (name, obj) in templatesets: if",
"of the # indices of tokens that have that tag.",
"list of transformational rules to correct the tags of individual",
"based on previous (nltk2) version by # <NAME>, <NAME>, <NAME>",
"g) in zip(*pair)) testing_stats = {} testing_stats['tokencount'] = sum(len(t) for",
"Template from nltk import jsontags ###################################################################### # Brill Templates ######################################################################",
"len(template_counts), len(tids)), ) print(\"TEST ({tokencount:7d} tokens) initial {initialerrors:5d} {initialacc:.4f} \"",
"Template(Pos([-2, -1])), Template(Pos([1, 2])), Template(Pos([-3, -2, -1])), Template(Pos([1, 2, 3])),",
"taggers can be created directly, from an initial tagger and",
"statistics collected during training, for possible later use :type training_stats:",
"sequences (sentences, in some applications) to be tagged :type sequences:",
"2])), Template(Word([-1, 0])), Template(Word([0, 1])), Template(Word([0])), Template(Word([-1]), Pos([-1])), Template(Word([1]), Pos([1])),",
"for possible later use :type training_stats: dict \"\"\" self._initial_tagger =",
"import print_function, division from collections import defaultdict, Counter from nltk.tag",
"their relative contribution (summed for all rules created from a",
"previous (nltk2) version by # <NAME>, <NAME>, <NAME> # URL:",
"from the postagging task of the fntbl distribution http://www.cs.jhu.edu/~rflorian/fntbl/ (37",
"single sequence). The point is to collect statistics on the",
"Template(Word([-3, -2, -1])), Template(Word([1, 2, 3])), Template(Word([-1]), Word([1])), ] def",
"Word([1])), Template(Pos([-2]), Pos([-1])), Template(Pos([1]), Pos([2])), Template(Pos([1]), Pos([2]), Word([1])) ] def",
"sep=\"\") test_tplscores = sorted(weighted_testcounts.items(), key=det_tplsort, reverse=True) for (tid, testscore) in",
"Brill (1995) \"\"\" return [ Template(Pos([-1])), Template(Pos([1])), Template(Pos([-2])), Template(Pos([2])), Template(Pos([-2,",
"the entire corpus, in order errors = [testing_stats['initialerrors']] for rule",
"token's text.\"\"\" return tokens[index][0] @jsontags.register_tag class Pos(Feature): \"\"\" Feature which",
"\"\"\"@return: The given token's text.\"\"\" return tokens[index][0] @jsontags.register_tag class Pos(Feature):",
"not care about statistics for individual rules and thus use",
"# # Copyright (C) 2001-2018 NLTK Project # Author: <NAME>",
"individual rules. NOTE: This is inefficient (does not build any",
"those positions. changed = rule.apply(tagged_tokens, positions) # Update tag_to_positions with",
"in unused: print(\"{0:03d} {1:s}\".format(tid, str(tpl))) if test_stats is None: print_train_stats()",
"nltk demo, and additionally a few multi-feature ones (the motivation",
"postagging task of the fntbl distribution http://www.cs.jhu.edu/~rflorian/fntbl/ (37 is after",
"of all unused templates :type printunused: bool :return: None :rtype:",
"(nltk2) version by # <NAME>, <NAME>, <NAME> # URL: <http://nltk.org/>",
"| Template\" print(head, \"\\n\", \"-\" * len(head), sep=\"\") train_tplscores =",
"tpl) in enumerate(Template.ALLTEMPLATES) if tid not in usedtpls] print(\"UNUSED TEMPLATES",
"statistics for individual rules and thus use batch_tag() instead :param",
"Word([2])), Template(Word([0]), Word([-2])), Template(Word([1, 2])), Template(Word([-2, -1])), Template(Word([1, 2, 3])),",
"Feature which examines the tags of nearby tokens. \"\"\" json_tag",
"Template(Word([1, 2])), Template(Word([-2, -1])), Template(Word([1, 2, 3])), Template(Word([-3, -2, -1])),",
"\"\"\" if statistic is None: return self._training_stats else: return self._training_stats.get(statistic)",
"Template(Pos([-2]), Pos([-1])), Template(Pos([1]), Pos([2])), Template(Word([-1])), Template(Word([1])), Template(Word([-2])), Template(Word([2])), Template(Word([-2, -1])),",
"Template(Pos([-1]), Pos([1])), Template(Pos([1]), Pos([2])), Template(Pos([-1]), Pos([-2])), Template(Pos([1])), Template(Pos([-1])), Template(Pos([-2])), Template(Pos([2])),",
"the original nltk demo, in multi-feature syntax \"\"\" return [",
"# Find the positions where it might apply positions =",
"any (but usually numbers) :param printunused: if True, print a",
"defaultdict, Counter from nltk.tag import TaggerI from nltk.tbl import Feature,",
"break ties deterministically # between python versions and will break",
"to get all functions in this module templatesets = inspect.getmembers(sys.modules[__name__],",
"import Feature, Template from nltk import jsontags ###################################################################### # Brill",
"37 templates taken from the postagging task of the fntbl",
"corpus (rather than all rules to a single sequence). The",
"({0})\".format(len(unused))) for (tid, tpl) in unused: print(\"{0:03d} {1:s}\".format(tid, str(tpl))) if",
"for individual rules. NOTE: This is inefficient (does not build",
"license information, see LICENSE.TXT from __future__ import print_function, division from",
"for tokens in sequences] testing_stats['initialerrors'] = counterrors(tagged_tokenses) testing_stats['initialacc'] = 1",
"extract_property(tokens, index): \"\"\"@return: The given token's text.\"\"\" return tokens[index][0] @jsontags.register_tag",
"number) \"\"\" if statistic is None: return self._training_stats else: return",
"by learning rules from a training corpus, using one of",
"sorted(weighted_traincounts.items(), key=det_tplsort, reverse=True) for (tid, trainscore) in train_tplscores: s =",
"Template(Pos([-1]), Word([0]), Word([1])), Template(Pos([-1]), Word([0]), Pos([1])), ] def fntbl37(): \"\"\"",
"template_counts[tid]/len(tids), Template.ALLTEMPLATES[int(tid)], ) print(s) def print_testtrain_stats(): testscores = test_stats['rulescores'] print(\"TEMPLATE",
"training of this tagger :rtype: any (but usually a number)",
"The given token's tag.\"\"\" return tokens[index][1] def nltkdemo18(): \"\"\" Return",
"templates, from the original nltk demo, in multi-feature syntax \"\"\"",
"None: return self._training_stats else: return self._training_stats.get(statistic) def tag(self, tokens): #",
"syntax \"\"\" return [ Template(Pos([-1])), Template(Pos([1])), Template(Pos([-2])), Template(Pos([2])), Template(Pos([-2, -1])),",
"\"-\" * len(head), sep=\"\") test_tplscores = sorted(weighted_testcounts.items(), key=det_tplsort, reverse=True) for",
"in zip(xs, gold) for (t, g) in zip(*pair)) testing_stats =",
"Pos([2])), Template(Word([0]), Pos([-2])), Template(Word([0]), Pos([1])), Template(Word([0]), Pos([-1])), Template(Word([0])), Template(Word([-2])), Template(Word([2])),",
"of list of strings :returns: tuple of (tagged_sequences, ordered list",
"template_counts[tid], template_counts[tid]/len(tids), Template.ALLTEMPLATES[int(tid)], ) print(s) def print_unused_templates(): usedtpls = set(int(tid)",
"for {1} rules\".format(trainscores, tids) template_counts = Counter(tids) weighted_traincounts = Counter()",
"is easy comparison with nltkdemo18) \"\"\" return nltkdemo18() + [",
"\" \"final: {finalerrors:5d} {finalacc:.4f} \".format(**test_stats)) print(\"TRAIN ({tokencount:7d} tokens) initial {initialerrors:5d}",
"len(head), sep=\"\") test_tplscores = sorted(weighted_testcounts.items(), key=det_tplsort, reverse=True) for (tid, testscore)",
"= \"{0} | {1:5d} {2:5.3f} |{3:4d} {4:.3f} | {5}\".format( tid,",
"taggers are created by learning rules from a training corpus,",
"templates, ranked according to efficiency. If test_stats is available, the",
"multi-feature syntax \"\"\" return [ Template(Pos([-1])), Template(Pos([1])), Template(Pos([-2])), Template(Pos([2])), Template(Pos([-2,",
"the ordered list of transformation rules that this tagger has",
"rule-based tagger. Brill taggers use an initial tagger (such as",
"print(s) def print_testtrain_stats(): testscores = test_stats['rulescores'] print(\"TEMPLATE STATISTICS (TEST AND",
"= tag_to_positions.get(rule.original_tag, []) # Apply the rule at those positions.",
"short description\" \"\"\" import inspect import sys # a bit",
"where it might apply positions = tag_to_positions.get(rule.original_tag, []) # Apply",
"of the fntbl distribution http://www.cs.jhu.edu/~rflorian/fntbl/ (37 is after excluding a",
"training_stats: A dictionary of statistics collected during training, for possible",
"import TaggerI from nltk.tbl import Feature, Template from nltk import",
"errors.append(counterrors(tagged_tokenses)) testing_stats['rulescores'] = [err0 - err1 for (err0, err1) in",
"from TaggerI # Run the initial tagger. tagged_tokens = self._initial_tagger.tag(tokens)",
"templates :type printunused: bool :return: None :rtype: None \"\"\" tids",
"- testing_stats['initialerrors']/testing_stats['tokencount'] # Apply each rule to the entire corpus,",
"Template(Pos([1, 2])), Template(Pos([-3, -2, -1])), Template(Pos([1, 2, 3])), Template(Pos([-1]), Pos([1])),",
"(but usually numbers) :param printunused: if True, print a list",
"train_tplscores = sorted(weighted_traincounts.items(), key=det_tplsort, reverse=True) for (tid, trainscore) in train_tplscores:",
"an initial tag sequence to a text; and then apply",
"train_tplscores: s = \"{0} | {1:5d} {2:5.3f} |{3:4d} {4:.3f} |",
"test_stats, then statistics collected during training are used instead. There",
"counting the rules). This is less informative, though, as many",
"STATISTICS (TRAIN) {0} templates, {1} rules)\".format( len(template_counts), len(tids)) ) print(\"TRAIN",
"{initialerrors:5d} {initialacc:.4f} \" \"final: {finalerrors:5d} {finalacc:.4f} \".format(**train_stats)) weighted_testcounts = Counter()",
"collected during training, for possible later use :type training_stats: dict",
"import sys # a bit of magic to get all",
"# For license information, see LICENSE.TXT from __future__ import print_function,",
"== \"describe_template_sets\": continue print(name, obj.__doc__, \"\\n\") ###################################################################### # The Brill",
"is for deterministic sorting; # the otherwise convenient Counter.most_common() unfortunately",
"on the test set for individual rules. NOTE: This is",
"initial_tagger: TaggerI :param rules: An ordered list of transformation rules",
"http://www.cs.jhu.edu/~rflorian/fntbl/ (37 is after excluding a handful which do not",
"from nltk.tag import TaggerI from nltk.tbl import Feature, Template from",
"nltk.tag import TaggerI from nltk.tbl import Feature, Template from nltk",
"is to collect statistics on the test set for individual",
"TaggerI # Run the initial tagger. tagged_tokens = self._initial_tagger.tag(tokens) #",
"(summed for all rules created from a given template, weighted",
"= len(sequences) tagged_tokenses = [self._initial_tagger.tag(tokens) for tokens in sequences] testing_stats['initialerrors']",
":param initial_tagger: The initial tagger :type initial_tagger: TaggerI :param rules:",
"NLTK Project # Author: <NAME> <<EMAIL>> # based on previous",
"\"\"\" return [ Template(Pos([-1])), Template(Pos([1])), Template(Pos([-2])), Template(Pos([2])), Template(Pos([-2, -1])), Template(Pos([1,",
"{1} rules)\".format( len(template_counts), len(tids)) ) print(\"TRAIN ({tokencount:7d} tokens) initial {initialerrors:5d}",
"in templatesets: if name == \"describe_template_sets\": continue print(name, obj.__doc__, \"\\n\")",
"counterrors(xs): return sum(t[1] != g[1] for pair in zip(xs, gold)",
"to a text; and then apply an ordered list of",
"@jsontags.register_tag class BrillTagger(TaggerI): \"\"\" Brill's transformational rule-based tagger. Brill taggers",
"self._rules, self._training_stats @classmethod def decode_json_obj(cls, obj): _initial_tagger, _rules, _training_stats =",
"+ [ Template(Word([-1]), Pos([1])), Template(Pos([-1]), Word([1])), Template(Word([-1]), Word([0]), Pos([1])), Template(Pos([-1]),",
"tag) in enumerate(tagged_tokens): tag_to_positions[tag].add(i) # Apply each rule, in order.",
"templates taken from the postagging task of the fntbl distribution",
"| #Rules | Template\" print(head, \"\\n\", \"-\" * len(head), sep=\"\")",
"= obj return cls(_initial_tagger, _rules, _training_stats) def rules(self): \"\"\" Return",
"= \"#ID | Score (test) | Score (train) | #Rules",
"the positions of tags that # were modified. for i",
"the tags of nearby tokens. \"\"\" json_tag = 'nltk.tag.brill.Pos' @staticmethod",
"[ Template(Word([-1]), Pos([1])), Template(Pos([-1]), Word([1])), Template(Word([-1]), Word([0]), Pos([1])), Template(Pos([-1]), Word([0]),",
"Template\" print(head, \"\\n\", \"-\" * len(head), sep=\"\") test_tplscores = sorted(weighted_testcounts.items(),",
"can do that but the current nltk implementation cannot.) \"\"\"",
"Pos([-1])), Template(Pos([1]), Pos([2])), Template(Pos([1]), Pos([2]), Word([1])) ] def brill24(): \"\"\"",
"testing_stats['rulescores'] = [err0 - err1 for (err0, err1) in zip(errors,",
"in tids) unused = [(tid, tpl) for (tid, tpl) in",
"rule, in order. Only try to apply rules at #",
"describe_template_sets(): \"\"\" Print the available template sets in this demo,",
"used to correct the initial tagging. :type rules: list(TagRule) :param",
"[r.templateid for r in self._rules] train_stats = self.train_stats() trainscores =",
"training. :param test_stats: dictionary of statistics collected during testing :type",
"_rules, _training_stats = obj return cls(_initial_tagger, _rules, _training_stats) def rules(self):",
":param training_stats: A dictionary of statistics collected during training, for",
"\"\\n\", \"-\" * len(head), sep=\"\") test_tplscores = sorted(weighted_testcounts.items(), key=det_tplsort, reverse=True)",
"__future__ import print_function, division from collections import defaultdict, Counter from",
"\"\"\" Return 18 templates, from the original nltk demo, in",
"for deterministic sorting; # the otherwise convenient Counter.most_common() unfortunately #",
"\"corrupt statistics: \" \\ \"{0} train scores for {1} rules\".format(trainscores,",
"'nltk.tag.brill.Pos' @staticmethod def extract_property(tokens, index): \"\"\"@return: The given token's tag.\"\"\"",
"head = \"#ID | Score (train) | #Rules | Template\"",
":type statistic: str :return: some statistic collected during training of",
"Template(Word([-2, -1])), Template(Word([1, 2])), Template(Word([-3, -2, -1])), Template(Word([1, 2, 3])),",
"tag to a list of the # indices of tokens",
"-1])), Template(Word([0]), Pos([2])), Template(Word([0]), Pos([-2])), Template(Word([0]), Pos([1])), Template(Word([0]), Pos([-1])), Template(Word([0])),",
"to assign an initial tag sequence to a text; and",
"for (err0, err1) in zip(errors, errors[1:])] testing_stats['finalerrors'] = errors[-1] testing_stats['finalacc']",
"be tagged :type sequences: list of list of strings :param",
"# Run the initial tagger. tagged_tokens = self._initial_tagger.tag(tokens) # Create",
"@staticmethod def extract_property(tokens, index): \"\"\"@return: The given token's tag.\"\"\" return",
"###################################################################### # Brill Templates ###################################################################### @jsontags.register_tag class Word(Feature): \"\"\" Feature",
"collected during training of this tagger :rtype: any (but usually",
"tagged_tokenses = [self._initial_tagger.tag(tokens) for tokens in sequences] testing_stats['initialerrors'] = counterrors(tagged_tokenses)",
"score) in zip(tids, trainscores): weighted_traincounts[tid] += score tottrainscores = sum(trainscores)",
"{initialerrors:5d} {initialacc:.4f} \" \"final: {finalerrors:5d} {finalacc:.4f} \".format(**train_stats)) head = \"#ID",
"but the current nltk implementation cannot.) \"\"\" return [ Template(Word([0]),",
"Word([0]), Word([1])), Template(Pos([-1]), Word([0]), Pos([1])), ] def fntbl37(): \"\"\" Return",
"on Pos[0]; fntbl can do that but the current nltk",
"{1:s}\".format(tid, str(tpl))) if test_stats is None: print_train_stats() else: print_testtrain_stats() print()",
"no test_stats, then statistics collected during training are used instead.",
"Print the available template sets in this demo, with a",
"rules(self): \"\"\" Return the ordered list of transformation rules that",
"tag. for rule in self._rules: # Find the positions where",
"ones (the motivation is easy comparison with nltkdemo18) \"\"\" return",
"print() def batch_tag_incremental(self, sequences, gold): \"\"\" Tags by applying each",
"testscores): weighted_testcounts[tid] += score tottestscores = sum(testscores) head = \"#ID",
"Template(Pos([1, 2, 3])), Template(Pos([1, 2])), Template(Pos([-3, -2, -1])), Template(Pos([-2, -1])),",
"import jsontags ###################################################################### # Brill Templates ###################################################################### @jsontags.register_tag class Word(Feature):",
"the performance on the test set. If no test_stats, then",
"key=det_tplsort, reverse=True) for (tid, testscore) in test_tplscores: s = \"{0:s}",
"Counter.most_common() unfortunately # does not break ties deterministically # between",
"Pos([2])), Template(Pos([1]), Pos([2]), Word([1])) ] def brill24(): \"\"\" Return 24",
"# were modified. for i in changed: tag_to_positions[rule.original_tag].remove(i) tag_to_positions[rule.replacement_tag].add(i) return",
"Pos([2])), Template(Word([-1])), Template(Word([1])), Template(Word([-2])), Template(Word([2])), Template(Word([-2, -1])), Template(Word([1, 2])), Template(Word([-1,",
"tokens) initial {initialerrors:5d} {initialacc:.4f} \" \"final: {finalerrors:5d} {finalacc:.4f} \".format(**train_stats)) weighted_testcounts",
"that should be used to correct the initial tagging. :type",
"the otherwise convenient Counter.most_common() unfortunately # does not break ties",
"list of all templates, ranked according to efficiency. If test_stats",
"collect statistics on the test set for individual rules. NOTE:",
"template_counts = Counter(tids) weighted_traincounts = Counter() for (tid, score) in",
"class Pos(Feature): \"\"\" Feature which examines the tags of nearby",
"in multi-feature syntax \"\"\" return [ Template(Pos([-1])), Template(Pos([1])), Template(Pos([-2])), Template(Pos([2])),",
"correct the initial tagging :rtype: list of Rules \"\"\" return",
"of transformation rules that this tagger has learnt :return: the",
"= Counter(tids) weighted_traincounts = Counter() for (tid, score) in zip(tids,",
"some statistic collected during training of this tagger :rtype: any",
"tokens): # Inherit documentation from TaggerI # Run the initial",
"nltkdemo18(): \"\"\" Return 18 templates, from the original nltk demo,",
"it might apply positions = tag_to_positions.get(rule.original_tag, []) # Apply the",
"using one of the TaggerTrainers available. \"\"\" json_tag = 'nltk.tag.BrillTagger'",
"changed: tag_to_positions[rule.original_tag].remove(i) tag_to_positions[rule.replacement_tag].add(i) return tagged_tokens def print_template_statistics(self, test_stats=None, printunused=True): \"\"\"",
"text (word) of nearby tokens. \"\"\" json_tag = 'nltk.tag.brill.Word' @staticmethod",
"Return the ordered list of transformation rules that this tagger",
"will break cross-version tests def det_tplsort(tpl_value): return (tpl_value[1], repr(tpl_value[0])) def",
"of this tagger :rtype: any (but usually a number) \"\"\"",
"TaggerI :param rules: An ordered list of transformation rules that",
"templates are ranked according to their relative contribution (summed for",
"tids) unused = [(tid, tpl) for (tid, tpl) in enumerate(Template.ALLTEMPLATES)",
"initial {initialerrors:5d} {initialacc:.4f} \" \"final: {finalerrors:5d} {finalacc:.4f} \".format(**test_stats)) print(\"TRAIN ({tokencount:7d}",
"to a list of the # indices of tokens that",
"\"final: {finalerrors:5d} {finalacc:.4f} \".format(**train_stats)) head = \"#ID | Score (train)",
"def brill24(): \"\"\" Return 24 templates of the seminal TBL",
"import defaultdict, Counter from nltk.tag import TaggerI from nltk.tbl import",
"training, or a dictionary of all available statistics if no",
"-1])), Template(Word([1, 2, 3])), Template(Word([-1]), Word([1])), ] def nltkdemo18plus(): \"\"\"",
"self.train_stats() trainscores = train_stats['rulescores'] assert len(trainscores) == len(tids), \"corrupt statistics:",
"(tid, tpl) in unused: print(\"{0:03d} {1:s}\".format(tid, str(tpl))) if test_stats is",
"-1])), Template(Word([1, 2])), Template(Word([-3, -2, -1])), Template(Word([1, 2, 3])), Template(Word([-1]),",
"see LICENSE.TXT from __future__ import print_function, division from collections import",
"tag_to_positions[rule.original_tag].remove(i) tag_to_positions[rule.replacement_tag].add(i) return tagged_tokens def print_template_statistics(self, test_stats=None, printunused=True): \"\"\" Print",
"trainscores): weighted_traincounts[tid] += score tottrainscores = sum(trainscores) # det_tplsort() is",
"= self.train_stats() trainscores = train_stats['rulescores'] assert len(trainscores) == len(tids), \"corrupt",
"the TaggerTrainers available. \"\"\" json_tag = 'nltk.tag.BrillTagger' def __init__(self, initial_tagger,",
"Pos([-1])), Template(Word([0]), Word([1]), Pos([1])), ] def describe_template_sets(): \"\"\" Print the",
"build any index, so will traverse the entire corpus N",
"-1])), Template(Pos([-2, -1])), Template(Pos([1]), Word([0]), Word([1])), Template(Pos([1]), Word([0]), Word([-1])), Template(Pos([-1]),",
"Template(Word([1, 2, 3])), Template(Word([-1]), Word([1])), ] def nltkdemo18plus(): \"\"\" Return",
"convenient Counter.most_common() unfortunately # does not break ties deterministically #",
"few multi-feature ones (the motivation is easy comparison with nltkdemo18)",
"end of training. :param test_stats: dictionary of statistics collected during",
"Template(Word([-1]), Word([0]), Pos([1])), Template(Pos([-1]), Word([0]), Word([1])), Template(Pos([-1]), Word([0]), Pos([1])), ]",
"Only try to apply rules at # positions that have",
"len(head), sep=\"\") train_tplscores = sorted(weighted_traincounts.items(), key=det_tplsort, reverse=True) for (tid, trainscore)",
"train_stats['rulescores'] assert len(trainscores) == len(tids), \"corrupt statistics: \" \\ \"{0}",
"(tagged_sequences, ordered list of rule scores (one for each rule))",
"g[1] for pair in zip(xs, gold) for (t, g) in",
"return self._rules def train_stats(self, statistic=None): \"\"\" Return a named statistic",
"of the TaggerTrainers available. \"\"\" json_tag = 'nltk.tag.BrillTagger' def __init__(self,",
"contribution (summed for all rules created from a given template,",
"print() if printunused: print_unused_templates() print() def batch_tag_incremental(self, sequences, gold): \"\"\"",
"-2, -1])), Template(Pos([-2, -1])), Template(Pos([1]), Word([0]), Word([1])), Template(Pos([1]), Word([0]), Word([-1])),",
"Toolkit: Transformation-based learning # # Copyright (C) 2001-2018 NLTK Project",
"tests def det_tplsort(tpl_value): return (tpl_value[1], repr(tpl_value[0])) def print_train_stats(): print(\"TEMPLATE STATISTICS",
"tagger :rtype: any (but usually a number) \"\"\" if statistic",
"not build any index, so will traverse the entire corpus",
"\"\"\" Return the ordered list of transformation rules that this",
"| {1:5d} {2:5.3f} |{3:4d} {4:.3f} | {5}\".format( tid, trainscore, trainscore/tottrainscores,",
"= [r.templateid for r in self._rules] train_stats = self.train_stats() trainscores",
"demo, and additionally a few multi-feature ones (the motivation is",
"less informative, though, as many low-score rules will appear towards",
"distribution http://www.cs.jhu.edu/~rflorian/fntbl/ (37 is after excluding a handful which do",
"created directly, from an initial tagger and a list of",
"of magic to get all functions in this module templatesets",
"statistic collected during training, or a dictionary of all available",
"nltk demo, in multi-feature syntax \"\"\" return [ Template(Pos([-1])), Template(Pos([1])),",
"of token sequences (sentences, in some applications) to be tagged",
"nearby tokens. \"\"\" json_tag = 'nltk.tag.brill.Pos' @staticmethod def extract_property(tokens, index):",
"template, weighted by score) to the performance on the test",
"Template(Word([-2])), Template(Word([2])), Template(Word([-2, -1])), Template(Word([1, 2])), Template(Word([-3, -2, -1])), Template(Word([1,",
"<NAME> # URL: <http://nltk.org/> # For license information, see LICENSE.TXT",
"if tid not in usedtpls] print(\"UNUSED TEMPLATES ({0})\".format(len(unused))) for (tid,",
"def nltkdemo18(): \"\"\" Return 18 templates, from the original nltk",
"transformation rules are specified by the ``TagRule`` interface. Brill taggers",
"return sum(t[1] != g[1] for pair in zip(xs, gold) for",
":param rules: An ordered list of transformation rules that should",
"{1:5d} {2:5.3f} |{3:4d} {4:.3f} | {5}\".format( tid, trainscore, trainscore/tottrainscores, template_counts[tid],",
"|{5:4d} {6:.3f} | {7:s}\".format( tid, testscore, testscore/tottestscores, weighted_traincounts[tid], weighted_traincounts[tid]/tottrainscores, template_counts[tid],",
"rules: list(TagRule) :param training_stats: A dictionary of statistics collected during",
"the fntbl distribution http://www.cs.jhu.edu/~rflorian/fntbl/ (37 is after excluding a handful",
"the rules). This is less informative, though, as many low-score",
"Template(Word([1]), Pos([1])), Template(Word([0]), Word([-1]), Pos([-1])), Template(Word([0]), Word([1]), Pos([1])), ] def",
"rules). This is less informative, though, as many low-score rules",
"rule at those positions. changed = rule.apply(tagged_tokens, positions) # Update",
"you would not care about statistics for individual rules and",
"module templatesets = inspect.getmembers(sys.modules[__name__], inspect.isfunction) for (name, obj) in templatesets:",
"information, see LICENSE.TXT from __future__ import print_function, division from collections",
"for rule in self._rules: for tagged_tokens in tagged_tokenses: rule.apply(tagged_tokens) errors.append(counterrors(tagged_tokenses))",
"transformational rules to correct the tags of individual tokens. These",
"sys # a bit of magic to get all functions",
"initial tagging. :type rules: list(TagRule) :param training_stats: A dictionary of",
"Template\" print(head, \"\\n\", \"-\" * len(head), sep=\"\") train_tplscores = sorted(weighted_traincounts.items(),",
"(tid, trainscore) in train_tplscores: s = \"{0} | {1:5d} {2:5.3f}",
"a number) \"\"\" if statistic is None: return self._training_stats else:",
"dict \"\"\" self._initial_tagger = initial_tagger self._rules = tuple(rules) self._training_stats =",
"any (but usually a number) \"\"\" if statistic is None:",
"[ Template(Word([0]), Word([1]), Word([2])), Template(Word([-1]), Word([0]), Word([1])), Template(Word([0]), Word([-1])), Template(Word([0]),",
"initial tagger. tagged_tokens = self._initial_tagger.tag(tokens) # Create a dictionary that",
"A dictionary of statistics collected during training, for possible later",
"extract_property(tokens, index): \"\"\"@return: The given token's tag.\"\"\" return tokens[index][1] def",
"statistics collected during testing :type test_stats: dict of str ->",
"Template(Pos([-1])), Template(Pos([1])), Template(Pos([-2])), Template(Pos([2])), Template(Pos([-2, -1])), Template(Pos([1, 2])), Template(Pos([-3, -2,",
"by the ``TagRule`` interface. Brill taggers can be created directly,",
"tokens[index][1] def nltkdemo18(): \"\"\" Return 18 templates, from the original",
"an unweighted measure (just counting the rules). This is less",
"return self._training_stats.get(statistic) def tag(self, tokens): # Inherit documentation from TaggerI",
"Template(Pos([1]), Pos([2])), Template(Pos([-1]), Pos([-2])), Template(Pos([1])), Template(Pos([-1])), Template(Pos([-2])), Template(Pos([2])), Template(Pos([1, 2,",
"Template(Word([0]), Pos([1])), Template(Word([0]), Pos([-1])), Template(Word([0])), Template(Word([-2])), Template(Word([2])), Template(Word([1])), Template(Word([-1])), Template(Pos([-1]),",
"ordered list of transformation rules that this tagger has learnt",
"2])), Template(Pos([-3, -2, -1])), Template(Pos([-2, -1])), Template(Pos([1]), Word([0]), Word([1])), Template(Pos([1]),",
":returns: tuple of (tagged_sequences, ordered list of rule scores (one",
"rules. NOTE: This is inefficient (does not build any index,",
":type test_stats: dict of str -> any (but usually numbers)",
"division from collections import defaultdict, Counter from nltk.tag import TaggerI",
"else: return self._training_stats.get(statistic) def tag(self, tokens): # Inherit documentation from",
"that maps each tag to a list of the #",
"Template(Pos([-1]), Word([1])), Template(Word([-1]), Word([0]), Pos([1])), Template(Pos([-1]), Word([0]), Word([1])), Template(Pos([-1]), Word([0]),",
"rules created from a given template, weighted by score) to",
"continue print(name, obj.__doc__, \"\\n\") ###################################################################### # The Brill Tagger ######################################################################",
"created by learning rules from a training corpus, using one",
"for (tid, testscore) in test_tplscores: s = \"{0:s} |{1:5d} {2:6.3f}",
"rules\".format(trainscores, tids) template_counts = Counter(tids) weighted_traincounts = Counter() for (tid,",
"sequence). The point is to collect statistics on the test",
"tagged :type sequences: list of list of strings :param gold:",
"tids) template_counts = Counter(tids) weighted_traincounts = Counter() for (tid, score)",
"Template(Word([1, 2, 3])), Template(Word([-3, -2, -1])), Template(Word([0]), Pos([2])), Template(Word([0]), Pos([-2])),",
"Template(Word([-1])), Template(Pos([-1]), Pos([1])), Template(Pos([1]), Pos([2])), Template(Pos([-1]), Pos([-2])), Template(Pos([1])), Template(Pos([-1])), Template(Pos([-2])),",
"motivation is easy comparison with nltkdemo18) \"\"\" return nltkdemo18() +",
"of strings :returns: tuple of (tagged_sequences, ordered list of rule",
"sorting; # the otherwise convenient Counter.most_common() unfortunately # does not",
"Project # Author: <NAME> <<EMAIL>> # based on previous (nltk2)",
"N times for N rules) -- usually you would not",
"the desired original tag. for rule in self._rules: # Find",
"Transformation-based learning # # Copyright (C) 2001-2018 NLTK Project #",
"corpus N times for N rules) -- usually you would",
"training are used instead. There is also an unweighted measure",
"= errors[-1] testing_stats['finalacc'] = 1 - testing_stats['finalerrors']/testing_stats['tokencount'] return (tagged_tokenses, testing_stats)",
"def decode_json_obj(cls, obj): _initial_tagger, _rules, _training_stats = obj return cls(_initial_tagger,",
"weighted_testcounts[tid] += score tottestscores = sum(testscores) head = \"#ID |",
"Word([1])), ] def nltkdemo18plus(): \"\"\" Return 18 templates, from the",
":type training_stats: dict \"\"\" self._initial_tagger = initial_tagger self._rules = tuple(rules)",
"{finalerrors:5d} {finalacc:.4f} \".format(**train_stats)) head = \"#ID | Score (train) |",
"initial_tagger, rules, training_stats=None): \"\"\" :param initial_tagger: The initial tagger :type",
"def encode_json_obj(self): return self._initial_tagger, self._rules, self._training_stats @classmethod def decode_json_obj(cls, obj):",
"Template(Pos([-2])), Template(Pos([2])), Template(Pos([-2, -1])), Template(Pos([1, 2])), Template(Pos([-3, -2, -1])), Template(Pos([1,",
"len(sequences) tagged_tokenses = [self._initial_tagger.tag(tokens) for tokens in sequences] testing_stats['initialerrors'] =",
"tokens) initial {initialerrors:5d} {initialacc:.4f} \" \"final: {finalerrors:5d} {finalacc:.4f} \".format(**test_stats)) print(\"TRAIN",
"\\ \"{0} train scores for {1} rules\".format(trainscores, tids) template_counts =",
"###################################################################### @jsontags.register_tag class Word(Feature): \"\"\" Feature which examines the text",
"all functions in this module templatesets = inspect.getmembers(sys.modules[__name__], inspect.isfunction) for",
"Template(Pos([1]), Word([0]), Word([1])), Template(Pos([1]), Word([0]), Word([-1])), Template(Pos([-1]), Word([-1]), Word([0])), Template(Pos([-1]),",
"= sum(trainscores) # det_tplsort() is for deterministic sorting; # the",
"This is inefficient (does not build any index, so will",
"correct the tags of individual tokens. These transformation rules are",
"Pos[0]; fntbl can do that but the current nltk implementation",
"list of rule scores (one for each rule)) \"\"\" def",
"interface. Brill taggers can be created directly, from an initial",
"apply an ordered list of transformational rules to correct the",
"collected during training are used instead. There is also an",
"taken from the postagging task of the fntbl distribution http://www.cs.jhu.edu/~rflorian/fntbl/",
"a dictionary that maps each tag to a list of",
":rtype: any (but usually a number) \"\"\" if statistic is",
"tuple of (tagged_sequences, ordered list of rule scores (one for",
"# a bit of magic to get all functions in",
"rules to correct the tags of individual tokens. These transformation",
"testscore, testscore/tottestscores, weighted_traincounts[tid], weighted_traincounts[tid]/tottrainscores, template_counts[tid], template_counts[tid]/len(tids), Template.ALLTEMPLATES[int(tid)], ) print(s) def",
"Template.ALLTEMPLATES[int(tid)], ) print(s) def print_unused_templates(): usedtpls = set(int(tid) for tid",
"tagging. :type rules: list(TagRule) :param training_stats: A dictionary of statistics",
"str -> any (but usually numbers) :param printunused: if True,",
"err1 for (err0, err1) in zip(errors, errors[1:])] testing_stats['finalerrors'] = errors[-1]",
"given :param statistic: name of statistic :type statistic: str :return:",
"(rather than all rules to a single sequence). The point",
"ranked according to their relative contribution (summed for all rules",
"| Template\" print(head, \"\\n\", \"-\" * len(head), sep=\"\") test_tplscores =",
"Pos([1])), Template(Pos([1]), Pos([2])), Template(Pos([-1]), Pos([-2])), Template(Pos([1])), Template(Pos([-1])), Template(Pos([-2])), Template(Pos([2])), Template(Pos([1,",
"-1])), Template(Word([1, 2])), Template(Word([-1, 0])), Template(Word([0, 1])), Template(Word([0])), Template(Word([-1]), Pos([-1])),",
"each rule, in order. Only try to apply rules at",
"Pos([1])), Template(Pos([-1]), Word([0]), Word([1])), Template(Pos([-1]), Word([0]), Pos([1])), ] def fntbl37():",
"Counter(tids) weighted_traincounts = Counter() for (tid, score) in zip(tids, trainscores):",
"[]) # Apply the rule at those positions. changed =",
"batch_tag() instead :param sequences: lists of token sequences (sentences, in",
"the test set. If no test_stats, then statistics collected during",
"demo, in multi-feature syntax \"\"\" return [ Template(Pos([-1])), Template(Pos([1])), Template(Pos([-2])),",
"gold standard :type gold: list of list of strings :returns:",
"errors[1:])] testing_stats['finalerrors'] = errors[-1] testing_stats['finalacc'] = 1 - testing_stats['finalerrors']/testing_stats['tokencount'] return",
"{1} rules\".format(trainscores, tids) template_counts = Counter(tids) weighted_traincounts = Counter() for",
"Template(Word([1])), Template(Word([-2])), Template(Word([2])), Template(Word([-2, -1])), Template(Word([1, 2])), Template(Word([-3, -2, -1])),",
"during training are used instead. There is also an unweighted",
"\"\"\" Tags by applying each rule to the entire corpus",
"initial tagger and a list of transformational rules; but more",
"rule to the entire corpus (rather than all rules to",
"rule in self._rules: for tagged_tokens in tagged_tokenses: rule.apply(tagged_tokens) errors.append(counterrors(tagged_tokenses)) testing_stats['rulescores']",
"collections import defaultdict, Counter from nltk.tag import TaggerI from nltk.tbl",
"Return 18 templates, from the original nltk demo, in multi-feature",
"-> any (but usually numbers) :param printunused: if True, print",
":return: None :rtype: None \"\"\" tids = [r.templateid for r",
"Return a named statistic collected during training, or a dictionary",
"and thus use batch_tag() instead :param sequences: lists of token",
"transformational rule-based tagger. Brill taggers use an initial tagger (such",
"Word([1])) ] def brill24(): \"\"\" Return 24 templates of the",
"Apply the rule at those positions. changed = rule.apply(tagged_tokens, positions)",
"sequences: list of list of strings :param gold: the gold",
"obj.__doc__, \"\\n\") ###################################################################### # The Brill Tagger ###################################################################### @jsontags.register_tag class",
"len(trainscores) == len(tids), \"corrupt statistics: \" \\ \"{0} train scores",
"# Apply the rule at those positions. changed = rule.apply(tagged_tokens,",
"json_tag = 'nltk.tag.brill.Word' @staticmethod def extract_property(tokens, index): \"\"\"@return: The given",
"according to efficiency. If test_stats is available, the templates are",
"the gold standard :type gold: list of list of strings",
"tags of nearby tokens. \"\"\" json_tag = 'nltk.tag.brill.Pos' @staticmethod def",
"{finalerrors:5d} {finalacc:.4f} \".format(**test_stats)) print(\"TRAIN ({tokencount:7d} tokens) initial {initialerrors:5d} {initialacc:.4f} \"",
"self._rules def train_stats(self, statistic=None): \"\"\" Return a named statistic collected",
"each rule to the entire corpus, in order errors =",
"do that but the current nltk implementation cannot.) \"\"\" return",
"trainscore, trainscore/tottrainscores, template_counts[tid], template_counts[tid]/len(tids), Template.ALLTEMPLATES[int(tid)], ) print(s) def print_testtrain_stats(): testscores",
"tid in tids) unused = [(tid, tpl) for (tid, tpl)",
"is inefficient (does not build any index, so will traverse",
"print_unused_templates(): usedtpls = set(int(tid) for tid in tids) unused =",
"tagger and a list of transformational rules; but more often,",
"self._training_stats.get(statistic) def tag(self, tokens): # Inherit documentation from TaggerI #",
"set. If no test_stats, then statistics collected during training are",
"Template(Word([0]), Pos([-1])), Template(Word([0])), Template(Word([-2])), Template(Word([2])), Template(Word([1])), Template(Word([-1])), Template(Pos([-1]), Pos([1])), Template(Pos([1]),"
] |
[
"logger.info(f\"Truncating to {max_data_samples} samples.\") # sentence text sentences = []",
"sys import numpy as np import torch from task_config import",
"* len(token_ids) # Generate mask where 1 for real tokens",
"st = len(\" \".join(tokens[:span_index])) + 1 if span_index != 0",
"ed = st + len(char_in_span) ed = st + len(char_in_text)",
"= [cur_len + 1, cur_len + len(xlnet_tokens_sub4)] else: xlnet_tokens_sub4 =",
"[] xlnet_token_masks = [] xlnet_token_segments = [] # Check the",
") if span1_char_index[0] < span2_char_index[0]: xlnet_tokens_sub2 = tokenizer.tokenize( text[span1_char_index[0] :",
"st + len(char_in_span) ed = st + len(char_in_text) return st,",
"max_len = len(tokens) token_ids = tokenizer.convert_tokens_to_ids(tokens) token_segments = [0] *",
"if span_index != 0 else 0 ed = st +",
"label = row[\"label\"] if \"label\" in row else True span1_char_index",
"text[span2_char_index[0] : span2_char_index[1]] ) cur_len = ( len(xlnet_tokens_sub1) + len(xlnet_tokens_sub2)",
"len(char_in_text) return st, ed # Index out of range if",
"is not None, f\"Check example {id} in {jsonl_path}\" # Tokenize",
"with extra chars char_in_text = \" \".join(tokens[span_index : span_index +",
"[0] * len(token_ids) # Generate mask where 1 for real",
"return st, ed return None def parse(jsonl_path, tokenizer, max_data_samples, max_sequence_length):",
"span2_char_index is not None, f\"Check example {id} in {jsonl_path}\" #",
"row[\"label\"] if \"label\" in row else True span1_char_index = get_char_index(text,",
": idx + length] != span_tokens[:length]: st = len(\" \".join(tokens[:idx]))",
"xlnet_token_ids.append(torch.LongTensor(token_ids)) xlnet_token_masks.append(torch.LongTensor(token_masks)) xlnet_token_segments.append(torch.LongTensor(token_segments)) token1_idxs = torch.from_numpy(np.array(token1_idxs)) token2_idxs = torch.from_numpy(np.array(token2_idxs)) labels",
"!= 0 else 0 # ed = st + len(char_in_span)",
"else 0 ed = st + len(char_in_text) return st, ed",
"+ len(xlnet_tokens_sub4)] if span1_char_index[0] < span2_char_index[0]: xlnet_tokens_sub5 = tokenizer.tokenize(text[span2_char_index[1] :])",
"in rows: index = row[\"idx\"] text = row[\"text\"] span1_text =",
"text[span2_char_index[0] : span2_char_index[1]] ) token2_idx = [ len(xlnet_tokens_sub1) + 1,",
"st, ed if span_index < len(tokens): # Token fuzzy match",
"path. logger = logging.getLogger(__name__) TASK_NAME = \"WSC\" def get_char_index(text, span_text,",
"labels.append(SuperGLUE_LABEL_MAPPING[TASK_NAME][label]) xlnet_tokens.append(tokens) xlnet_token_ids.append(torch.LongTensor(token_ids)) xlnet_token_masks.append(torch.LongTensor(token_masks)) xlnet_token_segments.append(torch.LongTensor(token_segments)) token1_idxs = torch.from_numpy(np.array(token1_idxs)) token2_idxs =",
"+ 1 if idx != 0 else 0 ed =",
"torch.from_numpy(np.array(token1_idxs)) token2_idxs = torch.from_numpy(np.array(token2_idxs)) labels = torch.from_numpy(np.array(labels)) logger.info(f\"Max token len",
"0 for padding tokens token_masks = [1] * len(token_ids) token1_idxs.append(token1_idx)",
"token2_idxs, \"tokens\": xlnet_tokens, \"token_ids\": xlnet_token_ids, \"token_masks\": xlnet_token_masks, \"token_segments\": xlnet_token_segments, },",
"\") # Token exact match if tokens[span_index : span_index +",
"torch from task_config import SuperGLUE_LABEL_MAPPING from snorkel.mtl.data import MultitaskDataset sys.path.append(\"..\")",
"+ 1 if span_index != 0 else 0 # ed",
"span1_idxs, \"span2_idx\": span2_idxs, \"token1_idx\": token1_idxs, \"token2_idx\": token2_idxs, \"tokens\": xlnet_tokens, \"token_ids\":",
"= [] xlnet_token_segments = [] # Check the maximum token",
"None def parse(jsonl_path, tokenizer, max_data_samples, max_sequence_length): logger.info(f\"Loading data from {jsonl_path}.\")",
"[] xlnet_tokens = [] xlnet_token_ids = [] xlnet_token_masks = []",
"f\"Check example {id} in {jsonl_path}\" assert span2_char_index is not None,",
"ed = st + len(char_in_text) return st, ed # Index",
"fuzzy match with different position for idx in range(span_index, len(tokens)):",
"= [json.loads(row) for row in open(jsonl_path, encoding=\"utf-8\")] for i in",
"for row in open(jsonl_path, encoding=\"utf-8\")] for i in range(2): logger.info(f\"Sample",
"1, cur_len + len(xlnet_tokens_sub4)] else: xlnet_tokens_sub4 = tokenizer.tokenize( text[span1_char_index[0] :",
"= tokenizer.tokenize(text[span2_char_index[1] :]) else: xlnet_tokens_sub5 = tokenizer.tokenize(text[span1_char_index[1] :]) tokens =",
"+ xlnet_tokens_sub2 + xlnet_tokens_sub3 + xlnet_tokens_sub4 + xlnet_tokens_sub5 + [\"[SEP]\"]",
"1, len(xlnet_tokens_sub1) + len(xlnet_tokens_sub2), ] else: xlnet_tokens_sub2 = tokenizer.tokenize( text[span2_char_index[0]",
"length max_len = -1 for row in rows: index =",
"get_char_index(text, span2_text, span2_index) assert span1_char_index is not None, f\"Check example",
"= ( [\"[CLS]\"] + xlnet_tokens_sub1 + xlnet_tokens_sub2 + xlnet_tokens_sub3 +",
"for real tokens and 0 for padding tokens token_masks =",
"\"span1_idx\": span1_idxs, \"span2_idx\": span2_idxs, \"token1_idx\": token1_idxs, \"token2_idx\": token2_idxs, \"tokens\": xlnet_tokens,",
"span_index != 0 else 0 # ed = st +",
"out of range if span_index >= len(tokens): span_index -= 10",
"st = len(\" \".join(tokens[:idx])) + 1 if idx != 0",
"len(xlnet_tokens_sub4)] else: xlnet_tokens_sub4 = tokenizer.tokenize( text[span1_char_index[0] : span1_char_index[1]] ) cur_len",
"else 0 # ed = st + len(char_in_span) ed =",
"to max_data_samples if max_data_samples: rows = rows[:max_data_samples] logger.info(f\"Truncating to {max_data_samples}",
"min(span1_char_index[0], span2_char_index[0])] ) if span1_char_index[0] < span2_char_index[0]: xlnet_tokens_sub2 = tokenizer.tokenize(",
"span2_char_index[0] else span2_char_index[0] ) xlnet_tokens_sub3 = tokenizer.tokenize(text[sub3_st:sub3_ed]) if span1_char_index[0] <",
"tokens[idx] == span_tokens[0]: for length in range(1, len(span_tokens)): if tokens[idx",
"where 1 for real tokens and 0 for padding tokens",
"row in rows: index = row[\"idx\"] text = row[\"text\"] span1_text",
"0 ed = st + len(span_text) return st, ed if",
"{id} in {jsonl_path}\" assert span2_char_index is not None, f\"Check example",
"= tokenizer.tokenize(text[sub3_st:sub3_ed]) if span1_char_index[0] < span2_char_index[0]: xlnet_tokens_sub4 = tokenizer.tokenize( text[span2_char_index[0]",
"+ len(xlnet_tokens_sub2), ] sub3_st = ( span1_char_index[1] if span1_char_index[0] <",
"logger = logging.getLogger(__name__) TASK_NAME = \"WSC\" def get_char_index(text, span_text, span_index):",
"[ len(xlnet_tokens_sub1) + 1, len(xlnet_tokens_sub1) + len(xlnet_tokens_sub2), ] sub3_st =",
"import sys import numpy as np import torch from task_config",
"parse(jsonl_path, tokenizer, max_data_samples, max_sequence_length): logger.info(f\"Loading data from {jsonl_path}.\") rows =",
"+ 1, cur_len + len(xlnet_tokens_sub4)] else: xlnet_tokens_sub4 = tokenizer.tokenize( text[span1_char_index[0]",
"span_tokens: st = len(\" \".join(tokens[:idx])) + 1 if idx !=",
"[] # span2 idx span2_idxs = [] # label labels",
"xlnet_tokens = [] xlnet_token_ids = [] xlnet_token_masks = [] xlnet_token_segments",
"len(xlnet_tokens_sub2) + len(xlnet_tokens_sub3) ) token2_idx = [cur_len + 1, cur_len",
"MultitaskDataset sys.path.append(\"..\") # Adds higher directory to python modules path.",
"extra chars char_in_text = \" \".join(tokens[span_index : span_index + len(span_tokens)])",
"row else True span1_char_index = get_char_index(text, span1_text, span1_index) span2_char_index =",
"[] # label labels = [] token1_idxs = [] token2_idxs",
": idx + len(span_tokens)] == span_tokens: st = len(\" \".join(tokens[:idx]))",
"samples.\") # sentence text sentences = [] # span1 span1s",
"range(2): logger.info(f\"Sample {i}: {rows[i]}\") # Truncate to max_data_samples if max_data_samples:",
"span1s = [] # span2 span2s = [] # span1",
"rows = rows[:max_data_samples] logger.info(f\"Truncating to {max_data_samples} samples.\") # sentence text",
") token2_idx = [cur_len + 1, cur_len + len(xlnet_tokens_sub4)] else:",
"span1_index = row[\"target\"][\"span1_index\"] span2_index = row[\"target\"][\"span2_index\"] label = row[\"label\"] if",
"row[\"target\"][\"span2_text\"] span1_index = row[\"target\"][\"span1_index\"] span2_index = row[\"target\"][\"span2_index\"] label = row[\"label\"]",
"len(span_tokens)): if tokens[idx : idx + length] != span_tokens[:length]: st",
"len(char_in_text) return st, ed # Token fuzzy match with extra",
"# Adds higher directory to python modules path. logger =",
"len(span_tokens)]) char_in_span = \" \".join(span_tokens) if char_in_span.startswith(char_in_text): st = len(\"",
"= row[\"target\"][\"span2_text\"] span1_index = row[\"target\"][\"span1_index\"] span2_index = row[\"target\"][\"span2_index\"] label =",
"\"tokens\": xlnet_tokens, \"token_ids\": xlnet_token_ids, \"token_masks\": xlnet_token_masks, \"token_segments\": xlnet_token_segments, }, Y_dict={\"labels\":",
"span1_char_index[0] < span2_char_index[0]: xlnet_tokens_sub4 = tokenizer.tokenize( text[span2_char_index[0] : span2_char_index[1]] )",
"MultitaskDataset( name=\"SuperGLUE\", X_dict={ \"sentence\": sentences, \"span1\": span1s, \"span2\": span2s, \"span1_idx\":",
"\" \".join(span_tokens) if char_in_text.startswith(char_in_span): st = len(\" \".join(tokens[:span_index])) + 1",
"\" \".join(span_tokens) if char_in_span.startswith(char_in_text): st = len(\" \".join(tokens[:span_index])) + 1",
"* len(token_ids) token1_idxs.append(token1_idx) token2_idxs.append(token2_idx) sentences.append(text) span1s.append(span1_text) span2s.append(span2_text) span1_idxs.append(span1_index) span2_idxs.append(span2_index) labels.append(SuperGLUE_LABEL_MAPPING[TASK_NAME][label])",
"import logging import sys import numpy as np import torch",
"len(xlnet_tokens_sub2) + len(xlnet_tokens_sub3) ) token1_idx = [cur_len + 1, cur_len",
"span2_char_index[0])] ) if span1_char_index[0] < span2_char_index[0]: xlnet_tokens_sub2 = tokenizer.tokenize( text[span1_char_index[0]",
"sys.path.append(\"..\") # Adds higher directory to python modules path. logger",
"and 0 for padding tokens token_masks = [1] * len(token_ids)",
"xlnet_token_ids = [] xlnet_token_masks = [] xlnet_token_segments = [] #",
"+ len(\" \".join(span_tokens[: length - 1])) return st, ed return",
"chars char_in_text = \" \".join(tokens[span_index : span_index + len(span_tokens)]) char_in_span",
"= tokenizer.tokenize( text[span2_char_index[0] : span2_char_index[1]] ) cur_len = ( len(xlnet_tokens_sub1)",
"span2s, \"span1_idx\": span1_idxs, \"span2_idx\": span2_idxs, \"token1_idx\": token1_idxs, \"token2_idx\": token2_idxs, \"tokens\":",
"len(xlnet_tokens_sub1) + len(xlnet_tokens_sub2), ] else: xlnet_tokens_sub2 = tokenizer.tokenize( text[span2_char_index[0] :",
"xlnet_tokens_sub5 + [\"[SEP]\"] ) if len(tokens) > max_len: max_len =",
"= tokenizer.tokenize(text[span1_char_index[1] :]) tokens = ( [\"[CLS]\"] + xlnet_tokens_sub1 +",
"+ len(span_tokens)] == span_tokens: st = len(\" \".join(tokens[:idx])) + 1",
"rows: index = row[\"idx\"] text = row[\"text\"] span1_text = row[\"target\"][\"span1_text\"]",
"span2_text, span2_index) assert span1_char_index is not None, f\"Check example {id}",
"idx in range(span_index, len(tokens)): if tokens[idx] == span_tokens[0]: for length",
"= ( span1_char_index[1] if span1_char_index[0] < span2_char_index[0] else span2_char_index[1] )",
"if span_index < len(tokens): # Token fuzzy match with extra",
"in range(2): logger.info(f\"Sample {i}: {rows[i]}\") # Truncate to max_data_samples if",
"def parse(jsonl_path, tokenizer, max_data_samples, max_sequence_length): logger.info(f\"Loading data from {jsonl_path}.\") rows",
"if tokens[idx : idx + length] != span_tokens[:length]: st =",
"( span1_char_index[1] if span1_char_index[0] < span2_char_index[0] else span2_char_index[1] ) sub3_ed",
"for row in rows: index = row[\"idx\"] text = row[\"text\"]",
"[\"[CLS]\"] + xlnet_tokens_sub1 + xlnet_tokens_sub2 + xlnet_tokens_sub3 + xlnet_tokens_sub4 +",
"len(tokens)): if tokens[idx] == span_tokens[0]: for length in range(1, len(span_tokens)):",
"+ 1, len(xlnet_tokens_sub1) + len(xlnet_tokens_sub2), ] else: xlnet_tokens_sub2 = tokenizer.tokenize(",
"{jsonl_path}.\") rows = [json.loads(row) for row in open(jsonl_path, encoding=\"utf-8\")] for",
"open(jsonl_path, encoding=\"utf-8\")] for i in range(2): logger.info(f\"Sample {i}: {rows[i]}\") #",
"span2_char_index[0] else span2_char_index[1] ) sub3_ed = ( span1_char_index[0] if span1_char_index[0]",
"0 # ed = st + len(char_in_span) ed = st",
"st + len(span_text) return st, ed if span_index < len(tokens):",
"= st + len(char_in_text) return st, ed # Token fuzzy",
"[ len(xlnet_tokens_sub1) + 1, len(xlnet_tokens_sub1) + len(xlnet_tokens_sub2), ] else: xlnet_tokens_sub2",
"= len(\" \".join(tokens[:span_index])) + 1 if span_index != 0 else",
"\").lower().split(\" \") span_tokens = span_text.replace(\"\\n\", \" \").lower().split(\" \") # Token",
"= ( span1_char_index[0] if span1_char_index[0] > span2_char_index[0] else span2_char_index[0] )",
"# Index out of range if span_index >= len(tokens): span_index",
"text sentences = [] # span1 span1s = [] #",
"in row else True span1_char_index = get_char_index(text, span1_text, span1_index) span2_char_index",
"len(xlnet_tokens_sub3) ) token1_idx = [cur_len + 1, cur_len + len(xlnet_tokens_sub4)]",
"sentences = [] # span1 span1s = [] # span2",
"padding tokens token_masks = [1] * len(token_ids) token1_idxs.append(token1_idx) token2_idxs.append(token2_idx) sentences.append(text)",
"text[: min(span1_char_index[0], span2_char_index[0])] ) if span1_char_index[0] < span2_char_index[0]: xlnet_tokens_sub2 =",
"rows[:max_data_samples] logger.info(f\"Truncating to {max_data_samples} samples.\") # sentence text sentences =",
"span_tokens[0]: for length in range(1, len(span_tokens)): if tokens[idx : idx",
"return MultitaskDataset( name=\"SuperGLUE\", X_dict={ \"sentence\": sentences, \"span1\": span1s, \"span2\": span2s,",
"= st + len(span_text) return st, ed # Token best",
"span1 span1s = [] # span2 span2s = [] #",
"row[\"target\"][\"span1_text\"] span2_text = row[\"target\"][\"span2_text\"] span1_index = row[\"target\"][\"span1_index\"] span2_index = row[\"target\"][\"span2_index\"]",
"+ 1 if span_index != 0 else 0 ed =",
"\"span2_idx\": span2_idxs, \"token1_idx\": token1_idxs, \"token2_idx\": token2_idxs, \"tokens\": xlnet_tokens, \"token_ids\": xlnet_token_ids,",
"+ xlnet_tokens_sub3 + xlnet_tokens_sub4 + xlnet_tokens_sub5 + [\"[SEP]\"] ) if",
"\" \").lower().split(\" \") # Token exact match if tokens[span_index :",
"if idx != 0 else 0 ed = st +",
"else: xlnet_tokens_sub5 = tokenizer.tokenize(text[span1_char_index[1] :]) tokens = ( [\"[CLS]\"] +",
"f\"Check example {id} in {jsonl_path}\" # Tokenize sentences xlnet_tokens_sub1 =",
"name=\"SuperGLUE\", X_dict={ \"sentence\": sentences, \"span1\": span1s, \"span2\": span2s, \"span1_idx\": span1_idxs,",
"if span1_char_index[0] > span2_char_index[0] else span2_char_index[0] ) xlnet_tokens_sub3 = tokenizer.tokenize(text[sub3_st:sub3_ed])",
") cur_len = ( len(xlnet_tokens_sub1) + len(xlnet_tokens_sub2) + len(xlnet_tokens_sub3) )",
"+ xlnet_tokens_sub1 + xlnet_tokens_sub2 + xlnet_tokens_sub3 + xlnet_tokens_sub4 + xlnet_tokens_sub5",
"= st + len(\" \".join(span_tokens[: length - 1])) return st,",
"len(xlnet_tokens_sub1) + len(xlnet_tokens_sub2), ] sub3_st = ( span1_char_index[1] if span1_char_index[0]",
"in range(span_index, len(tokens)): if tokens[idx] == span_tokens[0]: for length in",
"sub3_ed = ( span1_char_index[0] if span1_char_index[0] > span2_char_index[0] else span2_char_index[0]",
"import json import logging import sys import numpy as np",
"tokenizer.tokenize( text[: min(span1_char_index[0], span2_char_index[0])] ) if span1_char_index[0] < span2_char_index[0]: xlnet_tokens_sub2",
"range(span_index, len(tokens)): if tokens[idx : idx + len(span_tokens)] == span_tokens:",
"row[\"idx\"] text = row[\"text\"] span1_text = row[\"target\"][\"span1_text\"] span2_text = row[\"target\"][\"span2_text\"]",
"len(xlnet_tokens_sub2), ] sub3_st = ( span1_char_index[1] if span1_char_index[0] < span2_char_index[0]",
"tokens[idx : idx + length] != span_tokens[:length]: st = len(\"",
"# span2 idx span2_idxs = [] # label labels =",
"span_tokens[:length]: st = len(\" \".join(tokens[:idx])) + 1 if idx !=",
"cur_len = ( len(xlnet_tokens_sub1) + len(xlnet_tokens_sub2) + len(xlnet_tokens_sub3) ) token1_idx",
"xlnet_tokens_sub2 = tokenizer.tokenize( text[span2_char_index[0] : span2_char_index[1]] ) token2_idx = [",
"numpy as np import torch from task_config import SuperGLUE_LABEL_MAPPING from",
"idx in range(span_index, len(tokens)): if tokens[idx : idx + len(span_tokens)]",
"= tokenizer.tokenize( text[span1_char_index[0] : span1_char_index[1]] ) cur_len = ( len(xlnet_tokens_sub1)",
"0 else 0 # ed = st + len(char_in_span) ed",
"span2_char_index[0]: xlnet_tokens_sub2 = tokenizer.tokenize( text[span1_char_index[0] : span1_char_index[1]] ) token1_idx =",
"len {max_len}\") return MultitaskDataset( name=\"SuperGLUE\", X_dict={ \"sentence\": sentences, \"span1\": span1s,",
"span_index + len(span_tokens)]) char_in_span = \" \".join(span_tokens) if char_in_text.startswith(char_in_span): st",
"different position for idx in range(span_index, len(tokens)): if tokens[idx] ==",
"if char_in_span.startswith(char_in_text): st = len(\" \".join(tokens[:span_index])) + 1 if span_index",
"idx + len(span_tokens)] == span_tokens: st = len(\" \".join(tokens[:idx])) +",
"!= 0 else 0 ed = st + len(char_in_text) return",
"= row[\"text\"] span1_text = row[\"target\"][\"span1_text\"] span2_text = row[\"target\"][\"span2_text\"] span1_index =",
"[json.loads(row) for row in open(jsonl_path, encoding=\"utf-8\")] for i in range(2):",
"sub3_st = ( span1_char_index[1] if span1_char_index[0] < span2_char_index[0] else span2_char_index[1]",
"import torch from task_config import SuperGLUE_LABEL_MAPPING from snorkel.mtl.data import MultitaskDataset",
"span2s = [] # span1 idx span1_idxs = [] #",
") token1_idx = [cur_len + 1, cur_len + len(xlnet_tokens_sub4)] if",
"sentences, \"span1\": span1s, \"span2\": span2s, \"span1_idx\": span1_idxs, \"span2_idx\": span2_idxs, \"token1_idx\":",
"Generate mask where 1 for real tokens and 0 for",
"idx != 0 else 0 ed = st + len(span_text)",
":]) tokens = ( [\"[CLS]\"] + xlnet_tokens_sub1 + xlnet_tokens_sub2 +",
"len(token_ids) token1_idxs.append(token1_idx) token2_idxs.append(token2_idx) sentences.append(text) span1s.append(span1_text) span2s.append(span2_text) span1_idxs.append(span1_index) span2_idxs.append(span2_index) labels.append(SuperGLUE_LABEL_MAPPING[TASK_NAME][label]) xlnet_tokens.append(tokens)",
"= row[\"target\"][\"span1_index\"] span2_index = row[\"target\"][\"span2_index\"] label = row[\"label\"] if \"label\"",
"row[\"target\"][\"span2_index\"] label = row[\"label\"] if \"label\" in row else True",
"for length in range(1, len(span_tokens)): if tokens[idx : idx +",
"= [ len(xlnet_tokens_sub1) + 1, len(xlnet_tokens_sub1) + len(xlnet_tokens_sub2), ] else:",
"xlnet_tokens_sub5 = tokenizer.tokenize(text[span1_char_index[1] :]) tokens = ( [\"[CLS]\"] + xlnet_tokens_sub1",
"\".join(tokens[:span_index])) + 1 if span_index != 0 else 0 ed",
"span2_idxs.append(span2_index) labels.append(SuperGLUE_LABEL_MAPPING[TASK_NAME][label]) xlnet_tokens.append(tokens) xlnet_token_ids.append(torch.LongTensor(token_ids)) xlnet_token_masks.append(torch.LongTensor(token_masks)) xlnet_token_segments.append(torch.LongTensor(token_segments)) token1_idxs = torch.from_numpy(np.array(token1_idxs)) token2_idxs",
"span2 span2s = [] # span1 idx span1_idxs = []",
"span1_text, span1_index) span2_char_index = get_char_index(text, span2_text, span2_index) assert span1_char_index is",
"\".join(tokens[:span_index])) + 1 if span_index != 0 else 0 #",
": span1_char_index[1]] ) cur_len = ( len(xlnet_tokens_sub1) + len(xlnet_tokens_sub2) +",
"span_text, span_index): tokens = text.replace(\"\\n\", \" \").lower().split(\" \") span_tokens =",
"row in open(jsonl_path, encoding=\"utf-8\")] for i in range(2): logger.info(f\"Sample {i}:",
"= row[\"target\"][\"span1_text\"] span2_text = row[\"target\"][\"span2_text\"] span1_index = row[\"target\"][\"span1_index\"] span2_index =",
"in {jsonl_path}\" assert span2_char_index is not None, f\"Check example {id}",
"0 ed = st + len(span_text) return st, ed #",
"return st, ed if span_index < len(tokens): # Token fuzzy",
"different position for idx in range(span_index, len(tokens)): if tokens[idx :",
"\"token2_idx\": token2_idxs, \"tokens\": xlnet_tokens, \"token_ids\": xlnet_token_ids, \"token_masks\": xlnet_token_masks, \"token_segments\": xlnet_token_segments,",
"token_ids = tokenizer.convert_tokens_to_ids(tokens) token_segments = [0] * len(token_ids) # Generate",
"{rows[i]}\") # Truncate to max_data_samples if max_data_samples: rows = rows[:max_data_samples]",
"len(tokens) > max_len: max_len = len(tokens) token_ids = tokenizer.convert_tokens_to_ids(tokens) token_segments",
"> max_len: max_len = len(tokens) token_ids = tokenizer.convert_tokens_to_ids(tokens) token_segments =",
"SuperGLUE_LABEL_MAPPING from snorkel.mtl.data import MultitaskDataset sys.path.append(\"..\") # Adds higher directory",
": span_index + len(span_tokens)]) char_in_span = \" \".join(span_tokens) if char_in_span.startswith(char_in_text):",
"if char_in_text.startswith(char_in_span): st = len(\" \".join(tokens[:span_index])) + 1 if span_index",
"label labels = [] token1_idxs = [] token2_idxs = []",
"tokenizer.tokenize( text[span1_char_index[0] : span1_char_index[1]] ) cur_len = ( len(xlnet_tokens_sub1) +",
"cur_len + len(xlnet_tokens_sub4)] if span1_char_index[0] < span2_char_index[0]: xlnet_tokens_sub5 = tokenizer.tokenize(text[span2_char_index[1]",
"from snorkel.mtl.data import MultitaskDataset sys.path.append(\"..\") # Adds higher directory to",
"= st + len(char_in_text) return st, ed # Index out",
"[cur_len + 1, cur_len + len(xlnet_tokens_sub4)] else: xlnet_tokens_sub4 = tokenizer.tokenize(",
"( span1_char_index[0] if span1_char_index[0] > span2_char_index[0] else span2_char_index[0] ) xlnet_tokens_sub3",
"len(xlnet_tokens_sub1) + len(xlnet_tokens_sub2) + len(xlnet_tokens_sub3) ) token2_idx = [cur_len +",
"ed = st + len(span_text) return st, ed # Token",
"span1_char_index[0] < span2_char_index[0]: xlnet_tokens_sub5 = tokenizer.tokenize(text[span2_char_index[1] :]) else: xlnet_tokens_sub5 =",
"\".join(span_tokens) if char_in_text.startswith(char_in_span): st = len(\" \".join(tokens[:span_index])) + 1 if",
"# Tokenize sentences xlnet_tokens_sub1 = tokenizer.tokenize( text[: min(span1_char_index[0], span2_char_index[0])] )",
"\"WSC\" def get_char_index(text, span_text, span_index): tokens = text.replace(\"\\n\", \" \").lower().split(\"",
"1 for real tokens and 0 for padding tokens token_masks",
"st, ed return None def parse(jsonl_path, tokenizer, max_data_samples, max_sequence_length): logger.info(f\"Loading",
"logger.info(f\"Sample {i}: {rows[i]}\") # Truncate to max_data_samples if max_data_samples: rows",
"= ( len(xlnet_tokens_sub1) + len(xlnet_tokens_sub2) + len(xlnet_tokens_sub3) ) token1_idx =",
"= \" \".join(tokens[span_index : span_index + len(span_tokens)]) char_in_span = \"",
"+ len(span_tokens)]) char_in_span = \" \".join(span_tokens) if char_in_span.startswith(char_in_text): st =",
"else span2_char_index[1] ) sub3_ed = ( span1_char_index[0] if span1_char_index[0] >",
"ed # Token fuzzy match with extra chars char_in_text =",
"0 else 0 ed = st + len(char_in_text) return st,",
"span1s, \"span2\": span2s, \"span1_idx\": span1_idxs, \"span2_idx\": span2_idxs, \"token1_idx\": token1_idxs, \"token2_idx\":",
"the maximum token length max_len = -1 for row in",
"xlnet_token_masks.append(torch.LongTensor(token_masks)) xlnet_token_segments.append(torch.LongTensor(token_segments)) token1_idxs = torch.from_numpy(np.array(token1_idxs)) token2_idxs = torch.from_numpy(np.array(token2_idxs)) labels =",
"text[span1_char_index[0] : span1_char_index[1]] ) token1_idx = [ len(xlnet_tokens_sub1) + 1,",
"len(xlnet_tokens_sub1) + len(xlnet_tokens_sub2) + len(xlnet_tokens_sub3) ) token1_idx = [cur_len +",
"tokenizer.tokenize( text[span2_char_index[0] : span2_char_index[1]] ) cur_len = ( len(xlnet_tokens_sub1) +",
"token2_idxs.append(token2_idx) sentences.append(text) span1s.append(span1_text) span2s.append(span2_text) span1_idxs.append(span1_index) span2_idxs.append(span2_index) labels.append(SuperGLUE_LABEL_MAPPING[TASK_NAME][label]) xlnet_tokens.append(tokens) xlnet_token_ids.append(torch.LongTensor(token_ids)) xlnet_token_masks.append(torch.LongTensor(token_masks))",
"len(xlnet_tokens_sub1) + 1, len(xlnet_tokens_sub1) + len(xlnet_tokens_sub2), ] else: xlnet_tokens_sub2 =",
"span2s.append(span2_text) span1_idxs.append(span1_index) span2_idxs.append(span2_index) labels.append(SuperGLUE_LABEL_MAPPING[TASK_NAME][label]) xlnet_tokens.append(tokens) xlnet_token_ids.append(torch.LongTensor(token_ids)) xlnet_token_masks.append(torch.LongTensor(token_masks)) xlnet_token_segments.append(torch.LongTensor(token_segments)) token1_idxs =",
"= [] token1_idxs = [] token2_idxs = [] xlnet_tokens =",
"[] xlnet_token_ids = [] xlnet_token_masks = [] xlnet_token_segments = []",
"Truncate to max_data_samples if max_data_samples: rows = rows[:max_data_samples] logger.info(f\"Truncating to",
"st, ed # Index out of range if span_index >=",
"get_char_index(text, span_text, span_index): tokens = text.replace(\"\\n\", \" \").lower().split(\" \") span_tokens",
"char_in_span = \" \".join(span_tokens) if char_in_text.startswith(char_in_span): st = len(\" \".join(tokens[:span_index]))",
"= [] # span1 idx span1_idxs = [] # span2",
"real tokens and 0 for padding tokens token_masks = [1]",
"tokens = ( [\"[CLS]\"] + xlnet_tokens_sub1 + xlnet_tokens_sub2 + xlnet_tokens_sub3",
"sentences xlnet_tokens_sub1 = tokenizer.tokenize( text[: min(span1_char_index[0], span2_char_index[0])] ) if span1_char_index[0]",
"char_in_span.startswith(char_in_text): st = len(\" \".join(tokens[:span_index])) + 1 if span_index !=",
"{max_len}\") return MultitaskDataset( name=\"SuperGLUE\", X_dict={ \"sentence\": sentences, \"span1\": span1s, \"span2\":",
"len(xlnet_tokens_sub2), ] else: xlnet_tokens_sub2 = tokenizer.tokenize( text[span2_char_index[0] : span2_char_index[1]] )",
"\"label\" in row else True span1_char_index = get_char_index(text, span1_text, span1_index)",
"span2_idxs, \"token1_idx\": token1_idxs, \"token2_idx\": token2_idxs, \"tokens\": xlnet_tokens, \"token_ids\": xlnet_token_ids, \"token_masks\":",
"python modules path. logger = logging.getLogger(__name__) TASK_NAME = \"WSC\" def",
"xlnet_token_segments.append(torch.LongTensor(token_segments)) token1_idxs = torch.from_numpy(np.array(token1_idxs)) token2_idxs = torch.from_numpy(np.array(token2_idxs)) labels = torch.from_numpy(np.array(labels))",
"if span1_char_index[0] < span2_char_index[0] else span2_char_index[1] ) sub3_ed = (",
"= \" \".join(span_tokens) if char_in_span.startswith(char_in_text): st = len(\" \".join(tokens[:span_index])) +",
"tokenizer.tokenize( text[span2_char_index[0] : span2_char_index[1]] ) token2_idx = [ len(xlnet_tokens_sub1) +",
"+ len(xlnet_tokens_sub2) + len(xlnet_tokens_sub3) ) token1_idx = [cur_len + 1,",
"with different position for idx in range(span_index, len(tokens)): if tokens[idx",
"1, cur_len + len(xlnet_tokens_sub4)] if span1_char_index[0] < span2_char_index[0]: xlnet_tokens_sub5 =",
"!= span_tokens[:length]: st = len(\" \".join(tokens[:idx])) + 1 if idx",
"[] token1_idxs = [] token2_idxs = [] xlnet_tokens = []",
"= [] xlnet_token_masks = [] xlnet_token_segments = [] # Check",
"assert span2_char_index is not None, f\"Check example {id} in {jsonl_path}\"",
"+ len(char_in_span) ed = st + len(char_in_text) return st, ed",
"+ xlnet_tokens_sub4 + xlnet_tokens_sub5 + [\"[SEP]\"] ) if len(tokens) >",
"maximum token length max_len = -1 for row in rows:",
"sentence text sentences = [] # span1 span1s = []",
"else 0 ed = st + len(span_text) return st, ed",
"= [] token2_idxs = [] xlnet_tokens = [] xlnet_token_ids =",
") token1_idx = [ len(xlnet_tokens_sub1) + 1, len(xlnet_tokens_sub1) + len(xlnet_tokens_sub2),",
"xlnet_tokens_sub1 + xlnet_tokens_sub2 + xlnet_tokens_sub3 + xlnet_tokens_sub4 + xlnet_tokens_sub5 +",
"# sentence text sentences = [] # span1 span1s =",
"span2_char_index[0]: xlnet_tokens_sub4 = tokenizer.tokenize( text[span2_char_index[0] : span2_char_index[1]] ) cur_len =",
"logging import sys import numpy as np import torch from",
"span_index < len(tokens): # Token fuzzy match with extra chars",
"Check the maximum token length max_len = -1 for row",
"== span_tokens: st = len(\" \".join(tokens[:span_index])) + 1 if span_index",
"{id} in {jsonl_path}\" # Tokenize sentences xlnet_tokens_sub1 = tokenizer.tokenize( text[:",
"\".join(tokens[span_index : span_index + len(span_tokens)]) char_in_span = \" \".join(span_tokens) if",
"{i}: {rows[i]}\") # Truncate to max_data_samples if max_data_samples: rows =",
"match with extra chars char_in_text = \" \".join(tokens[span_index : span_index",
"xlnet_tokens, \"token_ids\": xlnet_token_ids, \"token_masks\": xlnet_token_masks, \"token_segments\": xlnet_token_segments, }, Y_dict={\"labels\": labels},",
"= -1 for row in rows: index = row[\"idx\"] text",
"match with different position for idx in range(span_index, len(tokens)): if",
"= [] # label labels = [] token1_idxs = []",
"ed return None def parse(jsonl_path, tokenizer, max_data_samples, max_sequence_length): logger.info(f\"Loading data",
"token2_idxs = [] xlnet_tokens = [] xlnet_token_ids = [] xlnet_token_masks",
"if tokens[idx] == span_tokens[0]: for length in range(1, len(span_tokens)): if",
"= [0] * len(token_ids) # Generate mask where 1 for",
"= [1] * len(token_ids) token1_idxs.append(token1_idx) token2_idxs.append(token2_idx) sentences.append(text) span1s.append(span1_text) span2s.append(span2_text) span1_idxs.append(span1_index)",
"tokens = text.replace(\"\\n\", \" \").lower().split(\" \") span_tokens = span_text.replace(\"\\n\", \"",
"tokenizer.tokenize(text[span2_char_index[1] :]) else: xlnet_tokens_sub5 = tokenizer.tokenize(text[span1_char_index[1] :]) tokens = (",
"import numpy as np import torch from task_config import SuperGLUE_LABEL_MAPPING",
"else: xlnet_tokens_sub4 = tokenizer.tokenize( text[span1_char_index[0] : span1_char_index[1]] ) cur_len =",
"( [\"[CLS]\"] + xlnet_tokens_sub1 + xlnet_tokens_sub2 + xlnet_tokens_sub3 + xlnet_tokens_sub4",
"if span1_char_index[0] < span2_char_index[0]: xlnet_tokens_sub4 = tokenizer.tokenize( text[span2_char_index[0] : span2_char_index[1]]",
"length] != span_tokens[:length]: st = len(\" \".join(tokens[:idx])) + 1 if",
"range(span_index, len(tokens)): if tokens[idx] == span_tokens[0]: for length in range(1,",
"else: xlnet_tokens_sub2 = tokenizer.tokenize( text[span2_char_index[0] : span2_char_index[1]] ) token2_idx =",
"rows = [json.loads(row) for row in open(jsonl_path, encoding=\"utf-8\")] for i",
"\" \").lower().split(\" \") span_tokens = span_text.replace(\"\\n\", \" \").lower().split(\" \") #",
"if len(tokens) > max_len: max_len = len(tokens) token_ids = tokenizer.convert_tokens_to_ids(tokens)",
"Token best fuzzy match with different position for idx in",
"= \" \".join(span_tokens) if char_in_text.startswith(char_in_span): st = len(\" \".join(tokens[:span_index])) +",
"\").lower().split(\" \") # Token exact match if tokens[span_index : span_index",
"len(\" \".join(span_tokens[: length - 1])) return st, ed return None",
": span2_char_index[1]] ) token2_idx = [ len(xlnet_tokens_sub1) + 1, len(xlnet_tokens_sub1)",
"[] token2_idxs = [] xlnet_tokens = [] xlnet_token_ids = []",
"max_sequence_length): logger.info(f\"Loading data from {jsonl_path}.\") rows = [json.loads(row) for row",
"of range if span_index >= len(tokens): span_index -= 10 #",
"char_in_text = \" \".join(tokens[span_index : span_index + len(span_tokens)]) char_in_span =",
"span1_char_index[1]] ) token1_idx = [ len(xlnet_tokens_sub1) + 1, len(xlnet_tokens_sub1) +",
"True span1_char_index = get_char_index(text, span1_text, span1_index) span2_char_index = get_char_index(text, span2_text,",
"span_index): tokens = text.replace(\"\\n\", \" \").lower().split(\" \") span_tokens = span_text.replace(\"\\n\",",
"X_dict={ \"sentence\": sentences, \"span1\": span1s, \"span2\": span2s, \"span1_idx\": span1_idxs, \"span2_idx\":",
"+ len(char_in_text) return st, ed # Token fuzzy match with",
"( len(xlnet_tokens_sub1) + len(xlnet_tokens_sub2) + len(xlnet_tokens_sub3) ) token2_idx = [cur_len",
"len(span_text) return st, ed # Token best fuzzy match with",
"for idx in range(span_index, len(tokens)): if tokens[idx : idx +",
"span_index + len(span_tokens)]) char_in_span = \" \".join(span_tokens) if char_in_span.startswith(char_in_text): st",
"# Generate mask where 1 for real tokens and 0",
"from {jsonl_path}.\") rows = [json.loads(row) for row in open(jsonl_path, encoding=\"utf-8\")]",
"logger.info(f\"Loading data from {jsonl_path}.\") rows = [json.loads(row) for row in",
":]) else: xlnet_tokens_sub5 = tokenizer.tokenize(text[span1_char_index[1] :]) tokens = ( [\"[CLS]\"]",
"= row[\"target\"][\"span2_index\"] label = row[\"label\"] if \"label\" in row else",
"+ len(span_tokens)]) char_in_span = \" \".join(span_tokens) if char_in_text.startswith(char_in_span): st =",
"< len(tokens): # Token fuzzy match with extra chars char_in_text",
"-= 10 # Token fuzzy match with different position for",
"length in range(1, len(span_tokens)): if tokens[idx : idx + length]",
"tokenizer.tokenize( text[span1_char_index[0] : span1_char_index[1]] ) token1_idx = [ len(xlnet_tokens_sub1) +",
"max_len: max_len = len(tokens) token_ids = tokenizer.convert_tokens_to_ids(tokens) token_segments = [0]",
"xlnet_token_segments = [] # Check the maximum token length max_len",
"\" \".join(tokens[span_index : span_index + len(span_tokens)]) char_in_span = \" \".join(span_tokens)",
"span_index != 0 else 0 ed = st + len(span_text)",
"[] # span2 span2s = [] # span1 idx span1_idxs",
"0 ed = st + len(char_in_text) return st, ed #",
"max_len = -1 for row in rows: index = row[\"idx\"]",
"[] # span1 span1s = [] # span2 span2s =",
"= [cur_len + 1, cur_len + len(xlnet_tokens_sub4)] if span1_char_index[0] <",
"len(span_tokens)]) char_in_span = \" \".join(span_tokens) if char_in_text.startswith(char_in_span): st = len(\"",
"# span1 idx span1_idxs = [] # span2 idx span2_idxs",
"xlnet_tokens_sub4 = tokenizer.tokenize( text[span1_char_index[0] : span1_char_index[1]] ) cur_len = (",
"token1_idx = [cur_len + 1, cur_len + len(xlnet_tokens_sub4)] if span1_char_index[0]",
"+ xlnet_tokens_sub5 + [\"[SEP]\"] ) if len(tokens) > max_len: max_len",
"max_data_samples, max_sequence_length): logger.info(f\"Loading data from {jsonl_path}.\") rows = [json.loads(row) for",
"> span2_char_index[0] else span2_char_index[0] ) xlnet_tokens_sub3 = tokenizer.tokenize(text[sub3_st:sub3_ed]) if span1_char_index[0]",
"< span2_char_index[0]: xlnet_tokens_sub5 = tokenizer.tokenize(text[span2_char_index[1] :]) else: xlnet_tokens_sub5 = tokenizer.tokenize(text[span1_char_index[1]",
"snorkel.mtl.data import MultitaskDataset sys.path.append(\"..\") # Adds higher directory to python",
"return st, ed # Index out of range if span_index",
"range(1, len(span_tokens)): if tokens[idx : idx + length] != span_tokens[:length]:",
"span2_index) assert span1_char_index is not None, f\"Check example {id} in",
"xlnet_tokens_sub2 = tokenizer.tokenize( text[span1_char_index[0] : span1_char_index[1]] ) token1_idx = [",
"position for idx in range(span_index, len(tokens)): if tokens[idx] == span_tokens[0]:",
"xlnet_tokens_sub4 + xlnet_tokens_sub5 + [\"[SEP]\"] ) if len(tokens) > max_len:",
"idx + length] != span_tokens[:length]: st = len(\" \".join(tokens[:idx])) +",
"!= 0 else 0 ed = st + len(span_text) return",
"ed = st + len(\" \".join(span_tokens[: length - 1])) return",
"best fuzzy match with different position for idx in range(span_index,",
"if span_index >= len(tokens): span_index -= 10 # Token fuzzy",
"row[\"target\"][\"span1_index\"] span2_index = row[\"target\"][\"span2_index\"] label = row[\"label\"] if \"label\" in",
"span1_char_index[0] if span1_char_index[0] > span2_char_index[0] else span2_char_index[0] ) xlnet_tokens_sub3 =",
"= st + len(span_text) return st, ed if span_index <",
"token2_idxs = torch.from_numpy(np.array(token2_idxs)) labels = torch.from_numpy(np.array(labels)) logger.info(f\"Max token len {max_len}\")",
"char_in_text.startswith(char_in_span): st = len(\" \".join(tokens[:span_index])) + 1 if span_index !=",
"token length max_len = -1 for row in rows: index",
"span2_char_index[1]] ) token2_idx = [ len(xlnet_tokens_sub1) + 1, len(xlnet_tokens_sub1) +",
"( len(xlnet_tokens_sub1) + len(xlnet_tokens_sub2) + len(xlnet_tokens_sub3) ) token1_idx = [cur_len",
"if \"label\" in row else True span1_char_index = get_char_index(text, span1_text,",
"+ 1, cur_len + len(xlnet_tokens_sub4)] if span1_char_index[0] < span2_char_index[0]: xlnet_tokens_sub5",
"span1_char_index[0] < span2_char_index[0]: xlnet_tokens_sub2 = tokenizer.tokenize( text[span1_char_index[0] : span1_char_index[1]] )",
"import MultitaskDataset sys.path.append(\"..\") # Adds higher directory to python modules",
"ed # Index out of range if span_index >= len(tokens):",
"\".join(span_tokens[: length - 1])) return st, ed return None def",
"= \"WSC\" def get_char_index(text, span_text, span_index): tokens = text.replace(\"\\n\", \"",
"len(tokens)): if tokens[idx : idx + len(span_tokens)] == span_tokens: st",
">= len(tokens): span_index -= 10 # Token fuzzy match with",
"token1_idxs = torch.from_numpy(np.array(token1_idxs)) token2_idxs = torch.from_numpy(np.array(token2_idxs)) labels = torch.from_numpy(np.array(labels)) logger.info(f\"Max",
"= get_char_index(text, span2_text, span2_index) assert span1_char_index is not None, f\"Check",
"len(xlnet_tokens_sub4)] if span1_char_index[0] < span2_char_index[0]: xlnet_tokens_sub5 = tokenizer.tokenize(text[span2_char_index[1] :]) else:",
"else 0 ed = st + len(\" \".join(span_tokens[: length -",
"span_index + len(span_tokens)] == span_tokens: st = len(\" \".join(tokens[:span_index])) +",
"1, len(xlnet_tokens_sub1) + len(xlnet_tokens_sub2), ] sub3_st = ( span1_char_index[1] if",
"= tokenizer.convert_tokens_to_ids(tokens) token_segments = [0] * len(token_ids) # Generate mask",
": span_index + len(span_tokens)] == span_tokens: st = len(\" \".join(tokens[:span_index]))",
"xlnet_token_masks = [] xlnet_token_segments = [] # Check the maximum",
"# Token fuzzy match with different position for idx in",
"+ len(span_text) return st, ed # Token best fuzzy match",
"else True span1_char_index = get_char_index(text, span1_text, span1_index) span2_char_index = get_char_index(text,",
"TASK_NAME = \"WSC\" def get_char_index(text, span_text, span_index): tokens = text.replace(\"\\n\",",
"as np import torch from task_config import SuperGLUE_LABEL_MAPPING from snorkel.mtl.data",
"# span1 span1s = [] # span2 span2s = []",
"= [] # span2 span2s = [] # span1 idx",
"+ len(xlnet_tokens_sub2), ] else: xlnet_tokens_sub2 = tokenizer.tokenize( text[span2_char_index[0] : span2_char_index[1]]",
"from task_config import SuperGLUE_LABEL_MAPPING from snorkel.mtl.data import MultitaskDataset sys.path.append(\"..\") #",
"1 if idx != 0 else 0 ed = st",
"len(span_tokens)] == span_tokens: st = len(\" \".join(tokens[:idx])) + 1 if",
"\"sentence\": sentences, \"span1\": span1s, \"span2\": span2s, \"span1_idx\": span1_idxs, \"span2_idx\": span2_idxs,",
"ed = st + len(char_in_text) return st, ed # Token",
"+ len(span_text) return st, ed if span_index < len(tokens): #",
"i in range(2): logger.info(f\"Sample {i}: {rows[i]}\") # Truncate to max_data_samples",
"span1_idxs = [] # span2 idx span2_idxs = [] #",
"+ 1, len(xlnet_tokens_sub1) + len(xlnet_tokens_sub2), ] sub3_st = ( span1_char_index[1]",
"len(tokens): span_index -= 10 # Token fuzzy match with different",
"return None def parse(jsonl_path, tokenizer, max_data_samples, max_sequence_length): logger.info(f\"Loading data from",
"position for idx in range(span_index, len(tokens)): if tokens[idx : idx",
"st + len(span_text) return st, ed # Token best fuzzy",
"modules path. logger = logging.getLogger(__name__) TASK_NAME = \"WSC\" def get_char_index(text,",
"== span_tokens: st = len(\" \".join(tokens[:idx])) + 1 if idx",
"= text.replace(\"\\n\", \" \").lower().split(\" \") span_tokens = span_text.replace(\"\\n\", \" \").lower().split(\"",
"ed = st + len(span_text) return st, ed if span_index",
"length - 1])) return st, ed return None def parse(jsonl_path,",
"= [] xlnet_tokens = [] xlnet_token_ids = [] xlnet_token_masks =",
"None, f\"Check example {id} in {jsonl_path}\" # Tokenize sentences xlnet_tokens_sub1",
"len(xlnet_tokens_sub3) ) token2_idx = [cur_len + 1, cur_len + len(xlnet_tokens_sub4)]",
"span2_char_index[1]] ) cur_len = ( len(xlnet_tokens_sub1) + len(xlnet_tokens_sub2) + len(xlnet_tokens_sub3)",
"torch.from_numpy(np.array(labels)) logger.info(f\"Max token len {max_len}\") return MultitaskDataset( name=\"SuperGLUE\", X_dict={ \"sentence\":",
"token1_idxs.append(token1_idx) token2_idxs.append(token2_idx) sentences.append(text) span1s.append(span1_text) span2s.append(span2_text) span1_idxs.append(span1_index) span2_idxs.append(span2_index) labels.append(SuperGLUE_LABEL_MAPPING[TASK_NAME][label]) xlnet_tokens.append(tokens) xlnet_token_ids.append(torch.LongTensor(token_ids))",
"max_data_samples: rows = rows[:max_data_samples] logger.info(f\"Truncating to {max_data_samples} samples.\") # sentence",
"tokens[span_index : span_index + len(span_tokens)] == span_tokens: st = len(\"",
"token1_idx = [ len(xlnet_tokens_sub1) + 1, len(xlnet_tokens_sub1) + len(xlnet_tokens_sub2), ]",
"for padding tokens token_masks = [1] * len(token_ids) token1_idxs.append(token1_idx) token2_idxs.append(token2_idx)",
"xlnet_tokens_sub1 = tokenizer.tokenize( text[: min(span1_char_index[0], span2_char_index[0])] ) if span1_char_index[0] <",
"tokens and 0 for padding tokens token_masks = [1] *",
"# span2 span2s = [] # span1 idx span1_idxs =",
"data from {jsonl_path}.\") rows = [json.loads(row) for row in open(jsonl_path,",
"Adds higher directory to python modules path. logger = logging.getLogger(__name__)",
"span_index >= len(tokens): span_index -= 10 # Token fuzzy match",
"xlnet_tokens.append(tokens) xlnet_token_ids.append(torch.LongTensor(token_ids)) xlnet_token_masks.append(torch.LongTensor(token_masks)) xlnet_token_segments.append(torch.LongTensor(token_segments)) token1_idxs = torch.from_numpy(np.array(token1_idxs)) token2_idxs = torch.from_numpy(np.array(token2_idxs))",
"span1_text = row[\"target\"][\"span1_text\"] span2_text = row[\"target\"][\"span2_text\"] span1_index = row[\"target\"][\"span1_index\"] span2_index",
"def get_char_index(text, span_text, span_index): tokens = text.replace(\"\\n\", \" \").lower().split(\" \")",
"else span2_char_index[0] ) xlnet_tokens_sub3 = tokenizer.tokenize(text[sub3_st:sub3_ed]) if span1_char_index[0] < span2_char_index[0]:",
"not None, f\"Check example {id} in {jsonl_path}\" # Tokenize sentences",
"encoding=\"utf-8\")] for i in range(2): logger.info(f\"Sample {i}: {rows[i]}\") # Truncate",
"= [ len(xlnet_tokens_sub1) + 1, len(xlnet_tokens_sub1) + len(xlnet_tokens_sub2), ] sub3_st",
"in open(jsonl_path, encoding=\"utf-8\")] for i in range(2): logger.info(f\"Sample {i}: {rows[i]}\")",
"example {id} in {jsonl_path}\" # Tokenize sentences xlnet_tokens_sub1 = tokenizer.tokenize(",
"not None, f\"Check example {id} in {jsonl_path}\" assert span2_char_index is",
"text = row[\"text\"] span1_text = row[\"target\"][\"span1_text\"] span2_text = row[\"target\"][\"span2_text\"] span1_index",
"return st, ed # Token fuzzy match with extra chars",
"span2 idx span2_idxs = [] # label labels = []",
"span1_char_index[0] < span2_char_index[0] else span2_char_index[1] ) sub3_ed = ( span1_char_index[0]",
"span1 idx span1_idxs = [] # span2 idx span2_idxs =",
"if span1_char_index[0] < span2_char_index[0]: xlnet_tokens_sub5 = tokenizer.tokenize(text[span2_char_index[1] :]) else: xlnet_tokens_sub5",
"if tokens[idx : idx + len(span_tokens)] == span_tokens: st =",
"span_text.replace(\"\\n\", \" \").lower().split(\" \") # Token exact match if tokens[span_index",
"span1_char_index = get_char_index(text, span1_text, span1_index) span2_char_index = get_char_index(text, span2_text, span2_index)",
"[\"[SEP]\"] ) if len(tokens) > max_len: max_len = len(tokens) token_ids",
"text[span1_char_index[0] : span1_char_index[1]] ) cur_len = ( len(xlnet_tokens_sub1) + len(xlnet_tokens_sub2)",
"len(\" \".join(tokens[:span_index])) + 1 if span_index != 0 else 0",
"idx != 0 else 0 ed = st + len(\"",
"span1_char_index is not None, f\"Check example {id} in {jsonl_path}\" assert",
"labels = torch.from_numpy(np.array(labels)) logger.info(f\"Max token len {max_len}\") return MultitaskDataset( name=\"SuperGLUE\",",
"+ len(char_in_text) return st, ed # Index out of range",
"with different position for idx in range(span_index, len(tokens)): if tokens[idx]",
"Token fuzzy match with extra chars char_in_text = \" \".join(tokens[span_index",
"= len(\" \".join(tokens[:idx])) + 1 if idx != 0 else",
"Tokenize sentences xlnet_tokens_sub1 = tokenizer.tokenize( text[: min(span1_char_index[0], span2_char_index[0])] ) if",
"len(tokens) token_ids = tokenizer.convert_tokens_to_ids(tokens) token_segments = [0] * len(token_ids) #",
"st + len(char_in_text) return st, ed # Token fuzzy match",
"token1_idxs, \"token2_idx\": token2_idxs, \"tokens\": xlnet_tokens, \"token_ids\": xlnet_token_ids, \"token_masks\": xlnet_token_masks, \"token_segments\":",
"st + len(char_in_text) return st, ed # Index out of",
"range if span_index >= len(tokens): span_index -= 10 # Token",
"return st, ed # Token best fuzzy match with different",
"span2_text = row[\"target\"][\"span2_text\"] span1_index = row[\"target\"][\"span1_index\"] span2_index = row[\"target\"][\"span2_index\"] label",
"labels = [] token1_idxs = [] token2_idxs = [] xlnet_tokens",
"st, ed # Token fuzzy match with extra chars char_in_text",
"1 if span_index != 0 else 0 ed = st",
"logging.getLogger(__name__) TASK_NAME = \"WSC\" def get_char_index(text, span_text, span_index): tokens =",
"= tokenizer.tokenize( text[: min(span1_char_index[0], span2_char_index[0])] ) if span1_char_index[0] < span2_char_index[0]:",
"] sub3_st = ( span1_char_index[1] if span1_char_index[0] < span2_char_index[0] else",
"< span2_char_index[0] else span2_char_index[1] ) sub3_ed = ( span1_char_index[0] if",
"\".join(span_tokens) if char_in_span.startswith(char_in_text): st = len(\" \".join(tokens[:span_index])) + 1 if",
"# label labels = [] token1_idxs = [] token2_idxs =",
"get_char_index(text, span1_text, span1_index) span2_char_index = get_char_index(text, span2_text, span2_index) assert span1_char_index",
"span_index -= 10 # Token fuzzy match with different position",
"= tokenizer.tokenize( text[span2_char_index[0] : span2_char_index[1]] ) token2_idx = [ len(xlnet_tokens_sub1)",
"higher directory to python modules path. logger = logging.getLogger(__name__) TASK_NAME",
"in range(1, len(span_tokens)): if tokens[idx : idx + length] !=",
"len(\" \".join(tokens[:idx])) + 1 if idx != 0 else 0",
"span2_idxs = [] # label labels = [] token1_idxs =",
"!= 0 else 0 ed = st + len(\" \".join(span_tokens[:",
"import SuperGLUE_LABEL_MAPPING from snorkel.mtl.data import MultitaskDataset sys.path.append(\"..\") # Adds higher",
"len(xlnet_tokens_sub1) + 1, len(xlnet_tokens_sub1) + len(xlnet_tokens_sub2), ] sub3_st = (",
"[] # Check the maximum token length max_len = -1",
"+ len(xlnet_tokens_sub2) + len(xlnet_tokens_sub3) ) token2_idx = [cur_len + 1,",
"if max_data_samples: rows = rows[:max_data_samples] logger.info(f\"Truncating to {max_data_samples} samples.\") #",
"if span1_char_index[0] < span2_char_index[0]: xlnet_tokens_sub2 = tokenizer.tokenize( text[span1_char_index[0] : span1_char_index[1]]",
"span_tokens: st = len(\" \".join(tokens[:span_index])) + 1 if span_index !=",
"token2_idx = [cur_len + 1, cur_len + len(xlnet_tokens_sub4)] else: xlnet_tokens_sub4",
"+ [\"[SEP]\"] ) if len(tokens) > max_len: max_len = len(tokens)",
"= [] # span2 idx span2_idxs = [] # label",
"match if tokens[span_index : span_index + len(span_tokens)] == span_tokens: st",
": span_index + len(span_tokens)]) char_in_span = \" \".join(span_tokens) if char_in_text.startswith(char_in_span):",
"xlnet_tokens_sub4 = tokenizer.tokenize( text[span2_char_index[0] : span2_char_index[1]] ) cur_len = (",
"len(span_tokens)] == span_tokens: st = len(\" \".join(tokens[:span_index])) + 1 if",
"span2_char_index[0] ) xlnet_tokens_sub3 = tokenizer.tokenize(text[sub3_st:sub3_ed]) if span1_char_index[0] < span2_char_index[0]: xlnet_tokens_sub4",
"tokens[idx : idx + len(span_tokens)] == span_tokens: st = len(\"",
") if len(tokens) > max_len: max_len = len(tokens) token_ids =",
"for idx in range(span_index, len(tokens)): if tokens[idx] == span_tokens[0]: for",
"= ( len(xlnet_tokens_sub1) + len(xlnet_tokens_sub2) + len(xlnet_tokens_sub3) ) token2_idx =",
"= span_text.replace(\"\\n\", \" \").lower().split(\" \") # Token exact match if",
"cur_len + len(xlnet_tokens_sub4)] else: xlnet_tokens_sub4 = tokenizer.tokenize( text[span1_char_index[0] : span1_char_index[1]]",
"logger.info(f\"Max token len {max_len}\") return MultitaskDataset( name=\"SuperGLUE\", X_dict={ \"sentence\": sentences,",
"[] xlnet_token_segments = [] # Check the maximum token length",
"10 # Token fuzzy match with different position for idx",
"directory to python modules path. logger = logging.getLogger(__name__) TASK_NAME =",
"for i in range(2): logger.info(f\"Sample {i}: {rows[i]}\") # Truncate to",
"= tokenizer.tokenize( text[span1_char_index[0] : span1_char_index[1]] ) token1_idx = [ len(xlnet_tokens_sub1)",
"+ len(xlnet_tokens_sub3) ) token1_idx = [cur_len + 1, cur_len +",
"Token fuzzy match with different position for idx in range(span_index,",
"= [] # span1 span1s = [] # span2 span2s",
"+ length] != span_tokens[:length]: st = len(\" \".join(tokens[:idx])) + 1",
"ed if span_index < len(tokens): # Token fuzzy match with",
"\".join(tokens[:idx])) + 1 if idx != 0 else 0 ed",
"ed # Token best fuzzy match with different position for",
") sub3_ed = ( span1_char_index[0] if span1_char_index[0] > span2_char_index[0] else",
"xlnet_tokens_sub2 + xlnet_tokens_sub3 + xlnet_tokens_sub4 + xlnet_tokens_sub5 + [\"[SEP]\"] )",
"xlnet_tokens_sub5 = tokenizer.tokenize(text[span2_char_index[1] :]) else: xlnet_tokens_sub5 = tokenizer.tokenize(text[span1_char_index[1] :]) tokens",
"0 ed = st + len(\" \".join(span_tokens[: length - 1]))",
"fuzzy match with extra chars char_in_text = \" \".join(tokens[span_index :",
"+ len(xlnet_tokens_sub3) ) token2_idx = [cur_len + 1, cur_len +",
"if span_index != 0 else 0 # ed = st",
"Token exact match if tokens[span_index : span_index + len(span_tokens)] ==",
"xlnet_tokens_sub3 = tokenizer.tokenize(text[sub3_st:sub3_ed]) if span1_char_index[0] < span2_char_index[0]: xlnet_tokens_sub4 = tokenizer.tokenize(",
"tokenizer.convert_tokens_to_ids(tokens) token_segments = [0] * len(token_ids) # Generate mask where",
"tokenizer.tokenize(text[sub3_st:sub3_ed]) if span1_char_index[0] < span2_char_index[0]: xlnet_tokens_sub4 = tokenizer.tokenize( text[span2_char_index[0] :",
"{jsonl_path}\" # Tokenize sentences xlnet_tokens_sub1 = tokenizer.tokenize( text[: min(span1_char_index[0], span2_char_index[0])]",
"token_segments = [0] * len(token_ids) # Generate mask where 1",
"idx span2_idxs = [] # label labels = [] token1_idxs",
"# Check the maximum token length max_len = -1 for",
"assert span1_char_index is not None, f\"Check example {id} in {jsonl_path}\"",
"# Token fuzzy match with extra chars char_in_text = \"",
"span_index != 0 else 0 ed = st + len(char_in_text)",
"- 1])) return st, ed return None def parse(jsonl_path, tokenizer,",
"< span2_char_index[0]: xlnet_tokens_sub2 = tokenizer.tokenize( text[span1_char_index[0] : span1_char_index[1]] ) token1_idx",
"to python modules path. logger = logging.getLogger(__name__) TASK_NAME = \"WSC\"",
"char_in_span = \" \".join(span_tokens) if char_in_span.startswith(char_in_text): st = len(\" \".join(tokens[:span_index]))",
"token_masks = [1] * len(token_ids) token1_idxs.append(token1_idx) token2_idxs.append(token2_idx) sentences.append(text) span1s.append(span1_text) span2s.append(span2_text)",
"st + len(\" \".join(span_tokens[: length - 1])) return st, ed",
"tokenizer, max_data_samples, max_sequence_length): logger.info(f\"Loading data from {jsonl_path}.\") rows = [json.loads(row)",
"= get_char_index(text, span1_text, span1_index) span2_char_index = get_char_index(text, span2_text, span2_index) assert",
"len(char_in_span) ed = st + len(char_in_text) return st, ed #",
"+ len(span_tokens)] == span_tokens: st = len(\" \".join(tokens[:span_index])) + 1",
"len(tokens): # Token fuzzy match with extra chars char_in_text =",
"= logging.getLogger(__name__) TASK_NAME = \"WSC\" def get_char_index(text, span_text, span_index): tokens",
"# Token best fuzzy match with different position for idx",
"0 else 0 ed = st + len(\" \".join(span_tokens[: length",
"tokens token_masks = [1] * len(token_ids) token1_idxs.append(token1_idx) token2_idxs.append(token2_idx) sentences.append(text) span1s.append(span1_text)",
"tokenizer.tokenize(text[span1_char_index[1] :]) tokens = ( [\"[CLS]\"] + xlnet_tokens_sub1 + xlnet_tokens_sub2",
"# Token exact match if tokens[span_index : span_index + len(span_tokens)]",
"= torch.from_numpy(np.array(token1_idxs)) token2_idxs = torch.from_numpy(np.array(token2_idxs)) labels = torch.from_numpy(np.array(labels)) logger.info(f\"Max token",
"= row[\"label\"] if \"label\" in row else True span1_char_index =",
"mask where 1 for real tokens and 0 for padding",
"token1_idxs = [] token2_idxs = [] xlnet_tokens = [] xlnet_token_ids",
"{max_data_samples} samples.\") # sentence text sentences = [] # span1",
"Index out of range if span_index >= len(tokens): span_index -=",
"span1_char_index[1] if span1_char_index[0] < span2_char_index[0] else span2_char_index[1] ) sub3_ed =",
"task_config import SuperGLUE_LABEL_MAPPING from snorkel.mtl.data import MultitaskDataset sys.path.append(\"..\") # Adds",
"torch.from_numpy(np.array(token2_idxs)) labels = torch.from_numpy(np.array(labels)) logger.info(f\"Max token len {max_len}\") return MultitaskDataset(",
"span1s.append(span1_text) span2s.append(span2_text) span1_idxs.append(span1_index) span2_idxs.append(span2_index) labels.append(SuperGLUE_LABEL_MAPPING[TASK_NAME][label]) xlnet_tokens.append(tokens) xlnet_token_ids.append(torch.LongTensor(token_ids)) xlnet_token_masks.append(torch.LongTensor(token_masks)) xlnet_token_segments.append(torch.LongTensor(token_segments)) token1_idxs",
"span_tokens = span_text.replace(\"\\n\", \" \").lower().split(\" \") # Token exact match",
"example {id} in {jsonl_path}\" assert span2_char_index is not None, f\"Check",
"exact match if tokens[span_index : span_index + len(span_tokens)] == span_tokens:",
"xlnet_tokens_sub3 + xlnet_tokens_sub4 + xlnet_tokens_sub5 + [\"[SEP]\"] ) if len(tokens)",
"span1_idxs.append(span1_index) span2_idxs.append(span2_index) labels.append(SuperGLUE_LABEL_MAPPING[TASK_NAME][label]) xlnet_tokens.append(tokens) xlnet_token_ids.append(torch.LongTensor(token_ids)) xlnet_token_masks.append(torch.LongTensor(token_masks)) xlnet_token_segments.append(torch.LongTensor(token_segments)) token1_idxs = torch.from_numpy(np.array(token1_idxs))",
"{jsonl_path}\" assert span2_char_index is not None, f\"Check example {id} in",
"= [] xlnet_token_ids = [] xlnet_token_masks = [] xlnet_token_segments =",
"= len(tokens) token_ids = tokenizer.convert_tokens_to_ids(tokens) token_segments = [0] * len(token_ids)",
"row[\"text\"] span1_text = row[\"target\"][\"span1_text\"] span2_text = row[\"target\"][\"span2_text\"] span1_index = row[\"target\"][\"span1_index\"]",
"span2_index = row[\"target\"][\"span2_index\"] label = row[\"label\"] if \"label\" in row",
"st, ed # Token best fuzzy match with different position",
": span1_char_index[1]] ) token1_idx = [ len(xlnet_tokens_sub1) + 1, len(xlnet_tokens_sub1)",
"1 if span_index != 0 else 0 # ed =",
"span1_char_index[0] > span2_char_index[0] else span2_char_index[0] ) xlnet_tokens_sub3 = tokenizer.tokenize(text[sub3_st:sub3_ed]) if",
"span1_index) span2_char_index = get_char_index(text, span2_text, span2_index) assert span1_char_index is not",
"is not None, f\"Check example {id} in {jsonl_path}\" assert span2_char_index",
"[] # span1 idx span1_idxs = [] # span2 idx",
"< span2_char_index[0]: xlnet_tokens_sub4 = tokenizer.tokenize( text[span2_char_index[0] : span2_char_index[1]] ) cur_len",
"0 else 0 ed = st + len(span_text) return st,",
"np import torch from task_config import SuperGLUE_LABEL_MAPPING from snorkel.mtl.data import",
"index = row[\"idx\"] text = row[\"text\"] span1_text = row[\"target\"][\"span1_text\"] span2_text",
"\"span2\": span2s, \"span1_idx\": span1_idxs, \"span2_idx\": span2_idxs, \"token1_idx\": token1_idxs, \"token2_idx\": token2_idxs,",
"cur_len = ( len(xlnet_tokens_sub1) + len(xlnet_tokens_sub2) + len(xlnet_tokens_sub3) ) token2_idx",
"span2_char_index[1] ) sub3_ed = ( span1_char_index[0] if span1_char_index[0] > span2_char_index[0]",
"in range(span_index, len(tokens)): if tokens[idx : idx + len(span_tokens)] ==",
") token2_idx = [ len(xlnet_tokens_sub1) + 1, len(xlnet_tokens_sub1) + len(xlnet_tokens_sub2),",
"= st + len(char_in_span) ed = st + len(char_in_text) return",
"token len {max_len}\") return MultitaskDataset( name=\"SuperGLUE\", X_dict={ \"sentence\": sentences, \"span1\":",
"\"token_ids\": xlnet_token_ids, \"token_masks\": xlnet_token_masks, \"token_segments\": xlnet_token_segments, }, Y_dict={\"labels\": labels}, )",
"text.replace(\"\\n\", \" \").lower().split(\" \") span_tokens = span_text.replace(\"\\n\", \" \").lower().split(\" \")",
"to {max_data_samples} samples.\") # sentence text sentences = [] #",
"span2_char_index = get_char_index(text, span2_text, span2_index) assert span1_char_index is not None,",
") xlnet_tokens_sub3 = tokenizer.tokenize(text[sub3_st:sub3_ed]) if span1_char_index[0] < span2_char_index[0]: xlnet_tokens_sub4 =",
"idx span1_idxs = [] # span2 idx span2_idxs = []",
"[1] * len(token_ids) token1_idxs.append(token1_idx) token2_idxs.append(token2_idx) sentences.append(text) span1s.append(span1_text) span2s.append(span2_text) span1_idxs.append(span1_index) span2_idxs.append(span2_index)",
": span2_char_index[1]] ) cur_len = ( len(xlnet_tokens_sub1) + len(xlnet_tokens_sub2) +",
"json import logging import sys import numpy as np import",
"len(token_ids) # Generate mask where 1 for real tokens and",
"= [] # Check the maximum token length max_len =",
"[cur_len + 1, cur_len + len(xlnet_tokens_sub4)] if span1_char_index[0] < span2_char_index[0]:",
"= rows[:max_data_samples] logger.info(f\"Truncating to {max_data_samples} samples.\") # sentence text sentences",
"1])) return st, ed return None def parse(jsonl_path, tokenizer, max_data_samples,",
"None, f\"Check example {id} in {jsonl_path}\" assert span2_char_index is not",
"token2_idx = [ len(xlnet_tokens_sub1) + 1, len(xlnet_tokens_sub1) + len(xlnet_tokens_sub2), ]",
"+ len(xlnet_tokens_sub4)] else: xlnet_tokens_sub4 = tokenizer.tokenize( text[span1_char_index[0] : span1_char_index[1]] )",
"\"span1\": span1s, \"span2\": span2s, \"span1_idx\": span1_idxs, \"span2_idx\": span2_idxs, \"token1_idx\": token1_idxs,",
"if tokens[span_index : span_index + len(span_tokens)] == span_tokens: st =",
"== span_tokens[0]: for length in range(1, len(span_tokens)): if tokens[idx :",
"= row[\"idx\"] text = row[\"text\"] span1_text = row[\"target\"][\"span1_text\"] span2_text =",
"in {jsonl_path}\" # Tokenize sentences xlnet_tokens_sub1 = tokenizer.tokenize( text[: min(span1_char_index[0],",
"span2_char_index[0]: xlnet_tokens_sub5 = tokenizer.tokenize(text[span2_char_index[1] :]) else: xlnet_tokens_sub5 = tokenizer.tokenize(text[span1_char_index[1] :])",
"-1 for row in rows: index = row[\"idx\"] text =",
"= torch.from_numpy(np.array(token2_idxs)) labels = torch.from_numpy(np.array(labels)) logger.info(f\"Max token len {max_len}\") return",
"max_data_samples if max_data_samples: rows = rows[:max_data_samples] logger.info(f\"Truncating to {max_data_samples} samples.\")",
"len(span_text) return st, ed if span_index < len(tokens): # Token",
"= torch.from_numpy(np.array(labels)) logger.info(f\"Max token len {max_len}\") return MultitaskDataset( name=\"SuperGLUE\", X_dict={",
"] else: xlnet_tokens_sub2 = tokenizer.tokenize( text[span2_char_index[0] : span2_char_index[1]] ) token2_idx",
"\") span_tokens = span_text.replace(\"\\n\", \" \").lower().split(\" \") # Token exact",
"# Truncate to max_data_samples if max_data_samples: rows = rows[:max_data_samples] logger.info(f\"Truncating",
"sentences.append(text) span1s.append(span1_text) span2s.append(span2_text) span1_idxs.append(span1_index) span2_idxs.append(span2_index) labels.append(SuperGLUE_LABEL_MAPPING[TASK_NAME][label]) xlnet_tokens.append(tokens) xlnet_token_ids.append(torch.LongTensor(token_ids)) xlnet_token_masks.append(torch.LongTensor(token_masks)) xlnet_token_segments.append(torch.LongTensor(token_segments))",
"# ed = st + len(char_in_span) ed = st +",
"\"token1_idx\": token1_idxs, \"token2_idx\": token2_idxs, \"tokens\": xlnet_tokens, \"token_ids\": xlnet_token_ids, \"token_masks\": xlnet_token_masks,",
"span1_char_index[1]] ) cur_len = ( len(xlnet_tokens_sub1) + len(xlnet_tokens_sub2) + len(xlnet_tokens_sub3)"
] |
[
"len(self.tokens), \"words\": words } def positivity(self): hits = 0 words",
"< 0: hits -= score words.append(word) return { \"score\": hits,",
"[\"Simplimental\"] class Simplimental: def __init__(self, text=\"This is not a bad",
"Simplimental: def __init__(self, text=\"This is not a bad idea\"): self.text",
"-score if score > 0 else 0 if score <",
"self.tokens.remove(t) def negativity(self): hits = 0 words = [] for",
"]+\", \" \", self.text) self.tokens = no_punctunation.lower().split(\" \") for t",
"positivity(self): hits = 0 words = [] for i in",
"[\"no\"]: self.tokens.remove(t) def negativity(self): hits = 0 words = []",
"is not a bad idea\"): self.text = text with open('simplimental/data/afinn.json')",
"0 else 0 if score > 0: hits += score",
"self.text) self.tokens = no_punctunation.lower().split(\" \") for t in self.tokens: if",
"self.dictionary = json.load(data_file) no_punctunation = re.sub(r\"[^a-zA-Z ]+\", \" \", self.text)",
"and self.tokens[i-1] in [\"no\", \"not\"]: word = \"not_\" + word",
"negativity = self.negativity() positivity = self.positivity() return { \"score\": positivity[\"score\"]",
"/ len(self.tokens), \"words\": words } def positivity(self): hits = 0",
"\"comparative\": float(hits) / len(self.tokens), \"words\": words } def positivity(self): hits",
"score > 0: hits += score words.append(word) return { \"score\":",
"as data_file: self.dictionary = json.load(data_file) no_punctunation = re.sub(r\"[^a-zA-Z ]+\", \"",
"score < 0: hits -= score words.append(word) return { \"score\":",
"no_punctunation = re.sub(r\"[^a-zA-Z ]+\", \" \", self.text) self.tokens = no_punctunation.lower().split(\"",
"open('simplimental/data/afinn.json') as data_file: self.dictionary = json.load(data_file) no_punctunation = re.sub(r\"[^a-zA-Z ]+\",",
"re.sub(r\"[^a-zA-Z ]+\", \" \", self.text) self.tokens = no_punctunation.lower().split(\" \") for",
"if score < 0: hits -= score words.append(word) return {",
"= no_punctunation.lower().split(\" \") for t in self.tokens: if len(t) <",
"0: hits -= score words.append(word) return { \"score\": hits, \"comparative\":",
"json.load(data_file) no_punctunation = re.sub(r\"[^a-zA-Z ]+\", \" \", self.text) self.tokens =",
"score = -score if score < 0 else 0 if",
"self.dictionary.get(word, 0) if i > 0 and self.tokens[i-1] in [\"no\",",
"= \"not_\" + word score = -score if score <",
"-= score words.append(word) return { \"score\": hits, \"comparative\": float(hits) /",
"import re import json __all__ = [\"Simplimental\"] class Simplimental: def",
"self.tokens: if len(t) < 3 and t not in [\"no\"]:",
"= re.sub(r\"[^a-zA-Z ]+\", \" \", self.text) self.tokens = no_punctunation.lower().split(\" \")",
"bad idea\"): self.text = text with open('simplimental/data/afinn.json') as data_file: self.dictionary",
"positivity = self.positivity() return { \"score\": positivity[\"score\"] - negativity[\"score\"], \"comparative\":",
"0 else 0 if score < 0: hits -= score",
"\"words\": words } def analyze(self): negativity = self.negativity() positivity =",
"def analyze(self): negativity = self.negativity() positivity = self.positivity() return {",
"text with open('simplimental/data/afinn.json') as data_file: self.dictionary = json.load(data_file) no_punctunation =",
"negativity(self): hits = 0 words = [] for i in",
"+ word score = -score if score < 0 else",
"float(hits) / len(self.tokens), \"words\": words } def analyze(self): negativity =",
"\"not_\" + word score = -score if score < 0",
"__init__(self, text=\"This is not a bad idea\"): self.text = text",
"\"not_\" + word score = -score if score > 0",
"self.positivity() return { \"score\": positivity[\"score\"] - negativity[\"score\"], \"comparative\": positivity[\"comparative\"] -",
"hits = 0 words = [] for i in range(len(self.tokens)):",
"float(hits) / len(self.tokens), \"words\": words } def positivity(self): hits =",
"not a bad idea\"): self.text = text with open('simplimental/data/afinn.json') as",
"} def positivity(self): hits = 0 words = [] for",
"\") for t in self.tokens: if len(t) < 3 and",
"score > 0 else 0 if score < 0: hits",
"> 0 and self.tokens[i-1] in [\"no\", \"not\"]: word = \"not_\"",
"hits, \"comparative\": float(hits) / len(self.tokens), \"words\": words } def positivity(self):",
"= [] for i in range(len(self.tokens)): word = self.tokens[i] score",
"= self.dictionary.get(word, 0) if i > 0 and self.tokens[i-1] in",
"score = -score if score > 0 else 0 if",
"= -score if score > 0 else 0 if score",
"return { \"score\": hits, \"comparative\": float(hits) / len(self.tokens), \"words\": words",
"hits -= score words.append(word) return { \"score\": hits, \"comparative\": float(hits)",
"if score > 0: hits += score words.append(word) return {",
"hits, \"comparative\": float(hits) / len(self.tokens), \"words\": words } def analyze(self):",
"t in self.tokens: if len(t) < 3 and t not",
"0 if score < 0: hits -= score words.append(word) return",
"{ \"score\": hits, \"comparative\": float(hits) / len(self.tokens), \"words\": words }",
"and t not in [\"no\"]: self.tokens.remove(t) def negativity(self): hits =",
"in self.tokens: if len(t) < 3 and t not in",
"self.negativity() positivity = self.positivity() return { \"score\": positivity[\"score\"] - negativity[\"score\"],",
"in [\"no\", \"not\"]: word = \"not_\" + word score =",
"text=\"This is not a bad idea\"): self.text = text with",
"__all__ = [\"Simplimental\"] class Simplimental: def __init__(self, text=\"This is not",
"self.text = text with open('simplimental/data/afinn.json') as data_file: self.dictionary = json.load(data_file)",
"0 if score > 0: hits += score words.append(word) return",
"\"comparative\": float(hits) / len(self.tokens), \"words\": words } def analyze(self): negativity",
"no_punctunation.lower().split(\" \") for t in self.tokens: if len(t) < 3",
"json __all__ = [\"Simplimental\"] class Simplimental: def __init__(self, text=\"This is",
"> 0: hits += score words.append(word) return { \"score\": hits,",
"len(t) < 3 and t not in [\"no\"]: self.tokens.remove(t) def",
"word = self.tokens[i] score = self.dictionary.get(word, 0) if i >",
"words } def analyze(self): negativity = self.negativity() positivity = self.positivity()",
"self.tokens[i] score = self.dictionary.get(word, 0) if i > 0 and",
"if i > 0 and self.tokens[i-1] in [\"no\", \"not\"]: word",
"score = self.dictionary.get(word, 0) if i > 0 and self.tokens[i-1]",
"if len(t) < 3 and t not in [\"no\"]: self.tokens.remove(t)",
"} def analyze(self): negativity = self.negativity() positivity = self.positivity() return",
"self.tokens[i-1] in [\"no\", \"not\"]: word = \"not_\" + word score",
"> 0 else 0 if score < 0: hits -=",
"return { \"score\": positivity[\"score\"] - negativity[\"score\"], \"comparative\": positivity[\"comparative\"] - negativity[\"comparative\"],",
"score words.append(word) return { \"score\": hits, \"comparative\": float(hits) / len(self.tokens),",
"= self.positivity() return { \"score\": positivity[\"score\"] - negativity[\"score\"], \"comparative\": positivity[\"comparative\"]",
"class Simplimental: def __init__(self, text=\"This is not a bad idea\"):",
"3 and t not in [\"no\"]: self.tokens.remove(t) def negativity(self): hits",
"< 0 else 0 if score > 0: hits +=",
"for t in self.tokens: if len(t) < 3 and t",
"i > 0 and self.tokens[i-1] in [\"no\", \"not\"]: word =",
"words.append(word) return { \"score\": hits, \"comparative\": float(hits) / len(self.tokens), \"words\":",
"= text with open('simplimental/data/afinn.json') as data_file: self.dictionary = json.load(data_file) no_punctunation",
"range(len(self.tokens)): word = self.tokens[i] score = self.dictionary.get(word, 0) if i",
"= 0 words = [] for i in range(len(self.tokens)): word",
"not in [\"no\"]: self.tokens.remove(t) def negativity(self): hits = 0 words",
"+ word score = -score if score > 0 else",
"if score > 0 else 0 if score < 0:",
"self.tokens = no_punctunation.lower().split(\" \") for t in self.tokens: if len(t)",
"else 0 if score < 0: hits -= score words.append(word)",
"word score = -score if score > 0 else 0",
"0: hits += score words.append(word) return { \"score\": hits, \"comparative\":",
"def __init__(self, text=\"This is not a bad idea\"): self.text =",
"def negativity(self): hits = 0 words = [] for i",
"0 and self.tokens[i-1] in [\"no\", \"not\"]: word = \"not_\" +",
"[\"no\", \"not\"]: word = \"not_\" + word score = -score",
"import json __all__ = [\"Simplimental\"] class Simplimental: def __init__(self, text=\"This",
"\"score\": hits, \"comparative\": float(hits) / len(self.tokens), \"words\": words } def",
"= self.negativity() positivity = self.positivity() return { \"score\": positivity[\"score\"] -",
"= self.tokens[i] score = self.dictionary.get(word, 0) if i > 0",
"in [\"no\"]: self.tokens.remove(t) def negativity(self): hits = 0 words =",
"word = \"not_\" + word score = -score if score",
"\"not\"]: word = \"not_\" + word score = -score if",
"with open('simplimental/data/afinn.json') as data_file: self.dictionary = json.load(data_file) no_punctunation = re.sub(r\"[^a-zA-Z",
"data_file: self.dictionary = json.load(data_file) no_punctunation = re.sub(r\"[^a-zA-Z ]+\", \" \",",
"< 3 and t not in [\"no\"]: self.tokens.remove(t) def negativity(self):",
"-score if score < 0 else 0 if score >",
"hits += score words.append(word) return { \"score\": hits, \"comparative\": float(hits)",
"0 words = [] for i in range(len(self.tokens)): word =",
"/ len(self.tokens), \"words\": words } def analyze(self): negativity = self.negativity()",
"= [\"Simplimental\"] class Simplimental: def __init__(self, text=\"This is not a",
"in range(len(self.tokens)): word = self.tokens[i] score = self.dictionary.get(word, 0) if",
"\"words\": words } def positivity(self): hits = 0 words =",
"\", self.text) self.tokens = no_punctunation.lower().split(\" \") for t in self.tokens:",
"words = [] for i in range(len(self.tokens)): word = self.tokens[i]",
"re import json __all__ = [\"Simplimental\"] class Simplimental: def __init__(self,",
"idea\"): self.text = text with open('simplimental/data/afinn.json') as data_file: self.dictionary =",
"score < 0 else 0 if score > 0: hits",
"= \"not_\" + word score = -score if score >",
"\" \", self.text) self.tokens = no_punctunation.lower().split(\" \") for t in",
"word score = -score if score < 0 else 0",
"analyze(self): negativity = self.negativity() positivity = self.positivity() return { \"score\":",
"for i in range(len(self.tokens)): word = self.tokens[i] score = self.dictionary.get(word,",
"if score < 0 else 0 if score > 0:",
"len(self.tokens), \"words\": words } def analyze(self): negativity = self.negativity() positivity",
"= json.load(data_file) no_punctunation = re.sub(r\"[^a-zA-Z ]+\", \" \", self.text) self.tokens",
"else 0 if score > 0: hits += score words.append(word)",
"i in range(len(self.tokens)): word = self.tokens[i] score = self.dictionary.get(word, 0)",
"t not in [\"no\"]: self.tokens.remove(t) def negativity(self): hits = 0",
"a bad idea\"): self.text = text with open('simplimental/data/afinn.json') as data_file:",
"def positivity(self): hits = 0 words = [] for i",
"= -score if score < 0 else 0 if score",
"{ \"score\": positivity[\"score\"] - negativity[\"score\"], \"comparative\": positivity[\"comparative\"] - negativity[\"comparative\"], }",
"0) if i > 0 and self.tokens[i-1] in [\"no\", \"not\"]:",
"[] for i in range(len(self.tokens)): word = self.tokens[i] score =",
"words } def positivity(self): hits = 0 words = []",
"+= score words.append(word) return { \"score\": hits, \"comparative\": float(hits) /"
] |
[
"# Using for relative joint motion smoothing (0: No, 1:",
"robot machining project manually or using the API. # #",
"of iterations \"Tol\": 0.0016, # Tolerance to stop iterations #",
"json_str = json.dumps(json.dumps(ToUpdate)) status = robot.setParam(\"OptimAxes\", json_str) print(status) # Full",
"\"AbsOn_9\": 1, # Weight for absolute reference joints (double): \"AbsW_1\":",
"= robot.setParam(\"OptimAxes\") json_object = json.loads(json_data) print(json.dumps(json_object, indent=4)) pause(0.2) # Example",
"Optimization settings using the RoboDK API and a JSON string.",
"ToUpdate = {} ToUpdate[\"AbsJnt_\" + str(i+1)] = (count+i)*4 ToUpdate[\"AbsOn_\" +",
"650, # Max. number of iterations \"Tol\": 0.0016, # Tolerance",
"https://robodk.com/doc/en/PythonAPI/robolink.html from robolink import * # RoboDK API # JSON",
"1, \"RelOn_7\": 1, \"RelOn_8\": 1, \"RelOn_9\": 1, # Weight for",
"1, \"RelOn_6\": 1, \"RelOn_7\": 1, \"RelOn_8\": 1, \"RelOn_9\": 1, #",
"or full update count = 1 while True: for i",
"ToUpdate[\"AbsJnt_\" + str(i+1)] = (count+i)*4 ToUpdate[\"AbsOn_\" + str(i+1)] = count",
"= RDK.ItemUserPick(\"Select a robot arm\",ITEM_TYPE_ROBOT_ARM) # Default optimization settings test",
"axes optimization settings: while True: json_data = robot.setParam(\"OptimAxes\") json_object =",
"i in range(7): # Partial update ToUpdate = {} ToUpdate[\"AbsJnt_\"",
"Start the RoboDK API RDK = Robolink() # Ask the",
"# Using Absolute reference joints (0: No, 1: Yes): \"AbsOn_1\":",
"JSON string. # You can select \"Axes optimization\" in a",
"\"Active\": 1, # Use generic axes optimization: 0=Disabled or 1=Enabled",
"\"RelOn_3\": 1, \"RelOn_4\": 1, \"RelOn_5\": 1, \"RelOn_6\": 1, \"RelOn_7\": 1,",
"1=Nelder Mead, 2=Samples, 3=Samples+Nelder Mead \"MaxIter\": 650, # Max. number",
"or modify the Axes Optimization settings using the RoboDK API",
"menu or the robot parameters to view the axes optimization",
"the robot parameters to view the axes optimization settings. #",
"https://robodk.com/doc/en/RoboDK-API.html # For more information visit: # https://robodk.com/doc/en/PythonAPI/robolink.html from robolink",
"\"AbsOn_3\": 1, \"AbsOn_4\": 1, \"AbsOn_5\": 1, \"AbsOn_6\": 1, \"AbsOn_7\": 1,",
"arm (6 axis robot wich can have external axes) robot",
"+ str(i+1)] = count % 2 ToUpdate[\"AbsW_\" + str(i+1)] =",
"1, \"AbsOn_9\": 1, # Weight for absolute reference joints (double):",
"= (count+i)*4 ToUpdate[\"AbsOn_\" + str(i+1)] = count % 2 ToUpdate[\"AbsW_\"",
"\"RelW_8\": 59, \"RelW_9\": 0, } # Update one value, for",
"robot.setParam(\"OptimAxes\", json_str) print(status) # Full update #OptimAxes_TEST[\"RefJoint_\" + str(i+1)] =",
"algorithm to use: 1=Nelder Mead, 2=Samples, 3=Samples+Nelder Mead \"MaxIter\": 650,",
"in a robot machining menu or the robot parameters to",
"+ str(i+1)] = (count+i)*4 #OptimAxes_TEST[\"RefWeight_\" + str(i+1)] = (count+i) #OptimAxes_TEST[\"RefOn_\"",
"#OptimAxes_TEST[\"RefWeight_\" + str(i+1)] = (count+i) #OptimAxes_TEST[\"RefOn_\" + str(i+1)] = count",
"robot arm\",ITEM_TYPE_ROBOT_ARM) # Default optimization settings test template AxesOptimSettings =",
"+ 1 # Read settings json_data = robot.setParam(\"OptimAxes\") json_object =",
"tools import json # Start the RoboDK API RDK =",
"= 1 json_str = json.dumps(json.dumps(ToUpdate)) status = robot.setParam(\"OptimAxes\", json_str) print(status)",
"to read or modify the Axes Optimization settings using the",
"No, 1: Yes): \"AbsOn_1\": 1, \"AbsOn_2\": 1, \"AbsOn_3\": 1, \"AbsOn_4\":",
"\"MaxIter\": 650, # Max. number of iterations \"Tol\": 0.0016, #",
"reference joints (double): \"AbsW_1\": 100, \"AbsW_2\": 100, \"AbsW_3\": 100, \"AbsW_4\":",
"select a robot arm (6 axis robot wich can have",
"to view the axes optimization settings. # It is possible",
"API here: # https://robodk.com/doc/en/RoboDK-API.html # For more information visit: #",
"information visit: # https://robodk.com/doc/en/PythonAPI/robolink.html from robolink import * # RoboDK",
"for relative joint motion smoothing (0: No, 1: Yes): \"RelOn_1\":",
"1, \"RelOn_5\": 1, \"RelOn_6\": 1, \"RelOn_7\": 1, \"RelOn_8\": 1, \"RelOn_9\":",
"update ToUpdate = {} ToUpdate[\"AbsJnt_\" + str(i+1)] = (count+i)*4 ToUpdate[\"AbsOn_\"",
"the user to select a robot arm (6 axis robot",
"the RoboDK API here: # https://robodk.com/doc/en/RoboDK-API.html # For more information",
"str(i+1)] = count % 2 # Full update #print(robot.setParam(\"OptimAxes\", str(AxesOptimSettings)))",
"print(status) # Full update #OptimAxes_TEST[\"RefJoint_\" + str(i+1)] = (count+i)*4 #OptimAxes_TEST[\"RefWeight_\"",
"test template AxesOptimSettings = { # Optimization parameters: \"Active\": 1,",
"iterations # Absolute Reference joints (double): \"AbsJnt_1\": 104.17, \"AbsJnt_2\": 11.22,",
"(double): \"AbsW_1\": 100, \"AbsW_2\": 100, \"AbsW_3\": 100, \"AbsW_4\": 89, \"AbsW_5\":",
"to make a partial or full update count = 1",
"92, \"AbsW_7\": 92, \"AbsW_8\": 96, \"AbsW_9\": 50, # Using for",
"RoboDK API and a JSON string. # You can select",
"stop iterations # Absolute Reference joints (double): \"AbsJnt_1\": 104.17, \"AbsJnt_2\":",
"# You can select \"Axes optimization\" in a robot machining",
"5, \"RelW_2\": 47, \"RelW_3\": 44, \"RelW_4\": 43, \"RelW_5\": 36, \"RelW_6\":",
"robot parameters to view the axes optimization settings. # It",
"2 ToUpdate[\"AbsW_\" + str(i+1)] = (count+i) json_str = json.dumps(json.dumps(ToUpdate)) status",
"machining project manually or using the API. # # More",
"-87.48, \"AbsJnt_5\": -75.36, \"AbsJnt_6\": 63.03, \"AbsJnt_7\": 174.13, \"AbsJnt_8\": 173.60, \"AbsJnt_9\":",
"# Example to make a partial or full update count",
"str(i+1)] = (count+i)*4 ToUpdate[\"AbsOn_\" + str(i+1)] = count % 2",
"manually or using the API. # # More information about",
"Full update #print(robot.setParam(\"OptimAxes\", str(AxesOptimSettings))) count = count + 1 #",
"1, # Use generic axes optimization: 0=Disabled or 1=Enabled \"Algorithm\":",
"Mead \"MaxIter\": 650, # Max. number of iterations \"Tol\": 0.0016,",
"ToUpdate = {} ToUpdate[\"Active\"] = 1 json_str = json.dumps(json.dumps(ToUpdate)) status",
"the API. # # More information about the RoboDK API",
"axes optimization settings attached to a robot or a robot",
"1, \"RelOn_2\": 1, \"RelOn_3\": 1, \"RelOn_4\": 1, \"RelOn_5\": 1, \"RelOn_6\":",
"JSON tools import json # Start the RoboDK API RDK",
"for relative joint motion (double): \"RelW_1\": 5, \"RelW_2\": 47, \"RelW_3\":",
"# https://robodk.com/doc/en/PythonAPI/robolink.html from robolink import * # RoboDK API #",
"(count+i) #OptimAxes_TEST[\"RefOn_\" + str(i+1)] = count % 2 # Full",
"settings: while True: json_data = robot.setParam(\"OptimAxes\") json_object = json.loads(json_data) print(json.dumps(json_object,",
"\"RelW_2\": 47, \"RelW_3\": 44, \"RelW_4\": 43, \"RelW_5\": 36, \"RelW_6\": 47,",
"user to select a robot arm (6 axis robot wich",
"1 # Read settings json_data = robot.setParam(\"OptimAxes\") json_object = json.loads(json_data)",
"= Robolink() # Ask the user to select a robot",
"Absolute Reference joints (double): \"AbsJnt_1\": 104.17, \"AbsJnt_2\": 11.22, \"AbsJnt_3\": 15.97,",
"# Weight for relative joint motion (double): \"RelW_1\": 5, \"RelW_2\":",
"count = 1 while True: for i in range(7): #",
"indent=4)) pause(0.2) # Example to read the current axes optimization",
"settings. # It is possible to update the axes optimization",
"43, \"RelW_5\": 36, \"RelW_6\": 47, \"RelW_7\": 53, \"RelW_8\": 59, \"RelW_9\":",
"RoboDK API here: # https://robodk.com/doc/en/RoboDK-API.html # For more information visit:",
"100, \"AbsW_4\": 89, \"AbsW_5\": 90, \"AbsW_6\": 92, \"AbsW_7\": 92, \"AbsW_8\":",
"36, \"RelW_6\": 47, \"RelW_7\": 53, \"RelW_8\": 59, \"RelW_9\": 0, }",
"joints (double): \"AbsJnt_1\": 104.17, \"AbsJnt_2\": 11.22, \"AbsJnt_3\": 15.97, \"AbsJnt_4\": -87.48,",
"# https://robodk.com/doc/en/RoboDK-API.html # For more information visit: # https://robodk.com/doc/en/PythonAPI/robolink.html from",
"or a robot machining project manually or using the API.",
"# For more information visit: # https://robodk.com/doc/en/PythonAPI/robolink.html from robolink import",
"2 # Full update #print(robot.setParam(\"OptimAxes\", str(AxesOptimSettings))) count = count +",
"\"RelOn_7\": 1, \"RelOn_8\": 1, \"RelOn_9\": 1, # Weight for relative",
"= (count+i) #OptimAxes_TEST[\"RefOn_\" + str(i+1)] = count % 2 #",
"1, \"RelOn_9\": 1, # Weight for relative joint motion (double):",
"89, \"AbsW_5\": 90, \"AbsW_6\": 92, \"AbsW_7\": 92, \"AbsW_8\": 96, \"AbsW_9\":",
"robot machining menu or the robot parameters to view the",
"53, \"RelW_8\": 59, \"RelW_9\": 0, } # Update one value,",
"str(i+1)] = count % 2 ToUpdate[\"AbsW_\" + str(i+1)] = (count+i)",
"settings attached to a robot or a robot machining project",
"1, \"RelOn_3\": 1, \"RelOn_4\": 1, \"RelOn_5\": 1, \"RelOn_6\": 1, \"RelOn_7\":",
"No, 1: Yes): \"RelOn_1\": 1, \"RelOn_2\": 1, \"RelOn_3\": 1, \"RelOn_4\":",
"= json.loads(json_data) print(json.dumps(json_object, indent=4)) pause(0.2) # Example to read the",
"partial or full update count = 1 while True: for",
"\"RelW_5\": 36, \"RelW_6\": 47, \"RelW_7\": 53, \"RelW_8\": 59, \"RelW_9\": 0,",
"# Tolerance to stop iterations # Absolute Reference joints (double):",
"or the robot parameters to view the axes optimization settings.",
"\"AbsJnt_4\": -87.48, \"AbsJnt_5\": -75.36, \"AbsJnt_6\": 63.03, \"AbsJnt_7\": 174.13, \"AbsJnt_8\": 173.60,",
"relative joint motion (double): \"RelW_1\": 5, \"RelW_2\": 47, \"RelW_3\": 44,",
"Reference joints (double): \"AbsJnt_1\": 104.17, \"AbsJnt_2\": 11.22, \"AbsJnt_3\": 15.97, \"AbsJnt_4\":",
"Example to make a partial or full update count =",
"settings json_data = robot.setParam(\"OptimAxes\") json_object = json.loads(json_data) print(json.dumps(json_object, indent=4)) pause(0.2)",
"use: 1=Nelder Mead, 2=Samples, 3=Samples+Nelder Mead \"MaxIter\": 650, # Max.",
"1=Enabled \"Algorithm\": 2, # Optimization algorithm to use: 1=Nelder Mead,",
"#OptimAxes_TEST[\"RefOn_\" + str(i+1)] = count % 2 # Full update",
"iterations \"Tol\": 0.0016, # Tolerance to stop iterations # Absolute",
"template AxesOptimSettings = { # Optimization parameters: \"Active\": 1, #",
"for i in range(7): # Partial update ToUpdate = {}",
"string. # You can select \"Axes optimization\" in a robot",
"json.dumps(json.dumps(ToUpdate)) status = robot.setParam(\"OptimAxes\", json_str) print(status) # Example to make",
"parameters: \"Active\": 1, # Use generic axes optimization: 0=Disabled or",
"str(i+1)] = (count+i) json_str = json.dumps(json.dumps(ToUpdate)) status = robot.setParam(\"OptimAxes\", json_str)",
"\"RelOn_4\": 1, \"RelOn_5\": 1, \"RelOn_6\": 1, \"RelOn_7\": 1, \"RelOn_8\": 1,",
"axis robot wich can have external axes) robot = RDK.ItemUserPick(\"Select",
"optimization settings: while True: json_data = robot.setParam(\"OptimAxes\") json_object = json.loads(json_data)",
"a robot machining project manually or using the API. #",
"have external axes) robot = RDK.ItemUserPick(\"Select a robot arm\",ITEM_TYPE_ROBOT_ARM) #",
"robot or a robot machining project manually or using the",
"15.97, \"AbsJnt_4\": -87.48, \"AbsJnt_5\": -75.36, \"AbsJnt_6\": 63.03, \"AbsJnt_7\": 174.13, \"AbsJnt_8\":",
"joints (double): \"AbsW_1\": 100, \"AbsW_2\": 100, \"AbsW_3\": 100, \"AbsW_4\": 89,",
"= (count+i)*4 #OptimAxes_TEST[\"RefWeight_\" + str(i+1)] = (count+i) #OptimAxes_TEST[\"RefOn_\" + str(i+1)]",
"(count+i)*4 #OptimAxes_TEST[\"RefWeight_\" + str(i+1)] = (count+i) #OptimAxes_TEST[\"RefOn_\" + str(i+1)] =",
"number of iterations \"Tol\": 0.0016, # Tolerance to stop iterations",
"shows how to read or modify the Axes Optimization settings",
"arm\",ITEM_TYPE_ROBOT_ARM) # Default optimization settings test template AxesOptimSettings = {",
"it active: ToUpdate = {} ToUpdate[\"Active\"] = 1 json_str =",
"= {} ToUpdate[\"Active\"] = 1 json_str = json.dumps(json.dumps(ToUpdate)) status =",
"Axes Optimization settings using the RoboDK API and a JSON",
"\"RelW_3\": 44, \"RelW_4\": 43, \"RelW_5\": 36, \"RelW_6\": 47, \"RelW_7\": 53,",
"\"Tol\": 0.0016, # Tolerance to stop iterations # Absolute Reference",
"+ str(i+1)] = (count+i)*4 ToUpdate[\"AbsOn_\" + str(i+1)] = count %",
"# More information about the RoboDK API here: # https://robodk.com/doc/en/RoboDK-API.html",
"50, # Using for relative joint motion smoothing (0: No,",
"= (count+i) json_str = json.dumps(json.dumps(ToUpdate)) status = robot.setParam(\"OptimAxes\", json_str) print(status)",
"Weight for relative joint motion (double): \"RelW_1\": 5, \"RelW_2\": 47,",
"range(7): # Partial update ToUpdate = {} ToUpdate[\"AbsJnt_\" + str(i+1)]",
"Yes): \"AbsOn_1\": 1, \"AbsOn_2\": 1, \"AbsOn_3\": 1, \"AbsOn_4\": 1, \"AbsOn_5\":",
"\"AbsW_2\": 100, \"AbsW_3\": 100, \"AbsW_4\": 89, \"AbsW_5\": 90, \"AbsW_6\": 92,",
"while True: json_data = robot.setParam(\"OptimAxes\") json_object = json.loads(json_data) print(json.dumps(json_object, indent=4))",
"1, \"AbsOn_5\": 1, \"AbsOn_6\": 1, \"AbsOn_7\": 1, \"AbsOn_8\": 1, \"AbsOn_9\":",
"1, # Weight for absolute reference joints (double): \"AbsW_1\": 100,",
"\"RelOn_9\": 1, # Weight for relative joint motion (double): \"RelW_1\":",
"optimization settings. # It is possible to update the axes",
"project manually or using the API. # # More information",
"1, \"AbsOn_7\": 1, \"AbsOn_8\": 1, \"AbsOn_9\": 1, # Weight for",
"# JSON tools import json # Start the RoboDK API",
"#OptimAxes_TEST[\"RefJoint_\" + str(i+1)] = (count+i)*4 #OptimAxes_TEST[\"RefWeight_\" + str(i+1)] = (count+i)",
"Partial update ToUpdate = {} ToUpdate[\"AbsJnt_\" + str(i+1)] = (count+i)*4",
"json_str) print(status) # Example to make a partial or full",
"= json.dumps(json.dumps(ToUpdate)) status = robot.setParam(\"OptimAxes\", json_str) print(status) # Example to",
"You can select \"Axes optimization\" in a robot machining menu",
"or using the API. # # More information about the",
"Absolute reference joints (0: No, 1: Yes): \"AbsOn_1\": 1, \"AbsOn_2\":",
"a robot machining menu or the robot parameters to view",
"one value, for example, make it active: ToUpdate = {}",
"json # Start the RoboDK API RDK = Robolink() #",
"\"AbsOn_2\": 1, \"AbsOn_3\": 1, \"AbsOn_4\": 1, \"AbsOn_5\": 1, \"AbsOn_6\": 1,",
"\"AbsOn_4\": 1, \"AbsOn_5\": 1, \"AbsOn_6\": 1, \"AbsOn_7\": 1, \"AbsOn_8\": 1,",
"1, \"AbsOn_2\": 1, \"AbsOn_3\": 1, \"AbsOn_4\": 1, \"AbsOn_5\": 1, \"AbsOn_6\":",
"True: json_data = robot.setParam(\"OptimAxes\") json_object = json.loads(json_data) print(json.dumps(json_object, indent=4)) pause(0.2)",
"11.22, \"AbsJnt_3\": 15.97, \"AbsJnt_4\": -87.48, \"AbsJnt_5\": -75.36, \"AbsJnt_6\": 63.03, \"AbsJnt_7\":",
"pause(0.2) # Example to read the current axes optimization settings:",
"\"AbsOn_6\": 1, \"AbsOn_7\": 1, \"AbsOn_8\": 1, \"AbsOn_9\": 1, # Weight",
"# Use generic axes optimization: 0=Disabled or 1=Enabled \"Algorithm\": 2,",
"status = robot.setParam(\"OptimAxes\", json_str) print(status) # Full update #OptimAxes_TEST[\"RefJoint_\" +",
"1, \"RelOn_8\": 1, \"RelOn_9\": 1, # Weight for relative joint",
"joint motion (double): \"RelW_1\": 5, \"RelW_2\": 47, \"RelW_3\": 44, \"RelW_4\":",
"Weight for absolute reference joints (double): \"AbsW_1\": 100, \"AbsW_2\": 100,",
"+ str(i+1)] = (count+i) json_str = json.dumps(json.dumps(ToUpdate)) status = robot.setParam(\"OptimAxes\",",
"ToUpdate[\"Active\"] = 1 json_str = json.dumps(json.dumps(ToUpdate)) status = robot.setParam(\"OptimAxes\", json_str)",
"is possible to update the axes optimization settings attached to",
"example shows how to read or modify the Axes Optimization",
"motion (double): \"RelW_1\": 5, \"RelW_2\": 47, \"RelW_3\": 44, \"RelW_4\": 43,",
"(0: No, 1: Yes): \"RelOn_1\": 1, \"RelOn_2\": 1, \"RelOn_3\": 1,",
"47, \"RelW_3\": 44, \"RelW_4\": 43, \"RelW_5\": 36, \"RelW_6\": 47, \"RelW_7\":",
"visit: # https://robodk.com/doc/en/PythonAPI/robolink.html from robolink import * # RoboDK API",
"= count % 2 # Full update #print(robot.setParam(\"OptimAxes\", str(AxesOptimSettings))) count",
"\"RelW_6\": 47, \"RelW_7\": 53, \"RelW_8\": 59, \"RelW_9\": 0, } #",
"status = robot.setParam(\"OptimAxes\", json_str) print(status) # Example to make a",
"+ str(i+1)] = (count+i) #OptimAxes_TEST[\"RefOn_\" + str(i+1)] = count %",
"robot arm (6 axis robot wich can have external axes)",
"100, \"AbsW_3\": 100, \"AbsW_4\": 89, \"AbsW_5\": 90, \"AbsW_6\": 92, \"AbsW_7\":",
"= robot.setParam(\"OptimAxes\", json_str) print(status) # Example to make a partial",
"in range(7): # Partial update ToUpdate = {} ToUpdate[\"AbsJnt_\" +",
"to read the current axes optimization settings: while True: json_data",
"Full update #OptimAxes_TEST[\"RefJoint_\" + str(i+1)] = (count+i)*4 #OptimAxes_TEST[\"RefWeight_\" + str(i+1)]",
"More information about the RoboDK API here: # https://robodk.com/doc/en/RoboDK-API.html #",
"json.loads(json_data) print(json.dumps(json_object, indent=4)) pause(0.2) # Example to read the current",
"json_str = json.dumps(json.dumps(ToUpdate)) status = robot.setParam(\"OptimAxes\", json_str) print(status) # Example",
"# Absolute Reference joints (double): \"AbsJnt_1\": 104.17, \"AbsJnt_2\": 11.22, \"AbsJnt_3\":",
"axes optimization settings. # It is possible to update the",
"= count % 2 ToUpdate[\"AbsW_\" + str(i+1)] = (count+i) json_str",
"Yes): \"RelOn_1\": 1, \"RelOn_2\": 1, \"RelOn_3\": 1, \"RelOn_4\": 1, \"RelOn_5\":",
"True: for i in range(7): # Partial update ToUpdate =",
"3=Samples+Nelder Mead \"MaxIter\": 650, # Max. number of iterations \"Tol\":",
"Optimization parameters: \"Active\": 1, # Use generic axes optimization: 0=Disabled",
"# Update one value, for example, make it active: ToUpdate",
"Max. number of iterations \"Tol\": 0.0016, # Tolerance to stop",
"json_str) print(status) # Full update #OptimAxes_TEST[\"RefJoint_\" + str(i+1)] = (count+i)*4",
"\"RelOn_5\": 1, \"RelOn_6\": 1, \"RelOn_7\": 1, \"RelOn_8\": 1, \"RelOn_9\": 1,",
"the RoboDK API RDK = Robolink() # Ask the user",
"axes optimization: 0=Disabled or 1=Enabled \"Algorithm\": 2, # Optimization algorithm",
"optimization\" in a robot machining menu or the robot parameters",
"# Weight for absolute reference joints (double): \"AbsW_1\": 100, \"AbsW_2\":",
"for example, make it active: ToUpdate = {} ToUpdate[\"Active\"] =",
"count % 2 # Full update #print(robot.setParam(\"OptimAxes\", str(AxesOptimSettings))) count =",
"and a JSON string. # You can select \"Axes optimization\"",
"# This example shows how to read or modify the",
"% 2 ToUpdate[\"AbsW_\" + str(i+1)] = (count+i) json_str = json.dumps(json.dumps(ToUpdate))",
"RoboDK API # JSON tools import json # Start the",
"robolink import * # RoboDK API # JSON tools import",
"make a partial or full update count = 1 while",
"44, \"RelW_4\": 43, \"RelW_5\": 36, \"RelW_6\": 47, \"RelW_7\": 53, \"RelW_8\":",
"full update count = 1 while True: for i in",
"ToUpdate[\"AbsOn_\" + str(i+1)] = count % 2 ToUpdate[\"AbsW_\" + str(i+1)]",
"attached to a robot or a robot machining project manually",
"63.03, \"AbsJnt_7\": 174.13, \"AbsJnt_8\": 173.60, \"AbsJnt_9\": 0, # Using Absolute",
"(6 axis robot wich can have external axes) robot =",
"Read settings json_data = robot.setParam(\"OptimAxes\") json_object = json.loads(json_data) print(json.dumps(json_object, indent=4))",
"API and a JSON string. # You can select \"Axes",
"\"AbsW_4\": 89, \"AbsW_5\": 90, \"AbsW_6\": 92, \"AbsW_7\": 92, \"AbsW_8\": 96,",
"smoothing (0: No, 1: Yes): \"RelOn_1\": 1, \"RelOn_2\": 1, \"RelOn_3\":",
"can have external axes) robot = RDK.ItemUserPick(\"Select a robot arm\",ITEM_TYPE_ROBOT_ARM)",
"joints (0: No, 1: Yes): \"AbsOn_1\": 1, \"AbsOn_2\": 1, \"AbsOn_3\":",
"settings using the RoboDK API and a JSON string. #",
"count + 1 # Read settings json_data = robot.setParam(\"OptimAxes\") json_object",
"motion smoothing (0: No, 1: Yes): \"RelOn_1\": 1, \"RelOn_2\": 1,",
"\"RelW_1\": 5, \"RelW_2\": 47, \"RelW_3\": 44, \"RelW_4\": 43, \"RelW_5\": 36,",
"to a robot or a robot machining project manually or",
"json.dumps(json.dumps(ToUpdate)) status = robot.setParam(\"OptimAxes\", json_str) print(status) # Full update #OptimAxes_TEST[\"RefJoint_\"",
"Using for relative joint motion smoothing (0: No, 1: Yes):",
"\"RelW_7\": 53, \"RelW_8\": 59, \"RelW_9\": 0, } # Update one",
"} # Update one value, for example, make it active:",
"1: Yes): \"RelOn_1\": 1, \"RelOn_2\": 1, \"RelOn_3\": 1, \"RelOn_4\": 1,",
"= robot.setParam(\"OptimAxes\", json_str) print(status) # Full update #OptimAxes_TEST[\"RefJoint_\" + str(i+1)]",
"value, for example, make it active: ToUpdate = {} ToUpdate[\"Active\"]",
"92, \"AbsW_8\": 96, \"AbsW_9\": 50, # Using for relative joint",
"update #print(robot.setParam(\"OptimAxes\", str(AxesOptimSettings))) count = count + 1 # Read",
"generic axes optimization: 0=Disabled or 1=Enabled \"Algorithm\": 2, # Optimization",
"API # JSON tools import json # Start the RoboDK",
"\"AbsOn_8\": 1, \"AbsOn_9\": 1, # Weight for absolute reference joints",
"59, \"RelW_9\": 0, } # Update one value, for example,",
"\"AbsW_5\": 90, \"AbsW_6\": 92, \"AbsW_7\": 92, \"AbsW_8\": 96, \"AbsW_9\": 50,",
"Mead, 2=Samples, 3=Samples+Nelder Mead \"MaxIter\": 650, # Max. number of",
"machining menu or the robot parameters to view the axes",
"# Read settings json_data = robot.setParam(\"OptimAxes\") json_object = json.loads(json_data) print(json.dumps(json_object,",
"settings test template AxesOptimSettings = { # Optimization parameters: \"Active\":",
"json_data = robot.setParam(\"OptimAxes\") json_object = json.loads(json_data) print(json.dumps(json_object, indent=4)) pause(0.2) #",
"(double): \"AbsJnt_1\": 104.17, \"AbsJnt_2\": 11.22, \"AbsJnt_3\": 15.97, \"AbsJnt_4\": -87.48, \"AbsJnt_5\":",
"(count+i) json_str = json.dumps(json.dumps(ToUpdate)) status = robot.setParam(\"OptimAxes\", json_str) print(status) #",
"robot.setParam(\"OptimAxes\", json_str) print(status) # Example to make a partial or",
"RoboDK API RDK = Robolink() # Ask the user to",
"a robot or a robot machining project manually or using",
"ToUpdate[\"AbsW_\" + str(i+1)] = (count+i) json_str = json.dumps(json.dumps(ToUpdate)) status =",
"how to read or modify the Axes Optimization settings using",
"For more information visit: # https://robodk.com/doc/en/PythonAPI/robolink.html from robolink import *",
"or 1=Enabled \"Algorithm\": 2, # Optimization algorithm to use: 1=Nelder",
"Tolerance to stop iterations # Absolute Reference joints (double): \"AbsJnt_1\":",
"# Ask the user to select a robot arm (6",
"reference joints (0: No, 1: Yes): \"AbsOn_1\": 1, \"AbsOn_2\": 1,",
"\"RelOn_6\": 1, \"RelOn_7\": 1, \"RelOn_8\": 1, \"RelOn_9\": 1, # Weight",
"a JSON string. # You can select \"Axes optimization\" in",
"\"RelOn_8\": 1, \"RelOn_9\": 1, # Weight for relative joint motion",
"using the API. # # More information about the RoboDK",
"\"AbsJnt_2\": 11.22, \"AbsJnt_3\": 15.97, \"AbsJnt_4\": -87.48, \"AbsJnt_5\": -75.36, \"AbsJnt_6\": 63.03,",
"# Example to read the current axes optimization settings: while",
"a partial or full update count = 1 while True:",
"str(i+1)] = (count+i) #OptimAxes_TEST[\"RefOn_\" + str(i+1)] = count % 2",
"# Partial update ToUpdate = {} ToUpdate[\"AbsJnt_\" + str(i+1)] =",
"# Start the RoboDK API RDK = Robolink() # Ask",
"= json.dumps(json.dumps(ToUpdate)) status = robot.setParam(\"OptimAxes\", json_str) print(status) # Full update",
"% 2 # Full update #print(robot.setParam(\"OptimAxes\", str(AxesOptimSettings))) count = count",
"# Full update #OptimAxes_TEST[\"RefJoint_\" + str(i+1)] = (count+i)*4 #OptimAxes_TEST[\"RefWeight_\" +",
"optimization settings test template AxesOptimSettings = { # Optimization parameters:",
"about the RoboDK API here: # https://robodk.com/doc/en/RoboDK-API.html # For more",
"* # RoboDK API # JSON tools import json #",
"update the axes optimization settings attached to a robot or",
"a robot arm\",ITEM_TYPE_ROBOT_ARM) # Default optimization settings test template AxesOptimSettings",
"{} ToUpdate[\"Active\"] = 1 json_str = json.dumps(json.dumps(ToUpdate)) status = robot.setParam(\"OptimAxes\",",
"# RoboDK API # JSON tools import json # Start",
"import json # Start the RoboDK API RDK = Robolink()",
"#print(robot.setParam(\"OptimAxes\", str(AxesOptimSettings))) count = count + 1 # Read settings",
"It is possible to update the axes optimization settings attached",
"1, \"AbsOn_6\": 1, \"AbsOn_7\": 1, \"AbsOn_8\": 1, \"AbsOn_9\": 1, #",
"1, # Weight for relative joint motion (double): \"RelW_1\": 5,",
"make it active: ToUpdate = {} ToUpdate[\"Active\"] = 1 json_str",
"API RDK = Robolink() # Ask the user to select",
"information about the RoboDK API here: # https://robodk.com/doc/en/RoboDK-API.html # For",
"0, } # Update one value, for example, make it",
"+ str(i+1)] = count % 2 # Full update #print(robot.setParam(\"OptimAxes\",",
"\"AbsOn_7\": 1, \"AbsOn_8\": 1, \"AbsOn_9\": 1, # Weight for absolute",
"robot.setParam(\"OptimAxes\") json_object = json.loads(json_data) print(json.dumps(json_object, indent=4)) pause(0.2) # Example to",
"2=Samples, 3=Samples+Nelder Mead \"MaxIter\": 650, # Max. number of iterations",
"\"AbsW_9\": 50, # Using for relative joint motion smoothing (0:",
"absolute reference joints (double): \"AbsW_1\": 100, \"AbsW_2\": 100, \"AbsW_3\": 100,",
"Robolink() # Ask the user to select a robot arm",
"47, \"RelW_7\": 53, \"RelW_8\": 59, \"RelW_9\": 0, } # Update",
"(count+i)*4 ToUpdate[\"AbsOn_\" + str(i+1)] = count % 2 ToUpdate[\"AbsW_\" +",
"while True: for i in range(7): # Partial update ToUpdate",
"-75.36, \"AbsJnt_6\": 63.03, \"AbsJnt_7\": 174.13, \"AbsJnt_8\": 173.60, \"AbsJnt_9\": 0, #",
"\"AbsW_7\": 92, \"AbsW_8\": 96, \"AbsW_9\": 50, # Using for relative",
"import * # RoboDK API # JSON tools import json",
"to update the axes optimization settings attached to a robot",
"modify the Axes Optimization settings using the RoboDK API and",
"\"AbsOn_5\": 1, \"AbsOn_6\": 1, \"AbsOn_7\": 1, \"AbsOn_8\": 1, \"AbsOn_9\": 1,",
"Ask the user to select a robot arm (6 axis",
"\"AbsW_3\": 100, \"AbsW_4\": 89, \"AbsW_5\": 90, \"AbsW_6\": 92, \"AbsW_7\": 92,",
"to use: 1=Nelder Mead, 2=Samples, 3=Samples+Nelder Mead \"MaxIter\": 650, #",
"(0: No, 1: Yes): \"AbsOn_1\": 1, \"AbsOn_2\": 1, \"AbsOn_3\": 1,",
"\"AbsJnt_5\": -75.36, \"AbsJnt_6\": 63.03, \"AbsJnt_7\": 174.13, \"AbsJnt_8\": 173.60, \"AbsJnt_9\": 0,",
"to select a robot arm (6 axis robot wich can",
"update #OptimAxes_TEST[\"RefJoint_\" + str(i+1)] = (count+i)*4 #OptimAxes_TEST[\"RefWeight_\" + str(i+1)] =",
"for absolute reference joints (double): \"AbsW_1\": 100, \"AbsW_2\": 100, \"AbsW_3\":",
"\"AbsJnt_9\": 0, # Using Absolute reference joints (0: No, 1:",
"Use generic axes optimization: 0=Disabled or 1=Enabled \"Algorithm\": 2, #",
"# Max. number of iterations \"Tol\": 0.0016, # Tolerance to",
"90, \"AbsW_6\": 92, \"AbsW_7\": 92, \"AbsW_8\": 96, \"AbsW_9\": 50, #",
"Update one value, for example, make it active: ToUpdate =",
"\"RelOn_2\": 1, \"RelOn_3\": 1, \"RelOn_4\": 1, \"RelOn_5\": 1, \"RelOn_6\": 1,",
"Example to read the current axes optimization settings: while True:",
"read the current axes optimization settings: while True: json_data =",
"\"RelOn_1\": 1, \"RelOn_2\": 1, \"RelOn_3\": 1, \"RelOn_4\": 1, \"RelOn_5\": 1,",
"1: Yes): \"AbsOn_1\": 1, \"AbsOn_2\": 1, \"AbsOn_3\": 1, \"AbsOn_4\": 1,",
"read or modify the Axes Optimization settings using the RoboDK",
"RDK = Robolink() # Ask the user to select a",
"\"AbsJnt_7\": 174.13, \"AbsJnt_8\": 173.60, \"AbsJnt_9\": 0, # Using Absolute reference",
"count = count + 1 # Read settings json_data =",
"This example shows how to read or modify the Axes",
"the axes optimization settings attached to a robot or a",
"= {} ToUpdate[\"AbsJnt_\" + str(i+1)] = (count+i)*4 ToUpdate[\"AbsOn_\" + str(i+1)]",
"update count = 1 while True: for i in range(7):",
"the RoboDK API and a JSON string. # You can",
"174.13, \"AbsJnt_8\": 173.60, \"AbsJnt_9\": 0, # Using Absolute reference joints",
"optimization settings attached to a robot or a robot machining",
"from robolink import * # RoboDK API # JSON tools",
"# Default optimization settings test template AxesOptimSettings = { #",
"print(json.dumps(json_object, indent=4)) pause(0.2) # Example to read the current axes",
"current axes optimization settings: while True: json_data = robot.setParam(\"OptimAxes\") json_object",
"active: ToUpdate = {} ToUpdate[\"Active\"] = 1 json_str = json.dumps(json.dumps(ToUpdate))",
"view the axes optimization settings. # It is possible to",
"a robot arm (6 axis robot wich can have external",
"robot = RDK.ItemUserPick(\"Select a robot arm\",ITEM_TYPE_ROBOT_ARM) # Default optimization settings",
"# Optimization algorithm to use: 1=Nelder Mead, 2=Samples, 3=Samples+Nelder Mead",
"\"AbsJnt_1\": 104.17, \"AbsJnt_2\": 11.22, \"AbsJnt_3\": 15.97, \"AbsJnt_4\": -87.48, \"AbsJnt_5\": -75.36,",
"0.0016, # Tolerance to stop iterations # Absolute Reference joints",
"axes) robot = RDK.ItemUserPick(\"Select a robot arm\",ITEM_TYPE_ROBOT_ARM) # Default optimization",
"can select \"Axes optimization\" in a robot machining menu or",
"\"RelW_9\": 0, } # Update one value, for example, make",
"parameters to view the axes optimization settings. # It is",
"96, \"AbsW_9\": 50, # Using for relative joint motion smoothing",
"using the RoboDK API and a JSON string. # You",
"relative joint motion smoothing (0: No, 1: Yes): \"RelOn_1\": 1,",
"str(i+1)] = (count+i)*4 #OptimAxes_TEST[\"RefWeight_\" + str(i+1)] = (count+i) #OptimAxes_TEST[\"RefOn_\" +",
"\"AbsJnt_8\": 173.60, \"AbsJnt_9\": 0, # Using Absolute reference joints (0:",
"2, # Optimization algorithm to use: 1=Nelder Mead, 2=Samples, 3=Samples+Nelder",
"select \"Axes optimization\" in a robot machining menu or the",
"\"AbsW_8\": 96, \"AbsW_9\": 50, # Using for relative joint motion",
"count % 2 ToUpdate[\"AbsW_\" + str(i+1)] = (count+i) json_str =",
"Default optimization settings test template AxesOptimSettings = { # Optimization",
"robot wich can have external axes) robot = RDK.ItemUserPick(\"Select a",
"1 json_str = json.dumps(json.dumps(ToUpdate)) status = robot.setParam(\"OptimAxes\", json_str) print(status) #",
"possible to update the axes optimization settings attached to a",
"\"AbsJnt_6\": 63.03, \"AbsJnt_7\": 174.13, \"AbsJnt_8\": 173.60, \"AbsJnt_9\": 0, # Using",
"# Optimization parameters: \"Active\": 1, # Use generic axes optimization:",
"1, \"AbsOn_3\": 1, \"AbsOn_4\": 1, \"AbsOn_5\": 1, \"AbsOn_6\": 1, \"AbsOn_7\":",
"\"RelW_4\": 43, \"RelW_5\": 36, \"RelW_6\": 47, \"RelW_7\": 53, \"RelW_8\": 59,",
"RDK.ItemUserPick(\"Select a robot arm\",ITEM_TYPE_ROBOT_ARM) # Default optimization settings test template",
"joint motion smoothing (0: No, 1: Yes): \"RelOn_1\": 1, \"RelOn_2\":",
"{} ToUpdate[\"AbsJnt_\" + str(i+1)] = (count+i)*4 ToUpdate[\"AbsOn_\" + str(i+1)] =",
"external axes) robot = RDK.ItemUserPick(\"Select a robot arm\",ITEM_TYPE_ROBOT_ARM) # Default",
"to stop iterations # Absolute Reference joints (double): \"AbsJnt_1\": 104.17,",
"\"Axes optimization\" in a robot machining menu or the robot",
"100, \"AbsW_2\": 100, \"AbsW_3\": 100, \"AbsW_4\": 89, \"AbsW_5\": 90, \"AbsW_6\":",
"= { # Optimization parameters: \"Active\": 1, # Use generic",
"# Full update #print(robot.setParam(\"OptimAxes\", str(AxesOptimSettings))) count = count + 1",
"{ # Optimization parameters: \"Active\": 1, # Use generic axes",
"\"Algorithm\": 2, # Optimization algorithm to use: 1=Nelder Mead, 2=Samples,",
"wich can have external axes) robot = RDK.ItemUserPick(\"Select a robot",
"Using Absolute reference joints (0: No, 1: Yes): \"AbsOn_1\": 1,",
"(double): \"RelW_1\": 5, \"RelW_2\": 47, \"RelW_3\": 44, \"RelW_4\": 43, \"RelW_5\":",
"1 while True: for i in range(7): # Partial update",
"more information visit: # https://robodk.com/doc/en/PythonAPI/robolink.html from robolink import * #",
"1, \"RelOn_4\": 1, \"RelOn_5\": 1, \"RelOn_6\": 1, \"RelOn_7\": 1, \"RelOn_8\":",
"optimization: 0=Disabled or 1=Enabled \"Algorithm\": 2, # Optimization algorithm to",
"json_object = json.loads(json_data) print(json.dumps(json_object, indent=4)) pause(0.2) # Example to read",
"AxesOptimSettings = { # Optimization parameters: \"Active\": 1, # Use",
"here: # https://robodk.com/doc/en/RoboDK-API.html # For more information visit: # https://robodk.com/doc/en/PythonAPI/robolink.html",
"print(status) # Example to make a partial or full update",
"0, # Using Absolute reference joints (0: No, 1: Yes):",
"# It is possible to update the axes optimization settings",
"0=Disabled or 1=Enabled \"Algorithm\": 2, # Optimization algorithm to use:",
"# # More information about the RoboDK API here: #",
"\"AbsOn_1\": 1, \"AbsOn_2\": 1, \"AbsOn_3\": 1, \"AbsOn_4\": 1, \"AbsOn_5\": 1,",
"str(AxesOptimSettings))) count = count + 1 # Read settings json_data",
"1, \"AbsOn_4\": 1, \"AbsOn_5\": 1, \"AbsOn_6\": 1, \"AbsOn_7\": 1, \"AbsOn_8\":",
"API. # # More information about the RoboDK API here:",
"the current axes optimization settings: while True: json_data = robot.setParam(\"OptimAxes\")",
"\"AbsW_6\": 92, \"AbsW_7\": 92, \"AbsW_8\": 96, \"AbsW_9\": 50, # Using",
"= 1 while True: for i in range(7): # Partial",
"104.17, \"AbsJnt_2\": 11.22, \"AbsJnt_3\": 15.97, \"AbsJnt_4\": -87.48, \"AbsJnt_5\": -75.36, \"AbsJnt_6\":",
"\"AbsW_1\": 100, \"AbsW_2\": 100, \"AbsW_3\": 100, \"AbsW_4\": 89, \"AbsW_5\": 90,",
"the Axes Optimization settings using the RoboDK API and a",
"\"AbsJnt_3\": 15.97, \"AbsJnt_4\": -87.48, \"AbsJnt_5\": -75.36, \"AbsJnt_6\": 63.03, \"AbsJnt_7\": 174.13,",
"the axes optimization settings. # It is possible to update",
"example, make it active: ToUpdate = {} ToUpdate[\"Active\"] = 1",
"= count + 1 # Read settings json_data = robot.setParam(\"OptimAxes\")",
"173.60, \"AbsJnt_9\": 0, # Using Absolute reference joints (0: No,",
"Optimization algorithm to use: 1=Nelder Mead, 2=Samples, 3=Samples+Nelder Mead \"MaxIter\":",
"1, \"AbsOn_8\": 1, \"AbsOn_9\": 1, # Weight for absolute reference"
] |
[
"as grammar_file: self.G = Grammar(grammar_file.read()) self.assertDictEqual( {'E': {('E', '+', 'T'),",
"( E ) F -> id\"\"\", \"\"\"E -> E ^",
"id\"\"\"] with self.assertRaises(ValueError): Grammar(self.grammar_str[0]) with self.assertRaises(ValueError): Grammar(self.grammar_str[1]) if __name__ ==",
"* F | F F -> ( E ) F",
"')', 'id'}, self.G.terminals) self.assertSetEqual({'E', 'T', 'F'}, self.G.nonterminals) self.assertSetEqual({'+', '*', '(',",
"import Grammar import unittest class TestGrammar(unittest.TestCase): def test_grammar(self): with open('tests/test_grammar.txt')",
"('F',)}, 'F': {('(', 'E', ')'), ('id',)}}, self.G.grammar) self.assertEqual('E', self.G.start) self.assertSetEqual({'+',",
"def test_grammar(self): with open('tests/test_grammar.txt') as grammar_file: self.G = Grammar(grammar_file.read()) self.assertDictEqual(",
"F F -> ( E ) F -> id\"\"\", \"\"\"E",
"F F -> ( E ) F -> id\"\"\"] with",
"T e -> T T -> T * F |",
"unittest class TestGrammar(unittest.TestCase): def test_grammar(self): with open('tests/test_grammar.txt') as grammar_file: self.G",
"= [\"\"\"E -> E + T e -> T T",
"'T', 'F'}, self.G.symbols) self.grammar_str = [\"\"\"E -> E + T",
"'T', 'F'}, self.G.nonterminals) self.assertSetEqual({'+', '*', '(', ')', 'id', 'E', 'T',",
"E ) F -> id\"\"\", \"\"\"E -> E ^ +",
"F -> ( E ) F -> id\"\"\"] with self.assertRaises(ValueError):",
"')'), ('id',)}}, self.G.grammar) self.assertEqual('E', self.G.start) self.assertSetEqual({'+', '*', '(', ')', 'id'},",
"self.G.grammar) self.assertEqual('E', self.G.start) self.assertSetEqual({'+', '*', '(', ')', 'id'}, self.G.terminals) self.assertSetEqual({'E',",
"self.G.terminals) self.assertSetEqual({'E', 'T', 'F'}, self.G.nonterminals) self.assertSetEqual({'+', '*', '(', ')', 'id',",
"slr_parser.grammar import Grammar import unittest class TestGrammar(unittest.TestCase): def test_grammar(self): with",
") F -> id\"\"\", \"\"\"E -> E ^ + T",
"[\"\"\"E -> E + T e -> T T ->",
"'T': {('T', '*', 'F'), ('F',)}, 'F': {('(', 'E', ')'), ('id',)}},",
"T T -> T * F | F F ->",
"e -> T T -> T * F | F",
"'T'), ('T',)}, 'T': {('T', '*', 'F'), ('F',)}, 'F': {('(', 'E',",
"^ + T E -> T T -> T *",
"= Grammar(grammar_file.read()) self.assertDictEqual( {'E': {('E', '+', 'T'), ('T',)}, 'T': {('T',",
"self.G.symbols) self.grammar_str = [\"\"\"E -> E + T e ->",
"test_grammar(self): with open('tests/test_grammar.txt') as grammar_file: self.G = Grammar(grammar_file.read()) self.assertDictEqual( {'E':",
"'F'}, self.G.symbols) self.grammar_str = [\"\"\"E -> E + T e",
"( E ) F -> id\"\"\"] with self.assertRaises(ValueError): Grammar(self.grammar_str[0]) with",
"'*', '(', ')', 'id'}, self.G.terminals) self.assertSetEqual({'E', 'T', 'F'}, self.G.nonterminals) self.assertSetEqual({'+',",
"{('T', '*', 'F'), ('F',)}, 'F': {('(', 'E', ')'), ('id',)}}, self.G.grammar)",
"from slr_parser.grammar import Grammar import unittest class TestGrammar(unittest.TestCase): def test_grammar(self):",
"-> E + T e -> T T -> T",
"self.assertRaises(ValueError): Grammar(self.grammar_str[0]) with self.assertRaises(ValueError): Grammar(self.grammar_str[1]) if __name__ == '__main__': unittest.main()",
"self.G.nonterminals) self.assertSetEqual({'+', '*', '(', ')', 'id', 'E', 'T', 'F'}, self.G.symbols)",
"'E', ')'), ('id',)}}, self.G.grammar) self.assertEqual('E', self.G.start) self.assertSetEqual({'+', '*', '(', ')',",
"T * F | F F -> ( E )",
"'+', 'T'), ('T',)}, 'T': {('T', '*', 'F'), ('F',)}, 'F': {('(',",
"'(', ')', 'id', 'E', 'T', 'F'}, self.G.symbols) self.grammar_str = [\"\"\"E",
"-> T * F | F F -> ( E",
"self.G = Grammar(grammar_file.read()) self.assertDictEqual( {'E': {('E', '+', 'T'), ('T',)}, 'T':",
"-> ( E ) F -> id\"\"\"] with self.assertRaises(ValueError): Grammar(self.grammar_str[0])",
"F -> id\"\"\", \"\"\"E -> E ^ + T E",
"F -> id\"\"\"] with self.assertRaises(ValueError): Grammar(self.grammar_str[0]) with self.assertRaises(ValueError): Grammar(self.grammar_str[1]) if",
"self.assertSetEqual({'E', 'T', 'F'}, self.G.nonterminals) self.assertSetEqual({'+', '*', '(', ')', 'id', 'E',",
"class TestGrammar(unittest.TestCase): def test_grammar(self): with open('tests/test_grammar.txt') as grammar_file: self.G =",
"self.grammar_str = [\"\"\"E -> E + T e -> T",
"-> id\"\"\", \"\"\"E -> E ^ + T E ->",
"F | F F -> ( E ) F ->",
"import unittest class TestGrammar(unittest.TestCase): def test_grammar(self): with open('tests/test_grammar.txt') as grammar_file:",
"E ^ + T E -> T T -> T",
"\"\"\"E -> E ^ + T E -> T T",
"'F'}, self.G.nonterminals) self.assertSetEqual({'+', '*', '(', ')', 'id', 'E', 'T', 'F'},",
"+ T e -> T T -> T * F",
"{('E', '+', 'T'), ('T',)}, 'T': {('T', '*', 'F'), ('F',)}, 'F':",
"Grammar import unittest class TestGrammar(unittest.TestCase): def test_grammar(self): with open('tests/test_grammar.txt') as",
"')', 'id', 'E', 'T', 'F'}, self.G.symbols) self.grammar_str = [\"\"\"E ->",
"E ) F -> id\"\"\"] with self.assertRaises(ValueError): Grammar(self.grammar_str[0]) with self.assertRaises(ValueError):",
"{'E': {('E', '+', 'T'), ('T',)}, 'T': {('T', '*', 'F'), ('F',)},",
"open('tests/test_grammar.txt') as grammar_file: self.G = Grammar(grammar_file.read()) self.assertDictEqual( {'E': {('E', '+',",
"with self.assertRaises(ValueError): Grammar(self.grammar_str[0]) with self.assertRaises(ValueError): Grammar(self.grammar_str[1]) if __name__ == '__main__':",
"| F F -> ( E ) F -> id\"\"\",",
"'id', 'E', 'T', 'F'}, self.G.symbols) self.grammar_str = [\"\"\"E -> E",
"-> E ^ + T E -> T T ->",
"T E -> T T -> T * F |",
"with open('tests/test_grammar.txt') as grammar_file: self.G = Grammar(grammar_file.read()) self.assertDictEqual( {'E': {('E',",
"-> ( E ) F -> id\"\"\", \"\"\"E -> E",
"'F'), ('F',)}, 'F': {('(', 'E', ')'), ('id',)}}, self.G.grammar) self.assertEqual('E', self.G.start)",
"-> T T -> T * F | F F",
"-> id\"\"\"] with self.assertRaises(ValueError): Grammar(self.grammar_str[0]) with self.assertRaises(ValueError): Grammar(self.grammar_str[1]) if __name__",
"TestGrammar(unittest.TestCase): def test_grammar(self): with open('tests/test_grammar.txt') as grammar_file: self.G = Grammar(grammar_file.read())",
"| F F -> ( E ) F -> id\"\"\"]",
"Grammar(grammar_file.read()) self.assertDictEqual( {'E': {('E', '+', 'T'), ('T',)}, 'T': {('T', '*',",
"'*', '(', ')', 'id', 'E', 'T', 'F'}, self.G.symbols) self.grammar_str =",
"('id',)}}, self.G.grammar) self.assertEqual('E', self.G.start) self.assertSetEqual({'+', '*', '(', ')', 'id'}, self.G.terminals)",
"E -> T T -> T * F | F",
"'id'}, self.G.terminals) self.assertSetEqual({'E', 'T', 'F'}, self.G.nonterminals) self.assertSetEqual({'+', '*', '(', ')',",
"self.assertEqual('E', self.G.start) self.assertSetEqual({'+', '*', '(', ')', 'id'}, self.G.terminals) self.assertSetEqual({'E', 'T',",
"+ T E -> T T -> T * F",
"self.assertDictEqual( {'E': {('E', '+', 'T'), ('T',)}, 'T': {('T', '*', 'F'),",
"F -> ( E ) F -> id\"\"\", \"\"\"E ->",
"('T',)}, 'T': {('T', '*', 'F'), ('F',)}, 'F': {('(', 'E', ')'),",
"{('(', 'E', ')'), ('id',)}}, self.G.grammar) self.assertEqual('E', self.G.start) self.assertSetEqual({'+', '*', '(',",
"'E', 'T', 'F'}, self.G.symbols) self.grammar_str = [\"\"\"E -> E +",
"id\"\"\", \"\"\"E -> E ^ + T E -> T",
"self.assertSetEqual({'+', '*', '(', ')', 'id'}, self.G.terminals) self.assertSetEqual({'E', 'T', 'F'}, self.G.nonterminals)",
") F -> id\"\"\"] with self.assertRaises(ValueError): Grammar(self.grammar_str[0]) with self.assertRaises(ValueError): Grammar(self.grammar_str[1])",
"grammar_file: self.G = Grammar(grammar_file.read()) self.assertDictEqual( {'E': {('E', '+', 'T'), ('T',)},",
"'(', ')', 'id'}, self.G.terminals) self.assertSetEqual({'E', 'T', 'F'}, self.G.nonterminals) self.assertSetEqual({'+', '*',",
"E + T e -> T T -> T *",
"T -> T * F | F F -> (",
"'*', 'F'), ('F',)}, 'F': {('(', 'E', ')'), ('id',)}}, self.G.grammar) self.assertEqual('E',",
"'F': {('(', 'E', ')'), ('id',)}}, self.G.grammar) self.assertEqual('E', self.G.start) self.assertSetEqual({'+', '*',",
"self.assertSetEqual({'+', '*', '(', ')', 'id', 'E', 'T', 'F'}, self.G.symbols) self.grammar_str",
"<filename>tests/test_grammar.py from slr_parser.grammar import Grammar import unittest class TestGrammar(unittest.TestCase): def",
"self.G.start) self.assertSetEqual({'+', '*', '(', ')', 'id'}, self.G.terminals) self.assertSetEqual({'E', 'T', 'F'},"
] |
[
"('result', models.CharField(max_length=40)), ('timecontrol', models.CharField(max_length=40)), ('timestamp', models.DateTimeField()), ('raw', models.TextField()), ('opening', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE,",
"initial = True dependencies = [ ] operations = [",
"Django 3.1 on 2020-09-08 07:43 from django.db import migrations, models",
"), migrations.CreateModel( name='User', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name',",
"), migrations.CreateModel( name='Opening', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name',",
"('unbalance_officers', models.IntegerField(default=0)), ('unbalance_exchange', models.IntegerField(default=0)), ('game', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='insight.game')), ], ), ]",
"models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('turnover_move', models.IntegerField(default=0)), ('turnover_evaluation', models.IntegerField(default=0)), ('unbalance_material', models.IntegerField(default=0)),",
"], ), migrations.CreateModel( name='Game', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),",
"models.CharField(max_length=3)), ('moves', models.TextField()), ('opening_system', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='insight.openingsystem')), ], ), migrations.CreateModel( name='Game',",
"models.TextField()), ('opening', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='insight.opening')), ], ), migrations.CreateModel( name='Analyse', fields=[ ('id',",
"models.IntegerField(default=0)), ('unbalance_material', models.IntegerField(default=0)), ('unbalance_officers', models.IntegerField(default=0)), ('unbalance_exchange', models.IntegerField(default=0)), ('game', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='insight.game')),",
"Generated by Django 3.1 on 2020-09-08 07:43 from django.db import",
"# Generated by Django 3.1 on 2020-09-08 07:43 from django.db",
"primary_key=True, serialize=False, verbose_name='ID')), ('turnover_move', models.IntegerField(default=0)), ('turnover_evaluation', models.IntegerField(default=0)), ('unbalance_material', models.IntegerField(default=0)), ('unbalance_officers',",
"fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('elo_mean', models.IntegerField(default=0)), ('elo_diff', models.IntegerField(default=0)),",
"migrations.CreateModel( name='Opening', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=40)),",
"name='Analyse', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('turnover_move', models.IntegerField(default=0)), ('turnover_evaluation',",
"to='insight.opening')), ], ), migrations.CreateModel( name='Analyse', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False,",
"models.CharField(max_length=40)), ('eco', models.CharField(max_length=3)), ('moves', models.TextField()), ('opening_system', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='insight.openingsystem')), ], ),",
"models.TextField()), ('opening_system', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='insight.openingsystem')), ], ), migrations.CreateModel( name='Game', fields=[ ('id',",
"by Django 3.1 on 2020-09-08 07:43 from django.db import migrations,",
"name='OpeningSystem', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=40)), ],",
"migrations.CreateModel( name='Analyse', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('turnover_move', models.IntegerField(default=0)),",
"name='Game', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('elo_mean', models.IntegerField(default=0)), ('elo_diff',",
"('name', models.CharField(max_length=40)), ], ), migrations.CreateModel( name='Opening', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True,",
"migrations.CreateModel( name='OpeningSystem', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=40)),",
"fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=40)), ('eco', models.CharField(max_length=3)),",
"('opening_system', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='insight.openingsystem')), ], ), migrations.CreateModel( name='Game', fields=[ ('id', models.AutoField(auto_created=True,",
"('timecontrol', models.CharField(max_length=40)), ('timestamp', models.DateTimeField()), ('raw', models.TextField()), ('opening', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='insight.opening')), ],",
"serialize=False, verbose_name='ID')), ('elo_mean', models.IntegerField(default=0)), ('elo_diff', models.IntegerField(default=0)), ('result', models.CharField(max_length=40)), ('timecontrol', models.CharField(max_length=40)),",
"serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=40)), ], ), migrations.CreateModel( name='Opening', fields=[ ('id',",
"import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [",
"import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True",
"primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=40)), ], ), migrations.CreateModel( name='Opening', fields=[",
"], ), migrations.CreateModel( name='Opening', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),",
"verbose_name='ID')), ('elo_mean', models.IntegerField(default=0)), ('elo_diff', models.IntegerField(default=0)), ('result', models.CharField(max_length=40)), ('timecontrol', models.CharField(max_length=40)), ('timestamp',",
"('moves', models.TextField()), ('opening_system', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='insight.openingsystem')), ], ), migrations.CreateModel( name='Game', fields=[",
"('turnover_evaluation', models.IntegerField(default=0)), ('unbalance_material', models.IntegerField(default=0)), ('unbalance_officers', models.IntegerField(default=0)), ('unbalance_exchange', models.IntegerField(default=0)), ('game', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE,",
"name='Opening', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=40)), ('eco',",
"), migrations.CreateModel( name='Analyse', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('turnover_move',",
"[ ] operations = [ migrations.CreateModel( name='OpeningSystem', fields=[ ('id', models.AutoField(auto_created=True,",
"fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('turnover_move', models.IntegerField(default=0)), ('turnover_evaluation', models.IntegerField(default=0)),",
"models.DateTimeField()), ('raw', models.TextField()), ('opening', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='insight.opening')), ], ), migrations.CreateModel( name='Analyse',",
"models.CharField(max_length=40)), ('timestamp', models.DateTimeField()), ('raw', models.TextField()), ('opening', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='insight.opening')), ], ),",
"django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ]",
"), migrations.CreateModel( name='Game', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('elo_mean',",
"] operations = [ migrations.CreateModel( name='OpeningSystem', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True,",
"models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='insight.openingsystem')), ], ), migrations.CreateModel( name='Game', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True,",
"models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies =",
"migrations.CreateModel( name='Game', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('elo_mean', models.IntegerField(default=0)),",
"django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial =",
"primary_key=True, serialize=False, verbose_name='ID')), ('elo_mean', models.IntegerField(default=0)), ('elo_diff', models.IntegerField(default=0)), ('result', models.CharField(max_length=40)), ('timecontrol',",
"primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=40)), ('eco', models.CharField(max_length=3)), ('moves', models.TextField()), ('opening_system',",
"models.CharField(max_length=40)), ], ), migrations.CreateModel( name='User', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False,",
"07:43 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration):",
"operations = [ migrations.CreateModel( name='OpeningSystem', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False,",
"models.IntegerField(default=0)), ('unbalance_officers', models.IntegerField(default=0)), ('unbalance_exchange', models.IntegerField(default=0)), ('game', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='insight.game')), ], ),",
"= [ ] operations = [ migrations.CreateModel( name='OpeningSystem', fields=[ ('id',",
"('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('turnover_move', models.IntegerField(default=0)), ('turnover_evaluation', models.IntegerField(default=0)), ('unbalance_material',",
"from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial",
"serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=40)), ('eco', models.CharField(max_length=3)), ('moves', models.TextField()), ('opening_system', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE,",
"class Migration(migrations.Migration): initial = True dependencies = [ ] operations",
"('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=40)), ('eco', models.CharField(max_length=3)), ('moves',",
"migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies",
"models.IntegerField(default=0)), ('result', models.CharField(max_length=40)), ('timecontrol', models.CharField(max_length=40)), ('timestamp', models.DateTimeField()), ('raw', models.TextField()), ('opening',",
"on 2020-09-08 07:43 from django.db import migrations, models import django.db.models.deletion",
"serialize=False, verbose_name='ID')), ('turnover_move', models.IntegerField(default=0)), ('turnover_evaluation', models.IntegerField(default=0)), ('unbalance_material', models.IntegerField(default=0)), ('unbalance_officers', models.IntegerField(default=0)),",
"('raw', models.TextField()), ('opening', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='insight.opening')), ], ), migrations.CreateModel( name='Analyse', fields=[",
"models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='insight.opening')), ], ), migrations.CreateModel( name='Analyse', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True,",
"dependencies = [ ] operations = [ migrations.CreateModel( name='OpeningSystem', fields=[",
"[ migrations.CreateModel( name='OpeningSystem', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name',",
"('name', models.CharField(max_length=40)), ], ), migrations.CreateModel( name='User', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True,",
"verbose_name='ID')), ('name', models.CharField(max_length=40)), ], ), migrations.CreateModel( name='Opening', fields=[ ('id', models.AutoField(auto_created=True,",
"('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=40)), ], ), migrations.CreateModel(",
"], ), migrations.CreateModel( name='Analyse', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),",
"Migration(migrations.Migration): initial = True dependencies = [ ] operations =",
"('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('elo_mean', models.IntegerField(default=0)), ('elo_diff', models.IntegerField(default=0)), ('result',",
"verbose_name='ID')), ('name', models.CharField(max_length=40)), ('eco', models.CharField(max_length=3)), ('moves', models.TextField()), ('opening_system', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='insight.openingsystem')),",
"True dependencies = [ ] operations = [ migrations.CreateModel( name='OpeningSystem',",
"('elo_mean', models.IntegerField(default=0)), ('elo_diff', models.IntegerField(default=0)), ('result', models.CharField(max_length=40)), ('timecontrol', models.CharField(max_length=40)), ('timestamp', models.DateTimeField()),",
"], ), migrations.CreateModel( name='User', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),",
"models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('elo_mean', models.IntegerField(default=0)), ('elo_diff', models.IntegerField(default=0)), ('result', models.CharField(max_length=40)),",
"verbose_name='ID')), ('name', models.CharField(max_length=40)), ], ), migrations.CreateModel( name='User', fields=[ ('id', models.AutoField(auto_created=True,",
"name='User', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=40)), ],",
"models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=40)), ], ), migrations.CreateModel( name='Opening',",
"('unbalance_material', models.IntegerField(default=0)), ('unbalance_officers', models.IntegerField(default=0)), ('unbalance_exchange', models.IntegerField(default=0)), ('game', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='insight.game')), ],",
"('name', models.CharField(max_length=40)), ('eco', models.CharField(max_length=3)), ('moves', models.TextField()), ('opening_system', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='insight.openingsystem')), ],",
"('opening', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='insight.opening')), ], ), migrations.CreateModel( name='Analyse', fields=[ ('id', models.AutoField(auto_created=True,",
"models.CharField(max_length=40)), ], ), migrations.CreateModel( name='Opening', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False,",
"verbose_name='ID')), ('turnover_move', models.IntegerField(default=0)), ('turnover_evaluation', models.IntegerField(default=0)), ('unbalance_material', models.IntegerField(default=0)), ('unbalance_officers', models.IntegerField(default=0)), ('unbalance_exchange',",
"('turnover_move', models.IntegerField(default=0)), ('turnover_evaluation', models.IntegerField(default=0)), ('unbalance_material', models.IntegerField(default=0)), ('unbalance_officers', models.IntegerField(default=0)), ('unbalance_exchange', models.IntegerField(default=0)),",
"fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=40)), ], ),",
"('timestamp', models.DateTimeField()), ('raw', models.TextField()), ('opening', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='insight.opening')), ], ), migrations.CreateModel(",
"2020-09-08 07:43 from django.db import migrations, models import django.db.models.deletion class",
"('elo_diff', models.IntegerField(default=0)), ('result', models.CharField(max_length=40)), ('timecontrol', models.CharField(max_length=40)), ('timestamp', models.DateTimeField()), ('raw', models.TextField()),",
"models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=40)), ], ), migrations.CreateModel( name='User',",
"('eco', models.CharField(max_length=3)), ('moves', models.TextField()), ('opening_system', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='insight.openingsystem')), ], ), migrations.CreateModel(",
"models.IntegerField(default=0)), ('turnover_evaluation', models.IntegerField(default=0)), ('unbalance_material', models.IntegerField(default=0)), ('unbalance_officers', models.IntegerField(default=0)), ('unbalance_exchange', models.IntegerField(default=0)), ('game',",
"serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=40)), ], ), migrations.CreateModel( name='User', fields=[ ('id',",
"models.CharField(max_length=40)), ('timecontrol', models.CharField(max_length=40)), ('timestamp', models.DateTimeField()), ('raw', models.TextField()), ('opening', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='insight.opening')),",
"models.IntegerField(default=0)), ('elo_diff', models.IntegerField(default=0)), ('result', models.CharField(max_length=40)), ('timecontrol', models.CharField(max_length=40)), ('timestamp', models.DateTimeField()), ('raw',",
"3.1 on 2020-09-08 07:43 from django.db import migrations, models import",
"= [ migrations.CreateModel( name='OpeningSystem', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),",
"primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=40)), ], ), migrations.CreateModel( name='User', fields=[",
"= True dependencies = [ ] operations = [ migrations.CreateModel(",
"migrations.CreateModel( name='User', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=40)),",
"to='insight.openingsystem')), ], ), migrations.CreateModel( name='Game', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False,",
"models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=40)), ('eco', models.CharField(max_length=3)), ('moves', models.TextField()),"
] |
[
"else 1, key=world.Get_rank()) if world.Get_rank() < num_workers: volume = np.array(x_shape).prod()",
"key=world.Get_rank()) if world.Get_rank() < num_workers: volume = np.array(x_shape).prod() x =",
"torch.tensor([[0, 1], [4, 5]]) elif comm.Get_rank() == 1: x =",
"= torch.tensor([[0, 1], [4, 5]]) elif comm.Get_rank() == 1: x",
"np.array(x_shape).prod() x = torch.arange(volume).view(x_shape) x = tensor_merge(x, comm=comm, worker_shape=worker_shape) e",
"= torch.tensor([ [0, 1, 2, 3], [4, 5, 6, 7],",
"worker_shape=worker_shape) if comm.Get_rank() == 0: e = torch.tensor([ [0, 1,",
"= [2, 2] world = MPI.COMM_WORLD num_workers = np.array(worker_shape).prod() comm",
"world = MPI.COMM_WORLD num_workers = np.array(worker_shape).prod() comm = MPI.COMM_WORLD.Split(color=0 if",
"[4, 5, 6, 7], [8, 9, 10, 11], [12, 13,",
"torch.tensor([ [0, 1, 2, 3], [4, 5, 6, 7], [8,",
"world.Get_rank() < num_workers else 1, key=world.Get_rank()) if world.Get_rank() < num_workers:",
"import numpy as np from mpi4py import MPI from parallel_pytorch.ops",
"== 0: x = torch.tensor([[0, 1], [4, 5]]) elif comm.Get_rank()",
"if world.Get_rank() < num_workers else 1, key=world.Get_rank()) if world.Get_rank() <",
"9], [12, 13]]) elif comm.Get_rank() == 3: x = torch.tensor([[10,",
"num_workers = np.array(worker_shape).prod() comm = MPI.COMM_WORLD.Split(color=0 if world.Get_rank() < num_workers",
"1] world = MPI.COMM_WORLD num_workers = np.array(worker_shape).prod() comm = MPI.COMM_WORLD.Split(color=0",
"x = tensor_merge(x, comm=comm, worker_shape=worker_shape) if comm.Get_rank() == 0: e",
"[12, 13, 14, 15], ]) assert torch.allclose(x, e), f'{x} !=",
"x_shape = [2, 2] worker_shape = [1, 1] world =",
"test_1(): worker_shape = [2, 2] world = MPI.COMM_WORLD num_workers =",
"x = tensor_merge(x, comm=comm, worker_shape=worker_shape) e = torch.tensor([[0, 1], [2,",
"import abort_on_exception @abort_on_exception def test_1(): worker_shape = [2, 2] world",
"x = torch.tensor([[8, 9], [12, 13]]) elif comm.Get_rank() == 3:",
"def test_2(): x_shape = [2, 2] worker_shape = [1, 1]",
"5, 6, 7], [8, 9, 10, 11], [12, 13, 14,",
"= np.array(x_shape).prod() x = torch.arange(volume).view(x_shape) x = tensor_merge(x, comm=comm, worker_shape=worker_shape)",
"world.Get_rank() < num_workers: if comm.Get_rank() == 0: x = torch.tensor([[0,",
"2] world = MPI.COMM_WORLD num_workers = np.array(worker_shape).prod() comm = MPI.COMM_WORLD.Split(color=0",
"MPI.COMM_WORLD num_workers = np.array(worker_shape).prod() comm = MPI.COMM_WORLD.Split(color=0 if world.Get_rank() <",
"15], ]) assert torch.allclose(x, e), f'{x} != {e}' @abort_on_exception def",
"[14, 15]]) x = tensor_merge(x, comm=comm, worker_shape=worker_shape) if comm.Get_rank() ==",
"1], [2, 3]]) assert torch.allclose(x, e), f'{x} != {e}' def",
"num_workers else 1, key=world.Get_rank()) if world.Get_rank() < num_workers: if comm.Get_rank()",
"torch.allclose(x, e), f'{x} != {e}' def run_all(): test_1() test_2() if",
"[2, 2] world = MPI.COMM_WORLD num_workers = np.array(worker_shape).prod() comm =",
"torch import numpy as np from mpi4py import MPI from",
"1: x = torch.tensor([[2, 3], [6, 7]]) elif comm.Get_rank() ==",
"1, key=world.Get_rank()) if world.Get_rank() < num_workers: volume = np.array(x_shape).prod() x",
"num_workers: if comm.Get_rank() == 0: x = torch.tensor([[0, 1], [4,",
"torch.tensor([[10, 11], [14, 15]]) x = tensor_merge(x, comm=comm, worker_shape=worker_shape) if",
"2: x = torch.tensor([[8, 9], [12, 13]]) elif comm.Get_rank() ==",
"= tensor_merge(x, comm=comm, worker_shape=worker_shape) if comm.Get_rank() == 0: e =",
"elif comm.Get_rank() == 2: x = torch.tensor([[8, 9], [12, 13]])",
"11], [14, 15]]) x = tensor_merge(x, comm=comm, worker_shape=worker_shape) if comm.Get_rank()",
"< num_workers: if comm.Get_rank() == 0: x = torch.tensor([[0, 1],",
"comm.Get_rank() == 3: x = torch.tensor([[10, 11], [14, 15]]) x",
"tensor_merge from parallel_pytorch.utils import abort_on_exception @abort_on_exception def test_1(): worker_shape =",
"< num_workers: volume = np.array(x_shape).prod() x = torch.arange(volume).view(x_shape) x =",
"< num_workers else 1, key=world.Get_rank()) if world.Get_rank() < num_workers: if",
"15]]) x = tensor_merge(x, comm=comm, worker_shape=worker_shape) if comm.Get_rank() == 0:",
"7], [8, 9, 10, 11], [12, 13, 14, 15], ])",
"@abort_on_exception def test_1(): worker_shape = [2, 2] world = MPI.COMM_WORLD",
"num_workers else 1, key=world.Get_rank()) if world.Get_rank() < num_workers: volume =",
"== 1: x = torch.tensor([[2, 3], [6, 7]]) elif comm.Get_rank()",
"{e}' def run_all(): test_1() test_2() if __name__ == '__main__': run_all()",
"test_2(): x_shape = [2, 2] worker_shape = [1, 1] world",
"numpy as np from mpi4py import MPI from parallel_pytorch.ops import",
"13]]) elif comm.Get_rank() == 3: x = torch.tensor([[10, 11], [14,",
"[1, 1] world = MPI.COMM_WORLD num_workers = np.array(worker_shape).prod() comm =",
"[2, 3]]) assert torch.allclose(x, e), f'{x} != {e}' def run_all():",
"worker_shape = [1, 1] world = MPI.COMM_WORLD num_workers = np.array(worker_shape).prod()",
"f'{x} != {e}' def run_all(): test_1() test_2() if __name__ ==",
"mpi4py import MPI from parallel_pytorch.ops import tensor_merge from parallel_pytorch.utils import",
"3], [6, 7]]) elif comm.Get_rank() == 2: x = torch.tensor([[8,",
"comm.Get_rank() == 0: e = torch.tensor([ [0, 1, 2, 3],",
"= MPI.COMM_WORLD.Split(color=0 if world.Get_rank() < num_workers else 1, key=world.Get_rank()) if",
"= torch.tensor([[2, 3], [6, 7]]) elif comm.Get_rank() == 2: x",
"torch.tensor([[8, 9], [12, 13]]) elif comm.Get_rank() == 3: x =",
"x = torch.tensor([[10, 11], [14, 15]]) x = tensor_merge(x, comm=comm,",
"10, 11], [12, 13, 14, 15], ]) assert torch.allclose(x, e),",
"np from mpi4py import MPI from parallel_pytorch.ops import tensor_merge from",
"3], [4, 5, 6, 7], [8, 9, 10, 11], [12,",
"comm=comm, worker_shape=worker_shape) if comm.Get_rank() == 0: e = torch.tensor([ [0,",
"worker_shape=worker_shape) e = torch.tensor([[0, 1], [2, 3]]) assert torch.allclose(x, e),",
"3]]) assert torch.allclose(x, e), f'{x} != {e}' def run_all(): test_1()",
"e = torch.tensor([ [0, 1, 2, 3], [4, 5, 6,",
"parallel_pytorch.utils import abort_on_exception @abort_on_exception def test_1(): worker_shape = [2, 2]",
"num_workers: volume = np.array(x_shape).prod() x = torch.arange(volume).view(x_shape) x = tensor_merge(x,",
"<filename>tests/test_merge.py import torch import numpy as np from mpi4py import",
"1, key=world.Get_rank()) if world.Get_rank() < num_workers: if comm.Get_rank() == 0:",
"13, 14, 15], ]) assert torch.allclose(x, e), f'{x} != {e}'",
"key=world.Get_rank()) if world.Get_rank() < num_workers: if comm.Get_rank() == 0: x",
"abort_on_exception @abort_on_exception def test_1(): worker_shape = [2, 2] world =",
"torch.allclose(x, e), f'{x} != {e}' @abort_on_exception def test_2(): x_shape =",
"[4, 5]]) elif comm.Get_rank() == 1: x = torch.tensor([[2, 3],",
"assert torch.allclose(x, e), f'{x} != {e}' def run_all(): test_1() test_2()",
"torch.tensor([[2, 3], [6, 7]]) elif comm.Get_rank() == 2: x =",
"as np from mpi4py import MPI from parallel_pytorch.ops import tensor_merge",
"comm.Get_rank() == 0: x = torch.tensor([[0, 1], [4, 5]]) elif",
"else 1, key=world.Get_rank()) if world.Get_rank() < num_workers: if comm.Get_rank() ==",
"2, 3], [4, 5, 6, 7], [8, 9, 10, 11],",
"0: e = torch.tensor([ [0, 1, 2, 3], [4, 5,",
"tensor_merge(x, comm=comm, worker_shape=worker_shape) if comm.Get_rank() == 0: e = torch.tensor([",
"11], [12, 13, 14, 15], ]) assert torch.allclose(x, e), f'{x}",
"world.Get_rank() < num_workers: volume = np.array(x_shape).prod() x = torch.arange(volume).view(x_shape) x",
"import tensor_merge from parallel_pytorch.utils import abort_on_exception @abort_on_exception def test_1(): worker_shape",
"14, 15], ]) assert torch.allclose(x, e), f'{x} != {e}' @abort_on_exception",
"[6, 7]]) elif comm.Get_rank() == 2: x = torch.tensor([[8, 9],",
"f'{x} != {e}' @abort_on_exception def test_2(): x_shape = [2, 2]",
"torch.tensor([[0, 1], [2, 3]]) assert torch.allclose(x, e), f'{x} != {e}'",
"assert torch.allclose(x, e), f'{x} != {e}' @abort_on_exception def test_2(): x_shape",
"[2, 2] worker_shape = [1, 1] world = MPI.COMM_WORLD num_workers",
"= torch.tensor([[0, 1], [2, 3]]) assert torch.allclose(x, e), f'{x} !=",
"if comm.Get_rank() == 0: e = torch.tensor([ [0, 1, 2,",
"[8, 9, 10, 11], [12, 13, 14, 15], ]) assert",
"9, 10, 11], [12, 13, 14, 15], ]) assert torch.allclose(x,",
"torch.arange(volume).view(x_shape) x = tensor_merge(x, comm=comm, worker_shape=worker_shape) e = torch.tensor([[0, 1],",
"7]]) elif comm.Get_rank() == 2: x = torch.tensor([[8, 9], [12,",
"if world.Get_rank() < num_workers: if comm.Get_rank() == 0: x =",
"elif comm.Get_rank() == 1: x = torch.tensor([[2, 3], [6, 7]])",
"from mpi4py import MPI from parallel_pytorch.ops import tensor_merge from parallel_pytorch.utils",
"== 3: x = torch.tensor([[10, 11], [14, 15]]) x =",
"elif comm.Get_rank() == 3: x = torch.tensor([[10, 11], [14, 15]])",
"= np.array(worker_shape).prod() comm = MPI.COMM_WORLD.Split(color=0 if world.Get_rank() < num_workers else",
"= MPI.COMM_WORLD num_workers = np.array(worker_shape).prod() comm = MPI.COMM_WORLD.Split(color=0 if world.Get_rank()",
"6, 7], [8, 9, 10, 11], [12, 13, 14, 15],",
"x = torch.tensor([[0, 1], [4, 5]]) elif comm.Get_rank() == 1:",
"= tensor_merge(x, comm=comm, worker_shape=worker_shape) e = torch.tensor([[0, 1], [2, 3]])",
"tensor_merge(x, comm=comm, worker_shape=worker_shape) e = torch.tensor([[0, 1], [2, 3]]) assert",
"x = torch.arange(volume).view(x_shape) x = tensor_merge(x, comm=comm, worker_shape=worker_shape) e =",
"= torch.arange(volume).view(x_shape) x = tensor_merge(x, comm=comm, worker_shape=worker_shape) e = torch.tensor([[0,",
"comm = MPI.COMM_WORLD.Split(color=0 if world.Get_rank() < num_workers else 1, key=world.Get_rank())",
"volume = np.array(x_shape).prod() x = torch.arange(volume).view(x_shape) x = tensor_merge(x, comm=comm,",
"if comm.Get_rank() == 0: x = torch.tensor([[0, 1], [4, 5]])",
"= [1, 1] world = MPI.COMM_WORLD num_workers = np.array(worker_shape).prod() comm",
"import MPI from parallel_pytorch.ops import tensor_merge from parallel_pytorch.utils import abort_on_exception",
"= torch.tensor([[8, 9], [12, 13]]) elif comm.Get_rank() == 3: x",
"[12, 13]]) elif comm.Get_rank() == 3: x = torch.tensor([[10, 11],",
"MPI from parallel_pytorch.ops import tensor_merge from parallel_pytorch.utils import abort_on_exception @abort_on_exception",
"def test_1(): worker_shape = [2, 2] world = MPI.COMM_WORLD num_workers",
"np.array(worker_shape).prod() comm = MPI.COMM_WORLD.Split(color=0 if world.Get_rank() < num_workers else 1,",
"= torch.tensor([[10, 11], [14, 15]]) x = tensor_merge(x, comm=comm, worker_shape=worker_shape)",
"== 0: e = torch.tensor([ [0, 1, 2, 3], [4,",
"{e}' @abort_on_exception def test_2(): x_shape = [2, 2] worker_shape =",
"[0, 1, 2, 3], [4, 5, 6, 7], [8, 9,",
"comm.Get_rank() == 2: x = torch.tensor([[8, 9], [12, 13]]) elif",
"e), f'{x} != {e}' @abort_on_exception def test_2(): x_shape = [2,",
"2] worker_shape = [1, 1] world = MPI.COMM_WORLD num_workers =",
"worker_shape = [2, 2] world = MPI.COMM_WORLD num_workers = np.array(worker_shape).prod()",
"!= {e}' @abort_on_exception def test_2(): x_shape = [2, 2] worker_shape",
"comm=comm, worker_shape=worker_shape) e = torch.tensor([[0, 1], [2, 3]]) assert torch.allclose(x,",
"1], [4, 5]]) elif comm.Get_rank() == 1: x = torch.tensor([[2,",
"parallel_pytorch.ops import tensor_merge from parallel_pytorch.utils import abort_on_exception @abort_on_exception def test_1():",
"e = torch.tensor([[0, 1], [2, 3]]) assert torch.allclose(x, e), f'{x}",
"from parallel_pytorch.utils import abort_on_exception @abort_on_exception def test_1(): worker_shape = [2,",
"0: x = torch.tensor([[0, 1], [4, 5]]) elif comm.Get_rank() ==",
"5]]) elif comm.Get_rank() == 1: x = torch.tensor([[2, 3], [6,",
"from parallel_pytorch.ops import tensor_merge from parallel_pytorch.utils import abort_on_exception @abort_on_exception def",
"!= {e}' def run_all(): test_1() test_2() if __name__ == '__main__':",
"import torch import numpy as np from mpi4py import MPI",
"x = torch.tensor([[2, 3], [6, 7]]) elif comm.Get_rank() == 2:",
"e), f'{x} != {e}' def run_all(): test_1() test_2() if __name__",
"== 2: x = torch.tensor([[8, 9], [12, 13]]) elif comm.Get_rank()",
"comm.Get_rank() == 1: x = torch.tensor([[2, 3], [6, 7]]) elif",
"]) assert torch.allclose(x, e), f'{x} != {e}' @abort_on_exception def test_2():",
"@abort_on_exception def test_2(): x_shape = [2, 2] worker_shape = [1,",
"< num_workers else 1, key=world.Get_rank()) if world.Get_rank() < num_workers: volume",
"1, 2, 3], [4, 5, 6, 7], [8, 9, 10,",
"MPI.COMM_WORLD.Split(color=0 if world.Get_rank() < num_workers else 1, key=world.Get_rank()) if world.Get_rank()",
"= [2, 2] worker_shape = [1, 1] world = MPI.COMM_WORLD",
"if world.Get_rank() < num_workers: volume = np.array(x_shape).prod() x = torch.arange(volume).view(x_shape)",
"3: x = torch.tensor([[10, 11], [14, 15]]) x = tensor_merge(x,"
] |
[
"1)} for pos in costs.keys(): for crab in positions: distance",
"((distance * distance) + distance) // 2 print(f\"Day 07: {min(costs.values())}\")",
"[int(x) for x in infile.readline().strip().split(',')] min_x = min(positions) max_x =",
"positions = [int(x) for x in infile.readline().strip().split(',')] min_x = min(positions)",
"max_x + 1)} for pos in costs.keys(): for crab in",
"as infile: positions = [int(x) for x in infile.readline().strip().split(',')] min_x",
"{x: 0 for x in range(min_x, max_x + 1)} for",
"\"\"\"Day 07\"\"\" def process(filename): with open(filename) as infile: positions =",
"x in range(min_x, max_x + 1)} for pos in costs.keys():",
"+ 1)} for pos in costs.keys(): for crab in positions:",
"range(min_x, max_x + 1)} for pos in costs.keys(): for crab",
"x in infile.readline().strip().split(',')] min_x = min(positions) max_x = max(positions) costs",
"in range(min_x, max_x + 1)} for pos in costs.keys(): for",
"costs[pos] += ((distance * distance) + distance) // 2 print(f\"Day",
"= min(positions) max_x = max(positions) costs = {x: 0 for",
"+ distance) // 2 print(f\"Day 07: {min(costs.values())}\") if __name__ ==",
"= abs(pos - crab) costs[pos] += ((distance * distance) +",
"for crab in positions: distance = abs(pos - crab) costs[pos]",
"max(positions) costs = {x: 0 for x in range(min_x, max_x",
"crab) costs[pos] += ((distance * distance) + distance) // 2",
"* distance) + distance) // 2 print(f\"Day 07: {min(costs.values())}\") if",
"process(filename): with open(filename) as infile: positions = [int(x) for x",
"min_x = min(positions) max_x = max(positions) costs = {x: 0",
"costs = {x: 0 for x in range(min_x, max_x +",
"open(filename) as infile: positions = [int(x) for x in infile.readline().strip().split(',')]",
"for pos in costs.keys(): for crab in positions: distance =",
"costs.keys(): for crab in positions: distance = abs(pos - crab)",
"- crab) costs[pos] += ((distance * distance) + distance) //",
"positions: distance = abs(pos - crab) costs[pos] += ((distance *",
"distance) // 2 print(f\"Day 07: {min(costs.values())}\") if __name__ == '__main__':",
"= {x: 0 for x in range(min_x, max_x + 1)}",
"= max(positions) costs = {x: 0 for x in range(min_x,",
"// 2 print(f\"Day 07: {min(costs.values())}\") if __name__ == '__main__': process('test.txt')",
"0 for x in range(min_x, max_x + 1)} for pos",
"in costs.keys(): for crab in positions: distance = abs(pos -",
"pos in costs.keys(): for crab in positions: distance = abs(pos",
"<filename>day07/main.py \"\"\"Day 07\"\"\" def process(filename): with open(filename) as infile: positions",
"abs(pos - crab) costs[pos] += ((distance * distance) + distance)",
"with open(filename) as infile: positions = [int(x) for x in",
"def process(filename): with open(filename) as infile: positions = [int(x) for",
"min(positions) max_x = max(positions) costs = {x: 0 for x",
"infile.readline().strip().split(',')] min_x = min(positions) max_x = max(positions) costs = {x:",
"distance = abs(pos - crab) costs[pos] += ((distance * distance)",
"07\"\"\" def process(filename): with open(filename) as infile: positions = [int(x)",
"max_x = max(positions) costs = {x: 0 for x in",
"crab in positions: distance = abs(pos - crab) costs[pos] +=",
"in positions: distance = abs(pos - crab) costs[pos] += ((distance",
"infile: positions = [int(x) for x in infile.readline().strip().split(',')] min_x =",
"+= ((distance * distance) + distance) // 2 print(f\"Day 07:",
"distance) + distance) // 2 print(f\"Day 07: {min(costs.values())}\") if __name__",
"= [int(x) for x in infile.readline().strip().split(',')] min_x = min(positions) max_x",
"2 print(f\"Day 07: {min(costs.values())}\") if __name__ == '__main__': process('test.txt') process('input.txt')",
"for x in infile.readline().strip().split(',')] min_x = min(positions) max_x = max(positions)",
"in infile.readline().strip().split(',')] min_x = min(positions) max_x = max(positions) costs =",
"for x in range(min_x, max_x + 1)} for pos in"
] |
[
"re def int2ordinal(n): # partially based on https://stackoverflow.com/questions/9647202/ordinal-numbers-replacement if (type(n)",
"[idx] idx = [n for n in idx if n",
"safe filter such that if one of the idx is",
"if one of the idx is not found, they are",
"= [idx] idx = [n for n in idx if",
"re.findall('[^,\\()]*\\s(\\([^,]*\\)\\s)*\\[([^,]*)\\]',x) if firstOnly: return [n[1] for n in r][0] else:",
"def int2ordinal(n): # partially based on https://stackoverflow.com/questions/9647202/ordinal-numbers-replacement if (type(n) is",
"n = int(n) return \"%d%s\"%(n,{1:\"st\",2:\"nd\",3:\"rd\"}.get(n if n<20 else n%10,\"th\")) else:",
"if type(idx) is not list: idx = [idx] idx =",
"one of the idx is not found, they are ignored",
"list: idx = [idx] idx = [n for n in",
"r] def pd_filter(df, idx): # filters a pandas data frame,",
"the idx is not found, they are ignored if idx",
"return '' r = re.findall('[^,\\()]*\\s(\\([^,]*\\)\\s)*\\[([^,]*)\\]',x) if firstOnly: return [n[1] for",
"filters a pandas data frame, given idx # this is",
"if(pd.isnull(x)): return '' r = re.findall('[^,\\()]*\\s(\\([^,]*\\)\\s)*\\[([^,]*)\\]',x) if firstOnly: return [n[1]",
"# -*- coding: utf-8 -*- \"\"\" utilities @author: boyangzhao \"\"\"",
"utilities @author: boyangzhao \"\"\" import pandas as pd import re",
"n def getFeatGene(x, firstOnly = False): # get gene if",
"import pandas as pd import re def int2ordinal(n): # partially",
"in r] def pd_filter(df, idx): # filters a pandas data",
"coding: utf-8 -*- \"\"\" utilities @author: boyangzhao \"\"\" import pandas",
"False): # get gene if pd.isnull(x): return '' r =",
"is a safe filter such that if one of the",
"else n%10,\"th\")) else: return n def getFeatGene(x, firstOnly = False):",
"that if one of the idx is not found, they",
"firstOnly = False): # get the data source if(pd.isnull(x)): return",
"r][0] else: return [n[1] for n in r] def pd_filter(df,",
"ignored if idx is None: return df if type(idx) is",
"firstOnly: return r[0][0] else: return [n[0] for n in r]",
"if firstOnly: return r[0][0] else: return [n[0] for n in",
"pandas as pd import re def int2ordinal(n): # partially based",
"partially based on https://stackoverflow.com/questions/9647202/ordinal-numbers-replacement if (type(n) is int) or n.isdigit():",
"# get gene if pd.isnull(x): return '' r = re.findall('([^,\\()]*)\\s(\\(([^,]*)\\)\\s)*\\[([^,]*)\\]',x)",
"r[0][0] else: return [n[0] for n in r] def getFeatSource(x,",
"# this is a safe filter such that if one",
"int) or n.isdigit(): if type(n) is not int: n =",
"n in r][0] else: return [n[1] for n in r]",
"the data source if(pd.isnull(x)): return '' r = re.findall('[^,\\()]*\\s(\\([^,]*\\)\\s)*\\[([^,]*)\\]',x) if",
"None: return df if type(idx) is not list: idx =",
"n.isdigit(): if type(n) is not int: n = int(n) return",
"not found, they are ignored if idx is None: return",
"for n in r] def getFeatSource(x, firstOnly = False): #",
"n%10,\"th\")) else: return n def getFeatGene(x, firstOnly = False): #",
"firstOnly = False): # get gene if pd.isnull(x): return ''",
"idx is None: return df if type(idx) is not list:",
"firstOnly: return [n[1] for n in r][0] else: return [n[1]",
"found, they are ignored if idx is None: return df",
"if type(n) is not int: n = int(n) return \"%d%s\"%(n,{1:\"st\",2:\"nd\",3:\"rd\"}.get(n",
"idx = [n for n in idx if n in",
"based on https://stackoverflow.com/questions/9647202/ordinal-numbers-replacement if (type(n) is int) or n.isdigit(): if",
"return [n[1] for n in r][0] else: return [n[1] for",
"re.findall('([^,\\()]*)\\s(\\(([^,]*)\\)\\s)*\\[([^,]*)\\]',x) if firstOnly: return r[0][0] else: return [n[0] for n",
"# get the data source if(pd.isnull(x)): return '' r =",
"int: n = int(n) return \"%d%s\"%(n,{1:\"st\",2:\"nd\",3:\"rd\"}.get(n if n<20 else n%10,\"th\"))",
"n in idx if n in df.index] return df.loc[idx, :]",
"pd import re def int2ordinal(n): # partially based on https://stackoverflow.com/questions/9647202/ordinal-numbers-replacement",
"this is a safe filter such that if one of",
"= int(n) return \"%d%s\"%(n,{1:\"st\",2:\"nd\",3:\"rd\"}.get(n if n<20 else n%10,\"th\")) else: return",
"df if type(idx) is not list: idx = [idx] idx",
"utf-8 -*- \"\"\" utilities @author: boyangzhao \"\"\" import pandas as",
"\"\"\" import pandas as pd import re def int2ordinal(n): #",
"def getFeatGene(x, firstOnly = False): # get gene if pd.isnull(x):",
"given idx # this is a safe filter such that",
"filter such that if one of the idx is not",
"# filters a pandas data frame, given idx # this",
"are ignored if idx is None: return df if type(idx)",
"\"\"\" utilities @author: boyangzhao \"\"\" import pandas as pd import",
"not list: idx = [idx] idx = [n for n",
"def pd_filter(df, idx): # filters a pandas data frame, given",
"<filename>src/ceres_infer/utils.py<gh_stars>0 #!/usr/bin/env python3 # -*- coding: utf-8 -*- \"\"\" utilities",
"of the idx is not found, they are ignored if",
"return [n[1] for n in r] def pd_filter(df, idx): #",
"if pd.isnull(x): return '' r = re.findall('([^,\\()]*)\\s(\\(([^,]*)\\)\\s)*\\[([^,]*)\\]',x) if firstOnly: return",
"[n for n in idx if n in df.index] return",
"'' r = re.findall('([^,\\()]*)\\s(\\(([^,]*)\\)\\s)*\\[([^,]*)\\]',x) if firstOnly: return r[0][0] else: return",
"such that if one of the idx is not found,",
"is not list: idx = [idx] idx = [n for",
"if idx is None: return df if type(idx) is not",
"getFeatGene(x, firstOnly = False): # get gene if pd.isnull(x): return",
"gene if pd.isnull(x): return '' r = re.findall('([^,\\()]*)\\s(\\(([^,]*)\\)\\s)*\\[([^,]*)\\]',x) if firstOnly:",
"r] def getFeatSource(x, firstOnly = False): # get the data",
"python3 # -*- coding: utf-8 -*- \"\"\" utilities @author: boyangzhao",
"[n[1] for n in r][0] else: return [n[1] for n",
"source if(pd.isnull(x)): return '' r = re.findall('[^,\\()]*\\s(\\([^,]*\\)\\s)*\\[([^,]*)\\]',x) if firstOnly: return",
"\"%d%s\"%(n,{1:\"st\",2:\"nd\",3:\"rd\"}.get(n if n<20 else n%10,\"th\")) else: return n def getFeatGene(x,",
"else: return [n[1] for n in r] def pd_filter(df, idx):",
"on https://stackoverflow.com/questions/9647202/ordinal-numbers-replacement if (type(n) is int) or n.isdigit(): if type(n)",
"False): # get the data source if(pd.isnull(x)): return '' r",
"is not int: n = int(n) return \"%d%s\"%(n,{1:\"st\",2:\"nd\",3:\"rd\"}.get(n if n<20",
"frame, given idx # this is a safe filter such",
"for n in r] def pd_filter(df, idx): # filters a",
"they are ignored if idx is None: return df if",
"return r[0][0] else: return [n[0] for n in r] def",
"else: return n def getFeatGene(x, firstOnly = False): # get",
"idx): # filters a pandas data frame, given idx #",
"idx = [idx] idx = [n for n in idx",
"r = re.findall('[^,\\()]*\\s(\\([^,]*\\)\\s)*\\[([^,]*)\\]',x) if firstOnly: return [n[1] for n in",
"-*- coding: utf-8 -*- \"\"\" utilities @author: boyangzhao \"\"\" import",
"n in r] def pd_filter(df, idx): # filters a pandas",
"(type(n) is int) or n.isdigit(): if type(n) is not int:",
"n in r] def getFeatSource(x, firstOnly = False): # get",
"boyangzhao \"\"\" import pandas as pd import re def int2ordinal(n):",
"return \"%d%s\"%(n,{1:\"st\",2:\"nd\",3:\"rd\"}.get(n if n<20 else n%10,\"th\")) else: return n def",
"pd.isnull(x): return '' r = re.findall('([^,\\()]*)\\s(\\(([^,]*)\\)\\s)*\\[([^,]*)\\]',x) if firstOnly: return r[0][0]",
"[n[0] for n in r] def getFeatSource(x, firstOnly = False):",
"a pandas data frame, given idx # this is a",
"is None: return df if type(idx) is not list: idx",
"return '' r = re.findall('([^,\\()]*)\\s(\\(([^,]*)\\)\\s)*\\[([^,]*)\\]',x) if firstOnly: return r[0][0] else:",
"data frame, given idx # this is a safe filter",
"not int: n = int(n) return \"%d%s\"%(n,{1:\"st\",2:\"nd\",3:\"rd\"}.get(n if n<20 else",
"return [n[0] for n in r] def getFeatSource(x, firstOnly =",
"type(idx) is not list: idx = [idx] idx = [n",
"idx # this is a safe filter such that if",
"= re.findall('[^,\\()]*\\s(\\([^,]*\\)\\s)*\\[([^,]*)\\]',x) if firstOnly: return [n[1] for n in r][0]",
"# partially based on https://stackoverflow.com/questions/9647202/ordinal-numbers-replacement if (type(n) is int) or",
"= False): # get the data source if(pd.isnull(x)): return ''",
"for n in r][0] else: return [n[1] for n in",
"get the data source if(pd.isnull(x)): return '' r = re.findall('[^,\\()]*\\s(\\([^,]*\\)\\s)*\\[([^,]*)\\]',x)",
"if firstOnly: return [n[1] for n in r][0] else: return",
"if (type(n) is int) or n.isdigit(): if type(n) is not",
"int(n) return \"%d%s\"%(n,{1:\"st\",2:\"nd\",3:\"rd\"}.get(n if n<20 else n%10,\"th\")) else: return n",
"return df if type(idx) is not list: idx = [idx]",
"import re def int2ordinal(n): # partially based on https://stackoverflow.com/questions/9647202/ordinal-numbers-replacement if",
"int2ordinal(n): # partially based on https://stackoverflow.com/questions/9647202/ordinal-numbers-replacement if (type(n) is int)",
"type(n) is not int: n = int(n) return \"%d%s\"%(n,{1:\"st\",2:\"nd\",3:\"rd\"}.get(n if",
"-*- \"\"\" utilities @author: boyangzhao \"\"\" import pandas as pd",
"@author: boyangzhao \"\"\" import pandas as pd import re def",
"'' r = re.findall('[^,\\()]*\\s(\\([^,]*\\)\\s)*\\[([^,]*)\\]',x) if firstOnly: return [n[1] for n",
"is int) or n.isdigit(): if type(n) is not int: n",
"#!/usr/bin/env python3 # -*- coding: utf-8 -*- \"\"\" utilities @author:",
"= False): # get gene if pd.isnull(x): return '' r",
"= re.findall('([^,\\()]*)\\s(\\(([^,]*)\\)\\s)*\\[([^,]*)\\]',x) if firstOnly: return r[0][0] else: return [n[0] for",
"in r] def getFeatSource(x, firstOnly = False): # get the",
"else: return [n[0] for n in r] def getFeatSource(x, firstOnly",
"or n.isdigit(): if type(n) is not int: n = int(n)",
"data source if(pd.isnull(x)): return '' r = re.findall('[^,\\()]*\\s(\\([^,]*\\)\\s)*\\[([^,]*)\\]',x) if firstOnly:",
"get gene if pd.isnull(x): return '' r = re.findall('([^,\\()]*)\\s(\\(([^,]*)\\)\\s)*\\[([^,]*)\\]',x) if",
"a safe filter such that if one of the idx",
"idx is not found, they are ignored if idx is",
"https://stackoverflow.com/questions/9647202/ordinal-numbers-replacement if (type(n) is int) or n.isdigit(): if type(n) is",
"getFeatSource(x, firstOnly = False): # get the data source if(pd.isnull(x)):",
"return n def getFeatGene(x, firstOnly = False): # get gene",
"is not found, they are ignored if idx is None:",
"def getFeatSource(x, firstOnly = False): # get the data source",
"in r][0] else: return [n[1] for n in r] def",
"as pd import re def int2ordinal(n): # partially based on",
"= [n for n in idx if n in df.index]",
"for n in idx if n in df.index] return df.loc[idx,",
"[n[1] for n in r] def pd_filter(df, idx): # filters",
"pandas data frame, given idx # this is a safe",
"if n<20 else n%10,\"th\")) else: return n def getFeatGene(x, firstOnly",
"pd_filter(df, idx): # filters a pandas data frame, given idx",
"n<20 else n%10,\"th\")) else: return n def getFeatGene(x, firstOnly =",
"r = re.findall('([^,\\()]*)\\s(\\(([^,]*)\\)\\s)*\\[([^,]*)\\]',x) if firstOnly: return r[0][0] else: return [n[0]"
] |
[
"gameObjs.UpDownButton OptionsScreen_RandomWindowTitle = gameObjs.UpDownButton OptionsScreen_NumberFormatting = gameObjs.UpDownButton ElementsX = 0",
"OptionsScreen_NumberFormatting global ElementsX global ElementsY if OptionsScreen_DebugModeEnabled .ButtonState == 2",
"if not current_val: gameMain.DefaultCnt.Write_RegKey(\"/OPTIONS/format_numbers\", \"True\") OptionsScreen_DebugModeEnabled.Set_X(ElementsX + 20) OptionsScreen_RandomWindowTitle.Set_X(ElementsX +",
"2.0 (the \"License\"); # you may not use this file",
"+ 52, gameMain.DefaultCnt.Get_RegKey(\"/OPTIONS/font_aa\")) # -- Random Title -- # gameMain.DefaultCnt.FontRender(DISPLAY,",
"gameMain.DefaultCnt.Get_RegKey(\"/strings/settings/number_formatting\") + str(gameMain.DefaultCnt.Get_RegKey(\"/OPTIONS/format_numbers\")), (240, 240, 240), ElementsX + 95, ElementsY",
"current_val: gameMain.DefaultCnt.Write_RegKey(\"/OPTIONS/debug_enabled\", \"True\") if OptionsScreen_RandomWindowTitle .ButtonState == 2 or OptionsScreen_RandomWindowTitle.ButtonState",
"OptionsScreen_NumberFormatting.ButtonState == 1: current_val = gameMain.DefaultCnt.Get_RegKey(\"/OPTIONS/format_numbers\", bool) if current_val: gameMain.DefaultCnt.Write_RegKey(\"/OPTIONS/format_numbers\",",
"\"/PressStart2P.ttf\", 14, gameMain.DefaultCnt.Get_RegKey(\"/strings/settings/random_title\") + str(gameMain.DefaultCnt.Get_RegKey(\"/OPTIONS/random_title\")), (240, 240, 240), ElementsX +",
"as gameMain import pygame, sys import importlib import time from",
"of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless",
"from ENGINE import APPDATA as reg from ENGINE import UTILS",
"limitations under the License. # # # -- Imports --",
"import MAIN as gameMain import pygame, sys import importlib import",
"# from ENGINE import APPDATA as reg from ENGINE import",
"use this file except in compliance with the License. #",
"if current_val: gameMain.DefaultCnt.Write_RegKey(\"/OPTIONS/debug_enabled\", \"False\") if not current_val: gameMain.DefaultCnt.Write_RegKey(\"/OPTIONS/debug_enabled\", \"True\") if",
"def EventUpdate(event): global OptionsScreen_DebugModeEnabled global OptionsScreen_RandomWindowTitle global OptionsScreen_NumberFormatting OptionsScreen_DebugModeEnabled.Update(event) OptionsScreen_RandomWindowTitle.Update(event)",
"-- # gameMain.DefaultCnt.FontRender(DISPLAY, \"/PressStart2P.ttf\", 14, gameMain.DefaultCnt.Get_RegKey(\"/strings/settings/debug_mode\") + str(gameMain.DefaultCnt.Get_RegKey(\"/OPTIONS/debug_enabled\")), (240, 240,",
"import pygame, sys import importlib import time from random import",
"the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required",
"gameObjs.UpDownButton(0,0,14) def Update(): global OptionsScreen_DebugModeEnabled global OptionsScreen_RandomWindowTitle global OptionsScreen_NumberFormatting global",
"License. # You may obtain a copy of the License",
"OptionsScreen_DebugModeEnabled.Render(DISPLAY) OptionsScreen_RandomWindowTitle.Render(DISPLAY) OptionsScreen_NumberFormatting.Render(DISPLAY) # -- Debug Mode -- # gameMain.DefaultCnt.FontRender(DISPLAY,",
"gameMain.DefaultCnt.Get_RegKey(\"/strings/settings/debug_mode\") + str(gameMain.DefaultCnt.Get_RegKey(\"/OPTIONS/debug_enabled\")), (240, 240, 240), ElementsX + 95, ElementsY",
"102, gameMain.DefaultCnt.Get_RegKey(\"/OPTIONS/font_aa\")) def EventUpdate(event): global OptionsScreen_DebugModeEnabled global OptionsScreen_RandomWindowTitle global OptionsScreen_NumberFormatting",
"under the License is distributed on an \"AS IS\" BASIS,",
"License for the specific language governing permissions and # limitations",
"= gameObjs.UpDownButton(0,0,14) def Update(): global OptionsScreen_DebugModeEnabled global OptionsScreen_RandomWindowTitle global OptionsScreen_NumberFormatting",
"240, 240), ElementsX + 95, ElementsY + 102, gameMain.DefaultCnt.Get_RegKey(\"/OPTIONS/font_aa\")) def",
"OptionsScreen_DebugModeEnabled global OptionsScreen_RandomWindowTitle global OptionsScreen_NumberFormatting global ElementsX global ElementsY if",
"gameMain import pygame, sys import importlib import time from random",
"\"/PressStart2P.ttf\", 14, gameMain.DefaultCnt.Get_RegKey(\"/strings/settings/number_formatting\") + str(gameMain.DefaultCnt.Get_RegKey(\"/OPTIONS/format_numbers\")), (240, 240, 240), ElementsX +",
"global ElementsX global ElementsY if OptionsScreen_DebugModeEnabled .ButtonState == 2 or",
"= gameMain.DefaultCnt.Get_RegKey(\"/OPTIONS/format_numbers\", bool) if current_val: gameMain.DefaultCnt.Write_RegKey(\"/OPTIONS/format_numbers\", \"False\") if not current_val:",
"== 1: current_val = gameMain.DefaultCnt.Get_RegKey(\"/OPTIONS/debug_enabled\", bool) if current_val: gameMain.DefaultCnt.Write_RegKey(\"/OPTIONS/debug_enabled\", \"False\")",
"gameMain.DefaultCnt.Write_RegKey(\"/OPTIONS/random_title\", \"True\") if OptionsScreen_NumberFormatting .ButtonState == 2 or OptionsScreen_NumberFormatting.ButtonState ==",
"OptionsScreen_RandomWindowTitle global OptionsScreen_NumberFormatting OptionsScreen_DebugModeEnabled = gameObjs.UpDownButton(0,0,14) OptionsScreen_RandomWindowTitle = gameObjs.UpDownButton(0,0,14) OptionsScreen_NumberFormatting",
"14, gameMain.DefaultCnt.Get_RegKey(\"/strings/settings/debug_mode\") + str(gameMain.DefaultCnt.Get_RegKey(\"/OPTIONS/debug_enabled\")), (240, 240, 240), ElementsX + 95,",
"OptionsScreen_DebugModeEnabled .ButtonState == 2 or OptionsScreen_DebugModeEnabled.ButtonState == 1: current_val =",
"in compliance with the License. # You may obtain a",
"14, gameMain.DefaultCnt.Get_RegKey(\"/strings/settings/number_formatting\") + str(gameMain.DefaultCnt.Get_RegKey(\"/OPTIONS/format_numbers\")), (240, 240, 240), ElementsX + 95,",
"software # distributed under the License is distributed on an",
"95, ElementsY + 102, gameMain.DefaultCnt.Get_RegKey(\"/OPTIONS/font_aa\")) def EventUpdate(event): global OptionsScreen_DebugModeEnabled global",
"ENGINE as tge from Fogoso.MAIN import ClassesUtils as gameObjs from",
"+ 75) OptionsScreen_NumberFormatting.Set_Y(ElementsY + 100) def Render(DISPLAY): global OptionsScreen_DebugModeEnabled global",
"50) OptionsScreen_RandomWindowTitle.Set_Y(ElementsY + 75) OptionsScreen_NumberFormatting.Set_Y(ElementsY + 100) def Render(DISPLAY): global",
"# gameMain.DefaultCnt.FontRender(DISPLAY, \"/PressStart2P.ttf\", 14, gameMain.DefaultCnt.Get_RegKey(\"/strings/settings/debug_mode\") + str(gameMain.DefaultCnt.Get_RegKey(\"/OPTIONS/debug_enabled\")), (240, 240, 240),",
"ClassesUtils as gameObjs from Fogoso import MAIN as gameMain import",
"MAIN as gameMain import pygame, sys import importlib import time",
"Random Title -- # gameMain.DefaultCnt.FontRender(DISPLAY, \"/PressStart2P.ttf\", 14, gameMain.DefaultCnt.Get_RegKey(\"/strings/settings/random_title\") + str(gameMain.DefaultCnt.Get_RegKey(\"/OPTIONS/random_title\")),",
"gameObjs.UpDownButton(0,0,14) OptionsScreen_NumberFormatting = gameObjs.UpDownButton(0,0,14) def Update(): global OptionsScreen_DebugModeEnabled global OptionsScreen_RandomWindowTitle",
"\"False\") if not current_val: gameMain.DefaultCnt.Write_RegKey(\"/OPTIONS/format_numbers\", \"True\") OptionsScreen_DebugModeEnabled.Set_X(ElementsX + 20) OptionsScreen_RandomWindowTitle.Set_X(ElementsX",
"ENGINE import UTILS as utils import ENGINE as tge from",
"== 2 or OptionsScreen_NumberFormatting.ButtonState == 1: current_val = gameMain.DefaultCnt.Get_RegKey(\"/OPTIONS/format_numbers\", bool)",
"EventUpdate(event): global OptionsScreen_DebugModeEnabled global OptionsScreen_RandomWindowTitle global OptionsScreen_NumberFormatting OptionsScreen_DebugModeEnabled.Update(event) OptionsScreen_RandomWindowTitle.Update(event) OptionsScreen_NumberFormatting.Update(event)",
"current_val: gameMain.DefaultCnt.Write_RegKey(\"/OPTIONS/debug_enabled\", \"False\") if not current_val: gameMain.DefaultCnt.Write_RegKey(\"/OPTIONS/debug_enabled\", \"True\") if OptionsScreen_RandomWindowTitle",
"gameMain.DefaultCnt.Write_RegKey(\"/OPTIONS/random_title\", \"False\") if not current_val: gameMain.DefaultCnt.Write_RegKey(\"/OPTIONS/random_title\", \"True\") if OptionsScreen_NumberFormatting .ButtonState",
"20) OptionsScreen_DebugModeEnabled.Set_Y(ElementsY + 50) OptionsScreen_RandomWindowTitle.Set_Y(ElementsY + 75) OptionsScreen_NumberFormatting.Set_Y(ElementsY + 100)",
"+ str(gameMain.DefaultCnt.Get_RegKey(\"/OPTIONS/format_numbers\")), (240, 240, 240), ElementsX + 95, ElementsY +",
"0 def Initialize(): global OptionsScreen_DebugModeEnabled global OptionsScreen_RandomWindowTitle global OptionsScreen_NumberFormatting OptionsScreen_DebugModeEnabled",
"100) def Render(DISPLAY): global OptionsScreen_DebugModeEnabled global OptionsScreen_RandomWindowTitle global OptionsScreen_NumberFormatting OptionsScreen_DebugModeEnabled.Render(DISPLAY)",
"OF ANY KIND, either express or implied. # See the",
"WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.",
"ANY KIND, either express or implied. # See the License",
"See the License for the specific language governing permissions and",
".ButtonState == 2 or OptionsScreen_RandomWindowTitle.ButtonState == 1: current_val = gameMain.DefaultCnt.Get_RegKey(\"/OPTIONS/random_title\",",
"the License. # You may obtain a copy of the",
"at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable",
"for the specific language governing permissions and # limitations under",
"to in writing, software # distributed under the License is",
"Render(DISPLAY): global OptionsScreen_DebugModeEnabled global OptionsScreen_RandomWindowTitle global OptionsScreen_NumberFormatting OptionsScreen_DebugModeEnabled.Render(DISPLAY) OptionsScreen_RandomWindowTitle.Render(DISPLAY) OptionsScreen_NumberFormatting.Render(DISPLAY)",
"# See the License for the specific language governing permissions",
"OptionsScreen_RandomWindowTitle .ButtonState == 2 or OptionsScreen_RandomWindowTitle.ButtonState == 1: current_val =",
"language governing permissions and # limitations under the License. #",
"or agreed to in writing, software # distributed under the",
"required by applicable law or agreed to in writing, software",
"bool) if current_val: gameMain.DefaultCnt.Write_RegKey(\"/OPTIONS/format_numbers\", \"False\") if not current_val: gameMain.DefaultCnt.Write_RegKey(\"/OPTIONS/format_numbers\", \"True\")",
"14, gameMain.DefaultCnt.Get_RegKey(\"/strings/settings/random_title\") + str(gameMain.DefaultCnt.Get_RegKey(\"/OPTIONS/random_title\")), (240, 240, 240), ElementsX + 95,",
"BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either",
"with the License. # You may obtain a copy of",
"from Fogoso.MAIN import ClassesUtils as gameObjs from Fogoso import MAIN",
"Update(): global OptionsScreen_DebugModeEnabled global OptionsScreen_RandomWindowTitle global OptionsScreen_NumberFormatting global ElementsX global",
"OptionsScreen_NumberFormatting.Set_X(ElementsX + 20) OptionsScreen_DebugModeEnabled.Set_Y(ElementsY + 50) OptionsScreen_RandomWindowTitle.Set_Y(ElementsY + 75) OptionsScreen_NumberFormatting.Set_Y(ElementsY",
"= gameObjs.UpDownButton(0,0,14) OptionsScreen_NumberFormatting = gameObjs.UpDownButton(0,0,14) def Update(): global OptionsScreen_DebugModeEnabled global",
"global OptionsScreen_NumberFormatting OptionsScreen_DebugModeEnabled.Render(DISPLAY) OptionsScreen_RandomWindowTitle.Render(DISPLAY) OptionsScreen_NumberFormatting.Render(DISPLAY) # -- Debug Mode --",
"from Fogoso import MAIN as gameMain import pygame, sys import",
"as tge from Fogoso.MAIN import ClassesUtils as gameObjs from Fogoso",
"compliance with the License. # You may obtain a copy",
"OptionsScreen_DebugModeEnabled = gameObjs.UpDownButton OptionsScreen_RandomWindowTitle = gameObjs.UpDownButton OptionsScreen_NumberFormatting = gameObjs.UpDownButton ElementsX",
"agreed to in writing, software # distributed under the License",
"Debug Mode -- # gameMain.DefaultCnt.FontRender(DISPLAY, \"/PressStart2P.ttf\", 14, gameMain.DefaultCnt.Get_RegKey(\"/strings/settings/debug_mode\") + str(gameMain.DefaultCnt.Get_RegKey(\"/OPTIONS/debug_enabled\")),",
"current_val = gameMain.DefaultCnt.Get_RegKey(\"/OPTIONS/format_numbers\", bool) if current_val: gameMain.DefaultCnt.Write_RegKey(\"/OPTIONS/format_numbers\", \"False\") if not",
"current_val: gameMain.DefaultCnt.Write_RegKey(\"/OPTIONS/format_numbers\", \"False\") if not current_val: gameMain.DefaultCnt.Write_RegKey(\"/OPTIONS/format_numbers\", \"True\") OptionsScreen_DebugModeEnabled.Set_X(ElementsX +",
"distributed under the License is distributed on an \"AS IS\"",
"+ 20) OptionsScreen_RandomWindowTitle.Set_X(ElementsX + 20) OptionsScreen_NumberFormatting.Set_X(ElementsX + 20) OptionsScreen_DebugModeEnabled.Set_Y(ElementsY +",
"express or implied. # See the License for the specific",
"except in compliance with the License. # You may obtain",
"str(gameMain.DefaultCnt.Get_RegKey(\"/OPTIONS/format_numbers\")), (240, 240, 240), ElementsX + 95, ElementsY + 102,",
"52, gameMain.DefaultCnt.Get_RegKey(\"/OPTIONS/font_aa\")) # -- Random Title -- # gameMain.DefaultCnt.FontRender(DISPLAY, \"/PressStart2P.ttf\",",
"permissions and # limitations under the License. # # #",
"240, 240), ElementsX + 95, ElementsY + 77, gameMain.DefaultCnt.Get_RegKey(\"/OPTIONS/font_aa\")) #",
"Licensed under the Apache License, Version 2.0 (the \"License\"); #",
"gameObjs.UpDownButton(0,0,14) OptionsScreen_RandomWindowTitle = gameObjs.UpDownButton(0,0,14) OptionsScreen_NumberFormatting = gameObjs.UpDownButton(0,0,14) def Update(): global",
"not use this file except in compliance with the License.",
"-- # gameMain.DefaultCnt.FontRender(DISPLAY, \"/PressStart2P.ttf\", 14, gameMain.DefaultCnt.Get_RegKey(\"/strings/settings/random_title\") + str(gameMain.DefaultCnt.Get_RegKey(\"/OPTIONS/random_title\")), (240, 240,",
"= gameObjs.UpDownButton(0,0,14) OptionsScreen_RandomWindowTitle = gameObjs.UpDownButton(0,0,14) OptionsScreen_NumberFormatting = gameObjs.UpDownButton(0,0,14) def Update():",
"OptionsScreen_NumberFormatting OptionsScreen_DebugModeEnabled.Render(DISPLAY) OptionsScreen_RandomWindowTitle.Render(DISPLAY) OptionsScreen_NumberFormatting.Render(DISPLAY) # -- Debug Mode -- #",
"= gameMain.DefaultCnt.Get_RegKey(\"/OPTIONS/random_title\", bool) if current_val: gameMain.DefaultCnt.Write_RegKey(\"/OPTIONS/random_title\", \"False\") if not current_val:",
"writing, software # distributed under the License is distributed on",
"you may not use this file except in compliance with",
"# Licensed under the Apache License, Version 2.0 (the \"License\");",
"OptionsScreen_RandomWindowTitle = gameObjs.UpDownButton(0,0,14) OptionsScreen_NumberFormatting = gameObjs.UpDownButton(0,0,14) def Update(): global OptionsScreen_DebugModeEnabled",
"2020 Aragubas # # Licensed under the Apache License, Version",
"import randint OptionsScreen_DebugModeEnabled = gameObjs.UpDownButton OptionsScreen_RandomWindowTitle = gameObjs.UpDownButton OptionsScreen_NumberFormatting =",
"as gameObjs from Fogoso import MAIN as gameMain import pygame,",
"2 or OptionsScreen_DebugModeEnabled.ButtonState == 1: current_val = gameMain.DefaultCnt.Get_RegKey(\"/OPTIONS/debug_enabled\", bool) if",
"OptionsScreen_RandomWindowTitle.Render(DISPLAY) OptionsScreen_NumberFormatting.Render(DISPLAY) # -- Debug Mode -- # gameMain.DefaultCnt.FontRender(DISPLAY, \"/PressStart2P.ttf\",",
"-- # gameMain.DefaultCnt.FontRender(DISPLAY, \"/PressStart2P.ttf\", 14, gameMain.DefaultCnt.Get_RegKey(\"/strings/settings/number_formatting\") + str(gameMain.DefaultCnt.Get_RegKey(\"/OPTIONS/format_numbers\")), (240, 240,",
"Title -- # gameMain.DefaultCnt.FontRender(DISPLAY, \"/PressStart2P.ttf\", 14, gameMain.DefaultCnt.Get_RegKey(\"/strings/settings/random_title\") + str(gameMain.DefaultCnt.Get_RegKey(\"/OPTIONS/random_title\")), (240,",
"gameMain.DefaultCnt.FontRender(DISPLAY, \"/PressStart2P.ttf\", 14, gameMain.DefaultCnt.Get_RegKey(\"/strings/settings/random_title\") + str(gameMain.DefaultCnt.Get_RegKey(\"/OPTIONS/random_title\")), (240, 240, 240), ElementsX",
"CONDITIONS OF ANY KIND, either express or implied. # See",
"global OptionsScreen_DebugModeEnabled global OptionsScreen_RandomWindowTitle global OptionsScreen_NumberFormatting OptionsScreen_DebugModeEnabled.Render(DISPLAY) OptionsScreen_RandomWindowTitle.Render(DISPLAY) OptionsScreen_NumberFormatting.Render(DISPLAY) #",
"Imports -- # from ENGINE import APPDATA as reg from",
"is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES",
"global ElementsY if OptionsScreen_DebugModeEnabled .ButtonState == 2 or OptionsScreen_DebugModeEnabled.ButtonState ==",
"-- Debug Mode -- # gameMain.DefaultCnt.FontRender(DISPLAY, \"/PressStart2P.ttf\", 14, gameMain.DefaultCnt.Get_RegKey(\"/strings/settings/debug_mode\") +",
"ENGINE import APPDATA as reg from ENGINE import UTILS as",
"75) OptionsScreen_NumberFormatting.Set_Y(ElementsY + 100) def Render(DISPLAY): global OptionsScreen_DebugModeEnabled global OptionsScreen_RandomWindowTitle",
"Fogoso import MAIN as gameMain import pygame, sys import importlib",
"OR CONDITIONS OF ANY KIND, either express or implied. #",
"# -- Number Formatting -- # gameMain.DefaultCnt.FontRender(DISPLAY, \"/PressStart2P.ttf\", 14, gameMain.DefaultCnt.Get_RegKey(\"/strings/settings/number_formatting\")",
"gameMain.DefaultCnt.Get_RegKey(\"/OPTIONS/debug_enabled\", bool) if current_val: gameMain.DefaultCnt.Write_RegKey(\"/OPTIONS/debug_enabled\", \"False\") if not current_val: gameMain.DefaultCnt.Write_RegKey(\"/OPTIONS/debug_enabled\",",
"current_val = gameMain.DefaultCnt.Get_RegKey(\"/OPTIONS/debug_enabled\", bool) if current_val: gameMain.DefaultCnt.Write_RegKey(\"/OPTIONS/debug_enabled\", \"False\") if not",
"the License is distributed on an \"AS IS\" BASIS, #",
"OptionsScreen_DebugModeEnabled.Set_X(ElementsX + 20) OptionsScreen_RandomWindowTitle.Set_X(ElementsX + 20) OptionsScreen_NumberFormatting.Set_X(ElementsX + 20) OptionsScreen_DebugModeEnabled.Set_Y(ElementsY",
"== 2 or OptionsScreen_DebugModeEnabled.ButtonState == 1: current_val = gameMain.DefaultCnt.Get_RegKey(\"/OPTIONS/debug_enabled\", bool)",
"and # limitations under the License. # # # --",
"or OptionsScreen_RandomWindowTitle.ButtonState == 1: current_val = gameMain.DefaultCnt.Get_RegKey(\"/OPTIONS/random_title\", bool) if current_val:",
"OptionsScreen_NumberFormatting.Render(DISPLAY) # -- Debug Mode -- # gameMain.DefaultCnt.FontRender(DISPLAY, \"/PressStart2P.ttf\", 14,",
"ElementsY + 102, gameMain.DefaultCnt.Get_RegKey(\"/OPTIONS/font_aa\")) def EventUpdate(event): global OptionsScreen_DebugModeEnabled global OptionsScreen_RandomWindowTitle",
"(240, 240, 240), ElementsX + 95, ElementsY + 102, gameMain.DefaultCnt.Get_RegKey(\"/OPTIONS/font_aa\"))",
"gameMain.DefaultCnt.Get_RegKey(\"/OPTIONS/random_title\", bool) if current_val: gameMain.DefaultCnt.Write_RegKey(\"/OPTIONS/random_title\", \"False\") if not current_val: gameMain.DefaultCnt.Write_RegKey(\"/OPTIONS/random_title\",",
"law or agreed to in writing, software # distributed under",
"gameMain.DefaultCnt.Write_RegKey(\"/OPTIONS/debug_enabled\", \"True\") if OptionsScreen_RandomWindowTitle .ButtonState == 2 or OptionsScreen_RandomWindowTitle.ButtonState ==",
"ElementsY + 52, gameMain.DefaultCnt.Get_RegKey(\"/OPTIONS/font_aa\")) # -- Random Title -- #",
"gameObjs from Fogoso import MAIN as gameMain import pygame, sys",
"sys import importlib import time from random import randint OptionsScreen_DebugModeEnabled",
"import ENGINE as tge from Fogoso.MAIN import ClassesUtils as gameObjs",
"if current_val: gameMain.DefaultCnt.Write_RegKey(\"/OPTIONS/format_numbers\", \"False\") if not current_val: gameMain.DefaultCnt.Write_RegKey(\"/OPTIONS/format_numbers\", \"True\") OptionsScreen_DebugModeEnabled.Set_X(ElementsX",
"240), ElementsX + 95, ElementsY + 77, gameMain.DefaultCnt.Get_RegKey(\"/OPTIONS/font_aa\")) # --",
"may obtain a copy of the License at # #",
"current_val: gameMain.DefaultCnt.Write_RegKey(\"/OPTIONS/format_numbers\", \"True\") OptionsScreen_DebugModeEnabled.Set_X(ElementsX + 20) OptionsScreen_RandomWindowTitle.Set_X(ElementsX + 20) OptionsScreen_NumberFormatting.Set_X(ElementsX",
"gameMain.DefaultCnt.Get_RegKey(\"/OPTIONS/format_numbers\", bool) if current_val: gameMain.DefaultCnt.Write_RegKey(\"/OPTIONS/format_numbers\", \"False\") if not current_val: gameMain.DefaultCnt.Write_RegKey(\"/OPTIONS/format_numbers\",",
"IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,",
"# # # -- Imports -- # from ENGINE import",
"global OptionsScreen_RandomWindowTitle global OptionsScreen_NumberFormatting global ElementsX global ElementsY if OptionsScreen_DebugModeEnabled",
"ElementsY + 77, gameMain.DefaultCnt.Get_RegKey(\"/OPTIONS/font_aa\")) # -- Number Formatting -- #",
"may not use this file except in compliance with the",
"under the License. # # # -- Imports -- #",
"WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or",
"this file except in compliance with the License. # You",
"+ 100) def Render(DISPLAY): global OptionsScreen_DebugModeEnabled global OptionsScreen_RandomWindowTitle global OptionsScreen_NumberFormatting",
"# # -- Imports -- # from ENGINE import APPDATA",
"\"True\") if OptionsScreen_NumberFormatting .ButtonState == 2 or OptionsScreen_NumberFormatting.ButtonState == 1:",
"# # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law",
"# # Licensed under the Apache License, Version 2.0 (the",
"# -- Random Title -- # gameMain.DefaultCnt.FontRender(DISPLAY, \"/PressStart2P.ttf\", 14, gameMain.DefaultCnt.Get_RegKey(\"/strings/settings/random_title\")",
"-- # from ENGINE import APPDATA as reg from ENGINE",
"file except in compliance with the License. # You may",
"on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS",
"if not current_val: gameMain.DefaultCnt.Write_RegKey(\"/OPTIONS/debug_enabled\", \"True\") if OptionsScreen_RandomWindowTitle .ButtonState == 2",
"# gameMain.DefaultCnt.FontRender(DISPLAY, \"/PressStart2P.ttf\", 14, gameMain.DefaultCnt.Get_RegKey(\"/strings/settings/random_title\") + str(gameMain.DefaultCnt.Get_RegKey(\"/OPTIONS/random_title\")), (240, 240, 240),",
"current_val: gameMain.DefaultCnt.Write_RegKey(\"/OPTIONS/random_title\", \"True\") if OptionsScreen_NumberFormatting .ButtonState == 2 or OptionsScreen_NumberFormatting.ButtonState",
"not current_val: gameMain.DefaultCnt.Write_RegKey(\"/OPTIONS/debug_enabled\", \"True\") if OptionsScreen_RandomWindowTitle .ButtonState == 2 or",
"# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express",
"if not current_val: gameMain.DefaultCnt.Write_RegKey(\"/OPTIONS/random_title\", \"True\") if OptionsScreen_NumberFormatting .ButtonState == 2",
"global OptionsScreen_RandomWindowTitle global OptionsScreen_NumberFormatting OptionsScreen_DebugModeEnabled.Render(DISPLAY) OptionsScreen_RandomWindowTitle.Render(DISPLAY) OptionsScreen_NumberFormatting.Render(DISPLAY) # -- Debug",
"gameMain.DefaultCnt.Get_RegKey(\"/OPTIONS/font_aa\")) def EventUpdate(event): global OptionsScreen_DebugModeEnabled global OptionsScreen_RandomWindowTitle global OptionsScreen_NumberFormatting OptionsScreen_DebugModeEnabled.Update(event)",
"+ str(gameMain.DefaultCnt.Get_RegKey(\"/OPTIONS/random_title\")), (240, 240, 240), ElementsX + 95, ElementsY +",
"= gameMain.DefaultCnt.Get_RegKey(\"/OPTIONS/debug_enabled\", bool) if current_val: gameMain.DefaultCnt.Write_RegKey(\"/OPTIONS/debug_enabled\", \"False\") if not current_val:",
"+ 95, ElementsY + 102, gameMain.DefaultCnt.Get_RegKey(\"/OPTIONS/font_aa\")) def EventUpdate(event): global OptionsScreen_DebugModeEnabled",
"http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed",
"240), ElementsX + 95, ElementsY + 52, gameMain.DefaultCnt.Get_RegKey(\"/OPTIONS/font_aa\")) # --",
"UTILS as utils import ENGINE as tge from Fogoso.MAIN import",
"global OptionsScreen_NumberFormatting global ElementsX global ElementsY if OptionsScreen_DebugModeEnabled .ButtonState ==",
"OptionsScreen_DebugModeEnabled.ButtonState == 1: current_val = gameMain.DefaultCnt.Get_RegKey(\"/OPTIONS/debug_enabled\", bool) if current_val: gameMain.DefaultCnt.Write_RegKey(\"/OPTIONS/debug_enabled\",",
"(240, 240, 240), ElementsX + 95, ElementsY + 77, gameMain.DefaultCnt.Get_RegKey(\"/OPTIONS/font_aa\"))",
"import time from random import randint OptionsScreen_DebugModeEnabled = gameObjs.UpDownButton OptionsScreen_RandomWindowTitle",
"or implied. # See the License for the specific language",
"if OptionsScreen_NumberFormatting .ButtonState == 2 or OptionsScreen_NumberFormatting.ButtonState == 1: current_val",
"KIND, either express or implied. # See the License for",
"specific language governing permissions and # limitations under the License.",
"== 1: current_val = gameMain.DefaultCnt.Get_RegKey(\"/OPTIONS/random_title\", bool) if current_val: gameMain.DefaultCnt.Write_RegKey(\"/OPTIONS/random_title\", \"False\")",
"tge from Fogoso.MAIN import ClassesUtils as gameObjs from Fogoso import",
"0 ElementsY = 0 def Initialize(): global OptionsScreen_DebugModeEnabled global OptionsScreen_RandomWindowTitle",
"def Initialize(): global OptionsScreen_DebugModeEnabled global OptionsScreen_RandomWindowTitle global OptionsScreen_NumberFormatting OptionsScreen_DebugModeEnabled =",
"\"False\") if not current_val: gameMain.DefaultCnt.Write_RegKey(\"/OPTIONS/random_title\", \"True\") if OptionsScreen_NumberFormatting .ButtonState ==",
"OptionsScreen_DebugModeEnabled = gameObjs.UpDownButton(0,0,14) OptionsScreen_RandomWindowTitle = gameObjs.UpDownButton(0,0,14) OptionsScreen_NumberFormatting = gameObjs.UpDownButton(0,0,14) def",
"License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by",
"ElementsX + 95, ElementsY + 102, gameMain.DefaultCnt.Get_RegKey(\"/OPTIONS/font_aa\")) def EventUpdate(event): global",
"2 or OptionsScreen_NumberFormatting.ButtonState == 1: current_val = gameMain.DefaultCnt.Get_RegKey(\"/OPTIONS/format_numbers\", bool) if",
"+ str(gameMain.DefaultCnt.Get_RegKey(\"/OPTIONS/debug_enabled\")), (240, 240, 240), ElementsX + 95, ElementsY +",
"or OptionsScreen_NumberFormatting.ButtonState == 1: current_val = gameMain.DefaultCnt.Get_RegKey(\"/OPTIONS/format_numbers\", bool) if current_val:",
"20) OptionsScreen_RandomWindowTitle.Set_X(ElementsX + 20) OptionsScreen_NumberFormatting.Set_X(ElementsX + 20) OptionsScreen_DebugModeEnabled.Set_Y(ElementsY + 50)",
"gameMain.DefaultCnt.Write_RegKey(\"/OPTIONS/format_numbers\", \"False\") if not current_val: gameMain.DefaultCnt.Write_RegKey(\"/OPTIONS/format_numbers\", \"True\") OptionsScreen_DebugModeEnabled.Set_X(ElementsX + 20)",
"# gameMain.DefaultCnt.FontRender(DISPLAY, \"/PressStart2P.ttf\", 14, gameMain.DefaultCnt.Get_RegKey(\"/strings/settings/number_formatting\") + str(gameMain.DefaultCnt.Get_RegKey(\"/OPTIONS/format_numbers\")), (240, 240, 240),",
"(the \"License\"); # you may not use this file except",
"the License. # # # -- Imports -- # from",
"current_val: gameMain.DefaultCnt.Write_RegKey(\"/OPTIONS/random_title\", \"False\") if not current_val: gameMain.DefaultCnt.Write_RegKey(\"/OPTIONS/random_title\", \"True\") if OptionsScreen_NumberFormatting",
"# you may not use this file except in compliance",
"240), ElementsX + 95, ElementsY + 102, gameMain.DefaultCnt.Get_RegKey(\"/OPTIONS/font_aa\")) def EventUpdate(event):",
"ElementsX = 0 ElementsY = 0 def Initialize(): global OptionsScreen_DebugModeEnabled",
"# limitations under the License. # # # -- Imports",
"95, ElementsY + 52, gameMain.DefaultCnt.Get_RegKey(\"/OPTIONS/font_aa\")) # -- Random Title --",
"+ 95, ElementsY + 52, gameMain.DefaultCnt.Get_RegKey(\"/OPTIONS/font_aa\")) # -- Random Title",
"ElementsX + 95, ElementsY + 52, gameMain.DefaultCnt.Get_RegKey(\"/OPTIONS/font_aa\")) # -- Random",
"Number Formatting -- # gameMain.DefaultCnt.FontRender(DISPLAY, \"/PressStart2P.ttf\", 14, gameMain.DefaultCnt.Get_RegKey(\"/strings/settings/number_formatting\") + str(gameMain.DefaultCnt.Get_RegKey(\"/OPTIONS/format_numbers\")),",
"-- Imports -- # from ENGINE import APPDATA as reg",
"pygame, sys import importlib import time from random import randint",
"if current_val: gameMain.DefaultCnt.Write_RegKey(\"/OPTIONS/random_title\", \"False\") if not current_val: gameMain.DefaultCnt.Write_RegKey(\"/OPTIONS/random_title\", \"True\") if",
"utils import ENGINE as tge from Fogoso.MAIN import ClassesUtils as",
"Formatting -- # gameMain.DefaultCnt.FontRender(DISPLAY, \"/PressStart2P.ttf\", 14, gameMain.DefaultCnt.Get_RegKey(\"/strings/settings/number_formatting\") + str(gameMain.DefaultCnt.Get_RegKey(\"/OPTIONS/format_numbers\")), (240,",
"# # Unless required by applicable law or agreed to",
"ElementsY = 0 def Initialize(): global OptionsScreen_DebugModeEnabled global OptionsScreen_RandomWindowTitle global",
"obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0",
"OptionsScreen_RandomWindowTitle.ButtonState == 1: current_val = gameMain.DefaultCnt.Get_RegKey(\"/OPTIONS/random_title\", bool) if current_val: gameMain.DefaultCnt.Write_RegKey(\"/OPTIONS/random_title\",",
"import importlib import time from random import randint OptionsScreen_DebugModeEnabled =",
"Version 2.0 (the \"License\"); # you may not use this",
"95, ElementsY + 77, gameMain.DefaultCnt.Get_RegKey(\"/OPTIONS/font_aa\")) # -- Number Formatting --",
"random import randint OptionsScreen_DebugModeEnabled = gameObjs.UpDownButton OptionsScreen_RandomWindowTitle = gameObjs.UpDownButton OptionsScreen_NumberFormatting",
"+ 50) OptionsScreen_RandomWindowTitle.Set_Y(ElementsY + 75) OptionsScreen_NumberFormatting.Set_Y(ElementsY + 100) def Render(DISPLAY):",
"\"/PressStart2P.ttf\", 14, gameMain.DefaultCnt.Get_RegKey(\"/strings/settings/debug_mode\") + str(gameMain.DefaultCnt.Get_RegKey(\"/OPTIONS/debug_enabled\")), (240, 240, 240), ElementsX +",
"#!/usr/bin/python3.7 # Copyright 2020 Aragubas # # Licensed under the",
"implied. # See the License for the specific language governing",
"bool) if current_val: gameMain.DefaultCnt.Write_RegKey(\"/OPTIONS/debug_enabled\", \"False\") if not current_val: gameMain.DefaultCnt.Write_RegKey(\"/OPTIONS/debug_enabled\", \"True\")",
"under the Apache License, Version 2.0 (the \"License\"); # you",
"randint OptionsScreen_DebugModeEnabled = gameObjs.UpDownButton OptionsScreen_RandomWindowTitle = gameObjs.UpDownButton OptionsScreen_NumberFormatting = gameObjs.UpDownButton",
"current_val = gameMain.DefaultCnt.Get_RegKey(\"/OPTIONS/random_title\", bool) if current_val: gameMain.DefaultCnt.Write_RegKey(\"/OPTIONS/random_title\", \"False\") if not",
"OptionsScreen_NumberFormatting.Set_Y(ElementsY + 100) def Render(DISPLAY): global OptionsScreen_DebugModeEnabled global OptionsScreen_RandomWindowTitle global",
"global OptionsScreen_DebugModeEnabled global OptionsScreen_RandomWindowTitle global OptionsScreen_NumberFormatting global ElementsX global ElementsY",
"by applicable law or agreed to in writing, software #",
"global OptionsScreen_NumberFormatting OptionsScreen_DebugModeEnabled = gameObjs.UpDownButton(0,0,14) OptionsScreen_RandomWindowTitle = gameObjs.UpDownButton(0,0,14) OptionsScreen_NumberFormatting =",
"20) OptionsScreen_NumberFormatting.Set_X(ElementsX + 20) OptionsScreen_DebugModeEnabled.Set_Y(ElementsY + 50) OptionsScreen_RandomWindowTitle.Set_Y(ElementsY + 75)",
"gameObjs.UpDownButton ElementsX = 0 ElementsY = 0 def Initialize(): global",
"OptionsScreen_RandomWindowTitle global OptionsScreen_NumberFormatting global ElementsX global ElementsY if OptionsScreen_DebugModeEnabled .ButtonState",
"OptionsScreen_NumberFormatting .ButtonState == 2 or OptionsScreen_NumberFormatting.ButtonState == 1: current_val =",
"OptionsScreen_NumberFormatting OptionsScreen_DebugModeEnabled = gameObjs.UpDownButton(0,0,14) OptionsScreen_RandomWindowTitle = gameObjs.UpDownButton(0,0,14) OptionsScreen_NumberFormatting = gameObjs.UpDownButton(0,0,14)",
"gameMain.DefaultCnt.Get_RegKey(\"/OPTIONS/font_aa\")) # -- Random Title -- # gameMain.DefaultCnt.FontRender(DISPLAY, \"/PressStart2P.ttf\", 14,",
"== 1: current_val = gameMain.DefaultCnt.Get_RegKey(\"/OPTIONS/format_numbers\", bool) if current_val: gameMain.DefaultCnt.Write_RegKey(\"/OPTIONS/format_numbers\", \"False\")",
"def Render(DISPLAY): global OptionsScreen_DebugModeEnabled global OptionsScreen_RandomWindowTitle global OptionsScreen_NumberFormatting OptionsScreen_DebugModeEnabled.Render(DISPLAY) OptionsScreen_RandomWindowTitle.Render(DISPLAY)",
"time from random import randint OptionsScreen_DebugModeEnabled = gameObjs.UpDownButton OptionsScreen_RandomWindowTitle =",
"+ 20) OptionsScreen_DebugModeEnabled.Set_Y(ElementsY + 50) OptionsScreen_RandomWindowTitle.Set_Y(ElementsY + 75) OptionsScreen_NumberFormatting.Set_Y(ElementsY +",
"= 0 def Initialize(): global OptionsScreen_DebugModeEnabled global OptionsScreen_RandomWindowTitle global OptionsScreen_NumberFormatting",
"1: current_val = gameMain.DefaultCnt.Get_RegKey(\"/OPTIONS/random_title\", bool) if current_val: gameMain.DefaultCnt.Write_RegKey(\"/OPTIONS/random_title\", \"False\") if",
"an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF",
"as utils import ENGINE as tge from Fogoso.MAIN import ClassesUtils",
"str(gameMain.DefaultCnt.Get_RegKey(\"/OPTIONS/random_title\")), (240, 240, 240), ElementsX + 95, ElementsY + 77,",
"Unless required by applicable law or agreed to in writing,",
"from random import randint OptionsScreen_DebugModeEnabled = gameObjs.UpDownButton OptionsScreen_RandomWindowTitle = gameObjs.UpDownButton",
"= 0 ElementsY = 0 def Initialize(): global OptionsScreen_DebugModeEnabled global",
"OptionsScreen_DebugModeEnabled global OptionsScreen_RandomWindowTitle global OptionsScreen_NumberFormatting OptionsScreen_DebugModeEnabled.Render(DISPLAY) OptionsScreen_RandomWindowTitle.Render(DISPLAY) OptionsScreen_NumberFormatting.Render(DISPLAY) # --",
"+ 20) OptionsScreen_NumberFormatting.Set_X(ElementsX + 20) OptionsScreen_DebugModeEnabled.Set_Y(ElementsY + 50) OptionsScreen_RandomWindowTitle.Set_Y(ElementsY +",
"(240, 240, 240), ElementsX + 95, ElementsY + 52, gameMain.DefaultCnt.Get_RegKey(\"/OPTIONS/font_aa\"))",
"+ 77, gameMain.DefaultCnt.Get_RegKey(\"/OPTIONS/font_aa\")) # -- Number Formatting -- # gameMain.DefaultCnt.FontRender(DISPLAY,",
"OptionsScreen_RandomWindowTitle global OptionsScreen_NumberFormatting OptionsScreen_DebugModeEnabled.Render(DISPLAY) OptionsScreen_RandomWindowTitle.Render(DISPLAY) OptionsScreen_NumberFormatting.Render(DISPLAY) # -- Debug Mode",
"the specific language governing permissions and # limitations under the",
"gameObjs.UpDownButton OptionsScreen_NumberFormatting = gameObjs.UpDownButton ElementsX = 0 ElementsY = 0",
"Fogoso.MAIN import ClassesUtils as gameObjs from Fogoso import MAIN as",
"77, gameMain.DefaultCnt.Get_RegKey(\"/OPTIONS/font_aa\")) # -- Number Formatting -- # gameMain.DefaultCnt.FontRender(DISPLAY, \"/PressStart2P.ttf\",",
"OptionsScreen_DebugModeEnabled.Set_Y(ElementsY + 50) OptionsScreen_RandomWindowTitle.Set_Y(ElementsY + 75) OptionsScreen_NumberFormatting.Set_Y(ElementsY + 100) def",
"OptionsScreen_RandomWindowTitle.Set_Y(ElementsY + 75) OptionsScreen_NumberFormatting.Set_Y(ElementsY + 100) def Render(DISPLAY): global OptionsScreen_DebugModeEnabled",
"importlib import time from random import randint OptionsScreen_DebugModeEnabled = gameObjs.UpDownButton",
"applicable law or agreed to in writing, software # distributed",
"OptionsScreen_DebugModeEnabled global OptionsScreen_RandomWindowTitle global OptionsScreen_NumberFormatting OptionsScreen_DebugModeEnabled = gameObjs.UpDownButton(0,0,14) OptionsScreen_RandomWindowTitle =",
"gameMain.DefaultCnt.Get_RegKey(\"/OPTIONS/font_aa\")) # -- Number Formatting -- # gameMain.DefaultCnt.FontRender(DISPLAY, \"/PressStart2P.ttf\", 14,",
"global OptionsScreen_DebugModeEnabled global OptionsScreen_RandomWindowTitle global OptionsScreen_NumberFormatting OptionsScreen_DebugModeEnabled = gameObjs.UpDownButton(0,0,14) OptionsScreen_RandomWindowTitle",
"in writing, software # distributed under the License is distributed",
"governing permissions and # limitations under the License. # #",
"as reg from ENGINE import UTILS as utils import ENGINE",
".ButtonState == 2 or OptionsScreen_NumberFormatting.ButtonState == 1: current_val = gameMain.DefaultCnt.Get_RegKey(\"/OPTIONS/format_numbers\",",
"import ClassesUtils as gameObjs from Fogoso import MAIN as gameMain",
"License. # # # -- Imports -- # from ENGINE",
"from ENGINE import UTILS as utils import ENGINE as tge",
"Copyright 2020 Aragubas # # Licensed under the Apache License,",
"-- Random Title -- # gameMain.DefaultCnt.FontRender(DISPLAY, \"/PressStart2P.ttf\", 14, gameMain.DefaultCnt.Get_RegKey(\"/strings/settings/random_title\") +",
".ButtonState == 2 or OptionsScreen_DebugModeEnabled.ButtonState == 1: current_val = gameMain.DefaultCnt.Get_RegKey(\"/OPTIONS/debug_enabled\",",
"License is distributed on an \"AS IS\" BASIS, # WITHOUT",
"import UTILS as utils import ENGINE as tge from Fogoso.MAIN",
"License, Version 2.0 (the \"License\"); # you may not use",
"# You may obtain a copy of the License at",
"<filename>MAIN/Screens/Settings/category_2/__init__.py #!/usr/bin/python3.7 # Copyright 2020 Aragubas # # Licensed under",
"ElementsX + 95, ElementsY + 77, gameMain.DefaultCnt.Get_RegKey(\"/OPTIONS/font_aa\")) # -- Number",
"copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # #",
"\"False\") if not current_val: gameMain.DefaultCnt.Write_RegKey(\"/OPTIONS/debug_enabled\", \"True\") if OptionsScreen_RandomWindowTitle .ButtonState ==",
"gameMain.DefaultCnt.Get_RegKey(\"/strings/settings/random_title\") + str(gameMain.DefaultCnt.Get_RegKey(\"/OPTIONS/random_title\")), (240, 240, 240), ElementsX + 95, ElementsY",
"the License for the specific language governing permissions and #",
"Initialize(): global OptionsScreen_DebugModeEnabled global OptionsScreen_RandomWindowTitle global OptionsScreen_NumberFormatting OptionsScreen_DebugModeEnabled = gameObjs.UpDownButton(0,0,14)",
"global OptionsScreen_RandomWindowTitle global OptionsScreen_NumberFormatting OptionsScreen_DebugModeEnabled = gameObjs.UpDownButton(0,0,14) OptionsScreen_RandomWindowTitle = gameObjs.UpDownButton(0,0,14)",
"Apache License, Version 2.0 (the \"License\"); # you may not",
"2 or OptionsScreen_RandomWindowTitle.ButtonState == 1: current_val = gameMain.DefaultCnt.Get_RegKey(\"/OPTIONS/random_title\", bool) if",
"def Update(): global OptionsScreen_DebugModeEnabled global OptionsScreen_RandomWindowTitle global OptionsScreen_NumberFormatting global ElementsX",
"either express or implied. # See the License for the",
"= gameObjs.UpDownButton OptionsScreen_RandomWindowTitle = gameObjs.UpDownButton OptionsScreen_NumberFormatting = gameObjs.UpDownButton ElementsX =",
"+ 102, gameMain.DefaultCnt.Get_RegKey(\"/OPTIONS/font_aa\")) def EventUpdate(event): global OptionsScreen_DebugModeEnabled global OptionsScreen_RandomWindowTitle global",
"reg from ENGINE import UTILS as utils import ENGINE as",
"# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or",
"not current_val: gameMain.DefaultCnt.Write_RegKey(\"/OPTIONS/random_title\", \"True\") if OptionsScreen_NumberFormatting .ButtonState == 2 or",
"+ 95, ElementsY + 77, gameMain.DefaultCnt.Get_RegKey(\"/OPTIONS/font_aa\")) # -- Number Formatting",
"\"True\") if OptionsScreen_RandomWindowTitle .ButtonState == 2 or OptionsScreen_RandomWindowTitle.ButtonState == 1:",
"gameMain.DefaultCnt.FontRender(DISPLAY, \"/PressStart2P.ttf\", 14, gameMain.DefaultCnt.Get_RegKey(\"/strings/settings/number_formatting\") + str(gameMain.DefaultCnt.Get_RegKey(\"/OPTIONS/format_numbers\")), (240, 240, 240), ElementsX",
"if OptionsScreen_DebugModeEnabled .ButtonState == 2 or OptionsScreen_DebugModeEnabled.ButtonState == 1: current_val",
"not current_val: gameMain.DefaultCnt.Write_RegKey(\"/OPTIONS/format_numbers\", \"True\") OptionsScreen_DebugModeEnabled.Set_X(ElementsX + 20) OptionsScreen_RandomWindowTitle.Set_X(ElementsX + 20)",
"Mode -- # gameMain.DefaultCnt.FontRender(DISPLAY, \"/PressStart2P.ttf\", 14, gameMain.DefaultCnt.Get_RegKey(\"/strings/settings/debug_mode\") + str(gameMain.DefaultCnt.Get_RegKey(\"/OPTIONS/debug_enabled\")), (240,",
"# -- Debug Mode -- # gameMain.DefaultCnt.FontRender(DISPLAY, \"/PressStart2P.ttf\", 14, gameMain.DefaultCnt.Get_RegKey(\"/strings/settings/debug_mode\")",
"OptionsScreen_NumberFormatting = gameObjs.UpDownButton(0,0,14) def Update(): global OptionsScreen_DebugModeEnabled global OptionsScreen_RandomWindowTitle global",
"1: current_val = gameMain.DefaultCnt.Get_RegKey(\"/OPTIONS/format_numbers\", bool) if current_val: gameMain.DefaultCnt.Write_RegKey(\"/OPTIONS/format_numbers\", \"False\") if",
"a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 #",
"APPDATA as reg from ENGINE import UTILS as utils import",
"or OptionsScreen_DebugModeEnabled.ButtonState == 1: current_val = gameMain.DefaultCnt.Get_RegKey(\"/OPTIONS/debug_enabled\", bool) if current_val:",
"1: current_val = gameMain.DefaultCnt.Get_RegKey(\"/OPTIONS/debug_enabled\", bool) if current_val: gameMain.DefaultCnt.Write_RegKey(\"/OPTIONS/debug_enabled\", \"False\") if",
"= gameObjs.UpDownButton ElementsX = 0 ElementsY = 0 def Initialize():",
"OptionsScreen_RandomWindowTitle = gameObjs.UpDownButton OptionsScreen_NumberFormatting = gameObjs.UpDownButton ElementsX = 0 ElementsY",
"\"License\"); # you may not use this file except in",
"OptionsScreen_NumberFormatting = gameObjs.UpDownButton ElementsX = 0 ElementsY = 0 def",
"== 2 or OptionsScreen_RandomWindowTitle.ButtonState == 1: current_val = gameMain.DefaultCnt.Get_RegKey(\"/OPTIONS/random_title\", bool)",
"= gameObjs.UpDownButton OptionsScreen_NumberFormatting = gameObjs.UpDownButton ElementsX = 0 ElementsY =",
"distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR",
"# distributed under the License is distributed on an \"AS",
"240, 240), ElementsX + 95, ElementsY + 52, gameMain.DefaultCnt.Get_RegKey(\"/OPTIONS/font_aa\")) #",
"ElementsX global ElementsY if OptionsScreen_DebugModeEnabled .ButtonState == 2 or OptionsScreen_DebugModeEnabled.ButtonState",
"ElementsY if OptionsScreen_DebugModeEnabled .ButtonState == 2 or OptionsScreen_DebugModeEnabled.ButtonState == 1:",
"# Unless required by applicable law or agreed to in",
"\"True\") OptionsScreen_DebugModeEnabled.Set_X(ElementsX + 20) OptionsScreen_RandomWindowTitle.Set_X(ElementsX + 20) OptionsScreen_NumberFormatting.Set_X(ElementsX + 20)",
"gameMain.DefaultCnt.Write_RegKey(\"/OPTIONS/format_numbers\", \"True\") OptionsScreen_DebugModeEnabled.Set_X(ElementsX + 20) OptionsScreen_RandomWindowTitle.Set_X(ElementsX + 20) OptionsScreen_NumberFormatting.Set_X(ElementsX +",
"str(gameMain.DefaultCnt.Get_RegKey(\"/OPTIONS/debug_enabled\")), (240, 240, 240), ElementsX + 95, ElementsY + 52,",
"-- Number Formatting -- # gameMain.DefaultCnt.FontRender(DISPLAY, \"/PressStart2P.ttf\", 14, gameMain.DefaultCnt.Get_RegKey(\"/strings/settings/number_formatting\") +",
"\"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY",
"gameMain.DefaultCnt.Write_RegKey(\"/OPTIONS/debug_enabled\", \"False\") if not current_val: gameMain.DefaultCnt.Write_RegKey(\"/OPTIONS/debug_enabled\", \"True\") if OptionsScreen_RandomWindowTitle .ButtonState",
"OptionsScreen_RandomWindowTitle.Set_X(ElementsX + 20) OptionsScreen_NumberFormatting.Set_X(ElementsX + 20) OptionsScreen_DebugModeEnabled.Set_Y(ElementsY + 50) OptionsScreen_RandomWindowTitle.Set_Y(ElementsY",
"You may obtain a copy of the License at #",
"# -- Imports -- # from ENGINE import APPDATA as",
"bool) if current_val: gameMain.DefaultCnt.Write_RegKey(\"/OPTIONS/random_title\", \"False\") if not current_val: gameMain.DefaultCnt.Write_RegKey(\"/OPTIONS/random_title\", \"True\")",
"Aragubas # # Licensed under the Apache License, Version 2.0",
"the Apache License, Version 2.0 (the \"License\"); # you may",
"if OptionsScreen_RandomWindowTitle .ButtonState == 2 or OptionsScreen_RandomWindowTitle.ButtonState == 1: current_val",
"import APPDATA as reg from ENGINE import UTILS as utils",
"# Copyright 2020 Aragubas # # Licensed under the Apache",
"gameMain.DefaultCnt.FontRender(DISPLAY, \"/PressStart2P.ttf\", 14, gameMain.DefaultCnt.Get_RegKey(\"/strings/settings/debug_mode\") + str(gameMain.DefaultCnt.Get_RegKey(\"/OPTIONS/debug_enabled\")), (240, 240, 240), ElementsX"
] |
[
"from robotpy_ext.control.toggle import Toggle from robotpy_ext.misc.precise_delay import NotifierDelay class FakeJoystick:",
"= False def test_toggle(): joystick = FakeJoystick() toggleButton = Toggle(joystick,",
"toggleButton.off assert toggleButton2.on def test_toggle_debounce(): # TODO: use simulated time",
"toggleButton.off joystick.release(0) assert toggleButton.off joystick.press(1) assert toggleButton.off assert toggleButton2.on def",
"NotifierDelay(0.5) joystick = FakeJoystick() toggleButton = Toggle(joystick, 1, 0.1) assert",
"joystick = FakeJoystick() toggleButton = Toggle(joystick, 0) toggleButton2 = Toggle(joystick,",
"True def release(self, num): self._pressed[num] = False def test_toggle(): joystick",
"toggleButton = Toggle(joystick, 0) toggleButton2 = Toggle(joystick, 1) assert toggleButton.off",
"joystick.press(0) assert toggleButton.off joystick.release(0) assert toggleButton.off joystick.press(1) assert toggleButton.off assert",
"simulated time delay = NotifierDelay(0.5) joystick = FakeJoystick() toggleButton =",
"self._pressed[num] = False def test_toggle(): joystick = FakeJoystick() toggleButton =",
"toggleButton.on joystick.press(0) assert toggleButton.off joystick.release(0) assert toggleButton.off joystick.press(1) assert toggleButton.off",
"FakeJoystick() toggleButton = Toggle(joystick, 0) toggleButton2 = Toggle(joystick, 1) assert",
"assert toggleButton.off joystick.release(0) assert toggleButton.off joystick.press(1) assert toggleButton.off assert toggleButton2.on",
"assert toggleButton.on joystick.press(0) assert toggleButton.off joystick.release(0) assert toggleButton.off joystick.press(1) assert",
"def getRawButton(self, num): return self._pressed[num] def press(self, num): self._pressed[num] =",
"joystick.press(0) assert toggleButton.on assert toggleButton2.off joystick.release(0) assert toggleButton.on joystick.press(0) assert",
"Toggle from robotpy_ext.misc.precise_delay import NotifierDelay class FakeJoystick: def __init__(self): self._pressed",
"= Toggle(joystick, 1) assert toggleButton.off joystick.press(0) assert toggleButton.on assert toggleButton2.off",
"toggleButton.on joystick.release(1) joystick.press(1) joystick.release(1) assert toggleButton.on delay.wait() assert toggleButton.on joystick.press(1)",
"NotifierDelay class FakeJoystick: def __init__(self): self._pressed = [False] * 2",
"def test_toggle_debounce(): # TODO: use simulated time delay = NotifierDelay(0.5)",
"test_toggle_debounce(): # TODO: use simulated time delay = NotifierDelay(0.5) joystick",
"__init__(self): self._pressed = [False] * 2 def getRawButton(self, num): return",
"num): self._pressed[num] = True def release(self, num): self._pressed[num] = False",
"toggleButton.off joystick.press(0) assert toggleButton.on assert toggleButton2.off joystick.release(0) assert toggleButton.on joystick.press(0)",
"joystick.press(1) assert toggleButton.on joystick.release(1) joystick.press(1) joystick.release(1) assert toggleButton.on delay.wait() assert",
"toggleButton2 = Toggle(joystick, 1) assert toggleButton.off joystick.press(0) assert toggleButton.on assert",
"toggleButton2.off joystick.release(0) assert toggleButton.on joystick.press(0) assert toggleButton.off joystick.release(0) assert toggleButton.off",
"= True def release(self, num): self._pressed[num] = False def test_toggle():",
"joystick.release(1) joystick.press(1) joystick.release(1) assert toggleButton.on delay.wait() assert toggleButton.on joystick.press(1) assert",
"test_toggle(): joystick = FakeJoystick() toggleButton = Toggle(joystick, 0) toggleButton2 =",
"getRawButton(self, num): return self._pressed[num] def press(self, num): self._pressed[num] = True",
"robotpy_ext.misc.precise_delay import NotifierDelay class FakeJoystick: def __init__(self): self._pressed = [False]",
"joystick.release(0) assert toggleButton.off joystick.press(1) assert toggleButton.off assert toggleButton2.on def test_toggle_debounce():",
"assert toggleButton.off joystick.press(1) assert toggleButton.off assert toggleButton2.on def test_toggle_debounce(): #",
"num): return self._pressed[num] def press(self, num): self._pressed[num] = True def",
"assert toggleButton.off joystick.press(1) assert toggleButton.on joystick.release(1) joystick.press(1) joystick.release(1) assert toggleButton.on",
"= NotifierDelay(0.5) joystick = FakeJoystick() toggleButton = Toggle(joystick, 1, 0.1)",
"self._pressed = [False] * 2 def getRawButton(self, num): return self._pressed[num]",
"assert toggleButton.off assert toggleButton2.on def test_toggle_debounce(): # TODO: use simulated",
"assert toggleButton2.off joystick.release(0) assert toggleButton.on joystick.press(0) assert toggleButton.off joystick.release(0) assert",
"def test_toggle(): joystick = FakeJoystick() toggleButton = Toggle(joystick, 0) toggleButton2",
"toggleButton.off joystick.press(1) assert toggleButton.on joystick.release(1) joystick.press(1) joystick.release(1) assert toggleButton.on delay.wait()",
"1, 0.1) assert toggleButton.off joystick.press(1) assert toggleButton.on joystick.release(1) joystick.press(1) joystick.release(1)",
"Toggle(joystick, 1) assert toggleButton.off joystick.press(0) assert toggleButton.on assert toggleButton2.off joystick.release(0)",
"assert toggleButton.on assert toggleButton2.off joystick.release(0) assert toggleButton.on joystick.press(0) assert toggleButton.off",
"toggleButton2.on def test_toggle_debounce(): # TODO: use simulated time delay =",
"[False] * 2 def getRawButton(self, num): return self._pressed[num] def press(self,",
"joystick = FakeJoystick() toggleButton = Toggle(joystick, 1, 0.1) assert toggleButton.off",
"= Toggle(joystick, 1, 0.1) assert toggleButton.off joystick.press(1) assert toggleButton.on joystick.release(1)",
"False def test_toggle(): joystick = FakeJoystick() toggleButton = Toggle(joystick, 0)",
"FakeJoystick() toggleButton = Toggle(joystick, 1, 0.1) assert toggleButton.off joystick.press(1) assert",
"from robotpy_ext.misc.precise_delay import NotifierDelay class FakeJoystick: def __init__(self): self._pressed =",
"= FakeJoystick() toggleButton = Toggle(joystick, 1, 0.1) assert toggleButton.off joystick.press(1)",
"assert toggleButton2.on def test_toggle_debounce(): # TODO: use simulated time delay",
"def press(self, num): self._pressed[num] = True def release(self, num): self._pressed[num]",
"Toggle(joystick, 1, 0.1) assert toggleButton.off joystick.press(1) assert toggleButton.on joystick.release(1) joystick.press(1)",
"num): self._pressed[num] = False def test_toggle(): joystick = FakeJoystick() toggleButton",
"= Toggle(joystick, 0) toggleButton2 = Toggle(joystick, 1) assert toggleButton.off joystick.press(0)",
"0.1) assert toggleButton.off joystick.press(1) assert toggleButton.on joystick.release(1) joystick.press(1) joystick.release(1) assert",
"2 def getRawButton(self, num): return self._pressed[num] def press(self, num): self._pressed[num]",
"def __init__(self): self._pressed = [False] * 2 def getRawButton(self, num):",
"def release(self, num): self._pressed[num] = False def test_toggle(): joystick =",
"TODO: use simulated time delay = NotifierDelay(0.5) joystick = FakeJoystick()",
"joystick.release(0) assert toggleButton.on joystick.press(0) assert toggleButton.off joystick.release(0) assert toggleButton.off joystick.press(1)",
"time delay = NotifierDelay(0.5) joystick = FakeJoystick() toggleButton = Toggle(joystick,",
"# TODO: use simulated time delay = NotifierDelay(0.5) joystick =",
"class FakeJoystick: def __init__(self): self._pressed = [False] * 2 def",
"assert toggleButton.on joystick.release(1) joystick.press(1) joystick.release(1) assert toggleButton.on delay.wait() assert toggleButton.on",
"use simulated time delay = NotifierDelay(0.5) joystick = FakeJoystick() toggleButton",
"toggleButton = Toggle(joystick, 1, 0.1) assert toggleButton.off joystick.press(1) assert toggleButton.on",
"joystick.press(1) joystick.release(1) assert toggleButton.on delay.wait() assert toggleButton.on joystick.press(1) assert toggleButton.off",
"self._pressed[num] = True def release(self, num): self._pressed[num] = False def",
"Toggle(joystick, 0) toggleButton2 = Toggle(joystick, 1) assert toggleButton.off joystick.press(0) assert",
"toggleButton.on assert toggleButton2.off joystick.release(0) assert toggleButton.on joystick.press(0) assert toggleButton.off joystick.release(0)",
"joystick.press(1) assert toggleButton.off assert toggleButton2.on def test_toggle_debounce(): # TODO: use",
"= [False] * 2 def getRawButton(self, num): return self._pressed[num] def",
"import NotifierDelay class FakeJoystick: def __init__(self): self._pressed = [False] *",
"FakeJoystick: def __init__(self): self._pressed = [False] * 2 def getRawButton(self,",
"toggleButton.off joystick.press(1) assert toggleButton.off assert toggleButton2.on def test_toggle_debounce(): # TODO:",
"0) toggleButton2 = Toggle(joystick, 1) assert toggleButton.off joystick.press(0) assert toggleButton.on",
"assert toggleButton.off joystick.press(0) assert toggleButton.on assert toggleButton2.off joystick.release(0) assert toggleButton.on",
"delay = NotifierDelay(0.5) joystick = FakeJoystick() toggleButton = Toggle(joystick, 1,",
"import Toggle from robotpy_ext.misc.precise_delay import NotifierDelay class FakeJoystick: def __init__(self):",
"* 2 def getRawButton(self, num): return self._pressed[num] def press(self, num):",
"self._pressed[num] def press(self, num): self._pressed[num] = True def release(self, num):",
"robotpy_ext.control.toggle import Toggle from robotpy_ext.misc.precise_delay import NotifierDelay class FakeJoystick: def",
"return self._pressed[num] def press(self, num): self._pressed[num] = True def release(self,",
"press(self, num): self._pressed[num] = True def release(self, num): self._pressed[num] =",
"1) assert toggleButton.off joystick.press(0) assert toggleButton.on assert toggleButton2.off joystick.release(0) assert",
"= FakeJoystick() toggleButton = Toggle(joystick, 0) toggleButton2 = Toggle(joystick, 1)",
"release(self, num): self._pressed[num] = False def test_toggle(): joystick = FakeJoystick()"
] |
[
"match when testing floating point values def test_linear(self): f =",
"feed_dict={x:0.5}), 0.4621, places=TestActivations.PLACES) # Case 3 self.assertAlmostEqual(sess.run(f(x), feed_dict={x:-0.25}), -0.2449, places=TestActivations.PLACES)",
"x: tflearn.leaky_relu(x, alpha=0.2) x = tf.placeholder(tf.float32, shape=()) with tf.Session() as",
"# Number of places to match when testing floating point",
"with tf.Session() as sess: # Case 1: 'linear' self.assertEqual( sess.run(tflearn.activation(x,",
"import tflearn import unittest class TestActivations(unittest.TestCase): ''' This class contains",
"x) # Case 2 x = tf.placeholder(tf.int64, shape=()) self.assertEqual(f(x), x)",
"# Case 1 self.assertEqual(sess.run(f(x), feed_dict={x:0}), 0) # Case 2 self.assertAlmostEqual(sess.run(f(x),",
"= lambda x: tflearn.leaky_relu(x, alpha=0.2) x = tf.constant(-0.25, tf.float32) with",
"as sess: # Case 1 self.assertEqual(sess.run(f(x), feed_dict={x:0}), 0) # Case",
"Case 2: 'relu' self.assertEqual( sess.run(tflearn.activation(x, 'relu')), 0) # Case 3:",
"tf.Session() as sess: # Case 1 self.assertEqual(sess.run(f(x), feed_dict={x:0}), 0) #",
"of places to match when testing floating point values def",
"self.assertAlmostEqual(sess.run(f(x), feed_dict={x:-1}), -0.2, places=TestActivations.PLACES) # Case 4 self.assertAlmostEqual(sess.run(f(x), feed_dict={x:-5}), -1,",
"x = tf.constant(-0.25, tf.float32) with tf.Session() as sess: # Case",
"def test_linear(self): f = tflearn.linear # Case 1 x =",
"'tanh')), -0.2449, places=TestActivations.PLACES) # Case 5: lrelu_02 (callable) self.assertAlmostEqual( sess.run(tflearn.activation(x,",
"places=TestActivations.PLACES) def test_leaky_relu(self): f = lambda x: tflearn.leaky_relu(x, alpha=0.2) x",
"1: 'linear' self.assertEqual( sess.run(tflearn.activation(x, 'linear')), -0.25) # Case 2: 'relu'",
"tflearn import unittest class TestActivations(unittest.TestCase): ''' This class contains test",
"with tf.Session() as sess: # Case 1 self.assertEqual(sess.run(f(x), feed_dict={x:0}), 0)",
"= 4 # Number of places to match when testing",
"for tflearn ''' import tensorflow.compat.v1 as tf import tflearn import",
"'leaky_relu')), -0.025, places=TestActivations.PLACES) # Case 4: 'tanh' self.assertAlmostEqual( sess.run(tflearn.activation(x, 'tanh')),",
"as tf import tflearn import unittest class TestActivations(unittest.TestCase): ''' This",
"point values def test_linear(self): f = tflearn.linear # Case 1",
"Case 2 self.assertAlmostEqual(sess.run(f(x), feed_dict={x:1}), 1, places=TestActivations.PLACES) # Case 3 self.assertAlmostEqual(sess.run(f(x),",
"Case 4 self.assertAlmostEqual(sess.run(f(x), feed_dict={x:-5}), -1, places=TestActivations.PLACES) def test_apply_activation(self): lrelu_02 =",
"Case 3 self.assertAlmostEqual(sess.run(f(x), feed_dict={x:-1}), -0.2, places=TestActivations.PLACES) # Case 4 self.assertAlmostEqual(sess.run(f(x),",
"shape=()) self.assertEqual(f(x), x) def test_tanh(self): f = tflearn.tanh x =",
"self.assertAlmostEqual(sess.run(f(x), feed_dict={x:-0.25}), -0.2449, places=TestActivations.PLACES) def test_leaky_relu(self): f = lambda x:",
"0) # Case 2 self.assertAlmostEqual(sess.run(f(x), feed_dict={x:0.5}), 0.4621, places=TestActivations.PLACES) # Case",
"contains test cases for tflearn ''' import tensorflow.compat.v1 as tf",
"-0.025, places=TestActivations.PLACES) # Case 4: 'tanh' self.assertAlmostEqual( sess.run(tflearn.activation(x, 'tanh')), -0.2449,",
"self.assertEqual( sess.run(tflearn.activation(x, 'relu')), 0) # Case 3: 'leaky_relu' self.assertAlmostEqual( sess.run(tflearn.activation(x,",
"feed_dict={x:-1}), -0.2, places=TestActivations.PLACES) # Case 4 self.assertAlmostEqual(sess.run(f(x), feed_dict={x:-5}), -1, places=TestActivations.PLACES)",
"1 self.assertEqual(sess.run(f(x), feed_dict={x:0}), 0) # Case 2 self.assertAlmostEqual(sess.run(f(x), feed_dict={x:1}), 1,",
"unittest class TestActivations(unittest.TestCase): ''' This class contains test cases for",
"-0.25) # Case 2: 'relu' self.assertEqual( sess.run(tflearn.activation(x, 'relu')), 0) #",
"tflearn/activations.py ''' PLACES = 4 # Number of places to",
"= tf.placeholder(tf.float32, shape=()) with tf.Session() as sess: # Case 1",
"Case 1 self.assertEqual(sess.run(f(x), feed_dict={x:0}), 0) # Case 2 self.assertAlmostEqual(sess.run(f(x), feed_dict={x:0.5}),",
"'tanh' self.assertAlmostEqual( sess.run(tflearn.activation(x, 'tanh')), -0.2449, places=TestActivations.PLACES) # Case 5: lrelu_02",
"self.assertEqual(sess.run(f(x), feed_dict={x:0}), 0) # Case 2 self.assertAlmostEqual(sess.run(f(x), feed_dict={x:0.5}), 0.4621, places=TestActivations.PLACES)",
"for the functions in tflearn/activations.py ''' PLACES = 4 #",
"x: tflearn.leaky_relu(x, alpha=0.2) x = tf.constant(-0.25, tf.float32) with tf.Session() as",
"Number of places to match when testing floating point values",
"Case 2 x = tf.placeholder(tf.int64, shape=()) self.assertEqual(f(x), x) def test_tanh(self):",
"tf.placeholder(tf.float32, shape=()) with tf.Session() as sess: # Case 1 self.assertEqual(sess.run(f(x),",
"lrelu_02 (callable) self.assertAlmostEqual( sess.run(tflearn.activation(x, lrelu_02)), -0.05, places=TestActivations.PLACES) if __name__ ==",
"self.assertAlmostEqual(sess.run(f(x), feed_dict={x:-5}), -1, places=TestActivations.PLACES) def test_apply_activation(self): lrelu_02 = lambda x:",
"'relu' self.assertEqual( sess.run(tflearn.activation(x, 'relu')), 0) # Case 3: 'leaky_relu' self.assertAlmostEqual(",
"places=TestActivations.PLACES) # Case 5: lrelu_02 (callable) self.assertAlmostEqual( sess.run(tflearn.activation(x, lrelu_02)), -0.05,",
"# Case 1 x = tf.placeholder(tf.float32, shape=()) self.assertEqual(f(x), x) #",
"3 self.assertAlmostEqual(sess.run(f(x), feed_dict={x:-0.25}), -0.2449, places=TestActivations.PLACES) def test_leaky_relu(self): f = lambda",
"places=TestActivations.PLACES) # Case 4 self.assertAlmostEqual(sess.run(f(x), feed_dict={x:-5}), -1, places=TestActivations.PLACES) def test_apply_activation(self):",
"lrelu_02 = lambda x: tflearn.leaky_relu(x, alpha=0.2) x = tf.constant(-0.25, tf.float32)",
"file contains test cases for tflearn ''' import tensorflow.compat.v1 as",
"= tflearn.linear # Case 1 x = tf.placeholder(tf.float32, shape=()) self.assertEqual(f(x),",
"tflearn.leaky_relu(x, alpha=0.2) x = tf.placeholder(tf.float32, shape=()) with tf.Session() as sess:",
"tf.Session() as sess: # Case 1: 'linear' self.assertEqual( sess.run(tflearn.activation(x, 'linear')),",
"sess: # Case 1: 'linear' self.assertEqual( sess.run(tflearn.activation(x, 'linear')), -0.25) #",
"# Case 5: lrelu_02 (callable) self.assertAlmostEqual( sess.run(tflearn.activation(x, lrelu_02)), -0.05, places=TestActivations.PLACES)",
"= tflearn.tanh x = tf.placeholder(tf.float32, shape=()) with tf.Session() as sess:",
"tflearn.tanh x = tf.placeholder(tf.float32, shape=()) with tf.Session() as sess: #",
"alpha=0.2) x = tf.placeholder(tf.float32, shape=()) with tf.Session() as sess: #",
"# Case 4 self.assertAlmostEqual(sess.run(f(x), feed_dict={x:-5}), -1, places=TestActivations.PLACES) def test_apply_activation(self): lrelu_02",
"places=TestActivations.PLACES) # Case 3 self.assertAlmostEqual(sess.run(f(x), feed_dict={x:-1}), -0.2, places=TestActivations.PLACES) # Case",
"functions in tflearn/activations.py ''' PLACES = 4 # Number of",
"Case 2 self.assertAlmostEqual(sess.run(f(x), feed_dict={x:0.5}), 0.4621, places=TestActivations.PLACES) # Case 3 self.assertAlmostEqual(sess.run(f(x),",
"self.assertEqual( sess.run(tflearn.activation(x, 'linear')), -0.25) # Case 2: 'relu' self.assertEqual( sess.run(tflearn.activation(x,",
"import tensorflow.compat.v1 as tf import tflearn import unittest class TestActivations(unittest.TestCase):",
"lambda x: tflearn.leaky_relu(x, alpha=0.2) x = tf.constant(-0.25, tf.float32) with tf.Session()",
"(callable) self.assertAlmostEqual( sess.run(tflearn.activation(x, lrelu_02)), -0.05, places=TestActivations.PLACES) if __name__ == \"__main__\":",
"shape=()) self.assertEqual(f(x), x) # Case 2 x = tf.placeholder(tf.int64, shape=())",
"places=TestActivations.PLACES) def test_apply_activation(self): lrelu_02 = lambda x: tflearn.leaky_relu(x, alpha=0.2) x",
"# Case 4: 'tanh' self.assertAlmostEqual( sess.run(tflearn.activation(x, 'tanh')), -0.2449, places=TestActivations.PLACES) #",
"feed_dict={x:0}), 0) # Case 2 self.assertAlmostEqual(sess.run(f(x), feed_dict={x:1}), 1, places=TestActivations.PLACES) #",
"x = tf.placeholder(tf.float32, shape=()) self.assertEqual(f(x), x) # Case 2 x",
"x = tf.placeholder(tf.int64, shape=()) self.assertEqual(f(x), x) def test_tanh(self): f =",
"''' This file contains test cases for tflearn ''' import",
"def test_leaky_relu(self): f = lambda x: tflearn.leaky_relu(x, alpha=0.2) x =",
"alpha=0.2) x = tf.constant(-0.25, tf.float32) with tf.Session() as sess: #",
"2 x = tf.placeholder(tf.int64, shape=()) self.assertEqual(f(x), x) def test_tanh(self): f",
"3 self.assertAlmostEqual(sess.run(f(x), feed_dict={x:-1}), -0.2, places=TestActivations.PLACES) # Case 4 self.assertAlmostEqual(sess.run(f(x), feed_dict={x:-5}),",
"floating point values def test_linear(self): f = tflearn.linear # Case",
"2 self.assertAlmostEqual(sess.run(f(x), feed_dict={x:1}), 1, places=TestActivations.PLACES) # Case 3 self.assertAlmostEqual(sess.run(f(x), feed_dict={x:-1}),",
"self.assertEqual(f(x), x) def test_tanh(self): f = tflearn.tanh x = tf.placeholder(tf.float32,",
"3: 'leaky_relu' self.assertAlmostEqual( sess.run(tflearn.activation(x, 'leaky_relu')), -0.025, places=TestActivations.PLACES) # Case 4:",
"TestActivations(unittest.TestCase): ''' This class contains test cases for the functions",
"class contains test cases for the functions in tflearn/activations.py '''",
"'linear')), -0.25) # Case 2: 'relu' self.assertEqual( sess.run(tflearn.activation(x, 'relu')), 0)",
"contains test cases for the functions in tflearn/activations.py ''' PLACES",
"This class contains test cases for the functions in tflearn/activations.py",
"x) def test_tanh(self): f = tflearn.tanh x = tf.placeholder(tf.float32, shape=())",
"feed_dict={x:0}), 0) # Case 2 self.assertAlmostEqual(sess.run(f(x), feed_dict={x:0.5}), 0.4621, places=TestActivations.PLACES) #",
"values def test_linear(self): f = tflearn.linear # Case 1 x",
"= lambda x: tflearn.leaky_relu(x, alpha=0.2) x = tf.placeholder(tf.float32, shape=()) with",
"# Case 3 self.assertAlmostEqual(sess.run(f(x), feed_dict={x:-1}), -0.2, places=TestActivations.PLACES) # Case 4",
"feed_dict={x:1}), 1, places=TestActivations.PLACES) # Case 3 self.assertAlmostEqual(sess.run(f(x), feed_dict={x:-1}), -0.2, places=TestActivations.PLACES)",
"cases for the functions in tflearn/activations.py ''' PLACES = 4",
"testing floating point values def test_linear(self): f = tflearn.linear #",
"sess.run(tflearn.activation(x, 'relu')), 0) # Case 3: 'leaky_relu' self.assertAlmostEqual( sess.run(tflearn.activation(x, 'leaky_relu')),",
"places=TestActivations.PLACES) # Case 4: 'tanh' self.assertAlmostEqual( sess.run(tflearn.activation(x, 'tanh')), -0.2449, places=TestActivations.PLACES)",
"= tf.constant(-0.25, tf.float32) with tf.Session() as sess: # Case 1:",
"import unittest class TestActivations(unittest.TestCase): ''' This class contains test cases",
"tf.placeholder(tf.int64, shape=()) self.assertEqual(f(x), x) def test_tanh(self): f = tflearn.tanh x",
"-0.2449, places=TestActivations.PLACES) # Case 5: lrelu_02 (callable) self.assertAlmostEqual( sess.run(tflearn.activation(x, lrelu_02)),",
"places=TestActivations.PLACES) # Case 3 self.assertAlmostEqual(sess.run(f(x), feed_dict={x:-0.25}), -0.2449, places=TestActivations.PLACES) def test_leaky_relu(self):",
"when testing floating point values def test_linear(self): f = tflearn.linear",
"1 self.assertEqual(sess.run(f(x), feed_dict={x:0}), 0) # Case 2 self.assertAlmostEqual(sess.run(f(x), feed_dict={x:0.5}), 0.4621,",
"Case 1 x = tf.placeholder(tf.float32, shape=()) self.assertEqual(f(x), x) # Case",
"in tflearn/activations.py ''' PLACES = 4 # Number of places",
"x = tf.placeholder(tf.float32, shape=()) with tf.Session() as sess: # Case",
"feed_dict={x:-0.25}), -0.2449, places=TestActivations.PLACES) def test_leaky_relu(self): f = lambda x: tflearn.leaky_relu(x,",
"f = tflearn.tanh x = tf.placeholder(tf.float32, shape=()) with tf.Session() as",
"tensorflow.compat.v1 as tf import tflearn import unittest class TestActivations(unittest.TestCase): '''",
"Case 1: 'linear' self.assertEqual( sess.run(tflearn.activation(x, 'linear')), -0.25) # Case 2:",
"# Case 2 self.assertAlmostEqual(sess.run(f(x), feed_dict={x:0.5}), 0.4621, places=TestActivations.PLACES) # Case 3",
"1, places=TestActivations.PLACES) # Case 3 self.assertAlmostEqual(sess.run(f(x), feed_dict={x:-1}), -0.2, places=TestActivations.PLACES) #",
"f = lambda x: tflearn.leaky_relu(x, alpha=0.2) x = tf.placeholder(tf.float32, shape=())",
"0) # Case 2 self.assertAlmostEqual(sess.run(f(x), feed_dict={x:1}), 1, places=TestActivations.PLACES) # Case",
"4 self.assertAlmostEqual(sess.run(f(x), feed_dict={x:-5}), -1, places=TestActivations.PLACES) def test_apply_activation(self): lrelu_02 = lambda",
"sess: # Case 1 self.assertEqual(sess.run(f(x), feed_dict={x:0}), 0) # Case 2",
"self.assertAlmostEqual( sess.run(tflearn.activation(x, 'tanh')), -0.2449, places=TestActivations.PLACES) # Case 5: lrelu_02 (callable)",
"to match when testing floating point values def test_linear(self): f",
"def test_tanh(self): f = tflearn.tanh x = tf.placeholder(tf.float32, shape=()) with",
"self.assertAlmostEqual(sess.run(f(x), feed_dict={x:0.5}), 0.4621, places=TestActivations.PLACES) # Case 3 self.assertAlmostEqual(sess.run(f(x), feed_dict={x:-0.25}), -0.2449,",
"# Case 1: 'linear' self.assertEqual( sess.run(tflearn.activation(x, 'linear')), -0.25) # Case",
"= tf.placeholder(tf.float32, shape=()) self.assertEqual(f(x), x) # Case 2 x =",
"# Case 2: 'relu' self.assertEqual( sess.run(tflearn.activation(x, 'relu')), 0) # Case",
"feed_dict={x:-5}), -1, places=TestActivations.PLACES) def test_apply_activation(self): lrelu_02 = lambda x: tflearn.leaky_relu(x,",
"tflearn.leaky_relu(x, alpha=0.2) x = tf.constant(-0.25, tf.float32) with tf.Session() as sess:",
"cases for tflearn ''' import tensorflow.compat.v1 as tf import tflearn",
"Case 4: 'tanh' self.assertAlmostEqual( sess.run(tflearn.activation(x, 'tanh')), -0.2449, places=TestActivations.PLACES) # Case",
"This file contains test cases for tflearn ''' import tensorflow.compat.v1",
"4: 'tanh' self.assertAlmostEqual( sess.run(tflearn.activation(x, 'tanh')), -0.2449, places=TestActivations.PLACES) # Case 5:",
"places to match when testing floating point values def test_linear(self):",
"self.assertAlmostEqual( sess.run(tflearn.activation(x, lrelu_02)), -0.05, places=TestActivations.PLACES) if __name__ == \"__main__\": unittest.main()",
"-1, places=TestActivations.PLACES) def test_apply_activation(self): lrelu_02 = lambda x: tflearn.leaky_relu(x, alpha=0.2)",
"f = tflearn.linear # Case 1 x = tf.placeholder(tf.float32, shape=())",
"'linear' self.assertEqual( sess.run(tflearn.activation(x, 'linear')), -0.25) # Case 2: 'relu' self.assertEqual(",
"'relu')), 0) # Case 3: 'leaky_relu' self.assertAlmostEqual( sess.run(tflearn.activation(x, 'leaky_relu')), -0.025,",
"test cases for tflearn ''' import tensorflow.compat.v1 as tf import",
"test_apply_activation(self): lrelu_02 = lambda x: tflearn.leaky_relu(x, alpha=0.2) x = tf.constant(-0.25,",
"test_leaky_relu(self): f = lambda x: tflearn.leaky_relu(x, alpha=0.2) x = tf.placeholder(tf.float32,",
"sess.run(tflearn.activation(x, 'leaky_relu')), -0.025, places=TestActivations.PLACES) # Case 4: 'tanh' self.assertAlmostEqual( sess.run(tflearn.activation(x,",
"4 # Number of places to match when testing floating",
"-0.2449, places=TestActivations.PLACES) def test_leaky_relu(self): f = lambda x: tflearn.leaky_relu(x, alpha=0.2)",
"lambda x: tflearn.leaky_relu(x, alpha=0.2) x = tf.placeholder(tf.float32, shape=()) with tf.Session()",
"= tf.placeholder(tf.int64, shape=()) self.assertEqual(f(x), x) def test_tanh(self): f = tflearn.tanh",
"self.assertEqual(sess.run(f(x), feed_dict={x:0}), 0) # Case 2 self.assertAlmostEqual(sess.run(f(x), feed_dict={x:1}), 1, places=TestActivations.PLACES)",
"as sess: # Case 1: 'linear' self.assertEqual( sess.run(tflearn.activation(x, 'linear')), -0.25)",
"Case 3: 'leaky_relu' self.assertAlmostEqual( sess.run(tflearn.activation(x, 'leaky_relu')), -0.025, places=TestActivations.PLACES) # Case",
"tflearn.linear # Case 1 x = tf.placeholder(tf.float32, shape=()) self.assertEqual(f(x), x)",
"self.assertEqual(f(x), x) # Case 2 x = tf.placeholder(tf.int64, shape=()) self.assertEqual(f(x),",
"self.assertAlmostEqual( sess.run(tflearn.activation(x, 'leaky_relu')), -0.025, places=TestActivations.PLACES) # Case 4: 'tanh' self.assertAlmostEqual(",
"# Case 2 x = tf.placeholder(tf.int64, shape=()) self.assertEqual(f(x), x) def",
"test_tanh(self): f = tflearn.tanh x = tf.placeholder(tf.float32, shape=()) with tf.Session()",
"class TestActivations(unittest.TestCase): ''' This class contains test cases for the",
"the functions in tflearn/activations.py ''' PLACES = 4 # Number",
"0) # Case 3: 'leaky_relu' self.assertAlmostEqual( sess.run(tflearn.activation(x, 'leaky_relu')), -0.025, places=TestActivations.PLACES)",
"test_linear(self): f = tflearn.linear # Case 1 x = tf.placeholder(tf.float32,",
"tf import tflearn import unittest class TestActivations(unittest.TestCase): ''' This class",
"2 self.assertAlmostEqual(sess.run(f(x), feed_dict={x:0.5}), 0.4621, places=TestActivations.PLACES) # Case 3 self.assertAlmostEqual(sess.run(f(x), feed_dict={x:-0.25}),",
"# Case 2 self.assertAlmostEqual(sess.run(f(x), feed_dict={x:1}), 1, places=TestActivations.PLACES) # Case 3",
"5: lrelu_02 (callable) self.assertAlmostEqual( sess.run(tflearn.activation(x, lrelu_02)), -0.05, places=TestActivations.PLACES) if __name__",
"tf.placeholder(tf.float32, shape=()) self.assertEqual(f(x), x) # Case 2 x = tf.placeholder(tf.int64,",
"tflearn ''' import tensorflow.compat.v1 as tf import tflearn import unittest",
"self.assertAlmostEqual(sess.run(f(x), feed_dict={x:1}), 1, places=TestActivations.PLACES) # Case 3 self.assertAlmostEqual(sess.run(f(x), feed_dict={x:-1}), -0.2,",
"tf.float32) with tf.Session() as sess: # Case 1: 'linear' self.assertEqual(",
"def test_apply_activation(self): lrelu_02 = lambda x: tflearn.leaky_relu(x, alpha=0.2) x =",
"0.4621, places=TestActivations.PLACES) # Case 3 self.assertAlmostEqual(sess.run(f(x), feed_dict={x:-0.25}), -0.2449, places=TestActivations.PLACES) def",
"sess.run(tflearn.activation(x, 'tanh')), -0.2449, places=TestActivations.PLACES) # Case 5: lrelu_02 (callable) self.assertAlmostEqual(",
"Case 3 self.assertAlmostEqual(sess.run(f(x), feed_dict={x:-0.25}), -0.2449, places=TestActivations.PLACES) def test_leaky_relu(self): f =",
"shape=()) with tf.Session() as sess: # Case 1 self.assertEqual(sess.run(f(x), feed_dict={x:0}),",
"PLACES = 4 # Number of places to match when",
"''' import tensorflow.compat.v1 as tf import tflearn import unittest class",
"# Case 3: 'leaky_relu' self.assertAlmostEqual( sess.run(tflearn.activation(x, 'leaky_relu')), -0.025, places=TestActivations.PLACES) #",
"-0.2, places=TestActivations.PLACES) # Case 4 self.assertAlmostEqual(sess.run(f(x), feed_dict={x:-5}), -1, places=TestActivations.PLACES) def",
"''' This class contains test cases for the functions in",
"''' PLACES = 4 # Number of places to match",
"1 x = tf.placeholder(tf.float32, shape=()) self.assertEqual(f(x), x) # Case 2",
"tf.constant(-0.25, tf.float32) with tf.Session() as sess: # Case 1: 'linear'",
"Case 1 self.assertEqual(sess.run(f(x), feed_dict={x:0}), 0) # Case 2 self.assertAlmostEqual(sess.run(f(x), feed_dict={x:1}),",
"test cases for the functions in tflearn/activations.py ''' PLACES =",
"sess.run(tflearn.activation(x, 'linear')), -0.25) # Case 2: 'relu' self.assertEqual( sess.run(tflearn.activation(x, 'relu')),",
"'leaky_relu' self.assertAlmostEqual( sess.run(tflearn.activation(x, 'leaky_relu')), -0.025, places=TestActivations.PLACES) # Case 4: 'tanh'",
"Case 5: lrelu_02 (callable) self.assertAlmostEqual( sess.run(tflearn.activation(x, lrelu_02)), -0.05, places=TestActivations.PLACES) if",
"# Case 3 self.assertAlmostEqual(sess.run(f(x), feed_dict={x:-0.25}), -0.2449, places=TestActivations.PLACES) def test_leaky_relu(self): f",
"2: 'relu' self.assertEqual( sess.run(tflearn.activation(x, 'relu')), 0) # Case 3: 'leaky_relu'"
] |
[
"# # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law",
"OF ANY # KIND, either express or implied. See the",
"if __name__ == \"__main__\": success = True try: subprocess.run('cd /root;",
"Software Foundation (ASF) under one # or more contributor license",
"more contributor license agreements. See the NOTICE file # distributed",
"Unless required by applicable law or agreed to in writing,",
"os.environ['request_id']) with open(\"/response/{}_{}_{}.json\".format(os.environ['conf_resource'], os.environ['project_name'], os.environ['request_id']), 'w') as response_file: response_file.write(json.dumps(reply)) try:",
"an # \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF",
"# regarding copyright ownership. The ASF licenses this file #",
"Apache Software Foundation (ASF) under one # or more contributor",
"reply = dict() reply['request_id'] = os.environ['request_id'] if success: reply['status'] =",
"try: subprocess.run('chmod 666 /response/*', shell=True, check=True) except: success = False",
"in compliance # with the License. You may obtain a",
"# to you under the Apache License, Version 2.0 (the",
"WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express",
"License for the # specific language governing permissions and limitations",
"WARRANTIES OR CONDITIONS OF ANY # KIND, either express or",
"and limitations # under the License. # # ****************************************************************************** import",
"with this work for additional information # regarding copyright ownership.",
"666 /response/*', shell=True, check=True) except: success = False if not",
"(ASF) under one # or more contributor license agreements. See",
"2.0 (the # \"License\"); you may not use this file",
"OR CONDITIONS OF ANY # KIND, either express or implied.",
"limitations # under the License. # # ****************************************************************************** import json",
"# under the License. # # ****************************************************************************** import json import",
"# or more contributor license agreements. See the NOTICE file",
"agreed to in writing, # software distributed under the License",
"#!/usr/bin/python3 # ***************************************************************************** # # Licensed to the Apache Software",
"reply['response']['result'] = json.loads(f.read()) except: reply['response']['result'] = {\"error\": \"Failed to open",
"of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless",
"work for additional information # regarding copyright ownership. The ASF",
"dict() try: with open(\"/root/result.json\") as f: reply['response']['result'] = json.loads(f.read()) except:",
"os.environ['project_name'], os.environ['request_id']), 'w') as response_file: response_file.write(json.dumps(reply)) try: subprocess.run('chmod 666 /response/*',",
"specific language governing permissions and limitations # under the License.",
"\"Failed to open result.json\"} reply['response']['log'] = \"/var/log/datalab/{0}/{0}_{1}_{2}.log\".format(os.environ['conf_resource'], os.environ['project_name'], os.environ['request_id']) with",
"under the License is distributed on an # \"AS IS\"",
"try: subprocess.run('cd /root; fab install-libs', shell=True, check=True) except: success =",
"this file # to you under the Apache License, Version",
"'err' reply['response'] = dict() try: with open(\"/root/result.json\") as f: reply['response']['result']",
"distributed under the License is distributed on an # \"AS",
"as response_file: response_file.write(json.dumps(reply)) try: subprocess.run('chmod 666 /response/*', shell=True, check=True) except:",
"BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either",
"# ***************************************************************************** # # Licensed to the Apache Software Foundation",
"copyright ownership. The ASF licenses this file # to you",
"False reply = dict() reply['request_id'] = os.environ['request_id'] if success: reply['status']",
"reply['status'] = 'err' reply['response'] = dict() try: with open(\"/root/result.json\") as",
"reply['response'] = dict() try: with open(\"/root/result.json\") as f: reply['response']['result'] =",
"# software distributed under the License is distributed on an",
"# # ****************************************************************************** import json import os import sys import",
"success = True try: subprocess.run('cd /root; fab install-libs', shell=True, check=True)",
"\"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY #",
"= 'err' reply['response'] = dict() try: with open(\"/root/result.json\") as f:",
"(the # \"License\"); you may not use this file except",
"the License. You may obtain a copy of the License",
"in writing, # software distributed under the License is distributed",
"= \"/var/log/datalab/{0}/{0}_{1}_{2}.log\".format(os.environ['conf_resource'], os.environ['project_name'], os.environ['request_id']) with open(\"/response/{}_{}_{}.json\".format(os.environ['conf_resource'], os.environ['project_name'], os.environ['request_id']), 'w') as",
"distributed with this work for additional information # regarding copyright",
"= json.loads(f.read()) except: reply['response']['result'] = {\"error\": \"Failed to open result.json\"}",
"http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed",
"License is distributed on an # \"AS IS\" BASIS, WITHOUT",
"ASF licenses this file # to you under the Apache",
"under the Apache License, Version 2.0 (the # \"License\"); you",
"for the # specific language governing permissions and limitations #",
"os.environ['project_name'], os.environ['request_id']) with open(\"/response/{}_{}_{}.json\".format(os.environ['conf_resource'], os.environ['project_name'], os.environ['request_id']), 'w') as response_file: response_file.write(json.dumps(reply))",
"import subprocess if __name__ == \"__main__\": success = True try:",
"distributed on an # \"AS IS\" BASIS, WITHOUT WARRANTIES OR",
"on an # \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS",
"regarding copyright ownership. The ASF licenses this file # to",
"\"/var/log/datalab/{0}/{0}_{1}_{2}.log\".format(os.environ['conf_resource'], os.environ['project_name'], os.environ['request_id']) with open(\"/response/{}_{}_{}.json\".format(os.environ['conf_resource'], os.environ['project_name'], os.environ['request_id']), 'w') as response_file:",
"See the License for the # specific language governing permissions",
"to in writing, # software distributed under the License is",
"or agreed to in writing, # software distributed under the",
"the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required",
"json.loads(f.read()) except: reply['response']['result'] = {\"error\": \"Failed to open result.json\"} reply['response']['log']",
"ownership. The ASF licenses this file # to you under",
"to open result.json\"} reply['response']['log'] = \"/var/log/datalab/{0}/{0}_{1}_{2}.log\".format(os.environ['conf_resource'], os.environ['project_name'], os.environ['request_id']) with open(\"/response/{}_{}_{}.json\".format(os.environ['conf_resource'],",
"import json import os import sys import subprocess if __name__",
"# ****************************************************************************** import json import os import sys import subprocess",
"with open(\"/root/result.json\") as f: reply['response']['result'] = json.loads(f.read()) except: reply['response']['result'] =",
"# \"License\"); you may not use this file except in",
"under the License. # # ****************************************************************************** import json import os",
"# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY",
"to the Apache Software Foundation (ASF) under one # or",
"os.environ['request_id']), 'w') as response_file: response_file.write(json.dumps(reply)) try: subprocess.run('chmod 666 /response/*', shell=True,",
"\"License\"); you may not use this file except in compliance",
"file # distributed with this work for additional information #",
"copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # #",
"open(\"/root/result.json\") as f: reply['response']['result'] = json.loads(f.read()) except: reply['response']['result'] = {\"error\":",
"subprocess.run('chmod 666 /response/*', shell=True, check=True) except: success = False if",
"/response/*', shell=True, check=True) except: success = False if not success:",
"== \"__main__\": success = True try: subprocess.run('cd /root; fab install-libs',",
"with the License. You may obtain a copy of the",
"License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by",
"or more contributor license agreements. See the NOTICE file #",
"***************************************************************************** # # Licensed to the Apache Software Foundation (ASF)",
"= False reply = dict() reply['request_id'] = os.environ['request_id'] if success:",
"applicable law or agreed to in writing, # software distributed",
"# distributed with this work for additional information # regarding",
"this work for additional information # regarding copyright ownership. The",
"writing, # software distributed under the License is distributed on",
"check=True) except: success = False reply = dict() reply['request_id'] =",
"the NOTICE file # distributed with this work for additional",
"reply['response']['result'] = {\"error\": \"Failed to open result.json\"} reply['response']['log'] = \"/var/log/datalab/{0}/{0}_{1}_{2}.log\".format(os.environ['conf_resource'],",
"= os.environ['request_id'] if success: reply['status'] = 'ok' else: reply['status'] =",
"is distributed on an # \"AS IS\" BASIS, WITHOUT WARRANTIES",
"implied. See the License for the # specific language governing",
"file # to you under the Apache License, Version 2.0",
"to you under the Apache License, Version 2.0 (the #",
"json import os import sys import subprocess if __name__ ==",
"CONDITIONS OF ANY # KIND, either express or implied. See",
"try: with open(\"/root/result.json\") as f: reply['response']['result'] = json.loads(f.read()) except: reply['response']['result']",
"# with the License. You may obtain a copy of",
"# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or",
"/root; fab install-libs', shell=True, check=True) except: success = False reply",
"language governing permissions and limitations # under the License. #",
"permissions and limitations # under the License. # # ******************************************************************************",
"may not use this file except in compliance # with",
"with open(\"/response/{}_{}_{}.json\".format(os.environ['conf_resource'], os.environ['project_name'], os.environ['request_id']), 'w') as response_file: response_file.write(json.dumps(reply)) try: subprocess.run('chmod",
"software distributed under the License is distributed on an #",
"Licensed to the Apache Software Foundation (ASF) under one #",
"for additional information # regarding copyright ownership. The ASF licenses",
"fab install-libs', shell=True, check=True) except: success = False reply =",
"the Apache Software Foundation (ASF) under one # or more",
"the License. # # ****************************************************************************** import json import os import",
"# # Unless required by applicable law or agreed to",
"'w') as response_file: response_file.write(json.dumps(reply)) try: subprocess.run('chmod 666 /response/*', shell=True, check=True)",
"Version 2.0 (the # \"License\"); you may not use this",
"under one # or more contributor license agreements. See the",
"one # or more contributor license agreements. See the NOTICE",
"License, Version 2.0 (the # \"License\"); you may not use",
"a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 #",
"either express or implied. See the License for the #",
"obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0",
"if success: reply['status'] = 'ok' else: reply['status'] = 'err' reply['response']",
"as f: reply['response']['result'] = json.loads(f.read()) except: reply['response']['result'] = {\"error\": \"Failed",
"KIND, either express or implied. See the License for the",
"****************************************************************************** import json import os import sys import subprocess if",
"information # regarding copyright ownership. The ASF licenses this file",
"response_file: response_file.write(json.dumps(reply)) try: subprocess.run('chmod 666 /response/*', shell=True, check=True) except: success",
"the Apache License, Version 2.0 (the # \"License\"); you may",
"__name__ == \"__main__\": success = True try: subprocess.run('cd /root; fab",
"response_file.write(json.dumps(reply)) try: subprocess.run('chmod 666 /response/*', shell=True, check=True) except: success =",
"shell=True, check=True) except: success = False if not success: sys.exit(1)",
"f: reply['response']['result'] = json.loads(f.read()) except: reply['response']['result'] = {\"error\": \"Failed to",
"except in compliance # with the License. You may obtain",
"additional information # regarding copyright ownership. The ASF licenses this",
"True try: subprocess.run('cd /root; fab install-libs', shell=True, check=True) except: success",
"reply['status'] = 'ok' else: reply['status'] = 'err' reply['response'] = dict()",
"you under the Apache License, Version 2.0 (the # \"License\");",
"= dict() reply['request_id'] = os.environ['request_id'] if success: reply['status'] = 'ok'",
"else: reply['status'] = 'err' reply['response'] = dict() try: with open(\"/root/result.json\")",
"= dict() try: with open(\"/root/result.json\") as f: reply['response']['result'] = json.loads(f.read())",
"or implied. See the License for the # specific language",
"See the NOTICE file # distributed with this work for",
"# KIND, either express or implied. See the License for",
"express or implied. See the License for the # specific",
"= 'ok' else: reply['status'] = 'err' reply['response'] = dict() try:",
"NOTICE file # distributed with this work for additional information",
"subprocess.run('cd /root; fab install-libs', shell=True, check=True) except: success = False",
"open(\"/response/{}_{}_{}.json\".format(os.environ['conf_resource'], os.environ['project_name'], os.environ['request_id']), 'w') as response_file: response_file.write(json.dumps(reply)) try: subprocess.run('chmod 666",
"this file except in compliance # with the License. You",
"reply['response']['log'] = \"/var/log/datalab/{0}/{0}_{1}_{2}.log\".format(os.environ['conf_resource'], os.environ['project_name'], os.environ['request_id']) with open(\"/response/{}_{}_{}.json\".format(os.environ['conf_resource'], os.environ['project_name'], os.environ['request_id']), 'w')",
"agreements. See the NOTICE file # distributed with this work",
"Apache License, Version 2.0 (the # \"License\"); you may not",
"the # specific language governing permissions and limitations # under",
"licenses this file # to you under the Apache License,",
"import os import sys import subprocess if __name__ == \"__main__\":",
"os import sys import subprocess if __name__ == \"__main__\": success",
"license agreements. See the NOTICE file # distributed with this",
"sys import subprocess if __name__ == \"__main__\": success = True",
"success: reply['status'] = 'ok' else: reply['status'] = 'err' reply['response'] =",
"= True try: subprocess.run('cd /root; fab install-libs', shell=True, check=True) except:",
"required by applicable law or agreed to in writing, #",
"success = False reply = dict() reply['request_id'] = os.environ['request_id'] if",
"by applicable law or agreed to in writing, # software",
"may obtain a copy of the License at # #",
"# Unless required by applicable law or agreed to in",
"open result.json\"} reply['response']['log'] = \"/var/log/datalab/{0}/{0}_{1}_{2}.log\".format(os.environ['conf_resource'], os.environ['project_name'], os.environ['request_id']) with open(\"/response/{}_{}_{}.json\".format(os.environ['conf_resource'], os.environ['project_name'],",
"except: success = False reply = dict() reply['request_id'] = os.environ['request_id']",
"import sys import subprocess if __name__ == \"__main__\": success =",
"at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable",
"The ASF licenses this file # to you under the",
"License. # # ****************************************************************************** import json import os import sys",
"file except in compliance # with the License. You may",
"IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND,",
"subprocess if __name__ == \"__main__\": success = True try: subprocess.run('cd",
"# specific language governing permissions and limitations # under the",
"'ok' else: reply['status'] = 'err' reply['response'] = dict() try: with",
"the License for the # specific language governing permissions and",
"License. You may obtain a copy of the License at",
"You may obtain a copy of the License at #",
"ANY # KIND, either express or implied. See the License",
"# Licensed to the Apache Software Foundation (ASF) under one",
"the License is distributed on an # \"AS IS\" BASIS,",
"dict() reply['request_id'] = os.environ['request_id'] if success: reply['status'] = 'ok' else:",
"you may not use this file except in compliance #",
"install-libs', shell=True, check=True) except: success = False reply = dict()",
"reply['request_id'] = os.environ['request_id'] if success: reply['status'] = 'ok' else: reply['status']",
"\"__main__\": success = True try: subprocess.run('cd /root; fab install-libs', shell=True,",
"use this file except in compliance # with the License.",
"compliance # with the License. You may obtain a copy",
"# # Licensed to the Apache Software Foundation (ASF) under",
"shell=True, check=True) except: success = False reply = dict() reply['request_id']",
"{\"error\": \"Failed to open result.json\"} reply['response']['log'] = \"/var/log/datalab/{0}/{0}_{1}_{2}.log\".format(os.environ['conf_resource'], os.environ['project_name'], os.environ['request_id'])",
"os.environ['request_id'] if success: reply['status'] = 'ok' else: reply['status'] = 'err'",
"law or agreed to in writing, # software distributed under",
"contributor license agreements. See the NOTICE file # distributed with",
"= {\"error\": \"Failed to open result.json\"} reply['response']['log'] = \"/var/log/datalab/{0}/{0}_{1}_{2}.log\".format(os.environ['conf_resource'], os.environ['project_name'],",
"Foundation (ASF) under one # or more contributor license agreements.",
"except: reply['response']['result'] = {\"error\": \"Failed to open result.json\"} reply['response']['log'] =",
"governing permissions and limitations # under the License. # #",
"not use this file except in compliance # with the",
"result.json\"} reply['response']['log'] = \"/var/log/datalab/{0}/{0}_{1}_{2}.log\".format(os.environ['conf_resource'], os.environ['project_name'], os.environ['request_id']) with open(\"/response/{}_{}_{}.json\".format(os.environ['conf_resource'], os.environ['project_name'], os.environ['request_id']),"
] |
[
"# # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law",
"# # Licensed under the Apache License, Version 2.0 (the",
"compliance with the License. # You may obtain a copy",
"an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF",
"2.0 (the \"License\"); # you may not use this file",
"agreed to in writing, software # distributed under the License",
"file except in compliance with the License. # You may",
"on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS",
"Unless required by applicable law or agreed to in writing,",
"distributed under the License is distributed on an \"AS IS\"",
"License. # ============================================================================ \"\"\" config settings, will be used in",
"'use_crf': False, 'clue_benchmark': False, }) bert_net_cfg = BertConfig( batch_size=8 if",
"Technologies Co., Ltd # # Licensed under the Apache License,",
"the specific language governing permissions and # limitations under the",
"'task': 'NER', 'num_labels': 41, 'data_file': '', 'schema_file': None, 'finetune_ckpt': '',",
"# limitations under the License. # ============================================================================ \"\"\" config settings,",
"# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express",
"vocab_size=30522, hidden_size=1024, num_hidden_layers=24, num_attention_heads=16, intermediate_size=4096, hidden_act=\"gelu\", hidden_dropout_prob=0.0, attention_probs_dropout_prob=0.0, max_position_embeddings=512, type_vocab_size=2,",
"batch_size=8 if not cfg.clue_benchmark else 1, seq_length=512, vocab_size=30522, hidden_size=1024, num_hidden_layers=24,",
"express or implied. # See the License for the specific",
"applicable law or agreed to in writing, software # distributed",
"1, seq_length=512, vocab_size=30522, hidden_size=1024, num_hidden_layers=24, num_attention_heads=16, intermediate_size=4096, hidden_act=\"gelu\", hidden_dropout_prob=0.0, attention_probs_dropout_prob=0.0,",
"except in compliance with the License. # You may obtain",
"of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless",
"as mstype from .bert_model import BertConfig cfg = edict({ 'task':",
"Licensed under the Apache License, Version 2.0 (the \"License\"); #",
"============================================================================ \"\"\" config settings, will be used in finetune.py \"\"\"",
"not use this file except in compliance with the License.",
"permissions and # limitations under the License. # ============================================================================ \"\"\"",
"writing, software # distributed under the License is distributed on",
"intermediate_size=4096, hidden_act=\"gelu\", hidden_dropout_prob=0.0, attention_probs_dropout_prob=0.0, max_position_embeddings=512, type_vocab_size=2, initializer_range=0.02, use_relative_positions=False, input_mask_from_dataset=True, token_type_ids_from_dataset=True,",
"in writing, software # distributed under the License is distributed",
"you may not use this file except in compliance with",
"# Licensed under the Apache License, Version 2.0 (the \"License\");",
"if not cfg.clue_benchmark else 1, seq_length=512, vocab_size=30522, hidden_size=1024, num_hidden_layers=24, num_attention_heads=16,",
"else 1, seq_length=512, vocab_size=30522, hidden_size=1024, num_hidden_layers=24, num_attention_heads=16, intermediate_size=4096, hidden_act=\"gelu\", hidden_dropout_prob=0.0,",
"use this file except in compliance with the License. #",
"41, 'data_file': '', 'schema_file': None, 'finetune_ckpt': '', 'use_crf': False, 'clue_benchmark':",
"http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed",
"'clue_benchmark': False, }) bert_net_cfg = BertConfig( batch_size=8 if not cfg.clue_benchmark",
"CONDITIONS OF ANY KIND, either express or implied. # See",
"Ltd # # Licensed under the Apache License, Version 2.0",
"the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required",
"and # limitations under the License. # ============================================================================ \"\"\" config",
"not cfg.clue_benchmark else 1, seq_length=512, vocab_size=30522, hidden_size=1024, num_hidden_layers=24, num_attention_heads=16, intermediate_size=4096,",
"or implied. # See the License for the specific language",
"License is distributed on an \"AS IS\" BASIS, # WITHOUT",
"License. # You may obtain a copy of the License",
"is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES",
"License, Version 2.0 (the \"License\"); # you may not use",
"edict import mindspore.common.dtype as mstype from .bert_model import BertConfig cfg",
"'num_labels': 41, 'data_file': '', 'schema_file': None, 'finetune_ckpt': '', 'use_crf': False,",
"# You may obtain a copy of the License at",
"import BertConfig cfg = edict({ 'task': 'NER', 'num_labels': 41, 'data_file':",
"KIND, either express or implied. # See the License for",
"specific language governing permissions and # limitations under the License.",
"# Copyright 2020 Huawei Technologies Co., Ltd # # Licensed",
"from easydict import EasyDict as edict import mindspore.common.dtype as mstype",
"under the License is distributed on an \"AS IS\" BASIS,",
"the License. # ============================================================================ \"\"\" config settings, will be used",
"copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # #",
"License for the specific language governing permissions and # limitations",
"# ============================================================================ \"\"\" config settings, will be used in finetune.py",
"import EasyDict as edict import mindspore.common.dtype as mstype from .bert_model",
"License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by",
"will be used in finetune.py \"\"\" from easydict import EasyDict",
"\"\"\" config settings, will be used in finetune.py \"\"\" from",
"False, }) bert_net_cfg = BertConfig( batch_size=8 if not cfg.clue_benchmark else",
"limitations under the License. # ============================================================================ \"\"\" config settings, will",
"used in finetune.py \"\"\" from easydict import EasyDict as edict",
"'NER', 'num_labels': 41, 'data_file': '', 'schema_file': None, 'finetune_ckpt': '', 'use_crf':",
"mstype from .bert_model import BertConfig cfg = edict({ 'task': 'NER',",
"the License for the specific language governing permissions and #",
"(the \"License\"); # you may not use this file except",
"hidden_act=\"gelu\", hidden_dropout_prob=0.0, attention_probs_dropout_prob=0.0, max_position_embeddings=512, type_vocab_size=2, initializer_range=0.02, use_relative_positions=False, input_mask_from_dataset=True, token_type_ids_from_dataset=True, dtype=mstype.float32,",
"Apache License, Version 2.0 (the \"License\"); # you may not",
"# you may not use this file except in compliance",
".bert_model import BertConfig cfg = edict({ 'task': 'NER', 'num_labels': 41,",
"either express or implied. # See the License for the",
"'schema_file': None, 'finetune_ckpt': '', 'use_crf': False, 'clue_benchmark': False, }) bert_net_cfg",
"OR CONDITIONS OF ANY KIND, either express or implied. #",
"# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or",
"from .bert_model import BertConfig cfg = edict({ 'task': 'NER', 'num_labels':",
"the License is distributed on an \"AS IS\" BASIS, #",
"in compliance with the License. # You may obtain a",
"software # distributed under the License is distributed on an",
"import mindspore.common.dtype as mstype from .bert_model import BertConfig cfg =",
"= edict({ 'task': 'NER', 'num_labels': 41, 'data_file': '', 'schema_file': None,",
"finetune.py \"\"\" from easydict import EasyDict as edict import mindspore.common.dtype",
"under the License. # ============================================================================ \"\"\" config settings, will be",
"'', 'use_crf': False, 'clue_benchmark': False, }) bert_net_cfg = BertConfig( batch_size=8",
"= BertConfig( batch_size=8 if not cfg.clue_benchmark else 1, seq_length=512, vocab_size=30522,",
"Huawei Technologies Co., Ltd # # Licensed under the Apache",
"# # Unless required by applicable law or agreed to",
"'', 'schema_file': None, 'finetune_ckpt': '', 'use_crf': False, 'clue_benchmark': False, })",
"in finetune.py \"\"\" from easydict import EasyDict as edict import",
"a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 #",
"obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0",
"}) bert_net_cfg = BertConfig( batch_size=8 if not cfg.clue_benchmark else 1,",
"Version 2.0 (the \"License\"); # you may not use this",
"settings, will be used in finetune.py \"\"\" from easydict import",
"seq_length=512, vocab_size=30522, hidden_size=1024, num_hidden_layers=24, num_attention_heads=16, intermediate_size=4096, hidden_act=\"gelu\", hidden_dropout_prob=0.0, attention_probs_dropout_prob=0.0, max_position_embeddings=512,",
"law or agreed to in writing, software # distributed under",
"Co., Ltd # # Licensed under the Apache License, Version",
"num_attention_heads=16, intermediate_size=4096, hidden_act=\"gelu\", hidden_dropout_prob=0.0, attention_probs_dropout_prob=0.0, max_position_embeddings=512, type_vocab_size=2, initializer_range=0.02, use_relative_positions=False, input_mask_from_dataset=True,",
"implied. # See the License for the specific language governing",
"EasyDict as edict import mindspore.common.dtype as mstype from .bert_model import",
"hidden_dropout_prob=0.0, attention_probs_dropout_prob=0.0, max_position_embeddings=512, type_vocab_size=2, initializer_range=0.02, use_relative_positions=False, input_mask_from_dataset=True, token_type_ids_from_dataset=True, dtype=mstype.float32, compute_type=mstype.float16,",
"under the Apache License, Version 2.0 (the \"License\"); # you",
"cfg = edict({ 'task': 'NER', 'num_labels': 41, 'data_file': '', 'schema_file':",
"\"License\"); # you may not use this file except in",
"distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR",
"hidden_size=1024, num_hidden_layers=24, num_attention_heads=16, intermediate_size=4096, hidden_act=\"gelu\", hidden_dropout_prob=0.0, attention_probs_dropout_prob=0.0, max_position_embeddings=512, type_vocab_size=2, initializer_range=0.02,",
"by applicable law or agreed to in writing, software #",
"# distributed under the License is distributed on an \"AS",
"OF ANY KIND, either express or implied. # See the",
"WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.",
"False, 'clue_benchmark': False, }) bert_net_cfg = BertConfig( batch_size=8 if not",
"2020 Huawei Technologies Co., Ltd # # Licensed under the",
"may obtain a copy of the License at # #",
"# Unless required by applicable law or agreed to in",
"ANY KIND, either express or implied. # See the License",
"See the License for the specific language governing permissions and",
"config settings, will be used in finetune.py \"\"\" from easydict",
"as edict import mindspore.common.dtype as mstype from .bert_model import BertConfig",
"'finetune_ckpt': '', 'use_crf': False, 'clue_benchmark': False, }) bert_net_cfg = BertConfig(",
"attention_probs_dropout_prob=0.0, max_position_embeddings=512, type_vocab_size=2, initializer_range=0.02, use_relative_positions=False, input_mask_from_dataset=True, token_type_ids_from_dataset=True, dtype=mstype.float32, compute_type=mstype.float16, )",
"Copyright 2020 Huawei Technologies Co., Ltd # # Licensed under",
"the License. # You may obtain a copy of the",
"at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable",
"for the specific language governing permissions and # limitations under",
"\"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY",
"to in writing, software # distributed under the License is",
"'data_file': '', 'schema_file': None, 'finetune_ckpt': '', 'use_crf': False, 'clue_benchmark': False,",
"easydict import EasyDict as edict import mindspore.common.dtype as mstype from",
"IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,",
"# See the License for the specific language governing permissions",
"edict({ 'task': 'NER', 'num_labels': 41, 'data_file': '', 'schema_file': None, 'finetune_ckpt':",
"You may obtain a copy of the License at #",
"language governing permissions and # limitations under the License. #",
"may not use this file except in compliance with the",
"or agreed to in writing, software # distributed under the",
"mindspore.common.dtype as mstype from .bert_model import BertConfig cfg = edict({",
"required by applicable law or agreed to in writing, software",
"\"\"\" from easydict import EasyDict as edict import mindspore.common.dtype as",
"BertConfig( batch_size=8 if not cfg.clue_benchmark else 1, seq_length=512, vocab_size=30522, hidden_size=1024,",
"BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either",
"WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or",
"with the License. # You may obtain a copy of",
"num_hidden_layers=24, num_attention_heads=16, intermediate_size=4096, hidden_act=\"gelu\", hidden_dropout_prob=0.0, attention_probs_dropout_prob=0.0, max_position_embeddings=512, type_vocab_size=2, initializer_range=0.02, use_relative_positions=False,",
"this file except in compliance with the License. # You",
"the Apache License, Version 2.0 (the \"License\"); # you may",
"bert_net_cfg = BertConfig( batch_size=8 if not cfg.clue_benchmark else 1, seq_length=512,",
"be used in finetune.py \"\"\" from easydict import EasyDict as",
"BertConfig cfg = edict({ 'task': 'NER', 'num_labels': 41, 'data_file': '',",
"cfg.clue_benchmark else 1, seq_length=512, vocab_size=30522, hidden_size=1024, num_hidden_layers=24, num_attention_heads=16, intermediate_size=4096, hidden_act=\"gelu\",",
"governing permissions and # limitations under the License. # ============================================================================",
"None, 'finetune_ckpt': '', 'use_crf': False, 'clue_benchmark': False, }) bert_net_cfg ="
] |
[
"from django.db.utils import IntegrityError from apps import core_articleviewedby_mdb from core.models",
"utopia-cms 2020. <NAME>. from django.core.management import BaseCommand from django.db.utils import",
"except ArticleViewedBy.DoesNotExist: try: ArticleViewedBy.objects.create( article_id=mdb_view['article'], user_id=mdb_view['user'], viewed_at=mdb_view['viewed_at']) except IntegrityError: pass",
"from core.models import ArticleViewedBy class Command(BaseCommand): help = \"Moves article",
"coding: utf-8 -*- # utopia-cms 2020. <NAME>. from django.core.management import",
"ArticleViewedBy.objects.get(article=mdb_view['article'], user=mdb_view['user']) avb.viewed_at = mdb_view['viewed_at'] avb.save() except ArticleViewedBy.DoesNotExist: try: ArticleViewedBy.objects.create(",
"= \"Moves article viewed by data from mongodb to Django",
"**options): mdb_view = core_articleviewedby_mdb.posts.find_one_and_delete({}) while mdb_view: try: avb = ArticleViewedBy.objects.get(article=mdb_view['article'],",
"Django model\" def handle(self, *args, **options): mdb_view = core_articleviewedby_mdb.posts.find_one_and_delete({}) while",
"viewed by data from mongodb to Django model\" def handle(self,",
"mdb_view = core_articleviewedby_mdb.posts.find_one_and_delete({}) while mdb_view: try: avb = ArticleViewedBy.objects.get(article=mdb_view['article'], user=mdb_view['user'])",
"model\" def handle(self, *args, **options): mdb_view = core_articleviewedby_mdb.posts.find_one_and_delete({}) while mdb_view:",
"-*- # utopia-cms 2020. <NAME>. from django.core.management import BaseCommand from",
"mdb_view: try: avb = ArticleViewedBy.objects.get(article=mdb_view['article'], user=mdb_view['user']) avb.viewed_at = mdb_view['viewed_at'] avb.save()",
"*args, **options): mdb_view = core_articleviewedby_mdb.posts.find_one_and_delete({}) while mdb_view: try: avb =",
"handle(self, *args, **options): mdb_view = core_articleviewedby_mdb.posts.find_one_and_delete({}) while mdb_view: try: avb",
"ArticleViewedBy.DoesNotExist: try: ArticleViewedBy.objects.create( article_id=mdb_view['article'], user_id=mdb_view['user'], viewed_at=mdb_view['viewed_at']) except IntegrityError: pass mdb_view",
"core_articleviewedby_mdb.posts.find_one_and_delete({}) while mdb_view: try: avb = ArticleViewedBy.objects.get(article=mdb_view['article'], user=mdb_view['user']) avb.viewed_at =",
"ArticleViewedBy class Command(BaseCommand): help = \"Moves article viewed by data",
"BaseCommand from django.db.utils import IntegrityError from apps import core_articleviewedby_mdb from",
"-*- coding: utf-8 -*- # utopia-cms 2020. <NAME>. from django.core.management",
"import core_articleviewedby_mdb from core.models import ArticleViewedBy class Command(BaseCommand): help =",
"class Command(BaseCommand): help = \"Moves article viewed by data from",
"django.db.utils import IntegrityError from apps import core_articleviewedby_mdb from core.models import",
"mongodb to Django model\" def handle(self, *args, **options): mdb_view =",
"avb.save() except ArticleViewedBy.DoesNotExist: try: ArticleViewedBy.objects.create( article_id=mdb_view['article'], user_id=mdb_view['user'], viewed_at=mdb_view['viewed_at']) except IntegrityError:",
"IntegrityError from apps import core_articleviewedby_mdb from core.models import ArticleViewedBy class",
"ArticleViewedBy.objects.create( article_id=mdb_view['article'], user_id=mdb_view['user'], viewed_at=mdb_view['viewed_at']) except IntegrityError: pass mdb_view = core_articleviewedby_mdb.posts.find_one_and_delete({})",
"utf-8 -*- # utopia-cms 2020. <NAME>. from django.core.management import BaseCommand",
"django.core.management import BaseCommand from django.db.utils import IntegrityError from apps import",
"to Django model\" def handle(self, *args, **options): mdb_view = core_articleviewedby_mdb.posts.find_one_and_delete({})",
"avb.viewed_at = mdb_view['viewed_at'] avb.save() except ArticleViewedBy.DoesNotExist: try: ArticleViewedBy.objects.create( article_id=mdb_view['article'], user_id=mdb_view['user'],",
"<NAME>. from django.core.management import BaseCommand from django.db.utils import IntegrityError from",
"import BaseCommand from django.db.utils import IntegrityError from apps import core_articleviewedby_mdb",
"from django.core.management import BaseCommand from django.db.utils import IntegrityError from apps",
"core.models import ArticleViewedBy class Command(BaseCommand): help = \"Moves article viewed",
"from apps import core_articleviewedby_mdb from core.models import ArticleViewedBy class Command(BaseCommand):",
"core_articleviewedby_mdb from core.models import ArticleViewedBy class Command(BaseCommand): help = \"Moves",
"import ArticleViewedBy class Command(BaseCommand): help = \"Moves article viewed by",
"while mdb_view: try: avb = ArticleViewedBy.objects.get(article=mdb_view['article'], user=mdb_view['user']) avb.viewed_at = mdb_view['viewed_at']",
"try: ArticleViewedBy.objects.create( article_id=mdb_view['article'], user_id=mdb_view['user'], viewed_at=mdb_view['viewed_at']) except IntegrityError: pass mdb_view =",
"\"Moves article viewed by data from mongodb to Django model\"",
"from mongodb to Django model\" def handle(self, *args, **options): mdb_view",
"avb = ArticleViewedBy.objects.get(article=mdb_view['article'], user=mdb_view['user']) avb.viewed_at = mdb_view['viewed_at'] avb.save() except ArticleViewedBy.DoesNotExist:",
"= core_articleviewedby_mdb.posts.find_one_and_delete({}) while mdb_view: try: avb = ArticleViewedBy.objects.get(article=mdb_view['article'], user=mdb_view['user']) avb.viewed_at",
"def handle(self, *args, **options): mdb_view = core_articleviewedby_mdb.posts.find_one_and_delete({}) while mdb_view: try:",
"= mdb_view['viewed_at'] avb.save() except ArticleViewedBy.DoesNotExist: try: ArticleViewedBy.objects.create( article_id=mdb_view['article'], user_id=mdb_view['user'], viewed_at=mdb_view['viewed_at'])",
"apps import core_articleviewedby_mdb from core.models import ArticleViewedBy class Command(BaseCommand): help",
"help = \"Moves article viewed by data from mongodb to",
"article viewed by data from mongodb to Django model\" def",
"import IntegrityError from apps import core_articleviewedby_mdb from core.models import ArticleViewedBy",
"by data from mongodb to Django model\" def handle(self, *args,",
"user=mdb_view['user']) avb.viewed_at = mdb_view['viewed_at'] avb.save() except ArticleViewedBy.DoesNotExist: try: ArticleViewedBy.objects.create( article_id=mdb_view['article'],",
"data from mongodb to Django model\" def handle(self, *args, **options):",
"# utopia-cms 2020. <NAME>. from django.core.management import BaseCommand from django.db.utils",
"try: avb = ArticleViewedBy.objects.get(article=mdb_view['article'], user=mdb_view['user']) avb.viewed_at = mdb_view['viewed_at'] avb.save() except",
"mdb_view['viewed_at'] avb.save() except ArticleViewedBy.DoesNotExist: try: ArticleViewedBy.objects.create( article_id=mdb_view['article'], user_id=mdb_view['user'], viewed_at=mdb_view['viewed_at']) except",
"# -*- coding: utf-8 -*- # utopia-cms 2020. <NAME>. from",
"Command(BaseCommand): help = \"Moves article viewed by data from mongodb",
"2020. <NAME>. from django.core.management import BaseCommand from django.db.utils import IntegrityError",
"= ArticleViewedBy.objects.get(article=mdb_view['article'], user=mdb_view['user']) avb.viewed_at = mdb_view['viewed_at'] avb.save() except ArticleViewedBy.DoesNotExist: try:"
] |
[
"out = self.relu(out) out_b3p8 = self.block3(out) # tensor_stride=16 out =",
"= self.block2(out) out = self.conv3p4s2(out_b2p4) out = self.bn3(out) out =",
"BLOCK = BasicBlock LAYERS = (2, 2, 2, 2, 2,",
"self.conv4p8s2(out_b3p8) out = self.bn4(out) out = self.relu(out) out = self.block4(out)",
"has_bias=True, dimension=D) self.relu = ME.MinkowskiReLU(inplace=True) def forward(self, x): out =",
"nn from torch.optim import SGD import MinkowskiEngine as ME from",
"class MinkUNet18B(MinkUNet18): PLANES = (32, 64, 128, 256, 128, 128,",
"self.BLOCK.expansion self.block5 = self._make_layer(self.BLOCK, self.PLANES[4], self.LAYERS[4]) self.convtr5p8s2 = ME.MinkowskiConvolutionTranspose( self.inplanes,",
"stride=2, dimension=D) self.bn4 = ME.MinkowskiBatchNorm(self.inplanes) self.block4 = self._make_layer(self.BLOCK, self.PLANES[3], self.LAYERS[3])",
"= 1 # To use the model, must call initialize_coords",
"MinkUNet18A(MinkUNet18): PLANES = (32, 64, 128, 256, 128, 128, 96,",
"self.conv4p8s2 = ME.MinkowskiConvolution( self.inplanes, self.inplanes, kernel_size=2, stride=2, dimension=D) self.bn4 =",
"PLANES = (32, 64, 128, 256, 256, 128, 64, 64)",
"network criterion = nn.CrossEntropyLoss() net = MinkUNet14A(in_channels=3, out_channels=5, D=2) print(net)",
"class MinkUNet18A(MinkUNet18): PLANES = (32, 64, 128, 256, 128, 128,",
"BLOCK = Bottleneck LAYERS = (2, 3, 4, 6, 2,",
"2, 2) INIT_DIM = 32 OUT_TENSOR_STRIDE = 1 # To",
"ME.MinkowskiConvolution( self.inplanes, self.inplanes, kernel_size=2, stride=2, dimension=D) self.bn1 = ME.MinkowskiBatchNorm(self.inplanes) self.block1",
"self.block1(out) out = self.conv2p2s2(out_b1p2) out = self.bn2(out) out = self.relu(out)",
"torch.optim import SGD import MinkowskiEngine as ME from MinkowskiEngine.modules.resnet_block import",
"first conv concated to conv6 self.inplanes = self.INIT_DIM self.conv0p1s1 =",
"Get new data coords, feat, label = data_loader(is_classification=False) input =",
"out = self.block5(out) # tensor_stride=4 out = self.convtr5p8s2(out) out =",
"Once data is processed, call clear to reset the model",
"self.PLANES[7], kernel_size=2, stride=2, dimension=D) self.bntr7 = ME.MinkowskiBatchNorm(self.PLANES[7]) self.inplanes = self.PLANES[7]",
"use the model, must call initialize_coords before forward pass. #",
"D): # Output of the first conv concated to conv6",
"Loss: ', loss.item()) # Gradient loss.backward() optimizer.step() # Saving and",
"1, 1) LAYERS = (2, 2, 2, 2, 2, 2,",
"self.relu(out) out_b1p2 = self.block1(out) out = self.conv2p2s2(out_b1p2) out = self.bn2(out)",
"= (32, 64, 128, 256, 128, 128, 96, 96) class",
"from examples.common import data_loader from examples.resnet import ResNetBase class MinkUNetBase(ResNetBase):",
"= nn.CrossEntropyLoss() net = MinkUNet14A(in_channels=3, out_channels=5, D=2) print(net) # a",
"256, 256, 128, 64, 32) class MinkUNet34C(MinkUNet34): PLANES = (32,",
"(32, 64, 128, 256, 128, 128, 128, 128) class MinkUNet14C(MinkUNet14):",
"96) if __name__ == '__main__': # loss and network criterion",
"x): out = self.conv0p1s1(x) out = self.bn0(out) out_p1 = self.relu(out)",
"class MinkUNet18(MinkUNetBase): BLOCK = BasicBlock LAYERS = (2, 2, 2,",
"128, 256, 128, 128, 128, 128) class MinkUNet14C(MinkUNet14): PLANES =",
"= BasicBlock LAYERS = (2, 3, 4, 6, 2, 2,",
"loss.backward() optimizer.step() # Saving and loading a network torch.save(net.state_dict(), 'test.pth')",
"== '__main__': # loss and network criterion = nn.CrossEntropyLoss() net",
"self.inplanes, kernel_size=2, stride=2, dimension=D) self.bn1 = ME.MinkowskiBatchNorm(self.inplanes) self.block1 = self._make_layer(self.BLOCK,",
"ME.MinkowskiBatchNorm(self.inplanes) self.block3 = self._make_layer(self.BLOCK, self.PLANES[2], self.LAYERS[2]) self.conv4p8s2 = ME.MinkowskiConvolution( self.inplanes,",
"2) class MinkUNet34(MinkUNetBase): BLOCK = BasicBlock LAYERS = (2, 3,",
"self.block5 = self._make_layer(self.BLOCK, self.PLANES[4], self.LAYERS[4]) self.convtr5p8s2 = ME.MinkowskiConvolutionTranspose( self.inplanes, self.PLANES[5],",
"def forward(self, x): out = self.conv0p1s1(x) out = self.bn0(out) out_p1",
"self.INIT_DIM self.conv0p1s1 = ME.MinkowskiConvolution( in_channels, self.inplanes, kernel_size=5, dimension=D) self.bn0 =",
"out_channels=5, D=2) print(net) # a data loader must return a",
"= self._make_layer(self.BLOCK, self.PLANES[1], self.LAYERS[1]) self.conv3p4s2 = ME.MinkowskiConvolution( self.inplanes, self.inplanes, kernel_size=2,",
"self._make_layer(self.BLOCK, self.PLANES[5], self.LAYERS[5]) self.convtr6p4s2 = ME.MinkowskiConvolutionTranspose( self.inplanes, self.PLANES[6], kernel_size=2, stride=2,",
"OUT_TENSOR_STRIDE = 1 # To use the model, must call",
"torch.nn as nn from torch.optim import SGD import MinkowskiEngine as",
"if __name__ == '__main__': # loss and network criterion =",
"labels. device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') net =",
"self.PLANES[1], self.LAYERS[1]) self.conv3p4s2 = ME.MinkowskiConvolution( self.inplanes, self.inplanes, kernel_size=2, stride=2, dimension=D)",
"= ME.cat((out, out_b2p4)) out = self.block6(out) # tensor_stride=2 out =",
"return self.final(out) class MinkUNet14(MinkUNetBase): BLOCK = BasicBlock LAYERS = (1,",
"self.PLANES[7], self.LAYERS[7]) self.final = ME.MinkowskiConvolution( self.PLANES[7], out_channels, kernel_size=1, has_bias=True, dimension=D)",
"LAYERS = (2, 3, 4, 23, 2, 2, 2, 2)",
"class MinkUNet34C(MinkUNet34): PLANES = (32, 64, 128, 256, 256, 128,",
"2, 2, 2, 2) class MinkUNet14A(MinkUNet14): PLANES = (32, 64,",
"out_b3p8)) out = self.block5(out) # tensor_stride=4 out = self.convtr5p8s2(out) out",
"2, 2, 2, 2) class MinkUNet50(MinkUNetBase): BLOCK = Bottleneck LAYERS",
"ResNetBase.__init__(self, in_channels, out_channels, D) def network_initialization(self, in_channels, out_channels, D): #",
"self._make_layer(self.BLOCK, self.PLANES[1], self.LAYERS[1]) self.conv3p4s2 = ME.MinkowskiConvolution( self.inplanes, self.inplanes, kernel_size=2, stride=2,",
"out = self.convtr6p4s2(out) out = self.bntr6(out) out = self.relu(out) out",
"2, 2, 2, 2) class MinkUNet34(MinkUNetBase): BLOCK = BasicBlock LAYERS",
"Bottleneck LAYERS = (2, 3, 4, 6, 2, 2, 2,",
"= ME.MinkowskiConvolution( self.inplanes, self.inplanes, kernel_size=2, stride=2, dimension=D) self.bn2 = ME.MinkowskiBatchNorm(self.inplanes)",
"model before calling # initialize_coords def __init__(self, in_channels, out_channels, D=3):",
"= (2, 3, 4, 23, 2, 2, 2, 2) class",
"import torch.nn as nn from torch.optim import SGD import MinkowskiEngine",
"kernel_size=2, stride=2, dimension=D) self.bn3 = ME.MinkowskiBatchNorm(self.inplanes) self.block3 = self._make_layer(self.BLOCK, self.PLANES[2],",
"out = ME.cat((out, out_b1p2)) out = self.block7(out) # tensor_stride=1 out",
"optimizer = SGD(net.parameters(), lr=1e-2) for i in range(10): optimizer.zero_grad() #",
"in_channels, out_channels, D=3): ResNetBase.__init__(self, in_channels, out_channels, D) def network_initialization(self, in_channels,",
"96, 96) class MinkUNet18B(MinkUNet18): PLANES = (32, 64, 128, 256,",
"PLANES = (32, 64, 128, 256, 192, 192, 128, 128)",
"# tensor_stride=8 out = self.convtr4p16s2(out) out = self.bntr4(out) out =",
"loss.item()) # Gradient loss.backward() optimizer.step() # Saving and loading a",
"tensor_stride=4 out = self.convtr5p8s2(out) out = self.bntr5(out) out = self.relu(out)",
"must return a tuple of coords, features, and labels. device",
"self.conv0p1s1 = ME.MinkowskiConvolution( in_channels, self.inplanes, kernel_size=5, dimension=D) self.bn0 = ME.MinkowskiBatchNorm(self.inplanes)",
"256, 256, 128, 64, 64) class MinkUNet34B(MinkUNet34): PLANES = (32,",
"out = self.block8(out) return self.final(out) class MinkUNet14(MinkUNetBase): BLOCK = BasicBlock",
"self.bn2 = ME.MinkowskiBatchNorm(self.inplanes) self.block2 = self._make_layer(self.BLOCK, self.PLANES[1], self.LAYERS[1]) self.conv3p4s2 =",
"kernel_size=2, stride=2, dimension=D) self.bntr5 = ME.MinkowskiBatchNorm(self.PLANES[5]) self.inplanes = self.PLANES[5] +",
"ME.cat((out, out_b3p8)) out = self.block5(out) # tensor_stride=4 out = self.convtr5p8s2(out)",
"self._make_layer(self.BLOCK, self.PLANES[0], self.LAYERS[0]) self.conv2p2s2 = ME.MinkowskiConvolution( self.inplanes, self.inplanes, kernel_size=2, stride=2,",
"self.inplanes, self.PLANES[6], kernel_size=2, stride=2, dimension=D) self.bntr6 = ME.MinkowskiBatchNorm(self.PLANES[6]) self.inplanes =",
"2, 2, 2, 2) INIT_DIM = 32 OUT_TENSOR_STRIDE = 1",
"call initialize_coords before forward pass. # Once data is processed,",
"data loader must return a tuple of coords, features, and",
"= None DILATIONS = (1, 1, 1, 1, 1, 1,",
"= BasicBlock LAYERS = (2, 2, 2, 2, 2, 2,",
"self.PLANES[7], out_channels, kernel_size=1, has_bias=True, dimension=D) self.relu = ME.MinkowskiReLU(inplace=True) def forward(self,",
"# tensor_stride=1 out = self.convtr7p2s2(out) out = self.bntr7(out) out =",
"= self.convtr5p8s2(out) out = self.bntr5(out) out = self.relu(out) out =",
"ME.MinkowskiBatchNorm(self.inplanes) self.block4 = self._make_layer(self.BLOCK, self.PLANES[3], self.LAYERS[3]) self.convtr4p16s2 = ME.MinkowskiConvolutionTranspose( self.inplanes,",
"self.PLANES[4], self.LAYERS[4]) self.convtr5p8s2 = ME.MinkowskiConvolutionTranspose( self.inplanes, self.PLANES[5], kernel_size=2, stride=2, dimension=D)",
"__init__(self, in_channels, out_channels, D=3): ResNetBase.__init__(self, in_channels, out_channels, D) def network_initialization(self,",
"= self.relu(out) out_b3p8 = self.block3(out) # tensor_stride=16 out = self.conv4p8s2(out_b3p8)",
"self.bn1(out) out = self.relu(out) out_b1p2 = self.block1(out) out = self.conv2p2s2(out_b1p2)",
"kernel_size=2, stride=2, dimension=D) self.bn4 = ME.MinkowskiBatchNorm(self.inplanes) self.block4 = self._make_layer(self.BLOCK, self.PLANES[3],",
"256, 256, 128, 96, 96) if __name__ == '__main__': #",
"MinkUNetBase(ResNetBase): BLOCK = None PLANES = None DILATIONS = (1,",
"self.PLANES[0], self.LAYERS[0]) self.conv2p2s2 = ME.MinkowskiConvolution( self.inplanes, self.inplanes, kernel_size=2, stride=2, dimension=D)",
"kernel_size=2, stride=2, dimension=D) self.bntr7 = ME.MinkowskiBatchNorm(self.PLANES[7]) self.inplanes = self.PLANES[7] +",
"self.block4(out) # tensor_stride=8 out = self.convtr4p16s2(out) out = self.bntr4(out) out",
"ME from MinkowskiEngine.modules.resnet_block import BasicBlock, Bottleneck from examples.common import data_loader",
"PLANES = (32, 64, 128, 256, 128, 128, 128, 128)",
"= ME.MinkowskiBatchNorm(self.PLANES[7]) self.inplanes = self.PLANES[7] + self.INIT_DIM self.block8 = self._make_layer(self.BLOCK,",
"128, 256, 256, 128, 64, 32) class MinkUNet34C(MinkUNet34): PLANES =",
"criterion(output.F, label) print('Iteration: ', i, ', Loss: ', loss.item()) #",
"2, 2, 2, 2, 2, 2, 2) INIT_DIM = 32",
"MinkUNet101(MinkUNetBase): BLOCK = Bottleneck LAYERS = (2, 3, 4, 23,",
"self.PLANES[1] * self.BLOCK.expansion self.block6 = self._make_layer(self.BLOCK, self.PLANES[5], self.LAYERS[5]) self.convtr6p4s2 =",
"BLOCK = BasicBlock LAYERS = (1, 1, 1, 1, 1,",
"out = self.bntr4(out) out = self.relu(out) out = ME.cat((out, out_b3p8))",
"self.block6(out) # tensor_stride=2 out = self.convtr6p4s2(out) out = self.bntr6(out) out",
"class MinkUNet18D(MinkUNet18): PLANES = (32, 64, 128, 256, 384, 384,",
"self.conv3p4s2 = ME.MinkowskiConvolution( self.inplanes, self.inplanes, kernel_size=2, stride=2, dimension=D) self.bn3 =",
"self._make_layer(self.BLOCK, self.PLANES[3], self.LAYERS[3]) self.convtr4p16s2 = ME.MinkowskiConvolutionTranspose( self.inplanes, self.PLANES[4], kernel_size=2, stride=2,",
"model, must call initialize_coords before forward pass. # Once data",
"self.LAYERS[3]) self.convtr4p16s2 = ME.MinkowskiConvolutionTranspose( self.inplanes, self.PLANES[4], kernel_size=2, stride=2, dimension=D) self.bntr4",
"MinkowskiEngine as ME from MinkowskiEngine.modules.resnet_block import BasicBlock, Bottleneck from examples.common",
"ME.MinkowskiConvolution( self.PLANES[7], out_channels, kernel_size=1, has_bias=True, dimension=D) self.relu = ME.MinkowskiReLU(inplace=True) def",
"ME.SparseTensor(feat, coords=coords).to(device) label = label.to(device) # Forward output = net(input)",
"label = label.to(device) # Forward output = net(input) # Loss",
"def network_initialization(self, in_channels, out_channels, D): # Output of the first",
"self.conv1p1s2 = ME.MinkowskiConvolution( self.inplanes, self.inplanes, kernel_size=2, stride=2, dimension=D) self.bn1 =",
"MinkUNet18D(MinkUNet18): PLANES = (32, 64, 128, 256, 384, 384, 384,",
"ME.MinkowskiBatchNorm(self.inplanes) self.conv1p1s2 = ME.MinkowskiConvolution( self.inplanes, self.inplanes, kernel_size=2, stride=2, dimension=D) self.bn1",
"net.to(device) optimizer = SGD(net.parameters(), lr=1e-2) for i in range(10): optimizer.zero_grad()",
"self.relu(out) out = ME.cat((out, out_b1p2)) out = self.block7(out) # tensor_stride=1",
"= self.relu(out) out = self.block4(out) # tensor_stride=8 out = self.convtr4p16s2(out)",
"= ME.cat((out, out_b3p8)) out = self.block5(out) # tensor_stride=4 out =",
"self.inplanes, self.PLANES[4], kernel_size=2, stride=2, dimension=D) self.bntr4 = ME.MinkowskiBatchNorm(self.PLANES[4]) self.inplanes =",
"out = self.bntr7(out) out = self.relu(out) out = ME.cat((out, out_p1))",
"1, 1, 1) class MinkUNet18(MinkUNetBase): BLOCK = BasicBlock LAYERS =",
"64, 128, 256, 128, 128, 128, 128) class MinkUNet14C(MinkUNet14): PLANES",
"examples.common import data_loader from examples.resnet import ResNetBase class MinkUNetBase(ResNetBase): BLOCK",
"import torch import torch.nn as nn from torch.optim import SGD",
"the model, must call initialize_coords before forward pass. # Once",
"in range(10): optimizer.zero_grad() # Get new data coords, feat, label",
"Loss loss = criterion(output.F, label) print('Iteration: ', i, ', Loss:",
"self.convtr7p2s2(out) out = self.bntr7(out) out = self.relu(out) out = ME.cat((out,",
"128) class MinkUNet14D(MinkUNet14): PLANES = (32, 64, 128, 256, 384,",
"= (1, 1, 1, 1, 1, 1, 1, 1) LAYERS",
"self.block1 = self._make_layer(self.BLOCK, self.PLANES[0], self.LAYERS[0]) self.conv2p2s2 = ME.MinkowskiConvolution( self.inplanes, self.inplanes,",
"as nn from torch.optim import SGD import MinkowskiEngine as ME",
"network_initialization(self, in_channels, out_channels, D): # Output of the first conv",
"kernel_size=2, stride=2, dimension=D) self.bn1 = ME.MinkowskiBatchNorm(self.inplanes) self.block1 = self._make_layer(self.BLOCK, self.PLANES[0],",
"32) class MinkUNet34C(MinkUNet34): PLANES = (32, 64, 128, 256, 256,",
"= self.block8(out) return self.final(out) class MinkUNet14(MinkUNetBase): BLOCK = BasicBlock LAYERS",
"self.convtr4p16s2 = ME.MinkowskiConvolutionTranspose( self.inplanes, self.PLANES[4], kernel_size=2, stride=2, dimension=D) self.bntr4 =",
"self.PLANES[0] * self.BLOCK.expansion self.block7 = self._make_layer(self.BLOCK, self.PLANES[6], self.LAYERS[6]) self.convtr7p2s2 =",
"2) INIT_DIM = 32 OUT_TENSOR_STRIDE = 1 # To use",
"* self.BLOCK.expansion self.block6 = self._make_layer(self.BLOCK, self.PLANES[5], self.LAYERS[5]) self.convtr6p4s2 = ME.MinkowskiConvolutionTranspose(",
"= (32, 64, 128, 256, 128, 128, 128, 128) class",
"2, 2) class MinkUNet14A(MinkUNet14): PLANES = (32, 64, 128, 256,",
"ME.MinkowskiConvolutionTranspose( self.inplanes, self.PLANES[5], kernel_size=2, stride=2, dimension=D) self.bntr5 = ME.MinkowskiBatchNorm(self.PLANES[5]) self.inplanes",
"64, 128, 256, 128, 128, 96, 96) class MinkUNet18B(MinkUNet18): PLANES",
"96, 96) class MinkUNet14B(MinkUNet14): PLANES = (32, 64, 128, 256,",
"128, 96, 96) class MinkUNet18B(MinkUNet18): PLANES = (32, 64, 128,",
"self.LAYERS[4]) self.convtr5p8s2 = ME.MinkowskiConvolutionTranspose( self.inplanes, self.PLANES[5], kernel_size=2, stride=2, dimension=D) self.bntr5",
"self.BLOCK.expansion self.block6 = self._make_layer(self.BLOCK, self.PLANES[5], self.LAYERS[5]) self.convtr6p4s2 = ME.MinkowskiConvolutionTranspose( self.inplanes,",
"lr=1e-2) for i in range(10): optimizer.zero_grad() # Get new data",
"self.inplanes, kernel_size=2, stride=2, dimension=D) self.bn4 = ME.MinkowskiBatchNorm(self.inplanes) self.block4 = self._make_layer(self.BLOCK,",
"self.convtr6p4s2(out) out = self.bntr6(out) out = self.relu(out) out = ME.cat((out,",
"label.to(device) # Forward output = net(input) # Loss loss =",
"= (32, 64, 128, 256, 384, 384, 384, 384) class",
"ME.MinkowskiConvolution( in_channels, self.inplanes, kernel_size=5, dimension=D) self.bn0 = ME.MinkowskiBatchNorm(self.inplanes) self.conv1p1s2 =",
"to conv6 self.inplanes = self.INIT_DIM self.conv0p1s1 = ME.MinkowskiConvolution( in_channels, self.inplanes,",
"in_channels, out_channels, D): # Output of the first conv concated",
"is processed, call clear to reset the model before calling",
"self.conv2p2s2(out_b1p2) out = self.bn2(out) out = self.relu(out) out_b2p4 = self.block2(out)",
"(2, 2, 2, 2, 2, 2, 2, 2) class MinkUNet34(MinkUNetBase):",
"stride=2, dimension=D) self.bn2 = ME.MinkowskiBatchNorm(self.inplanes) self.block2 = self._make_layer(self.BLOCK, self.PLANES[1], self.LAYERS[1])",
"and network criterion = nn.CrossEntropyLoss() net = MinkUNet14A(in_channels=3, out_channels=5, D=2)",
"1, 1, 1, 1) LAYERS = (2, 2, 2, 2,",
"must call initialize_coords before forward pass. # Once data is",
"384, 384, 384) class MinkUNet34A(MinkUNet34): PLANES = (32, 64, 128,",
"256, 128, 96, 96) if __name__ == '__main__': # loss",
"conv6 self.inplanes = self.INIT_DIM self.conv0p1s1 = ME.MinkowskiConvolution( in_channels, self.inplanes, kernel_size=5,",
"= self.conv3p4s2(out_b2p4) out = self.bn3(out) out = self.relu(out) out_b3p8 =",
"384, 384, 384) class MinkUNet18A(MinkUNet18): PLANES = (32, 64, 128,",
"class MinkUNet14(MinkUNetBase): BLOCK = BasicBlock LAYERS = (1, 1, 1,",
"= (32, 64, 128, 256, 192, 192, 128, 128) class",
"128, 256, 256, 128, 64, 64) class MinkUNet34B(MinkUNet34): PLANES =",
"+ self.PLANES[0] * self.BLOCK.expansion self.block7 = self._make_layer(self.BLOCK, self.PLANES[6], self.LAYERS[6]) self.convtr7p2s2",
"= (32, 64, 128, 256, 256, 128, 64, 32) class",
"import data_loader from examples.resnet import ResNetBase class MinkUNetBase(ResNetBase): BLOCK =",
"dimension=D) self.bntr5 = ME.MinkowskiBatchNorm(self.PLANES[5]) self.inplanes = self.PLANES[5] + self.PLANES[1] *",
"= ME.MinkowskiConvolutionTranspose( self.inplanes, self.PLANES[7], kernel_size=2, stride=2, dimension=D) self.bntr7 = ME.MinkowskiBatchNorm(self.PLANES[7])",
"self.inplanes, self.inplanes, kernel_size=2, stride=2, dimension=D) self.bn2 = ME.MinkowskiBatchNorm(self.inplanes) self.block2 =",
"96, 96) if __name__ == '__main__': # loss and network",
"Output of the first conv concated to conv6 self.inplanes =",
"for i in range(10): optimizer.zero_grad() # Get new data coords,",
"= self.relu(out) out = ME.cat((out, out_p1)) out = self.block8(out) return",
"= ME.MinkowskiBatchNorm(self.inplanes) self.block4 = self._make_layer(self.BLOCK, self.PLANES[3], self.LAYERS[3]) self.convtr4p16s2 = ME.MinkowskiConvolutionTranspose(",
"self.final = ME.MinkowskiConvolution( self.PLANES[7], out_channels, kernel_size=1, has_bias=True, dimension=D) self.relu =",
"= self.INIT_DIM self.conv0p1s1 = ME.MinkowskiConvolution( in_channels, self.inplanes, kernel_size=5, dimension=D) self.bn0",
"2, 2) class MinkUNet50(MinkUNetBase): BLOCK = Bottleneck LAYERS = (2,",
"ME.MinkowskiBatchNorm(self.inplanes) self.block2 = self._make_layer(self.BLOCK, self.PLANES[1], self.LAYERS[1]) self.conv3p4s2 = ME.MinkowskiConvolution( self.inplanes,",
"self.PLANES[6] + self.PLANES[0] * self.BLOCK.expansion self.block7 = self._make_layer(self.BLOCK, self.PLANES[6], self.LAYERS[6])",
"(32, 64, 128, 256, 256, 128, 64, 64) class MinkUNet34B(MinkUNet34):",
"ResNetBase class MinkUNetBase(ResNetBase): BLOCK = None PLANES = None DILATIONS",
"self.bntr7 = ME.MinkowskiBatchNorm(self.PLANES[7]) self.inplanes = self.PLANES[7] + self.INIT_DIM self.block8 =",
"64, 128, 256, 384, 384, 384, 384) class MinkUNet18A(MinkUNet18): PLANES",
"import ResNetBase class MinkUNetBase(ResNetBase): BLOCK = None PLANES = None",
"= self._make_layer(self.BLOCK, self.PLANES[3], self.LAYERS[3]) self.convtr4p16s2 = ME.MinkowskiConvolutionTranspose( self.inplanes, self.PLANES[4], kernel_size=2,",
"128, 256, 256, 128, 96, 96) if __name__ == '__main__':",
"dimension=D) self.relu = ME.MinkowskiReLU(inplace=True) def forward(self, x): out = self.conv0p1s1(x)",
"self.LAYERS[1]) self.conv3p4s2 = ME.MinkowskiConvolution( self.inplanes, self.inplanes, kernel_size=2, stride=2, dimension=D) self.bn3",
"1, 1, 1, 1) class MinkUNet18(MinkUNetBase): BLOCK = BasicBlock LAYERS",
"reset the model before calling # initialize_coords def __init__(self, in_channels,",
"None PLANES = None DILATIONS = (1, 1, 1, 1,",
"1, 1, 1, 1, 1, 1, 1) LAYERS = (2,",
"= ME.MinkowskiBatchNorm(self.inplanes) self.block2 = self._make_layer(self.BLOCK, self.PLANES[1], self.LAYERS[1]) self.conv3p4s2 = ME.MinkowskiConvolution(",
"= ME.MinkowskiBatchNorm(self.inplanes) self.block3 = self._make_layer(self.BLOCK, self.PLANES[2], self.LAYERS[2]) self.conv4p8s2 = ME.MinkowskiConvolution(",
"ME.MinkowskiBatchNorm(self.PLANES[7]) self.inplanes = self.PLANES[7] + self.INIT_DIM self.block8 = self._make_layer(self.BLOCK, self.PLANES[7],",
"BLOCK = Bottleneck LAYERS = (2, 3, 4, 23, 2,",
"the first conv concated to conv6 self.inplanes = self.INIT_DIM self.conv0p1s1",
"self.convtr6p4s2 = ME.MinkowskiConvolutionTranspose( self.inplanes, self.PLANES[6], kernel_size=2, stride=2, dimension=D) self.bntr6 =",
"128, 128, 128, 128) class MinkUNet14C(MinkUNet14): PLANES = (32, 64,",
"torch import torch.nn as nn from torch.optim import SGD import",
"BasicBlock LAYERS = (1, 1, 1, 1, 1, 1, 1,",
"384) class MinkUNet34A(MinkUNet34): PLANES = (32, 64, 128, 256, 256,",
"= self.bntr6(out) out = self.relu(out) out = ME.cat((out, out_b1p2)) out",
"MinkowskiEngine.modules.resnet_block import BasicBlock, Bottleneck from examples.common import data_loader from examples.resnet",
"= self.PLANES[6] + self.PLANES[0] * self.BLOCK.expansion self.block7 = self._make_layer(self.BLOCK, self.PLANES[6],",
"= self.bntr5(out) out = self.relu(out) out = ME.cat((out, out_b2p4)) out",
"MinkUNet14A(in_channels=3, out_channels=5, D=2) print(net) # a data loader must return",
"384, 384) class MinkUNet34A(MinkUNet34): PLANES = (32, 64, 128, 256,",
"= ME.MinkowskiConvolution( self.PLANES[7], out_channels, kernel_size=1, has_bias=True, dimension=D) self.relu = ME.MinkowskiReLU(inplace=True)",
"BasicBlock LAYERS = (2, 3, 4, 6, 2, 2, 2,",
"# Get new data coords, feat, label = data_loader(is_classification=False) input",
"out_channels, kernel_size=1, has_bias=True, dimension=D) self.relu = ME.MinkowskiReLU(inplace=True) def forward(self, x):",
"class MinkUNet50(MinkUNetBase): BLOCK = Bottleneck LAYERS = (2, 3, 4,",
"None DILATIONS = (1, 1, 1, 1, 1, 1, 1,",
"self.relu(out) out = ME.cat((out, out_b3p8)) out = self.block5(out) # tensor_stride=4",
"= self._make_layer(self.BLOCK, self.PLANES[5], self.LAYERS[5]) self.convtr6p4s2 = ME.MinkowskiConvolutionTranspose( self.inplanes, self.PLANES[6], kernel_size=2,",
"self.conv2p2s2 = ME.MinkowskiConvolution( self.inplanes, self.inplanes, kernel_size=2, stride=2, dimension=D) self.bn2 =",
"self.bntr6 = ME.MinkowskiBatchNorm(self.PLANES[6]) self.inplanes = self.PLANES[6] + self.PLANES[0] * self.BLOCK.expansion",
"ME.MinkowskiConvolution( self.inplanes, self.inplanes, kernel_size=2, stride=2, dimension=D) self.bn2 = ME.MinkowskiBatchNorm(self.inplanes) self.block2",
"= SGD(net.parameters(), lr=1e-2) for i in range(10): optimizer.zero_grad() # Get",
"= self.bn2(out) out = self.relu(out) out_b2p4 = self.block2(out) out =",
"self.block7 = self._make_layer(self.BLOCK, self.PLANES[6], self.LAYERS[6]) self.convtr7p2s2 = ME.MinkowskiConvolutionTranspose( self.inplanes, self.PLANES[7],",
"examples.resnet import ResNetBase class MinkUNetBase(ResNetBase): BLOCK = None PLANES =",
"self.PLANES[7] + self.INIT_DIM self.block8 = self._make_layer(self.BLOCK, self.PLANES[7], self.LAYERS[7]) self.final =",
"= self.conv2p2s2(out_b1p2) out = self.bn2(out) out = self.relu(out) out_b2p4 =",
"128, 128, 128, 128) class MinkUNet18D(MinkUNet18): PLANES = (32, 64,",
"128, 96, 96) if __name__ == '__main__': # loss and",
"(32, 64, 128, 256, 128, 128, 128, 128) class MinkUNet18D(MinkUNet18):",
"self.BLOCK.expansion self.block7 = self._make_layer(self.BLOCK, self.PLANES[6], self.LAYERS[6]) self.convtr7p2s2 = ME.MinkowskiConvolutionTranspose( self.inplanes,",
"self.inplanes, self.PLANES[7], kernel_size=2, stride=2, dimension=D) self.bntr7 = ME.MinkowskiBatchNorm(self.PLANES[7]) self.inplanes =",
"out = self.convtr5p8s2(out) out = self.bntr5(out) out = self.relu(out) out",
"BLOCK = None PLANES = None DILATIONS = (1, 1,",
"DILATIONS = (1, 1, 1, 1, 1, 1, 1, 1)",
"128, 256, 384, 384, 384, 384) class MinkUNet34A(MinkUNet34): PLANES =",
"MinkUNet34B(MinkUNet34): PLANES = (32, 64, 128, 256, 256, 128, 64,",
"SGD import MinkowskiEngine as ME from MinkowskiEngine.modules.resnet_block import BasicBlock, Bottleneck",
"self.inplanes = self.PLANES[7] + self.INIT_DIM self.block8 = self._make_layer(self.BLOCK, self.PLANES[7], self.LAYERS[7])",
"= self.conv4p8s2(out_b3p8) out = self.bn4(out) out = self.relu(out) out =",
"BasicBlock LAYERS = (2, 2, 2, 2, 2, 2, 2,",
"before calling # initialize_coords def __init__(self, in_channels, out_channels, D=3): ResNetBase.__init__(self,",
"tensor_stride=2 out = self.convtr6p4s2(out) out = self.bntr6(out) out = self.relu(out)",
"= Bottleneck LAYERS = (2, 3, 4, 23, 2, 2,",
"return a tuple of coords, features, and labels. device =",
"self.relu(out) out_b3p8 = self.block3(out) # tensor_stride=16 out = self.conv4p8s2(out_b3p8) out",
"processed, call clear to reset the model before calling #",
"= self.block5(out) # tensor_stride=4 out = self.convtr5p8s2(out) out = self.bntr5(out)",
"ME.MinkowskiReLU(inplace=True) def forward(self, x): out = self.conv0p1s1(x) out = self.bn0(out)",
"= ME.cat((out, out_b1p2)) out = self.block7(out) # tensor_stride=1 out =",
"= (2, 2, 2, 2, 2, 2, 2, 2) class",
"256, 128, 128, 128, 128) class MinkUNet14C(MinkUNet14): PLANES = (32,",
"a tuple of coords, features, and labels. device = torch.device('cuda'",
"from MinkowskiEngine.modules.resnet_block import BasicBlock, Bottleneck from examples.common import data_loader from",
"self.relu(out) out_b2p4 = self.block2(out) out = self.conv3p4s2(out_b2p4) out = self.bn3(out)",
"Bottleneck from examples.common import data_loader from examples.resnet import ResNetBase class",
"out_channels, D): # Output of the first conv concated to",
"2, 2, 2) class MinkUNet101(MinkUNetBase): BLOCK = Bottleneck LAYERS =",
"= self.bn3(out) out = self.relu(out) out_b3p8 = self.block3(out) # tensor_stride=16",
"= self.relu(out) out = ME.cat((out, out_b3p8)) out = self.block5(out) #",
"MinkUNet14A(MinkUNet14): PLANES = (32, 64, 128, 256, 128, 128, 96,",
"INIT_DIM = 32 OUT_TENSOR_STRIDE = 1 # To use the",
"128, 64, 64) class MinkUNet34B(MinkUNet34): PLANES = (32, 64, 128,",
"64) class MinkUNet34B(MinkUNet34): PLANES = (32, 64, 128, 256, 256,",
"out = self.conv4p8s2(out_b3p8) out = self.bn4(out) out = self.relu(out) out",
"self.relu(out) out = self.block4(out) # tensor_stride=8 out = self.convtr4p16s2(out) out",
"256, 128, 64, 32) class MinkUNet34C(MinkUNet34): PLANES = (32, 64,",
"1, 1, 1, 1, 1) LAYERS = (2, 2, 2,",
"a data loader must return a tuple of coords, features,",
"self.block4 = self._make_layer(self.BLOCK, self.PLANES[3], self.LAYERS[3]) self.convtr4p16s2 = ME.MinkowskiConvolutionTranspose( self.inplanes, self.PLANES[4],",
"(1, 1, 1, 1, 1, 1, 1, 1) class MinkUNet18(MinkUNetBase):",
"coords, features, and labels. device = torch.device('cuda' if torch.cuda.is_available() else",
"64, 128, 256, 128, 128, 96, 96) class MinkUNet14B(MinkUNet14): PLANES",
"PLANES = (32, 64, 128, 256, 256, 128, 96, 96)",
"D=3): ResNetBase.__init__(self, in_channels, out_channels, D) def network_initialization(self, in_channels, out_channels, D):",
"= ME.MinkowskiBatchNorm(self.inplanes) self.conv1p1s2 = ME.MinkowskiConvolution( self.inplanes, self.inplanes, kernel_size=2, stride=2, dimension=D)",
"self.bntr5(out) out = self.relu(out) out = ME.cat((out, out_b2p4)) out =",
"= (1, 1, 1, 1, 1, 1, 1, 1) class",
"self.final(out) class MinkUNet14(MinkUNetBase): BLOCK = BasicBlock LAYERS = (1, 1,",
"class MinkUNet34(MinkUNetBase): BLOCK = BasicBlock LAYERS = (2, 3, 4,",
"ME.MinkowskiBatchNorm(self.inplanes) self.block1 = self._make_layer(self.BLOCK, self.PLANES[0], self.LAYERS[0]) self.conv2p2s2 = ME.MinkowskiConvolution( self.inplanes,",
"out = self.bn0(out) out_p1 = self.relu(out) out = self.conv1p1s2(out_p1) out",
"out = self.conv2p2s2(out_b1p2) out = self.bn2(out) out = self.relu(out) out_b2p4",
"= self.bntr7(out) out = self.relu(out) out = ME.cat((out, out_p1)) out",
"self.bn0(out) out_p1 = self.relu(out) out = self.conv1p1s2(out_p1) out = self.bn1(out)",
"3, 4, 6, 2, 2, 2, 2) class MinkUNet101(MinkUNetBase): BLOCK",
"out = self.bn4(out) out = self.relu(out) out = self.block4(out) #",
"128, 256, 128, 128, 128, 128) class MinkUNet18D(MinkUNet18): PLANES =",
"self.PLANES[3], self.LAYERS[3]) self.convtr4p16s2 = ME.MinkowskiConvolutionTranspose( self.inplanes, self.PLANES[4], kernel_size=2, stride=2, dimension=D)",
"data coords, feat, label = data_loader(is_classification=False) input = ME.SparseTensor(feat, coords=coords).to(device)",
"class MinkUNet14A(MinkUNet14): PLANES = (32, 64, 128, 256, 128, 128,",
"out = self.relu(out) out = ME.cat((out, out_b3p8)) out = self.block5(out)",
"64, 64) class MinkUNet34B(MinkUNet34): PLANES = (32, 64, 128, 256,",
"out_b1p2)) out = self.block7(out) # tensor_stride=1 out = self.convtr7p2s2(out) out",
"loader must return a tuple of coords, features, and labels.",
"self.inplanes = self.PLANES[5] + self.PLANES[1] * self.BLOCK.expansion self.block6 = self._make_layer(self.BLOCK,",
"1, 1, 1, 1, 1) class MinkUNet18(MinkUNetBase): BLOCK = BasicBlock",
"self.relu(out) out = self.conv1p1s2(out_p1) out = self.bn1(out) out = self.relu(out)",
"= ME.MinkowskiConvolutionTranspose( self.inplanes, self.PLANES[4], kernel_size=2, stride=2, dimension=D) self.bntr4 = ME.MinkowskiBatchNorm(self.PLANES[4])",
"', Loss: ', loss.item()) # Gradient loss.backward() optimizer.step() # Saving",
"= ME.MinkowskiConvolution( self.inplanes, self.inplanes, kernel_size=2, stride=2, dimension=D) self.bn1 = ME.MinkowskiBatchNorm(self.inplanes)",
"= self.relu(out) out = ME.cat((out, out_b2p4)) out = self.block6(out) #",
"128, 64, 32) class MinkUNet34C(MinkUNet34): PLANES = (32, 64, 128,",
"out = self.relu(out) out = ME.cat((out, out_b2p4)) out = self.block6(out)",
"out_b2p4)) out = self.block6(out) # tensor_stride=2 out = self.convtr6p4s2(out) out",
"self.LAYERS[7]) self.final = ME.MinkowskiConvolution( self.PLANES[7], out_channels, kernel_size=1, has_bias=True, dimension=D) self.relu",
"2, 2, 2) class MinkUNet34(MinkUNetBase): BLOCK = BasicBlock LAYERS =",
"LAYERS = (2, 2, 2, 2, 2, 2, 2, 2)",
"3, 4, 6, 2, 2, 2, 2) class MinkUNet50(MinkUNetBase): BLOCK",
"# a data loader must return a tuple of coords,",
"self.block2(out) out = self.conv3p4s2(out_b2p4) out = self.bn3(out) out = self.relu(out)",
"output = net(input) # Loss loss = criterion(output.F, label) print('Iteration:",
"96) class MinkUNet18B(MinkUNet18): PLANES = (32, 64, 128, 256, 128,",
"= ME.MinkowskiConvolutionTranspose( self.inplanes, self.PLANES[5], kernel_size=2, stride=2, dimension=D) self.bntr5 = ME.MinkowskiBatchNorm(self.PLANES[5])",
"SGD(net.parameters(), lr=1e-2) for i in range(10): optimizer.zero_grad() # Get new",
"256, 128, 128, 96, 96) class MinkUNet18B(MinkUNet18): PLANES = (32,",
"self.bn3(out) out = self.relu(out) out_b3p8 = self.block3(out) # tensor_stride=16 out",
"range(10): optimizer.zero_grad() # Get new data coords, feat, label =",
"128, 128) class MinkUNet14C(MinkUNet14): PLANES = (32, 64, 128, 256,",
"MinkUNet34C(MinkUNet34): PLANES = (32, 64, 128, 256, 256, 128, 96,",
"1, 1, 1, 1, 1, 1) LAYERS = (2, 2,",
"initialize_coords before forward pass. # Once data is processed, call",
"self.INIT_DIM self.block8 = self._make_layer(self.BLOCK, self.PLANES[7], self.LAYERS[7]) self.final = ME.MinkowskiConvolution( self.PLANES[7],",
"384, 384, 384, 384) class MinkUNet18A(MinkUNet18): PLANES = (32, 64,",
"in_channels, out_channels, D) def network_initialization(self, in_channels, out_channels, D): # Output",
"= self.block3(out) # tensor_stride=16 out = self.conv4p8s2(out_b3p8) out = self.bn4(out)",
"in_channels, self.inplanes, kernel_size=5, dimension=D) self.bn0 = ME.MinkowskiBatchNorm(self.inplanes) self.conv1p1s2 = ME.MinkowskiConvolution(",
"out_b2p4 = self.block2(out) out = self.conv3p4s2(out_b2p4) out = self.bn3(out) out",
"MinkUNet14(MinkUNetBase): BLOCK = BasicBlock LAYERS = (1, 1, 1, 1,",
"= ME.MinkowskiConvolution( self.inplanes, self.inplanes, kernel_size=2, stride=2, dimension=D) self.bn3 = ME.MinkowskiBatchNorm(self.inplanes)",
"192, 192, 128, 128) class MinkUNet14D(MinkUNet14): PLANES = (32, 64,",
"', i, ', Loss: ', loss.item()) # Gradient loss.backward() optimizer.step()",
"criterion = nn.CrossEntropyLoss() net = MinkUNet14A(in_channels=3, out_channels=5, D=2) print(net) #",
"6, 2, 2, 2, 2) class MinkUNet50(MinkUNetBase): BLOCK = Bottleneck",
"kernel_size=2, stride=2, dimension=D) self.bn2 = ME.MinkowskiBatchNorm(self.inplanes) self.block2 = self._make_layer(self.BLOCK, self.PLANES[1],",
"# Gradient loss.backward() optimizer.step() # Saving and loading a network",
"= self._make_layer(self.BLOCK, self.PLANES[2], self.LAYERS[2]) self.conv4p8s2 = ME.MinkowskiConvolution( self.inplanes, self.inplanes, kernel_size=2,",
"ME.cat((out, out_b1p2)) out = self.block7(out) # tensor_stride=1 out = self.convtr7p2s2(out)",
"self.block3 = self._make_layer(self.BLOCK, self.PLANES[2], self.LAYERS[2]) self.conv4p8s2 = ME.MinkowskiConvolution( self.inplanes, self.inplanes,",
"kernel_size=5, dimension=D) self.bn0 = ME.MinkowskiBatchNorm(self.inplanes) self.conv1p1s2 = ME.MinkowskiConvolution( self.inplanes, self.inplanes,",
"self.inplanes, kernel_size=5, dimension=D) self.bn0 = ME.MinkowskiBatchNorm(self.inplanes) self.conv1p1s2 = ME.MinkowskiConvolution( self.inplanes,",
"self.inplanes, self.inplanes, kernel_size=2, stride=2, dimension=D) self.bn3 = ME.MinkowskiBatchNorm(self.inplanes) self.block3 =",
"self.bntr4 = ME.MinkowskiBatchNorm(self.PLANES[4]) self.inplanes = self.PLANES[4] + self.PLANES[2] * self.BLOCK.expansion",
"out = self.relu(out) out_b1p2 = self.block1(out) out = self.conv2p2s2(out_b1p2) out",
"self.bn1 = ME.MinkowskiBatchNorm(self.inplanes) self.block1 = self._make_layer(self.BLOCK, self.PLANES[0], self.LAYERS[0]) self.conv2p2s2 =",
"features, and labels. device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')",
"data_loader(is_classification=False) input = ME.SparseTensor(feat, coords=coords).to(device) label = label.to(device) # Forward",
"= ME.MinkowskiConvolutionTranspose( self.inplanes, self.PLANES[6], kernel_size=2, stride=2, dimension=D) self.bntr6 = ME.MinkowskiBatchNorm(self.PLANES[6])",
"# tensor_stride=16 out = self.conv4p8s2(out_b3p8) out = self.bn4(out) out =",
"self._make_layer(self.BLOCK, self.PLANES[2], self.LAYERS[2]) self.conv4p8s2 = ME.MinkowskiConvolution( self.inplanes, self.inplanes, kernel_size=2, stride=2,",
"(32, 64, 128, 256, 384, 384, 384, 384) class MinkUNet18A(MinkUNet18):",
"dimension=D) self.bntr7 = ME.MinkowskiBatchNorm(self.PLANES[7]) self.inplanes = self.PLANES[7] + self.INIT_DIM self.block8",
"PLANES = None DILATIONS = (1, 1, 1, 1, 1,",
"1) LAYERS = (2, 2, 2, 2, 2, 2, 2,",
"= ME.cat((out, out_p1)) out = self.block8(out) return self.final(out) class MinkUNet14(MinkUNetBase):",
"i in range(10): optimizer.zero_grad() # Get new data coords, feat,",
"i, ', Loss: ', loss.item()) # Gradient loss.backward() optimizer.step() #",
"256, 128, 128, 128, 128) class MinkUNet18D(MinkUNet18): PLANES = (32,",
"64, 128, 256, 256, 128, 64, 32) class MinkUNet34C(MinkUNet34): PLANES",
"2, 2) class MinkUNet34(MinkUNetBase): BLOCK = BasicBlock LAYERS = (2,",
"(32, 64, 128, 256, 384, 384, 384, 384) class MinkUNet34A(MinkUNet34):",
"= self.relu(out) out_b1p2 = self.block1(out) out = self.conv2p2s2(out_b1p2) out =",
"= (32, 64, 128, 256, 256, 128, 64, 64) class",
"as ME from MinkowskiEngine.modules.resnet_block import BasicBlock, Bottleneck from examples.common import",
"else 'cpu') net = net.to(device) optimizer = SGD(net.parameters(), lr=1e-2) for",
"384, 384, 384, 384) class MinkUNet34A(MinkUNet34): PLANES = (32, 64,",
"256, 128, 64, 64) class MinkUNet34B(MinkUNet34): PLANES = (32, 64,",
"and labels. device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') net",
"D) def network_initialization(self, in_channels, out_channels, D): # Output of the",
"128, 128, 128) class MinkUNet14C(MinkUNet14): PLANES = (32, 64, 128,",
"torch.device('cuda' if torch.cuda.is_available() else 'cpu') net = net.to(device) optimizer =",
"# Loss loss = criterion(output.F, label) print('Iteration: ', i, ',",
"(32, 64, 128, 256, 128, 128, 96, 96) class MinkUNet18B(MinkUNet18):",
"BasicBlock, Bottleneck from examples.common import data_loader from examples.resnet import ResNetBase",
"# tensor_stride=4 out = self.convtr5p8s2(out) out = self.bntr5(out) out =",
"out_p1)) out = self.block8(out) return self.final(out) class MinkUNet14(MinkUNetBase): BLOCK =",
"class MinkUNetBase(ResNetBase): BLOCK = None PLANES = None DILATIONS =",
"self.inplanes = self.INIT_DIM self.conv0p1s1 = ME.MinkowskiConvolution( in_channels, self.inplanes, kernel_size=5, dimension=D)",
"= ME.MinkowskiConvolution( in_channels, self.inplanes, kernel_size=5, dimension=D) self.bn0 = ME.MinkowskiBatchNorm(self.inplanes) self.conv1p1s2",
"= (32, 64, 128, 256, 256, 128, 96, 96) if",
"ME.MinkowskiConvolutionTranspose( self.inplanes, self.PLANES[6], kernel_size=2, stride=2, dimension=D) self.bntr6 = ME.MinkowskiBatchNorm(self.PLANES[6]) self.inplanes",
"384) class MinkUNet18A(MinkUNet18): PLANES = (32, 64, 128, 256, 128,",
"LAYERS = (2, 3, 4, 6, 2, 2, 2, 2)",
"D=2) print(net) # a data loader must return a tuple",
"384, 384) class MinkUNet18A(MinkUNet18): PLANES = (32, 64, 128, 256,",
"'cpu') net = net.to(device) optimizer = SGD(net.parameters(), lr=1e-2) for i",
"out = self.relu(out) out = ME.cat((out, out_p1)) out = self.block8(out)",
"optimizer.zero_grad() # Get new data coords, feat, label = data_loader(is_classification=False)",
"1, 1, 1, 1, 1, 1, 1) class MinkUNet18(MinkUNetBase): BLOCK",
"64, 128, 256, 384, 384, 384, 384) class MinkUNet34A(MinkUNet34): PLANES",
"= self.block4(out) # tensor_stride=8 out = self.convtr4p16s2(out) out = self.bntr4(out)",
"self.block2 = self._make_layer(self.BLOCK, self.PLANES[1], self.LAYERS[1]) self.conv3p4s2 = ME.MinkowskiConvolution( self.inplanes, self.inplanes,",
"out = self.convtr7p2s2(out) out = self.bntr7(out) out = self.relu(out) out",
"out = self.bn2(out) out = self.relu(out) out_b2p4 = self.block2(out) out",
"import BasicBlock, Bottleneck from examples.common import data_loader from examples.resnet import",
"+ self.PLANES[2] * self.BLOCK.expansion self.block5 = self._make_layer(self.BLOCK, self.PLANES[4], self.LAYERS[4]) self.convtr5p8s2",
"64, 128, 256, 192, 192, 128, 128) class MinkUNet14D(MinkUNet14): PLANES",
"coords, feat, label = data_loader(is_classification=False) input = ME.SparseTensor(feat, coords=coords).to(device) label",
"self.convtr5p8s2(out) out = self.bntr5(out) out = self.relu(out) out = ME.cat((out,",
"= self.block1(out) out = self.conv2p2s2(out_b1p2) out = self.bn2(out) out =",
"stride=2, dimension=D) self.bn3 = ME.MinkowskiBatchNorm(self.inplanes) self.block3 = self._make_layer(self.BLOCK, self.PLANES[2], self.LAYERS[2])",
"4, 6, 2, 2, 2, 2) class MinkUNet101(MinkUNetBase): BLOCK =",
"net = MinkUNet14A(in_channels=3, out_channels=5, D=2) print(net) # a data loader",
"Bottleneck LAYERS = (2, 3, 4, 23, 2, 2, 2,",
"self.LAYERS[0]) self.conv2p2s2 = ME.MinkowskiConvolution( self.inplanes, self.inplanes, kernel_size=2, stride=2, dimension=D) self.bn2",
"# tensor_stride=2 out = self.convtr6p4s2(out) out = self.bntr6(out) out =",
"= self._make_layer(self.BLOCK, self.PLANES[6], self.LAYERS[6]) self.convtr7p2s2 = ME.MinkowskiConvolutionTranspose( self.inplanes, self.PLANES[7], kernel_size=2,",
"23, 2, 2, 2, 2) class MinkUNet14A(MinkUNet14): PLANES = (32,",
"(2, 2, 2, 2, 2, 2, 2, 2) INIT_DIM =",
"nn.CrossEntropyLoss() net = MinkUNet14A(in_channels=3, out_channels=5, D=2) print(net) # a data",
"PLANES = (32, 64, 128, 256, 384, 384, 384, 384)",
"(2, 3, 4, 6, 2, 2, 2, 2) class MinkUNet50(MinkUNetBase):",
"= self._make_layer(self.BLOCK, self.PLANES[7], self.LAYERS[7]) self.final = ME.MinkowskiConvolution( self.PLANES[7], out_channels, kernel_size=1,",
"# To use the model, must call initialize_coords before forward",
"tensor_stride=16 out = self.conv4p8s2(out_b3p8) out = self.bn4(out) out = self.relu(out)",
"128, 128, 128) class MinkUNet18D(MinkUNet18): PLANES = (32, 64, 128,",
"out = ME.cat((out, out_b2p4)) out = self.block6(out) # tensor_stride=2 out",
"6, 2, 2, 2, 2) class MinkUNet101(MinkUNetBase): BLOCK = Bottleneck",
"2) class MinkUNet50(MinkUNetBase): BLOCK = Bottleneck LAYERS = (2, 3,",
"self.inplanes = self.PLANES[4] + self.PLANES[2] * self.BLOCK.expansion self.block5 = self._make_layer(self.BLOCK,",
"1, 1, 1) LAYERS = (2, 2, 2, 2, 2,",
"self.PLANES[6], self.LAYERS[6]) self.convtr7p2s2 = ME.MinkowskiConvolutionTranspose( self.inplanes, self.PLANES[7], kernel_size=2, stride=2, dimension=D)",
"self.inplanes = self.PLANES[6] + self.PLANES[0] * self.BLOCK.expansion self.block7 = self._make_layer(self.BLOCK,",
"self.relu = ME.MinkowskiReLU(inplace=True) def forward(self, x): out = self.conv0p1s1(x) out",
"= (2, 2, 2, 2, 2, 2, 2, 2) INIT_DIM",
"to reset the model before calling # initialize_coords def __init__(self,",
"= net.to(device) optimizer = SGD(net.parameters(), lr=1e-2) for i in range(10):",
"concated to conv6 self.inplanes = self.INIT_DIM self.conv0p1s1 = ME.MinkowskiConvolution( in_channels,",
"tensor_stride=8 out = self.convtr4p16s2(out) out = self.bntr4(out) out = self.relu(out)",
"1, 1, 1, 1, 1, 1) class MinkUNet18(MinkUNetBase): BLOCK =",
"MinkUNet34A(MinkUNet34): PLANES = (32, 64, 128, 256, 256, 128, 64,",
"self._make_layer(self.BLOCK, self.PLANES[7], self.LAYERS[7]) self.final = ME.MinkowskiConvolution( self.PLANES[7], out_channels, kernel_size=1, has_bias=True,",
"calling # initialize_coords def __init__(self, in_channels, out_channels, D=3): ResNetBase.__init__(self, in_channels,",
"(2, 3, 4, 23, 2, 2, 2, 2) class MinkUNet14A(MinkUNet14):",
"tuple of coords, features, and labels. device = torch.device('cuda' if",
"(1, 1, 1, 1, 1, 1, 1, 1) LAYERS =",
"self.PLANES[6], kernel_size=2, stride=2, dimension=D) self.bntr6 = ME.MinkowskiBatchNorm(self.PLANES[6]) self.inplanes = self.PLANES[6]",
"self.LAYERS[6]) self.convtr7p2s2 = ME.MinkowskiConvolutionTranspose( self.inplanes, self.PLANES[7], kernel_size=2, stride=2, dimension=D) self.bntr7",
"1 # To use the model, must call initialize_coords before",
"4, 6, 2, 2, 2, 2) class MinkUNet50(MinkUNetBase): BLOCK =",
"'__main__': # loss and network criterion = nn.CrossEntropyLoss() net =",
"# Output of the first conv concated to conv6 self.inplanes",
"dimension=D) self.bntr4 = ME.MinkowskiBatchNorm(self.PLANES[4]) self.inplanes = self.PLANES[4] + self.PLANES[2] *",
"4, 23, 2, 2, 2, 2) class MinkUNet14A(MinkUNet14): PLANES =",
"self.inplanes, self.inplanes, kernel_size=2, stride=2, dimension=D) self.bn4 = ME.MinkowskiBatchNorm(self.inplanes) self.block4 =",
"= (2, 3, 4, 6, 2, 2, 2, 2) class",
"= self.PLANES[4] + self.PLANES[2] * self.BLOCK.expansion self.block5 = self._make_layer(self.BLOCK, self.PLANES[4],",
"out = self.convtr4p16s2(out) out = self.bntr4(out) out = self.relu(out) out",
"call clear to reset the model before calling # initialize_coords",
"tensor_stride=1 out = self.convtr7p2s2(out) out = self.bntr7(out) out = self.relu(out)",
"self.block8 = self._make_layer(self.BLOCK, self.PLANES[7], self.LAYERS[7]) self.final = ME.MinkowskiConvolution( self.PLANES[7], out_channels,",
"128) class MinkUNet18D(MinkUNet18): PLANES = (32, 64, 128, 256, 384,",
"self.LAYERS[5]) self.convtr6p4s2 = ME.MinkowskiConvolutionTranspose( self.inplanes, self.PLANES[6], kernel_size=2, stride=2, dimension=D) self.bntr6",
"MinkUNet50(MinkUNetBase): BLOCK = Bottleneck LAYERS = (2, 3, 4, 6,",
"2) class MinkUNet101(MinkUNetBase): BLOCK = Bottleneck LAYERS = (2, 3,",
"out_channels, D) def network_initialization(self, in_channels, out_channels, D): # Output of",
"data_loader from examples.resnet import ResNetBase class MinkUNetBase(ResNetBase): BLOCK = None",
"ME.MinkowskiBatchNorm(self.PLANES[5]) self.inplanes = self.PLANES[5] + self.PLANES[1] * self.BLOCK.expansion self.block6 =",
"# Once data is processed, call clear to reset the",
"self.inplanes, self.inplanes, kernel_size=2, stride=2, dimension=D) self.bn1 = ME.MinkowskiBatchNorm(self.inplanes) self.block1 =",
"out = self.bn3(out) out = self.relu(out) out_b3p8 = self.block3(out) #",
"PLANES = (32, 64, 128, 256, 128, 128, 96, 96)",
"self.PLANES[5], kernel_size=2, stride=2, dimension=D) self.bntr5 = ME.MinkowskiBatchNorm(self.PLANES[5]) self.inplanes = self.PLANES[5]",
"= torch.device('cuda' if torch.cuda.is_available() else 'cpu') net = net.to(device) optimizer",
"kernel_size=2, stride=2, dimension=D) self.bntr4 = ME.MinkowskiBatchNorm(self.PLANES[4]) self.inplanes = self.PLANES[4] +",
"256, 384, 384, 384, 384) class MinkUNet18A(MinkUNet18): PLANES = (32,",
"out_b3p8 = self.block3(out) # tensor_stride=16 out = self.conv4p8s2(out_b3p8) out =",
"64, 128, 256, 128, 128, 128, 128) class MinkUNet18D(MinkUNet18): PLANES",
"= ME.MinkowskiReLU(inplace=True) def forward(self, x): out = self.conv0p1s1(x) out =",
"MinkUNet14B(MinkUNet14): PLANES = (32, 64, 128, 256, 128, 128, 128,",
"= criterion(output.F, label) print('Iteration: ', i, ', Loss: ', loss.item())",
"# loss and network criterion = nn.CrossEntropyLoss() net = MinkUNet14A(in_channels=3,",
"= self.block7(out) # tensor_stride=1 out = self.convtr7p2s2(out) out = self.bntr7(out)",
"MinkUNet18(MinkUNetBase): BLOCK = BasicBlock LAYERS = (2, 2, 2, 2,",
"128, 128, 96, 96) class MinkUNet18B(MinkUNet18): PLANES = (32, 64,",
"before forward pass. # Once data is processed, call clear",
"self.PLANES[5], self.LAYERS[5]) self.convtr6p4s2 = ME.MinkowskiConvolutionTranspose( self.inplanes, self.PLANES[6], kernel_size=2, stride=2, dimension=D)",
"out = self.conv3p4s2(out_b2p4) out = self.bn3(out) out = self.relu(out) out_b3p8",
"(32, 64, 128, 256, 128, 128, 96, 96) class MinkUNet14B(MinkUNet14):",
"net(input) # Loss loss = criterion(output.F, label) print('Iteration: ', i,",
"label) print('Iteration: ', i, ', Loss: ', loss.item()) # Gradient",
"To use the model, must call initialize_coords before forward pass.",
"= self.relu(out) out = ME.cat((out, out_b1p2)) out = self.block7(out) #",
"out = self.bntr6(out) out = self.relu(out) out = ME.cat((out, out_b1p2))",
"of the first conv concated to conv6 self.inplanes = self.INIT_DIM",
"PLANES = (32, 64, 128, 256, 256, 128, 64, 32)",
"128, 128, 96, 96) class MinkUNet14B(MinkUNet14): PLANES = (32, 64,",
"MinkUNet14C(MinkUNet14): PLANES = (32, 64, 128, 256, 192, 192, 128,",
"self.bntr5 = ME.MinkowskiBatchNorm(self.PLANES[5]) self.inplanes = self.PLANES[5] + self.PLANES[1] * self.BLOCK.expansion",
"stride=2, dimension=D) self.bn1 = ME.MinkowskiBatchNorm(self.inplanes) self.block1 = self._make_layer(self.BLOCK, self.PLANES[0], self.LAYERS[0])",
"= self.relu(out) out_b2p4 = self.block2(out) out = self.conv3p4s2(out_b2p4) out =",
"dimension=D) self.bn1 = ME.MinkowskiBatchNorm(self.inplanes) self.block1 = self._make_layer(self.BLOCK, self.PLANES[0], self.LAYERS[0]) self.conv2p2s2",
"conv concated to conv6 self.inplanes = self.INIT_DIM self.conv0p1s1 = ME.MinkowskiConvolution(",
"import SGD import MinkowskiEngine as ME from MinkowskiEngine.modules.resnet_block import BasicBlock,",
"self.PLANES[2], self.LAYERS[2]) self.conv4p8s2 = ME.MinkowskiConvolution( self.inplanes, self.inplanes, kernel_size=2, stride=2, dimension=D)",
"= ME.MinkowskiBatchNorm(self.PLANES[5]) self.inplanes = self.PLANES[5] + self.PLANES[1] * self.BLOCK.expansion self.block6",
"stride=2, dimension=D) self.bntr4 = ME.MinkowskiBatchNorm(self.PLANES[4]) self.inplanes = self.PLANES[4] + self.PLANES[2]",
"out_b1p2 = self.block1(out) out = self.conv2p2s2(out_b1p2) out = self.bn2(out) out",
"self.block7(out) # tensor_stride=1 out = self.convtr7p2s2(out) out = self.bntr7(out) out",
"out = self.relu(out) out = self.block4(out) # tensor_stride=8 out =",
"(2, 3, 4, 6, 2, 2, 2, 2) class MinkUNet101(MinkUNetBase):",
"= self.PLANES[7] + self.INIT_DIM self.block8 = self._make_layer(self.BLOCK, self.PLANES[7], self.LAYERS[7]) self.final",
"kernel_size=2, stride=2, dimension=D) self.bntr6 = ME.MinkowskiBatchNorm(self.PLANES[6]) self.inplanes = self.PLANES[6] +",
"128, 256, 128, 128, 96, 96) class MinkUNet14B(MinkUNet14): PLANES =",
"initialize_coords def __init__(self, in_channels, out_channels, D=3): ResNetBase.__init__(self, in_channels, out_channels, D)",
"self.block5(out) # tensor_stride=4 out = self.convtr5p8s2(out) out = self.bntr5(out) out",
"out = self.block6(out) # tensor_stride=2 out = self.convtr6p4s2(out) out =",
"128, 128) class MinkUNet18D(MinkUNet18): PLANES = (32, 64, 128, 256,",
"dimension=D) self.bntr6 = ME.MinkowskiBatchNorm(self.PLANES[6]) self.inplanes = self.PLANES[6] + self.PLANES[0] *",
"= BasicBlock LAYERS = (1, 1, 1, 1, 1, 1,",
"optimizer.step() # Saving and loading a network torch.save(net.state_dict(), 'test.pth') net.load_state_dict(torch.load('test.pth'))",
"64, 32) class MinkUNet34C(MinkUNet34): PLANES = (32, 64, 128, 256,",
"dimension=D) self.bn2 = ME.MinkowskiBatchNorm(self.inplanes) self.block2 = self._make_layer(self.BLOCK, self.PLANES[1], self.LAYERS[1]) self.conv3p4s2",
"2, 2) class MinkUNet101(MinkUNetBase): BLOCK = Bottleneck LAYERS = (2,",
"# Forward output = net(input) # Loss loss = criterion(output.F,",
"= self.bn4(out) out = self.relu(out) out = self.block4(out) # tensor_stride=8",
"192, 128, 128) class MinkUNet14D(MinkUNet14): PLANES = (32, 64, 128,",
"self._make_layer(self.BLOCK, self.PLANES[4], self.LAYERS[4]) self.convtr5p8s2 = ME.MinkowskiConvolutionTranspose( self.inplanes, self.PLANES[5], kernel_size=2, stride=2,",
"2, 2, 2, 2, 2, 2, 2) class MinkUNet34(MinkUNetBase): BLOCK",
"the model before calling # initialize_coords def __init__(self, in_channels, out_channels,",
"= self.block6(out) # tensor_stride=2 out = self.convtr6p4s2(out) out = self.bntr6(out)",
"= data_loader(is_classification=False) input = ME.SparseTensor(feat, coords=coords).to(device) label = label.to(device) #",
"out = ME.cat((out, out_p1)) out = self.block8(out) return self.final(out) class",
"out = self.block4(out) # tensor_stride=8 out = self.convtr4p16s2(out) out =",
"256, 192, 192, 128, 128) class MinkUNet14D(MinkUNet14): PLANES = (32,",
"MinkUNet14D(MinkUNet14): PLANES = (32, 64, 128, 256, 384, 384, 384,",
"out = self.bntr5(out) out = self.relu(out) out = ME.cat((out, out_b2p4))",
"= None PLANES = None DILATIONS = (1, 1, 1,",
"* self.BLOCK.expansion self.block5 = self._make_layer(self.BLOCK, self.PLANES[4], self.LAYERS[4]) self.convtr5p8s2 = ME.MinkowskiConvolutionTranspose(",
"def __init__(self, in_channels, out_channels, D=3): ResNetBase.__init__(self, in_channels, out_channels, D) def",
"256, 384, 384, 384, 384) class MinkUNet34A(MinkUNet34): PLANES = (32,",
"self.PLANES[4] + self.PLANES[2] * self.BLOCK.expansion self.block5 = self._make_layer(self.BLOCK, self.PLANES[4], self.LAYERS[4])",
"= self.convtr4p16s2(out) out = self.bntr4(out) out = self.relu(out) out =",
"= self.PLANES[5] + self.PLANES[1] * self.BLOCK.expansion self.block6 = self._make_layer(self.BLOCK, self.PLANES[5],",
"out = self.block7(out) # tensor_stride=1 out = self.convtr7p2s2(out) out =",
"dimension=D) self.bn3 = ME.MinkowskiBatchNorm(self.inplanes) self.block3 = self._make_layer(self.BLOCK, self.PLANES[2], self.LAYERS[2]) self.conv4p8s2",
"= self.convtr7p2s2(out) out = self.bntr7(out) out = self.relu(out) out =",
"2) class MinkUNet14A(MinkUNet14): PLANES = (32, 64, 128, 256, 128,",
"= ME.MinkowskiBatchNorm(self.PLANES[6]) self.inplanes = self.PLANES[6] + self.PLANES[0] * self.BLOCK.expansion self.block7",
"= ME.SparseTensor(feat, coords=coords).to(device) label = label.to(device) # Forward output =",
"self.convtr4p16s2(out) out = self.bntr4(out) out = self.relu(out) out = ME.cat((out,",
"pass. # Once data is processed, call clear to reset",
"out = self.relu(out) out_b2p4 = self.block2(out) out = self.conv3p4s2(out_b2p4) out",
"MinkUNet34(MinkUNetBase): BLOCK = BasicBlock LAYERS = (2, 3, 4, 6,",
"= self._make_layer(self.BLOCK, self.PLANES[4], self.LAYERS[4]) self.convtr5p8s2 = ME.MinkowskiConvolutionTranspose( self.inplanes, self.PLANES[5], kernel_size=2,",
"stride=2, dimension=D) self.bntr6 = ME.MinkowskiBatchNorm(self.PLANES[6]) self.inplanes = self.PLANES[6] + self.PLANES[0]",
"ME.MinkowskiConvolution( self.inplanes, self.inplanes, kernel_size=2, stride=2, dimension=D) self.bn4 = ME.MinkowskiBatchNorm(self.inplanes) self.block4",
"2, 2, 2, 2, 2) INIT_DIM = 32 OUT_TENSOR_STRIDE =",
"self.block3(out) # tensor_stride=16 out = self.conv4p8s2(out_b3p8) out = self.bn4(out) out",
"= self.conv0p1s1(x) out = self.bn0(out) out_p1 = self.relu(out) out =",
"forward(self, x): out = self.conv0p1s1(x) out = self.bn0(out) out_p1 =",
"forward pass. # Once data is processed, call clear to",
"data is processed, call clear to reset the model before",
"= Bottleneck LAYERS = (2, 3, 4, 6, 2, 2,",
"256, 128, 128, 96, 96) class MinkUNet14B(MinkUNet14): PLANES = (32,",
"print(net) # a data loader must return a tuple of",
"out = ME.cat((out, out_b3p8)) out = self.block5(out) # tensor_stride=4 out",
"self.relu(out) out = ME.cat((out, out_b2p4)) out = self.block6(out) # tensor_stride=2",
"out = self.conv0p1s1(x) out = self.bn0(out) out_p1 = self.relu(out) out",
"new data coords, feat, label = data_loader(is_classification=False) input = ME.SparseTensor(feat,",
"self.block6 = self._make_layer(self.BLOCK, self.PLANES[5], self.LAYERS[5]) self.convtr6p4s2 = ME.MinkowskiConvolutionTranspose( self.inplanes, self.PLANES[6],",
"ME.MinkowskiBatchNorm(self.PLANES[6]) self.inplanes = self.PLANES[6] + self.PLANES[0] * self.BLOCK.expansion self.block7 =",
"ME.MinkowskiConvolutionTranspose( self.inplanes, self.PLANES[4], kernel_size=2, stride=2, dimension=D) self.bntr4 = ME.MinkowskiBatchNorm(self.PLANES[4]) self.inplanes",
"self.bn2(out) out = self.relu(out) out_b2p4 = self.block2(out) out = self.conv3p4s2(out_b2p4)",
"ME.cat((out, out_p1)) out = self.block8(out) return self.final(out) class MinkUNet14(MinkUNetBase): BLOCK",
"128, 256, 128, 128, 96, 96) class MinkUNet18B(MinkUNet18): PLANES =",
"label = data_loader(is_classification=False) input = ME.SparseTensor(feat, coords=coords).to(device) label = label.to(device)",
"self.inplanes, self.PLANES[5], kernel_size=2, stride=2, dimension=D) self.bntr5 = ME.MinkowskiBatchNorm(self.PLANES[5]) self.inplanes =",
"dimension=D) self.bn4 = ME.MinkowskiBatchNorm(self.inplanes) self.block4 = self._make_layer(self.BLOCK, self.PLANES[3], self.LAYERS[3]) self.convtr4p16s2",
"ME.MinkowskiBatchNorm(self.PLANES[4]) self.inplanes = self.PLANES[4] + self.PLANES[2] * self.BLOCK.expansion self.block5 =",
"self.LAYERS[2]) self.conv4p8s2 = ME.MinkowskiConvolution( self.inplanes, self.inplanes, kernel_size=2, stride=2, dimension=D) self.bn4",
"= self.relu(out) out = self.conv1p1s2(out_p1) out = self.bn1(out) out =",
"Forward output = net(input) # Loss loss = criterion(output.F, label)",
"out = self.bn1(out) out = self.relu(out) out_b1p2 = self.block1(out) out",
"self.conv1p1s2(out_p1) out = self.bn1(out) out = self.relu(out) out_b1p2 = self.block1(out)",
"class MinkUNet34B(MinkUNet34): PLANES = (32, 64, 128, 256, 256, 128,",
"2, 2, 2, 2, 2, 2) class MinkUNet34(MinkUNetBase): BLOCK =",
"self._make_layer(self.BLOCK, self.PLANES[6], self.LAYERS[6]) self.convtr7p2s2 = ME.MinkowskiConvolutionTranspose( self.inplanes, self.PLANES[7], kernel_size=2, stride=2,",
"self.PLANES[2] * self.BLOCK.expansion self.block5 = self._make_layer(self.BLOCK, self.PLANES[4], self.LAYERS[4]) self.convtr5p8s2 =",
"+ self.PLANES[1] * self.BLOCK.expansion self.block6 = self._make_layer(self.BLOCK, self.PLANES[5], self.LAYERS[5]) self.convtr6p4s2",
"= ME.MinkowskiBatchNorm(self.PLANES[4]) self.inplanes = self.PLANES[4] + self.PLANES[2] * self.BLOCK.expansion self.block5",
"BLOCK = BasicBlock LAYERS = (2, 3, 4, 6, 2,",
"128, 128) class MinkUNet14D(MinkUNet14): PLANES = (32, 64, 128, 256,",
"128, 256, 192, 192, 128, 128) class MinkUNet14D(MinkUNet14): PLANES =",
"net = net.to(device) optimizer = SGD(net.parameters(), lr=1e-2) for i in",
"class MinkUNet101(MinkUNetBase): BLOCK = Bottleneck LAYERS = (2, 3, 4,",
"self.bn4(out) out = self.relu(out) out = self.block4(out) # tensor_stride=8 out",
"self.conv0p1s1(x) out = self.bn0(out) out_p1 = self.relu(out) out = self.conv1p1s2(out_p1)",
"self.inplanes, kernel_size=2, stride=2, dimension=D) self.bn2 = ME.MinkowskiBatchNorm(self.inplanes) self.block2 = self._make_layer(self.BLOCK,",
"loss and network criterion = nn.CrossEntropyLoss() net = MinkUNet14A(in_channels=3, out_channels=5,",
"= 32 OUT_TENSOR_STRIDE = 1 # To use the model,",
"loss = criterion(output.F, label) print('Iteration: ', i, ', Loss: ',",
"self.inplanes, kernel_size=2, stride=2, dimension=D) self.bn3 = ME.MinkowskiBatchNorm(self.inplanes) self.block3 = self._make_layer(self.BLOCK,",
"2, 2, 2) class MinkUNet14A(MinkUNet14): PLANES = (32, 64, 128,",
"= label.to(device) # Forward output = net(input) # Loss loss",
"out = self.conv1p1s2(out_p1) out = self.bn1(out) out = self.relu(out) out_b1p2",
"(32, 64, 128, 256, 192, 192, 128, 128) class MinkUNet14D(MinkUNet14):",
"= ME.MinkowskiBatchNorm(self.inplanes) self.block1 = self._make_layer(self.BLOCK, self.PLANES[0], self.LAYERS[0]) self.conv2p2s2 = ME.MinkowskiConvolution(",
"self.bn3 = ME.MinkowskiBatchNorm(self.inplanes) self.block3 = self._make_layer(self.BLOCK, self.PLANES[2], self.LAYERS[2]) self.conv4p8s2 =",
"self.bn0 = ME.MinkowskiBatchNorm(self.inplanes) self.conv1p1s2 = ME.MinkowskiConvolution( self.inplanes, self.inplanes, kernel_size=2, stride=2,",
"clear to reset the model before calling # initialize_coords def",
"= MinkUNet14A(in_channels=3, out_channels=5, D=2) print(net) # a data loader must",
"1, 1) class MinkUNet18(MinkUNetBase): BLOCK = BasicBlock LAYERS = (2,",
"out_p1 = self.relu(out) out = self.conv1p1s2(out_p1) out = self.bn1(out) out",
"self.bntr7(out) out = self.relu(out) out = ME.cat((out, out_p1)) out =",
"3, 4, 23, 2, 2, 2, 2) class MinkUNet14A(MinkUNet14): PLANES",
"* self.BLOCK.expansion self.block7 = self._make_layer(self.BLOCK, self.PLANES[6], self.LAYERS[6]) self.convtr7p2s2 = ME.MinkowskiConvolutionTranspose(",
"(32, 64, 128, 256, 256, 128, 96, 96) if __name__",
"import MinkowskiEngine as ME from MinkowskiEngine.modules.resnet_block import BasicBlock, Bottleneck from",
"(32, 64, 128, 256, 256, 128, 64, 32) class MinkUNet34C(MinkUNet34):",
"64, 128, 256, 256, 128, 96, 96) if __name__ ==",
"1) class MinkUNet18(MinkUNetBase): BLOCK = BasicBlock LAYERS = (2, 2,",
"128, 256, 384, 384, 384, 384) class MinkUNet18A(MinkUNet18): PLANES =",
"ME.MinkowskiConvolutionTranspose( self.inplanes, self.PLANES[7], kernel_size=2, stride=2, dimension=D) self.bntr7 = ME.MinkowskiBatchNorm(self.PLANES[7]) self.inplanes",
"64, 128, 256, 256, 128, 64, 64) class MinkUNet34B(MinkUNet34): PLANES",
"self.bn4 = ME.MinkowskiBatchNorm(self.inplanes) self.block4 = self._make_layer(self.BLOCK, self.PLANES[3], self.LAYERS[3]) self.convtr4p16s2 =",
"LAYERS = (1, 1, 1, 1, 1, 1, 1, 1)",
"coords=coords).to(device) label = label.to(device) # Forward output = net(input) #",
"self.conv3p4s2(out_b2p4) out = self.bn3(out) out = self.relu(out) out_b3p8 = self.block3(out)",
"Gradient loss.backward() optimizer.step() # Saving and loading a network torch.save(net.state_dict(),",
"class MinkUNet34A(MinkUNet34): PLANES = (32, 64, 128, 256, 256, 128,",
"= self.convtr6p4s2(out) out = self.bntr6(out) out = self.relu(out) out =",
"self.block8(out) return self.final(out) class MinkUNet14(MinkUNetBase): BLOCK = BasicBlock LAYERS =",
"', loss.item()) # Gradient loss.backward() optimizer.step() # Saving and loading",
"2, 2, 2, 2, 2) class MinkUNet34(MinkUNetBase): BLOCK = BasicBlock",
"self.convtr5p8s2 = ME.MinkowskiConvolutionTranspose( self.inplanes, self.PLANES[5], kernel_size=2, stride=2, dimension=D) self.bntr5 =",
"self.PLANES[4], kernel_size=2, stride=2, dimension=D) self.bntr4 = ME.MinkowskiBatchNorm(self.PLANES[4]) self.inplanes = self.PLANES[4]",
"device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') net = net.to(device)",
"2, 2, 2, 2, 2, 2) INIT_DIM = 32 OUT_TENSOR_STRIDE",
"of coords, features, and labels. device = torch.device('cuda' if torch.cuda.is_available()",
"feat, label = data_loader(is_classification=False) input = ME.SparseTensor(feat, coords=coords).to(device) label =",
"out = self.relu(out) out = ME.cat((out, out_b1p2)) out = self.block7(out)",
"input = ME.SparseTensor(feat, coords=coords).to(device) label = label.to(device) # Forward output",
"out_channels, D=3): ResNetBase.__init__(self, in_channels, out_channels, D) def network_initialization(self, in_channels, out_channels,",
"ME.cat((out, out_b2p4)) out = self.block6(out) # tensor_stride=2 out = self.convtr6p4s2(out)",
"__name__ == '__main__': # loss and network criterion = nn.CrossEntropyLoss()",
"32 OUT_TENSOR_STRIDE = 1 # To use the model, must",
"stride=2, dimension=D) self.bntr7 = ME.MinkowskiBatchNorm(self.PLANES[7]) self.inplanes = self.PLANES[7] + self.INIT_DIM",
"# initialize_coords def __init__(self, in_channels, out_channels, D=3): ResNetBase.__init__(self, in_channels, out_channels,",
"self.convtr7p2s2 = ME.MinkowskiConvolutionTranspose( self.inplanes, self.PLANES[7], kernel_size=2, stride=2, dimension=D) self.bntr7 =",
"2, 2, 2, 2) class MinkUNet101(MinkUNetBase): BLOCK = Bottleneck LAYERS",
"96) class MinkUNet14B(MinkUNet14): PLANES = (32, 64, 128, 256, 128,",
"if torch.cuda.is_available() else 'cpu') net = net.to(device) optimizer = SGD(net.parameters(),",
"print('Iteration: ', i, ', Loss: ', loss.item()) # Gradient loss.backward()",
"2, 2, 2) class MinkUNet50(MinkUNetBase): BLOCK = Bottleneck LAYERS =",
"= net(input) # Loss loss = criterion(output.F, label) print('Iteration: ',",
"self.bntr6(out) out = self.relu(out) out = ME.cat((out, out_b1p2)) out =",
"= self.bn1(out) out = self.relu(out) out_b1p2 = self.block1(out) out =",
"torch.cuda.is_available() else 'cpu') net = net.to(device) optimizer = SGD(net.parameters(), lr=1e-2)",
"kernel_size=1, has_bias=True, dimension=D) self.relu = ME.MinkowskiReLU(inplace=True) def forward(self, x): out",
"stride=2, dimension=D) self.bntr5 = ME.MinkowskiBatchNorm(self.PLANES[5]) self.inplanes = self.PLANES[5] + self.PLANES[1]",
"= ME.MinkowskiConvolution( self.inplanes, self.inplanes, kernel_size=2, stride=2, dimension=D) self.bn4 = ME.MinkowskiBatchNorm(self.inplanes)",
"= self._make_layer(self.BLOCK, self.PLANES[0], self.LAYERS[0]) self.conv2p2s2 = ME.MinkowskiConvolution( self.inplanes, self.inplanes, kernel_size=2,",
"self.relu(out) out = ME.cat((out, out_p1)) out = self.block8(out) return self.final(out)",
"from torch.optim import SGD import MinkowskiEngine as ME from MinkowskiEngine.modules.resnet_block",
"ME.MinkowskiConvolution( self.inplanes, self.inplanes, kernel_size=2, stride=2, dimension=D) self.bn3 = ME.MinkowskiBatchNorm(self.inplanes) self.block3",
"2, 2, 2) INIT_DIM = 32 OUT_TENSOR_STRIDE = 1 #",
"= self.bntr4(out) out = self.relu(out) out = ME.cat((out, out_b3p8)) out",
"MinkUNet18B(MinkUNet18): PLANES = (32, 64, 128, 256, 128, 128, 128,",
"+ self.INIT_DIM self.block8 = self._make_layer(self.BLOCK, self.PLANES[7], self.LAYERS[7]) self.final = ME.MinkowskiConvolution(",
"class MinkUNet14C(MinkUNet14): PLANES = (32, 64, 128, 256, 192, 192,",
"self.PLANES[5] + self.PLANES[1] * self.BLOCK.expansion self.block6 = self._make_layer(self.BLOCK, self.PLANES[5], self.LAYERS[5])",
"= self.bn0(out) out_p1 = self.relu(out) out = self.conv1p1s2(out_p1) out =",
"= self.conv1p1s2(out_p1) out = self.bn1(out) out = self.relu(out) out_b1p2 =",
"class MinkUNet14B(MinkUNet14): PLANES = (32, 64, 128, 256, 128, 128,",
"from examples.resnet import ResNetBase class MinkUNetBase(ResNetBase): BLOCK = None PLANES",
"dimension=D) self.bn0 = ME.MinkowskiBatchNorm(self.inplanes) self.conv1p1s2 = ME.MinkowskiConvolution( self.inplanes, self.inplanes, kernel_size=2,",
"128, 96, 96) class MinkUNet14B(MinkUNet14): PLANES = (32, 64, 128,",
"128) class MinkUNet14C(MinkUNet14): PLANES = (32, 64, 128, 256, 192,",
"self.bntr4(out) out = self.relu(out) out = ME.cat((out, out_b3p8)) out =",
"class MinkUNet14D(MinkUNet14): PLANES = (32, 64, 128, 256, 384, 384,"
] |
[
"from setuptools import setup setup( name='nginx-access-tailer', version='0.1', author='swfrench', url='https://github.com/swfrench/nginx-tailer', packages=['nginx_access_tailer',],",
"version='0.1', author='swfrench', url='https://github.com/swfrench/nginx-tailer', packages=['nginx_access_tailer',], license='BSD three-clause license', entry_points={ 'console_scripts': ['nginx-access-tailer",
"'python-gflags >= 3.1.1', 'google-cloud-monitoring >= 0.25.0', ], test_suite='nose.collector', tests_require=['nose', 'mock'],",
"['nginx-access-tailer = nginx_access_tailer.__main__:main'], }, install_requires=[ 'python-gflags >= 3.1.1', 'google-cloud-monitoring >=",
"'console_scripts': ['nginx-access-tailer = nginx_access_tailer.__main__:main'], }, install_requires=[ 'python-gflags >= 3.1.1', 'google-cloud-monitoring",
">= 3.1.1', 'google-cloud-monitoring >= 0.25.0', ], test_suite='nose.collector', tests_require=['nose', 'mock'], )",
"= nginx_access_tailer.__main__:main'], }, install_requires=[ 'python-gflags >= 3.1.1', 'google-cloud-monitoring >= 0.25.0',",
"entry_points={ 'console_scripts': ['nginx-access-tailer = nginx_access_tailer.__main__:main'], }, install_requires=[ 'python-gflags >= 3.1.1',",
"url='https://github.com/swfrench/nginx-tailer', packages=['nginx_access_tailer',], license='BSD three-clause license', entry_points={ 'console_scripts': ['nginx-access-tailer = nginx_access_tailer.__main__:main'],",
"import setup setup( name='nginx-access-tailer', version='0.1', author='swfrench', url='https://github.com/swfrench/nginx-tailer', packages=['nginx_access_tailer',], license='BSD three-clause",
"install_requires=[ 'python-gflags >= 3.1.1', 'google-cloud-monitoring >= 0.25.0', ], test_suite='nose.collector', tests_require=['nose',",
"nginx_access_tailer.__main__:main'], }, install_requires=[ 'python-gflags >= 3.1.1', 'google-cloud-monitoring >= 0.25.0', ],",
"packages=['nginx_access_tailer',], license='BSD three-clause license', entry_points={ 'console_scripts': ['nginx-access-tailer = nginx_access_tailer.__main__:main'], },",
"setup setup( name='nginx-access-tailer', version='0.1', author='swfrench', url='https://github.com/swfrench/nginx-tailer', packages=['nginx_access_tailer',], license='BSD three-clause license',",
"license='BSD three-clause license', entry_points={ 'console_scripts': ['nginx-access-tailer = nginx_access_tailer.__main__:main'], }, install_requires=[",
"setup( name='nginx-access-tailer', version='0.1', author='swfrench', url='https://github.com/swfrench/nginx-tailer', packages=['nginx_access_tailer',], license='BSD three-clause license', entry_points={",
"name='nginx-access-tailer', version='0.1', author='swfrench', url='https://github.com/swfrench/nginx-tailer', packages=['nginx_access_tailer',], license='BSD three-clause license', entry_points={ 'console_scripts':",
"setuptools import setup setup( name='nginx-access-tailer', version='0.1', author='swfrench', url='https://github.com/swfrench/nginx-tailer', packages=['nginx_access_tailer',], license='BSD",
"three-clause license', entry_points={ 'console_scripts': ['nginx-access-tailer = nginx_access_tailer.__main__:main'], }, install_requires=[ 'python-gflags",
"\"\"\"TODO.\"\"\" from setuptools import setup setup( name='nginx-access-tailer', version='0.1', author='swfrench', url='https://github.com/swfrench/nginx-tailer',",
"}, install_requires=[ 'python-gflags >= 3.1.1', 'google-cloud-monitoring >= 0.25.0', ], test_suite='nose.collector',",
"author='swfrench', url='https://github.com/swfrench/nginx-tailer', packages=['nginx_access_tailer',], license='BSD three-clause license', entry_points={ 'console_scripts': ['nginx-access-tailer =",
"license', entry_points={ 'console_scripts': ['nginx-access-tailer = nginx_access_tailer.__main__:main'], }, install_requires=[ 'python-gflags >="
] |
[
"# # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law",
"\"path\": \"/cmk/tests/data/config/minimal\", \"pools\": { \"exclusive\": { \"cpuLists\": { \"0\": {",
"\"cpuLists\": { \"0-2,8-10\": { \"cpus\": \"0-2,8-10\", \"tasks\": [ 3000, 3001,",
"# # Licensed under the Apache License, Version 2.0 (the",
"compliance with the License. # You may obtain a copy",
"an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF",
"2.0 (the \"License\"); # you may not use this file",
"agreed to in writing, software # distributed under the License",
"file except in compliance with the License. # You may",
"on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS",
"Unless required by applicable law or agreed to in writing,",
"permissions and # limitations under the License. from .. import",
"\"tasks\": [ 2003 ] } }, \"exclusive\": true, \"name\": \"exclusive\"",
"distributed under the License is distributed on an \"AS IS\"",
"[ 2003 ] } }, \"exclusive\": true, \"name\": \"exclusive\" },",
"\"exclusive\": true, \"name\": \"exclusive\" }, \"infra\": { \"cpuLists\": { \"0-2,8-10\":",
"\"pools\": { \"exclusive\": { \"cpuLists\": { \"0\": { \"cpus\": \"0\",",
"(c) 2017 Intel Corporation # # Licensed under the Apache",
"args = [\"describe\", \"--conf-dir={}\".format(helpers.conf_dir(\"ok\"))] assert helpers.execute(integration.cmk(), args) == b\"\"\"{ \"path\":",
"\"cpus\": \"5,13\", \"tasks\": [ 2001 ] }, \"6,14\": { \"cpus\":",
"under the License. from .. import helpers from . import",
"\"0\": { \"cpus\": \"0\", \"tasks\": [] } }, \"exclusive\": true,",
"def test_cmk_describe_minimal(): args = [\"describe\", \"--conf-dir={}\".format(helpers.conf_dir(\"minimal\"))] assert helpers.execute(integration.cmk(), args) ==",
"{ \"cpuLists\": { \"0\": { \"cpus\": \"0\", \"tasks\": [] }",
"\"shared\": { \"cpuLists\": { \"0\": { \"cpus\": \"0\", \"tasks\": []",
"}, \"6,14\": { \"cpus\": \"6,14\", \"tasks\": [ 2002 ] },",
"the specific language governing permissions and # limitations under the",
"assert helpers.execute(integration.cmk(), args) == b\"\"\"{ \"path\": \"/cmk/tests/data/config/minimal\", \"pools\": { \"exclusive\":",
"{ \"cpus\": \"4,12\", \"tasks\": [ 2000 ] }, \"5,13\": {",
"# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express",
"}, \"shared\": { \"cpuLists\": { \"3,11\": { \"cpus\": \"3,11\", \"tasks\":",
"\"exclusive\": true, \"name\": \"exclusive\" }, \"shared\": { \"cpuLists\": { \"0\":",
"[] } }, \"exclusive\": false, \"name\": \"shared\" } } }",
"express or implied. # See the License for the specific",
"applicable law or agreed to in writing, software # distributed",
"from .. import helpers from . import integration def test_cmk_describe_ok():",
"\"4,12\": { \"cpus\": \"4,12\", \"tasks\": [ 2000 ] }, \"5,13\":",
"except in compliance with the License. # You may obtain",
"}, \"exclusive\": true, \"name\": \"exclusive\" }, \"infra\": { \"cpuLists\": {",
"of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless",
"{ \"0-2,8-10\": { \"cpus\": \"0-2,8-10\", \"tasks\": [ 3000, 3001, 3002",
"{ \"cpus\": \"0-2,8-10\", \"tasks\": [ 3000, 3001, 3002 ] }",
"\"tasks\": [ 3000, 3001, 3002 ] } }, \"exclusive\": false,",
"Intel Corporation # # Licensed under the Apache License, Version",
"\"\"\" def test_cmk_describe_minimal(): args = [\"describe\", \"--conf-dir={}\".format(helpers.conf_dir(\"minimal\"))] assert helpers.execute(integration.cmk(), args)",
"Licensed under the Apache License, Version 2.0 (the \"License\"); #",
"License. from .. import helpers from . import integration def",
"not use this file except in compliance with the License.",
"\"tasks\": [ 2001 ] }, \"6,14\": { \"cpus\": \"6,14\", \"tasks\":",
"\"infra\": { \"cpuLists\": { \"0-2,8-10\": { \"cpus\": \"0-2,8-10\", \"tasks\": [",
"test_cmk_describe_ok(): args = [\"describe\", \"--conf-dir={}\".format(helpers.conf_dir(\"ok\"))] assert helpers.execute(integration.cmk(), args) == b\"\"\"{",
"} } } \"\"\" def test_cmk_describe_minimal(): args = [\"describe\", \"--conf-dir={}\".format(helpers.conf_dir(\"minimal\"))]",
"args) == b\"\"\"{ \"path\": \"/cmk/tests/data/config/ok\", \"pools\": { \"exclusive\": { \"cpuLists\":",
"2017 Intel Corporation # # Licensed under the Apache License,",
"from . import integration def test_cmk_describe_ok(): args = [\"describe\", \"--conf-dir={}\".format(helpers.conf_dir(\"ok\"))]",
"writing, software # distributed under the License is distributed on",
"in writing, software # distributed under the License is distributed",
"\"4,12\", \"tasks\": [ 2000 ] }, \"5,13\": { \"cpus\": \"5,13\",",
"[ 2000 ] }, \"5,13\": { \"cpus\": \"5,13\", \"tasks\": [",
"] }, \"5,13\": { \"cpus\": \"5,13\", \"tasks\": [ 2001 ]",
"\"3,11\", \"tasks\": [ 1000, 1001, 1002, 1003 ] } },",
"you may not use this file except in compliance with",
"2001 ] }, \"6,14\": { \"cpus\": \"6,14\", \"tasks\": [ 2002",
"# Licensed under the Apache License, Version 2.0 (the \"License\");",
"\"exclusive\": { \"cpuLists\": { \"4,12\": { \"cpus\": \"4,12\", \"tasks\": [",
"language governing permissions and # limitations under the License. from",
"# Copyright (c) 2017 Intel Corporation # # Licensed under",
"[\"describe\", \"--conf-dir={}\".format(helpers.conf_dir(\"minimal\"))] assert helpers.execute(integration.cmk(), args) == b\"\"\"{ \"path\": \"/cmk/tests/data/config/minimal\", \"pools\":",
"= [\"describe\", \"--conf-dir={}\".format(helpers.conf_dir(\"ok\"))] assert helpers.execute(integration.cmk(), args) == b\"\"\"{ \"path\": \"/cmk/tests/data/config/ok\",",
"\"name\": \"shared\" } } } \"\"\" def test_cmk_describe_minimal(): args =",
"use this file except in compliance with the License. #",
"{ \"cpus\": \"7,15\", \"tasks\": [ 2003 ] } }, \"exclusive\":",
"http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed",
"} }, \"exclusive\": false, \"name\": \"shared\" } } } \"\"\"",
"false, \"name\": \"infra\" }, \"shared\": { \"cpuLists\": { \"3,11\": {",
"the License. from .. import helpers from . import integration",
"\"name\": \"infra\" }, \"shared\": { \"cpuLists\": { \"3,11\": { \"cpus\":",
"\"6,14\", \"tasks\": [ 2002 ] }, \"7,15\": { \"cpus\": \"7,15\",",
"CONDITIONS OF ANY KIND, either express or implied. # See",
"\"tasks\": [ 2002 ] }, \"7,15\": { \"cpus\": \"7,15\", \"tasks\":",
"\"tasks\": [] } }, \"exclusive\": true, \"name\": \"exclusive\" }, \"shared\":",
"== b\"\"\"{ \"path\": \"/cmk/tests/data/config/ok\", \"pools\": { \"exclusive\": { \"cpuLists\": {",
"the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required",
"\"name\": \"exclusive\" }, \"infra\": { \"cpuLists\": { \"0-2,8-10\": { \"cpus\":",
"\"0-2,8-10\": { \"cpus\": \"0-2,8-10\", \"tasks\": [ 3000, 3001, 3002 ]",
"or implied. # See the License for the specific language",
"License is distributed on an \"AS IS\" BASIS, # WITHOUT",
"3000, 3001, 3002 ] } }, \"exclusive\": false, \"name\": \"infra\"",
"License. # You may obtain a copy of the License",
"is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES",
"License, Version 2.0 (the \"License\"); # you may not use",
"\"0\", \"tasks\": [] } }, \"exclusive\": false, \"name\": \"shared\" }",
"# You may obtain a copy of the License at",
"KIND, either express or implied. # See the License for",
"specific language governing permissions and # limitations under the License.",
"{ \"4,12\": { \"cpus\": \"4,12\", \"tasks\": [ 2000 ] },",
"\"name\": \"exclusive\" }, \"shared\": { \"cpuLists\": { \"0\": { \"cpus\":",
"\"exclusive\": false, \"name\": \"infra\" }, \"shared\": { \"cpuLists\": { \"3,11\":",
"under the License is distributed on an \"AS IS\" BASIS,",
"{ \"cpus\": \"5,13\", \"tasks\": [ 2001 ] }, \"6,14\": {",
"copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # #",
"License for the specific language governing permissions and # limitations",
"\"cpuLists\": { \"3,11\": { \"cpus\": \"3,11\", \"tasks\": [ 1000, 1001,",
"License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by",
"1003 ] } }, \"exclusive\": false, \"name\": \"shared\" } }",
"{ \"cpuLists\": { \"4,12\": { \"cpus\": \"4,12\", \"tasks\": [ 2000",
"\"shared\" } } } \"\"\" def test_cmk_describe_minimal(): args = [\"describe\",",
"} \"\"\" def test_cmk_describe_minimal(): args = [\"describe\", \"--conf-dir={}\".format(helpers.conf_dir(\"minimal\"))] assert helpers.execute(integration.cmk(),",
"false, \"name\": \"shared\" } } } \"\"\" def test_cmk_describe_minimal(): args",
"{ \"cpus\": \"0\", \"tasks\": [] } }, \"exclusive\": true, \"name\":",
"}, \"shared\": { \"cpuLists\": { \"0\": { \"cpus\": \"0\", \"tasks\":",
"the License for the specific language governing permissions and #",
"import integration def test_cmk_describe_ok(): args = [\"describe\", \"--conf-dir={}\".format(helpers.conf_dir(\"ok\"))] assert helpers.execute(integration.cmk(),",
"(the \"License\"); # you may not use this file except",
"1001, 1002, 1003 ] } }, \"exclusive\": false, \"name\": \"shared\"",
"Apache License, Version 2.0 (the \"License\"); # you may not",
"] } }, \"exclusive\": true, \"name\": \"exclusive\" }, \"infra\": {",
"# you may not use this file except in compliance",
"\"--conf-dir={}\".format(helpers.conf_dir(\"ok\"))] assert helpers.execute(integration.cmk(), args) == b\"\"\"{ \"path\": \"/cmk/tests/data/config/ok\", \"pools\": {",
"limitations under the License. from .. import helpers from .",
"either express or implied. # See the License for the",
"\"7,15\", \"tasks\": [ 2003 ] } }, \"exclusive\": true, \"name\":",
"} }, \"exclusive\": false, \"name\": \"infra\" }, \"shared\": { \"cpuLists\":",
"and # limitations under the License. from .. import helpers",
"OR CONDITIONS OF ANY KIND, either express or implied. #",
"== b\"\"\"{ \"path\": \"/cmk/tests/data/config/minimal\", \"pools\": { \"exclusive\": { \"cpuLists\": {",
"}, \"5,13\": { \"cpus\": \"5,13\", \"tasks\": [ 2001 ] },",
"\"6,14\": { \"cpus\": \"6,14\", \"tasks\": [ 2002 ] }, \"7,15\":",
"# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or",
"\"exclusive\" }, \"infra\": { \"cpuLists\": { \"0-2,8-10\": { \"cpus\": \"0-2,8-10\",",
"{ \"cpus\": \"6,14\", \"tasks\": [ 2002 ] }, \"7,15\": {",
"the License is distributed on an \"AS IS\" BASIS, #",
"2000 ] }, \"5,13\": { \"cpus\": \"5,13\", \"tasks\": [ 2001",
"] } }, \"exclusive\": false, \"name\": \"infra\" }, \"shared\": {",
"}, \"exclusive\": true, \"name\": \"exclusive\" }, \"shared\": { \"cpuLists\": {",
"in compliance with the License. # You may obtain a",
"] }, \"7,15\": { \"cpus\": \"7,15\", \"tasks\": [ 2003 ]",
"true, \"name\": \"exclusive\" }, \"shared\": { \"cpuLists\": { \"0\": {",
"software # distributed under the License is distributed on an",
"1002, 1003 ] } }, \"exclusive\": false, \"name\": \"shared\" }",
"\"pools\": { \"exclusive\": { \"cpuLists\": { \"4,12\": { \"cpus\": \"4,12\",",
"args = [\"describe\", \"--conf-dir={}\".format(helpers.conf_dir(\"minimal\"))] assert helpers.execute(integration.cmk(), args) == b\"\"\"{ \"path\":",
"true, \"name\": \"exclusive\" }, \"infra\": { \"cpuLists\": { \"0-2,8-10\": {",
"\"cpus\": \"3,11\", \"tasks\": [ 1000, 1001, 1002, 1003 ] }",
"} }, \"exclusive\": true, \"name\": \"exclusive\" }, \"infra\": { \"cpuLists\":",
"# # Unless required by applicable law or agreed to",
"3002 ] } }, \"exclusive\": false, \"name\": \"infra\" }, \"shared\":",
"helpers.execute(integration.cmk(), args) == b\"\"\"{ \"path\": \"/cmk/tests/data/config/minimal\", \"pools\": { \"exclusive\": {",
"2002 ] }, \"7,15\": { \"cpus\": \"7,15\", \"tasks\": [ 2003",
"a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 #",
"\"/cmk/tests/data/config/ok\", \"pools\": { \"exclusive\": { \"cpuLists\": { \"4,12\": { \"cpus\":",
"obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0",
"args) == b\"\"\"{ \"path\": \"/cmk/tests/data/config/minimal\", \"pools\": { \"exclusive\": { \"cpuLists\":",
"helpers.execute(integration.cmk(), args) == b\"\"\"{ \"path\": \"/cmk/tests/data/config/ok\", \"pools\": { \"exclusive\": {",
"{ \"cpuLists\": { \"0-2,8-10\": { \"cpus\": \"0-2,8-10\", \"tasks\": [ 3000,",
"}, \"infra\": { \"cpuLists\": { \"0-2,8-10\": { \"cpus\": \"0-2,8-10\", \"tasks\":",
".. import helpers from . import integration def test_cmk_describe_ok(): args",
"import helpers from . import integration def test_cmk_describe_ok(): args =",
"Version 2.0 (the \"License\"); # you may not use this",
"{ \"cpuLists\": { \"3,11\": { \"cpus\": \"3,11\", \"tasks\": [ 1000,",
"{ \"cpus\": \"3,11\", \"tasks\": [ 1000, 1001, 1002, 1003 ]",
"2003 ] } }, \"exclusive\": true, \"name\": \"exclusive\" }, \"infra\":",
"\"7,15\": { \"cpus\": \"7,15\", \"tasks\": [ 2003 ] } },",
"\"0-2,8-10\", \"tasks\": [ 3000, 3001, 3002 ] } }, \"exclusive\":",
"law or agreed to in writing, software # distributed under",
"\"5,13\", \"tasks\": [ 2001 ] }, \"6,14\": { \"cpus\": \"6,14\",",
"\"exclusive\" }, \"shared\": { \"cpuLists\": { \"0\": { \"cpus\": \"0\",",
"integration def test_cmk_describe_ok(): args = [\"describe\", \"--conf-dir={}\".format(helpers.conf_dir(\"ok\"))] assert helpers.execute(integration.cmk(), args)",
"{ \"exclusive\": { \"cpuLists\": { \"4,12\": { \"cpus\": \"4,12\", \"tasks\":",
"[\"describe\", \"--conf-dir={}\".format(helpers.conf_dir(\"ok\"))] assert helpers.execute(integration.cmk(), args) == b\"\"\"{ \"path\": \"/cmk/tests/data/config/ok\", \"pools\":",
". import integration def test_cmk_describe_ok(): args = [\"describe\", \"--conf-dir={}\".format(helpers.conf_dir(\"ok\"))] assert",
"\"/cmk/tests/data/config/minimal\", \"pools\": { \"exclusive\": { \"cpuLists\": { \"0\": { \"cpus\":",
"implied. # See the License for the specific language governing",
"1000, 1001, 1002, 1003 ] } }, \"exclusive\": false, \"name\":",
"[] } }, \"exclusive\": true, \"name\": \"exclusive\" }, \"shared\": {",
"[ 1000, 1001, 1002, 1003 ] } }, \"exclusive\": false,",
"\"cpus\": \"0-2,8-10\", \"tasks\": [ 3000, 3001, 3002 ] } },",
"helpers from . import integration def test_cmk_describe_ok(): args = [\"describe\",",
"under the Apache License, Version 2.0 (the \"License\"); # you",
"}, \"7,15\": { \"cpus\": \"7,15\", \"tasks\": [ 2003 ] }",
"{ \"cpus\": \"0\", \"tasks\": [] } }, \"exclusive\": false, \"name\":",
"\"License\"); # you may not use this file except in",
"b\"\"\"{ \"path\": \"/cmk/tests/data/config/ok\", \"pools\": { \"exclusive\": { \"cpuLists\": { \"4,12\":",
"\"tasks\": [ 2000 ] }, \"5,13\": { \"cpus\": \"5,13\", \"tasks\":",
"}, \"exclusive\": false, \"name\": \"shared\" } } } \"\"\" def",
"\"tasks\": [] } }, \"exclusive\": false, \"name\": \"shared\" } }",
"distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR",
"} } \"\"\" def test_cmk_describe_minimal(): args = [\"describe\", \"--conf-dir={}\".format(helpers.conf_dir(\"minimal\"))] assert",
"\"cpus\": \"0\", \"tasks\": [] } }, \"exclusive\": true, \"name\": \"exclusive\"",
"\"0\": { \"cpus\": \"0\", \"tasks\": [] } }, \"exclusive\": false,",
"\"cpus\": \"7,15\", \"tasks\": [ 2003 ] } }, \"exclusive\": true,",
"by applicable law or agreed to in writing, software #",
"# distributed under the License is distributed on an \"AS",
"OF ANY KIND, either express or implied. # See the",
"WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.",
"\"5,13\": { \"cpus\": \"5,13\", \"tasks\": [ 2001 ] }, \"6,14\":",
"\"cpuLists\": { \"4,12\": { \"cpus\": \"4,12\", \"tasks\": [ 2000 ]",
"{ \"0\": { \"cpus\": \"0\", \"tasks\": [] } }, \"exclusive\":",
"may obtain a copy of the License at # #",
"# Unless required by applicable law or agreed to in",
"ANY KIND, either express or implied. # See the License",
"See the License for the specific language governing permissions and",
"\"path\": \"/cmk/tests/data/config/ok\", \"pools\": { \"exclusive\": { \"cpuLists\": { \"4,12\": {",
"}, \"exclusive\": false, \"name\": \"infra\" }, \"shared\": { \"cpuLists\": {",
"the License. # You may obtain a copy of the",
"at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable",
"for the specific language governing permissions and # limitations under",
"{ \"exclusive\": { \"cpuLists\": { \"0\": { \"cpus\": \"0\", \"tasks\":",
"{ \"3,11\": { \"cpus\": \"3,11\", \"tasks\": [ 1000, 1001, 1002,",
"\"tasks\": [ 1000, 1001, 1002, 1003 ] } }, \"exclusive\":",
"\"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY",
"to in writing, software # distributed under the License is",
"b\"\"\"{ \"path\": \"/cmk/tests/data/config/minimal\", \"pools\": { \"exclusive\": { \"cpuLists\": { \"0\":",
"\"exclusive\": { \"cpuLists\": { \"0\": { \"cpus\": \"0\", \"tasks\": []",
"\"cpus\": \"0\", \"tasks\": [] } }, \"exclusive\": false, \"name\": \"shared\"",
"\"infra\" }, \"shared\": { \"cpuLists\": { \"3,11\": { \"cpus\": \"3,11\",",
"IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,",
"# See the License for the specific language governing permissions",
"[ 3000, 3001, 3002 ] } }, \"exclusive\": false, \"name\":",
"[ 2002 ] }, \"7,15\": { \"cpus\": \"7,15\", \"tasks\": [",
"] } }, \"exclusive\": false, \"name\": \"shared\" } } }",
"You may obtain a copy of the License at #",
"\"3,11\": { \"cpus\": \"3,11\", \"tasks\": [ 1000, 1001, 1002, 1003",
"3001, 3002 ] } }, \"exclusive\": false, \"name\": \"infra\" },",
"[ 2001 ] }, \"6,14\": { \"cpus\": \"6,14\", \"tasks\": [",
"may not use this file except in compliance with the",
"or agreed to in writing, software # distributed under the",
"\"shared\": { \"cpuLists\": { \"3,11\": { \"cpus\": \"3,11\", \"tasks\": [",
"required by applicable law or agreed to in writing, software",
"\"cpuLists\": { \"0\": { \"cpus\": \"0\", \"tasks\": [] } },",
"def test_cmk_describe_ok(): args = [\"describe\", \"--conf-dir={}\".format(helpers.conf_dir(\"ok\"))] assert helpers.execute(integration.cmk(), args) ==",
"\"cpus\": \"4,12\", \"tasks\": [ 2000 ] }, \"5,13\": { \"cpus\":",
"Copyright (c) 2017 Intel Corporation # # Licensed under the",
"Corporation # # Licensed under the Apache License, Version 2.0",
"BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either",
"WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or",
"= [\"describe\", \"--conf-dir={}\".format(helpers.conf_dir(\"minimal\"))] assert helpers.execute(integration.cmk(), args) == b\"\"\"{ \"path\": \"/cmk/tests/data/config/minimal\",",
"} }, \"exclusive\": true, \"name\": \"exclusive\" }, \"shared\": { \"cpuLists\":",
"with the License. # You may obtain a copy of",
"\"0\", \"tasks\": [] } }, \"exclusive\": true, \"name\": \"exclusive\" },",
"this file except in compliance with the License. # You",
"<filename>tests/integration/test_cmk_describe.py # Copyright (c) 2017 Intel Corporation # # Licensed",
"the Apache License, Version 2.0 (the \"License\"); # you may",
"governing permissions and # limitations under the License. from ..",
"\"--conf-dir={}\".format(helpers.conf_dir(\"minimal\"))] assert helpers.execute(integration.cmk(), args) == b\"\"\"{ \"path\": \"/cmk/tests/data/config/minimal\", \"pools\": {",
"test_cmk_describe_minimal(): args = [\"describe\", \"--conf-dir={}\".format(helpers.conf_dir(\"minimal\"))] assert helpers.execute(integration.cmk(), args) == b\"\"\"{",
"\"exclusive\": false, \"name\": \"shared\" } } } \"\"\" def test_cmk_describe_minimal():",
"\"cpus\": \"6,14\", \"tasks\": [ 2002 ] }, \"7,15\": { \"cpus\":",
"# limitations under the License. from .. import helpers from",
"assert helpers.execute(integration.cmk(), args) == b\"\"\"{ \"path\": \"/cmk/tests/data/config/ok\", \"pools\": { \"exclusive\":",
"] }, \"6,14\": { \"cpus\": \"6,14\", \"tasks\": [ 2002 ]"
] |
[
"os.pardir))) with open('requirements.txt') as f: install_requires = f.read().splitlines() setup( name='persistent-celery-beat-scheduler',",
"run from any path os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir))) with open('requirements.txt') as f:",
"import os from setuptools import find_packages, setup # allow setup.py",
":: 3.4', 'Programming Language :: Python :: 3.5', 'Programming Language",
"Independent', 'Programming Language :: Python', 'Programming Language :: Python ::",
"package_dir={'': 'src'}, include_package_data=True, zip_safe=False, description=( 'Celery Beat Scheduler that stores",
":: 3.3', 'Programming Language :: Python :: 3.4', 'Programming Language",
"author='<NAME>', author_email='<EMAIL>', license='Apache 2', long_description='https://github.com/richardasaurus/persistent-celery-beat-scheduler', install_requires=install_requires, classifiers=[ 'Intended Audience ::",
"# allow setup.py to be run from any path os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__),",
"Scheduler that stores the scheduler data in Redis.' ), author='<NAME>',",
"zip_safe=False, description=( 'Celery Beat Scheduler that stores the scheduler data",
"description=( 'Celery Beat Scheduler that stores the scheduler data in",
"author_email='<EMAIL>', license='Apache 2', long_description='https://github.com/richardasaurus/persistent-celery-beat-scheduler', install_requires=install_requires, classifiers=[ 'Intended Audience :: Developers',",
"Language :: Python :: 3', 'Programming Language :: Python ::",
"-* import os from setuptools import find_packages, setup # allow",
":: 3.5', 'Programming Language :: Python :: 3.6', 'Topic ::",
":: Python :: 3.4', 'Programming Language :: Python :: 3.5',",
"allow setup.py to be run from any path os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir)))",
":: Python :: 3.5', 'Programming Language :: Python :: 3.6',",
"setup.py to be run from any path os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir))) with",
":: 3', 'Programming Language :: Python :: 3.2', 'Programming Language",
"setup # allow setup.py to be run from any path",
"os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir))) with open('requirements.txt') as f: install_requires = f.read().splitlines() setup(",
"f: install_requires = f.read().splitlines() setup( name='persistent-celery-beat-scheduler', version='0.1.1.dev0', packages=find_packages('src', exclude=('tests',)), package_dir={'':",
"coding: utf-8 -* import os from setuptools import find_packages, setup",
":: OS Independent', 'Programming Language :: Python', 'Programming Language ::",
"long_description='https://github.com/richardasaurus/persistent-celery-beat-scheduler', install_requires=install_requires, classifiers=[ 'Intended Audience :: Developers', 'Operating System ::",
"os from setuptools import find_packages, setup # allow setup.py to",
"from setuptools import find_packages, setup # allow setup.py to be",
"Python :: 3.5', 'Programming Language :: Python :: 3.6', 'Topic",
"be run from any path os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir))) with open('requirements.txt') as",
"3', 'Programming Language :: Python :: 3.2', 'Programming Language ::",
":: Python :: 3.3', 'Programming Language :: Python :: 3.4',",
"version='0.1.1.dev0', packages=find_packages('src', exclude=('tests',)), package_dir={'': 'src'}, include_package_data=True, zip_safe=False, description=( 'Celery Beat",
":: Python :: 3.2', 'Programming Language :: Python :: 3.3',",
"3.5', 'Programming Language :: Python :: 3.6', 'Topic :: Internet",
":: Python :: 3', 'Programming Language :: Python :: 3.2',",
"that stores the scheduler data in Redis.' ), author='<NAME>', author_email='<EMAIL>',",
"as f: install_requires = f.read().splitlines() setup( name='persistent-celery-beat-scheduler', version='0.1.1.dev0', packages=find_packages('src', exclude=('tests',)),",
"'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming",
"import find_packages, setup # allow setup.py to be run from",
"Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Programming",
"Language :: Python :: 3.5', 'Programming Language :: Python ::",
"setup( name='persistent-celery-beat-scheduler', version='0.1.1.dev0', packages=find_packages('src', exclude=('tests',)), package_dir={'': 'src'}, include_package_data=True, zip_safe=False, description=(",
"name='persistent-celery-beat-scheduler', version='0.1.1.dev0', packages=find_packages('src', exclude=('tests',)), package_dir={'': 'src'}, include_package_data=True, zip_safe=False, description=( 'Celery",
"), author='<NAME>', author_email='<EMAIL>', license='Apache 2', long_description='https://github.com/richardasaurus/persistent-celery-beat-scheduler', install_requires=install_requires, classifiers=[ 'Intended Audience",
"3.3', 'Programming Language :: Python :: 3.4', 'Programming Language ::",
"'Programming Language :: Python :: 3.2', 'Programming Language :: Python",
"3.2', 'Programming Language :: Python :: 3.3', 'Programming Language ::",
"'Programming Language :: Python :: 3.3', 'Programming Language :: Python",
"exclude=('tests',)), package_dir={'': 'src'}, include_package_data=True, zip_safe=False, description=( 'Celery Beat Scheduler that",
"Redis.' ), author='<NAME>', author_email='<EMAIL>', license='Apache 2', long_description='https://github.com/richardasaurus/persistent-celery-beat-scheduler', install_requires=install_requires, classifiers=[ 'Intended",
":: Developers', 'Operating System :: OS Independent', 'Programming Language ::",
"'Programming Language :: Python :: 3', 'Programming Language :: Python",
"2', long_description='https://github.com/richardasaurus/persistent-celery-beat-scheduler', install_requires=install_requires, classifiers=[ 'Intended Audience :: Developers', 'Operating System",
"Python :: 3.2', 'Programming Language :: Python :: 3.3', 'Programming",
"Language :: Python :: 3.6', 'Topic :: Internet :: WWW/HTTP',",
"install_requires = f.read().splitlines() setup( name='persistent-celery-beat-scheduler', version='0.1.1.dev0', packages=find_packages('src', exclude=('tests',)), package_dir={'': 'src'},",
"the scheduler data in Redis.' ), author='<NAME>', author_email='<EMAIL>', license='Apache 2',",
"utf-8 -* import os from setuptools import find_packages, setup #",
"OS Independent', 'Programming Language :: Python', 'Programming Language :: Python",
"Python', 'Programming Language :: Python :: 3', 'Programming Language ::",
"python # -*- coding: utf-8 -* import os from setuptools",
"scheduler data in Redis.' ), author='<NAME>', author_email='<EMAIL>', license='Apache 2', long_description='https://github.com/richardasaurus/persistent-celery-beat-scheduler',",
"Audience :: Developers', 'Operating System :: OS Independent', 'Programming Language",
"Language :: Python', 'Programming Language :: Python :: 3', 'Programming",
"Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Programming",
"Beat Scheduler that stores the scheduler data in Redis.' ),",
"# -*- coding: utf-8 -* import os from setuptools import",
"= f.read().splitlines() setup( name='persistent-celery-beat-scheduler', version='0.1.1.dev0', packages=find_packages('src', exclude=('tests',)), package_dir={'': 'src'}, include_package_data=True,",
"'Programming Language :: Python', 'Programming Language :: Python :: 3',",
"install_requires=install_requires, classifiers=[ 'Intended Audience :: Developers', 'Operating System :: OS",
"'Programming Language :: Python :: 3.4', 'Programming Language :: Python",
"from any path os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir))) with open('requirements.txt') as f: install_requires",
"f.read().splitlines() setup( name='persistent-celery-beat-scheduler', version='0.1.1.dev0', packages=find_packages('src', exclude=('tests',)), package_dir={'': 'src'}, include_package_data=True, zip_safe=False,",
"'Programming Language :: Python :: 3.6', 'Topic :: Internet ::",
":: 3.2', 'Programming Language :: Python :: 3.3', 'Programming Language",
"in Redis.' ), author='<NAME>', author_email='<EMAIL>', license='Apache 2', long_description='https://github.com/richardasaurus/persistent-celery-beat-scheduler', install_requires=install_requires, classifiers=[",
"-*- coding: utf-8 -* import os from setuptools import find_packages,",
"Language :: Python :: 3.2', 'Programming Language :: Python ::",
"with open('requirements.txt') as f: install_requires = f.read().splitlines() setup( name='persistent-celery-beat-scheduler', version='0.1.1.dev0',",
"'Celery Beat Scheduler that stores the scheduler data in Redis.'",
"classifiers=[ 'Intended Audience :: Developers', 'Operating System :: OS Independent',",
":: Python', 'Programming Language :: Python :: 3', 'Programming Language",
"Language :: Python :: 3.3', 'Programming Language :: Python ::",
"stores the scheduler data in Redis.' ), author='<NAME>', author_email='<EMAIL>', license='Apache",
"'src'}, include_package_data=True, zip_safe=False, description=( 'Celery Beat Scheduler that stores the",
"'Programming Language :: Python :: 3.5', 'Programming Language :: Python",
"path os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir))) with open('requirements.txt') as f: install_requires = f.read().splitlines()",
"packages=find_packages('src', exclude=('tests',)), package_dir={'': 'src'}, include_package_data=True, zip_safe=False, description=( 'Celery Beat Scheduler",
"data in Redis.' ), author='<NAME>', author_email='<EMAIL>', license='Apache 2', long_description='https://github.com/richardasaurus/persistent-celery-beat-scheduler', install_requires=install_requires,",
"Python :: 3', 'Programming Language :: Python :: 3.2', 'Programming",
"Language :: Python :: 3.4', 'Programming Language :: Python ::",
"open('requirements.txt') as f: install_requires = f.read().splitlines() setup( name='persistent-celery-beat-scheduler', version='0.1.1.dev0', packages=find_packages('src',",
"3.4', 'Programming Language :: Python :: 3.5', 'Programming Language ::",
"find_packages, setup # allow setup.py to be run from any",
"license='Apache 2', long_description='https://github.com/richardasaurus/persistent-celery-beat-scheduler', install_requires=install_requires, classifiers=[ 'Intended Audience :: Developers', 'Operating",
"Developers', 'Operating System :: OS Independent', 'Programming Language :: Python',",
":: Python :: 3.6', 'Topic :: Internet :: WWW/HTTP', ],",
"any path os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir))) with open('requirements.txt') as f: install_requires =",
"#!/usr/bin/env python # -*- coding: utf-8 -* import os from",
"to be run from any path os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir))) with open('requirements.txt')",
"include_package_data=True, zip_safe=False, description=( 'Celery Beat Scheduler that stores the scheduler",
"System :: OS Independent', 'Programming Language :: Python', 'Programming Language",
"setuptools import find_packages, setup # allow setup.py to be run",
"'Intended Audience :: Developers', 'Operating System :: OS Independent', 'Programming",
"Python :: 3.6', 'Topic :: Internet :: WWW/HTTP', ], )"
] |
[
"Constants.END_LINE) with self.assertRaises(driver.DriverServerException): self.client.set('testkey', 'testvalue', 0, False) def test_set_value_with_client_error_response(self): self.mock.receive_buffer.append(Errors.CLIENT_ERROR",
"self.closed = True self.socket = None self.send_buffer = collections.deque() self.receive_buffer",
"self.assertTrue(response) def test_set_value_with_not_stored_response(self): self.mock.receive_buffer.append(StoreReply.NOT_STORED + Constants.END_LINE) response = self.client.set('testkey', 'testvalue',",
"self.assertFalse(response) def test_set_value_with_exists_response(self): self.mock.receive_buffer.append(StoreReply.EXISTS + Constants.END_LINE) response = self.client.set('testkey', 'testvalue',",
"False) self.assertTrue(response) def test_set_value_with_not_stored_response(self): self.mock.receive_buffer.append(StoreReply.NOT_STORED + Constants.END_LINE) response = self.client.set('testkey',",
"= socket_timeout self.closed = True self.socket = None self.send_buffer =",
"with self.assertRaises(driver.DriverClientException): self.client.set('testkey', 'testvalue', 0, False) def test_set_value_exception(self): error_message =",
"from driver.protocol import * _server = ('localhost', 11211) _dead_retry =",
"self.assertFalse(response) def test_set_value_with_error_response(self): self.mock.receive_buffer.append(Errors.ERROR + Constants.END_LINE) with self.assertRaises(driver.DriverUnknownException): self.client.set('testkey', 'testvalue',",
"\"Test read exception\" self.mock.on_read = lambda: _raise_exception(error_message) result = self.client.get('testkey')",
"Constants.END_LINE) response = self.client.set('testkey', 'testvalue', 0, False) self.assertFalse(response) def test_set_value_with_exists_response(self):",
"\"Test write exception\" self.mock.on_write = lambda: _raise_exception(error_message) result = self.client.set('testkey',",
"Constants.END_LINE) response = self.client.set('testkey', 'testvalue', 0, False) self.assertFalse(response) def test_set_value_with_error_response(self):",
"True return True def close(self): self.closed = True self.socket =",
"None def send(self, data): if self.on_write is not None: self.on_write()",
"exception\" self.mock.on_read = lambda: _raise_exception(error_message) result = self.client.get('testkey') self.assertIsNone(result) def",
"def read(self, size=_max_receive_size): if self.on_read is not None: self.on_read() return",
"'testvalue', 0, False) def test_set_value_with_server_error_response(self): self.mock.receive_buffer.append(Errors.SERVER_ERROR + b' Test server",
"error_message = \"Test write exception\" self.mock.on_write = lambda: _raise_exception(error_message) result",
"class MockConnection(object): def __init__(self, server=_server, dead_retry=30, socket_timeout=3): self.server = server",
"False) def test_set_value_with_client_error_response(self): self.mock.receive_buffer.append(Errors.CLIENT_ERROR + b' Test client error' +",
"None self.on_write = None def open(self): self.closed = False self.socket",
"collections.deque() self.receive_buffer = collections.deque() self.on_read = None self.on_write = None",
"collections.deque() self.on_read = None self.on_write = None def open(self): self.closed",
"= MockConnection() self.client._connection = self.mock self.client.connect() def test_initialize_and_connect(self): self.assertFalse(self.mock.closed) def",
"= collections.deque() self.receive_buffer = collections.deque() self.on_read = None self.on_write =",
"self.assertEqual(self.mock.send_buffer.pop(), b'set testkey 0 0 9 noreply\\r\\ntestvalue\\r\\n') def test_set_value_with_stored_response(self): self.mock.receive_buffer.append(StoreReply.STORED",
"def test_set_value_exception(self): error_message = \"Test write exception\" self.mock.on_write = lambda:",
"lambda: _raise_exception(error_message) result = self.client.set('testkey', 'testvalue', 0, False) self.assertFalse(result) def",
"'testvalue', 0, False) self.assertFalse(result) def test_get_value_exception(self): error_message = \"Test read",
"'testvalue', 0, False) self.assertTrue(response) def test_set_value_with_not_stored_response(self): self.mock.receive_buffer.append(StoreReply.NOT_STORED + Constants.END_LINE) response",
"test_set_value_with_server_error_response(self): self.mock.receive_buffer.append(Errors.SERVER_ERROR + b' Test server error' + Constants.END_LINE) with",
"= \"Test read exception\" self.mock.on_read = lambda: _raise_exception(error_message) result =",
"read exception\" self.mock.on_read = lambda: _raise_exception(error_message) result = self.client.get('testkey') self.assertIsNone(result)",
"self.mock = MockConnection() self.client._connection = self.mock self.client.connect() def test_initialize_and_connect(self): self.assertFalse(self.mock.closed)",
"driver.protocol import * _server = ('localhost', 11211) _dead_retry = 30",
"= None def open(self): self.closed = False self.socket = True",
"def test_set_value_without_response(self): self.client.set('testkey', 'testvalue') self.assertEqual(self.mock.send_buffer.pop(), b'set testkey 0 0 9",
"+ b' Test server error' + Constants.END_LINE) with self.assertRaises(driver.DriverServerException): self.client.set('testkey',",
"def test_set_value_with_exists_response(self): self.mock.receive_buffer.append(StoreReply.EXISTS + Constants.END_LINE) response = self.client.set('testkey', 'testvalue', 0,",
"def close(self): self.closed = True self.socket = None def send(self,",
"driver.Client(_server) self.mock = MockConnection() self.client._connection = self.mock self.client.connect() def test_initialize_and_connect(self):",
"self.client.set('testkey', 'testvalue', 0, False) self.assertFalse(response) def test_set_value_with_exists_response(self): self.mock.receive_buffer.append(StoreReply.EXISTS + Constants.END_LINE)",
"error_message = \"Test read exception\" self.mock.on_read = lambda: _raise_exception(error_message) result",
"socket_timeout=3): self.server = server self.dead_retry = dead_retry self.socket_timeout = socket_timeout",
"write exception\" self.mock.on_write = lambda: _raise_exception(error_message) result = self.client.set('testkey', 'testvalue',",
"def test_get_value_exception(self): error_message = \"Test read exception\" self.mock.on_read = lambda:",
"dead_retry=30, socket_timeout=3): self.server = server self.dead_retry = dead_retry self.socket_timeout =",
"= None self.send_buffer = collections.deque() self.receive_buffer = collections.deque() self.on_read =",
"def test_disconnect(self): self.client.disconnect() self.assertTrue(self.mock.closed) def test_set_value_without_response(self): self.client.set('testkey', 'testvalue') self.assertEqual(self.mock.send_buffer.pop(), b'set",
"not None: self.on_read() return self.receive_buffer.popleft() class ClientTests(unittest.TestCase): def setUp(self): self.client",
"def setUp(self): self.client = driver.Client(_server) self.mock = MockConnection() self.client._connection =",
"self.client.connect() def test_initialize_and_connect(self): self.assertFalse(self.mock.closed) def test_disconnect(self): self.client.disconnect() self.assertTrue(self.mock.closed) def test_set_value_without_response(self):",
"Test client error' + Constants.END_LINE) with self.assertRaises(driver.DriverClientException): self.client.set('testkey', 'testvalue', 0,",
"import * _server = ('localhost', 11211) _dead_retry = 30 _socket_timeout",
"9 noreply\\r\\ntestvalue\\r\\n') def test_set_value_with_stored_response(self): self.mock.receive_buffer.append(StoreReply.STORED + Constants.END_LINE) response = self.client.set('testkey',",
"close(self): self.closed = True self.socket = None def send(self, data):",
"None def open(self): self.closed = False self.socket = True return",
"self.socket = True return True def close(self): self.closed = True",
"self.mock.receive_buffer.append(Errors.ERROR + Constants.END_LINE) with self.assertRaises(driver.DriverUnknownException): self.client.set('testkey', 'testvalue', 0, False) def",
"return self.receive_buffer.popleft() class ClientTests(unittest.TestCase): def setUp(self): self.client = driver.Client(_server) self.mock",
"self.assertFalse(result) def test_get_value_exception(self): error_message = \"Test read exception\" self.mock.on_read =",
"test_set_value_without_response(self): self.client.set('testkey', 'testvalue') self.assertEqual(self.mock.send_buffer.pop(), b'set testkey 0 0 9 noreply\\r\\ntestvalue\\r\\n')",
"noreply\\r\\ntestvalue\\r\\n') def test_set_value_with_stored_response(self): self.mock.receive_buffer.append(StoreReply.STORED + Constants.END_LINE) response = self.client.set('testkey', 'testvalue',",
"= dead_retry self.socket_timeout = socket_timeout self.closed = True self.socket =",
"30 _socket_timeout = 3 _max_receive_size = 4096 class MockConnection(object): def",
"False) self.assertFalse(response) def test_set_value_with_exists_response(self): self.mock.receive_buffer.append(StoreReply.EXISTS + Constants.END_LINE) response = self.client.set('testkey',",
"self.assertFalse(self.mock.closed) def test_disconnect(self): self.client.disconnect() self.assertTrue(self.mock.closed) def test_set_value_without_response(self): self.client.set('testkey', 'testvalue') self.assertEqual(self.mock.send_buffer.pop(),",
"with self.assertRaises(driver.DriverServerException): self.client.set('testkey', 'testvalue', 0, False) def test_set_value_with_client_error_response(self): self.mock.receive_buffer.append(Errors.CLIENT_ERROR +",
"def __init__(self, server=_server, dead_retry=30, socket_timeout=3): self.server = server self.dead_retry =",
"self.server = server self.dead_retry = dead_retry self.socket_timeout = socket_timeout self.closed",
"exception\" self.mock.on_write = lambda: _raise_exception(error_message) result = self.client.set('testkey', 'testvalue', 0,",
"('localhost', 11211) _dead_retry = 30 _socket_timeout = 3 _max_receive_size =",
"dead_retry self.socket_timeout = socket_timeout self.closed = True self.socket = None",
"self.client._connection = self.mock self.client.connect() def test_initialize_and_connect(self): self.assertFalse(self.mock.closed) def test_disconnect(self): self.client.disconnect()",
"0, False) def test_set_value_exception(self): error_message = \"Test write exception\" self.mock.on_write",
"self.mock.on_write = lambda: _raise_exception(error_message) result = self.client.set('testkey', 'testvalue', 0, False)",
"open(self): self.closed = False self.socket = True return True def",
"= server self.dead_retry = dead_retry self.socket_timeout = socket_timeout self.closed =",
"False) def test_set_value_with_server_error_response(self): self.mock.receive_buffer.append(Errors.SERVER_ERROR + b' Test server error' +",
"0, False) self.assertFalse(response) def test_set_value_with_exists_response(self): self.mock.receive_buffer.append(StoreReply.EXISTS + Constants.END_LINE) response =",
"0, False) def test_set_value_with_client_error_response(self): self.mock.receive_buffer.append(Errors.CLIENT_ERROR + b' Test client error'",
"size=_max_receive_size): if self.on_read is not None: self.on_read() return self.receive_buffer.popleft() class",
"testkey 0 0 9 noreply\\r\\ntestvalue\\r\\n') def test_set_value_with_stored_response(self): self.mock.receive_buffer.append(StoreReply.STORED + Constants.END_LINE)",
"__init__(self, server=_server, dead_retry=30, socket_timeout=3): self.server = server self.dead_retry = dead_retry",
"self.socket_timeout = socket_timeout self.closed = True self.socket = None self.send_buffer",
"= True self.socket = None def send(self, data): if self.on_write",
"+ Constants.END_LINE) response = self.client.set('testkey', 'testvalue', 0, False) self.assertFalse(response) def",
"def test_set_value_with_server_error_response(self): self.mock.receive_buffer.append(Errors.SERVER_ERROR + b' Test server error' + Constants.END_LINE)",
"Constants.END_LINE) with self.assertRaises(driver.DriverClientException): self.client.set('testkey', 'testvalue', 0, False) def test_set_value_exception(self): error_message",
"test_set_value_with_not_stored_response(self): self.mock.receive_buffer.append(StoreReply.NOT_STORED + Constants.END_LINE) response = self.client.set('testkey', 'testvalue', 0, False)",
"def send(self, data): if self.on_write is not None: self.on_write() self.send_buffer.append(data)",
"ClientTests(unittest.TestCase): def setUp(self): self.client = driver.Client(_server) self.mock = MockConnection() self.client._connection",
"server self.dead_retry = dead_retry self.socket_timeout = socket_timeout self.closed = True",
"self.on_read() return self.receive_buffer.popleft() class ClientTests(unittest.TestCase): def setUp(self): self.client = driver.Client(_server)",
"self.receive_buffer = collections.deque() self.on_read = None self.on_write = None def",
"= lambda: _raise_exception(error_message) result = self.client.get('testkey') self.assertIsNone(result) def _raise_exception(message): raise",
"= 30 _socket_timeout = 3 _max_receive_size = 4096 class MockConnection(object):",
"def test_initialize_and_connect(self): self.assertFalse(self.mock.closed) def test_disconnect(self): self.client.disconnect() self.assertTrue(self.mock.closed) def test_set_value_without_response(self): self.client.set('testkey',",
"server error' + Constants.END_LINE) with self.assertRaises(driver.DriverServerException): self.client.set('testkey', 'testvalue', 0, False)",
"unittest import driver from driver.protocol import * _server = ('localhost',",
"if self.on_write is not None: self.on_write() self.send_buffer.append(data) def read(self, size=_max_receive_size):",
"self.client.set('testkey', 'testvalue', 0, False) self.assertFalse(result) def test_get_value_exception(self): error_message = \"Test",
"self.send_buffer.append(data) def read(self, size=_max_receive_size): if self.on_read is not None: self.on_read()",
"= False self.socket = True return True def close(self): self.closed",
"if self.on_read is not None: self.on_read() return self.receive_buffer.popleft() class ClientTests(unittest.TestCase):",
"self.client.set('testkey', 'testvalue', 0, False) self.assertFalse(response) def test_set_value_with_error_response(self): self.mock.receive_buffer.append(Errors.ERROR + Constants.END_LINE)",
"self.receive_buffer.popleft() class ClientTests(unittest.TestCase): def setUp(self): self.client = driver.Client(_server) self.mock =",
"self.mock.receive_buffer.append(Errors.CLIENT_ERROR + b' Test client error' + Constants.END_LINE) with self.assertRaises(driver.DriverClientException):",
"b' Test server error' + Constants.END_LINE) with self.assertRaises(driver.DriverServerException): self.client.set('testkey', 'testvalue',",
"self.client = driver.Client(_server) self.mock = MockConnection() self.client._connection = self.mock self.client.connect()",
"self.mock.receive_buffer.append(StoreReply.EXISTS + Constants.END_LINE) response = self.client.set('testkey', 'testvalue', 0, False) self.assertFalse(response)",
"test_set_value_with_exists_response(self): self.mock.receive_buffer.append(StoreReply.EXISTS + Constants.END_LINE) response = self.client.set('testkey', 'testvalue', 0, False)",
"self.on_write is not None: self.on_write() self.send_buffer.append(data) def read(self, size=_max_receive_size): if",
"result = self.client.set('testkey', 'testvalue', 0, False) self.assertFalse(result) def test_get_value_exception(self): error_message",
"self.assertTrue(self.mock.closed) def test_set_value_without_response(self): self.client.set('testkey', 'testvalue') self.assertEqual(self.mock.send_buffer.pop(), b'set testkey 0 0",
"server=_server, dead_retry=30, socket_timeout=3): self.server = server self.dead_retry = dead_retry self.socket_timeout",
"= self.client.set('testkey', 'testvalue', 0, False) self.assertTrue(response) def test_set_value_with_not_stored_response(self): self.mock.receive_buffer.append(StoreReply.NOT_STORED +",
"self.send_buffer = collections.deque() self.receive_buffer = collections.deque() self.on_read = None self.on_write",
"self.mock self.client.connect() def test_initialize_and_connect(self): self.assertFalse(self.mock.closed) def test_disconnect(self): self.client.disconnect() self.assertTrue(self.mock.closed) def",
"None: self.on_write() self.send_buffer.append(data) def read(self, size=_max_receive_size): if self.on_read is not",
"test_initialize_and_connect(self): self.assertFalse(self.mock.closed) def test_disconnect(self): self.client.disconnect() self.assertTrue(self.mock.closed) def test_set_value_without_response(self): self.client.set('testkey', 'testvalue')",
"self.mock.receive_buffer.append(StoreReply.STORED + Constants.END_LINE) response = self.client.set('testkey', 'testvalue', 0, False) self.assertTrue(response)",
"test_set_value_with_client_error_response(self): self.mock.receive_buffer.append(Errors.CLIENT_ERROR + b' Test client error' + Constants.END_LINE) with",
"False) def test_set_value_exception(self): error_message = \"Test write exception\" self.mock.on_write =",
"error' + Constants.END_LINE) with self.assertRaises(driver.DriverServerException): self.client.set('testkey', 'testvalue', 0, False) def",
"data): if self.on_write is not None: self.on_write() self.send_buffer.append(data) def read(self,",
"with self.assertRaises(driver.DriverUnknownException): self.client.set('testkey', 'testvalue', 0, False) def test_set_value_with_server_error_response(self): self.mock.receive_buffer.append(Errors.SERVER_ERROR +",
"setUp(self): self.client = driver.Client(_server) self.mock = MockConnection() self.client._connection = self.mock",
"self.client.set('testkey', 'testvalue', 0, False) self.assertTrue(response) def test_set_value_with_not_stored_response(self): self.mock.receive_buffer.append(StoreReply.NOT_STORED + Constants.END_LINE)",
"error' + Constants.END_LINE) with self.assertRaises(driver.DriverClientException): self.client.set('testkey', 'testvalue', 0, False) def",
"send(self, data): if self.on_write is not None: self.on_write() self.send_buffer.append(data) def",
"= self.mock self.client.connect() def test_initialize_and_connect(self): self.assertFalse(self.mock.closed) def test_disconnect(self): self.client.disconnect() self.assertTrue(self.mock.closed)",
"Test server error' + Constants.END_LINE) with self.assertRaises(driver.DriverServerException): self.client.set('testkey', 'testvalue', 0,",
"read(self, size=_max_receive_size): if self.on_read is not None: self.on_read() return self.receive_buffer.popleft()",
"+ Constants.END_LINE) with self.assertRaises(driver.DriverUnknownException): self.client.set('testkey', 'testvalue', 0, False) def test_set_value_with_server_error_response(self):",
"import driver from driver.protocol import * _server = ('localhost', 11211)",
"MockConnection() self.client._connection = self.mock self.client.connect() def test_initialize_and_connect(self): self.assertFalse(self.mock.closed) def test_disconnect(self):",
"False) self.assertFalse(result) def test_get_value_exception(self): error_message = \"Test read exception\" self.mock.on_read",
"driver from driver.protocol import * _server = ('localhost', 11211) _dead_retry",
"self.on_write = None def open(self): self.closed = False self.socket =",
"None self.send_buffer = collections.deque() self.receive_buffer = collections.deque() self.on_read = None",
"= True return True def close(self): self.closed = True self.socket",
"test_set_value_with_stored_response(self): self.mock.receive_buffer.append(StoreReply.STORED + Constants.END_LINE) response = self.client.set('testkey', 'testvalue', 0, False)",
"self.client.set('testkey', 'testvalue', 0, False) def test_set_value_exception(self): error_message = \"Test write",
"test_set_value_exception(self): error_message = \"Test write exception\" self.mock.on_write = lambda: _raise_exception(error_message)",
"self.closed = False self.socket = True return True def close(self):",
"response = self.client.set('testkey', 'testvalue', 0, False) self.assertTrue(response) def test_set_value_with_not_stored_response(self): self.mock.receive_buffer.append(StoreReply.NOT_STORED",
"= \"Test write exception\" self.mock.on_write = lambda: _raise_exception(error_message) result =",
"self.on_read = None self.on_write = None def open(self): self.closed =",
"self.client.set('testkey', 'testvalue') self.assertEqual(self.mock.send_buffer.pop(), b'set testkey 0 0 9 noreply\\r\\ntestvalue\\r\\n') def",
"+ Constants.END_LINE) with self.assertRaises(driver.DriverClientException): self.client.set('testkey', 'testvalue', 0, False) def test_set_value_exception(self):",
"self.on_read is not None: self.on_read() return self.receive_buffer.popleft() class ClientTests(unittest.TestCase): def",
"self.mock.receive_buffer.append(Errors.SERVER_ERROR + b' Test server error' + Constants.END_LINE) with self.assertRaises(driver.DriverServerException):",
"is not None: self.on_write() self.send_buffer.append(data) def read(self, size=_max_receive_size): if self.on_read",
"response = self.client.set('testkey', 'testvalue', 0, False) self.assertFalse(response) def test_set_value_with_exists_response(self): self.mock.receive_buffer.append(StoreReply.EXISTS",
"_raise_exception(error_message) result = self.client.set('testkey', 'testvalue', 0, False) self.assertFalse(result) def test_get_value_exception(self):",
"self.assertRaises(driver.DriverUnknownException): self.client.set('testkey', 'testvalue', 0, False) def test_set_value_with_server_error_response(self): self.mock.receive_buffer.append(Errors.SERVER_ERROR + b'",
"not None: self.on_write() self.send_buffer.append(data) def read(self, size=_max_receive_size): if self.on_read is",
"collections import unittest import driver from driver.protocol import * _server",
"self.client.set('testkey', 'testvalue', 0, False) def test_set_value_with_client_error_response(self): self.mock.receive_buffer.append(Errors.CLIENT_ERROR + b' Test",
"* _server = ('localhost', 11211) _dead_retry = 30 _socket_timeout =",
"self.socket = None self.send_buffer = collections.deque() self.receive_buffer = collections.deque() self.on_read",
"b'set testkey 0 0 9 noreply\\r\\ntestvalue\\r\\n') def test_set_value_with_stored_response(self): self.mock.receive_buffer.append(StoreReply.STORED +",
"MockConnection(object): def __init__(self, server=_server, dead_retry=30, socket_timeout=3): self.server = server self.dead_retry",
"self.dead_retry = dead_retry self.socket_timeout = socket_timeout self.closed = True self.socket",
"self.client.disconnect() self.assertTrue(self.mock.closed) def test_set_value_without_response(self): self.client.set('testkey', 'testvalue') self.assertEqual(self.mock.send_buffer.pop(), b'set testkey 0",
"0, False) self.assertFalse(result) def test_get_value_exception(self): error_message = \"Test read exception\"",
"= 4096 class MockConnection(object): def __init__(self, server=_server, dead_retry=30, socket_timeout=3): self.server",
"import unittest import driver from driver.protocol import * _server =",
"self.socket = None def send(self, data): if self.on_write is not",
"= self.client.set('testkey', 'testvalue', 0, False) self.assertFalse(result) def test_get_value_exception(self): error_message =",
"= driver.Client(_server) self.mock = MockConnection() self.client._connection = self.mock self.client.connect() def",
"return True def close(self): self.closed = True self.socket = None",
"Constants.END_LINE) with self.assertRaises(driver.DriverUnknownException): self.client.set('testkey', 'testvalue', 0, False) def test_set_value_with_server_error_response(self): self.mock.receive_buffer.append(Errors.SERVER_ERROR",
"def test_set_value_with_error_response(self): self.mock.receive_buffer.append(Errors.ERROR + Constants.END_LINE) with self.assertRaises(driver.DriverUnknownException): self.client.set('testkey', 'testvalue', 0,",
"= None self.on_write = None def open(self): self.closed = False",
"None: self.on_read() return self.receive_buffer.popleft() class ClientTests(unittest.TestCase): def setUp(self): self.client =",
"False self.socket = True return True def close(self): self.closed =",
"self.assertRaises(driver.DriverClientException): self.client.set('testkey', 'testvalue', 0, False) def test_set_value_exception(self): error_message = \"Test",
"def open(self): self.closed = False self.socket = True return True",
"'testvalue') self.assertEqual(self.mock.send_buffer.pop(), b'set testkey 0 0 9 noreply\\r\\ntestvalue\\r\\n') def test_set_value_with_stored_response(self):",
"self.assertRaises(driver.DriverServerException): self.client.set('testkey', 'testvalue', 0, False) def test_set_value_with_client_error_response(self): self.mock.receive_buffer.append(Errors.CLIENT_ERROR + b'",
"= 3 _max_receive_size = 4096 class MockConnection(object): def __init__(self, server=_server,",
"False) self.assertFalse(response) def test_set_value_with_error_response(self): self.mock.receive_buffer.append(Errors.ERROR + Constants.END_LINE) with self.assertRaises(driver.DriverUnknownException): self.client.set('testkey',",
"self.mock.receive_buffer.append(StoreReply.NOT_STORED + Constants.END_LINE) response = self.client.set('testkey', 'testvalue', 0, False) self.assertFalse(response)",
"0, False) def test_set_value_with_server_error_response(self): self.mock.receive_buffer.append(Errors.SERVER_ERROR + b' Test server error'",
"socket_timeout self.closed = True self.socket = None self.send_buffer = collections.deque()",
"self.on_write() self.send_buffer.append(data) def read(self, size=_max_receive_size): if self.on_read is not None:",
"True self.socket = None def send(self, data): if self.on_write is",
"_max_receive_size = 4096 class MockConnection(object): def __init__(self, server=_server, dead_retry=30, socket_timeout=3):",
"def test_set_value_with_stored_response(self): self.mock.receive_buffer.append(StoreReply.STORED + Constants.END_LINE) response = self.client.set('testkey', 'testvalue', 0,",
"def test_set_value_with_not_stored_response(self): self.mock.receive_buffer.append(StoreReply.NOT_STORED + Constants.END_LINE) response = self.client.set('testkey', 'testvalue', 0,",
"= ('localhost', 11211) _dead_retry = 30 _socket_timeout = 3 _max_receive_size",
"'testvalue', 0, False) self.assertFalse(response) def test_set_value_with_exists_response(self): self.mock.receive_buffer.append(StoreReply.EXISTS + Constants.END_LINE) response",
"= self.client.set('testkey', 'testvalue', 0, False) self.assertFalse(response) def test_set_value_with_error_response(self): self.mock.receive_buffer.append(Errors.ERROR +",
"def test_set_value_with_client_error_response(self): self.mock.receive_buffer.append(Errors.CLIENT_ERROR + b' Test client error' + Constants.END_LINE)",
"4096 class MockConnection(object): def __init__(self, server=_server, dead_retry=30, socket_timeout=3): self.server =",
"+ Constants.END_LINE) response = self.client.set('testkey', 'testvalue', 0, False) self.assertTrue(response) def",
"3 _max_receive_size = 4096 class MockConnection(object): def __init__(self, server=_server, dead_retry=30,",
"test_get_value_exception(self): error_message = \"Test read exception\" self.mock.on_read = lambda: _raise_exception(error_message)",
"self.client.set('testkey', 'testvalue', 0, False) def test_set_value_with_server_error_response(self): self.mock.receive_buffer.append(Errors.SERVER_ERROR + b' Test",
"= True self.socket = None self.send_buffer = collections.deque() self.receive_buffer =",
"0 9 noreply\\r\\ntestvalue\\r\\n') def test_set_value_with_stored_response(self): self.mock.receive_buffer.append(StoreReply.STORED + Constants.END_LINE) response =",
"+ Constants.END_LINE) with self.assertRaises(driver.DriverServerException): self.client.set('testkey', 'testvalue', 0, False) def test_set_value_with_client_error_response(self):",
"_dead_retry = 30 _socket_timeout = 3 _max_receive_size = 4096 class",
"test_disconnect(self): self.client.disconnect() self.assertTrue(self.mock.closed) def test_set_value_without_response(self): self.client.set('testkey', 'testvalue') self.assertEqual(self.mock.send_buffer.pop(), b'set testkey",
"= self.client.set('testkey', 'testvalue', 0, False) self.assertFalse(response) def test_set_value_with_exists_response(self): self.mock.receive_buffer.append(StoreReply.EXISTS +",
"test_set_value_with_error_response(self): self.mock.receive_buffer.append(Errors.ERROR + Constants.END_LINE) with self.assertRaises(driver.DriverUnknownException): self.client.set('testkey', 'testvalue', 0, False)",
"11211) _dead_retry = 30 _socket_timeout = 3 _max_receive_size = 4096",
"_socket_timeout = 3 _max_receive_size = 4096 class MockConnection(object): def __init__(self,",
"0, False) self.assertTrue(response) def test_set_value_with_not_stored_response(self): self.mock.receive_buffer.append(StoreReply.NOT_STORED + Constants.END_LINE) response =",
"Constants.END_LINE) response = self.client.set('testkey', 'testvalue', 0, False) self.assertTrue(response) def test_set_value_with_not_stored_response(self):",
"'testvalue', 0, False) def test_set_value_with_client_error_response(self): self.mock.receive_buffer.append(Errors.CLIENT_ERROR + b' Test client",
"self.closed = True self.socket = None def send(self, data): if",
"0, False) self.assertFalse(response) def test_set_value_with_error_response(self): self.mock.receive_buffer.append(Errors.ERROR + Constants.END_LINE) with self.assertRaises(driver.DriverUnknownException):",
"response = self.client.set('testkey', 'testvalue', 0, False) self.assertFalse(response) def test_set_value_with_error_response(self): self.mock.receive_buffer.append(Errors.ERROR",
"self.mock.on_read = lambda: _raise_exception(error_message) result = self.client.get('testkey') self.assertIsNone(result) def _raise_exception(message):",
"class ClientTests(unittest.TestCase): def setUp(self): self.client = driver.Client(_server) self.mock = MockConnection()",
"b' Test client error' + Constants.END_LINE) with self.assertRaises(driver.DriverClientException): self.client.set('testkey', 'testvalue',",
"client error' + Constants.END_LINE) with self.assertRaises(driver.DriverClientException): self.client.set('testkey', 'testvalue', 0, False)",
"lambda: _raise_exception(error_message) result = self.client.get('testkey') self.assertIsNone(result) def _raise_exception(message): raise Exception(message)",
"= lambda: _raise_exception(error_message) result = self.client.set('testkey', 'testvalue', 0, False) self.assertFalse(result)",
"= collections.deque() self.on_read = None self.on_write = None def open(self):",
"0 0 9 noreply\\r\\ntestvalue\\r\\n') def test_set_value_with_stored_response(self): self.mock.receive_buffer.append(StoreReply.STORED + Constants.END_LINE) response",
"'testvalue', 0, False) def test_set_value_exception(self): error_message = \"Test write exception\"",
"True def close(self): self.closed = True self.socket = None def",
"True self.socket = None self.send_buffer = collections.deque() self.receive_buffer = collections.deque()",
"'testvalue', 0, False) self.assertFalse(response) def test_set_value_with_error_response(self): self.mock.receive_buffer.append(Errors.ERROR + Constants.END_LINE) with",
"is not None: self.on_read() return self.receive_buffer.popleft() class ClientTests(unittest.TestCase): def setUp(self):",
"import collections import unittest import driver from driver.protocol import *",
"_server = ('localhost', 11211) _dead_retry = 30 _socket_timeout = 3",
"= None def send(self, data): if self.on_write is not None:",
"+ b' Test client error' + Constants.END_LINE) with self.assertRaises(driver.DriverClientException): self.client.set('testkey',"
] |
[
"= (366/Loan_Status)*100 # code ends here # -------------- # code",
"-------------- # Import packages import numpy as np import pandas",
"Loan_Status = 614 percentage_se = (56/Loan_Status)*100 percentage_nse = (366/Loan_Status)*100 #",
"#code ends here # -------------- # Code starts here avg_loan_amount",
"loan_term if i >= 25] big_loan_term = len(big_loan) print(big_loan_term) #[loan_term.value_counts()[i]",
"# code starts here bank = pd.read_csv(path) categorical_var = bank.select_dtypes(include",
"ends here # -------------- # code starts here loan_term =",
"# Import packages import numpy as np import pandas as",
"# code ends here # -------------- # code starts here",
"starts here loan_approved_se = ((banks['Self_Employed']=='Yes') & (banks['Loan_Status']=='Y')).value_counts() #print(loan_approved_se) loan_approved_nse =",
"big_loan = [i for i in loan_term if i >=",
"= banks.fillna(bank_mode) #code ends here # -------------- # Code starts",
"here # -------------- # code starts here loan_term = banks['Loan_Amount_Term'].apply",
">= 25] big_loan_term = len(big_loan) print(big_loan_term) #[loan_term.value_counts()[i] for i in",
"path # code starts here bank = pd.read_csv(path) categorical_var =",
"614 percentage_se = (56/Loan_Status)*100 percentage_nse = (366/Loan_Status)*100 # code ends",
"# -------------- # code starts here banks = bank.drop('Loan_ID',axis =",
"print(banks.isnull().sum()) bank_mode = banks.mode().iloc[0] banks = banks.fillna(bank_mode) #code ends here",
"here # -------------- # Code starts here avg_loan_amount = banks.pivot_table(index=['Gender','Married','Self_Employed'],values",
"starts here bank = pd.read_csv(path) categorical_var = bank.select_dtypes(include = 'object')",
"= 'LoanAmount') # code ends here # -------------- # code",
"(banks['Loan_Status']=='Y')).value_counts() #print(loan_approved_se) loan_approved_nse = ((banks['Self_Employed']=='No') & (banks['Loan_Status']=='Y')).value_counts() print(loan_approved_nse) Loan_Status =",
"& (banks['Loan_Status']=='Y')).value_counts() #print(loan_approved_se) loan_approved_nse = ((banks['Self_Employed']=='No') & (banks['Loan_Status']=='Y')).value_counts() print(loan_approved_nse) Loan_Status",
"loan_groupby = loan_groupby['ApplicantIncome','Credit_History'] mean_values = loan_groupby.mean() # code ends here",
"-------------- # code starts here loan_groupby = banks.groupby('Loan_Status') loan_groupby =",
"(56/Loan_Status)*100 percentage_nse = (366/Loan_Status)*100 # code ends here # --------------",
"# -------------- # Import packages import numpy as np import",
"if i >= 25] big_loan_term = len(big_loan) print(big_loan_term) #[loan_term.value_counts()[i] for",
"-------------- # Code starts here avg_loan_amount = banks.pivot_table(index=['Gender','Married','Self_Employed'],values = 'LoanAmount')",
"print(numerical_var) # code ends here # -------------- # code starts",
"import numpy as np import pandas as pd from scipy.stats",
"pd.read_csv(path) categorical_var = bank.select_dtypes(include = 'object') print(categorical_var) numerical_var = bank.select_dtypes(include",
"= bank.select_dtypes(include = 'object') print(categorical_var) numerical_var = bank.select_dtypes(include = 'number')",
"# -------------- # code starts here loan_term = banks['Loan_Amount_Term'].apply (lambda",
"numerical_var = bank.select_dtypes(include = 'number') print(numerical_var) # code ends here",
"here # -------------- # code starts here loan_approved_se = ((banks['Self_Employed']=='Yes')",
"# -------------- # code starts here loan_approved_se = ((banks['Self_Employed']=='Yes') &",
"code starts here loan_approved_se = ((banks['Self_Employed']=='Yes') & (banks['Loan_Status']=='Y')).value_counts() #print(loan_approved_se) loan_approved_nse",
"x : int(x)/12) print(loan_term.value_counts()) big_loan = [i for i in",
"'number') print(numerical_var) # code ends here # -------------- # code",
"25] # code ends here # -------------- # code starts",
"if loan_term.value_counts().index[i] >= 25] # code ends here # --------------",
"1) print(banks) print(banks.isnull().sum()) bank_mode = banks.mode().iloc[0] banks = banks.fillna(bank_mode) #code",
"code starts here loan_groupby = banks.groupby('Loan_Status') loan_groupby = loan_groupby['ApplicantIncome','Credit_History'] mean_values",
"ends here # -------------- # code starts here loan_approved_se =",
"banks['Loan_Amount_Term'].apply (lambda x : int(x)/12) print(loan_term.value_counts()) big_loan = [i for",
"loan_approved_se = ((banks['Self_Employed']=='Yes') & (banks['Loan_Status']=='Y')).value_counts() #print(loan_approved_se) loan_approved_nse = ((banks['Self_Employed']=='No') &",
"& (banks['Loan_Status']=='Y')).value_counts() print(loan_approved_nse) Loan_Status = 614 percentage_se = (56/Loan_Status)*100 percentage_nse",
"np import pandas as pd from scipy.stats import mode path",
"pd from scipy.stats import mode path # code starts here",
"code ends here # -------------- # code starts here banks",
"int(x)/12) print(loan_term.value_counts()) big_loan = [i for i in loan_term if",
"# code starts here loan_approved_se = ((banks['Self_Employed']=='Yes') & (banks['Loan_Status']=='Y')).value_counts() #print(loan_approved_se)",
"bank = pd.read_csv(path) categorical_var = bank.select_dtypes(include = 'object') print(categorical_var) numerical_var",
"bank.drop('Loan_ID',axis = 1) print(banks) print(banks.isnull().sum()) bank_mode = banks.mode().iloc[0] banks =",
"-------------- # code starts here loan_approved_se = ((banks['Self_Employed']=='Yes') & (banks['Loan_Status']=='Y')).value_counts()",
"= len(big_loan) print(big_loan_term) #[loan_term.value_counts()[i] for i in range(len(loan_terms)) if loan_term.value_counts().index[i]",
"print(big_loan_term) #[loan_term.value_counts()[i] for i in range(len(loan_terms)) if loan_term.value_counts().index[i] >= 25]",
"i in loan_term if i >= 25] big_loan_term = len(big_loan)",
"= banks.groupby('Loan_Status') loan_groupby = loan_groupby['ApplicantIncome','Credit_History'] mean_values = loan_groupby.mean() # code",
"avg_loan_amount = banks.pivot_table(index=['Gender','Married','Self_Employed'],values = 'LoanAmount') # code ends here #",
"import pandas as pd from scipy.stats import mode path #",
"banks.groupby('Loan_Status') loan_groupby = loan_groupby['ApplicantIncome','Credit_History'] mean_values = loan_groupby.mean() # code ends",
"(banks['Loan_Status']=='Y')).value_counts() print(loan_approved_nse) Loan_Status = 614 percentage_se = (56/Loan_Status)*100 percentage_nse =",
"banks = banks.fillna(bank_mode) #code ends here # -------------- # Code",
"mode path # code starts here bank = pd.read_csv(path) categorical_var",
"code starts here bank = pd.read_csv(path) categorical_var = bank.select_dtypes(include =",
"-------------- # code starts here banks = bank.drop('Loan_ID',axis = 1)",
"#print(loan_approved_se) loan_approved_nse = ((banks['Self_Employed']=='No') & (banks['Loan_Status']=='Y')).value_counts() print(loan_approved_nse) Loan_Status = 614",
">= 25] # code ends here # -------------- # code",
"ends here # -------------- # code starts here loan_groupby =",
"# -------------- # code starts here loan_groupby = banks.groupby('Loan_Status') loan_groupby",
"[i for i in loan_term if i >= 25] big_loan_term",
": int(x)/12) print(loan_term.value_counts()) big_loan = [i for i in loan_term",
"len(big_loan) print(big_loan_term) #[loan_term.value_counts()[i] for i in range(len(loan_terms)) if loan_term.value_counts().index[i] >=",
"range(len(loan_terms)) if loan_term.value_counts().index[i] >= 25] # code ends here #",
"here loan_approved_se = ((banks['Self_Employed']=='Yes') & (banks['Loan_Status']=='Y')).value_counts() #print(loan_approved_se) loan_approved_nse = ((banks['Self_Employed']=='No')",
"((banks['Self_Employed']=='Yes') & (banks['Loan_Status']=='Y')).value_counts() #print(loan_approved_se) loan_approved_nse = ((banks['Self_Employed']=='No') & (banks['Loan_Status']=='Y')).value_counts() print(loan_approved_nse)",
"(lambda x : int(x)/12) print(loan_term.value_counts()) big_loan = [i for i",
"= [i for i in loan_term if i >= 25]",
"numpy as np import pandas as pd from scipy.stats import",
"starts here banks = bank.drop('Loan_ID',axis = 1) print(banks) print(banks.isnull().sum()) bank_mode",
"bank.select_dtypes(include = 'object') print(categorical_var) numerical_var = bank.select_dtypes(include = 'number') print(numerical_var)",
"code starts here loan_term = banks['Loan_Amount_Term'].apply (lambda x : int(x)/12)",
"bank_mode = banks.mode().iloc[0] banks = banks.fillna(bank_mode) #code ends here #",
"loan_approved_nse = ((banks['Self_Employed']=='No') & (banks['Loan_Status']=='Y')).value_counts() print(loan_approved_nse) Loan_Status = 614 percentage_se",
"big_loan_term = len(big_loan) print(big_loan_term) #[loan_term.value_counts()[i] for i in range(len(loan_terms)) if",
"(366/Loan_Status)*100 # code ends here # -------------- # code starts",
"scipy.stats import mode path # code starts here bank =",
"#[loan_term.value_counts()[i] for i in range(len(loan_terms)) if loan_term.value_counts().index[i] >= 25] #",
"= (56/Loan_Status)*100 percentage_nse = (366/Loan_Status)*100 # code ends here #",
"as pd from scipy.stats import mode path # code starts",
"Code starts here avg_loan_amount = banks.pivot_table(index=['Gender','Married','Self_Employed'],values = 'LoanAmount') # code",
"= bank.drop('Loan_ID',axis = 1) print(banks) print(banks.isnull().sum()) bank_mode = banks.mode().iloc[0] banks",
"pandas as pd from scipy.stats import mode path # code",
"as np import pandas as pd from scipy.stats import mode",
"print(loan_approved_nse) Loan_Status = 614 percentage_se = (56/Loan_Status)*100 percentage_nse = (366/Loan_Status)*100",
"code ends here # -------------- # code starts here loan_groupby",
"# code starts here banks = bank.drop('Loan_ID',axis = 1) print(banks)",
"= banks.mode().iloc[0] banks = banks.fillna(bank_mode) #code ends here # --------------",
"import mode path # code starts here bank = pd.read_csv(path)",
"loan_term.value_counts().index[i] >= 25] # code ends here # -------------- #",
"-------------- # code starts here loan_term = banks['Loan_Amount_Term'].apply (lambda x",
"((banks['Self_Employed']=='No') & (banks['Loan_Status']=='Y')).value_counts() print(loan_approved_nse) Loan_Status = 614 percentage_se = (56/Loan_Status)*100",
"bank.select_dtypes(include = 'number') print(numerical_var) # code ends here # --------------",
"= 1) print(banks) print(banks.isnull().sum()) bank_mode = banks.mode().iloc[0] banks = banks.fillna(bank_mode)",
"for i in loan_term if i >= 25] big_loan_term =",
"here loan_groupby = banks.groupby('Loan_Status') loan_groupby = loan_groupby['ApplicantIncome','Credit_History'] mean_values = loan_groupby.mean()",
"categorical_var = bank.select_dtypes(include = 'object') print(categorical_var) numerical_var = bank.select_dtypes(include =",
"here # -------------- # code starts here loan_groupby = banks.groupby('Loan_Status')",
"packages import numpy as np import pandas as pd from",
"from scipy.stats import mode path # code starts here bank",
"loan_groupby = banks.groupby('Loan_Status') loan_groupby = loan_groupby['ApplicantIncome','Credit_History'] mean_values = loan_groupby.mean() #",
"= ((banks['Self_Employed']=='Yes') & (banks['Loan_Status']=='Y')).value_counts() #print(loan_approved_se) loan_approved_nse = ((banks['Self_Employed']=='No') & (banks['Loan_Status']=='Y')).value_counts()",
"print(categorical_var) numerical_var = bank.select_dtypes(include = 'number') print(numerical_var) # code ends",
"loan_term = banks['Loan_Amount_Term'].apply (lambda x : int(x)/12) print(loan_term.value_counts()) big_loan =",
"= 614 percentage_se = (56/Loan_Status)*100 percentage_nse = (366/Loan_Status)*100 # code",
"'LoanAmount') # code ends here # -------------- # code starts",
"banks.fillna(bank_mode) #code ends here # -------------- # Code starts here",
"for i in range(len(loan_terms)) if loan_term.value_counts().index[i] >= 25] # code",
"starts here loan_term = banks['Loan_Amount_Term'].apply (lambda x : int(x)/12) print(loan_term.value_counts())",
"= banks.pivot_table(index=['Gender','Married','Self_Employed'],values = 'LoanAmount') # code ends here # --------------",
"ends here # -------------- # Code starts here avg_loan_amount =",
"banks.pivot_table(index=['Gender','Married','Self_Employed'],values = 'LoanAmount') # code ends here # -------------- #",
"code ends here # -------------- # code starts here loan_term",
"here banks = bank.drop('Loan_ID',axis = 1) print(banks) print(banks.isnull().sum()) bank_mode =",
"starts here loan_groupby = banks.groupby('Loan_Status') loan_groupby = loan_groupby['ApplicantIncome','Credit_History'] mean_values =",
"here loan_term = banks['Loan_Amount_Term'].apply (lambda x : int(x)/12) print(loan_term.value_counts()) big_loan",
"Import packages import numpy as np import pandas as pd",
"= banks['Loan_Amount_Term'].apply (lambda x : int(x)/12) print(loan_term.value_counts()) big_loan = [i",
"here avg_loan_amount = banks.pivot_table(index=['Gender','Married','Self_Employed'],values = 'LoanAmount') # code ends here",
"banks.mode().iloc[0] banks = banks.fillna(bank_mode) #code ends here # -------------- #",
"here bank = pd.read_csv(path) categorical_var = bank.select_dtypes(include = 'object') print(categorical_var)",
"= 'number') print(numerical_var) # code ends here # -------------- #",
"= 'object') print(categorical_var) numerical_var = bank.select_dtypes(include = 'number') print(numerical_var) #",
"in loan_term if i >= 25] big_loan_term = len(big_loan) print(big_loan_term)",
"percentage_se = (56/Loan_Status)*100 percentage_nse = (366/Loan_Status)*100 # code ends here",
"= ((banks['Self_Employed']=='No') & (banks['Loan_Status']=='Y')).value_counts() print(loan_approved_nse) Loan_Status = 614 percentage_se =",
"# code starts here loan_term = banks['Loan_Amount_Term'].apply (lambda x :",
"ends here # -------------- # code starts here banks =",
"banks = bank.drop('Loan_ID',axis = 1) print(banks) print(banks.isnull().sum()) bank_mode = banks.mode().iloc[0]",
"print(banks) print(banks.isnull().sum()) bank_mode = banks.mode().iloc[0] banks = banks.fillna(bank_mode) #code ends",
"= pd.read_csv(path) categorical_var = bank.select_dtypes(include = 'object') print(categorical_var) numerical_var =",
"code ends here # -------------- # code starts here loan_approved_se",
"i >= 25] big_loan_term = len(big_loan) print(big_loan_term) #[loan_term.value_counts()[i] for i",
"i in range(len(loan_terms)) if loan_term.value_counts().index[i] >= 25] # code ends",
"print(loan_term.value_counts()) big_loan = [i for i in loan_term if i",
"25] big_loan_term = len(big_loan) print(big_loan_term) #[loan_term.value_counts()[i] for i in range(len(loan_terms))",
"percentage_nse = (366/Loan_Status)*100 # code ends here # -------------- #",
"'object') print(categorical_var) numerical_var = bank.select_dtypes(include = 'number') print(numerical_var) # code",
"# -------------- # Code starts here avg_loan_amount = banks.pivot_table(index=['Gender','Married','Self_Employed'],values =",
"here # -------------- # code starts here banks = bank.drop('Loan_ID',axis",
"= bank.select_dtypes(include = 'number') print(numerical_var) # code ends here #",
"in range(len(loan_terms)) if loan_term.value_counts().index[i] >= 25] # code ends here",
"starts here avg_loan_amount = banks.pivot_table(index=['Gender','Married','Self_Employed'],values = 'LoanAmount') # code ends",
"code starts here banks = bank.drop('Loan_ID',axis = 1) print(banks) print(banks.isnull().sum())",
"# Code starts here avg_loan_amount = banks.pivot_table(index=['Gender','Married','Self_Employed'],values = 'LoanAmount') #",
"# code starts here loan_groupby = banks.groupby('Loan_Status') loan_groupby = loan_groupby['ApplicantIncome','Credit_History']"
] |
[
"= EvalEnvironment.capture() data = {\"X\" : [0,1,2,3], \"Y\" : [1,2,3,4]}",
"import (EvalEnvironment, dmatrix, build_design_matrices, PatsyError, Origin) def test_issue_11(): # Give",
"PatsyError, Origin) def test_issue_11(): # Give a sensible error message",
"from patsy import (EvalEnvironment, dmatrix, build_design_matrices, PatsyError, Origin) def test_issue_11():",
"PatsyError as e: assert e.origin == Origin(formula, 0, 4) else:",
"\"Y\" : [1,2,3,4]} formula = \"C(X) + Y\" new_data =",
"covered somewhere # else) from patsy import (EvalEnvironment, dmatrix, build_design_matrices,",
"= dmatrix(formula, data) try: build_design_matrices([info.design_info], new_data) except PatsyError as e:",
"Give a sensible error message for level mismatches # (At",
"a sensible error message for level mismatches # (At some",
"for license information. # Regression tests for fixed bugs (when",
"LICENSE.txt for license information. # Regression tests for fixed bugs",
"def test_issue_11(): # Give a sensible error message for level",
"fixed bugs (when not otherwise better covered somewhere # else)",
"patsy import (EvalEnvironment, dmatrix, build_design_matrices, PatsyError, Origin) def test_issue_11(): #",
"on these errors) env = EvalEnvironment.capture() data = {\"X\" :",
"(C) 2013 <NAME> <<EMAIL>> # See file LICENSE.txt for license",
"try: build_design_matrices([info.design_info], new_data) except PatsyError as e: assert e.origin ==",
"e: assert e.origin == Origin(formula, 0, 4) else: assert False",
"# See file LICENSE.txt for license information. # Regression tests",
"EvalEnvironment.capture() data = {\"X\" : [0,1,2,3], \"Y\" : [1,2,3,4]} formula",
"message for level mismatches # (At some points we've failed",
"level mismatches # (At some points we've failed to put",
"[1,2,3,4]} formula = \"C(X) + Y\" new_data = {\"X\" :",
"dmatrix(formula, data) try: build_design_matrices([info.design_info], new_data) except PatsyError as e: assert",
"# This file is part of Patsy # Copyright (C)",
"build_design_matrices, PatsyError, Origin) def test_issue_11(): # Give a sensible error",
"we've failed to put an origin= on these errors) env",
"Regression tests for fixed bugs (when not otherwise better covered",
"information. # Regression tests for fixed bugs (when not otherwise",
"an origin= on these errors) env = EvalEnvironment.capture() data =",
"(EvalEnvironment, dmatrix, build_design_matrices, PatsyError, Origin) def test_issue_11(): # Give a",
"= \"C(X) + Y\" new_data = {\"X\" : [0,0,1,2,3,3,4], \"Y\"",
"failed to put an origin= on these errors) env =",
"info = dmatrix(formula, data) try: build_design_matrices([info.design_info], new_data) except PatsyError as",
"tests for fixed bugs (when not otherwise better covered somewhere",
"mismatches # (At some points we've failed to put an",
"data) try: build_design_matrices([info.design_info], new_data) except PatsyError as e: assert e.origin",
"[0,0,1,2,3,3,4], \"Y\" : [1,2,3,4,5,6,7]} info = dmatrix(formula, data) try: build_design_matrices([info.design_info],",
"put an origin= on these errors) env = EvalEnvironment.capture() data",
"<NAME> <<EMAIL>> # See file LICENSE.txt for license information. #",
"[0,1,2,3], \"Y\" : [1,2,3,4]} formula = \"C(X) + Y\" new_data",
": [0,1,2,3], \"Y\" : [1,2,3,4]} formula = \"C(X) + Y\"",
"some points we've failed to put an origin= on these",
"\"Y\" : [1,2,3,4,5,6,7]} info = dmatrix(formula, data) try: build_design_matrices([info.design_info], new_data)",
"as e: assert e.origin == Origin(formula, 0, 4) else: assert",
"of Patsy # Copyright (C) 2013 <NAME> <<EMAIL>> # See",
"to put an origin= on these errors) env = EvalEnvironment.capture()",
"= {\"X\" : [0,1,2,3], \"Y\" : [1,2,3,4]} formula = \"C(X)",
"+ Y\" new_data = {\"X\" : [0,0,1,2,3,3,4], \"Y\" : [1,2,3,4,5,6,7]}",
"dmatrix, build_design_matrices, PatsyError, Origin) def test_issue_11(): # Give a sensible",
"not otherwise better covered somewhere # else) from patsy import",
"is part of Patsy # Copyright (C) 2013 <NAME> <<EMAIL>>",
"for fixed bugs (when not otherwise better covered somewhere #",
"# else) from patsy import (EvalEnvironment, dmatrix, build_design_matrices, PatsyError, Origin)",
"license information. # Regression tests for fixed bugs (when not",
"new_data = {\"X\" : [0,0,1,2,3,3,4], \"Y\" : [1,2,3,4,5,6,7]} info =",
"data = {\"X\" : [0,1,2,3], \"Y\" : [1,2,3,4]} formula =",
"{\"X\" : [0,0,1,2,3,3,4], \"Y\" : [1,2,3,4,5,6,7]} info = dmatrix(formula, data)",
"2013 <NAME> <<EMAIL>> # See file LICENSE.txt for license information.",
"{\"X\" : [0,1,2,3], \"Y\" : [1,2,3,4]} formula = \"C(X) +",
": [1,2,3,4,5,6,7]} info = dmatrix(formula, data) try: build_design_matrices([info.design_info], new_data) except",
"for level mismatches # (At some points we've failed to",
"test_issue_11(): # Give a sensible error message for level mismatches",
"# Give a sensible error message for level mismatches #",
"(when not otherwise better covered somewhere # else) from patsy",
"<<EMAIL>> # See file LICENSE.txt for license information. # Regression",
"error message for level mismatches # (At some points we've",
"[1,2,3,4,5,6,7]} info = dmatrix(formula, data) try: build_design_matrices([info.design_info], new_data) except PatsyError",
"otherwise better covered somewhere # else) from patsy import (EvalEnvironment,",
"else) from patsy import (EvalEnvironment, dmatrix, build_design_matrices, PatsyError, Origin) def",
"Patsy # Copyright (C) 2013 <NAME> <<EMAIL>> # See file",
"bugs (when not otherwise better covered somewhere # else) from",
"(At some points we've failed to put an origin= on",
"# (At some points we've failed to put an origin=",
"part of Patsy # Copyright (C) 2013 <NAME> <<EMAIL>> #",
": [0,0,1,2,3,3,4], \"Y\" : [1,2,3,4,5,6,7]} info = dmatrix(formula, data) try:",
"# Copyright (C) 2013 <NAME> <<EMAIL>> # See file LICENSE.txt",
"origin= on these errors) env = EvalEnvironment.capture() data = {\"X\"",
"new_data) except PatsyError as e: assert e.origin == Origin(formula, 0,",
"# Regression tests for fixed bugs (when not otherwise better",
"build_design_matrices([info.design_info], new_data) except PatsyError as e: assert e.origin == Origin(formula,",
"\"C(X) + Y\" new_data = {\"X\" : [0,0,1,2,3,3,4], \"Y\" :",
"sensible error message for level mismatches # (At some points",
"Origin) def test_issue_11(): # Give a sensible error message for",
"these errors) env = EvalEnvironment.capture() data = {\"X\" : [0,1,2,3],",
"except PatsyError as e: assert e.origin == Origin(formula, 0, 4)",
"file LICENSE.txt for license information. # Regression tests for fixed",
"file is part of Patsy # Copyright (C) 2013 <NAME>",
"formula = \"C(X) + Y\" new_data = {\"X\" : [0,0,1,2,3,3,4],",
"This file is part of Patsy # Copyright (C) 2013",
"better covered somewhere # else) from patsy import (EvalEnvironment, dmatrix,",
"See file LICENSE.txt for license information. # Regression tests for",
"Y\" new_data = {\"X\" : [0,0,1,2,3,3,4], \"Y\" : [1,2,3,4,5,6,7]} info",
": [1,2,3,4]} formula = \"C(X) + Y\" new_data = {\"X\"",
"= {\"X\" : [0,0,1,2,3,3,4], \"Y\" : [1,2,3,4,5,6,7]} info = dmatrix(formula,",
"somewhere # else) from patsy import (EvalEnvironment, dmatrix, build_design_matrices, PatsyError,",
"Copyright (C) 2013 <NAME> <<EMAIL>> # See file LICENSE.txt for",
"points we've failed to put an origin= on these errors)",
"env = EvalEnvironment.capture() data = {\"X\" : [0,1,2,3], \"Y\" :",
"errors) env = EvalEnvironment.capture() data = {\"X\" : [0,1,2,3], \"Y\""
] |
[
"1 if img_num is not None: break if hasattr(image, 'fp')",
"the file is not readable image.getdata()[0] except IOError as e:",
"file is not readable image.getdata()[0] except IOError as e: site",
"format_str = \"PNG\" arr = np.asanyarray(arr) if arr.dtype.kind == 'b':",
"= shape[::-1] else: frame = np.array(frame, dtype=dtype) frames.append(frame) i +=",
"= ['imread', 'imsave'] import numpy as np from PIL import",
"np from PIL import Image from ...util import img_as_ubyte, img_as_uint",
"in a file with multiple images (zero-indexed). kwargs : keyword",
"is None: format_str = \"PNG\" # Check for png in",
"differences (R - G and G - B) # are",
": int, optional Specifies which image to read in a",
"mode) # PIL 1.1.7 else: image_shape = (arr.shape[1], arr.shape[0]) try:",
"image palette are gray. \"\"\" assert pil_image.mode == 'P' #",
"in Palette mode. Returns ------- is_grayscale : bool True if",
"arr, format_str=None, **kwargs): \"\"\"Save an image to disk. Parameters ----------",
"i += 1 if img_num is not None: break if",
"array with R, G, B columns palette = np.asarray(pil_image.getpalette()).reshape((256, 3))",
"to a PIL object. Parameters ---------- Refer to ``imsave``. \"\"\"",
"References ---------- .. [1] http://pillow.readthedocs.org/en/latest/handbook/image-file-formats.html \"\"\" # default to PNG",
"Pillow save function (or tifffile save function, for Tiff files).",
"= image.convert('RGB') elif image.mode == '1': frame = image.convert('L') elif",
"list of supported formats. References ---------- .. [1] http://pillow.readthedocs.org/en/latest/handbook/image-file-formats.html \"\"\"",
"an array with R, G, B columns palette = np.asarray(pil_image.getpalette()).reshape((256,",
"= 'L' mode_base = 'L' try: array_buffer = arr.tobytes() except",
"except AttributeError: im.fromstring(array_buffer, 'raw', mode) # PIL 1.1.7 else: image_shape",
"Tiff files). These are format dependent. For example, Pillow's JPEG",
"(arr.shape[1], arr.shape[0]) try: im = Image.frombytes(mode, image_shape, array_buffer) except AttributeError:",
"will be derived from the extension if fname is a",
"__all__ = ['imread', 'imsave'] import numpy as np from PIL",
"im def imsave(fname, arr, format_str=None, **kwargs): \"\"\"Save an image to",
"= image.convert('RGB') if image.mode.startswith('I;16'): shape = image.size dtype = '>u2'",
"dtype=dtype, img_num=img_num) else: im = Image.open(fname) return pil_to_ndarray(im, dtype=dtype, img_num=img_num)",
"and G - B) # are all zero. return np.allclose(np.diff(valid_palette),",
"an integer ``quality`` argument with values in [1, 95], while",
"uint8 or float Array (image) to save. Arrays of data-type",
"if all colors in image palette are gray. \"\"\" assert",
"image.convert('L') elif 'A' in image.mode: frame = image.convert('RGBA') elif image.mode",
"= Image.new(mode_base, arr.T.shape) try: im.frombytes(array_buffer, 'raw', mode) except AttributeError: im.fromstring(array_buffer,",
"whereas floating-point arrays must be in [0, 1]. format_str: str",
"that is in Palette mode. Returns ------- is_grayscale : bool",
"[0, 9]. Notes ----- Use the Python Imaging Library. See",
"ValueError(\"Invalid number of channels in image array.\") img = ndarray_to_pil(arr,",
"ndarray_to_pil(arr, format_str=None): \"\"\"Export an ndarray to a PIL object. Parameters",
"- Integer values in [0, 255] and Boolean types ->",
"(zero-indexed). kwargs : keyword pairs, optional Addition keyword arguments to",
"list of other supported formats. All images besides single channel",
"channel differences (R - G and G - B) #",
"are converted using `img_as_uint8`. Single Channel PNGs have the following",
"if arr.ndim not in (2, 3): raise ValueError(\"Invalid shape for",
"i = 0 while 1: try: image.seek(i) except EOFError: break",
"open(fname, 'rb') as f: im = Image.open(f) return pil_to_ndarray(im, dtype=dtype,",
"Palette mode. Returns ------- is_grayscale : bool True if all",
"arr = img_as_ubyte(arr) mode = 'L' mode_base = 'L' try:",
"values in [0, 255], whereas floating-point arrays must be in",
"this will raise an IOError if the file is not",
"Check for png in filename if (isinstance(fname, str) and fname.lower().endswith(\".png\")):",
"if arr.dtype.kind == 'f': arr = img_as_uint(arr) elif arr.max() <",
"0: arr = arr.astype(np.uint8) mode = mode_base = 'L' else:",
"'b': arr = arr.astype(np.uint8) if arr.ndim not in (2, 3):",
"'S' in image.mode: dtype = dtype.replace('u', 'i') frame = np.fromstring(frame.tobytes(),",
"get palette as an array with R, G, B columns",
"('Could not load \"%s\" \\n' 'Reason: \"%s\"\\n' 'Please see documentation",
"an ndarray, in memory. Parameters ---------- Refer to ``imread``. \"\"\"",
"formats. References ---------- .. [1] http://pillow.readthedocs.org/en/latest/handbook/image-file-formats.html \"\"\" if isinstance(fname, str):",
"_palette_is_grayscale(image) if grayscale: frame = image.convert('L') else: if image.format ==",
"is grayscale if channel differences (R - G and G",
"image.mode == '1': frame = image.convert('L') elif 'A' in image.mode:",
"'PNG' and 'transparency' in image.info: frame = image.convert('RGBA') else: frame",
"# this will raise an IOError if the file is",
"PNG if using a file-like object; this will be derived",
"not None: break if hasattr(image, 'fp') and image.fp: image.fp.close() if",
"all zero. return np.allclose(np.diff(valid_palette), 0) def ndarray_to_pil(arr, format_str=None): \"\"\"Export an",
"or file File name or file-like-object. dtype : numpy dtype",
"int, optional Specifies which image to read in a file",
"PIL docs [1]_ for a list of supported formats. References",
"try: im = Image.frombytes(mode, image_shape, array_buffer) except AttributeError: im =",
"array_buffer = arr.tobytes() except AttributeError: array_buffer = arr.tostring() # Numpy",
"[0, 1]. format_str: str Format to save as, this is",
"array_buffer) except AttributeError: im = Image.fromstring(mode, image_shape, array_buffer) # PIL",
"and image.mode == 'I' and dtype is None: dtype =",
"read in a file with multiple images (zero-indexed). kwargs :",
"in ['png', 'PNG']: mode = 'I;16' mode_base = 'I' if",
"'P': if grayscale is None: grayscale = _palette_is_grayscale(image) if grayscale:",
"of data-type uint8 should have values in [0, 255], whereas",
"if using a file-like object; this will be derived from",
"grayscale = None i = 0 while 1: try: image.seek(i)",
"``quality`` argument with values in [1, 95], while TIFFFile supports",
"array_buffer = arr.tostring() # Numpy < 1.9 if arr.ndim ==",
"if arr.shape[2] not in (3, 4): raise ValueError(\"Invalid number of",
"array_buffer) # PIL 1.1.7 return im def imsave(fname, arr, format_str=None,",
"floating-point arrays must be in [0, 1]. format_str: str Format",
"if fname is a string kwargs: dict Keyword arguments to",
"not isinstance(fname, str) and format_str is None: format_str = \"PNG\"",
"if arr.dtype.kind == 'b': arr = arr.astype(np.uint8) if arr.ndim not",
"Returns ------- is_grayscale : bool True if all colors in",
"import img_as_ubyte, img_as_uint def imread(fname, dtype=None, img_num=None, **kwargs): \"\"\"Load an",
"< 1.9 if arr.ndim == 2: im = Image.new(mode_base, arr.T.shape)",
"as f: im = Image.open(f) return pil_to_ndarray(im, dtype=dtype, img_num=img_num) else:",
"JPEG save function supports an integer ``quality`` argument with values",
"np.array(frames) elif frames: return frames[0] elif img_num: raise IndexError('Could not",
"docs [1]_ for a list of supported formats. References ----------",
"have values in [0, 255], whereas floating-point arrays must be",
"using the Python Imaging Library. See PIL docs [1]_ for",
"of uint8 or float Array (image) to save. Arrays of",
"= 0 while 1: try: image.seek(i) except EOFError: break frame",
"is_grayscale : bool True if all colors in image palette",
"\"\"\"Load an image from file. Parameters ---------- fname : str",
"image.convert('RGB') if image.mode.startswith('I;16'): shape = image.size dtype = '>u2' if",
"uint8 should have values in [0, 255], whereas floating-point arrays",
"[] grayscale = None i = 0 while 1: try:",
"3: arr = img_as_ubyte(arr) mode = {3: 'RGB', 4: 'RGBA'}[arr.shape[2]]",
"Numpy < 1.9 if arr.ndim == 2: im = Image.new(mode_base,",
"-> img_as_uint16 References ---------- .. [1] http://pillow.readthedocs.org/en/latest/handbook/image-file-formats.html \"\"\" # default",
"'I' and dtype is None: dtype = 'uint16' if image.mode",
"image #%s' % img_num) def _palette_is_grayscale(pil_image): \"\"\"Return True if PIL",
"[0, 255], whereas floating-point arrays must be in [0, 1].",
"argument with values in [0, 9]. Notes ----- Use the",
"if arr.ndim == 2: im = Image.new(mode_base, arr.T.shape) try: im.frombytes(array_buffer,",
"All images besides single channel PNGs are converted using `img_as_uint8`.",
"len(frames) > 1: return np.array(frames) elif frames: return frames[0] elif",
"in palette mode is grayscale. Parameters ---------- pil_image : PIL",
"img_num : int, optional Specifies which image to read in",
"data-type uint8 should have values in [0, 255], whereas floating-point",
"Integer values in [0, 255] and Boolean types -> img_as_uint8",
"argument with values in [1, 95], while TIFFFile supports a",
"string specifier Specifies data type of array elements. img_num :",
"img_num) def _palette_is_grayscale(pil_image): \"\"\"Return True if PIL image in palette",
"is None and len(frames) > 1: return np.array(frames) elif frames:",
"np.array(frame, dtype=dtype) frames.append(frame) i += 1 if img_num is not",
"import numpy as np from PIL import Image from ...util",
"else '<u2' if 'S' in image.mode: dtype = dtype.replace('u', 'i')",
"if PIL image in palette mode is grayscale. Parameters ----------",
"== 3: arr = img_as_ubyte(arr) mode = {3: 'RGB', 4:",
"= img_as_ubyte(arr) mode = 'L' mode_base = 'L' try: array_buffer",
"if image.mode.startswith('I;16'): shape = image.size dtype = '>u2' if image.mode.endswith('B')",
"Floating point and other integers -> img_as_uint16 References ---------- ..",
"to pass through. Notes ----- Files are read using the",
"if file-like object if not isinstance(fname, str) and format_str is",
"a list of supported formats. References ---------- .. [1] http://pillow.readthedocs.org/en/latest/handbook/image-file-formats.html",
"is None: dtype = 'uint16' if image.mode == 'P': if",
"= '>u2' if image.mode.endswith('B') else '<u2' if 'S' in image.mode:",
"not find image #%s' % img_num) def _palette_is_grayscale(pil_image): \"\"\"Return True",
"to ``imread``. \"\"\" try: # this will raise an IOError",
"'CMYK': frame = image.convert('RGB') if image.mode.startswith('I;16'): shape = image.size dtype",
"---------- pil_image : PIL image PIL Image that is in",
"e: site = \"http://pillow.readthedocs.org/en/latest/installation.html#external-libraries\" pillow_error_message = str(e) error_message = ('Could",
"PIL object. Parameters ---------- Refer to ``imsave``. \"\"\" if arr.ndim",
"# get palette as an array with R, G, B",
"= arr.astype(np.uint8) if arr.ndim not in (2, 3): raise ValueError(\"Invalid",
"Image that is in Palette mode. Returns ------- is_grayscale :",
"str): with open(fname, 'rb') as f: im = Image.open(f) return",
"while 1: try: image.seek(i) except EOFError: break frame = image",
"arguments to the Pillow save function (or tifffile save function,",
"memory. Parameters ---------- Refer to ``imread``. \"\"\" try: # this",
"img_as_ubyte, img_as_uint def imread(fname, dtype=None, img_num=None, **kwargs): \"\"\"Load an image",
"will raise an IOError if the file is not readable",
"through. Notes ----- Files are read using the Python Imaging",
"image.format == 'PNG' and image.mode == 'I' and dtype is",
"dtype=dtype) frames.append(frame) i += 1 if img_num is not None:",
"arr = arr.astype(np.uint8) mode = mode_base = 'L' else: arr",
"arr.ndim == 2: im = Image.new(mode_base, arr.T.shape) try: im.frombytes(array_buffer, 'raw',",
"type of array elements. img_num : int, optional Specifies which",
"= image.size dtype = '>u2' if image.mode.endswith('B') else '<u2' if",
"= _palette_is_grayscale(image) if grayscale: frame = image.convert('L') else: if image.format",
"'1': frame = image.convert('L') elif 'A' in image.mode: frame =",
"readable image.getdata()[0] except IOError as e: site = \"http://pillow.readthedocs.org/en/latest/installation.html#external-libraries\" pillow_error_message",
"frame.shape = shape[::-1] else: frame = np.array(frame, dtype=dtype) frames.append(frame) i",
"'PNG' and image.mode == 'I' and dtype is None: dtype",
"pairs, optional Addition keyword arguments to pass through. Notes -----",
"\"%s\" \\n' 'Reason: \"%s\"\\n' 'Please see documentation at: %s' %",
"site)) raise ValueError(error_message) frames = [] grayscale = None i",
"specifier Specifies data type of array elements. img_num : int,",
"= img_as_uint(arr) elif arr.max() < 256 and arr.min() >= 0:",
"object; this will be derived from the extension if fname",
"1 continue if image.format == 'PNG' and image.mode == 'I'",
"# Image is grayscale if channel differences (R - G",
"mode is grayscale. Parameters ---------- pil_image : PIL image PIL",
"not in (3, 4): raise ValueError(\"Invalid number of channels in",
"an IOError if the file is not readable image.getdata()[0] except",
"AttributeError: im = Image.fromstring(mode, image_shape, array_buffer) # PIL 1.1.7 return",
"number of channels in image array.\") img = ndarray_to_pil(arr, format_str=format_str)",
"image.seek(i) except EOFError: break frame = image if img_num is",
"destination file. arr : ndarray of uint8 or float Array",
"#%s' % img_num) def _palette_is_grayscale(pil_image): \"\"\"Return True if PIL image",
"'imsave'] import numpy as np from PIL import Image from",
"arr.shape[0]) try: im = Image.frombytes(mode, image_shape, array_buffer) except AttributeError: im",
"---------- .. [1] http://pillow.readthedocs.org/en/latest/handbook/image-file-formats.html \"\"\" if isinstance(fname, str): with open(fname,",
"for png in filename if (isinstance(fname, str) and fname.lower().endswith(\".png\")): format_str",
"the following behavior: - Integer values in [0, 255] and",
"str) and fname.lower().endswith(\".png\")): format_str = \"PNG\" arr = np.asanyarray(arr) if",
"PNGs are converted using `img_as_uint8`. Single Channel PNGs have the",
"== 'b': arr = arr.astype(np.uint8) if arr.ndim not in (2,",
"image if img_num is not None and img_num != i:",
"= Image.open(f) return pil_to_ndarray(im, dtype=dtype, img_num=img_num) else: im = Image.open(fname)",
"hasattr(image, 'fp') and image.fp: image.fp.close() if img_num is None and",
"image.info: frame = image.convert('RGBA') else: frame = image.convert('RGB') elif image.mode",
"(R - G and G - B) # are all",
"as, this is defaulted to PNG if using a file-like",
"\"http://pillow.readthedocs.org/en/latest/installation.html#external-libraries\" pillow_error_message = str(e) error_message = ('Could not load \"%s\"",
"----- Files are read using the Python Imaging Library. See",
"== 'PNG' and 'transparency' in image.info: frame = image.convert('RGBA') else:",
"% img_num) def _palette_is_grayscale(pil_image): \"\"\"Return True if PIL image in",
"% (image.filename, pillow_error_message, site)) raise ValueError(error_message) frames = [] grayscale",
"!= i: image.getdata()[0] i += 1 continue if image.format ==",
"if (isinstance(fname, str) and fname.lower().endswith(\".png\")): format_str = \"PNG\" arr =",
"the extension if fname is a string kwargs: dict Keyword",
"PIL Image that is in Palette mode. Returns ------- is_grayscale",
"# are all zero. return np.allclose(np.diff(valid_palette), 0) def ndarray_to_pil(arr, format_str=None):",
"and dtype is None: dtype = 'uint16' if image.mode ==",
"frame = image.convert('RGBA') elif image.mode == 'CMYK': frame = image.convert('RGB')",
"= np.asanyarray(arr) if arr.dtype.kind == 'b': arr = arr.astype(np.uint8) if",
"object Name of destination file. arr : ndarray of uint8",
"----- Use the Python Imaging Library. See PIL docs [1]_",
"Refer to ``imsave``. \"\"\" if arr.ndim == 3: arr =",
"(2, 3): raise ValueError(\"Invalid shape for image array: %s\" %",
"dtype = '>u2' if image.mode.endswith('B') else '<u2' if 'S' in",
"image.convert('RGBA') elif image.mode == 'CMYK': frame = image.convert('RGB') if image.mode.startswith('I;16'):",
"values in [0, 255] and Boolean types -> img_as_uint8 -",
"im.frombytes(array_buffer, 'raw', mode) except AttributeError: im.fromstring(array_buffer, 'raw', mode) # PIL",
"using `img_as_uint8`. Single Channel PNGs have the following behavior: -",
"**kwargs): \"\"\"Save an image to disk. Parameters ---------- fname :",
"a ``compress`` integer argument with values in [0, 9]. Notes",
"\\n' 'Reason: \"%s\"\\n' 'Please see documentation at: %s' % (image.filename,",
"Arrays of data-type uint8 should have values in [0, 255],",
"arr.tobytes() except AttributeError: array_buffer = arr.tostring() # Numpy < 1.9",
"[1]_ for a list of other supported formats. All images",
"95], while TIFFFile supports a ``compress`` integer argument with values",
"image array: %s\" % (arr.shape, )) if arr.ndim == 3:",
"images (zero-indexed). kwargs : keyword pairs, optional Addition keyword arguments",
"docs [1]_ for a list of other supported formats. All",
": bool True if all colors in image palette are",
"grayscale. Parameters ---------- pil_image : PIL image PIL Image that",
"be in [0, 1]. format_str: str Format to save as,",
"> 1: return np.array(frames) elif frames: return frames[0] elif img_num:",
"not load \"%s\" \\n' 'Reason: \"%s\"\\n' 'Please see documentation at:",
"isinstance(fname, str): with open(fname, 'rb') as f: im = Image.open(f)",
"site = \"http://pillow.readthedocs.org/en/latest/installation.html#external-libraries\" pillow_error_message = str(e) error_message = ('Could not",
"in (3, 4): raise ValueError(\"Invalid number of channels in image",
"break frame = image if img_num is not None and",
"filename if (isinstance(fname, str) and fname.lower().endswith(\".png\")): format_str = \"PNG\" arr",
"mode_base = 'I' if arr.dtype.kind == 'f': arr = img_as_uint(arr)",
"'f': arr = img_as_uint(arr) elif arr.max() < 256 and arr.min()",
"== 'CMYK': frame = image.convert('RGB') if image.mode.startswith('I;16'): shape = image.size",
"of array elements. img_num : int, optional Specifies which image",
"to ``imsave``. \"\"\" if arr.ndim == 3: arr = img_as_ubyte(arr)",
"1] # Image is grayscale if channel differences (R -",
"AttributeError: im.fromstring(array_buffer, 'raw', mode) # PIL 1.1.7 else: image_shape =",
"should have values in [0, 255], whereas floating-point arrays must",
"Parameters ---------- Refer to ``imread``. \"\"\" try: # this will",
"if 'S' in image.mode: dtype = dtype.replace('u', 'i') frame =",
"...util import img_as_ubyte, img_as_uint def imread(fname, dtype=None, img_num=None, **kwargs): \"\"\"Load",
"\"PNG\" arr = np.asanyarray(arr) if arr.dtype.kind == 'b': arr =",
"'P' # get palette as an array with R, G,",
"are format dependent. For example, Pillow's JPEG save function supports",
"name or file-like-object. dtype : numpy dtype object or string",
"frames.append(frame) i += 1 if img_num is not None: break",
"not in (2, 3): raise ValueError(\"Invalid shape for image array:",
"= arr.astype(np.uint8) mode = mode_base = 'L' else: arr =",
"---------- fname : str or file File name or file-like-object.",
")) if arr.ndim == 3: if arr.shape[2] not in (3,",
"is None: grayscale = _palette_is_grayscale(image) if grayscale: frame = image.convert('L')",
"'raw', mode) except AttributeError: im.fromstring(array_buffer, 'raw', mode) # PIL 1.1.7",
"Image is grayscale if channel differences (R - G and",
"optional Addition keyword arguments to pass through. Notes ----- Files",
"and Boolean types -> img_as_uint8 - Floating point and other",
"grayscale: frame = image.convert('L') else: if image.format == 'PNG' and",
"are all zero. return np.allclose(np.diff(valid_palette), 0) def ndarray_to_pil(arr, format_str=None): \"\"\"Export",
"Image.frombytes(mode, image_shape, array_buffer) except AttributeError: im = Image.fromstring(mode, image_shape, array_buffer)",
"image.getdata()[0] except IOError as e: site = \"http://pillow.readthedocs.org/en/latest/installation.html#external-libraries\" pillow_error_message =",
"[1] http://pillow.readthedocs.org/en/latest/handbook/image-file-formats.html \"\"\" # default to PNG if file-like object",
": ndarray of uint8 or float Array (image) to save.",
"Parameters ---------- pil_image : PIL image PIL Image that is",
"and len(frames) > 1: return np.array(frames) elif frames: return frames[0]",
"in image.info: frame = image.convert('RGBA') else: frame = image.convert('RGB') elif",
"elif img_num: raise IndexError('Could not find image #%s' % img_num)",
"else: frame = np.array(frame, dtype=dtype) frames.append(frame) i += 1 if",
"img_as_uint def imread(fname, dtype=None, img_num=None, **kwargs): \"\"\"Load an image from",
"format_str=None): \"\"\"Export an ndarray to a PIL object. Parameters ----------",
"Name of destination file. arr : ndarray of uint8 or",
": PIL image PIL Image that is in Palette mode.",
"dtype is None: dtype = 'uint16' if image.mode == 'P':",
"find image #%s' % img_num) def _palette_is_grayscale(pil_image): \"\"\"Return True if",
"of supported formats. References ---------- .. [1] http://pillow.readthedocs.org/en/latest/handbook/image-file-formats.html \"\"\" if",
"integer argument with values in [0, 9]. Notes ----- Use",
"== 3: if arr.shape[2] not in (3, 4): raise ValueError(\"Invalid",
"channels in image array.\") img = ndarray_to_pil(arr, format_str=format_str) img.save(fname, format=format_str,",
"image.mode: frame = image.convert('RGBA') elif image.mode == 'CMYK': frame =",
"= [] grayscale = None i = 0 while 1:",
"img_num is not None: break if hasattr(image, 'fp') and image.fp:",
"array: %s\" % (arr.shape, )) if arr.ndim == 3: if",
"with R, G, B columns palette = np.asarray(pil_image.getpalette()).reshape((256, 3)) #",
"See PIL docs [1]_ for a list of supported formats.",
"ValueError(error_message) frames = [] grayscale = None i = 0",
"'fp') and image.fp: image.fp.close() if img_num is None and len(frames)",
"with values in [1, 95], while TIFFFile supports a ``compress``",
"# Check for png in filename if (isinstance(fname, str) and",
"in filename if (isinstance(fname, str) and fname.lower().endswith(\".png\")): format_str = \"PNG\"",
"'L' try: array_buffer = arr.tobytes() except AttributeError: array_buffer = arr.tostring()",
"tifffile save function, for Tiff files). These are format dependent.",
"\"PNG\" # Check for png in filename if (isinstance(fname, str)",
"png in filename if (isinstance(fname, str) and fname.lower().endswith(\".png\")): format_str =",
"\"\"\" if isinstance(fname, str): with open(fname, 'rb') as f: im",
"palette as an array with R, G, B columns palette",
"extension if fname is a string kwargs: dict Keyword arguments",
">= 0: arr = arr.astype(np.uint8) mode = mode_base = 'L'",
"PNG if file-like object if not isinstance(fname, str) and format_str",
"to the Pillow save function (or tifffile save function, for",
"return pil_to_ndarray(im, dtype=dtype, img_num=img_num) else: im = Image.open(fname) return pil_to_ndarray(im,",
"format_str=None, **kwargs): \"\"\"Save an image to disk. Parameters ---------- fname",
"continue if image.format == 'PNG' and image.mode == 'I' and",
"1.9 if arr.ndim == 2: im = Image.new(mode_base, arr.T.shape) try:",
"PIL docs [1]_ for a list of other supported formats.",
"else: image_shape = (arr.shape[1], arr.shape[0]) try: im = Image.frombytes(mode, image_shape,",
"PIL 1.1.7 return im def imsave(fname, arr, format_str=None, **kwargs): \"\"\"Save",
"in [0, 1]. format_str: str Format to save as, this",
"http://pillow.readthedocs.org/en/latest/handbook/image-file-formats.html \"\"\" if isinstance(fname, str): with open(fname, 'rb') as f:",
"not None and img_num != i: image.getdata()[0] i += 1",
"= {3: 'RGB', 4: 'RGBA'}[arr.shape[2]] elif format_str in ['png', 'PNG']:",
"to save. Arrays of data-type uint8 should have values in",
"---------- Refer to ``imread``. \"\"\" try: # this will raise",
"dtype object or string specifier Specifies data type of array",
"\"\"\" # default to PNG if file-like object if not",
"except IOError as e: site = \"http://pillow.readthedocs.org/en/latest/installation.html#external-libraries\" pillow_error_message = str(e)",
"save function, for Tiff files). These are format dependent. For",
"image.mode == 'I' and dtype is None: dtype = 'uint16'",
"grayscale = _palette_is_grayscale(image) if grayscale: frame = image.convert('L') else: if",
"_palette_is_grayscale(pil_image): \"\"\"Return True if PIL image in palette mode is",
"multiple images (zero-indexed). kwargs : keyword pairs, optional Addition keyword",
"Files are read using the Python Imaging Library. See PIL",
"columns palette = np.asarray(pil_image.getpalette()).reshape((256, 3)) # Not all palette colors",
"integer ``quality`` argument with values in [1, 95], while TIFFFile",
"- Floating point and other integers -> img_as_uint16 References ----------",
"= None i = 0 while 1: try: image.seek(i) except",
"arr.dtype.kind == 'b': arr = arr.astype(np.uint8) if arr.ndim not in",
"to PNG if using a file-like object; this will be",
"dtype : numpy dtype object or string specifier Specifies data",
"save as, this is defaulted to PNG if using a",
"numpy as np from PIL import Image from ...util import",
"in [0, 255] and Boolean types -> img_as_uint8 - Floating",
"if grayscale: frame = image.convert('L') else: if image.format == 'PNG'",
"1: try: image.seek(i) except EOFError: break frame = image if",
"str(e) error_message = ('Could not load \"%s\" \\n' 'Reason: \"%s\"\\n'",
"IOError if the file is not readable image.getdata()[0] except IOError",
"documentation at: %s' % (image.filename, pillow_error_message, site)) raise ValueError(error_message) frames",
"are used; unused colors have junk values. start, stop =",
": str or file-like object Name of destination file. arr",
"files). These are format dependent. For example, Pillow's JPEG save",
"fname : str or file-like object Name of destination file.",
"= image.convert('L') elif 'A' in image.mode: frame = image.convert('RGBA') elif",
"{3: 'RGB', 4: 'RGBA'}[arr.shape[2]] elif format_str in ['png', 'PNG']: mode",
"Keyword arguments to the Pillow save function (or tifffile save",
"im.fromstring(array_buffer, 'raw', mode) # PIL 1.1.7 else: image_shape = (arr.shape[1],",
"single channel PNGs are converted using `img_as_uint8`. Single Channel PNGs",
"palette are gray. \"\"\" assert pil_image.mode == 'P' # get",
"\"\"\"Save an image to disk. Parameters ---------- fname : str",
"dtype = 'uint16' if image.mode == 'P': if grayscale is",
"from file. Parameters ---------- fname : str or file File",
"image.mode == 'CMYK': frame = image.convert('RGB') if image.mode.startswith('I;16'): shape =",
"file-like object Name of destination file. arr : ndarray of",
"\"\"\"Export an ndarray to a PIL object. Parameters ---------- Refer",
"from PIL import Image from ...util import img_as_ubyte, img_as_uint def",
"have the following behavior: - Integer values in [0, 255]",
"frame = image if img_num is not None and img_num",
"image.mode.startswith('I;16'): shape = image.size dtype = '>u2' if image.mode.endswith('B') else",
"im = Image.fromstring(mode, image_shape, array_buffer) # PIL 1.1.7 return im",
"defaulted to PNG if using a file-like object; this will",
"'PNG']: mode = 'I;16' mode_base = 'I' if arr.dtype.kind ==",
"if grayscale is None: grayscale = _palette_is_grayscale(image) if grayscale: frame",
"except AttributeError: im = Image.fromstring(mode, image_shape, array_buffer) # PIL 1.1.7",
"Notes ----- Files are read using the Python Imaging Library.",
"to an ndarray, in memory. Parameters ---------- Refer to ``imread``.",
"B) # are all zero. return np.allclose(np.diff(valid_palette), 0) def ndarray_to_pil(arr,",
"'>u2' if image.mode.endswith('B') else '<u2' if 'S' in image.mode: dtype",
"== 2: im = Image.new(mode_base, arr.T.shape) try: im.frombytes(array_buffer, 'raw', mode)",
"def _palette_is_grayscale(pil_image): \"\"\"Return True if PIL image in palette mode",
"References ---------- .. [1] http://pillow.readthedocs.org/en/latest/handbook/image-file-formats.html \"\"\" if isinstance(fname, str): with",
"= palette[start:stop + 1] # Image is grayscale if channel",
"arr = img_as_ubyte(arr) mode = {3: 'RGB', 4: 'RGBA'}[arr.shape[2]] elif",
"G, B columns palette = np.asarray(pil_image.getpalette()).reshape((256, 3)) # Not all",
"this is defaulted to PNG if using a file-like object;",
"%s\" % (arr.shape, )) if arr.ndim == 3: if arr.shape[2]",
"= \"http://pillow.readthedocs.org/en/latest/installation.html#external-libraries\" pillow_error_message = str(e) error_message = ('Could not load",
"file-like object; this will be derived from the extension if",
"image.convert('RGBA') else: frame = image.convert('RGB') elif image.mode == '1': frame",
"is not None and img_num != i: image.getdata()[0] i +=",
"dtype=dtype, img_num=img_num) def pil_to_ndarray(image, dtype=None, img_num=None): \"\"\"Import a PIL Image",
"'<u2' if 'S' in image.mode: dtype = dtype.replace('u', 'i') frame",
"PIL image PIL Image that is in Palette mode. Returns",
"img_as_uint8 - Floating point and other integers -> img_as_uint16 References",
"see documentation at: %s' % (image.filename, pillow_error_message, site)) raise ValueError(error_message)",
"= np.asarray(pil_image.getpalette()).reshape((256, 3)) # Not all palette colors are used;",
"Library. See PIL docs [1]_ for a list of supported",
"image_shape, array_buffer) # PIL 1.1.7 return im def imsave(fname, arr,",
"image.convert('RGB') elif image.mode == '1': frame = image.convert('L') elif 'A'",
".. [1] http://pillow.readthedocs.org/en/latest/handbook/image-file-formats.html \"\"\" if isinstance(fname, str): with open(fname, 'rb')",
"is grayscale. Parameters ---------- pil_image : PIL image PIL Image",
"must be in [0, 1]. format_str: str Format to save",
"raise an IOError if the file is not readable image.getdata()[0]",
"error_message = ('Could not load \"%s\" \\n' 'Reason: \"%s\"\\n' 'Please",
"colors have junk values. start, stop = pil_image.getextrema() valid_palette =",
"[1, 95], while TIFFFile supports a ``compress`` integer argument with",
"'RGB', 4: 'RGBA'}[arr.shape[2]] elif format_str in ['png', 'PNG']: mode =",
"pil_to_ndarray(image, dtype=None, img_num=None): \"\"\"Import a PIL Image object to an",
"frames[0] elif img_num: raise IndexError('Could not find image #%s' %",
"= Image.frombytes(mode, image_shape, array_buffer) except AttributeError: im = Image.fromstring(mode, image_shape,",
"in image palette are gray. \"\"\" assert pil_image.mode == 'P'",
"is a string kwargs: dict Keyword arguments to the Pillow",
"a string kwargs: dict Keyword arguments to the Pillow save",
"def imread(fname, dtype=None, img_num=None, **kwargs): \"\"\"Load an image from file.",
"frame = image.convert('RGB') elif image.mode == '1': frame = image.convert('L')",
"arr = img_as_uint(arr) elif arr.max() < 256 and arr.min() >=",
"pillow_error_message, site)) raise ValueError(error_message) frames = [] grayscale = None",
"mode_base = 'L' try: array_buffer = arr.tobytes() except AttributeError: array_buffer",
"Channel PNGs have the following behavior: - Integer values in",
"of other supported formats. All images besides single channel PNGs",
"Imaging Library. See PIL docs [1]_ for a list of",
"if img_num is not None and img_num != i: image.getdata()[0]",
"dict Keyword arguments to the Pillow save function (or tifffile",
"= str(e) error_message = ('Could not load \"%s\" \\n' 'Reason:",
"mode = 'L' mode_base = 'L' try: array_buffer = arr.tobytes()",
"= 'I;16' mode_base = 'I' if arr.dtype.kind == 'f': arr",
"fname is a string kwargs: dict Keyword arguments to the",
"(or tifffile save function, for Tiff files). These are format",
"in image.mode: dtype = dtype.replace('u', 'i') frame = np.fromstring(frame.tobytes(), dtype)",
"image.getdata()[0] i += 1 continue if image.format == 'PNG' and",
"for a list of supported formats. References ---------- .. [1]",
"frame = np.array(frame, dtype=dtype) frames.append(frame) i += 1 if img_num",
"save. Arrays of data-type uint8 should have values in [0,",
"all palette colors are used; unused colors have junk values.",
"# Numpy < 1.9 if arr.ndim == 2: im =",
"mode) except AttributeError: im.fromstring(array_buffer, 'raw', mode) # PIL 1.1.7 else:",
"disk. Parameters ---------- fname : str or file-like object Name",
"True if PIL image in palette mode is grayscale. Parameters",
"\"\"\"Return True if PIL image in palette mode is grayscale.",
"ValueError(\"Invalid shape for image array: %s\" % (arr.shape, )) if",
"palette mode is grayscale. Parameters ---------- pil_image : PIL image",
"['png', 'PNG']: mode = 'I;16' mode_base = 'I' if arr.dtype.kind",
"mode_base = 'L' else: arr = img_as_uint(arr) else: arr =",
"img_num=None, **kwargs): \"\"\"Load an image from file. Parameters ---------- fname",
"is in Palette mode. Returns ------- is_grayscale : bool True",
"format_str is None: format_str = \"PNG\" # Check for png",
"'I' if arr.dtype.kind == 'f': arr = img_as_uint(arr) elif arr.max()",
"= ('Could not load \"%s\" \\n' 'Reason: \"%s\"\\n' 'Please see",
"types -> img_as_uint8 - Floating point and other integers ->",
"grayscale if channel differences (R - G and G -",
"`img_as_uint8`. Single Channel PNGs have the following behavior: - Integer",
"# PIL 1.1.7 else: image_shape = (arr.shape[1], arr.shape[0]) try: im",
"'i') frame = np.fromstring(frame.tobytes(), dtype) frame.shape = shape[::-1] else: frame",
"+ 1] # Image is grayscale if channel differences (R",
"img_num=img_num) def pil_to_ndarray(image, dtype=None, img_num=None): \"\"\"Import a PIL Image object",
"'I;16' mode_base = 'I' if arr.dtype.kind == 'f': arr =",
"palette colors are used; unused colors have junk values. start,",
"None: dtype = 'uint16' if image.mode == 'P': if grayscale",
"function supports an integer ``quality`` argument with values in [1,",
"file-like-object. dtype : numpy dtype object or string specifier Specifies",
"'transparency' in image.info: frame = image.convert('RGBA') else: frame = image.convert('RGB')",
"- B) # are all zero. return np.allclose(np.diff(valid_palette), 0) def",
"img_num=img_num) else: im = Image.open(fname) return pil_to_ndarray(im, dtype=dtype, img_num=img_num) def",
"ndarray of uint8 or float Array (image) to save. Arrays",
"other integers -> img_as_uint16 References ---------- .. [1] http://pillow.readthedocs.org/en/latest/handbook/image-file-formats.html \"\"\"",
"else: arr = img_as_ubyte(arr) mode = 'L' mode_base = 'L'",
"1: return np.array(frames) elif frames: return frames[0] elif img_num: raise",
"\"\"\" assert pil_image.mode == 'P' # get palette as an",
"np.asarray(pil_image.getpalette()).reshape((256, 3)) # Not all palette colors are used; unused",
"dtype) frame.shape = shape[::-1] else: frame = np.array(frame, dtype=dtype) frames.append(frame)",
"2: im = Image.new(mode_base, arr.T.shape) try: im.frombytes(array_buffer, 'raw', mode) except",
"pillow_error_message = str(e) error_message = ('Could not load \"%s\" \\n'",
"colors in image palette are gray. \"\"\" assert pil_image.mode ==",
"as an array with R, G, B columns palette =",
"Image object to an ndarray, in memory. Parameters ---------- Refer",
"im = Image.frombytes(mode, image_shape, array_buffer) except AttributeError: im = Image.fromstring(mode,",
"def imsave(fname, arr, format_str=None, **kwargs): \"\"\"Save an image to disk.",
"return pil_to_ndarray(im, dtype=dtype, img_num=img_num) def pil_to_ndarray(image, dtype=None, img_num=None): \"\"\"Import a",
"file-like object if not isinstance(fname, str) and format_str is None:",
"of channels in image array.\") img = ndarray_to_pil(arr, format_str=format_str) img.save(fname,",
"== 'f': arr = img_as_uint(arr) elif arr.max() < 256 and",
"else: frame = image.convert('RGB') elif image.mode == '1': frame =",
"stop = pil_image.getextrema() valid_palette = palette[start:stop + 1] # Image",
"to save as, this is defaulted to PNG if using",
"i += 1 continue if image.format == 'PNG' and image.mode",
"frame = image.convert('RGB') if image.mode.startswith('I;16'): shape = image.size dtype =",
"Image.new(mode_base, arr.T.shape) try: im.frombytes(array_buffer, 'raw', mode) except AttributeError: im.fromstring(array_buffer, 'raw',",
"for Tiff files). These are format dependent. For example, Pillow's",
"is defaulted to PNG if using a file-like object; this",
"zero. return np.allclose(np.diff(valid_palette), 0) def ndarray_to_pil(arr, format_str=None): \"\"\"Export an ndarray",
"arr.tostring() # Numpy < 1.9 if arr.ndim == 2: im",
"Image from ...util import img_as_ubyte, img_as_uint def imread(fname, dtype=None, img_num=None,",
"if image.mode.endswith('B') else '<u2' if 'S' in image.mode: dtype =",
"\"\"\" if arr.ndim == 3: arr = img_as_ubyte(arr) mode =",
"Format to save as, this is defaulted to PNG if",
"3: if arr.shape[2] not in (3, 4): raise ValueError(\"Invalid number",
"arr = np.asanyarray(arr) if arr.dtype.kind == 'b': arr = arr.astype(np.uint8)",
"image.format == 'PNG' and 'transparency' in image.info: frame = image.convert('RGBA')",
"or file-like-object. dtype : numpy dtype object or string specifier",
"file. arr : ndarray of uint8 or float Array (image)",
"[1]_ for a list of supported formats. References ---------- ..",
"elif 'A' in image.mode: frame = image.convert('RGBA') elif image.mode ==",
"---------- fname : str or file-like object Name of destination",
"fname : str or file File name or file-like-object. dtype",
"PIL import Image from ...util import img_as_ubyte, img_as_uint def imread(fname,",
"arr.ndim == 3: if arr.shape[2] not in (3, 4): raise",
"not readable image.getdata()[0] except IOError as e: site = \"http://pillow.readthedocs.org/en/latest/installation.html#external-libraries\"",
"with multiple images (zero-indexed). kwargs : keyword pairs, optional Addition",
"and format_str is None: format_str = \"PNG\" # Check for",
"= 'uint16' if image.mode == 'P': if grayscale is None:",
"function (or tifffile save function, for Tiff files). These are",
"image.size dtype = '>u2' if image.mode.endswith('B') else '<u2' if 'S'",
"image to disk. Parameters ---------- fname : str or file-like",
"except EOFError: break frame = image if img_num is not",
"PIL image in palette mode is grayscale. Parameters ---------- pil_image",
"Python Imaging Library. See PIL docs [1]_ for a list",
"'L' else: arr = img_as_uint(arr) else: arr = img_as_ubyte(arr) mode",
"255], whereas floating-point arrays must be in [0, 1]. format_str:",
"and img_num != i: image.getdata()[0] i += 1 continue if",
"assert pil_image.mode == 'P' # get palette as an array",
"\"\"\"Import a PIL Image object to an ndarray, in memory.",
"in [0, 9]. Notes ----- Use the Python Imaging Library.",
"start, stop = pil_image.getextrema() valid_palette = palette[start:stop + 1] #",
"junk values. start, stop = pil_image.getextrema() valid_palette = palette[start:stop +",
"255] and Boolean types -> img_as_uint8 - Floating point and",
"image from file. Parameters ---------- fname : str or file",
"= \"PNG\" arr = np.asanyarray(arr) if arr.dtype.kind == 'b': arr",
"file File name or file-like-object. dtype : numpy dtype object",
"= (arr.shape[1], arr.shape[0]) try: im = Image.frombytes(mode, image_shape, array_buffer) except",
"frames = [] grayscale = None i = 0 while",
"np.allclose(np.diff(valid_palette), 0) def ndarray_to_pil(arr, format_str=None): \"\"\"Export an ndarray to a",
"a list of other supported formats. All images besides single",
"integers -> img_as_uint16 References ---------- .. [1] http://pillow.readthedocs.org/en/latest/handbook/image-file-formats.html \"\"\" #",
"Specifies which image to read in a file with multiple",
"raise IndexError('Could not find image #%s' % img_num) def _palette_is_grayscale(pil_image):",
"channel PNGs are converted using `img_as_uint8`. Single Channel PNGs have",
"arr.ndim not in (2, 3): raise ValueError(\"Invalid shape for image",
"'raw', mode) # PIL 1.1.7 else: image_shape = (arr.shape[1], arr.shape[0])",
"arr.astype(np.uint8) if arr.ndim not in (2, 3): raise ValueError(\"Invalid shape",
"pil_to_ndarray(im, dtype=dtype, img_num=img_num) def pil_to_ndarray(image, dtype=None, img_num=None): \"\"\"Import a PIL",
"= Image.fromstring(mode, image_shape, array_buffer) # PIL 1.1.7 return im def",
"str or file File name or file-like-object. dtype : numpy",
"= pil_image.getextrema() valid_palette = palette[start:stop + 1] # Image is",
"example, Pillow's JPEG save function supports an integer ``quality`` argument",
"raise ValueError(\"Invalid number of channels in image array.\") img =",
"'A' in image.mode: frame = image.convert('RGBA') elif image.mode == 'CMYK':",
"is not readable image.getdata()[0] except IOError as e: site =",
"None i = 0 while 1: try: image.seek(i) except EOFError:",
"= mode_base = 'L' else: arr = img_as_uint(arr) else: arr",
"function, for Tiff files). These are format dependent. For example,",
"frame = image.convert('RGBA') else: frame = image.convert('RGB') elif image.mode ==",
"supported formats. References ---------- .. [1] http://pillow.readthedocs.org/en/latest/handbook/image-file-formats.html \"\"\" if isinstance(fname,",
"= np.fromstring(frame.tobytes(), dtype) frame.shape = shape[::-1] else: frame = np.array(frame,",
"pil_image : PIL image PIL Image that is in Palette",
"and other integers -> img_as_uint16 References ---------- .. [1] http://pillow.readthedocs.org/en/latest/handbook/image-file-formats.html",
"im = Image.open(f) return pil_to_ndarray(im, dtype=dtype, img_num=img_num) else: im =",
"object if not isinstance(fname, str) and format_str is None: format_str",
"Parameters ---------- Refer to ``imsave``. \"\"\" if arr.ndim == 3:",
"format dependent. For example, Pillow's JPEG save function supports an",
"to disk. Parameters ---------- fname : str or file-like object",
"TIFFFile supports a ``compress`` integer argument with values in [0,",
"Parameters ---------- fname : str or file-like object Name of",
"float Array (image) to save. Arrays of data-type uint8 should",
"EOFError: break frame = image if img_num is not None",
"def pil_to_ndarray(image, dtype=None, img_num=None): \"\"\"Import a PIL Image object to",
"str) and format_str is None: format_str = \"PNG\" # Check",
"an image from file. Parameters ---------- fname : str or",
"['imread', 'imsave'] import numpy as np from PIL import Image",
"``imread``. \"\"\" try: # this will raise an IOError if",
"pass through. Notes ----- Files are read using the Python",
"arr = img_as_uint(arr) else: arr = img_as_ubyte(arr) mode = 'L'",
"Image.open(fname) return pil_to_ndarray(im, dtype=dtype, img_num=img_num) def pil_to_ndarray(image, dtype=None, img_num=None): \"\"\"Import",
"``imsave``. \"\"\" if arr.ndim == 3: arr = img_as_ubyte(arr) mode",
"Boolean types -> img_as_uint8 - Floating point and other integers",
"[1] http://pillow.readthedocs.org/en/latest/handbook/image-file-formats.html \"\"\" if isinstance(fname, str): with open(fname, 'rb') as",
"elif image.mode == '1': frame = image.convert('L') elif 'A' in",
"shape = image.size dtype = '>u2' if image.mode.endswith('B') else '<u2'",
"else: if image.format == 'PNG' and 'transparency' in image.info: frame",
"i: image.getdata()[0] i += 1 continue if image.format == 'PNG'",
"imsave(fname, arr, format_str=None, **kwargs): \"\"\"Save an image to disk. Parameters",
"else: arr = img_as_uint(arr) else: arr = img_as_ubyte(arr) mode =",
"B columns palette = np.asarray(pil_image.getpalette()).reshape((256, 3)) # Not all palette",
"this will be derived from the extension if fname is",
"G - B) # are all zero. return np.allclose(np.diff(valid_palette), 0)",
"image.fp.close() if img_num is None and len(frames) > 1: return",
"break if hasattr(image, 'fp') and image.fp: image.fp.close() if img_num is",
"== 'PNG' and image.mode == 'I' and dtype is None:",
"= dtype.replace('u', 'i') frame = np.fromstring(frame.tobytes(), dtype) frame.shape = shape[::-1]",
"4: 'RGBA'}[arr.shape[2]] elif format_str in ['png', 'PNG']: mode = 'I;16'",
"ndarray to a PIL object. Parameters ---------- Refer to ``imsave``.",
"arr.min() >= 0: arr = arr.astype(np.uint8) mode = mode_base =",
"pil_image.getextrema() valid_palette = palette[start:stop + 1] # Image is grayscale",
"\"%s\"\\n' 'Please see documentation at: %s' % (image.filename, pillow_error_message, site))",
"have junk values. start, stop = pil_image.getextrema() valid_palette = palette[start:stop",
"'Reason: \"%s\"\\n' 'Please see documentation at: %s' % (image.filename, pillow_error_message,",
"or file-like object Name of destination file. arr : ndarray",
"point and other integers -> img_as_uint16 References ---------- .. [1]",
"These are format dependent. For example, Pillow's JPEG save function",
"file with multiple images (zero-indexed). kwargs : keyword pairs, optional",
"G and G - B) # are all zero. return",
"arrays must be in [0, 1]. format_str: str Format to",
"return im def imsave(fname, arr, format_str=None, **kwargs): \"\"\"Save an image",
"img_num is None and len(frames) > 1: return np.array(frames) elif",
"\"\"\" try: # this will raise an IOError if the",
"images besides single channel PNGs are converted using `img_as_uint8`. Single",
"http://pillow.readthedocs.org/en/latest/handbook/image-file-formats.html \"\"\" # default to PNG if file-like object if",
"the Python Imaging Library. See PIL docs [1]_ for a",
"file. Parameters ---------- fname : str or file File name",
"if arr.ndim == 3: if arr.shape[2] not in (3, 4):",
"str or file-like object Name of destination file. arr :",
"using a file-like object; this will be derived from the",
"np.fromstring(frame.tobytes(), dtype) frame.shape = shape[::-1] else: frame = np.array(frame, dtype=dtype)",
"For example, Pillow's JPEG save function supports an integer ``quality``",
"(3, 4): raise ValueError(\"Invalid number of channels in image array.\")",
"as np from PIL import Image from ...util import img_as_ubyte,",
"'rb') as f: im = Image.open(f) return pil_to_ndarray(im, dtype=dtype, img_num=img_num)",
"if the file is not readable image.getdata()[0] except IOError as",
"imread(fname, dtype=None, img_num=None, **kwargs): \"\"\"Load an image from file. Parameters",
"None: break if hasattr(image, 'fp') and image.fp: image.fp.close() if img_num",
"1]. format_str: str Format to save as, this is defaulted",
"while TIFFFile supports a ``compress`` integer argument with values in",
"object. Parameters ---------- Refer to ``imsave``. \"\"\" if arr.ndim ==",
"img_num: raise IndexError('Could not find image #%s' % img_num) def",
"= np.array(frame, dtype=dtype) frames.append(frame) i += 1 if img_num is",
"File name or file-like-object. dtype : numpy dtype object or",
"and image.fp: image.fp.close() if img_num is None and len(frames) >",
"gray. \"\"\" assert pil_image.mode == 'P' # get palette as",
"image.convert('L') else: if image.format == 'PNG' and 'transparency' in image.info:",
"keyword arguments to pass through. Notes ----- Files are read",
"if hasattr(image, 'fp') and image.fp: image.fp.close() if img_num is None",
"Image.open(f) return pil_to_ndarray(im, dtype=dtype, img_num=img_num) else: im = Image.open(fname) return",
"array elements. img_num : int, optional Specifies which image to",
"arr.astype(np.uint8) mode = mode_base = 'L' else: arr = img_as_uint(arr)",
"ndarray, in memory. Parameters ---------- Refer to ``imread``. \"\"\" try:",
"= image if img_num is not None and img_num !=",
"256 and arr.min() >= 0: arr = arr.astype(np.uint8) mode =",
"None: format_str = \"PNG\" # Check for png in filename",
"Image.fromstring(mode, image_shape, array_buffer) # PIL 1.1.7 return im def imsave(fname,",
"R, G, B columns palette = np.asarray(pil_image.getpalette()).reshape((256, 3)) # Not",
"dependent. For example, Pillow's JPEG save function supports an integer",
"dtype=None, img_num=None, **kwargs): \"\"\"Load an image from file. Parameters ----------",
"valid_palette = palette[start:stop + 1] # Image is grayscale if",
"arr : ndarray of uint8 or float Array (image) to",
"0 while 1: try: image.seek(i) except EOFError: break frame =",
"in image array.\") img = ndarray_to_pil(arr, format_str=format_str) img.save(fname, format=format_str, **kwargs)",
"for a list of other supported formats. All images besides",
"Refer to ``imread``. \"\"\" try: # this will raise an",
"'uint16' if image.mode == 'P': if grayscale is None: grayscale",
"save function (or tifffile save function, for Tiff files). These",
"0) def ndarray_to_pil(arr, format_str=None): \"\"\"Export an ndarray to a PIL",
"True if all colors in image palette are gray. \"\"\"",
"'RGBA'}[arr.shape[2]] elif format_str in ['png', 'PNG']: mode = 'I;16' mode_base",
"= img_as_uint(arr) else: arr = img_as_ubyte(arr) mode = 'L' mode_base",
"PIL 1.1.7 else: image_shape = (arr.shape[1], arr.shape[0]) try: im =",
"+= 1 if img_num is not None: break if hasattr(image,",
"None and len(frames) > 1: return np.array(frames) elif frames: return",
"elements. img_num : int, optional Specifies which image to read",
"an ndarray to a PIL object. Parameters ---------- Refer to",
"AttributeError: array_buffer = arr.tostring() # Numpy < 1.9 if arr.ndim",
"data type of array elements. img_num : int, optional Specifies",
"img_as_uint16 References ---------- .. [1] http://pillow.readthedocs.org/en/latest/handbook/image-file-formats.html \"\"\" # default to",
"[0, 255] and Boolean types -> img_as_uint8 - Floating point",
"arguments to pass through. Notes ----- Files are read using",
"< 256 and arr.min() >= 0: arr = arr.astype(np.uint8) mode",
"PNGs have the following behavior: - Integer values in [0,",
"Parameters ---------- fname : str or file File name or",
"an image to disk. Parameters ---------- fname : str or",
"(image.filename, pillow_error_message, site)) raise ValueError(error_message) frames = [] grayscale =",
"Pillow's JPEG save function supports an integer ``quality`` argument with",
"# default to PNG if file-like object if not isinstance(fname,",
"if arr.ndim == 3: arr = img_as_ubyte(arr) mode = {3:",
"and fname.lower().endswith(\".png\")): format_str = \"PNG\" arr = np.asanyarray(arr) if arr.dtype.kind",
"img_num != i: image.getdata()[0] i += 1 continue if image.format",
"== 'P': if grayscale is None: grayscale = _palette_is_grayscale(image) if",
"kwargs : keyword pairs, optional Addition keyword arguments to pass",
"if image.format == 'PNG' and image.mode == 'I' and dtype",
"else: im = Image.open(fname) return pil_to_ndarray(im, dtype=dtype, img_num=img_num) def pil_to_ndarray(image,",
"== '1': frame = image.convert('L') elif 'A' in image.mode: frame",
"at: %s' % (image.filename, pillow_error_message, site)) raise ValueError(error_message) frames =",
"colors are used; unused colors have junk values. start, stop",
"try: # this will raise an IOError if the file",
"numpy dtype object or string specifier Specifies data type of",
"shape for image array: %s\" % (arr.shape, )) if arr.ndim",
"= image.convert('RGBA') else: frame = image.convert('RGB') elif image.mode == '1':",
"unused colors have junk values. start, stop = pil_image.getextrema() valid_palette",
"kwargs: dict Keyword arguments to the Pillow save function (or",
"image PIL Image that is in Palette mode. Returns -------",
"behavior: - Integer values in [0, 255] and Boolean types",
"mode = {3: 'RGB', 4: 'RGBA'}[arr.shape[2]] elif format_str in ['png',",
"dtype=None, img_num=None): \"\"\"Import a PIL Image object to an ndarray,",
"if img_num is None and len(frames) > 1: return np.array(frames)",
"of destination file. arr : ndarray of uint8 or float",
"1.1.7 return im def imsave(fname, arr, format_str=None, **kwargs): \"\"\"Save an",
"if channel differences (R - G and G - B)",
"# PIL 1.1.7 return im def imsave(fname, arr, format_str=None, **kwargs):",
"besides single channel PNGs are converted using `img_as_uint8`. Single Channel",
"values. start, stop = pil_image.getextrema() valid_palette = palette[start:stop + 1]",
"converted using `img_as_uint8`. Single Channel PNGs have the following behavior:",
"= 'L' try: array_buffer = arr.tobytes() except AttributeError: array_buffer =",
"%s' % (image.filename, pillow_error_message, site)) raise ValueError(error_message) frames = []",
"PIL Image object to an ndarray, in memory. Parameters ----------",
"- G and G - B) # are all zero.",
"for image array: %s\" % (arr.shape, )) if arr.ndim ==",
"shape[::-1] else: frame = np.array(frame, dtype=dtype) frames.append(frame) i += 1",
"+= 1 continue if image.format == 'PNG' and image.mode ==",
"with open(fname, 'rb') as f: im = Image.open(f) return pil_to_ndarray(im,",
"string kwargs: dict Keyword arguments to the Pillow save function",
"= Image.open(fname) return pil_to_ndarray(im, dtype=dtype, img_num=img_num) def pil_to_ndarray(image, dtype=None, img_num=None):",
"which image to read in a file with multiple images",
"raise ValueError(error_message) frames = [] grayscale = None i =",
"frame = np.fromstring(frame.tobytes(), dtype) frame.shape = shape[::-1] else: frame =",
"following behavior: - Integer values in [0, 255] and Boolean",
"image.fp: image.fp.close() if img_num is None and len(frames) > 1:",
"and arr.min() >= 0: arr = arr.astype(np.uint8) mode = mode_base",
"mode = 'I;16' mode_base = 'I' if arr.dtype.kind == 'f':",
"def ndarray_to_pil(arr, format_str=None): \"\"\"Export an ndarray to a PIL object.",
"'L' mode_base = 'L' try: array_buffer = arr.tobytes() except AttributeError:",
"in [1, 95], while TIFFFile supports a ``compress`` integer argument",
"format_str = \"PNG\" # Check for png in filename if",
"or string specifier Specifies data type of array elements. img_num",
"frame = image.convert('L') else: if image.format == 'PNG' and 'transparency'",
"as e: site = \"http://pillow.readthedocs.org/en/latest/installation.html#external-libraries\" pillow_error_message = str(e) error_message =",
"img_as_ubyte(arr) mode = 'L' mode_base = 'L' try: array_buffer =",
"= arr.tostring() # Numpy < 1.9 if arr.ndim == 2:",
"default to PNG if file-like object if not isinstance(fname, str)",
"Notes ----- Use the Python Imaging Library. See PIL docs",
"frame = image.convert('L') elif 'A' in image.mode: frame = image.convert('RGBA')",
"im = Image.new(mode_base, arr.T.shape) try: im.frombytes(array_buffer, 'raw', mode) except AttributeError:",
"Not all palette colors are used; unused colors have junk",
"f: im = Image.open(f) return pil_to_ndarray(im, dtype=dtype, img_num=img_num) else: im",
"format_str in ['png', 'PNG']: mode = 'I;16' mode_base = 'I'",
"try: im.frombytes(array_buffer, 'raw', mode) except AttributeError: im.fromstring(array_buffer, 'raw', mode) #",
"= 'L' else: arr = img_as_uint(arr) else: arr = img_as_ubyte(arr)",
"read using the Python Imaging Library. See PIL docs [1]_",
"from ...util import img_as_ubyte, img_as_uint def imread(fname, dtype=None, img_num=None, **kwargs):",
"(image) to save. Arrays of data-type uint8 should have values",
": str or file File name or file-like-object. dtype :",
"arr.dtype.kind == 'f': arr = img_as_uint(arr) elif arr.max() < 256",
"image_shape = (arr.shape[1], arr.shape[0]) try: im = Image.frombytes(mode, image_shape, array_buffer)",
"object to an ndarray, in memory. Parameters ---------- Refer to",
"Addition keyword arguments to pass through. Notes ----- Files are",
"arr.T.shape) try: im.frombytes(array_buffer, 'raw', mode) except AttributeError: im.fromstring(array_buffer, 'raw', mode)",
"------- is_grayscale : bool True if all colors in image",
"if image.format == 'PNG' and 'transparency' in image.info: frame =",
"load \"%s\" \\n' 'Reason: \"%s\"\\n' 'Please see documentation at: %s'",
"in (2, 3): raise ValueError(\"Invalid shape for image array: %s\"",
": numpy dtype object or string specifier Specifies data type",
"None and img_num != i: image.getdata()[0] i += 1 continue",
"is not None: break if hasattr(image, 'fp') and image.fp: image.fp.close()",
"a file with multiple images (zero-indexed). kwargs : keyword pairs,",
"---------- Refer to ``imsave``. \"\"\" if arr.ndim == 3: arr",
"elif format_str in ['png', 'PNG']: mode = 'I;16' mode_base =",
"4): raise ValueError(\"Invalid number of channels in image array.\") img",
"try: image.seek(i) except EOFError: break frame = image if img_num",
"# Not all palette colors are used; unused colors have",
"import Image from ...util import img_as_ubyte, img_as_uint def imread(fname, dtype=None,",
"all colors in image palette are gray. \"\"\" assert pil_image.mode",
"values in [1, 95], while TIFFFile supports a ``compress`` integer",
"3): raise ValueError(\"Invalid shape for image array: %s\" % (arr.shape,",
"from the extension if fname is a string kwargs: dict",
"= image.convert('RGBA') elif image.mode == 'CMYK': frame = image.convert('RGB') if",
"img_as_uint(arr) else: arr = img_as_ubyte(arr) mode = 'L' mode_base =",
"raise ValueError(\"Invalid shape for image array: %s\" % (arr.shape, ))",
"= image.convert('L') else: if image.format == 'PNG' and 'transparency' in",
"image.mode.endswith('B') else '<u2' if 'S' in image.mode: dtype = dtype.replace('u',",
"elif frames: return frames[0] elif img_num: raise IndexError('Could not find",
"if not isinstance(fname, str) and format_str is None: format_str =",
"image.mode: dtype = dtype.replace('u', 'i') frame = np.fromstring(frame.tobytes(), dtype) frame.shape",
"a PIL object. Parameters ---------- Refer to ``imsave``. \"\"\" if",
"except AttributeError: array_buffer = arr.tostring() # Numpy < 1.9 if",
": keyword pairs, optional Addition keyword arguments to pass through.",
"be derived from the extension if fname is a string",
"try: array_buffer = arr.tobytes() except AttributeError: array_buffer = arr.tostring() #",
"image_shape, array_buffer) except AttributeError: im = Image.fromstring(mode, image_shape, array_buffer) #",
"(isinstance(fname, str) and fname.lower().endswith(\".png\")): format_str = \"PNG\" arr = np.asanyarray(arr)",
"frames: return frames[0] elif img_num: raise IndexError('Could not find image",
"bool True if all colors in image palette are gray.",
"format_str: str Format to save as, this is defaulted to",
"pil_image.mode == 'P' # get palette as an array with",
".. [1] http://pillow.readthedocs.org/en/latest/handbook/image-file-formats.html \"\"\" # default to PNG if file-like",
"img_num=None): \"\"\"Import a PIL Image object to an ndarray, in",
"formats. All images besides single channel PNGs are converted using",
"elif image.mode == 'CMYK': frame = image.convert('RGB') if image.mode.startswith('I;16'): shape",
"in image.mode: frame = image.convert('RGBA') elif image.mode == 'CMYK': frame",
"if image.mode == 'P': if grayscale is None: grayscale =",
"grayscale is None: grayscale = _palette_is_grayscale(image) if grayscale: frame =",
"Array (image) to save. Arrays of data-type uint8 should have",
"**kwargs): \"\"\"Load an image from file. Parameters ---------- fname :",
"pil_to_ndarray(im, dtype=dtype, img_num=img_num) else: im = Image.open(fname) return pil_to_ndarray(im, dtype=dtype,",
"in memory. Parameters ---------- Refer to ``imread``. \"\"\" try: #",
"img_as_ubyte(arr) mode = {3: 'RGB', 4: 'RGBA'}[arr.shape[2]] elif format_str in",
"(arr.shape, )) if arr.ndim == 3: if arr.shape[2] not in",
"the Pillow save function (or tifffile save function, for Tiff",
"Library. See PIL docs [1]_ for a list of other",
"object or string specifier Specifies data type of array elements.",
"Specifies data type of array elements. img_num : int, optional",
"keyword pairs, optional Addition keyword arguments to pass through. Notes",
"arr.ndim == 3: arr = img_as_ubyte(arr) mode = {3: 'RGB',",
"arr.shape[2] not in (3, 4): raise ValueError(\"Invalid number of channels",
"a PIL Image object to an ndarray, in memory. Parameters",
"are gray. \"\"\" assert pil_image.mode == 'P' # get palette",
"arr = arr.astype(np.uint8) if arr.ndim not in (2, 3): raise",
"are read using the Python Imaging Library. See PIL docs",
"values in [0, 9]. Notes ----- Use the Python Imaging",
"if isinstance(fname, str): with open(fname, 'rb') as f: im =",
"9]. Notes ----- Use the Python Imaging Library. See PIL",
"-> img_as_uint8 - Floating point and other integers -> img_as_uint16",
"str Format to save as, this is defaulted to PNG",
"See PIL docs [1]_ for a list of other supported",
"img_num is not None and img_num != i: image.getdata()[0] i",
"elif arr.max() < 256 and arr.min() >= 0: arr =",
"3)) # Not all palette colors are used; unused colors",
"and 'transparency' in image.info: frame = image.convert('RGBA') else: frame =",
"Use the Python Imaging Library. See PIL docs [1]_ for",
"palette[start:stop + 1] # Image is grayscale if channel differences",
"supports an integer ``quality`` argument with values in [1, 95],",
"to read in a file with multiple images (zero-indexed). kwargs",
"return frames[0] elif img_num: raise IndexError('Could not find image #%s'",
"used; unused colors have junk values. start, stop = pil_image.getextrema()",
"= arr.tobytes() except AttributeError: array_buffer = arr.tostring() # Numpy <",
"---------- .. [1] http://pillow.readthedocs.org/en/latest/handbook/image-file-formats.html \"\"\" # default to PNG if",
"return np.allclose(np.diff(valid_palette), 0) def ndarray_to_pil(arr, format_str=None): \"\"\"Export an ndarray to",
"derived from the extension if fname is a string kwargs:",
"if img_num is not None: break if hasattr(image, 'fp') and",
"= img_as_ubyte(arr) mode = {3: 'RGB', 4: 'RGBA'}[arr.shape[2]] elif format_str",
"im = Image.open(fname) return pil_to_ndarray(im, dtype=dtype, img_num=img_num) def pil_to_ndarray(image, dtype=None,",
"a file-like object; this will be derived from the extension",
"return np.array(frames) elif frames: return frames[0] elif img_num: raise IndexError('Could",
"isinstance(fname, str) and format_str is None: format_str = \"PNG\" #",
"np.asanyarray(arr) if arr.dtype.kind == 'b': arr = arr.astype(np.uint8) if arr.ndim",
"with values in [0, 9]. Notes ----- Use the Python",
"image.mode == 'P': if grayscale is None: grayscale = _palette_is_grayscale(image)",
"to PNG if file-like object if not isinstance(fname, str) and",
"mode. Returns ------- is_grayscale : bool True if all colors",
"save function supports an integer ``quality`` argument with values in",
"Single Channel PNGs have the following behavior: - Integer values",
"image in palette mode is grayscale. Parameters ---------- pil_image :",
"supports a ``compress`` integer argument with values in [0, 9].",
"fname.lower().endswith(\".png\")): format_str = \"PNG\" arr = np.asanyarray(arr) if arr.dtype.kind ==",
"1.1.7 else: image_shape = (arr.shape[1], arr.shape[0]) try: im = Image.frombytes(mode,",
"supported formats. All images besides single channel PNGs are converted",
"arr.max() < 256 and arr.min() >= 0: arr = arr.astype(np.uint8)",
"% (arr.shape, )) if arr.ndim == 3: if arr.shape[2] not",
"None: grayscale = _palette_is_grayscale(image) if grayscale: frame = image.convert('L') else:",
"== 'P' # get palette as an array with R,",
"'Please see documentation at: %s' % (image.filename, pillow_error_message, site)) raise",
"or float Array (image) to save. Arrays of data-type uint8",
"optional Specifies which image to read in a file with",
"other supported formats. All images besides single channel PNGs are",
"dtype.replace('u', 'i') frame = np.fromstring(frame.tobytes(), dtype) frame.shape = shape[::-1] else:",
"in [0, 255], whereas floating-point arrays must be in [0,",
"palette = np.asarray(pil_image.getpalette()).reshape((256, 3)) # Not all palette colors are",
"mode = mode_base = 'L' else: arr = img_as_uint(arr) else:",
"img_as_uint(arr) elif arr.max() < 256 and arr.min() >= 0: arr",
"image to read in a file with multiple images (zero-indexed).",
"IOError as e: site = \"http://pillow.readthedocs.org/en/latest/installation.html#external-libraries\" pillow_error_message = str(e) error_message",
"dtype = dtype.replace('u', 'i') frame = np.fromstring(frame.tobytes(), dtype) frame.shape =",
"= \"PNG\" # Check for png in filename if (isinstance(fname,",
"IndexError('Could not find image #%s' % img_num) def _palette_is_grayscale(pil_image): \"\"\"Return",
"``compress`` integer argument with values in [0, 9]. Notes -----",
"== 'I' and dtype is None: dtype = 'uint16' if",
"= 'I' if arr.dtype.kind == 'f': arr = img_as_uint(arr) elif"
] |
[
"- S1/Keq1))/(1 + X0 + S1 + S4^h); J1: S1",
"(1 + S1 + S2); J2: S2 -> S3; (10",
"0; S2 = 0; S3 = 0; S4 = 0;",
"''' model feedback() // Reactions: J0: $X0 -> S1; (VM1",
"X0 = 10; X1 = 0; // Variable initialization: VM1",
"J0: $X0 -> S1; (VM1 * (X0 - S1/Keq1))/(1 +",
"10; V4 = 2.5; KS4 = 0.5; end''' r =",
"* S3) / (1 + S2 + S3); J3: S3",
"print_function, division import tellurium as te model = ''' model",
"KS4 = 0.5; end''' r = te.loada(model) result = r.simulate(0,",
"\"\"\" from __future__ import print_function, division import tellurium as te",
"tellurium as te model = ''' model feedback() // Reactions:",
"model feedback() // Reactions: J0: $X0 -> S1; (VM1 *",
"/ (KS4 + S4); // Species initializations: S1 = 0;",
"initialization: VM1 = 10; Keq1 = 10; h = 10;",
"Species initializations: S1 = 0; S2 = 0; S3 =",
"end''' r = te.loada(model) result = r.simulate(0, 40, 500) r.plotWithLegend(result)",
"2 * S3) / (1 + S2 + S3); J3:",
"$X0 -> S1; (VM1 * (X0 - S1/Keq1))/(1 + X0",
"(KS4 + S4); // Species initializations: S1 = 0; S2",
"h = 10; V4 = 2.5; KS4 = 0.5; end'''",
"S2; (10 * S1 - 2 * S2) / (1",
"= ''' model feedback() // Reactions: J0: $X0 -> S1;",
"(X0 - S1/Keq1))/(1 + X0 + S1 + S4^h); J1:",
"J2: S2 -> S3; (10 * S2 - 2 *",
"/ (1 + S3 + S4); J4: S4 -> $X1;",
"(1 + S3 + S4); J4: S4 -> $X1; (V4",
"-> S3; (10 * S2 - 2 * S3) /",
"+ S4); J4: S4 -> $X1; (V4 * S4) /",
"-> S1; (VM1 * (X0 - S1/Keq1))/(1 + X0 +",
"S1 + S2); J2: S2 -> S3; (10 * S2",
"(V4 * S4) / (KS4 + S4); // Species initializations:",
"S3 = 0; S4 = 0; X0 = 10; X1",
"te model = ''' model feedback() // Reactions: J0: $X0",
"+ S1 + S4^h); J1: S1 -> S2; (10 *",
"0; // Variable initialization: VM1 = 10; Keq1 = 10;",
"* S2) / (1 + S1 + S2); J2: S2",
"VM1 = 10; Keq1 = 10; h = 10; V4",
"-> S4; (10 * S3 - 2 * S4) /",
"S4; (10 * S3 - 2 * S4) / (1",
"= 0; // Variable initialization: VM1 = 10; Keq1 =",
"+ S3 + S4); J4: S4 -> $X1; (V4 *",
"model = ''' model feedback() // Reactions: J0: $X0 ->",
"// Reactions: J0: $X0 -> S1; (VM1 * (X0 -",
"(10 * S3 - 2 * S4) / (1 +",
"X0 + S1 + S4^h); J1: S1 -> S2; (10",
"feedback() // Reactions: J0: $X0 -> S1; (VM1 * (X0",
"+ S4^h); J1: S1 -> S2; (10 * S1 -",
"S4) / (KS4 + S4); // Species initializations: S1 =",
"J4: S4 -> $X1; (V4 * S4) / (KS4 +",
"S2 = 0; S3 = 0; S4 = 0; X0",
"S2) / (1 + S1 + S2); J2: S2 ->",
"2 * S4) / (1 + S3 + S4); J4:",
"utf-8 -*- \"\"\" Linear chain of reactions. \"\"\" from __future__",
"import print_function, division import tellurium as te model = '''",
"of reactions. \"\"\" from __future__ import print_function, division import tellurium",
"+ S2); J2: S2 -> S3; (10 * S2 -",
"\"\"\" Linear chain of reactions. \"\"\" from __future__ import print_function,",
"S4); J4: S4 -> $X1; (V4 * S4) / (KS4",
"+ X0 + S1 + S4^h); J1: S1 -> S2;",
"J1: S1 -> S2; (10 * S1 - 2 *",
"S3) / (1 + S2 + S3); J3: S3 ->",
"initializations: S1 = 0; S2 = 0; S3 = 0;",
"+ S1 + S2); J2: S2 -> S3; (10 *",
"V4 = 2.5; KS4 = 0.5; end''' r = te.loada(model)",
"10; X1 = 0; // Variable initialization: VM1 = 10;",
"(VM1 * (X0 - S1/Keq1))/(1 + X0 + S1 +",
"= 0; S2 = 0; S3 = 0; S4 =",
"division import tellurium as te model = ''' model feedback()",
"+ S3); J3: S3 -> S4; (10 * S3 -",
"-*- \"\"\" Linear chain of reactions. \"\"\" from __future__ import",
"* (X0 - S1/Keq1))/(1 + X0 + S1 + S4^h);",
"/ (1 + S2 + S3); J3: S3 -> S4;",
"* S2 - 2 * S3) / (1 + S2",
"S1 - 2 * S2) / (1 + S1 +",
"= 10; h = 10; V4 = 2.5; KS4 =",
"0; X0 = 10; X1 = 0; // Variable initialization:",
"S2 -> S3; (10 * S2 - 2 * S3)",
"__future__ import print_function, division import tellurium as te model =",
"S1 -> S2; (10 * S1 - 2 * S2)",
"from __future__ import print_function, division import tellurium as te model",
"= 0; S4 = 0; X0 = 10; X1 =",
"(10 * S2 - 2 * S3) / (1 +",
"-*- coding: utf-8 -*- \"\"\" Linear chain of reactions. \"\"\"",
"// Variable initialization: VM1 = 10; Keq1 = 10; h",
"Keq1 = 10; h = 10; V4 = 2.5; KS4",
"10; Keq1 = 10; h = 10; V4 = 2.5;",
"X1 = 0; // Variable initialization: VM1 = 10; Keq1",
"// Species initializations: S1 = 0; S2 = 0; S3",
"= 0; X0 = 10; X1 = 0; // Variable",
"0.5; end''' r = te.loada(model) result = r.simulate(0, 40, 500)",
"Variable initialization: VM1 = 10; Keq1 = 10; h =",
"* S1 - 2 * S2) / (1 + S1",
"S4); // Species initializations: S1 = 0; S2 = 0;",
"/ (1 + S1 + S2); J2: S2 -> S3;",
"+ S4); // Species initializations: S1 = 0; S2 =",
"2 * S2) / (1 + S1 + S2); J2:",
"(1 + S2 + S3); J3: S3 -> S4; (10",
"= 10; Keq1 = 10; h = 10; V4 =",
"S3 + S4); J4: S4 -> $X1; (V4 * S4)",
"S3); J3: S3 -> S4; (10 * S3 - 2",
"S4 = 0; X0 = 10; X1 = 0; //",
"Reactions: J0: $X0 -> S1; (VM1 * (X0 - S1/Keq1))/(1",
"S3 - 2 * S4) / (1 + S3 +",
"Linear chain of reactions. \"\"\" from __future__ import print_function, division",
"S3; (10 * S2 - 2 * S3) / (1",
"* S4) / (KS4 + S4); // Species initializations: S1",
"= 0.5; end''' r = te.loada(model) result = r.simulate(0, 40,",
"+ S2 + S3); J3: S3 -> S4; (10 *",
"0; S3 = 0; S4 = 0; X0 = 10;",
"S1 = 0; S2 = 0; S3 = 0; S4",
"- 2 * S3) / (1 + S2 + S3);",
"S3 -> S4; (10 * S3 - 2 * S4)",
"0; S4 = 0; X0 = 10; X1 = 0;",
"-> $X1; (V4 * S4) / (KS4 + S4); //",
"10; h = 10; V4 = 2.5; KS4 = 0.5;",
"S1 + S4^h); J1: S1 -> S2; (10 * S1",
"import tellurium as te model = ''' model feedback() //",
"S1/Keq1))/(1 + X0 + S1 + S4^h); J1: S1 ->",
"* S4) / (1 + S3 + S4); J4: S4",
"S4) / (1 + S3 + S4); J4: S4 ->",
"S2 - 2 * S3) / (1 + S2 +",
"2.5; KS4 = 0.5; end''' r = te.loada(model) result =",
"(10 * S1 - 2 * S2) / (1 +",
"S2); J2: S2 -> S3; (10 * S2 - 2",
"chain of reactions. \"\"\" from __future__ import print_function, division import",
"S4 -> $X1; (V4 * S4) / (KS4 + S4);",
"S1; (VM1 * (X0 - S1/Keq1))/(1 + X0 + S1",
"= 0; S3 = 0; S4 = 0; X0 =",
"as te model = ''' model feedback() // Reactions: J0:",
"# -*- coding: utf-8 -*- \"\"\" Linear chain of reactions.",
"= 10; X1 = 0; // Variable initialization: VM1 =",
"$X1; (V4 * S4) / (KS4 + S4); // Species",
"S4^h); J1: S1 -> S2; (10 * S1 - 2",
"= 10; V4 = 2.5; KS4 = 0.5; end''' r",
"coding: utf-8 -*- \"\"\" Linear chain of reactions. \"\"\" from",
"reactions. \"\"\" from __future__ import print_function, division import tellurium as",
"S2 + S3); J3: S3 -> S4; (10 * S3",
"-> S2; (10 * S1 - 2 * S2) /",
"- 2 * S4) / (1 + S3 + S4);",
"= 2.5; KS4 = 0.5; end''' r = te.loada(model) result",
"J3: S3 -> S4; (10 * S3 - 2 *",
"* S3 - 2 * S4) / (1 + S3",
"- 2 * S2) / (1 + S1 + S2);"
] |
[
"from .transactions import Transaction, TransactionCreate, TransactionUpdate from .accounts import Account,",
"Transaction, TransactionCreate, TransactionUpdate from .accounts import Account, AccountList, AccountSingle, AccountCreate,",
".accounts import Account, AccountList, AccountSingle, AccountCreate, AccountUpdate from .categories import",
"AccountList, AccountSingle, AccountCreate, AccountUpdate from .categories import Category, CategoryCreate, CategoryUpdate",
".transactions import Transaction, TransactionCreate, TransactionUpdate from .accounts import Account, AccountList,",
"import Account, AccountList, AccountSingle, AccountCreate, AccountUpdate from .categories import Category,",
"Account, AccountList, AccountSingle, AccountCreate, AccountUpdate from .categories import Category, CategoryCreate,",
"UserUpdate from .transactions import Transaction, TransactionCreate, TransactionUpdate from .accounts import",
"from .users import User, UserCreate, UserUpdate from .transactions import Transaction,",
"UserCreate, UserUpdate from .transactions import Transaction, TransactionCreate, TransactionUpdate from .accounts",
"import Transaction, TransactionCreate, TransactionUpdate from .accounts import Account, AccountList, AccountSingle,",
"TransactionCreate, TransactionUpdate from .accounts import Account, AccountList, AccountSingle, AccountCreate, AccountUpdate",
"TransactionUpdate from .accounts import Account, AccountList, AccountSingle, AccountCreate, AccountUpdate from",
"from .accounts import Account, AccountList, AccountSingle, AccountCreate, AccountUpdate from .categories",
"User, UserCreate, UserUpdate from .transactions import Transaction, TransactionCreate, TransactionUpdate from",
"import User, UserCreate, UserUpdate from .transactions import Transaction, TransactionCreate, TransactionUpdate",
".users import User, UserCreate, UserUpdate from .transactions import Transaction, TransactionCreate,"
] |
[
"pass class Bar(Foo): def __init__(self): super(Bar, self).__init__() # [super-with-arguments] class",
"exception would be 'RuntimeError: super(): __class__ cell not found') #",
"be 'RuntimeError: super(): __class__ cell not found') # Instead, we",
"not found') # Instead, we expect to *not* see a",
"class Bar(Foo): def __init__(self): super(Bar, self).__init__() # [super-with-arguments] class Baz(Foo):",
"no `__class__` cell found # (Exact exception would be 'RuntimeError:",
"# Explicitly passing `cls`, and `self` to `super()` is what's",
"here, since there's no `__class__` cell found # (Exact exception",
"__init__(self): super(Bar, self).__init__() # [super-with-arguments] class Baz(Foo): def __init__(self): super().__init__()",
"__init__(self): super.test(Bar, self).__init__() class InvalidSuperCall(Foo): def __init__(self): super(InvalidSuperCall.__class__, self).__init__() def",
"cell not found') # Instead, we expect to *not* see",
"def __init__(self): super().__init__() class Qux(Foo): def __init__(self): super(Bar, self).__init__() class",
"Using plain `super()` is not valid here, since there's no",
"super(InvalidSuperCall.__class__, self).__init__() def method_accepting_cls(cls, self): # Using plain `super()` is",
"self).__init__() # [super-with-arguments] class Baz(Foo): def __init__(self): super().__init__() class Qux(Foo):",
"since there's no `__class__` cell found # (Exact exception would",
"`super()` is not valid here, since there's no `__class__` cell",
"class InvalidSuperCall(Foo): def __init__(self): super(InvalidSuperCall.__class__, self).__init__() def method_accepting_cls(cls, self): #",
"would be 'RuntimeError: super(): __class__ cell not found') # Instead,",
"plain `super()` is not valid here, since there's no `__class__`",
"class Foo: pass class Bar(Foo): def __init__(self): super(Bar, self).__init__() #",
"*not* see a warning about `super-with-arguments`. # Explicitly passing `cls`,",
"def method_accepting_cls(cls, self): # Using plain `super()` is not valid",
"there's no `__class__` cell found # (Exact exception would be",
"(Exact exception would be 'RuntimeError: super(): __class__ cell not found')",
"# Instead, we expect to *not* see a warning about",
"'RuntimeError: super(): __class__ cell not found') # Instead, we expect",
"valid here, since there's no `__class__` cell found # (Exact",
"passing `cls`, and `self` to `super()` is what's required. super(cls,",
"not valid here, since there's no `__class__` cell found #",
"self): # Using plain `super()` is not valid here, since",
"def __init__(self): super(Bar, self).__init__() # [super-with-arguments] class Baz(Foo): def __init__(self):",
"super(): __class__ cell not found') # Instead, we expect to",
"NotSuperCall(Foo): def __init__(self): super.test(Bar, self).__init__() class InvalidSuperCall(Foo): def __init__(self): super(InvalidSuperCall.__class__,",
"we expect to *not* see a warning about `super-with-arguments`. #",
"super.test(Bar, self).__init__() class InvalidSuperCall(Foo): def __init__(self): super(InvalidSuperCall.__class__, self).__init__() def method_accepting_cls(cls,",
"expect to *not* see a warning about `super-with-arguments`. # Explicitly",
"[super-with-arguments] class Baz(Foo): def __init__(self): super().__init__() class Qux(Foo): def __init__(self):",
"def __init__(self): super(Bar, self).__init__() class NotSuperCall(Foo): def __init__(self): super.test(Bar, self).__init__()",
"super(Bar, self).__init__() class NotSuperCall(Foo): def __init__(self): super.test(Bar, self).__init__() class InvalidSuperCall(Foo):",
"found # (Exact exception would be 'RuntimeError: super(): __class__ cell",
"super(Bar, self).__init__() # [super-with-arguments] class Baz(Foo): def __init__(self): super().__init__() class",
"to *not* see a warning about `super-with-arguments`. # Explicitly passing",
"InvalidSuperCall(Foo): def __init__(self): super(InvalidSuperCall.__class__, self).__init__() def method_accepting_cls(cls, self): # Using",
"a warning about `super-with-arguments`. # Explicitly passing `cls`, and `self`",
"super().__init__() class Qux(Foo): def __init__(self): super(Bar, self).__init__() class NotSuperCall(Foo): def",
"cell found # (Exact exception would be 'RuntimeError: super(): __class__",
"self).__init__() def method_accepting_cls(cls, self): # Using plain `super()` is not",
"about `super-with-arguments`. # Explicitly passing `cls`, and `self` to `super()`",
"# [super-with-arguments] class Baz(Foo): def __init__(self): super().__init__() class Qux(Foo): def",
"__init__(self): super(Bar, self).__init__() class NotSuperCall(Foo): def __init__(self): super.test(Bar, self).__init__() class",
"class Baz(Foo): def __init__(self): super().__init__() class Qux(Foo): def __init__(self): super(Bar,",
"method_accepting_cls(cls, self): # Using plain `super()` is not valid here,",
"`cls`, and `self` to `super()` is what's required. super(cls, self).__init__()",
"Bar(Foo): def __init__(self): super(Bar, self).__init__() # [super-with-arguments] class Baz(Foo): def",
"def __init__(self): super(InvalidSuperCall.__class__, self).__init__() def method_accepting_cls(cls, self): # Using plain",
"<filename>vimfiles/bundle/vim-python/submodules/pylint/tests/functional/s/super/super_with_arguments.py class Foo: pass class Bar(Foo): def __init__(self): super(Bar, self).__init__()",
"Qux(Foo): def __init__(self): super(Bar, self).__init__() class NotSuperCall(Foo): def __init__(self): super.test(Bar,",
"`__class__` cell found # (Exact exception would be 'RuntimeError: super():",
"is not valid here, since there's no `__class__` cell found",
"# (Exact exception would be 'RuntimeError: super(): __class__ cell not",
"__class__ cell not found') # Instead, we expect to *not*",
"Baz(Foo): def __init__(self): super().__init__() class Qux(Foo): def __init__(self): super(Bar, self).__init__()",
"__init__(self): super(InvalidSuperCall.__class__, self).__init__() def method_accepting_cls(cls, self): # Using plain `super()`",
"Explicitly passing `cls`, and `self` to `super()` is what's required.",
"self).__init__() class InvalidSuperCall(Foo): def __init__(self): super(InvalidSuperCall.__class__, self).__init__() def method_accepting_cls(cls, self):",
"self).__init__() class NotSuperCall(Foo): def __init__(self): super.test(Bar, self).__init__() class InvalidSuperCall(Foo): def",
"Instead, we expect to *not* see a warning about `super-with-arguments`.",
"`super-with-arguments`. # Explicitly passing `cls`, and `self` to `super()` is",
"class Qux(Foo): def __init__(self): super(Bar, self).__init__() class NotSuperCall(Foo): def __init__(self):",
"# Using plain `super()` is not valid here, since there's",
"warning about `super-with-arguments`. # Explicitly passing `cls`, and `self` to",
"found') # Instead, we expect to *not* see a warning",
"see a warning about `super-with-arguments`. # Explicitly passing `cls`, and",
"__init__(self): super().__init__() class Qux(Foo): def __init__(self): super(Bar, self).__init__() class NotSuperCall(Foo):",
"def __init__(self): super.test(Bar, self).__init__() class InvalidSuperCall(Foo): def __init__(self): super(InvalidSuperCall.__class__, self).__init__()",
"Foo: pass class Bar(Foo): def __init__(self): super(Bar, self).__init__() # [super-with-arguments]",
"class NotSuperCall(Foo): def __init__(self): super.test(Bar, self).__init__() class InvalidSuperCall(Foo): def __init__(self):"
] |
[
"categories = ['<'+str(x) for x in range(2,22,2)] df1 = df",
"train_test_split from sklearn.preprocessing import LabelEncoder from sklearn.ensemble import RandomForestClassifier from",
"since Promotion\", ylabel=\"Total\") plt.xticks(rotation=-30) plt.savefig('templates/graphs/raw/YSCPvsAttr.png') ax = sns.countplot(x=\"MaritalStatus\", hue=\"Attrition\", palette=\"Set1\",",
"9]) labelencoder_X_12 = LabelEncoder() X[:, 12] = labelencoder_X_12.fit_transform(X[:, 12]) X",
"= LabelEncoder() X[:, 5] = labelencoder_X_5.fit_transform(X[:, 5]) labelencoder_X_6 = LabelEncoder()",
"12] = labelencoder_X_12.fit_transform(X[:, 12]) X = X.astype(float) labelencoder_y = LabelEncoder()",
"data=df1) ax.set(title=\"Distance from home vs Attrition\", xlabel=\"Distance\", ylabel=\"Total\") plt.xticks(rotation=-30) plt.savefig('templates/graphs/raw/DistanceFromHomevsAttr.png')",
"i = i+1 df1 = pd.DataFrame(X) df1.columns=['Attrition', 'Age', 'BusinessTravel', 'Department',",
"[x for x in range(0,22,2)] categories = ['<'+str(x) for x",
"df[['Attrition', 'Age', 'BusinessTravel', 'Department', 'DistanceFromHome', 'Education', 'EducationField', 'Gender', 'JobRole', 'JobSatisfaction',",
"THIS IS XXXX##########\") #print(X) att = check(X, clf) skills =",
"t+(a,) return t def analyze(df, clf): feature_importances = pd.DataFrame(clf.feature_importances_, index=['Age',",
"'PerformanceRating', 'TrainingTimesLastYear', 'RelationshipSatisfaction', 'StockOptionLevel', 'WorkLifeBalance', 'YearsWithCurrManager'], axis=1) df = df[['Attrition',",
"= labelencoder_X_7.fit_transform(X[:, 7]) labelencoder_X_9 = LabelEncoder() X[:, 9] = labelencoder_X_9.fit_transform(X[:,",
"= [x for x in range(0, 22000, 2000)] categories =",
"in Current Role vs Attrition\", xlabel=\"Number Of Years in Current",
"clf): feature_importances = pd.DataFrame(clf.feature_importances_, index=['Age', 'BusinessTravel', 'Department', 'DistanceFromHome', 'Education', 'EducationField',",
"df1['Current_Role'] = pd.cut(df.YearsInCurrentRole, intervals, labels=categories) ax = sns.countplot(x=\"Current_Role\", hue=\"Attrition\", palette=\"Set1\",",
"plt.xticks(rotation=-30) plt.savefig('templates/graphs/raw/MIvsAttr.png') intervals = [x for x in range(18,63,3)] categories",
"palette=\"Set1\", data=df1) ax.set(title=\"Number Of Years in Current Role vs Attrition\",",
"if x == 0: a = 'No' else: a =",
"accuracy_score from flask import flash import numpy as np def",
"def analyze(df, clf): feature_importances = pd.DataFrame(clf.feature_importances_, index=['Age', 'BusinessTravel', 'Department', 'DistanceFromHome',",
"'JobRole', 'JobSatisfaction', 'MaritalStatus', 'MonthlyIncome', 'NumCompaniesWorked', 'OverTime', 'PercentSalaryHike', 'YearsInCurrentRole', 'YearsSinceLastPromotion'] analyze(df,",
"Years since Promotion vs Attrition\", xlabel=\"Number of Years since Promotion\",",
"Percentage\", ylabel=\"Total\") plt.savefig('templates/graphs/raw/PercentSalaryHikevsAttr.png') ax = sns.countplot(x=\"NumCompaniesWorked\", hue=\"Attrition\", palette=\"Set1\", data=df1) ax.set(title=\"Number",
"'PercentSalaryHike', 'YearsInCurrentRole', 'YearsSinceLastPromotion']] #print(\"These re SKILSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSS\") #print(skills) X = df.iloc[:,",
"X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.40,random_state=0) clf =",
"X[:, 1] = labelencoder_X_1.fit_transform(X[:, 1]) labelencoder_X_2 = LabelEncoder() X[:, 2]",
"'TotalWorkingYears', 'JobLevel', 'HourlyRate', 'MonthlyRate', 'Over18', 'StandardHours', 'EnvironmentSatisfaction', 'JobInvolvement', 'PerformanceRating', 'TrainingTimesLastYear',",
"[x for x in range(0,18,2)] categories = ['<'+str(x) for x",
"X = np.array(X) labelencoder_X_1 = LabelEncoder() X[:, 1] = labelencoder_X_1.fit_transform(X[:,",
"intervals, labels=categories) ax = sns.countplot(x=\"Distance_from_home\", hue=\"Attrition\", palette=\"Set1\", data=df1) ax.set(title=\"Distance from",
"range(0, 22000, 2000)] categories = ['<'+str(x) for x in range(2000,",
"'OverTime', 'PercentSalaryHike', 'YearsInCurrentRole', 'YearsSinceLastPromotion'],columns=['importance']).sort_values('importance',ascending=False) feature_importances['x1'] = feature_importances.index ax = feature_importances.plot.bar(x='x1',",
"plt.savefig('templates/graphs/raw/YICRvsAttr.png') ax = sns.countplot(x=\"OverTime\", hue=\"Attrition\", palette=\"Set1\", data=df1) ax.set(title=\"Over Time vs",
"vs Attrition\", xlabel=\"Age group\", ylabel=\"Total\") plt.xticks(rotation=-30) plt.savefig('templates/graphs/raw/AgevsAttr.png') intervals = [x",
"data=df1) ax.set(title=\"Marital Status vs Attrition\", xlabel=\"Marital Status\", ylabel=\"Total\") plt.savefig('templates/graphs/raw/MSvsAttr.png') def",
"= labelencoder_X_2.fit_transform(X[:, 2]) labelencoder_X_5 = LabelEncoder() X[:, 5] = labelencoder_X_5.fit_transform(X[:,",
"Time vs Attrition\", xlabel=\"Over Time\", ylabel=\"Total\") plt.savefig('templates/graphs/raw/OverTimevsAttr.png') ax = sns.countplot(x=\"JobRole\",",
"'MaritalStatus', 'MonthlyIncome', 'NumCompaniesWorked', 'OverTime', 'PercentSalaryHike', 'YearsInCurrentRole', 'YearsSinceLastPromotion'],columns=['importance']).sort_values('importance',ascending=False) feature_importances['x1'] = feature_importances.index",
"from home vs Attrition\", xlabel=\"Distance\", ylabel=\"Total\") plt.xticks(rotation=-30) plt.savefig('templates/graphs/raw/DistanceFromHomevsAttr.png') ax =",
"'MonthlyRate', 'Over18', 'StandardHours', 'EnvironmentSatisfaction', 'JobInvolvement', 'PerformanceRating', 'TrainingTimesLastYear', 'RelationshipSatisfaction', 'StockOptionLevel', 'WorkLifeBalance',",
"sklearn.model_selection import train_test_split from sklearn.preprocessing import LabelEncoder from sklearn.ensemble import",
"'JobRole', 'JobSatisfaction', 'MaritalStatus', 'MonthlyIncome', 'NumCompaniesWorked', 'OverTime', 'PercentSalaryHike', 'YearsInCurrentRole', 'YearsSinceLastPromotion'],columns=['importance']).sort_values('importance',ascending=False) feature_importances['x1']",
"x in range(2000, 22000, 2000)] df1 = df df1['Income_Categories'] =",
"df df1['Age_Categories'] = pd.cut(df.Age, intervals, labels=categories) ax = sns.countplot(x=\"Age_Categories\", hue=\"Attrition\",",
"hue=\"Attrition\", palette=\"Set1\", data=df1) ax.set(title=\"Age vs Attrition\", xlabel=\"Age group\", ylabel=\"Total\") plt.xticks(rotation=-30)",
"df df1['Distance_from_home'] = pd.cut(df.DistanceFromHome, intervals, labels=categories) ax = sns.countplot(x=\"Distance_from_home\", hue=\"Attrition\",",
"since Promotion vs Attrition\", xlabel=\"Number of Years since Promotion\", ylabel=\"Total\")",
"'PercentSalaryHike', 'YearsInCurrentRole', 'YearsSinceLastPromotion'],columns=['importance']).sort_values('importance',ascending=False) feature_importances['x1'] = feature_importances.index ax = feature_importances.plot.bar(x='x1', y='importance',",
"+ str(len(skills))) i = 0 for row in att: X[i].insert(0,",
"= t+(a,) return t def analyze(df, clf): feature_importances = pd.DataFrame(clf.feature_importances_,",
"ax.set(title=\"Salary Hike Percentage vs Attrition\", xlabel=\"Salary Hike Percentage\", ylabel=\"Total\") plt.savefig('templates/graphs/raw/PercentSalaryHikevsAttr.png')",
"22000, 2000)] categories = ['<'+str(x) for x in range(2000, 22000,",
"sns from sklearn.model_selection import train_test_split from sklearn.preprocessing import LabelEncoder from",
"train_test_split(X, y, test_size=0.40,random_state=0) clf = RandomForestClassifier(n_estimators=200) clf.fit(X_train,y_train) p = clf.predict(X_test)",
"'YearsWithCurrManager'], axis=1) df = df[['Attrition', 'Age', 'BusinessTravel', 'Department', 'DistanceFromHome', 'Education',",
"clf = RandomForestClassifier(n_estimators=200) clf.fit(X_train,y_train) p = clf.predict(X_test) acc = accuracy_score(y_test,p)*100",
"Promotion\", ylabel=\"Total\") plt.xticks(rotation=-30) plt.savefig('templates/graphs/raw/YSCPvsAttr.png') ax = sns.countplot(x=\"MaritalStatus\", hue=\"Attrition\", palette=\"Set1\", data=df1)",
"skills = skills[:(len(att)):] print(\"LLLLLLLLLLLLLLLENGHT\" + str(len(att)) +\" \" + str(len(skills)))",
"= ['<'+str(x) for x in range(2000, 22000, 2000)] df1 =",
"import pandas as pd import matplotlib.pyplot as plt import seaborn",
"= LabelEncoder() X[:, 2] = labelencoder_X_2.fit_transform(X[:, 2]) labelencoder_X_5 = LabelEncoder()",
"Income vs Attrition\", xlabel=\"Income group\", ylabel=\"Total\") plt.xticks(rotation=-30) plt.savefig('templates/graphs/raw/MIvsAttr.png') intervals =",
"clf) skills = skills[:(len(att)):] print(\"LLLLLLLLLLLLLLLENGHT\" + str(len(att)) +\" \" +",
"= ['<'+str(x) for x in range(2,32,2)] df1 = df df1['Distance_from_home']",
"import flash import numpy as np def check(X, clf): #",
"sklearn.ensemble import RandomForestClassifier from sklearn.metrics import accuracy_score from flask import",
"= X.astype(float) labelencoder_y = LabelEncoder() y = labelencoder_y.fit_transform(y) X_train, X_test,",
"= RandomForestClassifier(n_estimators=200) clf.fit(X_train,y_train) p = clf.predict(X_test) acc = accuracy_score(y_test,p)*100 flash(acc)",
"'Age', 'BusinessTravel', 'Department', 'DistanceFromHome', 'Education', 'EducationField', 'Gender', 'JobRole', 'JobSatisfaction', 'MaritalStatus',",
"labels=categories) ax = sns.countplot(x=\"Income_Categories\", hue=\"Attrition\", palette=\"Set1\", data=df1) ax.set(title=\"Monthly Income vs",
"= labelencoder_X_12.fit_transform(X[:, 12]) X = X.astype(float) labelencoder_y = LabelEncoder() y",
"xlabel=\"Age group\", ylabel=\"Total\") plt.xticks(rotation=-30) plt.savefig('templates/graphs/raw/AgevsAttr.png') intervals = [x for x",
"Role\", ylabel=\"Total\") plt.xticks(rotation=70) plt.savefig('templates/graphs/raw/JobRolevsAttr.png') intervals = [x for x in",
"sns.countplot(x=\"Promotion\", hue=\"Attrition\", palette=\"Set1\", data=df1) ax.set(title=\"Number of Years since Promotion vs",
"x in range(18,63,3)] categories = ['<'+str(x) for x in range(21,63,3)]",
"sns.countplot(x=\"MaritalStatus\", hue=\"Attrition\", palette=\"Set1\", data=df1) ax.set(title=\"Marital Status vs Attrition\", xlabel=\"Marital Status\",",
"plt.xticks(rotation=-30) plt.savefig('templates/graphs/raw/AgevsAttr.png') intervals = [x for x in range(0,32,2)] categories",
"= pd.cut(df.DistanceFromHome, intervals, labels=categories) ax = sns.countplot(x=\"Distance_from_home\", hue=\"Attrition\", palette=\"Set1\", data=df1)",
"in range(0,22,2)] categories = ['<'+str(x) for x in range(2,22,2)] df1",
"hue=\"Attrition\", palette=\"Set1\", data=df1) ax.set(title=\"Monthly Income vs Attrition\", xlabel=\"Income group\", ylabel=\"Total\")",
"'MonthlyIncome', 'NumCompaniesWorked', 'OverTime', 'PercentSalaryHike', 'YearsInCurrentRole', 'YearsSinceLastPromotion'] analyze(df, clf) df1.to_csv('dataset1.csv') return",
"1] = labelencoder_X_1.fit_transform(X[:, 1]) labelencoder_X_2 = LabelEncoder() X[:, 2] =",
"plt import seaborn as sns from sklearn.model_selection import train_test_split from",
"LabelEncoder() X[:, 7] = labelencoder_X_7.fit_transform(X[:, 7]) labelencoder_X_9 = LabelEncoder() X[:,",
"Years in Current Role\", ylabel=\"Total\") plt.xticks(rotation=-30) plt.savefig('templates/graphs/raw/YICRvsAttr.png') ax = sns.countplot(x=\"OverTime\",",
"print(skills) df = df.drop(['DailyRate', 'EmployeeCount', 'YearsAtCompany', 'TotalWorkingYears', 'JobLevel', 'HourlyRate', 'MonthlyRate',",
"hue=\"Attrition\", palette=\"Set1\", data=df1) ax.set(title=\"Salary Hike Percentage vs Attrition\", xlabel=\"Salary Hike",
"[x for x in range(0, 22000, 2000)] categories = ['<'+str(x)",
"df1['Distance_from_home'] = pd.cut(df.DistanceFromHome, intervals, labels=categories) ax = sns.countplot(x=\"Distance_from_home\", hue=\"Attrition\", palette=\"Set1\",",
"labelencoder_X_12 = LabelEncoder() X[:, 12] = labelencoder_X_12.fit_transform(X[:, 12]) X =",
"= df.iloc[:, 1:].values y = df.iloc[:, 0].values labelencoder_X_1 = LabelEncoder()",
"df.iloc[:, 1:].values y = df.iloc[:, 0].values labelencoder_X_1 = LabelEncoder() X[:,",
"y, test_size=0.40,random_state=0) clf = RandomForestClassifier(n_estimators=200) clf.fit(X_train,y_train) p = clf.predict(X_test) acc",
"sklearn.metrics import accuracy_score from flask import flash import numpy as",
"X[:, 2] = labelencoder_X_2.fit_transform(X[:, 2]) labelencoder_X_5 = LabelEncoder() X[:, 5]",
"# print(skills) df = df.drop(['DailyRate', 'EmployeeCount', 'YearsAtCompany', 'TotalWorkingYears', 'JobLevel', 'HourlyRate',",
"sns.countplot(x=\"Current_Role\", hue=\"Attrition\", palette=\"Set1\", data=df1) ax.set(title=\"Number Of Years in Current Role",
"i+1 df1 = pd.DataFrame(X) df1.columns=['Attrition', 'Age', 'BusinessTravel', 'Department', 'DistanceFromHome', 'Education',",
"= df df1['Income_Categories'] = pd.cut(df.MonthlyIncome, intervals, labels=categories) ax = sns.countplot(x=\"Income_Categories\",",
"str(len(att)) +\" \" + str(len(skills))) i = 0 for row",
"'StockOptionLevel', 'WorkLifeBalance', 'YearsWithCurrManager'], axis=1) df = df[['Attrition', 'Age', 'BusinessTravel', 'Department',",
"X[:, 6] = labelencoder_X_6.fit_transform(X[:, 6]) labelencoder_X_7 = LabelEncoder() X[:, 7]",
"as np def check(X, clf): # print(\"TTTTTTTTTTTTThis is XXXXXXXXXXXX\") #",
"'RelationshipSatisfaction', 'StockOptionLevel', 'WorkLifeBalance', 'YearsWithCurrManager'], axis=1) df = df[['Attrition', 'Age', 'BusinessTravel',",
"palette=\"Set1\", data=df1) ax.set(title=\"Job Role vs Attrition\", xlabel=\"Job Role\", ylabel=\"Total\") plt.xticks(rotation=70)",
"= sns.countplot(x=\"Promotion\", hue=\"Attrition\", palette=\"Set1\", data=df1) ax.set(title=\"Number of Years since Promotion",
"df['Skills'].tolist() # print(\"SKKKKKKKKKKKKKKKILLLLLLLLLLLLLLLS\") # print(skills) df = df.drop(['DailyRate', 'EmployeeCount', 'YearsAtCompany',",
"ax = sns.countplot(x=\"Distance_from_home\", hue=\"Attrition\", palette=\"Set1\", data=df1) ax.set(title=\"Distance from home vs",
"data=df1) ax.set(title=\"Number of Years since Promotion vs Attrition\", xlabel=\"Number of",
"+ str(len(att)) +\" \" + str(len(skills))) i = 0 for",
"ax = sns.countplot(x=\"Income_Categories\", hue=\"Attrition\", palette=\"Set1\", data=df1) ax.set(title=\"Monthly Income vs Attrition\",",
"else: a = 'Yes' t = t+(a,) return t def",
"= skills[:(len(att)):] print(\"LLLLLLLLLLLLLLLENGHT\" + str(len(att)) +\" \" + str(len(skills))) i",
"df = pd.read_csv('original_dataset.csv') skills = df['Skills'].tolist() # print(\"SKKKKKKKKKKKKKKKILLLLLLLLLLLLLLLS\") # print(skills)",
"range(18,63,3)] categories = ['<'+str(x) for x in range(21,63,3)] df1 =",
"ax.set(title=\"Number Of Previously Worked Companies vs Attrition\", xlabel=\"Number Of Previously",
"labels=categories) ax = sns.countplot(x=\"Current_Role\", hue=\"Attrition\", palette=\"Set1\", data=df1) ax.set(title=\"Number Of Years",
"sns.countplot(x=\"Income_Categories\", hue=\"Attrition\", palette=\"Set1\", data=df1) ax.set(title=\"Monthly Income vs Attrition\", xlabel=\"Income group\",",
"X[:, 12] = labelencoder_X_12.fit_transform(X[:, 12]) X = X.astype(float) labelencoder_y =",
"#print(\"These re SKILSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSS\") #print(skills) X = df.iloc[:, 1:].values y =",
"ax = sns.countplot(x=\"Promotion\", hue=\"Attrition\", palette=\"Set1\", data=df1) ax.set(title=\"Number of Years since",
"0: a = 'No' else: a = 'Yes' t =",
"Years in Current Role vs Attrition\", xlabel=\"Number Of Years in",
"i = 0 for row in att: X[i].insert(0, row) i",
"'TrainingTimesLastYear', 'RelationshipSatisfaction', 'StockOptionLevel', 'WorkLifeBalance', 'YearsWithCurrManager'], axis=1) df = df[['Attrition', 'Age',",
"IS XXXX##########\") #print(X) att = check(X, clf) skills = skills[:(len(att)):]",
"row) i = i+1 df1 = pd.DataFrame(X) df1.columns=['Attrition', 'Age', 'BusinessTravel',",
"matplotlib.pyplot as plt import seaborn as sns from sklearn.model_selection import",
"x in range(2,22,2)] df1 = df df1['Current_Role'] = pd.cut(df.YearsInCurrentRole, intervals,",
"flash import numpy as np def check(X, clf): # print(\"TTTTTTTTTTTTThis",
"hue=\"Attrition\", palette=\"Set1\", data=df1) ax.set(title=\"Distance from home vs Attrition\", xlabel=\"Distance\", ylabel=\"Total\")",
"ylabel=\"Total\") plt.xticks(rotation=-30) plt.savefig('templates/graphs/raw/DistanceFromHomevsAttr.png') ax = sns.countplot(x=\"PercentSalaryHike\", hue=\"Attrition\", palette=\"Set1\", data=df1) ax.set(title=\"Salary",
"ax.set(title=\"Marital Status vs Attrition\", xlabel=\"Marital Status\", ylabel=\"Total\") plt.savefig('templates/graphs/raw/MSvsAttr.png') def run(data):",
"pd.cut(df.MonthlyIncome, intervals, labels=categories) ax = sns.countplot(x=\"Income_Categories\", hue=\"Attrition\", palette=\"Set1\", data=df1) ax.set(title=\"Monthly",
"'YearsInCurrentRole', 'YearsSinceLastPromotion']] #print(\"These re SKILSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSS\") #print(skills) X = df.iloc[:, 1:].values",
"Status\", ylabel=\"Total\") plt.savefig('templates/graphs/raw/MSvsAttr.png') def run(data): df = pd.read_csv('original_dataset.csv') skills =",
"5] = labelencoder_X_5.fit_transform(X[:, 5]) labelencoder_X_6 = LabelEncoder() X[:, 6] =",
"LabelEncoder() y = labelencoder_y.fit_transform(y) X_train, X_test, y_train, y_test = train_test_split(X,",
"'No' else: a = 'Yes' t = t+(a,) return t",
"categories = ['<'+str(x) for x in range(2,18,2)] df1 = df",
"x in p: if x == 0: a = 'No'",
"'JobSatisfaction', 'MaritalStatus', 'MonthlyIncome', 'NumCompaniesWorked', 'OverTime', 'PercentSalaryHike', 'YearsInCurrentRole', 'YearsSinceLastPromotion'] analyze(df, clf)",
"= [list(elem) for elem in data] [r.pop(0) for r in",
"a = 'No' else: a = 'Yes' t = t+(a,)",
"skills = df['Skills'].tolist() # print(\"SKKKKKKKKKKKKKKKILLLLLLLLLLLLLLLS\") # print(skills) df = df.drop(['DailyRate',",
"run(data): df = pd.read_csv('original_dataset.csv') skills = df['Skills'].tolist() # print(\"SKKKKKKKKKKKKKKKILLLLLLLLLLLLLLLS\") #",
"import accuracy_score from flask import flash import numpy as np",
"= check(X, clf) skills = skills[:(len(att)):] print(\"LLLLLLLLLLLLLLLENGHT\" + str(len(att)) +\"",
"= labelencoder_y.fit_transform(y) X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.40,random_state=0)",
"'JobSatisfaction', 'MaritalStatus', 'MonthlyIncome', 'NumCompaniesWorked', 'OverTime', 'PercentSalaryHike', 'YearsInCurrentRole', 'YearsSinceLastPromotion'],columns=['importance']).sort_values('importance',ascending=False) feature_importances['x1'] =",
"pd import matplotlib.pyplot as plt import seaborn as sns from",
"Attrition\", xlabel=\"Age group\", ylabel=\"Total\") plt.xticks(rotation=-30) plt.savefig('templates/graphs/raw/AgevsAttr.png') intervals = [x for",
"ax.set(title=\"Number Of Years in Current Role vs Attrition\", xlabel=\"Number Of",
"feature_importances.plot.bar(x='x1', y='importance', rot=90) plt.savefig('templates/graphs/raw/feature_importances.png', frameon=True) intervals = [x for x",
"labelencoder_X_9 = LabelEncoder() X[:, 9] = labelencoder_X_9.fit_transform(X[:, 9]) labelencoder_X_12 =",
"test_size=0.40,random_state=0) clf = RandomForestClassifier(n_estimators=200) clf.fit(X_train,y_train) p = clf.predict(X_test) acc =",
"= [x for x in range(0,18,2)] categories = ['<'+str(x) for",
"X.astype(float) labelencoder_y = LabelEncoder() y = labelencoder_y.fit_transform(y) X_train, X_test, y_train,",
"Previously Worked Companies\", ylabel=\"Total\") plt.savefig('templates/graphs/raw/NPWCvsAttr.png') intervals = [x for x",
"= [x for x in range(0,22,2)] categories = ['<'+str(x) for",
"() for x in p: if x == 0: a",
"data] [r.pop(0) for r in X] #print(\"####### THIS IS XXXX##########\")",
"= pd.cut(df.MonthlyIncome, intervals, labels=categories) ax = sns.countplot(x=\"Income_Categories\", hue=\"Attrition\", palette=\"Set1\", data=df1)",
"plt.xticks(rotation=-30) plt.savefig('templates/graphs/raw/YICRvsAttr.png') ax = sns.countplot(x=\"OverTime\", hue=\"Attrition\", palette=\"Set1\", data=df1) ax.set(title=\"Over Time",
"= sns.countplot(x=\"NumCompaniesWorked\", hue=\"Attrition\", palette=\"Set1\", data=df1) ax.set(title=\"Number Of Previously Worked Companies",
"labels=categories) ax = sns.countplot(x=\"Promotion\", hue=\"Attrition\", palette=\"Set1\", data=df1) ax.set(title=\"Number of Years",
"data=df1) ax.set(title=\"Over Time vs Attrition\", xlabel=\"Over Time\", ylabel=\"Total\") plt.savefig('templates/graphs/raw/OverTimevsAttr.png') ax",
"for x in range(0,18,2)] categories = ['<'+str(x) for x in",
"X[:, 9] = labelencoder_X_9.fit_transform(X[:, 9]) labelencoder_X_12 = LabelEncoder() X[:, 12]",
"print(\"LLLLLLLLLLLLLLLENGHT\" + str(len(att)) +\" \" + str(len(skills))) i = 0",
"'Gender', 'JobRole', 'JobSatisfaction', 'MaritalStatus', 'MonthlyIncome', 'NumCompaniesWorked', 'OverTime', 'PercentSalaryHike', 'YearsInCurrentRole', 'YearsSinceLastPromotion']",
"LabelEncoder() X[:, 12] = labelencoder_X_12.fit_transform(X[:, 12]) p = clf.predict(X) t",
"vs Attrition\", xlabel=\"Number of Years since Promotion\", ylabel=\"Total\") plt.xticks(rotation=-30) plt.savefig('templates/graphs/raw/YSCPvsAttr.png')",
"= clf.predict(X_test) acc = accuracy_score(y_test,p)*100 flash(acc) X = [list(elem) for",
"feature_importances = pd.DataFrame(clf.feature_importances_, index=['Age', 'BusinessTravel', 'Department', 'DistanceFromHome', 'Education', 'EducationField', 'Gender',",
"clf.predict(X_test) acc = accuracy_score(y_test,p)*100 flash(acc) X = [list(elem) for elem",
"labelencoder_X_2 = LabelEncoder() X[:, 2] = labelencoder_X_2.fit_transform(X[:, 2]) labelencoder_X_5 =",
"plt.savefig('templates/graphs/raw/YSCPvsAttr.png') ax = sns.countplot(x=\"MaritalStatus\", hue=\"Attrition\", palette=\"Set1\", data=df1) ax.set(title=\"Marital Status vs",
"df = df.drop(['DailyRate', 'EmployeeCount', 'YearsAtCompany', 'TotalWorkingYears', 'JobLevel', 'HourlyRate', 'MonthlyRate', 'Over18',",
"as pd import matplotlib.pyplot as plt import seaborn as sns",
"xlabel=\"Number Of Years in Current Role\", ylabel=\"Total\") plt.xticks(rotation=-30) plt.savefig('templates/graphs/raw/YICRvsAttr.png') ax",
"labelencoder_X_7.fit_transform(X[:, 7]) labelencoder_X_9 = LabelEncoder() X[:, 9] = labelencoder_X_9.fit_transform(X[:, 9])",
"feature_importances.index ax = feature_importances.plot.bar(x='x1', y='importance', rot=90) plt.savefig('templates/graphs/raw/feature_importances.png', frameon=True) intervals =",
"range(0,18,2)] categories = ['<'+str(x) for x in range(2,18,2)] df1 =",
"palette=\"Set1\", data=df1) ax.set(title=\"Number Of Previously Worked Companies vs Attrition\", xlabel=\"Number",
"ax = feature_importances.plot.bar(x='x1', y='importance', rot=90) plt.savefig('templates/graphs/raw/feature_importances.png', frameon=True) intervals = [x",
"df1 = df df1['Distance_from_home'] = pd.cut(df.DistanceFromHome, intervals, labels=categories) ax =",
"= [x for x in range(0,32,2)] categories = ['<'+str(x) for",
"ylabel=\"Total\") plt.xticks(rotation=-30) plt.savefig('templates/graphs/raw/MIvsAttr.png') intervals = [x for x in range(18,63,3)]",
"plt.savefig('templates/graphs/raw/OverTimevsAttr.png') ax = sns.countplot(x=\"JobRole\", hue=\"Attrition\", palette=\"Set1\", data=df1) ax.set(title=\"Job Role vs",
"pd.cut(df.YearsInCurrentRole, intervals, labels=categories) ax = sns.countplot(x=\"Current_Role\", hue=\"Attrition\", palette=\"Set1\", data=df1) ax.set(title=\"Number",
"0 for row in att: X[i].insert(0, row) i = i+1",
"['<'+str(x) for x in range(2000, 22000, 2000)] df1 = df",
"for elem in data] [r.pop(0) for r in X] #print(\"#######",
"= sns.countplot(x=\"OverTime\", hue=\"Attrition\", palette=\"Set1\", data=df1) ax.set(title=\"Over Time vs Attrition\", xlabel=\"Over",
"Role vs Attrition\", xlabel=\"Number Of Years in Current Role\", ylabel=\"Total\")",
"labelencoder_y.fit_transform(y) X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.40,random_state=0) clf",
"skills[:(len(att)):] print(\"LLLLLLLLLLLLLLLENGHT\" + str(len(att)) +\" \" + str(len(skills))) i =",
"df = df[['Attrition', 'Age', 'BusinessTravel', 'Department', 'DistanceFromHome', 'Education', 'EducationField', 'Gender',",
"# print(\"TTTTTTTTTTTTThis is XXXXXXXXXXXX\") # print(X) X = np.array(X) labelencoder_X_1",
"in range(0,32,2)] categories = ['<'+str(x) for x in range(2,32,2)] df1",
"pandas as pd import matplotlib.pyplot as plt import seaborn as",
"7] = labelencoder_X_7.fit_transform(X[:, 7]) labelencoder_X_9 = LabelEncoder() X[:, 9] =",
"Hike Percentage\", ylabel=\"Total\") plt.savefig('templates/graphs/raw/PercentSalaryHikevsAttr.png') ax = sns.countplot(x=\"NumCompaniesWorked\", hue=\"Attrition\", palette=\"Set1\", data=df1)",
"Companies vs Attrition\", xlabel=\"Number Of Previously Worked Companies\", ylabel=\"Total\") plt.savefig('templates/graphs/raw/NPWCvsAttr.png')",
"df1 = df df1['Promotion'] = pd.cut(df.YearsSinceLastPromotion, intervals, labels=categories) ax =",
"ax = sns.countplot(x=\"PercentSalaryHike\", hue=\"Attrition\", palette=\"Set1\", data=df1) ax.set(title=\"Salary Hike Percentage vs",
"range(0,22,2)] categories = ['<'+str(x) for x in range(2,22,2)] df1 =",
"= df df1['Age_Categories'] = pd.cut(df.Age, intervals, labels=categories) ax = sns.countplot(x=\"Age_Categories\",",
"= labelencoder_X_9.fit_transform(X[:, 9]) labelencoder_X_12 = LabelEncoder() X[:, 12] = labelencoder_X_12.fit_transform(X[:,",
"plt.savefig('templates/graphs/raw/MSvsAttr.png') def run(data): df = pd.read_csv('original_dataset.csv') skills = df['Skills'].tolist() #",
"= feature_importances.index ax = feature_importances.plot.bar(x='x1', y='importance', rot=90) plt.savefig('templates/graphs/raw/feature_importances.png', frameon=True) intervals",
"'Gender', 'JobRole', 'JobSatisfaction', 'MaritalStatus', 'MonthlyIncome', 'NumCompaniesWorked', 'OverTime', 'PercentSalaryHike', 'YearsInCurrentRole', 'YearsSinceLastPromotion'],columns=['importance']).sort_values('importance',ascending=False)",
"Attrition\", xlabel=\"Job Role\", ylabel=\"Total\") plt.xticks(rotation=70) plt.savefig('templates/graphs/raw/JobRolevsAttr.png') intervals = [x for",
"ylabel=\"Total\") plt.savefig('templates/graphs/raw/MSvsAttr.png') def run(data): df = pd.read_csv('original_dataset.csv') skills = df['Skills'].tolist()",
"palette=\"Set1\", data=df1) ax.set(title=\"Age vs Attrition\", xlabel=\"Age group\", ylabel=\"Total\") plt.xticks(rotation=-30) plt.savefig('templates/graphs/raw/AgevsAttr.png')",
"= feature_importances.plot.bar(x='x1', y='importance', rot=90) plt.savefig('templates/graphs/raw/feature_importances.png', frameon=True) intervals = [x for",
"Current Role vs Attrition\", xlabel=\"Number Of Years in Current Role\",",
"from sklearn.ensemble import RandomForestClassifier from sklearn.metrics import accuracy_score from flask",
"ax = sns.countplot(x=\"MaritalStatus\", hue=\"Attrition\", palette=\"Set1\", data=df1) ax.set(title=\"Marital Status vs Attrition\",",
"elem in data] [r.pop(0) for r in X] #print(\"####### THIS",
"range(2,22,2)] df1 = df df1['Current_Role'] = pd.cut(df.YearsInCurrentRole, intervals, labels=categories) ax",
"from sklearn.preprocessing import LabelEncoder from sklearn.ensemble import RandomForestClassifier from sklearn.metrics",
"for x in range(2,18,2)] df1 = df df1['Promotion'] = pd.cut(df.YearsSinceLastPromotion,",
"'JobSatisfaction', 'MaritalStatus', 'MonthlyIncome', 'NumCompaniesWorked', 'OverTime', 'PercentSalaryHike', 'YearsInCurrentRole', 'YearsSinceLastPromotion']] #print(\"These re",
"[x for x in range(0,32,2)] categories = ['<'+str(x) for x",
"ax.set(title=\"Over Time vs Attrition\", xlabel=\"Over Time\", ylabel=\"Total\") plt.savefig('templates/graphs/raw/OverTimevsAttr.png') ax =",
"pd.DataFrame(clf.feature_importances_, index=['Age', 'BusinessTravel', 'Department', 'DistanceFromHome', 'Education', 'EducationField', 'Gender', 'JobRole', 'JobSatisfaction',",
"p = clf.predict(X_test) acc = accuracy_score(y_test,p)*100 flash(acc) X = [list(elem)",
"plt.savefig('templates/graphs/raw/PercentSalaryHikevsAttr.png') ax = sns.countplot(x=\"NumCompaniesWorked\", hue=\"Attrition\", palette=\"Set1\", data=df1) ax.set(title=\"Number Of Previously",
"9]) labelencoder_X_12 = LabelEncoder() X[:, 12] = labelencoder_X_12.fit_transform(X[:, 12]) p",
"RandomForestClassifier(n_estimators=200) clf.fit(X_train,y_train) p = clf.predict(X_test) acc = accuracy_score(y_test,p)*100 flash(acc) X",
"2] = labelencoder_X_2.fit_transform(X[:, 2]) labelencoder_X_5 = LabelEncoder() X[:, 5] =",
"of Years since Promotion\", ylabel=\"Total\") plt.xticks(rotation=-30) plt.savefig('templates/graphs/raw/YSCPvsAttr.png') ax = sns.countplot(x=\"MaritalStatus\",",
"ax.set(title=\"Number of Years since Promotion vs Attrition\", xlabel=\"Number of Years",
"= labelencoder_X_1.fit_transform(X[:, 1]) labelencoder_X_2 = LabelEncoder() X[:, 2] = labelencoder_X_2.fit_transform(X[:,",
"[list(elem) for elem in data] [r.pop(0) for r in X]",
"'YearsAtCompany', 'TotalWorkingYears', 'JobLevel', 'HourlyRate', 'MonthlyRate', 'Over18', 'StandardHours', 'EnvironmentSatisfaction', 'JobInvolvement', 'PerformanceRating',",
"from sklearn.model_selection import train_test_split from sklearn.preprocessing import LabelEncoder from sklearn.ensemble",
"['<'+str(x) for x in range(2,32,2)] df1 = df df1['Distance_from_home'] =",
"vs Attrition\", xlabel=\"Distance\", ylabel=\"Total\") plt.xticks(rotation=-30) plt.savefig('templates/graphs/raw/DistanceFromHomevsAttr.png') ax = sns.countplot(x=\"PercentSalaryHike\", hue=\"Attrition\",",
"palette=\"Set1\", data=df1) ax.set(title=\"Salary Hike Percentage vs Attrition\", xlabel=\"Salary Hike Percentage\",",
"XXXX##########\") #print(X) att = check(X, clf) skills = skills[:(len(att)):] print(\"LLLLLLLLLLLLLLLENGHT\"",
"categories = ['<'+str(x) for x in range(2,32,2)] df1 = df",
"'NumCompaniesWorked', 'OverTime', 'PercentSalaryHike', 'YearsInCurrentRole', 'YearsSinceLastPromotion'] analyze(df, clf) df1.to_csv('dataset1.csv') return att,",
"= sns.countplot(x=\"PercentSalaryHike\", hue=\"Attrition\", palette=\"Set1\", data=df1) ax.set(title=\"Salary Hike Percentage vs Attrition\",",
"= labelencoder_X_12.fit_transform(X[:, 12]) p = clf.predict(X) t = () for",
"= () for x in p: if x == 0:",
"= sns.countplot(x=\"MaritalStatus\", hue=\"Attrition\", palette=\"Set1\", data=df1) ax.set(title=\"Marital Status vs Attrition\", xlabel=\"Marital",
"'MaritalStatus', 'MonthlyIncome', 'NumCompaniesWorked', 'OverTime', 'PercentSalaryHike', 'YearsInCurrentRole', 'YearsSinceLastPromotion']] #print(\"These re SKILSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSS\")",
"intervals = [x for x in range(0,32,2)] categories = ['<'+str(x)",
"Worked Companies vs Attrition\", xlabel=\"Number Of Previously Worked Companies\", ylabel=\"Total\")",
"sns.countplot(x=\"Age_Categories\", hue=\"Attrition\", palette=\"Set1\", data=df1) ax.set(title=\"Age vs Attrition\", xlabel=\"Age group\", ylabel=\"Total\")",
"palette=\"Set1\", data=df1) ax.set(title=\"Monthly Income vs Attrition\", xlabel=\"Income group\", ylabel=\"Total\") plt.xticks(rotation=-30)",
"= pd.cut(df.Age, intervals, labels=categories) ax = sns.countplot(x=\"Age_Categories\", hue=\"Attrition\", palette=\"Set1\", data=df1)",
"labels=categories) ax = sns.countplot(x=\"Distance_from_home\", hue=\"Attrition\", palette=\"Set1\", data=df1) ax.set(title=\"Distance from home",
"str(len(skills))) i = 0 for row in att: X[i].insert(0, row)",
"df1 = df df1['Income_Categories'] = pd.cut(df.MonthlyIncome, intervals, labels=categories) ax =",
"'MaritalStatus', 'MonthlyIncome', 'NumCompaniesWorked', 'OverTime', 'PercentSalaryHike', 'YearsInCurrentRole', 'YearsSinceLastPromotion'] analyze(df, clf) df1.to_csv('dataset1.csv')",
"df1['Age_Categories'] = pd.cut(df.Age, intervals, labels=categories) ax = sns.countplot(x=\"Age_Categories\", hue=\"Attrition\", palette=\"Set1\",",
"a = 'Yes' t = t+(a,) return t def analyze(df,",
"= 'No' else: a = 'Yes' t = t+(a,) return",
"range(2,32,2)] df1 = df df1['Distance_from_home'] = pd.cut(df.DistanceFromHome, intervals, labels=categories) ax",
"pd.cut(df.DistanceFromHome, intervals, labels=categories) ax = sns.countplot(x=\"Distance_from_home\", hue=\"Attrition\", palette=\"Set1\", data=df1) ax.set(title=\"Distance",
"= pd.DataFrame(clf.feature_importances_, index=['Age', 'BusinessTravel', 'Department', 'DistanceFromHome', 'Education', 'EducationField', 'Gender', 'JobRole',",
"7]) labelencoder_X_9 = LabelEncoder() X[:, 9] = labelencoder_X_9.fit_transform(X[:, 9]) labelencoder_X_12",
"plt.savefig('templates/graphs/raw/JobRolevsAttr.png') intervals = [x for x in range(0,18,2)] categories =",
"X = X.astype(float) labelencoder_y = LabelEncoder() y = labelencoder_y.fit_transform(y) X_train,",
"for r in X] #print(\"####### THIS IS XXXX##########\") #print(X) att",
"palette=\"Set1\", data=df1) ax.set(title=\"Marital Status vs Attrition\", xlabel=\"Marital Status\", ylabel=\"Total\") plt.savefig('templates/graphs/raw/MSvsAttr.png')",
"XXXXXXXXXXXX\") # print(X) X = np.array(X) labelencoder_X_1 = LabelEncoder() X[:,",
"x in range(0, 22000, 2000)] categories = ['<'+str(x) for x",
"df1['Income_Categories'] = pd.cut(df.MonthlyIncome, intervals, labels=categories) ax = sns.countplot(x=\"Income_Categories\", hue=\"Attrition\", palette=\"Set1\",",
"= pd.DataFrame(X) df1.columns=['Attrition', 'Age', 'BusinessTravel', 'Department', 'DistanceFromHome', 'Education', 'EducationField', 'Gender',",
"p: if x == 0: a = 'No' else: a",
"labelencoder_X_5 = LabelEncoder() X[:, 5] = labelencoder_X_5.fit_transform(X[:, 5]) labelencoder_X_6 =",
"Of Previously Worked Companies\", ylabel=\"Total\") plt.savefig('templates/graphs/raw/NPWCvsAttr.png') intervals = [x for",
"#print(skills) X = df.iloc[:, 1:].values y = df.iloc[:, 0].values labelencoder_X_1",
"Worked Companies\", ylabel=\"Total\") plt.savefig('templates/graphs/raw/NPWCvsAttr.png') intervals = [x for x in",
"att = check(X, clf) skills = skills[:(len(att)):] print(\"LLLLLLLLLLLLLLLENGHT\" + str(len(att))",
"print(X) X = np.array(X) labelencoder_X_1 = LabelEncoder() X[:, 1] =",
"numpy as np def check(X, clf): # print(\"TTTTTTTTTTTTThis is XXXXXXXXXXXX\")",
"Attrition\", xlabel=\"Income group\", ylabel=\"Total\") plt.xticks(rotation=-30) plt.savefig('templates/graphs/raw/MIvsAttr.png') intervals = [x for",
"np.array(X) labelencoder_X_1 = LabelEncoder() X[:, 1] = labelencoder_X_1.fit_transform(X[:, 1]) labelencoder_X_2",
"ax = sns.countplot(x=\"NumCompaniesWorked\", hue=\"Attrition\", palette=\"Set1\", data=df1) ax.set(title=\"Number Of Previously Worked",
"'Gender', 'JobRole', 'JobSatisfaction', 'MaritalStatus', 'MonthlyIncome', 'NumCompaniesWorked', 'OverTime', 'PercentSalaryHike', 'YearsInCurrentRole', 'YearsSinceLastPromotion']]",
"= sns.countplot(x=\"Current_Role\", hue=\"Attrition\", palette=\"Set1\", data=df1) ax.set(title=\"Number Of Years in Current",
"df1.columns=['Attrition', 'Age', 'BusinessTravel', 'Department', 'DistanceFromHome', 'Education', 'EducationField', 'Gender', 'JobRole', 'JobSatisfaction',",
"intervals, labels=categories) ax = sns.countplot(x=\"Promotion\", hue=\"Attrition\", palette=\"Set1\", data=df1) ax.set(title=\"Number of",
"clf): # print(\"TTTTTTTTTTTTThis is XXXXXXXXXXXX\") # print(X) X = np.array(X)",
"x in range(0,18,2)] categories = ['<'+str(x) for x in range(2,18,2)]",
"palette=\"Set1\", data=df1) ax.set(title=\"Over Time vs Attrition\", xlabel=\"Over Time\", ylabel=\"Total\") plt.savefig('templates/graphs/raw/OverTimevsAttr.png')",
"= labelencoder_X_5.fit_transform(X[:, 5]) labelencoder_X_6 = LabelEncoder() X[:, 6] = labelencoder_X_6.fit_transform(X[:,",
"1:].values y = df.iloc[:, 0].values labelencoder_X_1 = LabelEncoder() X[:, 1]",
"p = clf.predict(X) t = () for x in p:",
"df1 = df df1['Current_Role'] = pd.cut(df.YearsInCurrentRole, intervals, labels=categories) ax =",
"= ['<'+str(x) for x in range(21,63,3)] df1 = df df1['Age_Categories']",
"range(2000, 22000, 2000)] df1 = df df1['Income_Categories'] = pd.cut(df.MonthlyIncome, intervals,",
"vs Attrition\", xlabel=\"Salary Hike Percentage\", ylabel=\"Total\") plt.savefig('templates/graphs/raw/PercentSalaryHikevsAttr.png') ax = sns.countplot(x=\"NumCompaniesWorked\",",
"'MonthlyIncome', 'NumCompaniesWorked', 'OverTime', 'PercentSalaryHike', 'YearsInCurrentRole', 'YearsSinceLastPromotion'],columns=['importance']).sort_values('importance',ascending=False) feature_importances['x1'] = feature_importances.index ax",
"labelencoder_X_7 = LabelEncoder() X[:, 7] = labelencoder_X_7.fit_transform(X[:, 7]) labelencoder_X_9 =",
"= [x for x in range(18,63,3)] categories = ['<'+str(x) for",
"in data] [r.pop(0) for r in X] #print(\"####### THIS IS",
"flash(acc) X = [list(elem) for elem in data] [r.pop(0) for",
"= LabelEncoder() X[:, 6] = labelencoder_X_6.fit_transform(X[:, 6]) labelencoder_X_7 = LabelEncoder()",
"def run(data): df = pd.read_csv('original_dataset.csv') skills = df['Skills'].tolist() # print(\"SKKKKKKKKKKKKKKKILLLLLLLLLLLLLLLS\")",
"= df.iloc[:, 0].values labelencoder_X_1 = LabelEncoder() X[:, 1] = labelencoder_X_1.fit_transform(X[:,",
"intervals, labels=categories) ax = sns.countplot(x=\"Current_Role\", hue=\"Attrition\", palette=\"Set1\", data=df1) ax.set(title=\"Number Of",
"import matplotlib.pyplot as plt import seaborn as sns from sklearn.model_selection",
"1]) labelencoder_X_2 = LabelEncoder() X[:, 2] = labelencoder_X_2.fit_transform(X[:, 2]) labelencoder_X_5",
"att: X[i].insert(0, row) i = i+1 df1 = pd.DataFrame(X) df1.columns=['Attrition',",
"= i+1 df1 = pd.DataFrame(X) df1.columns=['Attrition', 'Age', 'BusinessTravel', 'Department', 'DistanceFromHome',",
"'Education', 'EducationField', 'Gender', 'JobRole', 'JobSatisfaction', 'MaritalStatus', 'MonthlyIncome', 'NumCompaniesWorked', 'OverTime', 'PercentSalaryHike',",
"re SKILSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSS\") #print(skills) X = df.iloc[:, 1:].values y = df.iloc[:,",
"is XXXXXXXXXXXX\") # print(X) X = np.array(X) labelencoder_X_1 = LabelEncoder()",
"for x in range(0,22,2)] categories = ['<'+str(x) for x in",
"'Over18', 'StandardHours', 'EnvironmentSatisfaction', 'JobInvolvement', 'PerformanceRating', 'TrainingTimesLastYear', 'RelationshipSatisfaction', 'StockOptionLevel', 'WorkLifeBalance', 'YearsWithCurrManager'],",
"for x in p: if x == 0: a =",
"intervals, labels=categories) ax = sns.countplot(x=\"Income_Categories\", hue=\"Attrition\", palette=\"Set1\", data=df1) ax.set(title=\"Monthly Income",
"vs Attrition\", xlabel=\"Over Time\", ylabel=\"Total\") plt.savefig('templates/graphs/raw/OverTimevsAttr.png') ax = sns.countplot(x=\"JobRole\", hue=\"Attrition\",",
"ylabel=\"Total\") plt.savefig('templates/graphs/raw/OverTimevsAttr.png') ax = sns.countplot(x=\"JobRole\", hue=\"Attrition\", palette=\"Set1\", data=df1) ax.set(title=\"Job Role",
"sns.countplot(x=\"Distance_from_home\", hue=\"Attrition\", palette=\"Set1\", data=df1) ax.set(title=\"Distance from home vs Attrition\", xlabel=\"Distance\",",
"in range(0,18,2)] categories = ['<'+str(x) for x in range(2,18,2)] df1",
"clf.predict(X) t = () for x in p: if x",
"xlabel=\"Income group\", ylabel=\"Total\") plt.xticks(rotation=-30) plt.savefig('templates/graphs/raw/MIvsAttr.png') intervals = [x for x",
"= sns.countplot(x=\"JobRole\", hue=\"Attrition\", palette=\"Set1\", data=df1) ax.set(title=\"Job Role vs Attrition\", xlabel=\"Job",
"index=['Age', 'BusinessTravel', 'Department', 'DistanceFromHome', 'Education', 'EducationField', 'Gender', 'JobRole', 'JobSatisfaction', 'MaritalStatus',",
"ylabel=\"Total\") plt.xticks(rotation=-30) plt.savefig('templates/graphs/raw/AgevsAttr.png') intervals = [x for x in range(0,32,2)]",
"df1 = pd.DataFrame(X) df1.columns=['Attrition', 'Age', 'BusinessTravel', 'Department', 'DistanceFromHome', 'Education', 'EducationField',",
"'Yes' t = t+(a,) return t def analyze(df, clf): feature_importances",
"x in range(2,32,2)] df1 = df df1['Distance_from_home'] = pd.cut(df.DistanceFromHome, intervals,",
"plt.savefig('templates/graphs/raw/NPWCvsAttr.png') intervals = [x for x in range(0,22,2)] categories =",
"plt.xticks(rotation=-30) plt.savefig('templates/graphs/raw/YSCPvsAttr.png') ax = sns.countplot(x=\"MaritalStatus\", hue=\"Attrition\", palette=\"Set1\", data=df1) ax.set(title=\"Marital Status",
"= LabelEncoder() X[:, 1] = labelencoder_X_1.fit_transform(X[:, 1]) labelencoder_X_2 = LabelEncoder()",
"clf.fit(X_train,y_train) p = clf.predict(X_test) acc = accuracy_score(y_test,p)*100 flash(acc) X =",
"'WorkLifeBalance', 'YearsWithCurrManager'], axis=1) df = df[['Attrition', 'Age', 'BusinessTravel', 'Department', 'DistanceFromHome',",
"Time\", ylabel=\"Total\") plt.savefig('templates/graphs/raw/OverTimevsAttr.png') ax = sns.countplot(x=\"JobRole\", hue=\"Attrition\", palette=\"Set1\", data=df1) ax.set(title=\"Job",
"= df df1['Current_Role'] = pd.cut(df.YearsInCurrentRole, intervals, labels=categories) ax = sns.countplot(x=\"Current_Role\",",
"print(\"TTTTTTTTTTTTThis is XXXXXXXXXXXX\") # print(X) X = np.array(X) labelencoder_X_1 =",
"in range(2,32,2)] df1 = df df1['Distance_from_home'] = pd.cut(df.DistanceFromHome, intervals, labels=categories)",
"ax = sns.countplot(x=\"OverTime\", hue=\"Attrition\", palette=\"Set1\", data=df1) ax.set(title=\"Over Time vs Attrition\",",
"= sns.countplot(x=\"Income_Categories\", hue=\"Attrition\", palette=\"Set1\", data=df1) ax.set(title=\"Monthly Income vs Attrition\", xlabel=\"Income",
"intervals = [x for x in range(18,63,3)] categories = ['<'+str(x)",
"xlabel=\"Distance\", ylabel=\"Total\") plt.xticks(rotation=-30) plt.savefig('templates/graphs/raw/DistanceFromHomevsAttr.png') ax = sns.countplot(x=\"PercentSalaryHike\", hue=\"Attrition\", palette=\"Set1\", data=df1)",
"vs Attrition\", xlabel=\"Number Of Previously Worked Companies\", ylabel=\"Total\") plt.savefig('templates/graphs/raw/NPWCvsAttr.png') intervals",
"labelencoder_X_2.fit_transform(X[:, 2]) labelencoder_X_5 = LabelEncoder() X[:, 5] = labelencoder_X_5.fit_transform(X[:, 5])",
"= LabelEncoder() X[:, 12] = labelencoder_X_12.fit_transform(X[:, 12]) p = clf.predict(X)",
"df1 = df df1['Age_Categories'] = pd.cut(df.Age, intervals, labels=categories) ax =",
"t = () for x in p: if x ==",
"x in range(0,22,2)] categories = ['<'+str(x) for x in range(2,22,2)]",
"df.drop(['DailyRate', 'EmployeeCount', 'YearsAtCompany', 'TotalWorkingYears', 'JobLevel', 'HourlyRate', 'MonthlyRate', 'Over18', 'StandardHours', 'EnvironmentSatisfaction',",
"<gh_stars>0 import pandas as pd import matplotlib.pyplot as plt import",
"vs Attrition\", xlabel=\"Number Of Years in Current Role\", ylabel=\"Total\") plt.xticks(rotation=-30)",
"frameon=True) intervals = [x for x in range(0, 22000, 2000)]",
"plt.xticks(rotation=70) plt.savefig('templates/graphs/raw/JobRolevsAttr.png') intervals = [x for x in range(0,18,2)] categories",
"RandomForestClassifier from sklearn.metrics import accuracy_score from flask import flash import",
"'OverTime', 'PercentSalaryHike', 'YearsInCurrentRole', 'YearsSinceLastPromotion'] analyze(df, clf) df1.to_csv('dataset1.csv') return att, skills",
"Years since Promotion\", ylabel=\"Total\") plt.xticks(rotation=-30) plt.savefig('templates/graphs/raw/YSCPvsAttr.png') ax = sns.countplot(x=\"MaritalStatus\", hue=\"Attrition\",",
"= pd.cut(df.YearsInCurrentRole, intervals, labels=categories) ax = sns.countplot(x=\"Current_Role\", hue=\"Attrition\", palette=\"Set1\", data=df1)",
"'JobRole', 'JobSatisfaction', 'MaritalStatus', 'MonthlyIncome', 'NumCompaniesWorked', 'OverTime', 'PercentSalaryHike', 'YearsInCurrentRole', 'YearsSinceLastPromotion']] #print(\"These",
"5]) labelencoder_X_6 = LabelEncoder() X[:, 6] = labelencoder_X_6.fit_transform(X[:, 6]) labelencoder_X_7",
"range(2,18,2)] df1 = df df1['Promotion'] = pd.cut(df.YearsSinceLastPromotion, intervals, labels=categories) ax",
"df1['Promotion'] = pd.cut(df.YearsSinceLastPromotion, intervals, labels=categories) ax = sns.countplot(x=\"Promotion\", hue=\"Attrition\", palette=\"Set1\",",
"12]) X = X.astype(float) labelencoder_y = LabelEncoder() y = labelencoder_y.fit_transform(y)",
"plt.savefig('templates/graphs/raw/AgevsAttr.png') intervals = [x for x in range(0,32,2)] categories =",
"Current Role\", ylabel=\"Total\") plt.xticks(rotation=-30) plt.savefig('templates/graphs/raw/YICRvsAttr.png') ax = sns.countplot(x=\"OverTime\", hue=\"Attrition\", palette=\"Set1\",",
"ylabel=\"Total\") plt.xticks(rotation=70) plt.savefig('templates/graphs/raw/JobRolevsAttr.png') intervals = [x for x in range(0,18,2)]",
"feature_importances['x1'] = feature_importances.index ax = feature_importances.plot.bar(x='x1', y='importance', rot=90) plt.savefig('templates/graphs/raw/feature_importances.png', frameon=True)",
"plt.xticks(rotation=-30) plt.savefig('templates/graphs/raw/DistanceFromHomevsAttr.png') ax = sns.countplot(x=\"PercentSalaryHike\", hue=\"Attrition\", palette=\"Set1\", data=df1) ax.set(title=\"Salary Hike",
"ax = sns.countplot(x=\"Current_Role\", hue=\"Attrition\", palette=\"Set1\", data=df1) ax.set(title=\"Number Of Years in",
"= pd.read_csv('original_dataset.csv') skills = df['Skills'].tolist() # print(\"SKKKKKKKKKKKKKKKILLLLLLLLLLLLLLLS\") # print(skills) df",
"ylabel=\"Total\") plt.xticks(rotation=-30) plt.savefig('templates/graphs/raw/YSCPvsAttr.png') ax = sns.countplot(x=\"MaritalStatus\", hue=\"Attrition\", palette=\"Set1\", data=df1) ax.set(title=\"Marital",
"'EmployeeCount', 'YearsAtCompany', 'TotalWorkingYears', 'JobLevel', 'HourlyRate', 'MonthlyRate', 'Over18', 'StandardHours', 'EnvironmentSatisfaction', 'JobInvolvement',",
"labelencoder_X_6 = LabelEncoder() X[:, 6] = labelencoder_X_6.fit_transform(X[:, 6]) labelencoder_X_7 =",
"ylabel=\"Total\") plt.savefig('templates/graphs/raw/PercentSalaryHikevsAttr.png') ax = sns.countplot(x=\"NumCompaniesWorked\", hue=\"Attrition\", palette=\"Set1\", data=df1) ax.set(title=\"Number Of",
"'StandardHours', 'EnvironmentSatisfaction', 'JobInvolvement', 'PerformanceRating', 'TrainingTimesLastYear', 'RelationshipSatisfaction', 'StockOptionLevel', 'WorkLifeBalance', 'YearsWithCurrManager'], axis=1)",
"hue=\"Attrition\", palette=\"Set1\", data=df1) ax.set(title=\"Over Time vs Attrition\", xlabel=\"Over Time\", ylabel=\"Total\")",
"in range(2,18,2)] df1 = df df1['Promotion'] = pd.cut(df.YearsSinceLastPromotion, intervals, labels=categories)",
"22000, 2000)] df1 = df df1['Income_Categories'] = pd.cut(df.MonthlyIncome, intervals, labels=categories)",
"xlabel=\"Number of Years since Promotion\", ylabel=\"Total\") plt.xticks(rotation=-30) plt.savefig('templates/graphs/raw/YSCPvsAttr.png') ax =",
"Attrition\", xlabel=\"Marital Status\", ylabel=\"Total\") plt.savefig('templates/graphs/raw/MSvsAttr.png') def run(data): df = pd.read_csv('original_dataset.csv')",
"= df.drop(['DailyRate', 'EmployeeCount', 'YearsAtCompany', 'TotalWorkingYears', 'JobLevel', 'HourlyRate', 'MonthlyRate', 'Over18', 'StandardHours',",
"xlabel=\"Salary Hike Percentage\", ylabel=\"Total\") plt.savefig('templates/graphs/raw/PercentSalaryHikevsAttr.png') ax = sns.countplot(x=\"NumCompaniesWorked\", hue=\"Attrition\", palette=\"Set1\",",
"ax.set(title=\"Job Role vs Attrition\", xlabel=\"Job Role\", ylabel=\"Total\") plt.xticks(rotation=70) plt.savefig('templates/graphs/raw/JobRolevsAttr.png') intervals",
"df df1['Current_Role'] = pd.cut(df.YearsInCurrentRole, intervals, labels=categories) ax = sns.countplot(x=\"Current_Role\", hue=\"Attrition\",",
"+\" \" + str(len(skills))) i = 0 for row in",
"= accuracy_score(y_test,p)*100 flash(acc) X = [list(elem) for elem in data]",
"for x in range(2000, 22000, 2000)] df1 = df df1['Income_Categories']",
"print(\"SKKKKKKKKKKKKKKKILLLLLLLLLLLLLLLS\") # print(skills) df = df.drop(['DailyRate', 'EmployeeCount', 'YearsAtCompany', 'TotalWorkingYears', 'JobLevel',",
"as sns from sklearn.model_selection import train_test_split from sklearn.preprocessing import LabelEncoder",
"data=df1) ax.set(title=\"Salary Hike Percentage vs Attrition\", xlabel=\"Salary Hike Percentage\", ylabel=\"Total\")",
"plt.savefig('templates/graphs/raw/MIvsAttr.png') intervals = [x for x in range(18,63,3)] categories =",
"= LabelEncoder() X[:, 9] = labelencoder_X_9.fit_transform(X[:, 9]) labelencoder_X_12 = LabelEncoder()",
"Attrition\", xlabel=\"Number of Years since Promotion\", ylabel=\"Total\") plt.xticks(rotation=-30) plt.savefig('templates/graphs/raw/YSCPvsAttr.png') ax",
"['<'+str(x) for x in range(2,22,2)] df1 = df df1['Current_Role'] =",
"x in range(0,32,2)] categories = ['<'+str(x) for x in range(2,32,2)]",
"Attrition\", xlabel=\"Over Time\", ylabel=\"Total\") plt.savefig('templates/graphs/raw/OverTimevsAttr.png') ax = sns.countplot(x=\"JobRole\", hue=\"Attrition\", palette=\"Set1\",",
"import numpy as np def check(X, clf): # print(\"TTTTTTTTTTTTThis is",
"#print(\"####### THIS IS XXXX##########\") #print(X) att = check(X, clf) skills",
"t def analyze(df, clf): feature_importances = pd.DataFrame(clf.feature_importances_, index=['Age', 'BusinessTravel', 'Department',",
"data=df1) ax.set(title=\"Job Role vs Attrition\", xlabel=\"Job Role\", ylabel=\"Total\") plt.xticks(rotation=70) plt.savefig('templates/graphs/raw/JobRolevsAttr.png')",
"# print(X) X = np.array(X) labelencoder_X_1 = LabelEncoder() X[:, 1]",
"labelencoder_X_6.fit_transform(X[:, 6]) labelencoder_X_7 = LabelEncoder() X[:, 7] = labelencoder_X_7.fit_transform(X[:, 7])",
"[x for x in range(18,63,3)] categories = ['<'+str(x) for x",
"data=df1) ax.set(title=\"Monthly Income vs Attrition\", xlabel=\"Income group\", ylabel=\"Total\") plt.xticks(rotation=-30) plt.savefig('templates/graphs/raw/MIvsAttr.png')",
"xlabel=\"Number Of Previously Worked Companies\", ylabel=\"Total\") plt.savefig('templates/graphs/raw/NPWCvsAttr.png') intervals = [x",
"'YearsSinceLastPromotion'],columns=['importance']).sort_values('importance',ascending=False) feature_importances['x1'] = feature_importances.index ax = feature_importances.plot.bar(x='x1', y='importance', rot=90) plt.savefig('templates/graphs/raw/feature_importances.png',",
"'BusinessTravel', 'Department', 'DistanceFromHome', 'Education', 'EducationField', 'Gender', 'JobRole', 'JobSatisfaction', 'MaritalStatus', 'MonthlyIncome',",
"plt.savefig('templates/graphs/raw/DistanceFromHomevsAttr.png') ax = sns.countplot(x=\"PercentSalaryHike\", hue=\"Attrition\", palette=\"Set1\", data=df1) ax.set(title=\"Salary Hike Percentage",
"vs Attrition\", xlabel=\"Job Role\", ylabel=\"Total\") plt.xticks(rotation=70) plt.savefig('templates/graphs/raw/JobRolevsAttr.png') intervals = [x",
"12] = labelencoder_X_12.fit_transform(X[:, 12]) p = clf.predict(X) t = ()",
"ax = sns.countplot(x=\"JobRole\", hue=\"Attrition\", palette=\"Set1\", data=df1) ax.set(title=\"Job Role vs Attrition\",",
"labelencoder_X_12.fit_transform(X[:, 12]) X = X.astype(float) labelencoder_y = LabelEncoder() y =",
"np def check(X, clf): # print(\"TTTTTTTTTTTTThis is XXXXXXXXXXXX\") # print(X)",
"= 0 for row in att: X[i].insert(0, row) i =",
"check(X, clf): # print(\"TTTTTTTTTTTTThis is XXXXXXXXXXXX\") # print(X) X =",
"= LabelEncoder() X[:, 12] = labelencoder_X_12.fit_transform(X[:, 12]) X = X.astype(float)",
"from flask import flash import numpy as np def check(X,",
"y_test = train_test_split(X, y, test_size=0.40,random_state=0) clf = RandomForestClassifier(n_estimators=200) clf.fit(X_train,y_train) p",
"data=df1) ax.set(title=\"Number Of Years in Current Role vs Attrition\", xlabel=\"Number",
"= clf.predict(X) t = () for x in p: if",
"= LabelEncoder() y = labelencoder_y.fit_transform(y) X_train, X_test, y_train, y_test =",
"ax.set(title=\"Distance from home vs Attrition\", xlabel=\"Distance\", ylabel=\"Total\") plt.xticks(rotation=-30) plt.savefig('templates/graphs/raw/DistanceFromHomevsAttr.png') ax",
"= df['Skills'].tolist() # print(\"SKKKKKKKKKKKKKKKILLLLLLLLLLLLLLLS\") # print(skills) df = df.drop(['DailyRate', 'EmployeeCount',",
"home vs Attrition\", xlabel=\"Distance\", ylabel=\"Total\") plt.xticks(rotation=-30) plt.savefig('templates/graphs/raw/DistanceFromHomevsAttr.png') ax = sns.countplot(x=\"PercentSalaryHike\",",
"for x in range(0,32,2)] categories = ['<'+str(x) for x in",
"'Department', 'DistanceFromHome', 'Education', 'EducationField', 'Gender', 'JobRole', 'JobSatisfaction', 'MaritalStatus', 'MonthlyIncome', 'NumCompaniesWorked',",
"X[:, 5] = labelencoder_X_5.fit_transform(X[:, 5]) labelencoder_X_6 = LabelEncoder() X[:, 6]",
"x == 0: a = 'No' else: a = 'Yes'",
"= 'Yes' t = t+(a,) return t def analyze(df, clf):",
"= np.array(X) labelencoder_X_1 = LabelEncoder() X[:, 1] = labelencoder_X_1.fit_transform(X[:, 1])",
"in range(2,22,2)] df1 = df df1['Current_Role'] = pd.cut(df.YearsInCurrentRole, intervals, labels=categories)",
"LabelEncoder() X[:, 5] = labelencoder_X_5.fit_transform(X[:, 5]) labelencoder_X_6 = LabelEncoder() X[:,",
"= df df1['Promotion'] = pd.cut(df.YearsSinceLastPromotion, intervals, labels=categories) ax = sns.countplot(x=\"Promotion\",",
"LabelEncoder() X[:, 6] = labelencoder_X_6.fit_transform(X[:, 6]) labelencoder_X_7 = LabelEncoder() X[:,",
"for x in range(2,32,2)] df1 = df df1['Distance_from_home'] = pd.cut(df.DistanceFromHome,",
"X] #print(\"####### THIS IS XXXX##########\") #print(X) att = check(X, clf)",
"= labelencoder_X_6.fit_transform(X[:, 6]) labelencoder_X_7 = LabelEncoder() X[:, 7] = labelencoder_X_7.fit_transform(X[:,",
"check(X, clf) skills = skills[:(len(att)):] print(\"LLLLLLLLLLLLLLLENGHT\" + str(len(att)) +\" \"",
"df.iloc[:, 0].values labelencoder_X_1 = LabelEncoder() X[:, 1] = labelencoder_X_1.fit_transform(X[:, 1])",
"palette=\"Set1\", data=df1) ax.set(title=\"Number of Years since Promotion vs Attrition\", xlabel=\"Number",
"= LabelEncoder() X[:, 7] = labelencoder_X_7.fit_transform(X[:, 7]) labelencoder_X_9 = LabelEncoder()",
"LabelEncoder from sklearn.ensemble import RandomForestClassifier from sklearn.metrics import accuracy_score from",
"sns.countplot(x=\"PercentSalaryHike\", hue=\"Attrition\", palette=\"Set1\", data=df1) ax.set(title=\"Salary Hike Percentage vs Attrition\", xlabel=\"Salary",
"range(0,32,2)] categories = ['<'+str(x) for x in range(2,32,2)] df1 =",
"sklearn.preprocessing import LabelEncoder from sklearn.ensemble import RandomForestClassifier from sklearn.metrics import",
"ylabel=\"Total\") plt.xticks(rotation=-30) plt.savefig('templates/graphs/raw/YICRvsAttr.png') ax = sns.countplot(x=\"OverTime\", hue=\"Attrition\", palette=\"Set1\", data=df1) ax.set(title=\"Over",
"= pd.cut(df.YearsSinceLastPromotion, intervals, labels=categories) ax = sns.countplot(x=\"Promotion\", hue=\"Attrition\", palette=\"Set1\", data=df1)",
"Status vs Attrition\", xlabel=\"Marital Status\", ylabel=\"Total\") plt.savefig('templates/graphs/raw/MSvsAttr.png') def run(data): df",
"from sklearn.metrics import accuracy_score from flask import flash import numpy",
"as plt import seaborn as sns from sklearn.model_selection import train_test_split",
"xlabel=\"Job Role\", ylabel=\"Total\") plt.xticks(rotation=70) plt.savefig('templates/graphs/raw/JobRolevsAttr.png') intervals = [x for x",
"Attrition\", xlabel=\"Number Of Previously Worked Companies\", ylabel=\"Total\") plt.savefig('templates/graphs/raw/NPWCvsAttr.png') intervals =",
"hue=\"Attrition\", palette=\"Set1\", data=df1) ax.set(title=\"Number Of Previously Worked Companies vs Attrition\",",
"pd.DataFrame(X) df1.columns=['Attrition', 'Age', 'BusinessTravel', 'Department', 'DistanceFromHome', 'Education', 'EducationField', 'Gender', 'JobRole',",
"LabelEncoder() X[:, 9] = labelencoder_X_9.fit_transform(X[:, 9]) labelencoder_X_12 = LabelEncoder() X[:,",
"group\", ylabel=\"Total\") plt.xticks(rotation=-30) plt.savefig('templates/graphs/raw/AgevsAttr.png') intervals = [x for x in",
"'JobInvolvement', 'PerformanceRating', 'TrainingTimesLastYear', 'RelationshipSatisfaction', 'StockOptionLevel', 'WorkLifeBalance', 'YearsWithCurrManager'], axis=1) df =",
"2000)] categories = ['<'+str(x) for x in range(2000, 22000, 2000)]",
"labelencoder_X_1 = LabelEncoder() X[:, 1] = labelencoder_X_1.fit_transform(X[:, 1]) labelencoder_X_2 =",
"LabelEncoder() X[:, 12] = labelencoder_X_12.fit_transform(X[:, 12]) X = X.astype(float) labelencoder_y",
"9] = labelencoder_X_9.fit_transform(X[:, 9]) labelencoder_X_12 = LabelEncoder() X[:, 12] =",
"in range(21,63,3)] df1 = df df1['Age_Categories'] = pd.cut(df.Age, intervals, labels=categories)",
"'EnvironmentSatisfaction', 'JobInvolvement', 'PerformanceRating', 'TrainingTimesLastYear', 'RelationshipSatisfaction', 'StockOptionLevel', 'WorkLifeBalance', 'YearsWithCurrManager'], axis=1) df",
"vs Attrition\", xlabel=\"Marital Status\", ylabel=\"Total\") plt.savefig('templates/graphs/raw/MSvsAttr.png') def run(data): df =",
"df df1['Promotion'] = pd.cut(df.YearsSinceLastPromotion, intervals, labels=categories) ax = sns.countplot(x=\"Promotion\", hue=\"Attrition\",",
"pd.read_csv('original_dataset.csv') skills = df['Skills'].tolist() # print(\"SKKKKKKKKKKKKKKKILLLLLLLLLLLLLLLS\") # print(skills) df =",
"intervals, labels=categories) ax = sns.countplot(x=\"Age_Categories\", hue=\"Attrition\", palette=\"Set1\", data=df1) ax.set(title=\"Age vs",
"Role vs Attrition\", xlabel=\"Job Role\", ylabel=\"Total\") plt.xticks(rotation=70) plt.savefig('templates/graphs/raw/JobRolevsAttr.png') intervals =",
"X[:, 12] = labelencoder_X_12.fit_transform(X[:, 12]) p = clf.predict(X) t =",
"ylabel=\"Total\") plt.savefig('templates/graphs/raw/NPWCvsAttr.png') intervals = [x for x in range(0,22,2)] categories",
"X = [list(elem) for elem in data] [r.pop(0) for r",
"row in att: X[i].insert(0, row) i = i+1 df1 =",
"= ['<'+str(x) for x in range(2,18,2)] df1 = df df1['Promotion']",
"LabelEncoder() X[:, 2] = labelencoder_X_2.fit_transform(X[:, 2]) labelencoder_X_5 = LabelEncoder() X[:,",
"hue=\"Attrition\", palette=\"Set1\", data=df1) ax.set(title=\"Number of Years since Promotion vs Attrition\",",
"Of Previously Worked Companies vs Attrition\", xlabel=\"Number Of Previously Worked",
"Percentage vs Attrition\", xlabel=\"Salary Hike Percentage\", ylabel=\"Total\") plt.savefig('templates/graphs/raw/PercentSalaryHikevsAttr.png') ax =",
"labelencoder_y = LabelEncoder() y = labelencoder_y.fit_transform(y) X_train, X_test, y_train, y_test",
"xlabel=\"Marital Status\", ylabel=\"Total\") plt.savefig('templates/graphs/raw/MSvsAttr.png') def run(data): df = pd.read_csv('original_dataset.csv') skills",
"#print(X) att = check(X, clf) skills = skills[:(len(att)):] print(\"LLLLLLLLLLLLLLLENGHT\" +",
"Previously Worked Companies vs Attrition\", xlabel=\"Number Of Previously Worked Companies\",",
"intervals = [x for x in range(0, 22000, 2000)] categories",
"SKILSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSS\") #print(skills) X = df.iloc[:, 1:].values y = df.iloc[:, 0].values",
"= sns.countplot(x=\"Distance_from_home\", hue=\"Attrition\", palette=\"Set1\", data=df1) ax.set(title=\"Distance from home vs Attrition\",",
"ax = sns.countplot(x=\"Age_Categories\", hue=\"Attrition\", palette=\"Set1\", data=df1) ax.set(title=\"Age vs Attrition\", xlabel=\"Age",
"= df df1['Distance_from_home'] = pd.cut(df.DistanceFromHome, intervals, labels=categories) ax = sns.countplot(x=\"Distance_from_home\",",
"in p: if x == 0: a = 'No' else:",
"2000)] df1 = df df1['Income_Categories'] = pd.cut(df.MonthlyIncome, intervals, labels=categories) ax",
"in att: X[i].insert(0, row) i = i+1 df1 = pd.DataFrame(X)",
"Of Years in Current Role\", ylabel=\"Total\") plt.xticks(rotation=-30) plt.savefig('templates/graphs/raw/YICRvsAttr.png') ax =",
"y='importance', rot=90) plt.savefig('templates/graphs/raw/feature_importances.png', frameon=True) intervals = [x for x in",
"df df1['Income_Categories'] = pd.cut(df.MonthlyIncome, intervals, labels=categories) ax = sns.countplot(x=\"Income_Categories\", hue=\"Attrition\",",
"labelencoder_X_1.fit_transform(X[:, 1]) labelencoder_X_2 = LabelEncoder() X[:, 2] = labelencoder_X_2.fit_transform(X[:, 2])",
"in X] #print(\"####### THIS IS XXXX##########\") #print(X) att = check(X,",
"= ['<'+str(x) for x in range(2,22,2)] df1 = df df1['Current_Role']",
"acc = accuracy_score(y_test,p)*100 flash(acc) X = [list(elem) for elem in",
"import seaborn as sns from sklearn.model_selection import train_test_split from sklearn.preprocessing",
"in Current Role\", ylabel=\"Total\") plt.xticks(rotation=-30) plt.savefig('templates/graphs/raw/YICRvsAttr.png') ax = sns.countplot(x=\"OverTime\", hue=\"Attrition\",",
"Attrition\", xlabel=\"Salary Hike Percentage\", ylabel=\"Total\") plt.savefig('templates/graphs/raw/PercentSalaryHikevsAttr.png') ax = sns.countplot(x=\"NumCompaniesWorked\", hue=\"Attrition\",",
"t = t+(a,) return t def analyze(df, clf): feature_importances =",
"y = df.iloc[:, 0].values labelencoder_X_1 = LabelEncoder() X[:, 1] =",
"plt.savefig('templates/graphs/raw/feature_importances.png', frameon=True) intervals = [x for x in range(0, 22000,",
"import LabelEncoder from sklearn.ensemble import RandomForestClassifier from sklearn.metrics import accuracy_score",
"'YearsInCurrentRole', 'YearsSinceLastPromotion'],columns=['importance']).sort_values('importance',ascending=False) feature_importances['x1'] = feature_importances.index ax = feature_importances.plot.bar(x='x1', y='importance', rot=90)",
"labelencoder_X_5.fit_transform(X[:, 5]) labelencoder_X_6 = LabelEncoder() X[:, 6] = labelencoder_X_6.fit_transform(X[:, 6])",
"sns.countplot(x=\"OverTime\", hue=\"Attrition\", palette=\"Set1\", data=df1) ax.set(title=\"Over Time vs Attrition\", xlabel=\"Over Time\",",
"Role\", ylabel=\"Total\") plt.xticks(rotation=-30) plt.savefig('templates/graphs/raw/YICRvsAttr.png') ax = sns.countplot(x=\"OverTime\", hue=\"Attrition\", palette=\"Set1\", data=df1)",
"of Years since Promotion vs Attrition\", xlabel=\"Number of Years since",
"accuracy_score(y_test,p)*100 flash(acc) X = [list(elem) for elem in data] [r.pop(0)",
"r in X] #print(\"####### THIS IS XXXX##########\") #print(X) att =",
"labels=categories) ax = sns.countplot(x=\"Age_Categories\", hue=\"Attrition\", palette=\"Set1\", data=df1) ax.set(title=\"Age vs Attrition\",",
"xlabel=\"Over Time\", ylabel=\"Total\") plt.savefig('templates/graphs/raw/OverTimevsAttr.png') ax = sns.countplot(x=\"JobRole\", hue=\"Attrition\", palette=\"Set1\", data=df1)",
"group\", ylabel=\"Total\") plt.xticks(rotation=-30) plt.savefig('templates/graphs/raw/MIvsAttr.png') intervals = [x for x in",
"range(21,63,3)] df1 = df df1['Age_Categories'] = pd.cut(df.Age, intervals, labels=categories) ax",
"for x in range(18,63,3)] categories = ['<'+str(x) for x in",
"for row in att: X[i].insert(0, row) i = i+1 df1",
"import train_test_split from sklearn.preprocessing import LabelEncoder from sklearn.ensemble import RandomForestClassifier",
"'HourlyRate', 'MonthlyRate', 'Over18', 'StandardHours', 'EnvironmentSatisfaction', 'JobInvolvement', 'PerformanceRating', 'TrainingTimesLastYear', 'RelationshipSatisfaction', 'StockOptionLevel',",
"X[i].insert(0, row) i = i+1 df1 = pd.DataFrame(X) df1.columns=['Attrition', 'Age',",
"# print(\"SKKKKKKKKKKKKKKKILLLLLLLLLLLLLLLS\") # print(skills) df = df.drop(['DailyRate', 'EmployeeCount', 'YearsAtCompany', 'TotalWorkingYears',",
"pd.cut(df.Age, intervals, labels=categories) ax = sns.countplot(x=\"Age_Categories\", hue=\"Attrition\", palette=\"Set1\", data=df1) ax.set(title=\"Age",
"import RandomForestClassifier from sklearn.metrics import accuracy_score from flask import flash",
"pd.cut(df.YearsSinceLastPromotion, intervals, labels=categories) ax = sns.countplot(x=\"Promotion\", hue=\"Attrition\", palette=\"Set1\", data=df1) ax.set(title=\"Number",
"\" + str(len(skills))) i = 0 for row in att:",
"intervals = [x for x in range(0,22,2)] categories = ['<'+str(x)",
"ax.set(title=\"Monthly Income vs Attrition\", xlabel=\"Income group\", ylabel=\"Total\") plt.xticks(rotation=-30) plt.savefig('templates/graphs/raw/MIvsAttr.png') intervals",
"intervals = [x for x in range(0,18,2)] categories = ['<'+str(x)",
"in range(2000, 22000, 2000)] df1 = df df1['Income_Categories'] = pd.cut(df.MonthlyIncome,",
"axis=1) df = df[['Attrition', 'Age', 'BusinessTravel', 'Department', 'DistanceFromHome', 'Education', 'EducationField',",
"= df[['Attrition', 'Age', 'BusinessTravel', 'Department', 'DistanceFromHome', 'Education', 'EducationField', 'Gender', 'JobRole',",
"data=df1) ax.set(title=\"Age vs Attrition\", xlabel=\"Age group\", ylabel=\"Total\") plt.xticks(rotation=-30) plt.savefig('templates/graphs/raw/AgevsAttr.png') intervals",
"['<'+str(x) for x in range(2,18,2)] df1 = df df1['Promotion'] =",
"in range(18,63,3)] categories = ['<'+str(x) for x in range(21,63,3)] df1",
"seaborn as sns from sklearn.model_selection import train_test_split from sklearn.preprocessing import",
"['<'+str(x) for x in range(21,63,3)] df1 = df df1['Age_Categories'] =",
"ax.set(title=\"Age vs Attrition\", xlabel=\"Age group\", ylabel=\"Total\") plt.xticks(rotation=-30) plt.savefig('templates/graphs/raw/AgevsAttr.png') intervals =",
"== 0: a = 'No' else: a = 'Yes' t",
"Attrition\", xlabel=\"Distance\", ylabel=\"Total\") plt.xticks(rotation=-30) plt.savefig('templates/graphs/raw/DistanceFromHomevsAttr.png') ax = sns.countplot(x=\"PercentSalaryHike\", hue=\"Attrition\", palette=\"Set1\",",
"Of Years in Current Role vs Attrition\", xlabel=\"Number Of Years",
"= train_test_split(X, y, test_size=0.40,random_state=0) clf = RandomForestClassifier(n_estimators=200) clf.fit(X_train,y_train) p =",
"hue=\"Attrition\", palette=\"Set1\", data=df1) ax.set(title=\"Marital Status vs Attrition\", xlabel=\"Marital Status\", ylabel=\"Total\")",
"for x in range(21,63,3)] df1 = df df1['Age_Categories'] = pd.cut(df.Age,",
"hue=\"Attrition\", palette=\"Set1\", data=df1) ax.set(title=\"Number Of Years in Current Role vs",
"x in range(2,18,2)] df1 = df df1['Promotion'] = pd.cut(df.YearsSinceLastPromotion, intervals,",
"analyze(df, clf): feature_importances = pd.DataFrame(clf.feature_importances_, index=['Age', 'BusinessTravel', 'Department', 'DistanceFromHome', 'Education',",
"'YearsSinceLastPromotion']] #print(\"These re SKILSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSS\") #print(skills) X = df.iloc[:, 1:].values y",
"def check(X, clf): # print(\"TTTTTTTTTTTTThis is XXXXXXXXXXXX\") # print(X) X",
"categories = ['<'+str(x) for x in range(21,63,3)] df1 = df",
"rot=90) plt.savefig('templates/graphs/raw/feature_importances.png', frameon=True) intervals = [x for x in range(0,",
"y_train, y_test = train_test_split(X, y, test_size=0.40,random_state=0) clf = RandomForestClassifier(n_estimators=200) clf.fit(X_train,y_train)",
"Promotion vs Attrition\", xlabel=\"Number of Years since Promotion\", ylabel=\"Total\") plt.xticks(rotation=-30)",
"categories = ['<'+str(x) for x in range(2000, 22000, 2000)] df1",
"vs Attrition\", xlabel=\"Income group\", ylabel=\"Total\") plt.xticks(rotation=-30) plt.savefig('templates/graphs/raw/MIvsAttr.png') intervals = [x",
"in range(0, 22000, 2000)] categories = ['<'+str(x) for x in",
"'OverTime', 'PercentSalaryHike', 'YearsInCurrentRole', 'YearsSinceLastPromotion']] #print(\"These re SKILSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSS\") #print(skills) X =",
"'MonthlyIncome', 'NumCompaniesWorked', 'OverTime', 'PercentSalaryHike', 'YearsInCurrentRole', 'YearsSinceLastPromotion']] #print(\"These re SKILSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSS\") #print(skills)",
"labelencoder_X_9.fit_transform(X[:, 9]) labelencoder_X_12 = LabelEncoder() X[:, 12] = labelencoder_X_12.fit_transform(X[:, 12])",
"palette=\"Set1\", data=df1) ax.set(title=\"Distance from home vs Attrition\", xlabel=\"Distance\", ylabel=\"Total\") plt.xticks(rotation=-30)",
"'EducationField', 'Gender', 'JobRole', 'JobSatisfaction', 'MaritalStatus', 'MonthlyIncome', 'NumCompaniesWorked', 'OverTime', 'PercentSalaryHike', 'YearsInCurrentRole',",
"6] = labelencoder_X_6.fit_transform(X[:, 6]) labelencoder_X_7 = LabelEncoder() X[:, 7] =",
"12]) p = clf.predict(X) t = () for x in",
"for x in range(2,22,2)] df1 = df df1['Current_Role'] = pd.cut(df.YearsInCurrentRole,",
"'JobLevel', 'HourlyRate', 'MonthlyRate', 'Over18', 'StandardHours', 'EnvironmentSatisfaction', 'JobInvolvement', 'PerformanceRating', 'TrainingTimesLastYear', 'RelationshipSatisfaction',",
"'DistanceFromHome', 'Education', 'EducationField', 'Gender', 'JobRole', 'JobSatisfaction', 'MaritalStatus', 'MonthlyIncome', 'NumCompaniesWorked', 'OverTime',",
"for x in range(0, 22000, 2000)] categories = ['<'+str(x) for",
"Attrition\", xlabel=\"Number Of Years in Current Role\", ylabel=\"Total\") plt.xticks(rotation=-30) plt.savefig('templates/graphs/raw/YICRvsAttr.png')",
"'NumCompaniesWorked', 'OverTime', 'PercentSalaryHike', 'YearsInCurrentRole', 'YearsSinceLastPromotion'],columns=['importance']).sort_values('importance',ascending=False) feature_importances['x1'] = feature_importances.index ax =",
"6]) labelencoder_X_7 = LabelEncoder() X[:, 7] = labelencoder_X_7.fit_transform(X[:, 7]) labelencoder_X_9",
"LabelEncoder() X[:, 1] = labelencoder_X_1.fit_transform(X[:, 1]) labelencoder_X_2 = LabelEncoder() X[:,",
"0].values labelencoder_X_1 = LabelEncoder() X[:, 1] = labelencoder_X_1.fit_transform(X[:, 1]) labelencoder_X_2",
"labelencoder_X_12 = LabelEncoder() X[:, 12] = labelencoder_X_12.fit_transform(X[:, 12]) p =",
"= sns.countplot(x=\"Age_Categories\", hue=\"Attrition\", palette=\"Set1\", data=df1) ax.set(title=\"Age vs Attrition\", xlabel=\"Age group\",",
"flask import flash import numpy as np def check(X, clf):",
"X = df.iloc[:, 1:].values y = df.iloc[:, 0].values labelencoder_X_1 =",
"Hike Percentage vs Attrition\", xlabel=\"Salary Hike Percentage\", ylabel=\"Total\") plt.savefig('templates/graphs/raw/PercentSalaryHikevsAttr.png') ax",
"hue=\"Attrition\", palette=\"Set1\", data=df1) ax.set(title=\"Job Role vs Attrition\", xlabel=\"Job Role\", ylabel=\"Total\")",
"x in range(21,63,3)] df1 = df df1['Age_Categories'] = pd.cut(df.Age, intervals,",
"2]) labelencoder_X_5 = LabelEncoder() X[:, 5] = labelencoder_X_5.fit_transform(X[:, 5]) labelencoder_X_6",
"return t def analyze(df, clf): feature_importances = pd.DataFrame(clf.feature_importances_, index=['Age', 'BusinessTravel',",
"labelencoder_X_12.fit_transform(X[:, 12]) p = clf.predict(X) t = () for x",
"sns.countplot(x=\"NumCompaniesWorked\", hue=\"Attrition\", palette=\"Set1\", data=df1) ax.set(title=\"Number Of Previously Worked Companies vs",
"[r.pop(0) for r in X] #print(\"####### THIS IS XXXX##########\") #print(X)",
"Companies\", ylabel=\"Total\") plt.savefig('templates/graphs/raw/NPWCvsAttr.png') intervals = [x for x in range(0,22,2)]",
"X[:, 7] = labelencoder_X_7.fit_transform(X[:, 7]) labelencoder_X_9 = LabelEncoder() X[:, 9]",
"sns.countplot(x=\"JobRole\", hue=\"Attrition\", palette=\"Set1\", data=df1) ax.set(title=\"Job Role vs Attrition\", xlabel=\"Job Role\",",
"X_test, y_train, y_test = train_test_split(X, y, test_size=0.40,random_state=0) clf = RandomForestClassifier(n_estimators=200)",
"y = labelencoder_y.fit_transform(y) X_train, X_test, y_train, y_test = train_test_split(X, y,",
"'NumCompaniesWorked', 'OverTime', 'PercentSalaryHike', 'YearsInCurrentRole', 'YearsSinceLastPromotion']] #print(\"These re SKILSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSS\") #print(skills) X",
"data=df1) ax.set(title=\"Number Of Previously Worked Companies vs Attrition\", xlabel=\"Number Of"
] |
[
"Imports and aliases import pickle import torch as t import",
"A_labels, C_train, C_val, C_test, N = ehf.load_data(data_loc, mat_f_name, S_train, S_val,",
".78, .79, .80, .81, .82, .83, .84, .85, .86, .87,",
"precision_test, recall_test, f1_test, loss_test] elif eval_type == \"MAP-MRR\": ep_acc_loss[ep] =",
"\"F1\": ep_acc_loss = np.zeros((no_epochs,12)) # (precision_train, recall_train, f1_train, loss_train, precision_val,",
"no_trials == 1: pickle.dump(ep_acc_loss, open(save_res_fname, \"wb\")) print(\"Results saved for single",
"\"MAP-MRR\" or \"F1\" data_loc = \"data/Bitcoin_\" + dataset + \"/\"",
"= 95 eval_type = \"MAP-MRR\" # \"MAP-MRR\" or \"F1\" data_loc",
"print(\"alpha/Tr/Ep %.2f/%d/%d. Val MAP/MRR %.16f/%.16f. Val loss %.16f.\" % (alpha,",
"MAP_test, MRR_test = ehf.compute_MAP_MRR(output_test, target_test[edges_test[0]!=0], edges_test[:, edges_test[0]!=0]) loss_test = criterion(output_test,",
"19 beta2 = 19 cutoff = 95 eval_type = \"MAP-MRR\"",
"= [precision_train, recall_train, f1_train, loss_train, precision_val, recall_val, f1_val, loss_val, precision_test,",
"experiment imports data preprocessed in Matlab, and uses the GCN",
"doing more often than this guess_train = t.argmax(output_train, dim=1) if",
"precision_test, recall_test, f1_test, loss_test) elif eval_type == \"MAP-MRR\": ep_acc_loss =",
"0.9 # Load and return relevant data A, A_labels, C_train,",
"== 0: # Compute stats for training data; no point",
"nn import torch.nn.functional as F import torchvision import torchvision.datasets as",
"\"/\" S_train, S_val, S_test = 95, 20, 20 lr =",
"target) if eval_type == \"F1\": ep_acc_loss = np.zeros((no_epochs,12)) # (precision_train,",
"output_train = gcn() loss_train = criterion(output_train, target_train[edges_train[0]!=0]) loss_train.backward() optimizer.step() #",
"loss %.16f.\\n\" % (alpha, tr, ep, MAP_test, MRR_test, loss_test)) #",
".93, .94, .95] no_layers = 1 dataset = \"OTC\" #",
"loss_val)) print(\"FINAL: Test MAP/MRR %.16f/%.16f. Test loss %.16f.\\n\" % (MAP_test,",
"loss_test) elif eval_type == \"MAP-MRR\": ep_acc_loss = np.zeros((no_epochs,9)) # (MAP_train,",
"%.16f/%.16f. Test loss %.16f.\\n\" % (MAP_test, MRR_test, loss_test)) if no_trials",
"# The point of this script is to do link",
"t.argmax(output_test, dim=1) if eval_type == \"F1\": precision_test, recall_test, f1_test =",
"elif eval_type == \"MAP-MRR\": ep_acc_loss = np.zeros((no_epochs,9)) # (MAP_train, MRR_train,",
"edges_train[0]!=0]) # Compute stats for validation data output_val = gcn(C_val[:-1],",
"recall_test, f1_test, loss_test, is_final=True) elif eval_type == \"MAP-MRR\": print(\"FINAL: Train",
"loss_val, MAP_test, MRR_test, loss_test) for ep in range(no_epochs): # Compute",
"e_train, [6,6,2], nonlin2=\"selu\") elif no_layers == 1: gcn = ehf.EmbeddingKWGCN(C_train[:-1],",
"ehf.compute_f1(guess_val, target_val[edges_val[0]!=0]) elif eval_type == \"MAP-MRR\": MAP_val, MRR_val = ehf.compute_MAP_MRR(output_val,",
"= 0.01 momentum = 0.9 # Load and return relevant",
"do link prediction # Imports and aliases import pickle import",
"S_val, S_test, same_block_size=False) # Extract edges and labels from A_labels,",
"loss %.16f.\" % (MAP_train, MRR_train, loss_train)) print(\"FINAL: Val MAP/MRR %.16f/%.16f.",
"import torch.nn.functional as F import torchvision import torchvision.datasets as datasets",
"t import torch.nn as nn import torch.nn.functional as F import",
"1000 mat_f_name = \"saved_content_bitcoin_otc.mat\" no_trials = 1 beta1 = 19",
"= \"saved_content_bitcoin_otc.mat\" no_trials = 1 beta1 = 19 beta2 =",
"== \"MAP-MRR\": print(\"FINAL: Train MAP/MRR %.16f/%.16f. Train loss %.16f.\" %",
"%.16f.\\n\" % (alpha, tr, ep, MAP_test, MRR_test, loss_test)) # Store",
"edges_val[0]!=0]) loss_val = criterion(output_val, target_val[edges_val[0]!=0]) # Compute stats for test",
"ep, MAP_test, MRR_test, loss_test)) # Store values with results if",
"= 19 cutoff = 95 eval_type = \"MAP-MRR\" # \"MAP-MRR\"",
"and labels from A_labels, and augment with nonexisting edges #",
"of this script is to do link prediction # Imports",
"beta1 = 19 beta2 = 19 cutoff = 95 eval_type",
"if no_trials == 1: pickle.dump(ep_acc_loss, open(save_res_fname, \"wb\")) print(\"Results saved for",
"if no_trials > 1: pickle.dump(ep_acc_loss_vec, open(save_res_fname + \"_no_trials\" + str(no_trials),",
"recall_test, f1_test, loss_test) elif eval_type == \"MAP-MRR\": ep_acc_loss = np.zeros((no_epochs,9))",
"edges_train[:, edges_train[0]!=0]) # Compute stats for validation data output_val =",
"preprocessed in Matlab, and uses the GCN baseline # The",
"This version of the bitcoin experiment imports data preprocessed in",
"N = ehf.load_data(data_loc, mat_f_name, S_train, S_val, S_test, transformed=False) # Create",
"unsq = t.unsqueeze sq = t.squeeze # Settings alpha_vec =",
"import torch.nn as nn import torch.nn.functional as F import torchvision",
"np import matplotlib.pyplot as plt import cProfile import pandas as",
"open(save_res_fname + \"_no_trials\" + str(no_trials), \"wb\")) print(\"Results saved for all",
"Test MAP/MRR %.16f/%.16f. Test loss %.16f.\\n\" % (alpha, tr, ep,",
"= gcn() loss_train = criterion(output_train, target_train[edges_train[0]!=0]) loss_train.backward() optimizer.step() # Things",
"and labels into training, validation and testing sets edges_train, target_train,",
"MAP_train, MRR_train = ehf.compute_MAP_MRR(output_train, target_train[edges_train[0]!=0], edges_train[:, edges_train[0]!=0]) # Compute stats",
"# Settings alpha_vec = [.75, .76, .77, .78, .79, .80,",
"= \"data/Bitcoin_\" + dataset + \"/\" S_train, S_val, S_test =",
"== \"MAP-MRR\": ep_acc_loss = np.zeros((no_epochs,9)) # (MAP_train, MRR_train, loss_train, MAP_val,",
"str(round(float(class_weights[0])*100)) + \"_\" + dataset + \"_link_prediction\" # Create gcn",
"target_val[edges_val[0]!=0]) # Compute stats for test data output_test = gcn(C_test[:-1],",
"target_val, e_val, edges_test, target_test, e_test = ehf.split_data(edges_aug, labels, S_train, S_val,",
"dim=1) if eval_type == \"F1\": precision_val, recall_val, f1_val = ehf.compute_f1(guess_val,",
"f1_val, loss_val, precision_test, recall_test, f1_test, loss_test, alpha, tr, ep) elif",
"and uses the GCN baseline # The point of this",
"MAP/MRR %.16f/%.16f. Train loss %.16f.\" % (alpha, tr, ep, MAP_train,",
"criterion(output_train, target_train[edges_train[0]!=0]) loss_train.backward() optimizer.step() # Things that don't require gradient",
"= 1 beta1 = 19 beta2 = 19 cutoff =",
"lr = 0.01 momentum = 0.9 # Load and return",
"MRR_val = ehf.compute_MAP_MRR(output_val, target_val[edges_val[0]!=0], edges_val[:, edges_val[0]!=0]) loss_val = criterion(output_val, target_val[edges_val[0]!=0])",
"# Compute stats for validation data output_val = gcn(C_val[:-1], X_val[:-1],",
"== \"F1\": precision_val, recall_val, f1_val = ehf.compute_f1(guess_val, target_val[edges_val[0]!=0]) elif eval_type",
".89, .90, .91, .92, .93, .94, .95] no_layers = 1",
"%.16f/%.16f. Val loss %.16f.\" % (alpha, tr, ep, MAP_val, MRR_val,",
"training if no_layers == 2: gcn = ehf.EmbeddingKWGCN(C_train[:-1], X_train[:-1], e_train,",
"= ehf.split_data(edges_aug, labels, S_train, S_val, S_test, same_block_size = False) if",
"# Imports and aliases import pickle import torch as t",
"A, A_labels, C_train, C_val, C_test, N = ehf.load_data(data_loc, mat_f_name, S_train,",
"+ \"_link_prediction\" # Create gcn for training if no_layers ==",
"f1_val, loss_val, precision_test, recall_test, f1_test, loss_test] elif eval_type == \"MAP-MRR\":",
"%.16f.\" % (MAP_train, MRR_train, loss_train)) print(\"FINAL: Val MAP/MRR %.16f/%.16f. Val",
"= ehf.compute_MAP_MRR(output_train, target_train[edges_train[0]!=0], edges_train[:, edges_train[0]!=0]) # Compute stats for validation",
"# OTC or Alpha no_epochs = 1000 mat_f_name = \"saved_content_bitcoin_otc.mat\"",
".90, .91, .92, .93, .94, .95] no_layers = 1 dataset",
"= \"MAP-MRR\" # \"MAP-MRR\" or \"F1\" data_loc = \"data/Bitcoin_\" +",
"Val loss %.16f.\" % (alpha, tr, ep, MAP_val, MRR_val, loss_val))",
"(MAP_val, MRR_val, loss_val)) print(\"FINAL: Test MAP/MRR %.16f/%.16f. Test loss %.16f.\\n\"",
"no_layers == 1: gcn = ehf.EmbeddingKWGCN(C_train[:-1], X_train[:-1], e_train, [6,2]) #",
"if eval_type == \"F1\": ehf.print_f1(precision_train, recall_train, f1_train, loss_train, precision_val, recall_val,",
"0: # Compute stats for training data; no point in",
"elif eval_type == \"MAP-MRR\": MAP_train, MRR_train = ehf.compute_MAP_MRR(output_train, target_train[edges_train[0]!=0], edges_train[:,",
"as pd import datetime from scipy.sparse import csr_matrix import os.path",
"\"results_BASELINE_layers\" + str(no_layers) + \"_w\" + str(round(float(class_weights[0])*100)) + \"_\" +",
"target_train[edges_train[0]!=0]) loss_train.backward() optimizer.step() # Things that don't require gradient with",
"labels from A_labels, and augment with nonexisting edges # edges,",
"transformed=False) # Create features for the nodes X_train, X_val, X_test",
"edges = A_labels._indices() edges_aug, labels = ehf.augment_edges(edges, N, beta1, beta2,",
"MRR_val, loss_val)) print(\"FINAL: Test MAP/MRR %.16f/%.16f. Test loss %.16f.\\n\" %",
".88, .89, .90, .91, .92, .93, .94, .95] no_layers =",
"\"_\" + dataset + \"_link_prediction\" # Create gcn for training",
"X_train[:-1], e_train, [6,2]) # Train optimizer = t.optim.SGD(gcn.parameters(), lr=lr, momentum=momentum)",
"momentum=momentum) criterion = nn.CrossEntropyLoss(weight=class_weights) # Takes arguments (output, target) if",
"loss_test] if eval_type == \"F1\": ehf.print_f1(precision_train, recall_train, f1_train, loss_train, precision_val,",
"loss_val, precision_test, recall_test, f1_test, loss_test, alpha, tr, ep) elif eval_type",
"as t import torch.nn as nn import torch.nn.functional as F",
"% (MAP_train, MRR_train, loss_train)) print(\"FINAL: Val MAP/MRR %.16f/%.16f. Val loss",
"\"OTC\" # OTC or Alpha no_epochs = 1000 mat_f_name =",
"MRR_test, loss_test] if eval_type == \"F1\": ehf.print_f1(precision_train, recall_train, f1_train, loss_train,",
"torch.nn.functional as F import torchvision import torchvision.datasets as datasets import",
"[6,2]) # Train optimizer = t.optim.SGD(gcn.parameters(), lr=lr, momentum=momentum) criterion =",
"Train MAP/MRR %.16f/%.16f. Train loss %.16f.\" % (alpha, tr, ep,",
"optimizer.step() # Things that don't require gradient with t.no_grad(): if",
"same_block_size = False) if no_trials > 1: ep_acc_loss_vec = []",
"print(\"FINAL: Test MAP/MRR %.16f/%.16f. Test loss %.16f.\\n\" % (MAP_test, MRR_test,",
"S_val, S_test = 95, 20, 20 lr = 0.01 momentum",
"import numpy as np import matplotlib.pyplot as plt import cProfile",
"return relevant data A, A_labels, C_train, C_val, C_test, N =",
"f1_test, loss_test) elif eval_type == \"MAP-MRR\": ep_acc_loss = np.zeros((no_epochs,9)) #",
"MAP/MRR %.16f/%.16f. Val loss %.16f.\" % (MAP_val, MRR_val, loss_val)) print(\"FINAL:",
"loss %.16f.\" % (MAP_val, MRR_val, loss_val)) print(\"FINAL: Test MAP/MRR %.16f/%.16f.",
"precision_val, recall_val, f1_val, loss_val, precision_test, recall_test, f1_test, loss_test) elif eval_type",
"\"F1\": precision_test, recall_test, f1_test = ehf.compute_f1(guess_test, target_test[edges_test[0]!=0]) elif eval_type ==",
"= np.zeros((no_epochs,12)) # (precision_train, recall_train, f1_train, loss_train, precision_val, recall_val, f1_val,",
"gcn() loss_train = criterion(output_train, target_train[edges_train[0]!=0]) loss_train.backward() optimizer.step() # Things that",
"print(\"FINAL: Train MAP/MRR %.16f/%.16f. Train loss %.16f.\" % (MAP_train, MRR_train,",
"MAP_test, MRR_test, loss_test)) # Store values with results if eval_type",
"edges # edges, beta edges = A_labels._indices() edges_aug, labels =",
"edges_val, target_val, e_val, edges_test, target_test, e_test = ehf.split_data(edges_aug, labels, S_train,",
"this script is to do link prediction # Imports and",
"or \"F1\" data_loc = \"data/Bitcoin_\" + dataset + \"/\" S_train,",
"imports data preprocessed in Matlab, and uses the GCN baseline",
"print(\"alpha/Tr/Ep %.2f/%d/%d. Test MAP/MRR %.16f/%.16f. Test loss %.16f.\\n\" % (alpha,",
"19 cutoff = 95 eval_type = \"MAP-MRR\" # \"MAP-MRR\" or",
"= ehf.augment_edges(edges, N, beta1, beta2, cutoff) # Divide adjacency matrices",
"Train loss %.16f.\" % (MAP_train, MRR_train, loss_train)) print(\"FINAL: Val MAP/MRR",
"target_test[edges_test[0]!=0], edges_test[:, edges_test[0]!=0]) loss_test = criterion(output_test, target_test[edges_test[0]!=0]) # Print if",
"= 19 beta2 = 19 cutoff = 95 eval_type =",
"+ \"_w\" + str(round(float(class_weights[0])*100)) + \"_\" + dataset + \"_link_prediction\"",
"= t.argmax(output_test, dim=1) if eval_type == \"F1\": precision_test, recall_test, f1_test",
"+ str(no_layers) + \"_w\" + str(round(float(class_weights[0])*100)) + \"_\" + dataset",
"loss_test, alpha, tr, ep) elif eval_type == \"MAP-MRR\": print(\"alpha/Tr/Ep %.2f/%d/%d.",
"% (MAP_test, MRR_test, loss_test)) if no_trials == 1: pickle.dump(ep_acc_loss, open(save_res_fname,",
"relevant data A, A_labels, C_train, C_val, C_test, N = ehf.load_data(data_loc,",
"= A_labels._indices() edges_aug, labels = ehf.augment_edges(edges, N, beta1, beta2, cutoff)",
"= False) if no_trials > 1: ep_acc_loss_vec = [] for",
"for ep in range(no_epochs): # Compute loss and take step",
"save_res_fname = \"results_BASELINE_layers\" + str(no_layers) + \"_w\" + str(round(float(class_weights[0])*100)) +",
"(alpha, tr, ep, MAP_val, MRR_val, loss_val)) print(\"alpha/Tr/Ep %.2f/%d/%d. Test MAP/MRR",
"elif no_layers == 1: gcn = ehf.EmbeddingKWGCN(C_train[:-1], X_train[:-1], e_train, [6,2])",
"C_val, C_test, N = ehf.load_data(data_loc, mat_f_name, S_train, S_val, S_test, transformed=False)",
"torch.nn as nn import torch.nn.functional as F import torchvision import",
"require gradient with t.no_grad(): if ep % 100 == 0:",
"plt import cProfile import pandas as pd import datetime from",
"\"MAP-MRR\": MAP_test, MRR_test = ehf.compute_MAP_MRR(output_test, target_test[edges_test[0]!=0], edges_test[:, edges_test[0]!=0]) loss_test =",
"= [MAP_train, MRR_train, loss_train, MAP_val, MRR_val, loss_val, MAP_test, MRR_test, loss_test]",
"pickle.dump(ep_acc_loss, open(save_res_fname, \"wb\")) print(\"Results saved for single trial\") else: ep_acc_loss_vec.append(ep_acc_loss)",
"+ \"_no_trials\" + str(no_trials), \"wb\")) print(\"Results saved for all trials\")",
"GCN baseline # The point of this script is to",
"# Divide adjacency matrices and labels into training, validation and",
"the bitcoin experiment imports data preprocessed in Matlab, and uses",
"ehf import scipy.io as sio unsq = t.unsqueeze sq =",
"the GCN baseline # The point of this script is",
"take step optimizer.zero_grad() output_train = gcn() loss_train = criterion(output_train, target_train[edges_train[0]!=0])",
"tr, ep, MAP_val, MRR_val, loss_val)) print(\"alpha/Tr/Ep %.2f/%d/%d. Test MAP/MRR %.16f/%.16f.",
"import pandas as pd import datetime from scipy.sparse import csr_matrix",
"cutoff) # Divide adjacency matrices and labels into training, validation",
"= ehf.compute_f1(guess_val, target_val[edges_val[0]!=0]) elif eval_type == \"MAP-MRR\": MAP_val, MRR_val =",
"recall_test, f1_test, loss_test] elif eval_type == \"MAP-MRR\": ep_acc_loss[ep] = [MAP_train,",
"in doing more often than this guess_train = t.argmax(output_train, dim=1)",
"= np.zeros((no_epochs,9)) # (MAP_train, MRR_train, loss_train, MAP_val, MRR_val, loss_val, MAP_test,",
"loss %.16f.\" % (alpha, tr, ep, MAP_train, MRR_train, loss_train)) print(\"alpha/Tr/Ep",
"loss_test = criterion(output_test, target_test[edges_test[0]!=0]) # Print if eval_type == \"F1\":",
"\"F1\": ehf.print_f1(precision_train, recall_train, f1_train, loss_train, precision_val, recall_val, f1_val, loss_val, precision_test,",
"elif eval_type == \"MAP-MRR\": ep_acc_loss[ep] = [MAP_train, MRR_train, loss_train, MAP_val,",
"eval_type == \"MAP-MRR\": MAP_val, MRR_val = ehf.compute_MAP_MRR(output_val, target_val[edges_val[0]!=0], edges_val[:, edges_val[0]!=0])",
"MRR_train, loss_train)) print(\"FINAL: Val MAP/MRR %.16f/%.16f. Val loss %.16f.\" %",
"[precision_train, recall_train, f1_train, loss_train, precision_val, recall_val, f1_val, loss_val, precision_test, recall_test,",
"gcn = ehf.EmbeddingKWGCN(C_train[:-1], X_train[:-1], e_train, [6,6,2], nonlin2=\"selu\") elif no_layers ==",
"os.path import embedding_help_functions as ehf import scipy.io as sio unsq",
"\"_w\" + str(round(float(class_weights[0])*100)) + \"_\" + dataset + \"_link_prediction\" #",
".79, .80, .81, .82, .83, .84, .85, .86, .87, .88,",
"\"MAP-MRR\": MAP_val, MRR_val = ehf.compute_MAP_MRR(output_val, target_val[edges_val[0]!=0], edges_val[:, edges_val[0]!=0]) loss_val =",
"eval_type == \"F1\": precision_test, recall_test, f1_test = ehf.compute_f1(guess_test, target_test[edges_test[0]!=0]) elif",
"Alpha no_epochs = 1000 mat_f_name = \"saved_content_bitcoin_otc.mat\" no_trials = 1",
"1: pickle.dump(ep_acc_loss_vec, open(save_res_fname + \"_no_trials\" + str(no_trials), \"wb\")) print(\"Results saved",
"+ dataset + \"/\" S_train, S_val, S_test = 95, 20,",
"# Compute loss and take step optimizer.zero_grad() output_train = gcn()",
"== \"MAP-MRR\": ep_acc_loss[ep] = [MAP_train, MRR_train, loss_train, MAP_val, MRR_val, loss_val,",
"MRR_test, loss_test)) # Store values with results if eval_type ==",
"lr=lr, momentum=momentum) criterion = nn.CrossEntropyLoss(weight=class_weights) # Takes arguments (output, target)",
"gcn(C_test[:-1], X_test[:-1], e_test) guess_test = t.argmax(output_test, dim=1) if eval_type ==",
"= 0.9 # Load and return relevant data A, A_labels,",
"== \"F1\": precision_test, recall_test, f1_test = ehf.compute_f1(guess_test, target_test[edges_test[0]!=0]) elif eval_type",
"target_train, e_train, edges_val, target_val, e_val, edges_test, target_test, e_test = ehf.split_data(edges_aug,",
"t.optim.SGD(gcn.parameters(), lr=lr, momentum=momentum) criterion = nn.CrossEntropyLoss(weight=class_weights) # Takes arguments (output,",
"\"MAP-MRR\" # \"MAP-MRR\" or \"F1\" data_loc = \"data/Bitcoin_\" + dataset",
"arguments (output, target) if eval_type == \"F1\": ep_acc_loss = np.zeros((no_epochs,12))",
"t.squeeze # Settings alpha_vec = [.75, .76, .77, .78, .79,",
"elif eval_type == \"MAP-MRR\": MAP_test, MRR_test = ehf.compute_MAP_MRR(output_test, target_test[edges_test[0]!=0], edges_test[:,",
"ep) elif eval_type == \"MAP-MRR\": print(\"alpha/Tr/Ep %.2f/%d/%d. Train MAP/MRR %.16f/%.16f.",
"loss_val, precision_test, recall_test, f1_test, loss_test, is_final=True) elif eval_type == \"MAP-MRR\":",
"scipy.io as sio unsq = t.unsqueeze sq = t.squeeze #",
"= t.argmax(output_val, dim=1) if eval_type == \"F1\": precision_val, recall_val, f1_val",
"target_val[edges_val[0]!=0], edges_val[:, edges_val[0]!=0]) loss_val = criterion(output_val, target_val[edges_val[0]!=0]) # Compute stats",
"output_test = gcn(C_test[:-1], X_test[:-1], e_test) guess_test = t.argmax(output_test, dim=1) if",
"tr, ep, MAP_train, MRR_train, loss_train)) print(\"alpha/Tr/Ep %.2f/%d/%d. Val MAP/MRR %.16f/%.16f.",
"test data output_test = gcn(C_test[:-1], X_test[:-1], e_test) guess_test = t.argmax(output_test,",
"ehf.EmbeddingKWGCN(C_train[:-1], X_train[:-1], e_train, [6,2]) # Train optimizer = t.optim.SGD(gcn.parameters(), lr=lr,",
"= 1 dataset = \"OTC\" # OTC or Alpha no_epochs",
"nn.CrossEntropyLoss(weight=class_weights) # Takes arguments (output, target) if eval_type == \"F1\":",
"that don't require gradient with t.no_grad(): if ep % 100",
"adjacency matrices and labels into training, validation and testing sets",
"edges_val[:, edges_val[0]!=0]) loss_val = criterion(output_val, target_val[edges_val[0]!=0]) # Compute stats for",
"link prediction # Imports and aliases import pickle import torch",
"+ \"_\" + dataset + \"_link_prediction\" # Create gcn for",
"S_val, S_test, same_block_size = False) if no_trials > 1: ep_acc_loss_vec",
".76, .77, .78, .79, .80, .81, .82, .83, .84, .85,",
"alpha_vec: class_weights = t.tensor([alpha, 1.0-alpha]) save_res_fname = \"results_BASELINE_layers\" + str(no_layers)",
"# Create gcn for training if no_layers == 2: gcn",
"eval_type == \"F1\": ep_acc_loss[ep] = [precision_train, recall_train, f1_train, loss_train, precision_val,",
"Test MAP/MRR %.16f/%.16f. Test loss %.16f.\\n\" % (MAP_test, MRR_test, loss_test))",
"= [.75, .76, .77, .78, .79, .80, .81, .82, .83,",
"%.16f/%.16f. Val loss %.16f.\" % (MAP_val, MRR_val, loss_val)) print(\"FINAL: Test",
"# (precision_train, recall_train, f1_train, loss_train, precision_val, recall_val, f1_val, loss_val, precision_test,",
"precision_test, recall_test, f1_test = ehf.compute_f1(guess_test, target_test[edges_test[0]!=0]) elif eval_type == \"MAP-MRR\":",
"alpha, tr, ep) elif eval_type == \"MAP-MRR\": print(\"alpha/Tr/Ep %.2f/%d/%d. Train",
"loss_train, precision_val, recall_val, f1_val, loss_val, precision_test, recall_test, f1_test, loss_test, is_final=True)",
"for training if no_layers == 2: gcn = ehf.EmbeddingKWGCN(C_train[:-1], X_train[:-1],",
"more often than this guess_train = t.argmax(output_train, dim=1) if eval_type",
"MRR_val, loss_val)) print(\"alpha/Tr/Ep %.2f/%d/%d. Test MAP/MRR %.16f/%.16f. Test loss %.16f.\\n\"",
"Val MAP/MRR %.16f/%.16f. Val loss %.16f.\" % (alpha, tr, ep,",
"f1_test, loss_test, alpha, tr, ep) elif eval_type == \"MAP-MRR\": print(\"alpha/Tr/Ep",
"Settings alpha_vec = [.75, .76, .77, .78, .79, .80, .81,",
"precision_val, recall_val, f1_val, loss_val, precision_test, recall_test, f1_test, loss_test, is_final=True) elif",
"eval_type == \"MAP-MRR\": print(\"alpha/Tr/Ep %.2f/%d/%d. Train MAP/MRR %.16f/%.16f. Train loss",
"1 beta1 = 19 beta2 = 19 cutoff = 95",
"S_train, S_val, S_test, transformed=False) # Create features for the nodes",
"Compute stats for test data output_test = gcn(C_test[:-1], X_test[:-1], e_test)",
"Test loss %.16f.\\n\" % (alpha, tr, ep, MAP_test, MRR_test, loss_test))",
"data preprocessed in Matlab, and uses the GCN baseline #",
"augment with nonexisting edges # edges, beta edges = A_labels._indices()",
"F import torchvision import torchvision.datasets as datasets import numpy as",
"20, 20 lr = 0.01 momentum = 0.9 # Load",
"results if eval_type == \"F1\": ep_acc_loss[ep] = [precision_train, recall_train, f1_train,",
"saved for single trial\") else: ep_acc_loss_vec.append(ep_acc_loss) if no_trials > 1:",
"gcn for training if no_layers == 2: gcn = ehf.EmbeddingKWGCN(C_train[:-1],",
"ehf.split_data(edges_aug, labels, S_train, S_val, S_test, same_block_size = False) if no_trials",
"MAP/MRR %.16f/%.16f. Test loss %.16f.\\n\" % (MAP_test, MRR_test, loss_test)) if",
"scipy.sparse import csr_matrix import os.path import embedding_help_functions as ehf import",
"as ehf import scipy.io as sio unsq = t.unsqueeze sq",
"from A_labels, and augment with nonexisting edges # edges, beta",
"loss_train.backward() optimizer.step() # Things that don't require gradient with t.no_grad():",
"nodes X_train, X_val, X_test = ehf.create_node_features(A, S_train, S_val, S_test, same_block_size=False)",
"ep_acc_loss_vec = [] for tr in range(no_trials): for alpha in",
"MRR_val, loss_val, MAP_test, MRR_test, loss_test] if eval_type == \"F1\": ehf.print_f1(precision_train,",
"MAP_val, MRR_val, loss_val, MAP_test, MRR_test, loss_test] if eval_type == \"F1\":",
"print(\"alpha/Tr/Ep %.2f/%d/%d. Train MAP/MRR %.16f/%.16f. Train loss %.16f.\" % (alpha,",
"% 100 == 0: # Compute stats for training data;",
"# edges, beta edges = A_labels._indices() edges_aug, labels = ehf.augment_edges(edges,",
"range(no_trials): for alpha in alpha_vec: class_weights = t.tensor([alpha, 1.0-alpha]) save_res_fname",
"import matplotlib.pyplot as plt import cProfile import pandas as pd",
"== \"F1\": ep_acc_loss = np.zeros((no_epochs,12)) # (precision_train, recall_train, f1_train, loss_train,",
"t.argmax(output_train, dim=1) if eval_type == \"F1\": precision_train, recall_train, f1_train =",
"\"MAP-MRR\": print(\"alpha/Tr/Ep %.2f/%d/%d. Train MAP/MRR %.16f/%.16f. Train loss %.16f.\" %",
"loss_train = criterion(output_train, target_train[edges_train[0]!=0]) loss_train.backward() optimizer.step() # Things that don't",
"= ehf.compute_f1(guess_test, target_test[edges_test[0]!=0]) elif eval_type == \"MAP-MRR\": MAP_test, MRR_test =",
"loss %.16f.\\n\" % (MAP_test, MRR_test, loss_test)) if no_trials == 1:",
"as nn import torch.nn.functional as F import torchvision import torchvision.datasets",
"loss_test] elif eval_type == \"MAP-MRR\": ep_acc_loss[ep] = [MAP_train, MRR_train, loss_train,",
"== \"F1\": precision_train, recall_train, f1_train = ehf.compute_f1(guess_train, target_train[edges_train[0]!=0]) elif eval_type",
"f1_val, loss_val, precision_test, recall_test, f1_test, loss_test) elif eval_type == \"MAP-MRR\":",
"f1_train = ehf.compute_f1(guess_train, target_train[edges_train[0]!=0]) elif eval_type == \"MAP-MRR\": MAP_train, MRR_train",
"labels, S_train, S_val, S_test, same_block_size = False) if no_trials >",
"# Print if eval_type == \"F1\": ehf.print_f1(precision_train, recall_train, f1_train, loss_train,",
"= t.optim.SGD(gcn.parameters(), lr=lr, momentum=momentum) criterion = nn.CrossEntropyLoss(weight=class_weights) # Takes arguments",
"%.2f/%d/%d. Val MAP/MRR %.16f/%.16f. Val loss %.16f.\" % (alpha, tr,",
"Train MAP/MRR %.16f/%.16f. Train loss %.16f.\" % (MAP_train, MRR_train, loss_train))",
"elif eval_type == \"MAP-MRR\": MAP_val, MRR_val = ehf.compute_MAP_MRR(output_val, target_val[edges_val[0]!=0], edges_val[:,",
"+ \"/\" S_train, S_val, S_test = 95, 20, 20 lr",
"%.16f.\" % (alpha, tr, ep, MAP_train, MRR_train, loss_train)) print(\"alpha/Tr/Ep %.2f/%d/%d.",
"(output, target) if eval_type == \"F1\": ep_acc_loss = np.zeros((no_epochs,12)) #",
"1: pickle.dump(ep_acc_loss, open(save_res_fname, \"wb\")) print(\"Results saved for single trial\") else:",
"cutoff = 95 eval_type = \"MAP-MRR\" # \"MAP-MRR\" or \"F1\"",
"guess_test = t.argmax(output_test, dim=1) if eval_type == \"F1\": precision_test, recall_test,",
".87, .88, .89, .90, .91, .92, .93, .94, .95] no_layers",
"often than this guess_train = t.argmax(output_train, dim=1) if eval_type ==",
"ep % 100 == 0: # Compute stats for training",
"ehf.compute_f1(guess_train, target_train[edges_train[0]!=0]) elif eval_type == \"MAP-MRR\": MAP_train, MRR_train = ehf.compute_MAP_MRR(output_train,",
"the nodes X_train, X_val, X_test = ehf.create_node_features(A, S_train, S_val, S_test,",
"if no_trials > 1: ep_acc_loss_vec = [] for tr in",
"ehf.augment_edges(edges, N, beta1, beta2, cutoff) # Divide adjacency matrices and",
"MAP_test, MRR_test, loss_test) for ep in range(no_epochs): # Compute loss",
"loss_val, MAP_test, MRR_test, loss_test] if eval_type == \"F1\": ehf.print_f1(precision_train, recall_train,",
"# Things that don't require gradient with t.no_grad(): if ep",
"recall_val, f1_val = ehf.compute_f1(guess_val, target_val[edges_val[0]!=0]) elif eval_type == \"MAP-MRR\": MAP_val,",
"elif eval_type == \"MAP-MRR\": print(\"alpha/Tr/Ep %.2f/%d/%d. Train MAP/MRR %.16f/%.16f. Train",
"criterion(output_test, target_test[edges_test[0]!=0]) # Print if eval_type == \"F1\": ehf.print_f1(precision_train, recall_train,",
"point of this script is to do link prediction #",
"= ehf.load_data(data_loc, mat_f_name, S_train, S_val, S_test, transformed=False) # Create features",
"# Create features for the nodes X_train, X_val, X_test =",
"data; no point in doing more often than this guess_train",
"f1_test, loss_test] elif eval_type == \"MAP-MRR\": ep_acc_loss[ep] = [MAP_train, MRR_train,",
"import os.path import embedding_help_functions as ehf import scipy.io as sio",
"print(\"FINAL: Val MAP/MRR %.16f/%.16f. Val loss %.16f.\" % (MAP_val, MRR_val,",
"S_train, S_val, S_test, same_block_size=False) # Extract edges and labels from",
"edges_test[:, edges_test[0]!=0]) loss_test = criterion(output_test, target_test[edges_test[0]!=0]) # Print if eval_type",
"%.16f/%.16f. Train loss %.16f.\" % (MAP_train, MRR_train, loss_train)) print(\"FINAL: Val",
"same_block_size=False) # Extract edges and labels from A_labels, and augment",
"f1_train, loss_train, precision_val, recall_val, f1_val, loss_val, precision_test, recall_test, f1_test, loss_test]",
"sets edges_train, target_train, e_train, edges_val, target_val, e_val, edges_test, target_test, e_test",
"\"F1\": precision_train, recall_train, f1_train = ehf.compute_f1(guess_train, target_train[edges_train[0]!=0]) elif eval_type ==",
"no_trials = 1 beta1 = 19 beta2 = 19 cutoff",
"1.0-alpha]) save_res_fname = \"results_BASELINE_layers\" + str(no_layers) + \"_w\" + str(round(float(class_weights[0])*100))",
"# Compute stats for training data; no point in doing",
"= gcn(C_test[:-1], X_test[:-1], e_test) guess_test = t.argmax(output_test, dim=1) if eval_type",
"edges_test[0]!=0]) loss_test = criterion(output_test, target_test[edges_test[0]!=0]) # Print if eval_type ==",
"precision_test, recall_test, f1_test, loss_test, is_final=True) elif eval_type == \"MAP-MRR\": print(\"FINAL:",
"MAP/MRR %.16f/%.16f. Val loss %.16f.\" % (alpha, tr, ep, MAP_val,",
"> 1: pickle.dump(ep_acc_loss_vec, open(save_res_fname + \"_no_trials\" + str(no_trials), \"wb\")) print(\"Results",
"values with results if eval_type == \"F1\": ep_acc_loss[ep] = [precision_train,",
"recall_val, f1_val, loss_val, precision_test, recall_test, f1_test, loss_test, alpha, tr, ep)",
"if eval_type == \"F1\": precision_train, recall_train, f1_train = ehf.compute_f1(guess_train, target_train[edges_train[0]!=0])",
"loss_train)) print(\"FINAL: Val MAP/MRR %.16f/%.16f. Val loss %.16f.\" % (MAP_val,",
"== 1: pickle.dump(ep_acc_loss, open(save_res_fname, \"wb\")) print(\"Results saved for single trial\")",
"for alpha in alpha_vec: class_weights = t.tensor([alpha, 1.0-alpha]) save_res_fname =",
"open(save_res_fname, \"wb\")) print(\"Results saved for single trial\") else: ep_acc_loss_vec.append(ep_acc_loss) if",
"no point in doing more often than this guess_train =",
"S_test, same_block_size = False) if no_trials > 1: ep_acc_loss_vec =",
"recall_val, f1_val, loss_val, precision_test, recall_test, f1_test, loss_test, is_final=True) elif eval_type",
"S_test, same_block_size=False) # Extract edges and labels from A_labels, and",
"dataset = \"OTC\" # OTC or Alpha no_epochs = 1000",
"MRR_train, loss_train, MAP_val, MRR_val, loss_val, MAP_test, MRR_test, loss_test] if eval_type",
"ep_acc_loss_vec.append(ep_acc_loss) if no_trials > 1: pickle.dump(ep_acc_loss_vec, open(save_res_fname + \"_no_trials\" +",
"f1_train, loss_train, precision_val, recall_val, f1_val, loss_val, precision_test, recall_test, f1_test, loss_test,",
"optimizer.zero_grad() output_train = gcn() loss_train = criterion(output_train, target_train[edges_train[0]!=0]) loss_train.backward() optimizer.step()",
"beta2 = 19 cutoff = 95 eval_type = \"MAP-MRR\" #",
"tr, ep) elif eval_type == \"MAP-MRR\": print(\"alpha/Tr/Ep %.2f/%d/%d. Train MAP/MRR",
"MAP_train, MRR_train, loss_train)) print(\"alpha/Tr/Ep %.2f/%d/%d. Val MAP/MRR %.16f/%.16f. Val loss",
"t.no_grad(): if ep % 100 == 0: # Compute stats",
"= ehf.compute_f1(guess_train, target_train[edges_train[0]!=0]) elif eval_type == \"MAP-MRR\": MAP_train, MRR_train =",
"\"data/Bitcoin_\" + dataset + \"/\" S_train, S_val, S_test = 95,",
".85, .86, .87, .88, .89, .90, .91, .92, .93, .94,",
"guess_train = t.argmax(output_train, dim=1) if eval_type == \"F1\": precision_train, recall_train,",
"target_test, e_test = ehf.split_data(edges_aug, labels, S_train, S_val, S_test, same_block_size =",
"precision_val, recall_val, f1_val, loss_val, precision_test, recall_test, f1_test, loss_test] elif eval_type",
"MRR_test, loss_test)) if no_trials == 1: pickle.dump(ep_acc_loss, open(save_res_fname, \"wb\")) print(\"Results",
"sio unsq = t.unsqueeze sq = t.squeeze # Settings alpha_vec",
"for the nodes X_train, X_val, X_test = ehf.create_node_features(A, S_train, S_val,",
"dataset + \"_link_prediction\" # Create gcn for training if no_layers",
"loss_val, precision_test, recall_test, f1_test, loss_test) elif eval_type == \"MAP-MRR\": ep_acc_loss",
"MRR_val, loss_val, MAP_test, MRR_test, loss_test) for ep in range(no_epochs): #",
"with results if eval_type == \"F1\": ep_acc_loss[ep] = [precision_train, recall_train,",
"(alpha, tr, ep, MAP_train, MRR_train, loss_train)) print(\"alpha/Tr/Ep %.2f/%d/%d. Val MAP/MRR",
"+ dataset + \"_link_prediction\" # Create gcn for training if",
"== 1: gcn = ehf.EmbeddingKWGCN(C_train[:-1], X_train[:-1], e_train, [6,2]) # Train",
"as F import torchvision import torchvision.datasets as datasets import numpy",
"e_test = ehf.split_data(edges_aug, labels, S_train, S_val, S_test, same_block_size = False)",
"eval_type == \"F1\": precision_val, recall_val, f1_val = ehf.compute_f1(guess_val, target_val[edges_val[0]!=0]) elif",
"MRR_train, loss_train, MAP_val, MRR_val, loss_val, MAP_test, MRR_test, loss_test) for ep",
"100 == 0: # Compute stats for training data; no",
"# This version of the bitcoin experiment imports data preprocessed",
".92, .93, .94, .95] no_layers = 1 dataset = \"OTC\"",
"eval_type == \"MAP-MRR\": print(\"FINAL: Train MAP/MRR %.16f/%.16f. Train loss %.16f.\"",
"stats for training data; no point in doing more often",
"C_train, C_val, C_test, N = ehf.load_data(data_loc, mat_f_name, S_train, S_val, S_test,",
"X_val[:-1], e_val) guess_val = t.argmax(output_val, dim=1) if eval_type == \"F1\":",
"Store values with results if eval_type == \"F1\": ep_acc_loss[ep] =",
"eval_type == \"MAP-MRR\": ep_acc_loss[ep] = [MAP_train, MRR_train, loss_train, MAP_val, MRR_val,",
"if no_layers == 2: gcn = ehf.EmbeddingKWGCN(C_train[:-1], X_train[:-1], e_train, [6,6,2],",
"recall_test, f1_test = ehf.compute_f1(guess_test, target_test[edges_test[0]!=0]) elif eval_type == \"MAP-MRR\": MAP_test,",
"[.75, .76, .77, .78, .79, .80, .81, .82, .83, .84,",
"Compute loss and take step optimizer.zero_grad() output_train = gcn() loss_train",
"recall_train, f1_train, loss_train, precision_val, recall_val, f1_val, loss_val, precision_test, recall_test, f1_test,",
"The point of this script is to do link prediction",
"alpha_vec = [.75, .76, .77, .78, .79, .80, .81, .82,",
"labels = ehf.augment_edges(edges, N, beta1, beta2, cutoff) # Divide adjacency",
"% (alpha, tr, ep, MAP_test, MRR_test, loss_test)) # Store values",
"validation data output_val = gcn(C_val[:-1], X_val[:-1], e_val) guess_val = t.argmax(output_val,",
"\"wb\")) print(\"Results saved for single trial\") else: ep_acc_loss_vec.append(ep_acc_loss) if no_trials",
"A_labels, and augment with nonexisting edges # edges, beta edges",
"Compute stats for validation data output_val = gcn(C_val[:-1], X_val[:-1], e_val)",
"tr, ep, MAP_test, MRR_test, loss_test)) # Store values with results",
"MAP/MRR %.16f/%.16f. Train loss %.16f.\" % (MAP_train, MRR_train, loss_train)) print(\"FINAL:",
"loss_val)) print(\"alpha/Tr/Ep %.2f/%d/%d. Test MAP/MRR %.16f/%.16f. Test loss %.16f.\\n\" %",
"of the bitcoin experiment imports data preprocessed in Matlab, and",
"is_final=True) elif eval_type == \"MAP-MRR\": print(\"FINAL: Train MAP/MRR %.16f/%.16f. Train",
"+ str(round(float(class_weights[0])*100)) + \"_\" + dataset + \"_link_prediction\" # Create",
"target_val[edges_val[0]!=0]) elif eval_type == \"MAP-MRR\": MAP_val, MRR_val = ehf.compute_MAP_MRR(output_val, target_val[edges_val[0]!=0],",
"ehf.create_node_features(A, S_train, S_val, S_test, same_block_size=False) # Extract edges and labels",
"%.16f.\" % (MAP_val, MRR_val, loss_val)) print(\"FINAL: Test MAP/MRR %.16f/%.16f. Test",
"for single trial\") else: ep_acc_loss_vec.append(ep_acc_loss) if no_trials > 1: pickle.dump(ep_acc_loss_vec,",
"ep, MAP_val, MRR_val, loss_val)) print(\"alpha/Tr/Ep %.2f/%d/%d. Test MAP/MRR %.16f/%.16f. Test",
"point in doing more often than this guess_train = t.argmax(output_train,",
"optimizer = t.optim.SGD(gcn.parameters(), lr=lr, momentum=momentum) criterion = nn.CrossEntropyLoss(weight=class_weights) # Takes",
"import torchvision import torchvision.datasets as datasets import numpy as np",
"gcn(C_val[:-1], X_val[:-1], e_val) guess_val = t.argmax(output_val, dim=1) if eval_type ==",
"X_train[:-1], e_train, [6,6,2], nonlin2=\"selu\") elif no_layers == 1: gcn =",
"(MAP_train, MRR_train, loss_train, MAP_val, MRR_val, loss_val, MAP_test, MRR_test, loss_test) for",
"MAP/MRR %.16f/%.16f. Test loss %.16f.\\n\" % (alpha, tr, ep, MAP_test,",
"%.16f/%.16f. Test loss %.16f.\\n\" % (alpha, tr, ep, MAP_test, MRR_test,",
".94, .95] no_layers = 1 dataset = \"OTC\" # OTC",
"beta edges = A_labels._indices() edges_aug, labels = ehf.augment_edges(edges, N, beta1,",
"loss_test)) if no_trials == 1: pickle.dump(ep_acc_loss, open(save_res_fname, \"wb\")) print(\"Results saved",
"ep_acc_loss[ep] = [precision_train, recall_train, f1_train, loss_train, precision_val, recall_val, f1_val, loss_val,",
"ep_acc_loss = np.zeros((no_epochs,12)) # (precision_train, recall_train, f1_train, loss_train, precision_val, recall_val,",
"features for the nodes X_train, X_val, X_test = ehf.create_node_features(A, S_train,",
"validation and testing sets edges_train, target_train, e_train, edges_val, target_val, e_val,",
"2: gcn = ehf.EmbeddingKWGCN(C_train[:-1], X_train[:-1], e_train, [6,6,2], nonlin2=\"selu\") elif no_layers",
"don't require gradient with t.no_grad(): if ep % 100 ==",
"1: gcn = ehf.EmbeddingKWGCN(C_train[:-1], X_train[:-1], e_train, [6,2]) # Train optimizer",
"== \"MAP-MRR\": MAP_test, MRR_test = ehf.compute_MAP_MRR(output_test, target_test[edges_test[0]!=0], edges_test[:, edges_test[0]!=0]) loss_test",
"[] for tr in range(no_trials): for alpha in alpha_vec: class_weights",
".84, .85, .86, .87, .88, .89, .90, .91, .92, .93,",
"loss_train, precision_val, recall_val, f1_val, loss_val, precision_test, recall_test, f1_test, loss_test] elif",
"labels into training, validation and testing sets edges_train, target_train, e_train,",
"= t.tensor([alpha, 1.0-alpha]) save_res_fname = \"results_BASELINE_layers\" + str(no_layers) + \"_w\"",
"Train loss %.16f.\" % (alpha, tr, ep, MAP_train, MRR_train, loss_train))",
"e_test) guess_test = t.argmax(output_test, dim=1) if eval_type == \"F1\": precision_test,",
"pickle.dump(ep_acc_loss_vec, open(save_res_fname + \"_no_trials\" + str(no_trials), \"wb\")) print(\"Results saved for",
"MRR_test, loss_test) for ep in range(no_epochs): # Compute loss and",
"eval_type == \"F1\": ep_acc_loss = np.zeros((no_epochs,12)) # (precision_train, recall_train, f1_train,",
"than this guess_train = t.argmax(output_train, dim=1) if eval_type == \"F1\":",
"to do link prediction # Imports and aliases import pickle",
"\"_link_prediction\" # Create gcn for training if no_layers == 2:",
"= ehf.compute_MAP_MRR(output_test, target_test[edges_test[0]!=0], edges_test[:, edges_test[0]!=0]) loss_test = criterion(output_test, target_test[edges_test[0]!=0]) #",
"else: ep_acc_loss_vec.append(ep_acc_loss) if no_trials > 1: pickle.dump(ep_acc_loss_vec, open(save_res_fname + \"_no_trials\"",
"Takes arguments (output, target) if eval_type == \"F1\": ep_acc_loss =",
"criterion = nn.CrossEntropyLoss(weight=class_weights) # Takes arguments (output, target) if eval_type",
"edges_test, target_test, e_test = ehf.split_data(edges_aug, labels, S_train, S_val, S_test, same_block_size",
"S_test, transformed=False) # Create features for the nodes X_train, X_val,",
"Val MAP/MRR %.16f/%.16f. Val loss %.16f.\" % (MAP_val, MRR_val, loss_val))",
"is to do link prediction # Imports and aliases import",
"if eval_type == \"F1\": precision_val, recall_val, f1_val = ehf.compute_f1(guess_val, target_val[edges_val[0]!=0])",
"prediction # Imports and aliases import pickle import torch as",
"%.16f.\\n\" % (MAP_test, MRR_test, loss_test)) if no_trials == 1: pickle.dump(ep_acc_loss,",
"= ehf.compute_MAP_MRR(output_val, target_val[edges_val[0]!=0], edges_val[:, edges_val[0]!=0]) loss_val = criterion(output_val, target_val[edges_val[0]!=0]) #",
"20 lr = 0.01 momentum = 0.9 # Load and",
"e_val) guess_val = t.argmax(output_val, dim=1) if eval_type == \"F1\": precision_val,",
"t.argmax(output_val, dim=1) if eval_type == \"F1\": precision_val, recall_val, f1_val =",
"data output_val = gcn(C_val[:-1], X_val[:-1], e_val) guess_val = t.argmax(output_val, dim=1)",
"torchvision import torchvision.datasets as datasets import numpy as np import",
"precision_val, recall_val, f1_val = ehf.compute_f1(guess_val, target_val[edges_val[0]!=0]) elif eval_type == \"MAP-MRR\":",
"\"MAP-MRR\": print(\"FINAL: Train MAP/MRR %.16f/%.16f. Train loss %.16f.\" % (MAP_train,",
"= 1000 mat_f_name = \"saved_content_bitcoin_otc.mat\" no_trials = 1 beta1 =",
"= t.argmax(output_train, dim=1) if eval_type == \"F1\": precision_train, recall_train, f1_train",
"for training data; no point in doing more often than",
"from scipy.sparse import csr_matrix import os.path import embedding_help_functions as ehf",
"loss_train, MAP_val, MRR_val, loss_val, MAP_test, MRR_test, loss_test) for ep in",
"f1_train, loss_train, precision_val, recall_val, f1_val, loss_val, precision_test, recall_test, f1_test, loss_test)",
"eval_type == \"MAP-MRR\": MAP_train, MRR_train = ehf.compute_MAP_MRR(output_train, target_train[edges_train[0]!=0], edges_train[:, edges_train[0]!=0])",
"loss_train)) print(\"alpha/Tr/Ep %.2f/%d/%d. Val MAP/MRR %.16f/%.16f. Val loss %.16f.\" %",
"X_train, X_val, X_test = ehf.create_node_features(A, S_train, S_val, S_test, same_block_size=False) #",
"MAP_val, MRR_val, loss_val)) print(\"alpha/Tr/Ep %.2f/%d/%d. Test MAP/MRR %.16f/%.16f. Test loss",
"alpha in alpha_vec: class_weights = t.tensor([alpha, 1.0-alpha]) save_res_fname = \"results_BASELINE_layers\"",
"\"F1\" data_loc = \"data/Bitcoin_\" + dataset + \"/\" S_train, S_val,",
"Matlab, and uses the GCN baseline # The point of",
"f1_val, loss_val, precision_test, recall_test, f1_test, loss_test, is_final=True) elif eval_type ==",
"with t.no_grad(): if ep % 100 == 0: # Compute",
".91, .92, .93, .94, .95] no_layers = 1 dataset =",
"or Alpha no_epochs = 1000 mat_f_name = \"saved_content_bitcoin_otc.mat\" no_trials =",
"this guess_train = t.argmax(output_train, dim=1) if eval_type == \"F1\": precision_train,",
"== \"MAP-MRR\": MAP_train, MRR_train = ehf.compute_MAP_MRR(output_train, target_train[edges_train[0]!=0], edges_train[:, edges_train[0]!=0]) #",
"= \"results_BASELINE_layers\" + str(no_layers) + \"_w\" + str(round(float(class_weights[0])*100)) + \"_\"",
"precision_val, recall_val, f1_val, loss_val, precision_test, recall_test, f1_test, loss_test, alpha, tr,",
"recall_test, f1_test, loss_test, alpha, tr, ep) elif eval_type == \"MAP-MRR\":",
"training, validation and testing sets edges_train, target_train, e_train, edges_val, target_val,",
"== \"MAP-MRR\": MAP_val, MRR_val = ehf.compute_MAP_MRR(output_val, target_val[edges_val[0]!=0], edges_val[:, edges_val[0]!=0]) loss_val",
"cProfile import pandas as pd import datetime from scipy.sparse import",
"if eval_type == \"F1\": precision_test, recall_test, f1_test = ehf.compute_f1(guess_test, target_test[edges_test[0]!=0])",
"as sio unsq = t.unsqueeze sq = t.squeeze # Settings",
"# Extract edges and labels from A_labels, and augment with",
"ehf.print_f1(precision_train, recall_train, f1_train, loss_train, precision_val, recall_val, f1_val, loss_val, precision_test, recall_test,",
"%.2f/%d/%d. Train MAP/MRR %.16f/%.16f. Train loss %.16f.\" % (alpha, tr,",
"== \"F1\": ep_acc_loss[ep] = [precision_train, recall_train, f1_train, loss_train, precision_val, recall_val,",
"\"MAP-MRR\": ep_acc_loss[ep] = [MAP_train, MRR_train, loss_train, MAP_val, MRR_val, loss_val, MAP_test,",
"e_train, [6,2]) # Train optimizer = t.optim.SGD(gcn.parameters(), lr=lr, momentum=momentum) criterion",
"precision_train, recall_train, f1_train = ehf.compute_f1(guess_train, target_train[edges_train[0]!=0]) elif eval_type == \"MAP-MRR\":",
"import torch as t import torch.nn as nn import torch.nn.functional",
"S_test = 95, 20, 20 lr = 0.01 momentum =",
"edges_aug, labels = ehf.augment_edges(edges, N, beta1, beta2, cutoff) # Divide",
"= 95, 20, 20 lr = 0.01 momentum = 0.9",
"Things that don't require gradient with t.no_grad(): if ep %",
"mat_f_name = \"saved_content_bitcoin_otc.mat\" no_trials = 1 beta1 = 19 beta2",
"S_train, S_val, S_test, same_block_size = False) if no_trials > 1:",
"95 eval_type = \"MAP-MRR\" # \"MAP-MRR\" or \"F1\" data_loc =",
"= ehf.EmbeddingKWGCN(C_train[:-1], X_train[:-1], e_train, [6,2]) # Train optimizer = t.optim.SGD(gcn.parameters(),",
"1 dataset = \"OTC\" # OTC or Alpha no_epochs =",
"[6,6,2], nonlin2=\"selu\") elif no_layers == 1: gcn = ehf.EmbeddingKWGCN(C_train[:-1], X_train[:-1],",
"e_val, edges_test, target_test, e_test = ehf.split_data(edges_aug, labels, S_train, S_val, S_test,",
"N, beta1, beta2, cutoff) # Divide adjacency matrices and labels",
"csr_matrix import os.path import embedding_help_functions as ehf import scipy.io as",
"MRR_train, loss_train)) print(\"alpha/Tr/Ep %.2f/%d/%d. Val MAP/MRR %.16f/%.16f. Val loss %.16f.\"",
"beta1, beta2, cutoff) # Divide adjacency matrices and labels into",
"= criterion(output_test, target_test[edges_test[0]!=0]) # Print if eval_type == \"F1\": ehf.print_f1(precision_train,",
"Test loss %.16f.\\n\" % (MAP_test, MRR_test, loss_test)) if no_trials ==",
"== \"MAP-MRR\": print(\"alpha/Tr/Ep %.2f/%d/%d. Train MAP/MRR %.16f/%.16f. Train loss %.16f.\"",
"no_layers = 1 dataset = \"OTC\" # OTC or Alpha",
"import scipy.io as sio unsq = t.unsqueeze sq = t.squeeze",
"loss_test) for ep in range(no_epochs): # Compute loss and take",
"= gcn(C_val[:-1], X_val[:-1], e_val) guess_val = t.argmax(output_val, dim=1) if eval_type",
"target_test[edges_test[0]!=0]) # Print if eval_type == \"F1\": ehf.print_f1(precision_train, recall_train, f1_train,",
"S_val, S_test, transformed=False) # Create features for the nodes X_train,",
"gradient with t.no_grad(): if ep % 100 == 0: #",
"no_layers == 2: gcn = ehf.EmbeddingKWGCN(C_train[:-1], X_train[:-1], e_train, [6,6,2], nonlin2=\"selu\")",
"np.zeros((no_epochs,12)) # (precision_train, recall_train, f1_train, loss_train, precision_val, recall_val, f1_val, loss_val,",
"nonexisting edges # edges, beta edges = A_labels._indices() edges_aug, labels",
"ehf.compute_MAP_MRR(output_train, target_train[edges_train[0]!=0], edges_train[:, edges_train[0]!=0]) # Compute stats for validation data",
"# \"MAP-MRR\" or \"F1\" data_loc = \"data/Bitcoin_\" + dataset +",
"data A, A_labels, C_train, C_val, C_test, N = ehf.load_data(data_loc, mat_f_name,",
"= t.squeeze # Settings alpha_vec = [.75, .76, .77, .78,",
"Extract edges and labels from A_labels, and augment with nonexisting",
"95, 20, 20 lr = 0.01 momentum = 0.9 #",
"MAP_test, MRR_test, loss_test] if eval_type == \"F1\": ehf.print_f1(precision_train, recall_train, f1_train,",
"dataset + \"/\" S_train, S_val, S_test = 95, 20, 20",
"Divide adjacency matrices and labels into training, validation and testing",
"# Takes arguments (output, target) if eval_type == \"F1\": ep_acc_loss",
"t.tensor([alpha, 1.0-alpha]) save_res_fname = \"results_BASELINE_layers\" + str(no_layers) + \"_w\" +",
"as datasets import numpy as np import matplotlib.pyplot as plt",
"Load and return relevant data A, A_labels, C_train, C_val, C_test,",
"Create gcn for training if no_layers == 2: gcn =",
".82, .83, .84, .85, .86, .87, .88, .89, .90, .91,",
"import torchvision.datasets as datasets import numpy as np import matplotlib.pyplot",
"recall_val, f1_val, loss_val, precision_test, recall_test, f1_test, loss_test) elif eval_type ==",
"%.2f/%d/%d. Test MAP/MRR %.16f/%.16f. Test loss %.16f.\\n\" % (alpha, tr,",
"= ehf.create_node_features(A, S_train, S_val, S_test, same_block_size=False) # Extract edges and",
"for validation data output_val = gcn(C_val[:-1], X_val[:-1], e_val) guess_val =",
"import datetime from scipy.sparse import csr_matrix import os.path import embedding_help_functions",
"%.16f.\" % (alpha, tr, ep, MAP_val, MRR_val, loss_val)) print(\"alpha/Tr/Ep %.2f/%d/%d.",
"eval_type = \"MAP-MRR\" # \"MAP-MRR\" or \"F1\" data_loc = \"data/Bitcoin_\"",
"in range(no_trials): for alpha in alpha_vec: class_weights = t.tensor([alpha, 1.0-alpha])",
"\"saved_content_bitcoin_otc.mat\" no_trials = 1 beta1 = 19 beta2 = 19",
"\"F1\": precision_val, recall_val, f1_val = ehf.compute_f1(guess_val, target_val[edges_val[0]!=0]) elif eval_type ==",
"Create features for the nodes X_train, X_val, X_test = ehf.create_node_features(A,",
"target_train[edges_train[0]!=0]) elif eval_type == \"MAP-MRR\": MAP_train, MRR_train = ehf.compute_MAP_MRR(output_train, target_train[edges_train[0]!=0],",
"X_val, X_test = ehf.create_node_features(A, S_train, S_val, S_test, same_block_size=False) # Extract",
"X_test = ehf.create_node_features(A, S_train, S_val, S_test, same_block_size=False) # Extract edges",
"str(no_layers) + \"_w\" + str(round(float(class_weights[0])*100)) + \"_\" + dataset +",
"target_train[edges_train[0]!=0], edges_train[:, edges_train[0]!=0]) # Compute stats for validation data output_val",
"1: ep_acc_loss_vec = [] for tr in range(no_trials): for alpha",
"edges_train, target_train, e_train, edges_val, target_val, e_val, edges_test, target_test, e_test =",
"np.zeros((no_epochs,9)) # (MAP_train, MRR_train, loss_train, MAP_val, MRR_val, loss_val, MAP_test, MRR_test,",
"stats for validation data output_val = gcn(C_val[:-1], X_val[:-1], e_val) guess_val",
"eval_type == \"MAP-MRR\": MAP_test, MRR_test = ehf.compute_MAP_MRR(output_test, target_test[edges_test[0]!=0], edges_test[:, edges_test[0]!=0])",
"torch as t import torch.nn as nn import torch.nn.functional as",
"= \"OTC\" # OTC or Alpha no_epochs = 1000 mat_f_name",
"in alpha_vec: class_weights = t.tensor([alpha, 1.0-alpha]) save_res_fname = \"results_BASELINE_layers\" +",
".86, .87, .88, .89, .90, .91, .92, .93, .94, .95]",
"ehf.compute_MAP_MRR(output_val, target_val[edges_val[0]!=0], edges_val[:, edges_val[0]!=0]) loss_val = criterion(output_val, target_val[edges_val[0]!=0]) # Compute",
"f1_test = ehf.compute_f1(guess_test, target_test[edges_test[0]!=0]) elif eval_type == \"MAP-MRR\": MAP_test, MRR_test",
".80, .81, .82, .83, .84, .85, .86, .87, .88, .89,",
"and aliases import pickle import torch as t import torch.nn",
"> 1: ep_acc_loss_vec = [] for tr in range(no_trials): for",
"in range(no_epochs): # Compute loss and take step optimizer.zero_grad() output_train",
"data_loc = \"data/Bitcoin_\" + dataset + \"/\" S_train, S_val, S_test",
"MRR_test = ehf.compute_MAP_MRR(output_test, target_test[edges_test[0]!=0], edges_test[:, edges_test[0]!=0]) loss_test = criterion(output_test, target_test[edges_test[0]!=0])",
"loss_val = criterion(output_val, target_val[edges_val[0]!=0]) # Compute stats for test data",
"class_weights = t.tensor([alpha, 1.0-alpha]) save_res_fname = \"results_BASELINE_layers\" + str(no_layers) +",
"no_trials > 1: ep_acc_loss_vec = [] for tr in range(no_trials):",
"= [] for tr in range(no_trials): for alpha in alpha_vec:",
"import pickle import torch as t import torch.nn as nn",
"and testing sets edges_train, target_train, e_train, edges_val, target_val, e_val, edges_test,",
"X_test[:-1], e_test) guess_test = t.argmax(output_test, dim=1) if eval_type == \"F1\":",
"matrices and labels into training, validation and testing sets edges_train,",
"testing sets edges_train, target_train, e_train, edges_val, target_val, e_val, edges_test, target_test,",
"embedding_help_functions as ehf import scipy.io as sio unsq = t.unsqueeze",
"version of the bitcoin experiment imports data preprocessed in Matlab,",
"eval_type == \"F1\": ehf.print_f1(precision_train, recall_train, f1_train, loss_train, precision_val, recall_val, f1_val,",
"%.16f/%.16f. Train loss %.16f.\" % (alpha, tr, ep, MAP_train, MRR_train,",
"script is to do link prediction # Imports and aliases",
"ehf.load_data(data_loc, mat_f_name, S_train, S_val, S_test, transformed=False) # Create features for",
"loss %.16f.\" % (alpha, tr, ep, MAP_val, MRR_val, loss_val)) print(\"alpha/Tr/Ep",
"loss_test)) # Store values with results if eval_type == \"F1\":",
"= ehf.EmbeddingKWGCN(C_train[:-1], X_train[:-1], e_train, [6,6,2], nonlin2=\"selu\") elif no_layers == 1:",
"\"MAP-MRR\": MAP_train, MRR_train = ehf.compute_MAP_MRR(output_train, target_train[edges_train[0]!=0], edges_train[:, edges_train[0]!=0]) # Compute",
"== 2: gcn = ehf.EmbeddingKWGCN(C_train[:-1], X_train[:-1], e_train, [6,6,2], nonlin2=\"selu\") elif",
"(alpha, tr, ep, MAP_test, MRR_test, loss_test)) # Store values with",
"print(\"Results saved for single trial\") else: ep_acc_loss_vec.append(ep_acc_loss) if no_trials >",
"as plt import cProfile import pandas as pd import datetime",
"numpy as np import matplotlib.pyplot as plt import cProfile import",
"data output_test = gcn(C_test[:-1], X_test[:-1], e_test) guess_test = t.argmax(output_test, dim=1)",
"if eval_type == \"F1\": ep_acc_loss[ep] = [precision_train, recall_train, f1_train, loss_train,",
"ep, MAP_train, MRR_train, loss_train)) print(\"alpha/Tr/Ep %.2f/%d/%d. Val MAP/MRR %.16f/%.16f. Val",
"edges, beta edges = A_labels._indices() edges_aug, labels = ehf.augment_edges(edges, N,",
"MAP_val, MRR_val, loss_val, MAP_test, MRR_test, loss_test) for ep in range(no_epochs):",
".83, .84, .85, .86, .87, .88, .89, .90, .91, .92,",
"OTC or Alpha no_epochs = 1000 mat_f_name = \"saved_content_bitcoin_otc.mat\" no_trials",
"\"MAP-MRR\": ep_acc_loss = np.zeros((no_epochs,9)) # (MAP_train, MRR_train, loss_train, MAP_val, MRR_val,",
"# Load and return relevant data A, A_labels, C_train, C_val,",
"% (alpha, tr, ep, MAP_val, MRR_val, loss_val)) print(\"alpha/Tr/Ep %.2f/%d/%d. Test",
"training data; no point in doing more often than this",
"loss_train, MAP_val, MRR_val, loss_val, MAP_test, MRR_test, loss_test] if eval_type ==",
"f1_test, loss_test, is_final=True) elif eval_type == \"MAP-MRR\": print(\"FINAL: Train MAP/MRR",
"# (MAP_train, MRR_train, loss_train, MAP_val, MRR_val, loss_val, MAP_test, MRR_test, loss_test)",
"target_test[edges_test[0]!=0]) elif eval_type == \"MAP-MRR\": MAP_test, MRR_test = ehf.compute_MAP_MRR(output_test, target_test[edges_test[0]!=0],",
"mat_f_name, S_train, S_val, S_test, transformed=False) # Create features for the",
"momentum = 0.9 # Load and return relevant data A,",
"C_test, N = ehf.load_data(data_loc, mat_f_name, S_train, S_val, S_test, transformed=False) #",
"matplotlib.pyplot as plt import cProfile import pandas as pd import",
"into training, validation and testing sets edges_train, target_train, e_train, edges_val,",
"datasets import numpy as np import matplotlib.pyplot as plt import",
"stats for test data output_test = gcn(C_test[:-1], X_test[:-1], e_test) guess_test",
"e_train, edges_val, target_val, e_val, edges_test, target_test, e_test = ehf.split_data(edges_aug, labels,",
"import csr_matrix import os.path import embedding_help_functions as ehf import scipy.io",
"in Matlab, and uses the GCN baseline # The point",
"ehf.EmbeddingKWGCN(C_train[:-1], X_train[:-1], e_train, [6,6,2], nonlin2=\"selu\") elif no_layers == 1: gcn",
"and return relevant data A, A_labels, C_train, C_val, C_test, N",
"step optimizer.zero_grad() output_train = gcn() loss_train = criterion(output_train, target_train[edges_train[0]!=0]) loss_train.backward()",
"beta2, cutoff) # Divide adjacency matrices and labels into training,",
"(precision_train, recall_train, f1_train, loss_train, precision_val, recall_val, f1_val, loss_val, precision_test, recall_test,",
"dim=1) if eval_type == \"F1\": precision_test, recall_test, f1_test = ehf.compute_f1(guess_test,",
"loss_train, precision_val, recall_val, f1_val, loss_val, precision_test, recall_test, f1_test, loss_test, alpha,",
"[MAP_train, MRR_train, loss_train, MAP_val, MRR_val, loss_val, MAP_test, MRR_test, loss_test] if",
"== \"F1\": ehf.print_f1(precision_train, recall_train, f1_train, loss_train, precision_val, recall_val, f1_val, loss_val,",
"eval_type == \"MAP-MRR\": ep_acc_loss = np.zeros((no_epochs,9)) # (MAP_train, MRR_train, loss_train,",
"baseline # The point of this script is to do",
"single trial\") else: ep_acc_loss_vec.append(ep_acc_loss) if no_trials > 1: pickle.dump(ep_acc_loss_vec, open(save_res_fname",
"gcn = ehf.EmbeddingKWGCN(C_train[:-1], X_train[:-1], e_train, [6,2]) # Train optimizer =",
"ep in range(no_epochs): # Compute loss and take step optimizer.zero_grad()",
"# Train optimizer = t.optim.SGD(gcn.parameters(), lr=lr, momentum=momentum) criterion = nn.CrossEntropyLoss(weight=class_weights)",
"if ep % 100 == 0: # Compute stats for",
"loss_train, precision_val, recall_val, f1_val, loss_val, precision_test, recall_test, f1_test, loss_test) elif",
"guess_val = t.argmax(output_val, dim=1) if eval_type == \"F1\": precision_val, recall_val,",
"# Compute stats for test data output_test = gcn(C_test[:-1], X_test[:-1],",
"no_trials > 1: pickle.dump(ep_acc_loss_vec, open(save_res_fname + \"_no_trials\" + str(no_trials), \"wb\"))",
"bitcoin experiment imports data preprocessed in Matlab, and uses the",
"t.unsqueeze sq = t.squeeze # Settings alpha_vec = [.75, .76,",
".81, .82, .83, .84, .85, .86, .87, .88, .89, .90,",
"pandas as pd import datetime from scipy.sparse import csr_matrix import",
"output_val = gcn(C_val[:-1], X_val[:-1], e_val) guess_val = t.argmax(output_val, dim=1) if",
"sq = t.squeeze # Settings alpha_vec = [.75, .76, .77,",
"loss and take step optimizer.zero_grad() output_train = gcn() loss_train =",
"MAP_val, MRR_val = ehf.compute_MAP_MRR(output_val, target_val[edges_val[0]!=0], edges_val[:, edges_val[0]!=0]) loss_val = criterion(output_val,",
"recall_val, f1_val, loss_val, precision_test, recall_test, f1_test, loss_test] elif eval_type ==",
"loss_val, precision_test, recall_test, f1_test, loss_test] elif eval_type == \"MAP-MRR\": ep_acc_loss[ep]",
"(MAP_test, MRR_test, loss_test)) if no_trials == 1: pickle.dump(ep_acc_loss, open(save_res_fname, \"wb\"))",
"dim=1) if eval_type == \"F1\": precision_train, recall_train, f1_train = ehf.compute_f1(guess_train,",
"f1_val = ehf.compute_f1(guess_val, target_val[edges_val[0]!=0]) elif eval_type == \"MAP-MRR\": MAP_val, MRR_val",
"elif eval_type == \"MAP-MRR\": print(\"FINAL: Train MAP/MRR %.16f/%.16f. Train loss",
"no_epochs = 1000 mat_f_name = \"saved_content_bitcoin_otc.mat\" no_trials = 1 beta1",
"for test data output_test = gcn(C_test[:-1], X_test[:-1], e_test) guess_test =",
"MRR_train = ehf.compute_MAP_MRR(output_train, target_train[edges_train[0]!=0], edges_train[:, edges_train[0]!=0]) # Compute stats for",
"loss_test, is_final=True) elif eval_type == \"MAP-MRR\": print(\"FINAL: Train MAP/MRR %.16f/%.16f.",
"and take step optimizer.zero_grad() output_train = gcn() loss_train = criterion(output_train,",
"Train optimizer = t.optim.SGD(gcn.parameters(), lr=lr, momentum=momentum) criterion = nn.CrossEntropyLoss(weight=class_weights) #",
"as np import matplotlib.pyplot as plt import cProfile import pandas",
"Compute stats for training data; no point in doing more",
"eval_type == \"F1\": precision_train, recall_train, f1_train = ehf.compute_f1(guess_train, target_train[edges_train[0]!=0]) elif",
"if eval_type == \"F1\": ep_acc_loss = np.zeros((no_epochs,12)) # (precision_train, recall_train,",
"% (MAP_val, MRR_val, loss_val)) print(\"FINAL: Test MAP/MRR %.16f/%.16f. Test loss",
"(MAP_train, MRR_train, loss_train)) print(\"FINAL: Val MAP/MRR %.16f/%.16f. Val loss %.16f.\"",
"False) if no_trials > 1: ep_acc_loss_vec = [] for tr",
"Print if eval_type == \"F1\": ehf.print_f1(precision_train, recall_train, f1_train, loss_train, precision_val,",
"range(no_epochs): # Compute loss and take step optimizer.zero_grad() output_train =",
"import embedding_help_functions as ehf import scipy.io as sio unsq =",
"S_train, S_val, S_test = 95, 20, 20 lr = 0.01",
"recall_train, f1_train = ehf.compute_f1(guess_train, target_train[edges_train[0]!=0]) elif eval_type == \"MAP-MRR\": MAP_train,",
"for tr in range(no_trials): for alpha in alpha_vec: class_weights =",
"aliases import pickle import torch as t import torch.nn as",
"tr in range(no_trials): for alpha in alpha_vec: class_weights = t.tensor([alpha,",
"pd import datetime from scipy.sparse import csr_matrix import os.path import",
".77, .78, .79, .80, .81, .82, .83, .84, .85, .86,",
"= criterion(output_train, target_train[edges_train[0]!=0]) loss_train.backward() optimizer.step() # Things that don't require",
"trial\") else: ep_acc_loss_vec.append(ep_acc_loss) if no_trials > 1: pickle.dump(ep_acc_loss_vec, open(save_res_fname +",
"nonlin2=\"selu\") elif no_layers == 1: gcn = ehf.EmbeddingKWGCN(C_train[:-1], X_train[:-1], e_train,",
"Val loss %.16f.\" % (MAP_val, MRR_val, loss_val)) print(\"FINAL: Test MAP/MRR",
"= t.unsqueeze sq = t.squeeze # Settings alpha_vec = [.75,",
"datetime from scipy.sparse import csr_matrix import os.path import embedding_help_functions as",
"ep_acc_loss = np.zeros((no_epochs,9)) # (MAP_train, MRR_train, loss_train, MAP_val, MRR_val, loss_val,",
"= criterion(output_val, target_val[edges_val[0]!=0]) # Compute stats for test data output_test",
"A_labels._indices() edges_aug, labels = ehf.augment_edges(edges, N, beta1, beta2, cutoff) #",
"with nonexisting edges # edges, beta edges = A_labels._indices() edges_aug,",
"criterion(output_val, target_val[edges_val[0]!=0]) # Compute stats for test data output_test =",
"% (alpha, tr, ep, MAP_train, MRR_train, loss_train)) print(\"alpha/Tr/Ep %.2f/%d/%d. Val",
"# Store values with results if eval_type == \"F1\": ep_acc_loss[ep]",
"precision_test, recall_test, f1_test, loss_test, alpha, tr, ep) elif eval_type ==",
"= nn.CrossEntropyLoss(weight=class_weights) # Takes arguments (output, target) if eval_type ==",
"edges and labels from A_labels, and augment with nonexisting edges",
"uses the GCN baseline # The point of this script",
"import cProfile import pandas as pd import datetime from scipy.sparse",
".95] no_layers = 1 dataset = \"OTC\" # OTC or",
"torchvision.datasets as datasets import numpy as np import matplotlib.pyplot as",
"\"F1\": ep_acc_loss[ep] = [precision_train, recall_train, f1_train, loss_train, precision_val, recall_val, f1_val,",
"and augment with nonexisting edges # edges, beta edges =",
"ep_acc_loss[ep] = [MAP_train, MRR_train, loss_train, MAP_val, MRR_val, loss_val, MAP_test, MRR_test,",
"ehf.compute_f1(guess_test, target_test[edges_test[0]!=0]) elif eval_type == \"MAP-MRR\": MAP_test, MRR_test = ehf.compute_MAP_MRR(output_test,",
"pickle import torch as t import torch.nn as nn import",
"0.01 momentum = 0.9 # Load and return relevant data",
"ehf.compute_MAP_MRR(output_test, target_test[edges_test[0]!=0], edges_test[:, edges_test[0]!=0]) loss_test = criterion(output_test, target_test[edges_test[0]!=0]) # Print"
] |
[
"alpha=0.93, activation_func='multiquadric', regressor=linear_model.Ridge(), random_state=21398023) cls.fit(train_x, train_y) # Evaluate model print",
"'rb') as f: return cPickle.load(f) def get_datasets(data): _train_x, _train_y =",
"ELM cls = ELMClassifier(n_hidden=7000, alpha=0.93, activation_func='multiquadric', regressor=linear_model.Ridge(), random_state=21398023) cls.fit(train_x, train_y)",
"train_y) # Evaluate model print 'Validation error:', cls.score(val_x, val_y) print",
"ELMClassifier(n_hidden=7000, alpha=0.93, activation_func='multiquadric', regressor=linear_model.Ridge(), random_state=21398023) cls.fit(train_x, train_y) # Evaluate model",
"data[1][0], np.array(data[1][1]).reshape(len(data[1][1]), 1) _test_x, _test_y = data[2][0], np.array(data[2][1]).reshape(len(data[2][1]), 1) return",
"regressor=linear_model.Ridge(), random_state=21398023) cls.fit(train_x, train_y) # Evaluate model print 'Validation error:',",
"1) return _train_x, _train_y, _val_x, _val_y, _test_x, _test_y if __name__",
"data[2][0], np.array(data[2][1]).reshape(len(data[2][1]), 1) return _train_x, _train_y, _val_x, _val_y, _test_x, _test_y",
"test_x, test_y = get_datasets(load_mnist()) # Build ELM cls = ELMClassifier(n_hidden=7000,",
"return cPickle.load(f) def get_datasets(data): _train_x, _train_y = data[0][0], np.array(data[0][1]).reshape(len(data[0][1]), 1)",
"np.array(data[1][1]).reshape(len(data[1][1]), 1) _test_x, _test_y = data[2][0], np.array(data[2][1]).reshape(len(data[2][1]), 1) return _train_x,",
"= get_datasets(load_mnist()) # Build ELM cls = ELMClassifier(n_hidden=7000, alpha=0.93, activation_func='multiquadric',",
"_test_y = data[2][0], np.array(data[2][1]).reshape(len(data[2][1]), 1) return _train_x, _train_y, _val_x, _val_y,",
"val_x, val_y, test_x, test_y = get_datasets(load_mnist()) # Build ELM cls",
"val_y, test_x, test_y = get_datasets(load_mnist()) # Build ELM cls =",
"cls = ELMClassifier(n_hidden=7000, alpha=0.93, activation_func='multiquadric', regressor=linear_model.Ridge(), random_state=21398023) cls.fit(train_x, train_y) #",
"def load_mnist(path='../Data/mnist.pkl'): with open(path, 'rb') as f: return cPickle.load(f) def",
"open(path, 'rb') as f: return cPickle.load(f) def get_datasets(data): _train_x, _train_y",
"get_datasets(data): _train_x, _train_y = data[0][0], np.array(data[0][1]).reshape(len(data[0][1]), 1) _val_x, _val_y =",
"from sklearn import linear_model def load_mnist(path='../Data/mnist.pkl'): with open(path, 'rb') as",
"_train_y = data[0][0], np.array(data[0][1]).reshape(len(data[0][1]), 1) _val_x, _val_y = data[1][0], np.array(data[1][1]).reshape(len(data[1][1]),",
"1) _val_x, _val_y = data[1][0], np.array(data[1][1]).reshape(len(data[1][1]), 1) _test_x, _test_y =",
"data sets train_x, train_y, val_x, val_y, test_x, test_y = get_datasets(load_mnist())",
"cPickle import numpy as np from elm import ELMClassifier from",
"from elm import ELMClassifier from sklearn import linear_model def load_mnist(path='../Data/mnist.pkl'):",
"_train_x, _train_y, _val_x, _val_y, _test_x, _test_y if __name__ == '__main__':",
"np.array(data[0][1]).reshape(len(data[0][1]), 1) _val_x, _val_y = data[1][0], np.array(data[1][1]).reshape(len(data[1][1]), 1) _test_x, _test_y",
"elm import ELMClassifier from sklearn import linear_model def load_mnist(path='../Data/mnist.pkl'): with",
"f: return cPickle.load(f) def get_datasets(data): _train_x, _train_y = data[0][0], np.array(data[0][1]).reshape(len(data[0][1]),",
"_test_x, _test_y = data[2][0], np.array(data[2][1]).reshape(len(data[2][1]), 1) return _train_x, _train_y, _val_x,",
"_val_y, _test_x, _test_y if __name__ == '__main__': # Load data",
"linear_model def load_mnist(path='../Data/mnist.pkl'): with open(path, 'rb') as f: return cPickle.load(f)",
"cls.fit(train_x, train_y) # Evaluate model print 'Validation error:', cls.score(val_x, val_y)",
"activation_func='multiquadric', regressor=linear_model.Ridge(), random_state=21398023) cls.fit(train_x, train_y) # Evaluate model print 'Validation",
"numpy as np from elm import ELMClassifier from sklearn import",
"_train_y, _val_x, _val_y, _test_x, _test_y if __name__ == '__main__': #",
"model print 'Validation error:', cls.score(val_x, val_y) print 'Test error:', cls.score(test_x,",
"= data[1][0], np.array(data[1][1]).reshape(len(data[1][1]), 1) _test_x, _test_y = data[2][0], np.array(data[2][1]).reshape(len(data[2][1]), 1)",
"Load data sets train_x, train_y, val_x, val_y, test_x, test_y =",
"def get_datasets(data): _train_x, _train_y = data[0][0], np.array(data[0][1]).reshape(len(data[0][1]), 1) _val_x, _val_y",
"with open(path, 'rb') as f: return cPickle.load(f) def get_datasets(data): _train_x,",
"import ELMClassifier from sklearn import linear_model def load_mnist(path='../Data/mnist.pkl'): with open(path,",
"if __name__ == '__main__': # Load data sets train_x, train_y,",
"test_y = get_datasets(load_mnist()) # Build ELM cls = ELMClassifier(n_hidden=7000, alpha=0.93,",
"ELMClassifier from sklearn import linear_model def load_mnist(path='../Data/mnist.pkl'): with open(path, 'rb')",
"== '__main__': # Load data sets train_x, train_y, val_x, val_y,",
"as np from elm import ELMClassifier from sklearn import linear_model",
"sets train_x, train_y, val_x, val_y, test_x, test_y = get_datasets(load_mnist()) #",
"np from elm import ELMClassifier from sklearn import linear_model def",
"1) _test_x, _test_y = data[2][0], np.array(data[2][1]).reshape(len(data[2][1]), 1) return _train_x, _train_y,",
"Evaluate model print 'Validation error:', cls.score(val_x, val_y) print 'Test error:',",
"= ELMClassifier(n_hidden=7000, alpha=0.93, activation_func='multiquadric', regressor=linear_model.Ridge(), random_state=21398023) cls.fit(train_x, train_y) # Evaluate",
"_test_y if __name__ == '__main__': # Load data sets train_x,",
"<reponame>ahara/-blog import cPickle import numpy as np from elm import",
"import numpy as np from elm import ELMClassifier from sklearn",
"cPickle.load(f) def get_datasets(data): _train_x, _train_y = data[0][0], np.array(data[0][1]).reshape(len(data[0][1]), 1) _val_x,",
"_test_x, _test_y if __name__ == '__main__': # Load data sets",
"print 'Validation error:', cls.score(val_x, val_y) print 'Test error:', cls.score(test_x, test_y)",
"= data[0][0], np.array(data[0][1]).reshape(len(data[0][1]), 1) _val_x, _val_y = data[1][0], np.array(data[1][1]).reshape(len(data[1][1]), 1)",
"import cPickle import numpy as np from elm import ELMClassifier",
"get_datasets(load_mnist()) # Build ELM cls = ELMClassifier(n_hidden=7000, alpha=0.93, activation_func='multiquadric', regressor=linear_model.Ridge(),",
"# Load data sets train_x, train_y, val_x, val_y, test_x, test_y",
"__name__ == '__main__': # Load data sets train_x, train_y, val_x,",
"# Evaluate model print 'Validation error:', cls.score(val_x, val_y) print 'Test",
"train_x, train_y, val_x, val_y, test_x, test_y = get_datasets(load_mnist()) # Build",
"return _train_x, _train_y, _val_x, _val_y, _test_x, _test_y if __name__ ==",
"_train_x, _train_y = data[0][0], np.array(data[0][1]).reshape(len(data[0][1]), 1) _val_x, _val_y = data[1][0],",
"load_mnist(path='../Data/mnist.pkl'): with open(path, 'rb') as f: return cPickle.load(f) def get_datasets(data):",
"data[0][0], np.array(data[0][1]).reshape(len(data[0][1]), 1) _val_x, _val_y = data[1][0], np.array(data[1][1]).reshape(len(data[1][1]), 1) _test_x,",
"_val_x, _val_y = data[1][0], np.array(data[1][1]).reshape(len(data[1][1]), 1) _test_x, _test_y = data[2][0],",
"random_state=21398023) cls.fit(train_x, train_y) # Evaluate model print 'Validation error:', cls.score(val_x,",
"sklearn import linear_model def load_mnist(path='../Data/mnist.pkl'): with open(path, 'rb') as f:",
"_val_y = data[1][0], np.array(data[1][1]).reshape(len(data[1][1]), 1) _test_x, _test_y = data[2][0], np.array(data[2][1]).reshape(len(data[2][1]),",
"'__main__': # Load data sets train_x, train_y, val_x, val_y, test_x,",
"import linear_model def load_mnist(path='../Data/mnist.pkl'): with open(path, 'rb') as f: return",
"Build ELM cls = ELMClassifier(n_hidden=7000, alpha=0.93, activation_func='multiquadric', regressor=linear_model.Ridge(), random_state=21398023) cls.fit(train_x,",
"np.array(data[2][1]).reshape(len(data[2][1]), 1) return _train_x, _train_y, _val_x, _val_y, _test_x, _test_y if",
"_val_x, _val_y, _test_x, _test_y if __name__ == '__main__': # Load",
"train_y, val_x, val_y, test_x, test_y = get_datasets(load_mnist()) # Build ELM",
"as f: return cPickle.load(f) def get_datasets(data): _train_x, _train_y = data[0][0],",
"= data[2][0], np.array(data[2][1]).reshape(len(data[2][1]), 1) return _train_x, _train_y, _val_x, _val_y, _test_x,",
"# Build ELM cls = ELMClassifier(n_hidden=7000, alpha=0.93, activation_func='multiquadric', regressor=linear_model.Ridge(), random_state=21398023)"
] |
[
"as msg: print(msg); sys.exit(1) while 1: conn, addr = sock_self.accept()",
"= bob.send_cipher_key() sock_with_kdc.send(bob_cipher_key_packet.encode()) kdc_bob_cipher_key_packet = sock_with_kdc.recv(1024).decode() print(kdc_bob_cipher_key_packet) bob.process_packet(kdc_bob_cipher_key_packet) except socket.error",
"sock_self.bind((bob_host, bob_port)) sock_self.listen(10) except socket.error as msg: print(msg); sys.exit(1) while",
"connection from user {0}'.format(addr)); #conn.settimeout(500) # conn.send(b'Hi, This is bob.",
"bytes.decode(buf).rstrip('\\x00') reply_packet = bob.process_packet(receive_packet) conn.send(reply_packet.encode()) buf = conn.recv(1024) else: time.sleep(0.5)",
"socket.SO_REUSEADDR, 1) sock_self.bind((bob_host, bob_port)) sock_self.listen(10) except socket.error as msg: print(msg);",
"= socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock_self.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) sock_self.bind((bob_host, bob_port)) sock_self.listen(10) except",
"9999 bob_host, bob_port = 'localhost', 9200 # talk to kdc",
"except socket.error as msg: print(msg); sys.exit(1) # sock_with_kdc.shutdown(socket.SHUT_WR) # talk",
"for your sess key') buf = conn.recv(1024) while True: if",
"print(msg); sys.exit(1) while 1: conn, addr = sock_self.accept() thread =",
"#conn.settimeout(500) # conn.send(b'Hi, This is bob. Waiting for your sess",
"your sess key') buf = conn.recv(1024) while True: if buf:",
"socket.error as msg: print(msg); sys.exit(1) # sock_with_kdc.shutdown(socket.SHUT_WR) # talk to",
"-*- #!/usr/bin/env python3 from PKC_Classes import NetworkUser, KDC from DES",
"key try: sock_with_kdc = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock_with_kdc.connect((kdc_host, kdc_port)) print(sock_with_kdc.recv(1024)) #",
"except socket.error as msg: print(msg); sys.exit(1) while 1: conn, addr",
"# -*- coding: utf-8 -*- #!/usr/bin/env python3 from PKC_Classes import",
"else: time.sleep(0.5) conn.close() bob = NetworkUser('Alice', DES(), RSA(9973, 97), 200)",
"kdc for sess key try: sock_with_kdc = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock_with_kdc.connect((kdc_host,",
"bob_host, bob_port = 'localhost', 9200 # talk to kdc for",
"coding: utf-8 -*- #!/usr/bin/env python3 from PKC_Classes import NetworkUser, KDC",
"{0}'.format(addr)); #conn.settimeout(500) # conn.send(b'Hi, This is bob. Waiting for your",
"import NetworkUser, KDC from DES import DES from RSA_Class import",
"sys.exit(1) while 1: conn, addr = sock_self.accept() thread = threading.Thread(target=reply_conn,",
"new connection from user {0}'.format(addr)); #conn.settimeout(500) # conn.send(b'Hi, This is",
"bob.uid) # socket communication kdc_host, kdc_port = 'localhost', 9999 bob_host,",
"'localhost', 9200 # talk to kdc for sess key try:",
"bob_cipher_key_packet = bob.send_cipher_key() sock_with_kdc.send(bob_cipher_key_packet.encode()) kdc_bob_cipher_key_packet = sock_with_kdc.recv(1024).decode() print(kdc_bob_cipher_key_packet) bob.process_packet(kdc_bob_cipher_key_packet) except",
"RSA_Class import RSA import socket import os import sys import",
"sock_with_kdc.send(bob_cipher_key_packet.encode()) kdc_bob_cipher_key_packet = sock_with_kdc.recv(1024).decode() print(kdc_bob_cipher_key_packet) bob.process_packet(kdc_bob_cipher_key_packet) except socket.error as msg:",
"be using Python 3\") def reply_conn(conn, addr): print('Accept new connection",
"to kdc for sess key try: sock_with_kdc = socket.socket(socket.AF_INET, socket.SOCK_STREAM)",
"python3 from PKC_Classes import NetworkUser, KDC from DES import DES",
"RSA(9973, 97), 200) print('bob:', bob.uid) # socket communication kdc_host, kdc_port",
"# talk to bob try: sock_self = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock_self.setsockopt(socket.SOL_SOCKET,",
"sys.exit(1) # sock_with_kdc.shutdown(socket.SHUT_WR) # talk to bob try: sock_self =",
"sock_self.listen(10) except socket.error as msg: print(msg); sys.exit(1) while 1: conn,",
"= conn.recv(1024) while True: if buf: receive_packet = bytes.decode(buf).rstrip('\\x00') reply_packet",
"RSA import socket import os import sys import threading import",
"1) sock_self.bind((bob_host, bob_port)) sock_self.listen(10) except socket.error as msg: print(msg); sys.exit(1)",
"try: sock_with_kdc = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock_with_kdc.connect((kdc_host, kdc_port)) print(sock_with_kdc.recv(1024)) # send",
"print(kdc_bob_cipher_key_packet) bob.process_packet(kdc_bob_cipher_key_packet) except socket.error as msg: print(msg); sys.exit(1) # sock_with_kdc.shutdown(socket.SHUT_WR)",
"receive_packet = bytes.decode(buf).rstrip('\\x00') reply_packet = bob.process_packet(receive_packet) conn.send(reply_packet.encode()) buf = conn.recv(1024)",
"200) print('bob:', bob.uid) # socket communication kdc_host, kdc_port = 'localhost',",
"from PKC_Classes import NetworkUser, KDC from DES import DES from",
"conn.recv(1024) while True: if buf: receive_packet = bytes.decode(buf).rstrip('\\x00') reply_packet =",
"DES import DES from RSA_Class import RSA import socket import",
"while True: if buf: receive_packet = bytes.decode(buf).rstrip('\\x00') reply_packet = bob.process_packet(receive_packet)",
"import threading import time if sys.version_info[0] < 3: raise Exception(\"Must",
"# talk to kdc for sess key try: sock_with_kdc =",
"bob. Waiting for your sess key') buf = conn.recv(1024) while",
"print('Accept new connection from user {0}'.format(addr)); #conn.settimeout(500) # conn.send(b'Hi, This",
"buf = conn.recv(1024) else: time.sleep(0.5) conn.close() bob = NetworkUser('Alice', DES(),",
"97), 200) print('bob:', bob.uid) # socket communication kdc_host, kdc_port =",
"socket import os import sys import threading import time if",
"# conn.send(b'Hi, This is bob. Waiting for your sess key')",
"sess key') buf = conn.recv(1024) while True: if buf: receive_packet",
"# sock_with_kdc.shutdown(socket.SHUT_WR) # talk to bob try: sock_self = socket.socket(socket.AF_INET,",
"is bob. Waiting for your sess key') buf = conn.recv(1024)",
"conn.send(b'Hi, This is bob. Waiting for your sess key') buf",
"= 'localhost', 9200 # talk to kdc for sess key",
"msg: print(msg); sys.exit(1) # sock_with_kdc.shutdown(socket.SHUT_WR) # talk to bob try:",
"True: if buf: receive_packet = bytes.decode(buf).rstrip('\\x00') reply_packet = bob.process_packet(receive_packet) conn.send(reply_packet.encode())",
"print(msg); sys.exit(1) # sock_with_kdc.shutdown(socket.SHUT_WR) # talk to bob try: sock_self",
"if sys.version_info[0] < 3: raise Exception(\"Must be using Python 3\")",
"= NetworkUser('Alice', DES(), RSA(9973, 97), 200) print('bob:', bob.uid) # socket",
"try: sock_self = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock_self.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) sock_self.bind((bob_host, bob_port))",
"import time if sys.version_info[0] < 3: raise Exception(\"Must be using",
"print(sock_with_kdc.recv(1024)) # send cipher_key bob_cipher_key_packet = bob.send_cipher_key() sock_with_kdc.send(bob_cipher_key_packet.encode()) kdc_bob_cipher_key_packet =",
"sock_with_kdc.recv(1024).decode() print(kdc_bob_cipher_key_packet) bob.process_packet(kdc_bob_cipher_key_packet) except socket.error as msg: print(msg); sys.exit(1) #",
"'localhost', 9999 bob_host, bob_port = 'localhost', 9200 # talk to",
"import RSA import socket import os import sys import threading",
"= sock_with_kdc.recv(1024).decode() print(kdc_bob_cipher_key_packet) bob.process_packet(kdc_bob_cipher_key_packet) except socket.error as msg: print(msg); sys.exit(1)",
"= sock_self.accept() thread = threading.Thread(target=reply_conn, args=(conn, addr)) thread.start() # sock_self.close()",
"socket.SOCK_STREAM) sock_self.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) sock_self.bind((bob_host, bob_port)) sock_self.listen(10) except socket.error as",
"sock_self = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock_self.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) sock_self.bind((bob_host, bob_port)) sock_self.listen(10)",
"conn.recv(1024) else: time.sleep(0.5) conn.close() bob = NetworkUser('Alice', DES(), RSA(9973, 97),",
"NetworkUser, KDC from DES import DES from RSA_Class import RSA",
"bob_port = 'localhost', 9200 # talk to kdc for sess",
"= 'localhost', 9999 bob_host, bob_port = 'localhost', 9200 # talk",
"buf = conn.recv(1024) while True: if buf: receive_packet = bytes.decode(buf).rstrip('\\x00')",
"bob try: sock_self = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock_self.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) sock_self.bind((bob_host,",
"Exception(\"Must be using Python 3\") def reply_conn(conn, addr): print('Accept new",
"DES from RSA_Class import RSA import socket import os import",
"3: raise Exception(\"Must be using Python 3\") def reply_conn(conn, addr):",
"DES(), RSA(9973, 97), 200) print('bob:', bob.uid) # socket communication kdc_host,",
"-*- coding: utf-8 -*- #!/usr/bin/env python3 from PKC_Classes import NetworkUser,",
"sys import threading import time if sys.version_info[0] < 3: raise",
"bob.process_packet(kdc_bob_cipher_key_packet) except socket.error as msg: print(msg); sys.exit(1) # sock_with_kdc.shutdown(socket.SHUT_WR) #",
"= conn.recv(1024) else: time.sleep(0.5) conn.close() bob = NetworkUser('Alice', DES(), RSA(9973,",
"bob.send_cipher_key() sock_with_kdc.send(bob_cipher_key_packet.encode()) kdc_bob_cipher_key_packet = sock_with_kdc.recv(1024).decode() print(kdc_bob_cipher_key_packet) bob.process_packet(kdc_bob_cipher_key_packet) except socket.error as",
"import sys import threading import time if sys.version_info[0] < 3:",
"PKC_Classes import NetworkUser, KDC from DES import DES from RSA_Class",
"socket communication kdc_host, kdc_port = 'localhost', 9999 bob_host, bob_port =",
"This is bob. Waiting for your sess key') buf =",
"from DES import DES from RSA_Class import RSA import socket",
"9200 # talk to kdc for sess key try: sock_with_kdc",
"kdc_host, kdc_port = 'localhost', 9999 bob_host, bob_port = 'localhost', 9200",
"Waiting for your sess key') buf = conn.recv(1024) while True:",
"import os import sys import threading import time if sys.version_info[0]",
"kdc_bob_cipher_key_packet = sock_with_kdc.recv(1024).decode() print(kdc_bob_cipher_key_packet) bob.process_packet(kdc_bob_cipher_key_packet) except socket.error as msg: print(msg);",
"= bob.process_packet(receive_packet) conn.send(reply_packet.encode()) buf = conn.recv(1024) else: time.sleep(0.5) conn.close() bob",
"reply_packet = bob.process_packet(receive_packet) conn.send(reply_packet.encode()) buf = conn.recv(1024) else: time.sleep(0.5) conn.close()",
"os import sys import threading import time if sys.version_info[0] <",
"sock_with_kdc.connect((kdc_host, kdc_port)) print(sock_with_kdc.recv(1024)) # send cipher_key bob_cipher_key_packet = bob.send_cipher_key() sock_with_kdc.send(bob_cipher_key_packet.encode())",
"communication kdc_host, kdc_port = 'localhost', 9999 bob_host, bob_port = 'localhost',",
"reply_conn(conn, addr): print('Accept new connection from user {0}'.format(addr)); #conn.settimeout(500) #",
"while 1: conn, addr = sock_self.accept() thread = threading.Thread(target=reply_conn, args=(conn,",
"# send cipher_key bob_cipher_key_packet = bob.send_cipher_key() sock_with_kdc.send(bob_cipher_key_packet.encode()) kdc_bob_cipher_key_packet = sock_with_kdc.recv(1024).decode()",
"def reply_conn(conn, addr): print('Accept new connection from user {0}'.format(addr)); #conn.settimeout(500)",
"conn.send(reply_packet.encode()) buf = conn.recv(1024) else: time.sleep(0.5) conn.close() bob = NetworkUser('Alice',",
"# socket communication kdc_host, kdc_port = 'localhost', 9999 bob_host, bob_port",
"kdc_port = 'localhost', 9999 bob_host, bob_port = 'localhost', 9200 #",
"threading import time if sys.version_info[0] < 3: raise Exception(\"Must be",
"buf: receive_packet = bytes.decode(buf).rstrip('\\x00') reply_packet = bob.process_packet(receive_packet) conn.send(reply_packet.encode()) buf =",
"sock_with_kdc = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock_with_kdc.connect((kdc_host, kdc_port)) print(sock_with_kdc.recv(1024)) # send cipher_key",
"time.sleep(0.5) conn.close() bob = NetworkUser('Alice', DES(), RSA(9973, 97), 200) print('bob:',",
"sess key try: sock_with_kdc = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock_with_kdc.connect((kdc_host, kdc_port)) print(sock_with_kdc.recv(1024))",
"kdc_port)) print(sock_with_kdc.recv(1024)) # send cipher_key bob_cipher_key_packet = bob.send_cipher_key() sock_with_kdc.send(bob_cipher_key_packet.encode()) kdc_bob_cipher_key_packet",
"socket.SOCK_STREAM) sock_with_kdc.connect((kdc_host, kdc_port)) print(sock_with_kdc.recv(1024)) # send cipher_key bob_cipher_key_packet = bob.send_cipher_key()",
"3\") def reply_conn(conn, addr): print('Accept new connection from user {0}'.format(addr));",
"KDC from DES import DES from RSA_Class import RSA import",
"talk to kdc for sess key try: sock_with_kdc = socket.socket(socket.AF_INET,",
"bob = NetworkUser('Alice', DES(), RSA(9973, 97), 200) print('bob:', bob.uid) #",
"using Python 3\") def reply_conn(conn, addr): print('Accept new connection from",
"socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock_with_kdc.connect((kdc_host, kdc_port)) print(sock_with_kdc.recv(1024)) # send cipher_key bob_cipher_key_packet =",
"talk to bob try: sock_self = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock_self.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR,",
"as msg: print(msg); sys.exit(1) # sock_with_kdc.shutdown(socket.SHUT_WR) # talk to bob",
"Python 3\") def reply_conn(conn, addr): print('Accept new connection from user",
"addr): print('Accept new connection from user {0}'.format(addr)); #conn.settimeout(500) # conn.send(b'Hi,",
"import DES from RSA_Class import RSA import socket import os",
"from RSA_Class import RSA import socket import os import sys",
"from user {0}'.format(addr)); #conn.settimeout(500) # conn.send(b'Hi, This is bob. Waiting",
"key') buf = conn.recv(1024) while True: if buf: receive_packet =",
"conn.close() bob = NetworkUser('Alice', DES(), RSA(9973, 97), 200) print('bob:', bob.uid)",
"to bob try: sock_self = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock_self.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)",
"if buf: receive_packet = bytes.decode(buf).rstrip('\\x00') reply_packet = bob.process_packet(receive_packet) conn.send(reply_packet.encode()) buf",
"addr = sock_self.accept() thread = threading.Thread(target=reply_conn, args=(conn, addr)) thread.start() #",
"raise Exception(\"Must be using Python 3\") def reply_conn(conn, addr): print('Accept",
"user {0}'.format(addr)); #conn.settimeout(500) # conn.send(b'Hi, This is bob. Waiting for",
"cipher_key bob_cipher_key_packet = bob.send_cipher_key() sock_with_kdc.send(bob_cipher_key_packet.encode()) kdc_bob_cipher_key_packet = sock_with_kdc.recv(1024).decode() print(kdc_bob_cipher_key_packet) bob.process_packet(kdc_bob_cipher_key_packet)",
"#!/usr/bin/env python3 from PKC_Classes import NetworkUser, KDC from DES import",
"for sess key try: sock_with_kdc = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock_with_kdc.connect((kdc_host, kdc_port))",
"time if sys.version_info[0] < 3: raise Exception(\"Must be using Python",
"utf-8 -*- #!/usr/bin/env python3 from PKC_Classes import NetworkUser, KDC from",
"import socket import os import sys import threading import time",
"= bytes.decode(buf).rstrip('\\x00') reply_packet = bob.process_packet(receive_packet) conn.send(reply_packet.encode()) buf = conn.recv(1024) else:",
"bob.process_packet(receive_packet) conn.send(reply_packet.encode()) buf = conn.recv(1024) else: time.sleep(0.5) conn.close() bob =",
"NetworkUser('Alice', DES(), RSA(9973, 97), 200) print('bob:', bob.uid) # socket communication",
"sys.version_info[0] < 3: raise Exception(\"Must be using Python 3\") def",
"msg: print(msg); sys.exit(1) while 1: conn, addr = sock_self.accept() thread",
"socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock_self.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) sock_self.bind((bob_host, bob_port)) sock_self.listen(10) except socket.error",
"sock_self.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) sock_self.bind((bob_host, bob_port)) sock_self.listen(10) except socket.error as msg:",
"= socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock_with_kdc.connect((kdc_host, kdc_port)) print(sock_with_kdc.recv(1024)) # send cipher_key bob_cipher_key_packet",
"bob_port)) sock_self.listen(10) except socket.error as msg: print(msg); sys.exit(1) while 1:",
"sock_with_kdc.shutdown(socket.SHUT_WR) # talk to bob try: sock_self = socket.socket(socket.AF_INET, socket.SOCK_STREAM)",
"1: conn, addr = sock_self.accept() thread = threading.Thread(target=reply_conn, args=(conn, addr))",
"socket.error as msg: print(msg); sys.exit(1) while 1: conn, addr =",
"print('bob:', bob.uid) # socket communication kdc_host, kdc_port = 'localhost', 9999",
"< 3: raise Exception(\"Must be using Python 3\") def reply_conn(conn,",
"send cipher_key bob_cipher_key_packet = bob.send_cipher_key() sock_with_kdc.send(bob_cipher_key_packet.encode()) kdc_bob_cipher_key_packet = sock_with_kdc.recv(1024).decode() print(kdc_bob_cipher_key_packet)",
"conn, addr = sock_self.accept() thread = threading.Thread(target=reply_conn, args=(conn, addr)) thread.start()"
] |
[
"net.module.cuda() with open(os.path.join(config.out_dir, \"config.pickle\"), 'wb') as outfile: pickle.dump(config, outfile) with",
"Results storage -------------------------------------------------------------- if config.restart: if not taking_best: next_epoch =",
"if taking_best: opt_path = os.path.join(config.out_dir, \"best_optimiser.pytorch\") optimiser.load_state_dict(torch.load(opt_path)) # Results storage",
"= config.masses[:next_epoch, :] config.per_class_acc = config.per_class_acc[:next_epoch, :] else: config.epoch_acc =",
"to last saved model else: next_epoch = np.argmax(np.array(config.epoch_acc)) + 1",
"allow diff crop for imgs_tf parser.add_argument(\"--tf3_crop_diff\", dest=\"tf3_crop_diff\", default=False, action=\"store_true\") parser.add_argument(\"--tf3_crop_sz\",",
"print(\"Starting e_i: %d\" % (e_i)) if e_i in config.lr_schedule: optimiser",
"diff crop for imgs_tf parser.add_argument(\"--tf3_crop_diff\", dest=\"tf3_crop_diff\", default=False, action=\"store_true\") parser.add_argument(\"--tf3_crop_sz\", type=int,",
"fig.tight_layout() fig.canvas.draw_idle() fig.savefig(os.path.join(config.out_dir, \"plots.png\")) if is_best or (e_i % config.save_freq",
"action=\"store_true\") parser.add_argument(\"--no_flip\", dest=\"no_flip\", default=False, action=\"store_true\") config = parser.parse_args() # Fixed",
"if e_i % config.save_freq == 0: torch.save(net.module.state_dict(), os.path.join(config.out_dir, \"latest_net.pytorch\")) torch.save(optimiser.state_dict(),",
"default=False, action=\"store_true\") parser.add_argument(\"--tf3_crop_sz\", type=int, default=0) parser.add_argument(\"--input_sz\", type=int, default=96) parser.add_argument(\"--rot_val\", type=float,",
"config.per_class_acc = None _ = triplets_eval(config, net, dataloader_test=dataloader_test, sobel=False) print(\"Pre:",
"import proj.archs as archs from proj.utils.cluster.general import config_to_str, get_opt, update_lr",
"dataloader_positive, dataloader_negative] net = archs.__dict__[config.arch](config) if config.restart: model_path = os.path.join(config.out_dir,",
"print(\"Loss is not finite... %s:\" % str(curr_loss.item())) exit(1) avg_loss +=",
"== 0: torch.save(net.module.state_dict(), os.path.join(config.out_dir, \"latest_net.pytorch\")) torch.save(optimiser.state_dict(), os.path.join(config.out_dir, \"latest_optimiser.pytorch\")) config.last_epoch =",
"(datetime.now(), config.epoch_acc[-1])) sys.stdout.flush() axarr[0].clear() axarr[0].plot(config.epoch_acc) axarr[0].set_title(\"acc, top: %f\" % max(config.epoch_acc))",
"\"best_net.pytorch\")) torch.save(optimiser.state_dict(), os.path.join(config.out_dir, \"best_optimiser.pytorch\")) if e_i % config.save_freq == 0:",
"imgs_tf parser.add_argument(\"--tf3_crop_diff\", dest=\"tf3_crop_diff\", default=False, action=\"store_true\") parser.add_argument(\"--tf3_crop_sz\", type=int, default=0) parser.add_argument(\"--input_sz\", type=int,",
"parser.parse_args() # Fixed settings and checks ---------------------------------------------------- config.in_channels = 1",
"\"kmeans_on_features\"): config.kmeans_on_features = False else: print(\"Config: %s\" % config_to_str(config)) #",
"outs_pos = net(imgs_pos) outs_neg = net(imgs_neg) curr_loss = triplets_loss(outs_orig, outs_pos,",
"[dataloader_original, dataloader_positive, dataloader_negative] net = archs.__dict__[config.arch](config) if config.restart: model_path =",
"torch.nn.DataParallel(net) net.train() optimiser = get_opt(config.opt)(net.module.parameters(), lr=config.lr) if config.restart: opt_path =",
"axarr[2].clear() for c in xrange(config.gt_k): axarr[2].plot(config.masses[:, c]) axarr[2].set_title(\"masses\") axarr[3].clear() for",
"= triplets_loss(outs_orig, outs_pos, outs_neg) if ((b_i % 100) == 0)",
"version (no sobel). \"\"\" # Options ---------------------------------------------------------------------- parser = argparse.ArgumentParser()",
"storage)) net.cuda() net = torch.nn.DataParallel(net) net.train() optimiser = get_opt(config.opt)(net.module.parameters(), lr=config.lr)",
"parser.add_argument(\"--arch\", type=str, required=True) parser.add_argument(\"--opt\", type=str, default=\"Adam\") parser.add_argument(\"--dataset\", type=str, required=True) parser.add_argument(\"--dataset_root\",",
"= 0 for tup in itertools.izip(*iterators): net.module.zero_grad() imgs_orig = tup[0][0].cuda()",
"avg_loss = float(avg_loss / avg_loss_count) config.epoch_loss.append(avg_loss) # Eval and storage",
"parser.add_argument(\"--input_sz\", type=int, default=96) parser.add_argument(\"--rot_val\", type=float, default=0.) parser.add_argument(\"--always_rot\", dest=\"always_rot\", default=False, action=\"store_true\")",
"!= config.gt_k: assert (config.output_k > config.gt_k) assert (config.kmeans_on_features) config.out_dir =",
"c in xrange(config.gt_k): axarr[3].plot(config.per_class_acc[:, c]) axarr[3].set_title(\"per_class_acc\") fig.tight_layout() fig.canvas.draw_idle() fig.savefig(os.path.join(config.out_dir, \"plots.png\"))",
"transforms # used for \"positive\" sample parser.add_argument(\"--demean\", dest=\"demean\", default=False, action=\"store_true\")",
"= torch.nn.DataParallel(net) net.train() optimiser = get_opt(config.opt)(net.module.parameters(), lr=config.lr) if config.restart: opt_path",
"default=\"/scratch/shared/slow/xuji/iid_private\") parser.add_argument(\"--restart\", dest=\"restart\", default=False, action=\"store_true\") parser.add_argument(\"--test_code\", dest=\"test_code\", default=False, action=\"store_true\") parser.add_argument(\"--save_freq\",",
"axarr[1].clear() axarr[1].plot(config.epoch_loss) axarr[1].set_title(\"Loss\") axarr[2].clear() for c in xrange(config.gt_k): axarr[2].plot(config.masses[:, c])",
"% reloaded_config_path) with open(reloaded_config_path, \"rb\") as config_f: config = pickle.load(config_f)",
"fig.savefig(os.path.join(config.out_dir, \"plots.png\")) if is_best or (e_i % config.save_freq == 0):",
"batch %d \" \"loss %f time %s\" % \\ (config.model_ind,",
"<filename>proj/scripts/cluster/baselines/triplets_greyscale.py from __future__ import print_function import argparse import itertools import",
"type=str, required=True) parser.add_argument(\"--opt\", type=str, default=\"Adam\") parser.add_argument(\"--dataset\", type=str, required=True) parser.add_argument(\"--dataset_root\", type=str,",
"config.epoch_acc[-1])) sys.stdout.flush() next_epoch = 1 fig, axarr = plt.subplots(4, sharex=False,",
"0) or (e_i == next_epoch and b_i < 10): print(\"Model",
"% config.save_freq == 0: torch.save(net.module.state_dict(), os.path.join(config.out_dir, \"latest_net.pytorch\")) torch.save(optimiser.state_dict(), os.path.join(config.out_dir, \"latest_optimiser.pytorch\"))",
"type=float, default=0.01) parser.add_argument(\"--lr_schedule\", type=int, nargs=\"+\", default=[]) parser.add_argument(\"--lr_mult\", type=float, default=0.1) parser.add_argument(\"--num_epochs\",",
"(no sobel). \"\"\" # Options ---------------------------------------------------------------------- parser = argparse.ArgumentParser() parser.add_argument(\"--model_ind\",",
"%s:\" % str(curr_loss.item())) exit(1) avg_loss += curr_loss.item() avg_loss_count += 1",
"if not taking_best: next_epoch = config.last_epoch + 1 # corresponds",
"axarr[0].plot(config.epoch_acc) axarr[0].set_title(\"acc, top: %f\" % max(config.epoch_acc)) axarr[1].clear() axarr[1].plot(config.epoch_loss) axarr[1].set_title(\"Loss\") axarr[2].clear()",
"config.output_k != config.gt_k: assert (config.output_k > config.gt_k) assert (config.kmeans_on_features) config.out_dir",
"\"\"\" Triplets. Makes output distribution same as that of attractor,",
"new num_epochs and lr schedule config.num_epochs = given_config.num_epochs config.lr_schedule =",
"and checks ---------------------------------------------------- config.in_channels = 1 if config.output_k != config.gt_k:",
"parser.add_argument(\"--tf2_crop\", type=str, default=\"random\") parser.add_argument(\"--tf1_crop_sz\", type=int, default=84) parser.add_argument(\"--tf2_crop_szs\", type=int, nargs=\"+\", default=[84])",
"is not finite... %s:\" % str(curr_loss.item())) exit(1) avg_loss += curr_loss.item()",
"dest=\"no_flip\", default=False, action=\"store_true\") config = parser.parse_args() # Fixed settings and",
"time %s: \\n %s\" % (datetime.now(), config.epoch_acc[-1])) sys.stdout.flush() next_epoch =",
"type=int, nargs=\"+\", default=[]) parser.add_argument(\"--lr_mult\", type=float, default=0.1) parser.add_argument(\"--num_epochs\", type=int, default=1000) parser.add_argument(\"--batch_sz\",",
"fig, axarr = plt.subplots(4, sharex=False, figsize=(20, 20)) # Train ------------------------------------------------------------------------",
"(config.kmeans_on_features) config.out_dir = os.path.join(config.out_root, str(config.model_ind)) config.dataloader_batch_sz = config.batch_sz config.num_dataloaders =",
"import datetime import matplotlib import numpy as np import torch",
"taking_best: next_epoch = config.last_epoch + 1 # corresponds to last",
"parser.add_argument(\"--out_root\", type=str, default=\"/scratch/shared/slow/xuji/iid_private\") parser.add_argument(\"--restart\", dest=\"restart\", default=False, action=\"store_true\") parser.add_argument(\"--test_code\", dest=\"test_code\", default=False,",
"net.cuda() net = torch.nn.DataParallel(net) net.train() optimiser = get_opt(config.opt)(net.module.parameters(), lr=config.lr) if",
"config.per_class_acc[:next_epoch, :] else: config.epoch_acc = [] config.epoch_loss = [] config.masses",
"optimiser.step() b_i += 1 if b_i == 2 and config.test_code:",
"proj.archs as archs from proj.utils.cluster.general import config_to_str, get_opt, update_lr from",
"default=False, action=\"store_true\") parser.add_argument(\"--no_flip\", dest=\"no_flip\", default=False, action=\"store_true\") config = parser.parse_args() #",
"# num pairs parser.add_argument(\"--out_root\", type=str, default=\"/scratch/shared/slow/xuji/iid_private\") parser.add_argument(\"--restart\", dest=\"restart\", default=False, action=\"store_true\")",
"0): net.module.cpu() if is_best: torch.save(net.module.state_dict(), os.path.join(config.out_dir, \"best_net.pytorch\")) torch.save(optimiser.state_dict(), os.path.join(config.out_dir, \"best_optimiser.pytorch\"))",
"os.path.join(config.out_dir, \"latest_net.pytorch\")) torch.save(optimiser.state_dict(), os.path.join(config.out_dir, \"latest_optimiser.pytorch\")) config.last_epoch = e_i # for",
"str(curr_loss.item())) exit(1) avg_loss += curr_loss.item() avg_loss_count += 1 curr_loss.backward() optimiser.step()",
"archs from proj.utils.cluster.general import config_to_str, get_opt, update_lr from proj.utils.cluster.baselines.triplets import",
"config.restart: given_config = config reloaded_config_path = os.path.join(given_config.out_dir, \"config.pickle\") print(\"Loading restarting",
"last saved version net.module.cuda() with open(os.path.join(config.out_dir, \"config.pickle\"), 'wb') as outfile:",
"sobel=False) print(\"Time %s, acc %s\" % (datetime.now(), config.epoch_acc[-1])) sys.stdout.flush() axarr[0].clear()",
"(and sub_heads) avg_loss_count = 0 sys.stdout.flush() iterators = (d for",
"tup[0][0].cuda() imgs_pos = tup[1][0].cuda() imgs_neg = tup[2][0].cuda() outs_orig = net(imgs_orig)",
"%d\" % (e_i)) if e_i in config.lr_schedule: optimiser = update_lr(optimiser,",
"+= 1 if b_i == 2 and config.test_code: break avg_loss",
"not os.path.exists(model_path) if taking_best: print(\"using best instead of latest\") model_path",
"parser.add_argument(\"--tf1_crop_sz\", type=int, default=84) parser.add_argument(\"--tf2_crop_szs\", type=int, nargs=\"+\", default=[84]) # allow diff",
"== next_epoch and b_i < 10): print(\"Model ind %d epoch",
"1 if config.output_k != config.gt_k: assert (config.output_k > config.gt_k) assert",
"epoch %d\" % next_epoch) config.epoch_acc = config.epoch_acc[:next_epoch] # in case",
"xrange(next_epoch, config.num_epochs): print(\"Starting e_i: %d\" % (e_i)) if e_i in",
"in train_dataloaders) b_i = 0 for tup in itertools.izip(*iterators): net.module.zero_grad()",
"------------------------------------------------------------------------ for e_i in xrange(next_epoch, config.num_epochs): print(\"Starting e_i: %d\" %",
"torch.save(optimiser.state_dict(), os.path.join(config.out_dir, \"best_optimiser.pytorch\")) if e_i % config.save_freq == 0: torch.save(net.module.state_dict(),",
"net(imgs_orig) outs_pos = net(imgs_pos) outs_neg = net(imgs_neg) curr_loss = triplets_loss(outs_orig,",
"= net(imgs_pos) outs_neg = net(imgs_neg) curr_loss = triplets_loss(outs_orig, outs_pos, outs_neg)",
"config.lr_schedule = given_config.lr_schedule if not hasattr(config, \"kmeans_on_features\"): config.kmeans_on_features = False",
"break avg_loss = float(avg_loss / avg_loss_count) config.epoch_loss.append(avg_loss) # Eval and",
"not os.path.exists(config.out_dir): os.makedirs(config.out_dir) if config.restart: given_config = config reloaded_config_path =",
"argparse.ArgumentParser() parser.add_argument(\"--model_ind\", type=int, required=True) parser.add_argument(\"--arch\", type=str, required=True) parser.add_argument(\"--opt\", type=str, default=\"Adam\")",
"\"positive\" sample parser.add_argument(\"--demean\", dest=\"demean\", default=False, action=\"store_true\") parser.add_argument(\"--per_img_demean\", dest=\"per_img_demean\", default=False, action=\"store_true\")",
"% config.save_freq == 0): net.module.cpu() if is_best: torch.save(net.module.state_dict(), os.path.join(config.out_dir, \"best_net.pytorch\"))",
"config = pickle.load(config_f) assert (config.model_ind == given_config.model_ind) config.restart = True",
"last saved model else: next_epoch = np.argmax(np.array(config.epoch_acc)) + 1 print(\"starting",
"train_dataloaders) b_i = 0 for tup in itertools.izip(*iterators): net.module.zero_grad() imgs_orig",
"torch matplotlib.use('Agg') import matplotlib.pyplot as plt import proj.archs as archs",
"dataloader_test = make_triplets_data(config) train_dataloaders = [dataloader_original, dataloader_positive, dataloader_negative] net =",
"= given_config.lr_schedule if not hasattr(config, \"kmeans_on_features\"): config.kmeans_on_features = False else:",
"\"best_net.pytorch\") net.load_state_dict( torch.load(model_path, map_location=lambda storage, loc: storage)) net.cuda() net =",
"Train ------------------------------------------------------------------------ for e_i in xrange(next_epoch, config.num_epochs): print(\"Starting e_i: %d\"",
"in xrange(config.gt_k): axarr[3].plot(config.per_class_acc[:, c]) axarr[3].set_title(\"per_class_acc\") fig.tight_layout() fig.canvas.draw_idle() fig.savefig(os.path.join(config.out_dir, \"plots.png\")) if",
"\"best_optimiser.pytorch\") optimiser.load_state_dict(torch.load(opt_path)) # Results storage -------------------------------------------------------------- if config.restart: if not",
"as outfile: pickle.dump(config, outfile) with open(os.path.join(config.out_dir, \"config.txt\"), \"w\") as text_file:",
"= None _ = triplets_eval(config, net, dataloader_test=dataloader_test, sobel=False) print(\"Pre: time",
"print(\"Model ind %d epoch %d batch %d \" \"loss %f",
"of repeller. Greyscale version (no sobel). \"\"\" # Options ----------------------------------------------------------------------",
"version net.module.cuda() with open(os.path.join(config.out_dir, \"config.pickle\"), 'wb') as outfile: pickle.dump(config, outfile)",
"axarr = plt.subplots(4, sharex=False, figsize=(20, 20)) # Train ------------------------------------------------------------------------ for",
"acc %s\" % (datetime.now(), config.epoch_acc[-1])) sys.stdout.flush() axarr[0].clear() axarr[0].plot(config.epoch_acc) axarr[0].set_title(\"acc, top:",
"Makes output distribution same as that of attractor, and different",
"that of repeller. Greyscale version (no sobel). \"\"\" # Options",
"num pairs parser.add_argument(\"--out_root\", type=str, default=\"/scratch/shared/slow/xuji/iid_private\") parser.add_argument(\"--restart\", dest=\"restart\", default=False, action=\"store_true\") parser.add_argument(\"--test_code\",",
"True # copy over new num_epochs and lr schedule config.num_epochs",
"from epoch %d\" % next_epoch) config.epoch_acc = config.epoch_acc[:next_epoch] # in",
"if b_i == 2 and config.test_code: break avg_loss = float(avg_loss",
"given_config = config reloaded_config_path = os.path.join(given_config.out_dir, \"config.pickle\") print(\"Loading restarting config",
"# corresponds to last saved model else: next_epoch = np.argmax(np.array(config.epoch_acc))",
"reloaded_config_path) with open(reloaded_config_path, \"rb\") as config_f: config = pickle.load(config_f) assert",
"parser.add_argument(\"--tf2_crop_szs\", type=int, nargs=\"+\", default=[84]) # allow diff crop for imgs_tf",
"= triplets_eval(config, net, dataloader_test=dataloader_test, sobel=False) print(\"Time %s, acc %s\" %",
"os.path.exists(model_path) if taking_best: print(\"using best instead of latest\") model_path =",
"float(avg_loss / avg_loss_count) config.epoch_loss.append(avg_loss) # Eval and storage ----------------------------------------------------------- #",
"config.restart: if not taking_best: next_epoch = config.last_epoch + 1 #",
"Greyscale version (no sobel). \"\"\" # Options ---------------------------------------------------------------------- parser =",
"avg_loss_count) config.epoch_loss.append(avg_loss) # Eval and storage ----------------------------------------------------------- # when epoch",
"output distribution same as that of attractor, and different to",
"max(config.epoch_acc)) axarr[1].clear() axarr[1].plot(config.epoch_loss) axarr[1].set_title(\"Loss\") axarr[2].clear() for c in xrange(config.gt_k): axarr[2].plot(config.masses[:,",
"matplotlib import numpy as np import torch matplotlib.use('Agg') import matplotlib.pyplot",
"if config.restart: if not taking_best: next_epoch = config.last_epoch + 1",
"with open(os.path.join(config.out_dir, \"config.txt\"), \"w\") as text_file: text_file.write(\"%s\" % config) if",
"type=str, default=\"random\") parser.add_argument(\"--tf1_crop_sz\", type=int, default=84) parser.add_argument(\"--tf2_crop_szs\", type=int, nargs=\"+\", default=[84]) #",
"config.restart: model_path = os.path.join(config.out_dir, \"latest_net.pytorch\") taking_best = not os.path.exists(model_path) if",
"None config.per_class_acc = None _ = triplets_eval(config, net, dataloader_test=dataloader_test, sobel=False)",
"dest=\"test_code\", default=False, action=\"store_true\") parser.add_argument(\"--save_freq\", type=int, default=10) parser.add_argument(\"--kmeans_on_features\", default=False, action=\"store_true\") #",
"% \\ (config.model_ind, e_i, b_i, curr_loss.item(), datetime.now())) sys.stdout.flush() if not",
"model_path = os.path.join(config.out_dir, \"best_net.pytorch\") net.load_state_dict( torch.load(model_path, map_location=lambda storage, loc: storage))",
"% 100) == 0) or (e_i == next_epoch and b_i",
"sample parser.add_argument(\"--demean\", dest=\"demean\", default=False, action=\"store_true\") parser.add_argument(\"--per_img_demean\", dest=\"per_img_demean\", default=False, action=\"store_true\") parser.add_argument(\"--data_mean\",",
"lr_mult=config.lr_mult) avg_loss = 0. # over heads and head_epochs (and",
"import config_to_str, get_opt, update_lr from proj.utils.cluster.baselines.triplets import make_triplets_data, \\ triplets_eval,",
"0.5, 0.5]) parser.add_argument(\"--data_std\", type=float, nargs=\"+\", default=[0.5, 0.5, 0.5]) parser.add_argument(\"--crop_orig\", dest=\"crop_orig\",",
"if config.restart: model_path = os.path.join(config.out_dir, \"latest_net.pytorch\") taking_best = not os.path.exists(model_path)",
"config.num_epochs = given_config.num_epochs config.lr_schedule = given_config.lr_schedule if not hasattr(config, \"kmeans_on_features\"):",
"over heads and head_epochs (and sub_heads) avg_loss_count = 0 sys.stdout.flush()",
"as that of attractor, and different to that of repeller.",
"dataloader_negative] net = archs.__dict__[config.arch](config) if config.restart: model_path = os.path.join(config.out_dir, \"latest_net.pytorch\")",
"taking_best: opt_path = os.path.join(config.out_dir, \"best_optimiser.pytorch\") optimiser.load_state_dict(torch.load(opt_path)) # Results storage --------------------------------------------------------------",
"config_f: config = pickle.load(config_f) assert (config.model_ind == given_config.model_ind) config.restart =",
"given_config.num_epochs config.lr_schedule = given_config.lr_schedule if not hasattr(config, \"kmeans_on_features\"): config.kmeans_on_features =",
"type=int, default=96) parser.add_argument(\"--rot_val\", type=float, default=0.) parser.add_argument(\"--always_rot\", dest=\"always_rot\", default=False, action=\"store_true\") parser.add_argument(\"--no_jitter\",",
"% next_epoch) config.epoch_acc = config.epoch_acc[:next_epoch] # in case we overshot",
"print(\"using best instead of latest\") model_path = os.path.join(config.out_dir, \"best_net.pytorch\") net.load_state_dict(",
"parser = argparse.ArgumentParser() parser.add_argument(\"--model_ind\", type=int, required=True) parser.add_argument(\"--arch\", type=str, required=True) parser.add_argument(\"--opt\",",
"parser.add_argument(\"--restart\", dest=\"restart\", default=False, action=\"store_true\") parser.add_argument(\"--test_code\", dest=\"test_code\", default=False, action=\"store_true\") parser.add_argument(\"--save_freq\", type=int,",
"sharex=False, figsize=(20, 20)) # Train ------------------------------------------------------------------------ for e_i in xrange(next_epoch,",
"dest=\"restart\", default=False, action=\"store_true\") parser.add_argument(\"--test_code\", dest=\"test_code\", default=False, action=\"store_true\") parser.add_argument(\"--save_freq\", type=int, default=10)",
"parser.add_argument(\"--crop_other\", dest=\"crop_other\", default=False, action=\"store_true\") parser.add_argument(\"--tf1_crop\", type=str, default=\"random\") # type name",
"latest\") model_path = os.path.join(config.out_dir, \"best_net.pytorch\") net.load_state_dict( torch.load(model_path, map_location=lambda storage, loc:",
"over new num_epochs and lr schedule config.num_epochs = given_config.num_epochs config.lr_schedule",
"# when epoch over both heads is finished is_best =",
"Eval and storage ----------------------------------------------------------- # when epoch over both heads",
"default=1000) parser.add_argument(\"--batch_sz\", type=int, required=True) # num pairs parser.add_argument(\"--out_root\", type=str, default=\"/scratch/shared/slow/xuji/iid_private\")",
"distribution same as that of attractor, and different to that",
"# Fixed settings and checks ---------------------------------------------------- config.in_channels = 1 if",
"taking_best = not os.path.exists(model_path) if taking_best: print(\"using best instead of",
"action=\"store_true\") parser.add_argument(\"--data_mean\", type=float, nargs=\"+\", default=[0.5, 0.5, 0.5]) parser.add_argument(\"--data_std\", type=float, nargs=\"+\",",
"False else: print(\"Config: %s\" % config_to_str(config)) # Data, nets, optimisers",
"net.module.zero_grad() imgs_orig = tup[0][0].cuda() imgs_pos = tup[1][0].cuda() imgs_neg = tup[2][0].cuda()",
"avg_loss_count = 0 sys.stdout.flush() iterators = (d for d in",
"is_best or (e_i % config.save_freq == 0): net.module.cpu() if is_best:",
"---------------------------------------------------- config.in_channels = 1 if config.output_k != config.gt_k: assert (config.output_k",
"is finished is_best = triplets_eval(config, net, dataloader_test=dataloader_test, sobel=False) print(\"Time %s,",
"= False else: print(\"Config: %s\" % config_to_str(config)) # Data, nets,",
"case we overshot config.epoch_loss = config.epoch_loss[:next_epoch] config.masses = config.masses[:next_epoch, :]",
"action=\"store_true\") parser.add_argument(\"--tf3_crop_sz\", type=int, default=0) parser.add_argument(\"--input_sz\", type=int, default=96) parser.add_argument(\"--rot_val\", type=float, default=0.)",
"default=False, action=\"store_true\") parser.add_argument(\"--per_img_demean\", dest=\"per_img_demean\", default=False, action=\"store_true\") parser.add_argument(\"--data_mean\", type=float, nargs=\"+\", default=[0.5,",
"storage ----------------------------------------------------------- # when epoch over both heads is finished",
"if not os.path.exists(config.out_dir): os.makedirs(config.out_dir) if config.restart: given_config = config reloaded_config_path",
"from __future__ import print_function import argparse import itertools import os",
"epoch %d batch %d \" \"loss %f time %s\" %",
"parser.add_argument(\"--per_img_demean\", dest=\"per_img_demean\", default=False, action=\"store_true\") parser.add_argument(\"--data_mean\", type=float, nargs=\"+\", default=[0.5, 0.5, 0.5])",
"default=\"random\") parser.add_argument(\"--tf1_crop_sz\", type=int, default=84) parser.add_argument(\"--tf2_crop_szs\", type=int, nargs=\"+\", default=[84]) # allow",
"tup[2][0].cuda() outs_orig = net(imgs_orig) outs_pos = net(imgs_pos) outs_neg = net(imgs_neg)",
"import make_triplets_data, \\ triplets_eval, triplets_loss \"\"\" Triplets. Makes output distribution",
"axarr[1].plot(config.epoch_loss) axarr[1].set_title(\"Loss\") axarr[2].clear() for c in xrange(config.gt_k): axarr[2].plot(config.masses[:, c]) axarr[2].set_title(\"masses\")",
"net, dataloader_test=dataloader_test, sobel=False) print(\"Time %s, acc %s\" % (datetime.now(), config.epoch_acc[-1]))",
"avg_loss_count += 1 curr_loss.backward() optimiser.step() b_i += 1 if b_i",
"curr_loss.backward() optimiser.step() b_i += 1 if b_i == 2 and",
"imgs_orig = tup[0][0].cuda() imgs_pos = tup[1][0].cuda() imgs_neg = tup[2][0].cuda() outs_orig",
"= 0 sys.stdout.flush() iterators = (d for d in train_dataloaders)",
"exit(1) avg_loss += curr_loss.item() avg_loss_count += 1 curr_loss.backward() optimiser.step() b_i",
"import itertools import os import pickle import sys from datetime",
"sys.stdout.flush() if not np.isfinite(float(curr_loss.item())): print(\"Loss is not finite... %s:\" %",
"both heads is finished is_best = triplets_eval(config, net, dataloader_test=dataloader_test, sobel=False)",
"= plt.subplots(4, sharex=False, figsize=(20, 20)) # Train ------------------------------------------------------------------------ for e_i",
"xrange(config.gt_k): axarr[2].plot(config.masses[:, c]) axarr[2].set_title(\"masses\") axarr[3].clear() for c in xrange(config.gt_k): axarr[3].plot(config.per_class_acc[:,",
"parser.add_argument(\"--opt\", type=str, default=\"Adam\") parser.add_argument(\"--dataset\", type=str, required=True) parser.add_argument(\"--dataset_root\", type=str, required=True) parser.add_argument(\"--gt_k\",",
"default=0.) parser.add_argument(\"--always_rot\", dest=\"always_rot\", default=False, action=\"store_true\") parser.add_argument(\"--no_jitter\", dest=\"no_jitter\", default=False, action=\"store_true\") parser.add_argument(\"--no_flip\",",
"config.epoch_acc = [] config.epoch_loss = [] config.masses = None config.per_class_acc",
"optimiser.load_state_dict(torch.load(opt_path)) # Results storage -------------------------------------------------------------- if config.restart: if not taking_best:",
"name parser.add_argument(\"--tf2_crop\", type=str, default=\"random\") parser.add_argument(\"--tf1_crop_sz\", type=int, default=84) parser.add_argument(\"--tf2_crop_szs\", type=int, nargs=\"+\",",
"100) == 0) or (e_i == next_epoch and b_i <",
"% max(config.epoch_acc)) axarr[1].clear() axarr[1].plot(config.epoch_loss) axarr[1].set_title(\"Loss\") axarr[2].clear() for c in xrange(config.gt_k):",
"parser.add_argument(\"--save_freq\", type=int, default=10) parser.add_argument(\"--kmeans_on_features\", default=False, action=\"store_true\") # transforms # used",
"parser.add_argument(\"--model_ind\", type=int, required=True) parser.add_argument(\"--arch\", type=str, required=True) parser.add_argument(\"--opt\", type=str, default=\"Adam\") parser.add_argument(\"--dataset\",",
"axarr[2].set_title(\"masses\") axarr[3].clear() for c in xrange(config.gt_k): axarr[3].plot(config.per_class_acc[:, c]) axarr[3].set_title(\"per_class_acc\") fig.tight_layout()",
"outfile) with open(os.path.join(config.out_dir, \"config.txt\"), \"w\") as text_file: text_file.write(\"%s\" % config)",
"assert (config.model_ind == given_config.model_ind) config.restart = True # copy over",
"type=int, nargs=\"+\", default=[84]) # allow diff crop for imgs_tf parser.add_argument(\"--tf3_crop_diff\",",
"nargs=\"+\", default=[84]) # allow diff crop for imgs_tf parser.add_argument(\"--tf3_crop_diff\", dest=\"tf3_crop_diff\",",
"optimiser = get_opt(config.opt)(net.module.parameters(), lr=config.lr) if config.restart: opt_path = os.path.join(config.out_dir, \"latest_optimiser.pytorch\")",
"we overshot config.epoch_loss = config.epoch_loss[:next_epoch] config.masses = config.masses[:next_epoch, :] config.per_class_acc",
"d in train_dataloaders) b_i = 0 for tup in itertools.izip(*iterators):",
"\\ (config.model_ind, e_i, b_i, curr_loss.item(), datetime.now())) sys.stdout.flush() if not np.isfinite(float(curr_loss.item())):",
"+ 1 # corresponds to last saved model else: next_epoch",
"= config reloaded_config_path = os.path.join(given_config.out_dir, \"config.pickle\") print(\"Loading restarting config from:",
"head_epochs (and sub_heads) avg_loss_count = 0 sys.stdout.flush() iterators = (d",
"from: %s\" % reloaded_config_path) with open(reloaded_config_path, \"rb\") as config_f: config",
"(d for d in train_dataloaders) b_i = 0 for tup",
"required=True) parser.add_argument(\"--output_k\", type=int, required=True) parser.add_argument(\"--lr\", type=float, default=0.01) parser.add_argument(\"--lr_schedule\", type=int, nargs=\"+\",",
"default=False, action=\"store_true\") # transforms # used for \"positive\" sample parser.add_argument(\"--demean\",",
"of latest\") model_path = os.path.join(config.out_dir, \"best_net.pytorch\") net.load_state_dict( torch.load(model_path, map_location=lambda storage,",
"triplets_loss \"\"\" Triplets. Makes output distribution same as that of",
"os.path.join(config.out_dir, \"latest_optimiser.pytorch\")) config.last_epoch = e_i # for last saved version",
"b_i == 2 and config.test_code: break avg_loss = float(avg_loss /",
"datetime import datetime import matplotlib import numpy as np import",
"= given_config.num_epochs config.lr_schedule = given_config.lr_schedule if not hasattr(config, \"kmeans_on_features\"): config.kmeans_on_features",
"np.isfinite(float(curr_loss.item())): print(\"Loss is not finite... %s:\" % str(curr_loss.item())) exit(1) avg_loss",
"numpy as np import torch matplotlib.use('Agg') import matplotlib.pyplot as plt",
"lr schedule config.num_epochs = given_config.num_epochs config.lr_schedule = given_config.lr_schedule if not",
"required=True) parser.add_argument(\"--opt\", type=str, default=\"Adam\") parser.add_argument(\"--dataset\", type=str, required=True) parser.add_argument(\"--dataset_root\", type=str, required=True)",
"model else: next_epoch = np.argmax(np.array(config.epoch_acc)) + 1 print(\"starting from epoch",
"in config.lr_schedule: optimiser = update_lr(optimiser, lr_mult=config.lr_mult) avg_loss = 0. #",
"type=int, required=True) parser.add_argument(\"--lr\", type=float, default=0.01) parser.add_argument(\"--lr_schedule\", type=int, nargs=\"+\", default=[]) parser.add_argument(\"--lr_mult\",",
"parser.add_argument(\"--crop_orig\", dest=\"crop_orig\", default=False, action=\"store_true\") parser.add_argument(\"--crop_other\", dest=\"crop_other\", default=False, action=\"store_true\") parser.add_argument(\"--tf1_crop\", type=str,",
"next_epoch = config.last_epoch + 1 # corresponds to last saved",
"avg_loss = 0. # over heads and head_epochs (and sub_heads)",
"torch.load(model_path, map_location=lambda storage, loc: storage)) net.cuda() net = torch.nn.DataParallel(net) net.train()",
"in case we overshot config.epoch_loss = config.epoch_loss[:next_epoch] config.masses = config.masses[:next_epoch,",
"%s: \\n %s\" % (datetime.now(), config.epoch_acc[-1])) sys.stdout.flush() next_epoch = 1",
":] config.per_class_acc = config.per_class_acc[:next_epoch, :] else: config.epoch_acc = [] config.epoch_loss",
"pickle.dump(config, outfile) with open(os.path.join(config.out_dir, \"config.txt\"), \"w\") as text_file: text_file.write(\"%s\" %",
"heads is finished is_best = triplets_eval(config, net, dataloader_test=dataloader_test, sobel=False) print(\"Time",
"parser.add_argument(\"--lr_mult\", type=float, default=0.1) parser.add_argument(\"--num_epochs\", type=int, default=1000) parser.add_argument(\"--batch_sz\", type=int, required=True) #",
"type=int, default=10) parser.add_argument(\"--kmeans_on_features\", default=False, action=\"store_true\") # transforms # used for",
":] else: config.epoch_acc = [] config.epoch_loss = [] config.masses =",
"dataloader_test=dataloader_test, sobel=False) print(\"Time %s, acc %s\" % (datetime.now(), config.epoch_acc[-1])) sys.stdout.flush()",
"str(config.model_ind)) config.dataloader_batch_sz = config.batch_sz config.num_dataloaders = 1 if not os.path.exists(config.out_dir):",
"type=str, required=True) parser.add_argument(\"--gt_k\", type=int, required=True) parser.add_argument(\"--output_k\", type=int, required=True) parser.add_argument(\"--lr\", type=float,",
"net(imgs_neg) curr_loss = triplets_loss(outs_orig, outs_pos, outs_neg) if ((b_i % 100)",
"+= 1 curr_loss.backward() optimiser.step() b_i += 1 if b_i ==",
"= os.path.join(config.out_dir, \"latest_net.pytorch\") taking_best = not os.path.exists(model_path) if taking_best: print(\"using",
"make_triplets_data(config) train_dataloaders = [dataloader_original, dataloader_positive, dataloader_negative] net = archs.__dict__[config.arch](config) if",
"(datetime.now(), config.epoch_acc[-1])) sys.stdout.flush() next_epoch = 1 fig, axarr = plt.subplots(4,",
"----------------------------------------------------------- # when epoch over both heads is finished is_best",
"if is_best: torch.save(net.module.state_dict(), os.path.join(config.out_dir, \"best_net.pytorch\")) torch.save(optimiser.state_dict(), os.path.join(config.out_dir, \"best_optimiser.pytorch\")) if e_i",
"storage, loc: storage)) net.cuda() net = torch.nn.DataParallel(net) net.train() optimiser =",
"= config.batch_sz config.num_dataloaders = 1 if not os.path.exists(config.out_dir): os.makedirs(config.out_dir) if",
"is_best: torch.save(net.module.state_dict(), os.path.join(config.out_dir, \"best_net.pytorch\")) torch.save(optimiser.state_dict(), os.path.join(config.out_dir, \"best_optimiser.pytorch\")) if e_i %",
"default=[]) parser.add_argument(\"--lr_mult\", type=float, default=0.1) parser.add_argument(\"--num_epochs\", type=int, default=1000) parser.add_argument(\"--batch_sz\", type=int, required=True)",
"0 for tup in itertools.izip(*iterators): net.module.zero_grad() imgs_orig = tup[0][0].cuda() imgs_pos",
"\"loss %f time %s\" % \\ (config.model_ind, e_i, b_i, curr_loss.item(),",
"= make_triplets_data(config) train_dataloaders = [dataloader_original, dataloader_positive, dataloader_negative] net = archs.__dict__[config.arch](config)",
"outfile: pickle.dump(config, outfile) with open(os.path.join(config.out_dir, \"config.txt\"), \"w\") as text_file: text_file.write(\"%s\"",
"config.save_freq == 0: torch.save(net.module.state_dict(), os.path.join(config.out_dir, \"latest_net.pytorch\")) torch.save(optimiser.state_dict(), os.path.join(config.out_dir, \"latest_optimiser.pytorch\")) config.last_epoch",
"\"config.pickle\"), 'wb') as outfile: pickle.dump(config, outfile) with open(os.path.join(config.out_dir, \"config.txt\"), \"w\")",
"sobel=False) print(\"Pre: time %s: \\n %s\" % (datetime.now(), config.epoch_acc[-1])) sys.stdout.flush()",
"pairs parser.add_argument(\"--out_root\", type=str, default=\"/scratch/shared/slow/xuji/iid_private\") parser.add_argument(\"--restart\", dest=\"restart\", default=False, action=\"store_true\") parser.add_argument(\"--test_code\", dest=\"test_code\",",
"map_location=lambda storage, loc: storage)) net.cuda() net = torch.nn.DataParallel(net) net.train() optimiser",
"os import pickle import sys from datetime import datetime import",
"config.num_epochs): print(\"Starting e_i: %d\" % (e_i)) if e_i in config.lr_schedule:",
"and storage ----------------------------------------------------------- # when epoch over both heads is",
"and head_epochs (and sub_heads) avg_loss_count = 0 sys.stdout.flush() iterators =",
"and config.test_code: break avg_loss = float(avg_loss / avg_loss_count) config.epoch_loss.append(avg_loss) #",
"or (e_i == next_epoch and b_i < 10): print(\"Model ind",
"config.batch_sz config.num_dataloaders = 1 if not os.path.exists(config.out_dir): os.makedirs(config.out_dir) if config.restart:",
"for e_i in xrange(next_epoch, config.num_epochs): print(\"Starting e_i: %d\" % (e_i))",
"heads and head_epochs (and sub_heads) avg_loss_count = 0 sys.stdout.flush() iterators",
"import torch matplotlib.use('Agg') import matplotlib.pyplot as plt import proj.archs as",
"1 if not os.path.exists(config.out_dir): os.makedirs(config.out_dir) if config.restart: given_config = config",
"sub_heads) avg_loss_count = 0 sys.stdout.flush() iterators = (d for d",
"# transforms # used for \"positive\" sample parser.add_argument(\"--demean\", dest=\"demean\", default=False,",
"imgs_pos = tup[1][0].cuda() imgs_neg = tup[2][0].cuda() outs_orig = net(imgs_orig) outs_pos",
"action=\"store_true\") parser.add_argument(\"--test_code\", dest=\"test_code\", default=False, action=\"store_true\") parser.add_argument(\"--save_freq\", type=int, default=10) parser.add_argument(\"--kmeans_on_features\", default=False,",
"torch.save(net.module.state_dict(), os.path.join(config.out_dir, \"best_net.pytorch\")) torch.save(optimiser.state_dict(), os.path.join(config.out_dir, \"best_optimiser.pytorch\")) if e_i % config.save_freq",
"config.epoch_acc = config.epoch_acc[:next_epoch] # in case we overshot config.epoch_loss =",
"0.5]) parser.add_argument(\"--crop_orig\", dest=\"crop_orig\", default=False, action=\"store_true\") parser.add_argument(\"--crop_other\", dest=\"crop_other\", default=False, action=\"store_true\") parser.add_argument(\"--tf1_crop\",",
"hasattr(config, \"kmeans_on_features\"): config.kmeans_on_features = False else: print(\"Config: %s\" % config_to_str(config))",
"nargs=\"+\", default=[0.5, 0.5, 0.5]) parser.add_argument(\"--data_std\", type=float, nargs=\"+\", default=[0.5, 0.5, 0.5])",
"to that of repeller. Greyscale version (no sobel). \"\"\" #",
"from proj.utils.cluster.baselines.triplets import make_triplets_data, \\ triplets_eval, triplets_loss \"\"\" Triplets. Makes",
"= config.per_class_acc[:next_epoch, :] else: config.epoch_acc = [] config.epoch_loss = []",
"not hasattr(config, \"kmeans_on_features\"): config.kmeans_on_features = False else: print(\"Config: %s\" %",
"= argparse.ArgumentParser() parser.add_argument(\"--model_ind\", type=int, required=True) parser.add_argument(\"--arch\", type=str, required=True) parser.add_argument(\"--opt\", type=str,",
"if is_best or (e_i % config.save_freq == 0): net.module.cpu() if",
"(e_i == next_epoch and b_i < 10): print(\"Model ind %d",
"= [] config.epoch_loss = [] config.masses = None config.per_class_acc =",
"import argparse import itertools import os import pickle import sys",
"reloaded_config_path = os.path.join(given_config.out_dir, \"config.pickle\") print(\"Loading restarting config from: %s\" %",
"= None config.per_class_acc = None _ = triplets_eval(config, net, dataloader_test=dataloader_test,",
"tup[1][0].cuda() imgs_neg = tup[2][0].cuda() outs_orig = net(imgs_orig) outs_pos = net(imgs_pos)",
"c]) axarr[2].set_title(\"masses\") axarr[3].clear() for c in xrange(config.gt_k): axarr[3].plot(config.per_class_acc[:, c]) axarr[3].set_title(\"per_class_acc\")",
"parser.add_argument(\"--tf3_crop_sz\", type=int, default=0) parser.add_argument(\"--input_sz\", type=int, default=96) parser.add_argument(\"--rot_val\", type=float, default=0.) parser.add_argument(\"--always_rot\",",
"%d\" % next_epoch) config.epoch_acc = config.epoch_acc[:next_epoch] # in case we",
"print(\"Loading restarting config from: %s\" % reloaded_config_path) with open(reloaded_config_path, \"rb\")",
"type=int, default=1000) parser.add_argument(\"--batch_sz\", type=int, required=True) # num pairs parser.add_argument(\"--out_root\", type=str,",
"sys.stdout.flush() next_epoch = 1 fig, axarr = plt.subplots(4, sharex=False, figsize=(20,",
"action=\"store_true\") parser.add_argument(\"--per_img_demean\", dest=\"per_img_demean\", default=False, action=\"store_true\") parser.add_argument(\"--data_mean\", type=float, nargs=\"+\", default=[0.5, 0.5,",
"best instead of latest\") model_path = os.path.join(config.out_dir, \"best_net.pytorch\") net.load_state_dict( torch.load(model_path,",
"outs_neg = net(imgs_neg) curr_loss = triplets_loss(outs_orig, outs_pos, outs_neg) if ((b_i",
"\"best_optimiser.pytorch\")) if e_i % config.save_freq == 0: torch.save(net.module.state_dict(), os.path.join(config.out_dir, \"latest_net.pytorch\"))",
"[] config.masses = None config.per_class_acc = None _ = triplets_eval(config,",
"loc: storage)) net.cuda() net = torch.nn.DataParallel(net) net.train() optimiser = get_opt(config.opt)(net.module.parameters(),",
"2 and config.test_code: break avg_loss = float(avg_loss / avg_loss_count) config.epoch_loss.append(avg_loss)",
"torch.save(optimiser.state_dict(), os.path.join(config.out_dir, \"latest_optimiser.pytorch\")) config.last_epoch = e_i # for last saved",
"type=str, default=\"random\") # type name parser.add_argument(\"--tf2_crop\", type=str, default=\"random\") parser.add_argument(\"--tf1_crop_sz\", type=int,",
"b_i, curr_loss.item(), datetime.now())) sys.stdout.flush() if not np.isfinite(float(curr_loss.item())): print(\"Loss is not",
"b_i = 0 for tup in itertools.izip(*iterators): net.module.zero_grad() imgs_orig =",
"= e_i # for last saved version net.module.cuda() with open(os.path.join(config.out_dir,",
"1 fig, axarr = plt.subplots(4, sharex=False, figsize=(20, 20)) # Train",
"\"\"\" # Options ---------------------------------------------------------------------- parser = argparse.ArgumentParser() parser.add_argument(\"--model_ind\", type=int, required=True)",
"# for last saved version net.module.cuda() with open(os.path.join(config.out_dir, \"config.pickle\"), 'wb')",
"\"latest_net.pytorch\") taking_best = not os.path.exists(model_path) if taking_best: print(\"using best instead",
"parser.add_argument(\"--data_mean\", type=float, nargs=\"+\", default=[0.5, 0.5, 0.5]) parser.add_argument(\"--data_std\", type=float, nargs=\"+\", default=[0.5,",
"parser.add_argument(\"--num_epochs\", type=int, default=1000) parser.add_argument(\"--batch_sz\", type=int, required=True) # num pairs parser.add_argument(\"--out_root\",",
"axarr[3].clear() for c in xrange(config.gt_k): axarr[3].plot(config.per_class_acc[:, c]) axarr[3].set_title(\"per_class_acc\") fig.tight_layout() fig.canvas.draw_idle()",
"restarting config from: %s\" % reloaded_config_path) with open(reloaded_config_path, \"rb\") as",
"else: print(\"Config: %s\" % config_to_str(config)) # Data, nets, optimisers -------------------------------------------------------",
"when epoch over both heads is finished is_best = triplets_eval(config,",
"config.epoch_acc[:next_epoch] # in case we overshot config.epoch_loss = config.epoch_loss[:next_epoch] config.masses",
"different to that of repeller. Greyscale version (no sobel). \"\"\"",
"config reloaded_config_path = os.path.join(given_config.out_dir, \"config.pickle\") print(\"Loading restarting config from: %s\"",
"attractor, and different to that of repeller. Greyscale version (no",
"# copy over new num_epochs and lr schedule config.num_epochs =",
"(config.output_k > config.gt_k) assert (config.kmeans_on_features) config.out_dir = os.path.join(config.out_root, str(config.model_ind)) config.dataloader_batch_sz",
"top: %f\" % max(config.epoch_acc)) axarr[1].clear() axarr[1].plot(config.epoch_loss) axarr[1].set_title(\"Loss\") axarr[2].clear() for c",
"datetime import matplotlib import numpy as np import torch matplotlib.use('Agg')",
"# Results storage -------------------------------------------------------------- if config.restart: if not taking_best: next_epoch",
"or (e_i % config.save_freq == 0): net.module.cpu() if is_best: torch.save(net.module.state_dict(),",
"type=int, default=84) parser.add_argument(\"--tf2_crop_szs\", type=int, nargs=\"+\", default=[84]) # allow diff crop",
"config.epoch_acc[-1])) sys.stdout.flush() axarr[0].clear() axarr[0].plot(config.epoch_acc) axarr[0].set_title(\"acc, top: %f\" % max(config.epoch_acc)) axarr[1].clear()",
"saved version net.module.cuda() with open(os.path.join(config.out_dir, \"config.pickle\"), 'wb') as outfile: pickle.dump(config,",
"avg_loss += curr_loss.item() avg_loss_count += 1 curr_loss.backward() optimiser.step() b_i +=",
"'wb') as outfile: pickle.dump(config, outfile) with open(os.path.join(config.out_dir, \"config.txt\"), \"w\") as",
"import print_function import argparse import itertools import os import pickle",
"parser.add_argument(\"--kmeans_on_features\", default=False, action=\"store_true\") # transforms # used for \"positive\" sample",
"parser.add_argument(\"--rot_val\", type=float, default=0.) parser.add_argument(\"--always_rot\", dest=\"always_rot\", default=False, action=\"store_true\") parser.add_argument(\"--no_jitter\", dest=\"no_jitter\", default=False,",
"type=int, required=True) # num pairs parser.add_argument(\"--out_root\", type=str, default=\"/scratch/shared/slow/xuji/iid_private\") parser.add_argument(\"--restart\", dest=\"restart\",",
"type=int, required=True) parser.add_argument(\"--arch\", type=str, required=True) parser.add_argument(\"--opt\", type=str, default=\"Adam\") parser.add_argument(\"--dataset\", type=str,",
"given_config.lr_schedule if not hasattr(config, \"kmeans_on_features\"): config.kmeans_on_features = False else: print(\"Config:",
"dataloader_negative, \\ dataloader_test = make_triplets_data(config) train_dataloaders = [dataloader_original, dataloader_positive, dataloader_negative]",
"\\n %s\" % (datetime.now(), config.epoch_acc[-1])) sys.stdout.flush() next_epoch = 1 fig,",
"config.in_channels = 1 if config.output_k != config.gt_k: assert (config.output_k >",
"1 # corresponds to last saved model else: next_epoch =",
"\"plots.png\")) if is_best or (e_i % config.save_freq == 0): net.module.cpu()",
"type=int, default=0) parser.add_argument(\"--input_sz\", type=int, default=96) parser.add_argument(\"--rot_val\", type=float, default=0.) parser.add_argument(\"--always_rot\", dest=\"always_rot\",",
"default=False, action=\"store_true\") parser.add_argument(\"--data_mean\", type=float, nargs=\"+\", default=[0.5, 0.5, 0.5]) parser.add_argument(\"--data_std\", type=float,",
"\"latest_optimiser.pytorch\") if taking_best: opt_path = os.path.join(config.out_dir, \"best_optimiser.pytorch\") optimiser.load_state_dict(torch.load(opt_path)) # Results",
"= os.path.join(config.out_dir, \"best_optimiser.pytorch\") optimiser.load_state_dict(torch.load(opt_path)) # Results storage -------------------------------------------------------------- if config.restart:",
"os.path.join(config.out_dir, \"best_optimiser.pytorch\") optimiser.load_state_dict(torch.load(opt_path)) # Results storage -------------------------------------------------------------- if config.restart: if",
"outs_neg) if ((b_i % 100) == 0) or (e_i ==",
"config.masses[:next_epoch, :] config.per_class_acc = config.per_class_acc[:next_epoch, :] else: config.epoch_acc = []",
"imgs_neg = tup[2][0].cuda() outs_orig = net(imgs_orig) outs_pos = net(imgs_pos) outs_neg",
"curr_loss.item() avg_loss_count += 1 curr_loss.backward() optimiser.step() b_i += 1 if",
"config.out_dir = os.path.join(config.out_root, str(config.model_ind)) config.dataloader_batch_sz = config.batch_sz config.num_dataloaders = 1",
"== 0) or (e_i == next_epoch and b_i < 10):",
"sys from datetime import datetime import matplotlib import numpy as",
"config.last_epoch = e_i # for last saved version net.module.cuda() with",
"action=\"store_true\") parser.add_argument(\"--crop_other\", dest=\"crop_other\", default=False, action=\"store_true\") parser.add_argument(\"--tf1_crop\", type=str, default=\"random\") # type",
"\" \"loss %f time %s\" % \\ (config.model_ind, e_i, b_i,",
"if config.output_k != config.gt_k: assert (config.output_k > config.gt_k) assert (config.kmeans_on_features)",
"# Eval and storage ----------------------------------------------------------- # when epoch over both",
"config.num_dataloaders = 1 if not os.path.exists(config.out_dir): os.makedirs(config.out_dir) if config.restart: given_config",
"proj.utils.cluster.baselines.triplets import make_triplets_data, \\ triplets_eval, triplets_loss \"\"\" Triplets. Makes output",
"dataloader_test=dataloader_test, sobel=False) print(\"Pre: time %s: \\n %s\" % (datetime.now(), config.epoch_acc[-1]))",
"# Options ---------------------------------------------------------------------- parser = argparse.ArgumentParser() parser.add_argument(\"--model_ind\", type=int, required=True) parser.add_argument(\"--arch\",",
"dest=\"per_img_demean\", default=False, action=\"store_true\") parser.add_argument(\"--data_mean\", type=float, nargs=\"+\", default=[0.5, 0.5, 0.5]) parser.add_argument(\"--data_std\",",
"triplets_eval, triplets_loss \"\"\" Triplets. Makes output distribution same as that",
"%d batch %d \" \"loss %f time %s\" % \\",
"for d in train_dataloaders) b_i = 0 for tup in",
"if config.restart: opt_path = os.path.join(config.out_dir, \"latest_optimiser.pytorch\") if taking_best: opt_path =",
"%s\" % reloaded_config_path) with open(reloaded_config_path, \"rb\") as config_f: config =",
"with open(reloaded_config_path, \"rb\") as config_f: config = pickle.load(config_f) assert (config.model_ind",
"< 10): print(\"Model ind %d epoch %d batch %d \"",
"plt.subplots(4, sharex=False, figsize=(20, 20)) # Train ------------------------------------------------------------------------ for e_i in",
"time %s\" % \\ (config.model_ind, e_i, b_i, curr_loss.item(), datetime.now())) sys.stdout.flush()",
"= config.epoch_acc[:next_epoch] # in case we overshot config.epoch_loss = config.epoch_loss[:next_epoch]",
"and lr schedule config.num_epochs = given_config.num_epochs config.lr_schedule = given_config.lr_schedule if",
"os.path.join(config.out_dir, \"latest_optimiser.pytorch\") if taking_best: opt_path = os.path.join(config.out_dir, \"best_optimiser.pytorch\") optimiser.load_state_dict(torch.load(opt_path)) #",
"copy over new num_epochs and lr schedule config.num_epochs = given_config.num_epochs",
"e_i in config.lr_schedule: optimiser = update_lr(optimiser, lr_mult=config.lr_mult) avg_loss = 0.",
"open(os.path.join(config.out_dir, \"config.txt\"), \"w\") as text_file: text_file.write(\"%s\" % config) if config.test_code:",
"(config.model_ind == given_config.model_ind) config.restart = True # copy over new",
"= archs.__dict__[config.arch](config) if config.restart: model_path = os.path.join(config.out_dir, \"latest_net.pytorch\") taking_best =",
"get_opt(config.opt)(net.module.parameters(), lr=config.lr) if config.restart: opt_path = os.path.join(config.out_dir, \"latest_optimiser.pytorch\") if taking_best:",
"%f\" % max(config.epoch_acc)) axarr[1].clear() axarr[1].plot(config.epoch_loss) axarr[1].set_title(\"Loss\") axarr[2].clear() for c in",
"default=10) parser.add_argument(\"--kmeans_on_features\", default=False, action=\"store_true\") # transforms # used for \"positive\"",
"parser.add_argument(\"--dataset\", type=str, required=True) parser.add_argument(\"--dataset_root\", type=str, required=True) parser.add_argument(\"--gt_k\", type=int, required=True) parser.add_argument(\"--output_k\",",
"parser.add_argument(\"--lr\", type=float, default=0.01) parser.add_argument(\"--lr_schedule\", type=int, nargs=\"+\", default=[]) parser.add_argument(\"--lr_mult\", type=float, default=0.1)",
"matplotlib.use('Agg') import matplotlib.pyplot as plt import proj.archs as archs from",
"and b_i < 10): print(\"Model ind %d epoch %d batch",
"parser.add_argument(\"--output_k\", type=int, required=True) parser.add_argument(\"--lr\", type=float, default=0.01) parser.add_argument(\"--lr_schedule\", type=int, nargs=\"+\", default=[])",
"%s\" % config_to_str(config)) # Data, nets, optimisers ------------------------------------------------------- dataloader_original, dataloader_positive,",
"dest=\"no_jitter\", default=False, action=\"store_true\") parser.add_argument(\"--no_flip\", dest=\"no_flip\", default=False, action=\"store_true\") config = parser.parse_args()",
"0.5]) parser.add_argument(\"--data_std\", type=float, nargs=\"+\", default=[0.5, 0.5, 0.5]) parser.add_argument(\"--crop_orig\", dest=\"crop_orig\", default=False,",
"dataloader_positive, dataloader_negative, \\ dataloader_test = make_triplets_data(config) train_dataloaders = [dataloader_original, dataloader_positive,",
"repeller. Greyscale version (no sobel). \"\"\" # Options ---------------------------------------------------------------------- parser",
"1 curr_loss.backward() optimiser.step() b_i += 1 if b_i == 2",
"= net(imgs_orig) outs_pos = net(imgs_pos) outs_neg = net(imgs_neg) curr_loss =",
"c in xrange(config.gt_k): axarr[2].plot(config.masses[:, c]) axarr[2].set_title(\"masses\") axarr[3].clear() for c in",
"else: config.epoch_acc = [] config.epoch_loss = [] config.masses = None",
"net = torch.nn.DataParallel(net) net.train() optimiser = get_opt(config.opt)(net.module.parameters(), lr=config.lr) if config.restart:",
"config.restart = True # copy over new num_epochs and lr",
"%d \" \"loss %f time %s\" % \\ (config.model_ind, e_i,",
"for imgs_tf parser.add_argument(\"--tf3_crop_diff\", dest=\"tf3_crop_diff\", default=False, action=\"store_true\") parser.add_argument(\"--tf3_crop_sz\", type=int, default=0) parser.add_argument(\"--input_sz\",",
"is_best = triplets_eval(config, net, dataloader_test=dataloader_test, sobel=False) print(\"Time %s, acc %s\"",
"default=0) parser.add_argument(\"--input_sz\", type=int, default=96) parser.add_argument(\"--rot_val\", type=float, default=0.) parser.add_argument(\"--always_rot\", dest=\"always_rot\", default=False,",
"config.lr_schedule: optimiser = update_lr(optimiser, lr_mult=config.lr_mult) avg_loss = 0. # over",
"assert (config.kmeans_on_features) config.out_dir = os.path.join(config.out_root, str(config.model_ind)) config.dataloader_batch_sz = config.batch_sz config.num_dataloaders",
"axarr[1].set_title(\"Loss\") axarr[2].clear() for c in xrange(config.gt_k): axarr[2].plot(config.masses[:, c]) axarr[2].set_title(\"masses\") axarr[3].clear()",
"= (d for d in train_dataloaders) b_i = 0 for",
"of attractor, and different to that of repeller. Greyscale version",
"import sys from datetime import datetime import matplotlib import numpy",
"= pickle.load(config_f) assert (config.model_ind == given_config.model_ind) config.restart = True #",
"default=[84]) # allow diff crop for imgs_tf parser.add_argument(\"--tf3_crop_diff\", dest=\"tf3_crop_diff\", default=False,",
"config.last_epoch + 1 # corresponds to last saved model else:",
"print_function import argparse import itertools import os import pickle import",
"taking_best: print(\"using best instead of latest\") model_path = os.path.join(config.out_dir, \"best_net.pytorch\")",
"net = archs.__dict__[config.arch](config) if config.restart: model_path = os.path.join(config.out_dir, \"latest_net.pytorch\") taking_best",
"default=0.1) parser.add_argument(\"--num_epochs\", type=int, default=1000) parser.add_argument(\"--batch_sz\", type=int, required=True) # num pairs",
"finite... %s:\" % str(curr_loss.item())) exit(1) avg_loss += curr_loss.item() avg_loss_count +=",
"import os import pickle import sys from datetime import datetime",
"% str(curr_loss.item())) exit(1) avg_loss += curr_loss.item() avg_loss_count += 1 curr_loss.backward()",
"proj.utils.cluster.general import config_to_str, get_opt, update_lr from proj.utils.cluster.baselines.triplets import make_triplets_data, \\",
"dest=\"demean\", default=False, action=\"store_true\") parser.add_argument(\"--per_img_demean\", dest=\"per_img_demean\", default=False, action=\"store_true\") parser.add_argument(\"--data_mean\", type=float, nargs=\"+\",",
"\"config.pickle\") print(\"Loading restarting config from: %s\" % reloaded_config_path) with open(reloaded_config_path,",
"= tup[2][0].cuda() outs_orig = net(imgs_orig) outs_pos = net(imgs_pos) outs_neg =",
"config_to_str(config)) # Data, nets, optimisers ------------------------------------------------------- dataloader_original, dataloader_positive, dataloader_negative, \\",
"for \"positive\" sample parser.add_argument(\"--demean\", dest=\"demean\", default=False, action=\"store_true\") parser.add_argument(\"--per_img_demean\", dest=\"per_img_demean\", default=False,",
"dest=\"tf3_crop_diff\", default=False, action=\"store_true\") parser.add_argument(\"--tf3_crop_sz\", type=int, default=0) parser.add_argument(\"--input_sz\", type=int, default=96) parser.add_argument(\"--rot_val\",",
"== given_config.model_ind) config.restart = True # copy over new num_epochs",
"os.path.join(config.out_dir, \"best_net.pytorch\")) torch.save(optimiser.state_dict(), os.path.join(config.out_dir, \"best_optimiser.pytorch\")) if e_i % config.save_freq ==",
"type=float, nargs=\"+\", default=[0.5, 0.5, 0.5]) parser.add_argument(\"--crop_orig\", dest=\"crop_orig\", default=False, action=\"store_true\") parser.add_argument(\"--crop_other\",",
"net.load_state_dict( torch.load(model_path, map_location=lambda storage, loc: storage)) net.cuda() net = torch.nn.DataParallel(net)",
"config.save_freq == 0): net.module.cpu() if is_best: torch.save(net.module.state_dict(), os.path.join(config.out_dir, \"best_net.pytorch\")) torch.save(optimiser.state_dict(),",
"_ = triplets_eval(config, net, dataloader_test=dataloader_test, sobel=False) print(\"Pre: time %s: \\n",
"for last saved version net.module.cuda() with open(os.path.join(config.out_dir, \"config.pickle\"), 'wb') as",
"action=\"store_true\") parser.add_argument(\"--no_jitter\", dest=\"no_jitter\", default=False, action=\"store_true\") parser.add_argument(\"--no_flip\", dest=\"no_flip\", default=False, action=\"store_true\") config",
"= tup[1][0].cuda() imgs_neg = tup[2][0].cuda() outs_orig = net(imgs_orig) outs_pos =",
"not finite... %s:\" % str(curr_loss.item())) exit(1) avg_loss += curr_loss.item() avg_loss_count",
"nargs=\"+\", default=[]) parser.add_argument(\"--lr_mult\", type=float, default=0.1) parser.add_argument(\"--num_epochs\", type=int, default=1000) parser.add_argument(\"--batch_sz\", type=int,",
"0.5, 0.5]) parser.add_argument(\"--crop_orig\", dest=\"crop_orig\", default=False, action=\"store_true\") parser.add_argument(\"--crop_other\", dest=\"crop_other\", default=False, action=\"store_true\")",
"action=\"store_true\") parser.add_argument(\"--tf1_crop\", type=str, default=\"random\") # type name parser.add_argument(\"--tf2_crop\", type=str, default=\"random\")",
"\\ dataloader_test = make_triplets_data(config) train_dataloaders = [dataloader_original, dataloader_positive, dataloader_negative] net",
"import matplotlib import numpy as np import torch matplotlib.use('Agg') import",
"get_opt, update_lr from proj.utils.cluster.baselines.triplets import make_triplets_data, \\ triplets_eval, triplets_loss \"\"\"",
"config.per_class_acc = config.per_class_acc[:next_epoch, :] else: config.epoch_acc = [] config.epoch_loss =",
"parser.add_argument(\"--no_jitter\", dest=\"no_jitter\", default=False, action=\"store_true\") parser.add_argument(\"--no_flip\", dest=\"no_flip\", default=False, action=\"store_true\") config =",
"os.makedirs(config.out_dir) if config.restart: given_config = config reloaded_config_path = os.path.join(given_config.out_dir, \"config.pickle\")",
"parser.add_argument(\"--data_std\", type=float, nargs=\"+\", default=[0.5, 0.5, 0.5]) parser.add_argument(\"--crop_orig\", dest=\"crop_orig\", default=False, action=\"store_true\")",
"instead of latest\") model_path = os.path.join(config.out_dir, \"best_net.pytorch\") net.load_state_dict( torch.load(model_path, map_location=lambda",
"curr_loss = triplets_loss(outs_orig, outs_pos, outs_neg) if ((b_i % 100) ==",
"that of attractor, and different to that of repeller. Greyscale",
"os.path.exists(config.out_dir): os.makedirs(config.out_dir) if config.restart: given_config = config reloaded_config_path = os.path.join(given_config.out_dir,",
"as np import torch matplotlib.use('Agg') import matplotlib.pyplot as plt import",
"as archs from proj.utils.cluster.general import config_to_str, get_opt, update_lr from proj.utils.cluster.baselines.triplets",
"+ 1 print(\"starting from epoch %d\" % next_epoch) config.epoch_acc =",
"%d epoch %d batch %d \" \"loss %f time %s\"",
"epoch over both heads is finished is_best = triplets_eval(config, net,",
"for c in xrange(config.gt_k): axarr[2].plot(config.masses[:, c]) axarr[2].set_title(\"masses\") axarr[3].clear() for c",
"= 0. # over heads and head_epochs (and sub_heads) avg_loss_count",
"default=False, action=\"store_true\") parser.add_argument(\"--save_freq\", type=int, default=10) parser.add_argument(\"--kmeans_on_features\", default=False, action=\"store_true\") # transforms",
"dest=\"crop_orig\", default=False, action=\"store_true\") parser.add_argument(\"--crop_other\", dest=\"crop_other\", default=False, action=\"store_true\") parser.add_argument(\"--tf1_crop\", type=str, default=\"random\")",
"with open(os.path.join(config.out_dir, \"config.pickle\"), 'wb') as outfile: pickle.dump(config, outfile) with open(os.path.join(config.out_dir,",
"Options ---------------------------------------------------------------------- parser = argparse.ArgumentParser() parser.add_argument(\"--model_ind\", type=int, required=True) parser.add_argument(\"--arch\", type=str,",
"% config_to_str(config)) # Data, nets, optimisers ------------------------------------------------------- dataloader_original, dataloader_positive, dataloader_negative,",
"type=float, nargs=\"+\", default=[0.5, 0.5, 0.5]) parser.add_argument(\"--data_std\", type=float, nargs=\"+\", default=[0.5, 0.5,",
"curr_loss.item(), datetime.now())) sys.stdout.flush() if not np.isfinite(float(curr_loss.item())): print(\"Loss is not finite...",
"iterators = (d for d in train_dataloaders) b_i = 0",
"config.kmeans_on_features = False else: print(\"Config: %s\" % config_to_str(config)) # Data,",
"optimisers ------------------------------------------------------- dataloader_original, dataloader_positive, dataloader_negative, \\ dataloader_test = make_triplets_data(config) train_dataloaders",
"parser.add_argument(\"--tf1_crop\", type=str, default=\"random\") # type name parser.add_argument(\"--tf2_crop\", type=str, default=\"random\") parser.add_argument(\"--tf1_crop_sz\",",
"\"config.txt\"), \"w\") as text_file: text_file.write(\"%s\" % config) if config.test_code: exit(0)",
"storage -------------------------------------------------------------- if config.restart: if not taking_best: next_epoch = config.last_epoch",
"import numpy as np import torch matplotlib.use('Agg') import matplotlib.pyplot as",
"default=False, action=\"store_true\") parser.add_argument(\"--no_jitter\", dest=\"no_jitter\", default=False, action=\"store_true\") parser.add_argument(\"--no_flip\", dest=\"no_flip\", default=False, action=\"store_true\")",
"next_epoch = 1 fig, axarr = plt.subplots(4, sharex=False, figsize=(20, 20))",
"required=True) parser.add_argument(\"--arch\", type=str, required=True) parser.add_argument(\"--opt\", type=str, default=\"Adam\") parser.add_argument(\"--dataset\", type=str, required=True)",
"as config_f: config = pickle.load(config_f) assert (config.model_ind == given_config.model_ind) config.restart",
"saved model else: next_epoch = np.argmax(np.array(config.epoch_acc)) + 1 print(\"starting from",
"parser.add_argument(\"--demean\", dest=\"demean\", default=False, action=\"store_true\") parser.add_argument(\"--per_img_demean\", dest=\"per_img_demean\", default=False, action=\"store_true\") parser.add_argument(\"--data_mean\", type=float,",
"e_i: %d\" % (e_i)) if e_i in config.lr_schedule: optimiser =",
"action=\"store_true\") # transforms # used for \"positive\" sample parser.add_argument(\"--demean\", dest=\"demean\",",
"= tup[0][0].cuda() imgs_pos = tup[1][0].cuda() imgs_neg = tup[2][0].cuda() outs_orig =",
"%s\" % (datetime.now(), config.epoch_acc[-1])) sys.stdout.flush() axarr[0].clear() axarr[0].plot(config.epoch_acc) axarr[0].set_title(\"acc, top: %f\"",
"config.masses = config.masses[:next_epoch, :] config.per_class_acc = config.per_class_acc[:next_epoch, :] else: config.epoch_acc",
"torch.save(net.module.state_dict(), os.path.join(config.out_dir, \"latest_net.pytorch\")) torch.save(optimiser.state_dict(), os.path.join(config.out_dir, \"latest_optimiser.pytorch\")) config.last_epoch = e_i #",
"num_epochs and lr schedule config.num_epochs = given_config.num_epochs config.lr_schedule = given_config.lr_schedule",
"0 sys.stdout.flush() iterators = (d for d in train_dataloaders) b_i",
"opt_path = os.path.join(config.out_dir, \"latest_optimiser.pytorch\") if taking_best: opt_path = os.path.join(config.out_dir, \"best_optimiser.pytorch\")",
"dest=\"crop_other\", default=False, action=\"store_true\") parser.add_argument(\"--tf1_crop\", type=str, default=\"random\") # type name parser.add_argument(\"--tf2_crop\",",
"type=str, default=\"Adam\") parser.add_argument(\"--dataset\", type=str, required=True) parser.add_argument(\"--dataset_root\", type=str, required=True) parser.add_argument(\"--gt_k\", type=int,",
"lr=config.lr) if config.restart: opt_path = os.path.join(config.out_dir, \"latest_optimiser.pytorch\") if taking_best: opt_path",
"schedule config.num_epochs = given_config.num_epochs config.lr_schedule = given_config.lr_schedule if not hasattr(config,",
"axarr[0].set_title(\"acc, top: %f\" % max(config.epoch_acc)) axarr[1].clear() axarr[1].plot(config.epoch_loss) axarr[1].set_title(\"Loss\") axarr[2].clear() for",
"config.restart: opt_path = os.path.join(config.out_dir, \"latest_optimiser.pytorch\") if taking_best: opt_path = os.path.join(config.out_dir,",
"config.test_code: break avg_loss = float(avg_loss / avg_loss_count) config.epoch_loss.append(avg_loss) # Eval",
"(config.model_ind, e_i, b_i, curr_loss.item(), datetime.now())) sys.stdout.flush() if not np.isfinite(float(curr_loss.item())): print(\"Loss",
"# Train ------------------------------------------------------------------------ for e_i in xrange(next_epoch, config.num_epochs): print(\"Starting e_i:",
"config.epoch_loss[:next_epoch] config.masses = config.masses[:next_epoch, :] config.per_class_acc = config.per_class_acc[:next_epoch, :] else:",
"parser.add_argument(\"--lr_schedule\", type=int, nargs=\"+\", default=[]) parser.add_argument(\"--lr_mult\", type=float, default=0.1) parser.add_argument(\"--num_epochs\", type=int, default=1000)",
"xrange(config.gt_k): axarr[3].plot(config.per_class_acc[:, c]) axarr[3].set_title(\"per_class_acc\") fig.tight_layout() fig.canvas.draw_idle() fig.savefig(os.path.join(config.out_dir, \"plots.png\")) if is_best",
"%s\" % (datetime.now(), config.epoch_acc[-1])) sys.stdout.flush() next_epoch = 1 fig, axarr",
"= 1 if config.output_k != config.gt_k: assert (config.output_k > config.gt_k)",
"sobel). \"\"\" # Options ---------------------------------------------------------------------- parser = argparse.ArgumentParser() parser.add_argument(\"--model_ind\", type=int,",
"> config.gt_k) assert (config.kmeans_on_features) config.out_dir = os.path.join(config.out_root, str(config.model_ind)) config.dataloader_batch_sz =",
"== 2 and config.test_code: break avg_loss = float(avg_loss / avg_loss_count)",
"default=\"Adam\") parser.add_argument(\"--dataset\", type=str, required=True) parser.add_argument(\"--dataset_root\", type=str, required=True) parser.add_argument(\"--gt_k\", type=int, required=True)",
"argparse import itertools import os import pickle import sys from",
"required=True) parser.add_argument(\"--gt_k\", type=int, required=True) parser.add_argument(\"--output_k\", type=int, required=True) parser.add_argument(\"--lr\", type=float, default=0.01)",
"and different to that of repeller. Greyscale version (no sobel).",
"= [dataloader_original, dataloader_positive, dataloader_negative] net = archs.__dict__[config.arch](config) if config.restart: model_path",
"os.path.join(config.out_root, str(config.model_ind)) config.dataloader_batch_sz = config.batch_sz config.num_dataloaders = 1 if not",
"settings and checks ---------------------------------------------------- config.in_channels = 1 if config.output_k !=",
"type=int, required=True) parser.add_argument(\"--output_k\", type=int, required=True) parser.add_argument(\"--lr\", type=float, default=0.01) parser.add_argument(\"--lr_schedule\", type=int,",
"type=float, default=0.) parser.add_argument(\"--always_rot\", dest=\"always_rot\", default=False, action=\"store_true\") parser.add_argument(\"--no_jitter\", dest=\"no_jitter\", default=False, action=\"store_true\")",
"fig.canvas.draw_idle() fig.savefig(os.path.join(config.out_dir, \"plots.png\")) if is_best or (e_i % config.save_freq ==",
"b_i < 10): print(\"Model ind %d epoch %d batch %d",
"net.module.cpu() if is_best: torch.save(net.module.state_dict(), os.path.join(config.out_dir, \"best_net.pytorch\")) torch.save(optimiser.state_dict(), os.path.join(config.out_dir, \"best_optimiser.pytorch\")) if",
"# over heads and head_epochs (and sub_heads) avg_loss_count = 0",
"= triplets_eval(config, net, dataloader_test=dataloader_test, sobel=False) print(\"Pre: time %s: \\n %s\"",
"config.epoch_loss.append(avg_loss) # Eval and storage ----------------------------------------------------------- # when epoch over",
"%f time %s\" % \\ (config.model_ind, e_i, b_i, curr_loss.item(), datetime.now()))",
"for tup in itertools.izip(*iterators): net.module.zero_grad() imgs_orig = tup[0][0].cuda() imgs_pos =",
"update_lr from proj.utils.cluster.baselines.triplets import make_triplets_data, \\ triplets_eval, triplets_loss \"\"\" Triplets.",
"matplotlib.pyplot as plt import proj.archs as archs from proj.utils.cluster.general import",
"triplets_loss(outs_orig, outs_pos, outs_neg) if ((b_i % 100) == 0) or",
"opt_path = os.path.join(config.out_dir, \"best_optimiser.pytorch\") optimiser.load_state_dict(torch.load(opt_path)) # Results storage -------------------------------------------------------------- if",
"if not hasattr(config, \"kmeans_on_features\"): config.kmeans_on_features = False else: print(\"Config: %s\"",
"config.epoch_loss = config.epoch_loss[:next_epoch] config.masses = config.masses[:next_epoch, :] config.per_class_acc = config.per_class_acc[:next_epoch,",
"%s\" % \\ (config.model_ind, e_i, b_i, curr_loss.item(), datetime.now())) sys.stdout.flush() if",
"datetime.now())) sys.stdout.flush() if not np.isfinite(float(curr_loss.item())): print(\"Loss is not finite... %s:\"",
"% (e_i)) if e_i in config.lr_schedule: optimiser = update_lr(optimiser, lr_mult=config.lr_mult)",
"dataloader_original, dataloader_positive, dataloader_negative, \\ dataloader_test = make_triplets_data(config) train_dataloaders = [dataloader_original,",
"parser.add_argument(\"--batch_sz\", type=int, required=True) # num pairs parser.add_argument(\"--out_root\", type=str, default=\"/scratch/shared/slow/xuji/iid_private\") parser.add_argument(\"--restart\",",
"not np.isfinite(float(curr_loss.item())): print(\"Loss is not finite... %s:\" % str(curr_loss.item())) exit(1)",
"model_path = os.path.join(config.out_dir, \"latest_net.pytorch\") taking_best = not os.path.exists(model_path) if taking_best:",
"in xrange(next_epoch, config.num_epochs): print(\"Starting e_i: %d\" % (e_i)) if e_i",
"net(imgs_pos) outs_neg = net(imgs_neg) curr_loss = triplets_loss(outs_orig, outs_pos, outs_neg) if",
"== 0): net.module.cpu() if is_best: torch.save(net.module.state_dict(), os.path.join(config.out_dir, \"best_net.pytorch\")) torch.save(optimiser.state_dict(), os.path.join(config.out_dir,",
"10): print(\"Model ind %d epoch %d batch %d \" \"loss",
"parser.add_argument(\"--no_flip\", dest=\"no_flip\", default=False, action=\"store_true\") config = parser.parse_args() # Fixed settings",
"plt import proj.archs as archs from proj.utils.cluster.general import config_to_str, get_opt,",
"corresponds to last saved model else: next_epoch = np.argmax(np.array(config.epoch_acc)) +",
"from proj.utils.cluster.general import config_to_str, get_opt, update_lr from proj.utils.cluster.baselines.triplets import make_triplets_data,",
"net.train() optimiser = get_opt(config.opt)(net.module.parameters(), lr=config.lr) if config.restart: opt_path = os.path.join(config.out_dir,",
"-------------------------------------------------------------- if config.restart: if not taking_best: next_epoch = config.last_epoch +",
"%s, acc %s\" % (datetime.now(), config.epoch_acc[-1])) sys.stdout.flush() axarr[0].clear() axarr[0].plot(config.epoch_acc) axarr[0].set_title(\"acc,",
"= config.epoch_loss[:next_epoch] config.masses = config.masses[:next_epoch, :] config.per_class_acc = config.per_class_acc[:next_epoch, :]",
"print(\"starting from epoch %d\" % next_epoch) config.epoch_acc = config.epoch_acc[:next_epoch] #",
"sys.stdout.flush() axarr[0].clear() axarr[0].plot(config.epoch_acc) axarr[0].set_title(\"acc, top: %f\" % max(config.epoch_acc)) axarr[1].clear() axarr[1].plot(config.epoch_loss)",
"parser.add_argument(\"--always_rot\", dest=\"always_rot\", default=False, action=\"store_true\") parser.add_argument(\"--no_jitter\", dest=\"no_jitter\", default=False, action=\"store_true\") parser.add_argument(\"--no_flip\", dest=\"no_flip\",",
"import pickle import sys from datetime import datetime import matplotlib",
"config.gt_k: assert (config.output_k > config.gt_k) assert (config.kmeans_on_features) config.out_dir = os.path.join(config.out_root,",
"20)) # Train ------------------------------------------------------------------------ for e_i in xrange(next_epoch, config.num_epochs): print(\"Starting",
"config.masses = None config.per_class_acc = None _ = triplets_eval(config, net,",
"overshot config.epoch_loss = config.epoch_loss[:next_epoch] config.masses = config.masses[:next_epoch, :] config.per_class_acc =",
"figsize=(20, 20)) # Train ------------------------------------------------------------------------ for e_i in xrange(next_epoch, config.num_epochs):",
"Fixed settings and checks ---------------------------------------------------- config.in_channels = 1 if config.output_k",
"config.dataloader_batch_sz = config.batch_sz config.num_dataloaders = 1 if not os.path.exists(config.out_dir): os.makedirs(config.out_dir)",
"net, dataloader_test=dataloader_test, sobel=False) print(\"Pre: time %s: \\n %s\" % (datetime.now(),",
"1 if b_i == 2 and config.test_code: break avg_loss =",
"given_config.model_ind) config.restart = True # copy over new num_epochs and",
"# Data, nets, optimisers ------------------------------------------------------- dataloader_original, dataloader_positive, dataloader_negative, \\ dataloader_test",
"finished is_best = triplets_eval(config, net, dataloader_test=dataloader_test, sobel=False) print(\"Time %s, acc",
"archs.__dict__[config.arch](config) if config.restart: model_path = os.path.join(config.out_dir, \"latest_net.pytorch\") taking_best = not",
"import matplotlib.pyplot as plt import proj.archs as archs from proj.utils.cluster.general",
"= os.path.join(config.out_root, str(config.model_ind)) config.dataloader_batch_sz = config.batch_sz config.num_dataloaders = 1 if",
"Triplets. Makes output distribution same as that of attractor, and",
"os.path.join(given_config.out_dir, \"config.pickle\") print(\"Loading restarting config from: %s\" % reloaded_config_path) with",
"train_dataloaders = [dataloader_original, dataloader_positive, dataloader_negative] net = archs.__dict__[config.arch](config) if config.restart:",
"print(\"Pre: time %s: \\n %s\" % (datetime.now(), config.epoch_acc[-1])) sys.stdout.flush() next_epoch",
"if e_i in config.lr_schedule: optimiser = update_lr(optimiser, lr_mult=config.lr_mult) avg_loss =",
"next_epoch) config.epoch_acc = config.epoch_acc[:next_epoch] # in case we overshot config.epoch_loss",
"if config.restart: given_config = config reloaded_config_path = os.path.join(given_config.out_dir, \"config.pickle\") print(\"Loading",
"in itertools.izip(*iterators): net.module.zero_grad() imgs_orig = tup[0][0].cuda() imgs_pos = tup[1][0].cuda() imgs_neg",
"default=False, action=\"store_true\") parser.add_argument(\"--tf1_crop\", type=str, default=\"random\") # type name parser.add_argument(\"--tf2_crop\", type=str,",
"pickle.load(config_f) assert (config.model_ind == given_config.model_ind) config.restart = True # copy",
"default=0.01) parser.add_argument(\"--lr_schedule\", type=int, nargs=\"+\", default=[]) parser.add_argument(\"--lr_mult\", type=float, default=0.1) parser.add_argument(\"--num_epochs\", type=int,",
"action=\"store_true\") config = parser.parse_args() # Fixed settings and checks ----------------------------------------------------",
"None _ = triplets_eval(config, net, dataloader_test=dataloader_test, sobel=False) print(\"Pre: time %s:",
"outs_orig = net(imgs_orig) outs_pos = net(imgs_pos) outs_neg = net(imgs_neg) curr_loss",
"required=True) parser.add_argument(\"--lr\", type=float, default=0.01) parser.add_argument(\"--lr_schedule\", type=int, nargs=\"+\", default=[]) parser.add_argument(\"--lr_mult\", type=float,",
"+= curr_loss.item() avg_loss_count += 1 curr_loss.backward() optimiser.step() b_i += 1",
"make_triplets_data, \\ triplets_eval, triplets_loss \"\"\" Triplets. Makes output distribution same",
"nets, optimisers ------------------------------------------------------- dataloader_original, dataloader_positive, dataloader_negative, \\ dataloader_test = make_triplets_data(config)",
"---------------------------------------------------------------------- parser = argparse.ArgumentParser() parser.add_argument(\"--model_ind\", type=int, required=True) parser.add_argument(\"--arch\", type=str, required=True)",
"config.epoch_loss = [] config.masses = None config.per_class_acc = None _",
"b_i += 1 if b_i == 2 and config.test_code: break",
"1 print(\"starting from epoch %d\" % next_epoch) config.epoch_acc = config.epoch_acc[:next_epoch]",
"over both heads is finished is_best = triplets_eval(config, net, dataloader_test=dataloader_test,",
"type=str, required=True) parser.add_argument(\"--dataset_root\", type=str, required=True) parser.add_argument(\"--gt_k\", type=int, required=True) parser.add_argument(\"--output_k\", type=int,",
"type name parser.add_argument(\"--tf2_crop\", type=str, default=\"random\") parser.add_argument(\"--tf1_crop_sz\", type=int, default=84) parser.add_argument(\"--tf2_crop_szs\", type=int,",
"(e_i)) if e_i in config.lr_schedule: optimiser = update_lr(optimiser, lr_mult=config.lr_mult) avg_loss",
"e_i, b_i, curr_loss.item(), datetime.now())) sys.stdout.flush() if not np.isfinite(float(curr_loss.item())): print(\"Loss is",
"required=True) parser.add_argument(\"--dataset_root\", type=str, required=True) parser.add_argument(\"--gt_k\", type=int, required=True) parser.add_argument(\"--output_k\", type=int, required=True)",
"pickle import sys from datetime import datetime import matplotlib import",
"parser.add_argument(\"--dataset_root\", type=str, required=True) parser.add_argument(\"--gt_k\", type=int, required=True) parser.add_argument(\"--output_k\", type=int, required=True) parser.add_argument(\"--lr\",",
"= [] config.masses = None config.per_class_acc = None _ =",
"((b_i % 100) == 0) or (e_i == next_epoch and",
"= 1 fig, axarr = plt.subplots(4, sharex=False, figsize=(20, 20)) #",
"default=\"random\") # type name parser.add_argument(\"--tf2_crop\", type=str, default=\"random\") parser.add_argument(\"--tf1_crop_sz\", type=int, default=84)",
"# allow diff crop for imgs_tf parser.add_argument(\"--tf3_crop_diff\", dest=\"tf3_crop_diff\", default=False, action=\"store_true\")",
"action=\"store_true\") parser.add_argument(\"--save_freq\", type=int, default=10) parser.add_argument(\"--kmeans_on_features\", default=False, action=\"store_true\") # transforms #",
"sys.stdout.flush() iterators = (d for d in train_dataloaders) b_i =",
"for c in xrange(config.gt_k): axarr[3].plot(config.per_class_acc[:, c]) axarr[3].set_title(\"per_class_acc\") fig.tight_layout() fig.canvas.draw_idle() fig.savefig(os.path.join(config.out_dir,",
"open(reloaded_config_path, \"rb\") as config_f: config = pickle.load(config_f) assert (config.model_ind ==",
"\\ triplets_eval, triplets_loss \"\"\" Triplets. Makes output distribution same as",
"default=[0.5, 0.5, 0.5]) parser.add_argument(\"--crop_orig\", dest=\"crop_orig\", default=False, action=\"store_true\") parser.add_argument(\"--crop_other\", dest=\"crop_other\", default=False,",
"outs_pos, outs_neg) if ((b_i % 100) == 0) or (e_i",
"else: next_epoch = np.argmax(np.array(config.epoch_acc)) + 1 print(\"starting from epoch %d\"",
"0. # over heads and head_epochs (and sub_heads) avg_loss_count =",
"same as that of attractor, and different to that of",
"dest=\"always_rot\", default=False, action=\"store_true\") parser.add_argument(\"--no_jitter\", dest=\"no_jitter\", default=False, action=\"store_true\") parser.add_argument(\"--no_flip\", dest=\"no_flip\", default=False,",
"print(\"Time %s, acc %s\" % (datetime.now(), config.epoch_acc[-1])) sys.stdout.flush() axarr[0].clear() axarr[0].plot(config.epoch_acc)",
"(e_i % config.save_freq == 0): net.module.cpu() if is_best: torch.save(net.module.state_dict(), os.path.join(config.out_dir,",
"next_epoch = np.argmax(np.array(config.epoch_acc)) + 1 print(\"starting from epoch %d\" %",
"ind %d epoch %d batch %d \" \"loss %f time",
"default=False, action=\"store_true\") parser.add_argument(\"--test_code\", dest=\"test_code\", default=False, action=\"store_true\") parser.add_argument(\"--save_freq\", type=int, default=10) parser.add_argument(\"--kmeans_on_features\",",
"default=False, action=\"store_true\") parser.add_argument(\"--crop_other\", dest=\"crop_other\", default=False, action=\"store_true\") parser.add_argument(\"--tf1_crop\", type=str, default=\"random\") #",
"= parser.parse_args() # Fixed settings and checks ---------------------------------------------------- config.in_channels =",
"axarr[3].plot(config.per_class_acc[:, c]) axarr[3].set_title(\"per_class_acc\") fig.tight_layout() fig.canvas.draw_idle() fig.savefig(os.path.join(config.out_dir, \"plots.png\")) if is_best or",
"\"latest_net.pytorch\")) torch.save(optimiser.state_dict(), os.path.join(config.out_dir, \"latest_optimiser.pytorch\")) config.last_epoch = e_i # for last",
"axarr[3].set_title(\"per_class_acc\") fig.tight_layout() fig.canvas.draw_idle() fig.savefig(os.path.join(config.out_dir, \"plots.png\")) if is_best or (e_i %",
"np import torch matplotlib.use('Agg') import matplotlib.pyplot as plt import proj.archs",
"= float(avg_loss / avg_loss_count) config.epoch_loss.append(avg_loss) # Eval and storage -----------------------------------------------------------",
"= os.path.join(config.out_dir, \"latest_optimiser.pytorch\") if taking_best: opt_path = os.path.join(config.out_dir, \"best_optimiser.pytorch\") optimiser.load_state_dict(torch.load(opt_path))",
"type=float, default=0.1) parser.add_argument(\"--num_epochs\", type=int, default=1000) parser.add_argument(\"--batch_sz\", type=int, required=True) # num",
"__future__ import print_function import argparse import itertools import os import",
"default=96) parser.add_argument(\"--rot_val\", type=float, default=0.) parser.add_argument(\"--always_rot\", dest=\"always_rot\", default=False, action=\"store_true\") parser.add_argument(\"--no_jitter\", dest=\"no_jitter\",",
"# type name parser.add_argument(\"--tf2_crop\", type=str, default=\"random\") parser.add_argument(\"--tf1_crop_sz\", type=int, default=84) parser.add_argument(\"--tf2_crop_szs\",",
"used for \"positive\" sample parser.add_argument(\"--demean\", dest=\"demean\", default=False, action=\"store_true\") parser.add_argument(\"--per_img_demean\", dest=\"per_img_demean\",",
"if not np.isfinite(float(curr_loss.item())): print(\"Loss is not finite... %s:\" % str(curr_loss.item()))",
"axarr[2].plot(config.masses[:, c]) axarr[2].set_title(\"masses\") axarr[3].clear() for c in xrange(config.gt_k): axarr[3].plot(config.per_class_acc[:, c])",
"c]) axarr[3].set_title(\"per_class_acc\") fig.tight_layout() fig.canvas.draw_idle() fig.savefig(os.path.join(config.out_dir, \"plots.png\")) if is_best or (e_i",
"parser.add_argument(\"--test_code\", dest=\"test_code\", default=False, action=\"store_true\") parser.add_argument(\"--save_freq\", type=int, default=10) parser.add_argument(\"--kmeans_on_features\", default=False, action=\"store_true\")",
"in xrange(config.gt_k): axarr[2].plot(config.masses[:, c]) axarr[2].set_title(\"masses\") axarr[3].clear() for c in xrange(config.gt_k):",
"from datetime import datetime import matplotlib import numpy as np",
"required=True) # num pairs parser.add_argument(\"--out_root\", type=str, default=\"/scratch/shared/slow/xuji/iid_private\") parser.add_argument(\"--restart\", dest=\"restart\", default=False,",
"= update_lr(optimiser, lr_mult=config.lr_mult) avg_loss = 0. # over heads and",
"config_to_str, get_opt, update_lr from proj.utils.cluster.baselines.triplets import make_triplets_data, \\ triplets_eval, triplets_loss",
"os.path.join(config.out_dir, \"best_net.pytorch\") net.load_state_dict( torch.load(model_path, map_location=lambda storage, loc: storage)) net.cuda() net",
"type=str, default=\"/scratch/shared/slow/xuji/iid_private\") parser.add_argument(\"--restart\", dest=\"restart\", default=False, action=\"store_true\") parser.add_argument(\"--test_code\", dest=\"test_code\", default=False, action=\"store_true\")",
"= not os.path.exists(model_path) if taking_best: print(\"using best instead of latest\")",
"itertools import os import pickle import sys from datetime import",
"not taking_best: next_epoch = config.last_epoch + 1 # corresponds to",
"parser.add_argument(\"--gt_k\", type=int, required=True) parser.add_argument(\"--output_k\", type=int, required=True) parser.add_argument(\"--lr\", type=float, default=0.01) parser.add_argument(\"--lr_schedule\",",
"nargs=\"+\", default=[0.5, 0.5, 0.5]) parser.add_argument(\"--crop_orig\", dest=\"crop_orig\", default=False, action=\"store_true\") parser.add_argument(\"--crop_other\", dest=\"crop_other\",",
"Data, nets, optimisers ------------------------------------------------------- dataloader_original, dataloader_positive, dataloader_negative, \\ dataloader_test =",
"np.argmax(np.array(config.epoch_acc)) + 1 print(\"starting from epoch %d\" % next_epoch) config.epoch_acc",
"os.path.join(config.out_dir, \"latest_net.pytorch\") taking_best = not os.path.exists(model_path) if taking_best: print(\"using best",
"if taking_best: print(\"using best instead of latest\") model_path = os.path.join(config.out_dir,",
"% (datetime.now(), config.epoch_acc[-1])) sys.stdout.flush() next_epoch = 1 fig, axarr =",
"tup in itertools.izip(*iterators): net.module.zero_grad() imgs_orig = tup[0][0].cuda() imgs_pos = tup[1][0].cuda()",
"if ((b_i % 100) == 0) or (e_i == next_epoch",
"/ avg_loss_count) config.epoch_loss.append(avg_loss) # Eval and storage ----------------------------------------------------------- # when",
"= os.path.join(config.out_dir, \"best_net.pytorch\") net.load_state_dict( torch.load(model_path, map_location=lambda storage, loc: storage)) net.cuda()",
"default=False, action=\"store_true\") config = parser.parse_args() # Fixed settings and checks",
"assert (config.output_k > config.gt_k) assert (config.kmeans_on_features) config.out_dir = os.path.join(config.out_root, str(config.model_ind))",
"= get_opt(config.opt)(net.module.parameters(), lr=config.lr) if config.restart: opt_path = os.path.join(config.out_dir, \"latest_optimiser.pytorch\") if",
"= net(imgs_neg) curr_loss = triplets_loss(outs_orig, outs_pos, outs_neg) if ((b_i %",
"e_i % config.save_freq == 0: torch.save(net.module.state_dict(), os.path.join(config.out_dir, \"latest_net.pytorch\")) torch.save(optimiser.state_dict(), os.path.join(config.out_dir,",
"e_i # for last saved version net.module.cuda() with open(os.path.join(config.out_dir, \"config.pickle\"),",
"% (datetime.now(), config.epoch_acc[-1])) sys.stdout.flush() axarr[0].clear() axarr[0].plot(config.epoch_acc) axarr[0].set_title(\"acc, top: %f\" %",
"parser.add_argument(\"--tf3_crop_diff\", dest=\"tf3_crop_diff\", default=False, action=\"store_true\") parser.add_argument(\"--tf3_crop_sz\", type=int, default=0) parser.add_argument(\"--input_sz\", type=int, default=96)",
"\"latest_optimiser.pytorch\")) config.last_epoch = e_i # for last saved version net.module.cuda()",
"default=84) parser.add_argument(\"--tf2_crop_szs\", type=int, nargs=\"+\", default=[84]) # allow diff crop for",
"print(\"Config: %s\" % config_to_str(config)) # Data, nets, optimisers ------------------------------------------------------- dataloader_original,",
"# in case we overshot config.epoch_loss = config.epoch_loss[:next_epoch] config.masses =",
"checks ---------------------------------------------------- config.in_channels = 1 if config.output_k != config.gt_k: assert",
"triplets_eval(config, net, dataloader_test=dataloader_test, sobel=False) print(\"Pre: time %s: \\n %s\" %",
"itertools.izip(*iterators): net.module.zero_grad() imgs_orig = tup[0][0].cuda() imgs_pos = tup[1][0].cuda() imgs_neg =",
"axarr[0].clear() axarr[0].plot(config.epoch_acc) axarr[0].set_title(\"acc, top: %f\" % max(config.epoch_acc)) axarr[1].clear() axarr[1].plot(config.epoch_loss) axarr[1].set_title(\"Loss\")",
"triplets_eval(config, net, dataloader_test=dataloader_test, sobel=False) print(\"Time %s, acc %s\" % (datetime.now(),",
"as plt import proj.archs as archs from proj.utils.cluster.general import config_to_str,",
"config.gt_k) assert (config.kmeans_on_features) config.out_dir = os.path.join(config.out_root, str(config.model_ind)) config.dataloader_batch_sz = config.batch_sz",
"config from: %s\" % reloaded_config_path) with open(reloaded_config_path, \"rb\") as config_f:",
"= os.path.join(given_config.out_dir, \"config.pickle\") print(\"Loading restarting config from: %s\" % reloaded_config_path)",
"os.path.join(config.out_dir, \"best_optimiser.pytorch\")) if e_i % config.save_freq == 0: torch.save(net.module.state_dict(), os.path.join(config.out_dir,",
"# used for \"positive\" sample parser.add_argument(\"--demean\", dest=\"demean\", default=False, action=\"store_true\") parser.add_argument(\"--per_img_demean\",",
"open(os.path.join(config.out_dir, \"config.pickle\"), 'wb') as outfile: pickle.dump(config, outfile) with open(os.path.join(config.out_dir, \"config.txt\"),",
"= 1 if not os.path.exists(config.out_dir): os.makedirs(config.out_dir) if config.restart: given_config =",
"crop for imgs_tf parser.add_argument(\"--tf3_crop_diff\", dest=\"tf3_crop_diff\", default=False, action=\"store_true\") parser.add_argument(\"--tf3_crop_sz\", type=int, default=0)",
"------------------------------------------------------- dataloader_original, dataloader_positive, dataloader_negative, \\ dataloader_test = make_triplets_data(config) train_dataloaders =",
"\"rb\") as config_f: config = pickle.load(config_f) assert (config.model_ind == given_config.model_ind)",
"config = parser.parse_args() # Fixed settings and checks ---------------------------------------------------- config.in_channels",
"= np.argmax(np.array(config.epoch_acc)) + 1 print(\"starting from epoch %d\" % next_epoch)",
"e_i in xrange(next_epoch, config.num_epochs): print(\"Starting e_i: %d\" % (e_i)) if",
"= config.last_epoch + 1 # corresponds to last saved model",
"[] config.epoch_loss = [] config.masses = None config.per_class_acc = None",
"= True # copy over new num_epochs and lr schedule",
"next_epoch and b_i < 10): print(\"Model ind %d epoch %d",
"0: torch.save(net.module.state_dict(), os.path.join(config.out_dir, \"latest_net.pytorch\")) torch.save(optimiser.state_dict(), os.path.join(config.out_dir, \"latest_optimiser.pytorch\")) config.last_epoch = e_i",
"optimiser = update_lr(optimiser, lr_mult=config.lr_mult) avg_loss = 0. # over heads",
"update_lr(optimiser, lr_mult=config.lr_mult) avg_loss = 0. # over heads and head_epochs",
"default=[0.5, 0.5, 0.5]) parser.add_argument(\"--data_std\", type=float, nargs=\"+\", default=[0.5, 0.5, 0.5]) parser.add_argument(\"--crop_orig\","
] |
[
"sa.Column(\"updated_at\", sa.DateTime(), nullable=True), sa.ForeignKeyConstraint( [\"job_id\"], [\"jobs.id\"], ), sa.PrimaryKeyConstraint(\"id\"), ) op.create_index(op.f(\"ix_job_statistics_job_id\"),",
"nullable=True), sa.ForeignKeyConstraint( [\"job_id\"], [\"jobs.id\"], ), sa.PrimaryKeyConstraint(\"id\"), ) op.create_index(op.f(\"ix_job_statistics_job_id\"), \"job_statistics\", [\"job_id\"],",
"[\"jobs.id\"], ), sa.PrimaryKeyConstraint(\"id\"), ) op.create_index(op.f(\"ix_job_statistics_job_id\"), \"job_statistics\", [\"job_id\"], unique=True) def downgrade():",
"Revises: 0083_add_perm_types_and_svc_perm Create Date: 2017-05-12 13:16:14.147368 \"\"\" # revision identifiers,",
"sa.BigInteger(), nullable=False), sa.Column(\"sms_sent\", sa.BigInteger(), nullable=False), sa.Column(\"sms_delivered\", sa.BigInteger(), nullable=False), sa.Column(\"sms_failed\", sa.BigInteger(),",
"sa.DateTime(), nullable=True), sa.ForeignKeyConstraint( [\"job_id\"], [\"jobs.id\"], ), sa.PrimaryKeyConstraint(\"id\"), ) op.create_index(op.f(\"ix_job_statistics_job_id\"), \"job_statistics\",",
"sa.Column(\"sms_failed\", sa.BigInteger(), nullable=False), sa.Column(\"letters_sent\", sa.BigInteger(), nullable=False), sa.Column(\"letters_failed\", sa.BigInteger(), nullable=False), sa.Column(\"created_at\",",
"sqlalchemy as sa from alembic import op from sqlalchemy.dialects import",
"nullable=False), sa.Column(\"letters_failed\", sa.BigInteger(), nullable=False), sa.Column(\"created_at\", sa.DateTime(), nullable=True), sa.Column(\"updated_at\", sa.DateTime(), nullable=True),",
"sa.PrimaryKeyConstraint(\"id\"), ) op.create_index(op.f(\"ix_job_statistics_job_id\"), \"job_statistics\", [\"job_id\"], unique=True) def downgrade(): op.drop_index(op.f(\"ix_job_statistics_job_id\"), table_name=\"job_statistics\")",
"sa.Column(\"letters_sent\", sa.BigInteger(), nullable=False), sa.Column(\"letters_failed\", sa.BigInteger(), nullable=False), sa.Column(\"created_at\", sa.DateTime(), nullable=True), sa.Column(\"updated_at\",",
"sa.ForeignKeyConstraint( [\"job_id\"], [\"jobs.id\"], ), sa.PrimaryKeyConstraint(\"id\"), ) op.create_index(op.f(\"ix_job_statistics_job_id\"), \"job_statistics\", [\"job_id\"], unique=True)",
"alembic import op from sqlalchemy.dialects import postgresql def upgrade(): op.create_table(",
"0084_add_job_stats Revises: 0083_add_perm_types_and_svc_perm Create Date: 2017-05-12 13:16:14.147368 \"\"\" # revision",
"sa.BigInteger(), nullable=False), sa.Column(\"letters_failed\", sa.BigInteger(), nullable=False), sa.Column(\"created_at\", sa.DateTime(), nullable=True), sa.Column(\"updated_at\", sa.DateTime(),",
"nullable=False), sa.Column(\"letters_sent\", sa.BigInteger(), nullable=False), sa.Column(\"letters_failed\", sa.BigInteger(), nullable=False), sa.Column(\"created_at\", sa.DateTime(), nullable=True),",
"Date: 2017-05-12 13:16:14.147368 \"\"\" # revision identifiers, used by Alembic.",
"\"\"\"empty message Revision ID: 0084_add_job_stats Revises: 0083_add_perm_types_and_svc_perm Create Date: 2017-05-12",
"nullable=False), sa.Column(\"job_id\", postgresql.UUID(as_uuid=True), nullable=False), sa.Column(\"emails_sent\", sa.BigInteger(), nullable=False), sa.Column(\"emails_delivered\", sa.BigInteger(), nullable=False),",
"Create Date: 2017-05-12 13:16:14.147368 \"\"\" # revision identifiers, used by",
"import postgresql def upgrade(): op.create_table( \"job_statistics\", sa.Column(\"id\", postgresql.UUID(as_uuid=True), nullable=False), sa.Column(\"job_id\",",
"def upgrade(): op.create_table( \"job_statistics\", sa.Column(\"id\", postgresql.UUID(as_uuid=True), nullable=False), sa.Column(\"job_id\", postgresql.UUID(as_uuid=True), nullable=False),",
"nullable=False), sa.Column(\"emails_delivered\", sa.BigInteger(), nullable=False), sa.Column(\"emails_failed\", sa.BigInteger(), nullable=False), sa.Column(\"sms_sent\", sa.BigInteger(), nullable=False),",
"sa.BigInteger(), nullable=False), sa.Column(\"letters_sent\", sa.BigInteger(), nullable=False), sa.Column(\"letters_failed\", sa.BigInteger(), nullable=False), sa.Column(\"created_at\", sa.DateTime(),",
"sa.Column(\"sms_sent\", sa.BigInteger(), nullable=False), sa.Column(\"sms_delivered\", sa.BigInteger(), nullable=False), sa.Column(\"sms_failed\", sa.BigInteger(), nullable=False), sa.Column(\"letters_sent\",",
"= \"0083_add_perm_types_and_svc_perm\" import sqlalchemy as sa from alembic import op",
"), sa.PrimaryKeyConstraint(\"id\"), ) op.create_index(op.f(\"ix_job_statistics_job_id\"), \"job_statistics\", [\"job_id\"], unique=True) def downgrade(): op.drop_index(op.f(\"ix_job_statistics_job_id\"),",
"nullable=False), sa.Column(\"sms_sent\", sa.BigInteger(), nullable=False), sa.Column(\"sms_delivered\", sa.BigInteger(), nullable=False), sa.Column(\"sms_failed\", sa.BigInteger(), nullable=False),",
"nullable=False), sa.Column(\"created_at\", sa.DateTime(), nullable=True), sa.Column(\"updated_at\", sa.DateTime(), nullable=True), sa.ForeignKeyConstraint( [\"job_id\"], [\"jobs.id\"],",
"sa.BigInteger(), nullable=False), sa.Column(\"emails_failed\", sa.BigInteger(), nullable=False), sa.Column(\"sms_sent\", sa.BigInteger(), nullable=False), sa.Column(\"sms_delivered\", sa.BigInteger(),",
"nullable=False), sa.Column(\"emails_failed\", sa.BigInteger(), nullable=False), sa.Column(\"sms_sent\", sa.BigInteger(), nullable=False), sa.Column(\"sms_delivered\", sa.BigInteger(), nullable=False),",
"sa.Column(\"emails_delivered\", sa.BigInteger(), nullable=False), sa.Column(\"emails_failed\", sa.BigInteger(), nullable=False), sa.Column(\"sms_sent\", sa.BigInteger(), nullable=False), sa.Column(\"sms_delivered\",",
"as sa from alembic import op from sqlalchemy.dialects import postgresql",
"sa.Column(\"emails_failed\", sa.BigInteger(), nullable=False), sa.Column(\"sms_sent\", sa.BigInteger(), nullable=False), sa.Column(\"sms_delivered\", sa.BigInteger(), nullable=False), sa.Column(\"sms_failed\",",
"sa.BigInteger(), nullable=False), sa.Column(\"created_at\", sa.DateTime(), nullable=True), sa.Column(\"updated_at\", sa.DateTime(), nullable=True), sa.ForeignKeyConstraint( [\"job_id\"],",
"postgresql.UUID(as_uuid=True), nullable=False), sa.Column(\"emails_sent\", sa.BigInteger(), nullable=False), sa.Column(\"emails_delivered\", sa.BigInteger(), nullable=False), sa.Column(\"emails_failed\", sa.BigInteger(),",
"nullable=False), sa.Column(\"emails_sent\", sa.BigInteger(), nullable=False), sa.Column(\"emails_delivered\", sa.BigInteger(), nullable=False), sa.Column(\"emails_failed\", sa.BigInteger(), nullable=False),",
"import sqlalchemy as sa from alembic import op from sqlalchemy.dialects",
"revision identifiers, used by Alembic. revision = \"0084_add_job_stats\" down_revision =",
"op.create_table( \"job_statistics\", sa.Column(\"id\", postgresql.UUID(as_uuid=True), nullable=False), sa.Column(\"job_id\", postgresql.UUID(as_uuid=True), nullable=False), sa.Column(\"emails_sent\", sa.BigInteger(),",
"sqlalchemy.dialects import postgresql def upgrade(): op.create_table( \"job_statistics\", sa.Column(\"id\", postgresql.UUID(as_uuid=True), nullable=False),",
"sa.Column(\"letters_failed\", sa.BigInteger(), nullable=False), sa.Column(\"created_at\", sa.DateTime(), nullable=True), sa.Column(\"updated_at\", sa.DateTime(), nullable=True), sa.ForeignKeyConstraint(",
"sa.Column(\"id\", postgresql.UUID(as_uuid=True), nullable=False), sa.Column(\"job_id\", postgresql.UUID(as_uuid=True), nullable=False), sa.Column(\"emails_sent\", sa.BigInteger(), nullable=False), sa.Column(\"emails_delivered\",",
"\"\"\" # revision identifiers, used by Alembic. revision = \"0084_add_job_stats\"",
"\"0083_add_perm_types_and_svc_perm\" import sqlalchemy as sa from alembic import op from",
"revision = \"0084_add_job_stats\" down_revision = \"0083_add_perm_types_and_svc_perm\" import sqlalchemy as sa",
"Alembic. revision = \"0084_add_job_stats\" down_revision = \"0083_add_perm_types_and_svc_perm\" import sqlalchemy as",
"sa.DateTime(), nullable=True), sa.Column(\"updated_at\", sa.DateTime(), nullable=True), sa.ForeignKeyConstraint( [\"job_id\"], [\"jobs.id\"], ), sa.PrimaryKeyConstraint(\"id\"),",
"sa.Column(\"job_id\", postgresql.UUID(as_uuid=True), nullable=False), sa.Column(\"emails_sent\", sa.BigInteger(), nullable=False), sa.Column(\"emails_delivered\", sa.BigInteger(), nullable=False), sa.Column(\"emails_failed\",",
"nullable=False), sa.Column(\"sms_failed\", sa.BigInteger(), nullable=False), sa.Column(\"letters_sent\", sa.BigInteger(), nullable=False), sa.Column(\"letters_failed\", sa.BigInteger(), nullable=False),",
"message Revision ID: 0084_add_job_stats Revises: 0083_add_perm_types_and_svc_perm Create Date: 2017-05-12 13:16:14.147368",
"by Alembic. revision = \"0084_add_job_stats\" down_revision = \"0083_add_perm_types_and_svc_perm\" import sqlalchemy",
"identifiers, used by Alembic. revision = \"0084_add_job_stats\" down_revision = \"0083_add_perm_types_and_svc_perm\"",
"[\"job_id\"], [\"jobs.id\"], ), sa.PrimaryKeyConstraint(\"id\"), ) op.create_index(op.f(\"ix_job_statistics_job_id\"), \"job_statistics\", [\"job_id\"], unique=True) def",
"sa.Column(\"created_at\", sa.DateTime(), nullable=True), sa.Column(\"updated_at\", sa.DateTime(), nullable=True), sa.ForeignKeyConstraint( [\"job_id\"], [\"jobs.id\"], ),",
"0083_add_perm_types_and_svc_perm Create Date: 2017-05-12 13:16:14.147368 \"\"\" # revision identifiers, used",
"Revision ID: 0084_add_job_stats Revises: 0083_add_perm_types_and_svc_perm Create Date: 2017-05-12 13:16:14.147368 \"\"\"",
"sa.BigInteger(), nullable=False), sa.Column(\"emails_delivered\", sa.BigInteger(), nullable=False), sa.Column(\"emails_failed\", sa.BigInteger(), nullable=False), sa.Column(\"sms_sent\", sa.BigInteger(),",
"sa.BigInteger(), nullable=False), sa.Column(\"sms_delivered\", sa.BigInteger(), nullable=False), sa.Column(\"sms_failed\", sa.BigInteger(), nullable=False), sa.Column(\"letters_sent\", sa.BigInteger(),",
"down_revision = \"0083_add_perm_types_and_svc_perm\" import sqlalchemy as sa from alembic import",
"nullable=False), sa.Column(\"sms_delivered\", sa.BigInteger(), nullable=False), sa.Column(\"sms_failed\", sa.BigInteger(), nullable=False), sa.Column(\"letters_sent\", sa.BigInteger(), nullable=False),",
"sa.Column(\"sms_delivered\", sa.BigInteger(), nullable=False), sa.Column(\"sms_failed\", sa.BigInteger(), nullable=False), sa.Column(\"letters_sent\", sa.BigInteger(), nullable=False), sa.Column(\"letters_failed\",",
"= \"0084_add_job_stats\" down_revision = \"0083_add_perm_types_and_svc_perm\" import sqlalchemy as sa from",
"postgresql.UUID(as_uuid=True), nullable=False), sa.Column(\"job_id\", postgresql.UUID(as_uuid=True), nullable=False), sa.Column(\"emails_sent\", sa.BigInteger(), nullable=False), sa.Column(\"emails_delivered\", sa.BigInteger(),",
") op.create_index(op.f(\"ix_job_statistics_job_id\"), \"job_statistics\", [\"job_id\"], unique=True) def downgrade(): op.drop_index(op.f(\"ix_job_statistics_job_id\"), table_name=\"job_statistics\") op.drop_table(\"job_statistics\")",
"ID: 0084_add_job_stats Revises: 0083_add_perm_types_and_svc_perm Create Date: 2017-05-12 13:16:14.147368 \"\"\" #",
"sa from alembic import op from sqlalchemy.dialects import postgresql def",
"op from sqlalchemy.dialects import postgresql def upgrade(): op.create_table( \"job_statistics\", sa.Column(\"id\",",
"# revision identifiers, used by Alembic. revision = \"0084_add_job_stats\" down_revision",
"2017-05-12 13:16:14.147368 \"\"\" # revision identifiers, used by Alembic. revision",
"nullable=True), sa.Column(\"updated_at\", sa.DateTime(), nullable=True), sa.ForeignKeyConstraint( [\"job_id\"], [\"jobs.id\"], ), sa.PrimaryKeyConstraint(\"id\"), )",
"from alembic import op from sqlalchemy.dialects import postgresql def upgrade():",
"\"0084_add_job_stats\" down_revision = \"0083_add_perm_types_and_svc_perm\" import sqlalchemy as sa from alembic",
"used by Alembic. revision = \"0084_add_job_stats\" down_revision = \"0083_add_perm_types_and_svc_perm\" import",
"sa.Column(\"emails_sent\", sa.BigInteger(), nullable=False), sa.Column(\"emails_delivered\", sa.BigInteger(), nullable=False), sa.Column(\"emails_failed\", sa.BigInteger(), nullable=False), sa.Column(\"sms_sent\",",
"postgresql def upgrade(): op.create_table( \"job_statistics\", sa.Column(\"id\", postgresql.UUID(as_uuid=True), nullable=False), sa.Column(\"job_id\", postgresql.UUID(as_uuid=True),",
"from sqlalchemy.dialects import postgresql def upgrade(): op.create_table( \"job_statistics\", sa.Column(\"id\", postgresql.UUID(as_uuid=True),",
"13:16:14.147368 \"\"\" # revision identifiers, used by Alembic. revision =",
"sa.BigInteger(), nullable=False), sa.Column(\"sms_failed\", sa.BigInteger(), nullable=False), sa.Column(\"letters_sent\", sa.BigInteger(), nullable=False), sa.Column(\"letters_failed\", sa.BigInteger(),",
"upgrade(): op.create_table( \"job_statistics\", sa.Column(\"id\", postgresql.UUID(as_uuid=True), nullable=False), sa.Column(\"job_id\", postgresql.UUID(as_uuid=True), nullable=False), sa.Column(\"emails_sent\",",
"\"job_statistics\", sa.Column(\"id\", postgresql.UUID(as_uuid=True), nullable=False), sa.Column(\"job_id\", postgresql.UUID(as_uuid=True), nullable=False), sa.Column(\"emails_sent\", sa.BigInteger(), nullable=False),",
"import op from sqlalchemy.dialects import postgresql def upgrade(): op.create_table( \"job_statistics\","
] |
[
"def test_remove_from_confirmed_user(self): # drift defaults to 0. Change it so",
"self.user_settings.totp_drift = 1 self.user_settings.save() self.user.delete_addon('twofactor') self.user_settings.reload() assert_equal(self.user_settings.totp_drift, 0) assert_is_none(self.user_settings.totp_secret) assert_false(self.user_settings.is_confirmed)",
"TOTP_SECRET = 'b8f85986068f8079aa9d' TOTP_SECRET_B32 = 'XD4FTBQGR6AHTKU5' def setUp(self): super(TestUserSettingsModel, self).setUp()",
"self).tearDown() self.user.__class__.delete(self.user) def test_b32(self): assert_equal(self.user_settings.totp_secret_b32, self.TOTP_SECRET_B32) def test_otpauth_url(self): url =",
"test_json(self): # url = 'otpauth://totp/RDM:{}?secret=' + self.TOTP_SECRET_B32 settings = self.user_settings.to_json(user=None)",
"tearDown(self): super(TestUserSettingsModel, self).tearDown() self.user.__class__.delete(self.user) def test_b32(self): assert_equal(self.user_settings.totp_secret_b32, self.TOTP_SECRET_B32) def test_otpauth_url(self):",
"self.user.delete_addon('twofactor') self.user_settings.reload() assert_equal(self.user_settings.totp_drift, 0) assert_is_none(self.user_settings.totp_secret) assert_false(self.user_settings.is_confirmed) def test_remove_from_confirmed_user(self): # drift",
"addons.twofactor.tests.utils import _valid_code from nose.tools import (assert_equal, assert_false, assert_is_none, assert_is_not_none,",
"assert_equal(self.user_settings.totp_drift, 2) # use the current code (which is now",
"# drift defaults to 0. Change it so we can",
"self.user_settings.reload() assert_equal(self.user_settings.totp_drift, 0) assert_is_none(self.user_settings.totp_secret) assert_false(self.user_settings.is_confirmed) def test_remove_from_confirmed_user(self): # drift defaults",
"was changed back. self.user_settings.totp_drift = 1 self.user_settings.is_confirmed = True self.user_settings.save()",
"is updated. assert_equal(self.user_settings.totp_drift, 2) # use the current code (which",
"= 1 self.user_settings.save() self.user.delete_addon('twofactor') self.user_settings.reload() assert_equal(self.user_settings.totp_drift, 0) assert_is_none(self.user_settings.totp_secret) assert_false(self.user_settings.is_confirmed) def",
"changed back. self.user_settings.totp_drift = 1 self.user_settings.is_confirmed = True self.user_settings.save() self.user.delete_addon('twofactor')",
"use the current code (which is now 2 periods away",
") ) # make sure drift is updated. assert_equal(self.user_settings.totp_drift, 1)",
"UserFactory() self.user.add_addon('twofactor') self.user_settings = self.user.get_addon('twofactor') def test_add_to_user(self): assert_equal(self.user_settings.totp_drift, 0) assert_is_not_none(self.user_settings.totp_secret)",
") def test_json(self): # url = 'otpauth://totp/RDM:{}?secret=' + self.TOTP_SECRET_B32 settings",
"self.user_settings.save() self.user.delete_addon('twofactor') self.user_settings.reload() assert_equal(self.user_settings.totp_drift, 0) assert_is_none(self.user_settings.totp_secret) assert_false(self.user_settings.is_confirmed) class TestUserSettingsModel(unittest.TestCase): TOTP_SECRET",
"= 'XD4FTBQGR6AHTKU5' def setUp(self): super(TestUserSettingsModel, self).setUp() self.user = UserFactory() self.user.add_addon('twofactor')",
"test it was changed back. self.user_settings.totp_drift = 1 self.user_settings.save() self.user.delete_addon('twofactor')",
"assert_equal( settings, { 'is_enabled': True, 'addon_full_name': 'Two-factor Authentication', 'addon_short_name': 'twofactor',",
"from 60 seconds in the future assert_true( self.user_settings.verify_code( _valid_code(self.TOTP_SECRET, drift=2)",
"test_verify_valid_code(self): assert_true( self.user_settings.verify_code(_valid_code(self.TOTP_SECRET)) ) def test_verify_valid_core_drift(self): # use a code",
"test_add_to_user(self): assert_equal(self.user_settings.totp_drift, 0) assert_is_not_none(self.user_settings.totp_secret) assert_false(self.user_settings.is_confirmed) def test_remove_from_unconfirmed_user(self): # drift defaults",
"assert_equal(url.netloc, 'totp') assert_equal(url.path, '/RDM:{}'.format(self.user.username)) assert_equal( parse_qs(url.query), {'secret': [self.TOTP_SECRET_B32]} ) def",
"= urlparse(self.user_settings.otpauth_url) assert_equal(url.scheme, 'otpauth') assert_equal(url.netloc, 'totp') assert_equal(url.path, '/RDM:{}'.format(self.user.username)) assert_equal( parse_qs(url.query),",
"= self.user.get_addon('twofactor') self.user_settings.totp_secret = self.TOTP_SECRET self.user_settings.save() def tearDown(self): super(TestUserSettingsModel, self).tearDown()",
"[], 'secret': self.TOTP_SECRET_B32, 'has_auth': False, } ) def test_verify_valid_code(self): assert_true(",
"we can test it was changed back. self.user_settings.totp_drift = 1",
"assert_equal(self.user_settings.totp_drift, 1) # use a code from 60 seconds in",
"class TestUserSettingsModel(unittest.TestCase): TOTP_SECRET = 'b8f85986068f8079aa9d' TOTP_SECRET_B32 = 'XD4FTBQGR6AHTKU5' def setUp(self):",
"the current code (which is now 2 periods away from",
"0) assert_is_none(self.user_settings.totp_secret) assert_false(self.user_settings.is_confirmed) def test_remove_from_confirmed_user(self): # drift defaults to 0.",
"assert_true) from osf_tests.factories import UserFactory pytestmark = pytest.mark.django_db class TestCallbacks(unittest.TestCase):",
") # make sure drift is updated. assert_equal(self.user_settings.totp_drift, 1) #",
"1 self.user_settings.is_confirmed = True self.user_settings.save() self.user.delete_addon('twofactor') self.user_settings.reload() assert_equal(self.user_settings.totp_drift, 0) assert_is_none(self.user_settings.totp_secret)",
"{ 'is_enabled': True, 'addon_full_name': 'Two-factor Authentication', 'addon_short_name': 'twofactor', 'drift': 0,",
"super(TestUserSettingsModel, self).tearDown() self.user.__class__.delete(self.user) def test_b32(self): assert_equal(self.user_settings.totp_secret_b32, self.TOTP_SECRET_B32) def test_otpauth_url(self): url",
"0) assert_is_not_none(self.user_settings.totp_secret) assert_false(self.user_settings.is_confirmed) def test_remove_from_unconfirmed_user(self): # drift defaults to 0.",
"= 1 self.user_settings.is_confirmed = True self.user_settings.save() self.user.delete_addon('twofactor') self.user_settings.reload() assert_equal(self.user_settings.totp_drift, 0)",
"super(TestUserSettingsModel, self).setUp() self.user = UserFactory() self.user.add_addon('twofactor') self.user_settings = self.user.get_addon('twofactor') self.user_settings.totp_secret",
"_valid_code(self.TOTP_SECRET, drift=2) ) ) # make sure drift is updated.",
"make sure drift is updated. assert_equal(self.user_settings.totp_drift, 1) # use a",
"'has_auth': False, } ) def test_verify_valid_code(self): assert_true( self.user_settings.verify_code(_valid_code(self.TOTP_SECRET)) ) def",
"from future.moves.urllib.parse import urlparse, urljoin, parse_qs import pytest from addons.twofactor.tests.utils",
"TestUserSettingsModel(unittest.TestCase): TOTP_SECRET = 'b8f85986068f8079aa9d' TOTP_SECRET_B32 = 'XD4FTBQGR6AHTKU5' def setUp(self): super(TestUserSettingsModel,",
"code from 30 seconds in the future assert_true( self.user_settings.verify_code( _valid_code(self.TOTP_SECRET,",
"assert_false(self.user_settings.is_confirmed) def test_remove_from_confirmed_user(self): # drift defaults to 0. Change it",
"def test_verify_valid_code(self): assert_true( self.user_settings.verify_code(_valid_code(self.TOTP_SECRET)) ) def test_verify_valid_core_drift(self): # use a",
"self.user_settings.is_confirmed = True self.user_settings.save() self.user.delete_addon('twofactor') self.user_settings.reload() assert_equal(self.user_settings.totp_drift, 0) assert_is_none(self.user_settings.totp_secret) assert_false(self.user_settings.is_confirmed)",
"self.user_settings.reload() assert_equal(self.user_settings.totp_drift, 0) assert_is_none(self.user_settings.totp_secret) assert_false(self.user_settings.is_confirmed) class TestUserSettingsModel(unittest.TestCase): TOTP_SECRET = 'b8f85986068f8079aa9d'",
"self.TOTP_SECRET_B32) def test_otpauth_url(self): url = urlparse(self.user_settings.otpauth_url) assert_equal(url.scheme, 'otpauth') assert_equal(url.netloc, 'totp')",
"self.user.get_addon('twofactor') self.user_settings.totp_secret = self.TOTP_SECRET self.user_settings.save() def tearDown(self): super(TestUserSettingsModel, self).tearDown() self.user.__class__.delete(self.user)",
"'Two-factor Authentication', 'addon_short_name': 'twofactor', 'drift': 0, 'is_confirmed': False, 'nodes': [],",
"drift is updated. assert_equal(self.user_settings.totp_drift, 1) # use a code from",
"'otpauth') assert_equal(url.netloc, 'totp') assert_equal(url.path, '/RDM:{}'.format(self.user.username)) assert_equal( parse_qs(url.query), {'secret': [self.TOTP_SECRET_B32]} )",
"url = urlparse(self.user_settings.otpauth_url) assert_equal(url.scheme, 'otpauth') assert_equal(url.netloc, 'totp') assert_equal(url.path, '/RDM:{}'.format(self.user.username)) assert_equal(",
"False, 'nodes': [], 'secret': self.TOTP_SECRET_B32, 'has_auth': False, } ) def",
"can test it was changed back. self.user_settings.totp_drift = 1 self.user_settings.save()",
"urlparse(self.user_settings.otpauth_url) assert_equal(url.scheme, 'otpauth') assert_equal(url.netloc, 'totp') assert_equal(url.path, '/RDM:{}'.format(self.user.username)) assert_equal( parse_qs(url.query), {'secret':",
"'is_confirmed': False, 'nodes': [], 'secret': self.TOTP_SECRET_B32, 'has_auth': False, } )",
"code (which is now 2 periods away from the drift)",
"self.user_settings = self.user.get_addon('twofactor') def test_add_to_user(self): assert_equal(self.user_settings.totp_drift, 0) assert_is_not_none(self.user_settings.totp_secret) assert_false(self.user_settings.is_confirmed) def",
"import UserFactory pytestmark = pytest.mark.django_db class TestCallbacks(unittest.TestCase): def setUp(self): super(TestCallbacks,",
"assert_is_not_none(self.user_settings.totp_secret) assert_false(self.user_settings.is_confirmed) def test_remove_from_unconfirmed_user(self): # drift defaults to 0. Change",
"= UserFactory() self.user.add_addon('twofactor') self.user_settings = self.user.get_addon('twofactor') self.user_settings.totp_secret = self.TOTP_SECRET self.user_settings.save()",
"use a code from 30 seconds in the future assert_true(",
"changed back. self.user_settings.totp_drift = 1 self.user_settings.save() self.user.delete_addon('twofactor') self.user_settings.reload() assert_equal(self.user_settings.totp_drift, 0)",
"'addon_full_name': 'Two-factor Authentication', 'addon_short_name': 'twofactor', 'drift': 0, 'is_confirmed': False, 'nodes':",
"pytestmark = pytest.mark.django_db class TestCallbacks(unittest.TestCase): def setUp(self): super(TestCallbacks, self).setUp() self.user",
"assert_is_none(self.user_settings.totp_secret) assert_false(self.user_settings.is_confirmed) class TestUserSettingsModel(unittest.TestCase): TOTP_SECRET = 'b8f85986068f8079aa9d' TOTP_SECRET_B32 = 'XD4FTBQGR6AHTKU5'",
"assert_true( self.user_settings.verify_code(_valid_code(self.TOTP_SECRET)) ) def test_verify_valid_core_drift(self): # use a code from",
"self.user_settings.save() def tearDown(self): super(TestUserSettingsModel, self).tearDown() self.user.__class__.delete(self.user) def test_b32(self): assert_equal(self.user_settings.totp_secret_b32, self.TOTP_SECRET_B32)",
"30 seconds in the future assert_true( self.user_settings.verify_code( _valid_code(self.TOTP_SECRET, drift=1) )",
"self.user = UserFactory() self.user.add_addon('twofactor') self.user_settings = self.user.get_addon('twofactor') def test_add_to_user(self): assert_equal(self.user_settings.totp_drift,",
"def tearDown(self): super(TestUserSettingsModel, self).tearDown() self.user.__class__.delete(self.user) def test_b32(self): assert_equal(self.user_settings.totp_secret_b32, self.TOTP_SECRET_B32) def",
"it was changed back. self.user_settings.totp_drift = 1 self.user_settings.save() self.user.delete_addon('twofactor') self.user_settings.reload()",
"= 'b8f85986068f8079aa9d' TOTP_SECRET_B32 = 'XD4FTBQGR6AHTKU5' def setUp(self): super(TestUserSettingsModel, self).setUp() self.user",
"updated. assert_equal(self.user_settings.totp_drift, 2) # use the current code (which is",
"# use a code from 60 seconds in the future",
"'drift': 0, 'is_confirmed': False, 'nodes': [], 'secret': self.TOTP_SECRET_B32, 'has_auth': False,",
"super(TestCallbacks, self).setUp() self.user = UserFactory() self.user.add_addon('twofactor') self.user_settings = self.user.get_addon('twofactor') def",
"def setUp(self): super(TestUserSettingsModel, self).setUp() self.user = UserFactory() self.user.add_addon('twofactor') self.user_settings =",
"in the future assert_true( self.user_settings.verify_code( _valid_code(self.TOTP_SECRET, drift=2) ) ) #",
"was changed back. self.user_settings.totp_drift = 1 self.user_settings.save() self.user.delete_addon('twofactor') self.user_settings.reload() assert_equal(self.user_settings.totp_drift,",
"assert_equal(self.user_settings.totp_drift, 0) assert_is_none(self.user_settings.totp_secret) assert_false(self.user_settings.is_confirmed) def test_remove_from_confirmed_user(self): # drift defaults to",
"urljoin, parse_qs import pytest from addons.twofactor.tests.utils import _valid_code from nose.tools",
"= self.TOTP_SECRET self.user_settings.save() def tearDown(self): super(TestUserSettingsModel, self).tearDown() self.user.__class__.delete(self.user) def test_b32(self):",
"Change it so we can test it was changed back.",
"test_b32(self): assert_equal(self.user_settings.totp_secret_b32, self.TOTP_SECRET_B32) def test_otpauth_url(self): url = urlparse(self.user_settings.otpauth_url) assert_equal(url.scheme, 'otpauth')",
"test_verify_valid_core_drift(self): # use a code from 30 seconds in the",
"the future assert_true( self.user_settings.verify_code( _valid_code(self.TOTP_SECRET, drift=1) ) ) # make",
"# make sure drift is updated. assert_equal(self.user_settings.totp_drift, 1) # use",
") # make sure drift is updated. assert_equal(self.user_settings.totp_drift, 2) #",
"assert_false(self.user_settings.is_confirmed) class TestUserSettingsModel(unittest.TestCase): TOTP_SECRET = 'b8f85986068f8079aa9d' TOTP_SECRET_B32 = 'XD4FTBQGR6AHTKU5' def",
"import (assert_equal, assert_false, assert_is_none, assert_is_not_none, assert_true) from osf_tests.factories import UserFactory",
"url = 'otpauth://totp/RDM:{}?secret=' + self.TOTP_SECRET_B32 settings = self.user_settings.to_json(user=None) assert_equal( settings,",
"now 2 periods away from the drift) assert_false( self.user_settings.verify_code(_valid_code(self.TOTP_SECRET)) )",
"= True self.user_settings.save() self.user.delete_addon('twofactor') self.user_settings.reload() assert_equal(self.user_settings.totp_drift, 0) assert_is_none(self.user_settings.totp_secret) assert_false(self.user_settings.is_confirmed) class",
"self.user.__class__.delete(self.user) def test_b32(self): assert_equal(self.user_settings.totp_secret_b32, self.TOTP_SECRET_B32) def test_otpauth_url(self): url = urlparse(self.user_settings.otpauth_url)",
"TestCallbacks(unittest.TestCase): def setUp(self): super(TestCallbacks, self).setUp() self.user = UserFactory() self.user.add_addon('twofactor') self.user_settings",
"it was changed back. self.user_settings.totp_drift = 1 self.user_settings.is_confirmed = True",
"self.user.add_addon('twofactor') self.user_settings = self.user.get_addon('twofactor') def test_add_to_user(self): assert_equal(self.user_settings.totp_drift, 0) assert_is_not_none(self.user_settings.totp_secret) assert_false(self.user_settings.is_confirmed)",
"self.user = UserFactory() self.user.add_addon('twofactor') self.user_settings = self.user.get_addon('twofactor') self.user_settings.totp_secret = self.TOTP_SECRET",
"from nose.tools import (assert_equal, assert_false, assert_is_none, assert_is_not_none, assert_true) from osf_tests.factories",
"def setUp(self): super(TestCallbacks, self).setUp() self.user = UserFactory() self.user.add_addon('twofactor') self.user_settings =",
"a code from 60 seconds in the future assert_true( self.user_settings.verify_code(",
"'twofactor', 'drift': 0, 'is_confirmed': False, 'nodes': [], 'secret': self.TOTP_SECRET_B32, 'has_auth':",
"1 self.user_settings.save() self.user.delete_addon('twofactor') self.user_settings.reload() assert_equal(self.user_settings.totp_drift, 0) assert_is_none(self.user_settings.totp_secret) assert_false(self.user_settings.is_confirmed) def test_remove_from_confirmed_user(self):",
"setUp(self): super(TestUserSettingsModel, self).setUp() self.user = UserFactory() self.user.add_addon('twofactor') self.user_settings = self.user.get_addon('twofactor')",
"is updated. assert_equal(self.user_settings.totp_drift, 1) # use a code from 60",
"(assert_equal, assert_false, assert_is_none, assert_is_not_none, assert_true) from osf_tests.factories import UserFactory pytestmark",
"import pytest from addons.twofactor.tests.utils import _valid_code from nose.tools import (assert_equal,",
"def test_json(self): # url = 'otpauth://totp/RDM:{}?secret=' + self.TOTP_SECRET_B32 settings =",
"assert_is_not_none, assert_true) from osf_tests.factories import UserFactory pytestmark = pytest.mark.django_db class",
"drift=2) ) ) # make sure drift is updated. assert_equal(self.user_settings.totp_drift,",
"to 0. Change it so we can test it was",
"defaults to 0. Change it so we can test it",
"pytest.mark.django_db class TestCallbacks(unittest.TestCase): def setUp(self): super(TestCallbacks, self).setUp() self.user = UserFactory()",
"TOTP_SECRET_B32 = 'XD4FTBQGR6AHTKU5' def setUp(self): super(TestUserSettingsModel, self).setUp() self.user = UserFactory()",
"60 seconds in the future assert_true( self.user_settings.verify_code( _valid_code(self.TOTP_SECRET, drift=2) )",
"assert_true( self.user_settings.verify_code( _valid_code(self.TOTP_SECRET, drift=1) ) ) # make sure drift",
"'b8f85986068f8079aa9d' TOTP_SECRET_B32 = 'XD4FTBQGR6AHTKU5' def setUp(self): super(TestUserSettingsModel, self).setUp() self.user =",
"= self.user_settings.to_json(user=None) assert_equal( settings, { 'is_enabled': True, 'addon_full_name': 'Two-factor Authentication',",
"test it was changed back. self.user_settings.totp_drift = 1 self.user_settings.is_confirmed =",
"seconds in the future assert_true( self.user_settings.verify_code( _valid_code(self.TOTP_SECRET, drift=1) ) )",
"code from 60 seconds in the future assert_true( self.user_settings.verify_code( _valid_code(self.TOTP_SECRET,",
"assert_equal(self.user_settings.totp_drift, 0) assert_is_none(self.user_settings.totp_secret) assert_false(self.user_settings.is_confirmed) class TestUserSettingsModel(unittest.TestCase): TOTP_SECRET = 'b8f85986068f8079aa9d' TOTP_SECRET_B32",
"self).setUp() self.user = UserFactory() self.user.add_addon('twofactor') self.user_settings = self.user.get_addon('twofactor') self.user_settings.totp_secret =",
"def test_remove_from_unconfirmed_user(self): # drift defaults to 0. Change it so",
"back. self.user_settings.totp_drift = 1 self.user_settings.is_confirmed = True self.user_settings.save() self.user.delete_addon('twofactor') self.user_settings.reload()",
"assert_equal(url.scheme, 'otpauth') assert_equal(url.netloc, 'totp') assert_equal(url.path, '/RDM:{}'.format(self.user.username)) assert_equal( parse_qs(url.query), {'secret': [self.TOTP_SECRET_B32]}",
"+ self.TOTP_SECRET_B32 settings = self.user_settings.to_json(user=None) assert_equal( settings, { 'is_enabled': True,",
"'nodes': [], 'secret': self.TOTP_SECRET_B32, 'has_auth': False, } ) def test_verify_valid_code(self):",
"drift=1) ) ) # make sure drift is updated. assert_equal(self.user_settings.totp_drift,",
"nose.tools import (assert_equal, assert_false, assert_is_none, assert_is_not_none, assert_true) from osf_tests.factories import",
"test_otpauth_url(self): url = urlparse(self.user_settings.otpauth_url) assert_equal(url.scheme, 'otpauth') assert_equal(url.netloc, 'totp') assert_equal(url.path, '/RDM:{}'.format(self.user.username))",
"parse_qs(url.query), {'secret': [self.TOTP_SECRET_B32]} ) def test_json(self): # url = 'otpauth://totp/RDM:{}?secret='",
"assert_true( self.user_settings.verify_code( _valid_code(self.TOTP_SECRET, drift=2) ) ) # make sure drift",
") def test_verify_valid_core_drift(self): # use a code from 30 seconds",
"import unittest from future.moves.urllib.parse import urlparse, urljoin, parse_qs import pytest",
"updated. assert_equal(self.user_settings.totp_drift, 1) # use a code from 60 seconds",
"test_remove_from_unconfirmed_user(self): # drift defaults to 0. Change it so we",
"[self.TOTP_SECRET_B32]} ) def test_json(self): # url = 'otpauth://totp/RDM:{}?secret=' + self.TOTP_SECRET_B32",
"from osf_tests.factories import UserFactory pytestmark = pytest.mark.django_db class TestCallbacks(unittest.TestCase): def",
"setUp(self): super(TestCallbacks, self).setUp() self.user = UserFactory() self.user.add_addon('twofactor') self.user_settings = self.user.get_addon('twofactor')",
"so we can test it was changed back. self.user_settings.totp_drift =",
"self.TOTP_SECRET self.user_settings.save() def tearDown(self): super(TestUserSettingsModel, self).tearDown() self.user.__class__.delete(self.user) def test_b32(self): assert_equal(self.user_settings.totp_secret_b32,",
"0, 'is_confirmed': False, 'nodes': [], 'secret': self.TOTP_SECRET_B32, 'has_auth': False, }",
"parse_qs import pytest from addons.twofactor.tests.utils import _valid_code from nose.tools import",
"UserFactory() self.user.add_addon('twofactor') self.user_settings = self.user.get_addon('twofactor') self.user_settings.totp_secret = self.TOTP_SECRET self.user_settings.save() def",
"drift is updated. assert_equal(self.user_settings.totp_drift, 2) # use the current code",
"urlparse, urljoin, parse_qs import pytest from addons.twofactor.tests.utils import _valid_code from",
"assert_equal(self.user_settings.totp_drift, 0) assert_is_not_none(self.user_settings.totp_secret) assert_false(self.user_settings.is_confirmed) def test_remove_from_unconfirmed_user(self): # drift defaults to",
"test_remove_from_confirmed_user(self): # drift defaults to 0. Change it so we",
"def test_add_to_user(self): assert_equal(self.user_settings.totp_drift, 0) assert_is_not_none(self.user_settings.totp_secret) assert_false(self.user_settings.is_confirmed) def test_remove_from_unconfirmed_user(self): # drift",
"2) # use the current code (which is now 2",
"'is_enabled': True, 'addon_full_name': 'Two-factor Authentication', 'addon_short_name': 'twofactor', 'drift': 0, 'is_confirmed':",
"self.user_settings.verify_code( _valid_code(self.TOTP_SECRET, drift=2) ) ) # make sure drift is",
"} ) def test_verify_valid_code(self): assert_true( self.user_settings.verify_code(_valid_code(self.TOTP_SECRET)) ) def test_verify_valid_core_drift(self): #",
"1) # use a code from 60 seconds in the",
"'secret': self.TOTP_SECRET_B32, 'has_auth': False, } ) def test_verify_valid_code(self): assert_true( self.user_settings.verify_code(_valid_code(self.TOTP_SECRET))",
"UserFactory pytestmark = pytest.mark.django_db class TestCallbacks(unittest.TestCase): def setUp(self): super(TestCallbacks, self).setUp()",
"# use a code from 30 seconds in the future",
"assert_false, assert_is_none, assert_is_not_none, assert_true) from osf_tests.factories import UserFactory pytestmark =",
"self.user.add_addon('twofactor') self.user_settings = self.user.get_addon('twofactor') self.user_settings.totp_secret = self.TOTP_SECRET self.user_settings.save() def tearDown(self):",
"assert_equal(self.user_settings.totp_secret_b32, self.TOTP_SECRET_B32) def test_otpauth_url(self): url = urlparse(self.user_settings.otpauth_url) assert_equal(url.scheme, 'otpauth') assert_equal(url.netloc,",
"False, } ) def test_verify_valid_code(self): assert_true( self.user_settings.verify_code(_valid_code(self.TOTP_SECRET)) ) def test_verify_valid_core_drift(self):",
"make sure drift is updated. assert_equal(self.user_settings.totp_drift, 2) # use the",
"from 30 seconds in the future assert_true( self.user_settings.verify_code( _valid_code(self.TOTP_SECRET, drift=1)",
"= self.user.get_addon('twofactor') def test_add_to_user(self): assert_equal(self.user_settings.totp_drift, 0) assert_is_not_none(self.user_settings.totp_secret) assert_false(self.user_settings.is_confirmed) def test_remove_from_unconfirmed_user(self):",
"self.user_settings.save() self.user.delete_addon('twofactor') self.user_settings.reload() assert_equal(self.user_settings.totp_drift, 0) assert_is_none(self.user_settings.totp_secret) assert_false(self.user_settings.is_confirmed) def test_remove_from_confirmed_user(self): #",
"osf_tests.factories import UserFactory pytestmark = pytest.mark.django_db class TestCallbacks(unittest.TestCase): def setUp(self):",
"0. Change it so we can test it was changed",
"can test it was changed back. self.user_settings.totp_drift = 1 self.user_settings.is_confirmed",
"0) assert_is_none(self.user_settings.totp_secret) assert_false(self.user_settings.is_confirmed) class TestUserSettingsModel(unittest.TestCase): TOTP_SECRET = 'b8f85986068f8079aa9d' TOTP_SECRET_B32 =",
"settings = self.user_settings.to_json(user=None) assert_equal( settings, { 'is_enabled': True, 'addon_full_name': 'Two-factor",
"sure drift is updated. assert_equal(self.user_settings.totp_drift, 1) # use a code",
") ) # make sure drift is updated. assert_equal(self.user_settings.totp_drift, 2)",
"'XD4FTBQGR6AHTKU5' def setUp(self): super(TestUserSettingsModel, self).setUp() self.user = UserFactory() self.user.add_addon('twofactor') self.user_settings",
"self.TOTP_SECRET_B32 settings = self.user_settings.to_json(user=None) assert_equal( settings, { 'is_enabled': True, 'addon_full_name':",
"Authentication', 'addon_short_name': 'twofactor', 'drift': 0, 'is_confirmed': False, 'nodes': [], 'secret':",
"seconds in the future assert_true( self.user_settings.verify_code( _valid_code(self.TOTP_SECRET, drift=2) ) )",
"<reponame>tsukaeru/RDM-osf.io import unittest from future.moves.urllib.parse import urlparse, urljoin, parse_qs import",
"import urlparse, urljoin, parse_qs import pytest from addons.twofactor.tests.utils import _valid_code",
"in the future assert_true( self.user_settings.verify_code( _valid_code(self.TOTP_SECRET, drift=1) ) ) #",
"from addons.twofactor.tests.utils import _valid_code from nose.tools import (assert_equal, assert_false, assert_is_none,",
"settings, { 'is_enabled': True, 'addon_full_name': 'Two-factor Authentication', 'addon_short_name': 'twofactor', 'drift':",
"(which is now 2 periods away from the drift) assert_false(",
"sure drift is updated. assert_equal(self.user_settings.totp_drift, 2) # use the current",
"self.user_settings.verify_code( _valid_code(self.TOTP_SECRET, drift=1) ) ) # make sure drift is",
"use a code from 60 seconds in the future assert_true(",
"assert_false(self.user_settings.is_confirmed) def test_remove_from_unconfirmed_user(self): # drift defaults to 0. Change it",
"= UserFactory() self.user.add_addon('twofactor') self.user_settings = self.user.get_addon('twofactor') def test_add_to_user(self): assert_equal(self.user_settings.totp_drift, 0)",
"self.TOTP_SECRET_B32, 'has_auth': False, } ) def test_verify_valid_code(self): assert_true( self.user_settings.verify_code(_valid_code(self.TOTP_SECRET)) )",
"it so we can test it was changed back. self.user_settings.totp_drift",
"True, 'addon_full_name': 'Two-factor Authentication', 'addon_short_name': 'twofactor', 'drift': 0, 'is_confirmed': False,",
"self.user_settings.totp_secret = self.TOTP_SECRET self.user_settings.save() def tearDown(self): super(TestUserSettingsModel, self).tearDown() self.user.__class__.delete(self.user) def",
"back. self.user_settings.totp_drift = 1 self.user_settings.save() self.user.delete_addon('twofactor') self.user_settings.reload() assert_equal(self.user_settings.totp_drift, 0) assert_is_none(self.user_settings.totp_secret)",
"self.user_settings.verify_code(_valid_code(self.TOTP_SECRET)) ) def test_verify_valid_core_drift(self): # use a code from 30",
"self.user_settings.to_json(user=None) assert_equal( settings, { 'is_enabled': True, 'addon_full_name': 'Two-factor Authentication', 'addon_short_name':",
"def test_verify_valid_core_drift(self): # use a code from 30 seconds in",
"# make sure drift is updated. assert_equal(self.user_settings.totp_drift, 2) # use",
"# use the current code (which is now 2 periods",
"current code (which is now 2 periods away from the",
"def test_b32(self): assert_equal(self.user_settings.totp_secret_b32, self.TOTP_SECRET_B32) def test_otpauth_url(self): url = urlparse(self.user_settings.otpauth_url) assert_equal(url.scheme,",
"self).setUp() self.user = UserFactory() self.user.add_addon('twofactor') self.user_settings = self.user.get_addon('twofactor') def test_add_to_user(self):",
"'addon_short_name': 'twofactor', 'drift': 0, 'is_confirmed': False, 'nodes': [], 'secret': self.TOTP_SECRET_B32,",
"assert_equal( parse_qs(url.query), {'secret': [self.TOTP_SECRET_B32]} ) def test_json(self): # url =",
"= 'otpauth://totp/RDM:{}?secret=' + self.TOTP_SECRET_B32 settings = self.user_settings.to_json(user=None) assert_equal( settings, {",
"unittest from future.moves.urllib.parse import urlparse, urljoin, parse_qs import pytest from",
"def test_otpauth_url(self): url = urlparse(self.user_settings.otpauth_url) assert_equal(url.scheme, 'otpauth') assert_equal(url.netloc, 'totp') assert_equal(url.path,",
"pytest from addons.twofactor.tests.utils import _valid_code from nose.tools import (assert_equal, assert_false,",
"self.user.delete_addon('twofactor') self.user_settings.reload() assert_equal(self.user_settings.totp_drift, 0) assert_is_none(self.user_settings.totp_secret) assert_false(self.user_settings.is_confirmed) class TestUserSettingsModel(unittest.TestCase): TOTP_SECRET =",
"self.user.get_addon('twofactor') def test_add_to_user(self): assert_equal(self.user_settings.totp_drift, 0) assert_is_not_none(self.user_settings.totp_secret) assert_false(self.user_settings.is_confirmed) def test_remove_from_unconfirmed_user(self): #",
"'otpauth://totp/RDM:{}?secret=' + self.TOTP_SECRET_B32 settings = self.user_settings.to_json(user=None) assert_equal( settings, { 'is_enabled':",
"import _valid_code from nose.tools import (assert_equal, assert_false, assert_is_none, assert_is_not_none, assert_true)",
"self.user_settings = self.user.get_addon('twofactor') self.user_settings.totp_secret = self.TOTP_SECRET self.user_settings.save() def tearDown(self): super(TestUserSettingsModel,",
"# url = 'otpauth://totp/RDM:{}?secret=' + self.TOTP_SECRET_B32 settings = self.user_settings.to_json(user=None) assert_equal(",
"'totp') assert_equal(url.path, '/RDM:{}'.format(self.user.username)) assert_equal( parse_qs(url.query), {'secret': [self.TOTP_SECRET_B32]} ) def test_json(self):",
"self.user_settings.totp_drift = 1 self.user_settings.is_confirmed = True self.user_settings.save() self.user.delete_addon('twofactor') self.user_settings.reload() assert_equal(self.user_settings.totp_drift,",
"class TestCallbacks(unittest.TestCase): def setUp(self): super(TestCallbacks, self).setUp() self.user = UserFactory() self.user.add_addon('twofactor')",
"True self.user_settings.save() self.user.delete_addon('twofactor') self.user_settings.reload() assert_equal(self.user_settings.totp_drift, 0) assert_is_none(self.user_settings.totp_secret) assert_false(self.user_settings.is_confirmed) class TestUserSettingsModel(unittest.TestCase):",
"is now 2 periods away from the drift) assert_false( self.user_settings.verify_code(_valid_code(self.TOTP_SECRET))",
"the future assert_true( self.user_settings.verify_code( _valid_code(self.TOTP_SECRET, drift=2) ) ) # make",
"_valid_code from nose.tools import (assert_equal, assert_false, assert_is_none, assert_is_not_none, assert_true) from",
"assert_is_none, assert_is_not_none, assert_true) from osf_tests.factories import UserFactory pytestmark = pytest.mark.django_db",
"assert_is_none(self.user_settings.totp_secret) assert_false(self.user_settings.is_confirmed) def test_remove_from_confirmed_user(self): # drift defaults to 0. Change",
"future assert_true( self.user_settings.verify_code( _valid_code(self.TOTP_SECRET, drift=1) ) ) # make sure",
"'/RDM:{}'.format(self.user.username)) assert_equal( parse_qs(url.query), {'secret': [self.TOTP_SECRET_B32]} ) def test_json(self): # url",
"{'secret': [self.TOTP_SECRET_B32]} ) def test_json(self): # url = 'otpauth://totp/RDM:{}?secret=' +",
"a code from 30 seconds in the future assert_true( self.user_settings.verify_code(",
"assert_equal(url.path, '/RDM:{}'.format(self.user.username)) assert_equal( parse_qs(url.query), {'secret': [self.TOTP_SECRET_B32]} ) def test_json(self): #",
"future.moves.urllib.parse import urlparse, urljoin, parse_qs import pytest from addons.twofactor.tests.utils import",
"future assert_true( self.user_settings.verify_code( _valid_code(self.TOTP_SECRET, drift=2) ) ) # make sure",
"= pytest.mark.django_db class TestCallbacks(unittest.TestCase): def setUp(self): super(TestCallbacks, self).setUp() self.user =",
") def test_verify_valid_code(self): assert_true( self.user_settings.verify_code(_valid_code(self.TOTP_SECRET)) ) def test_verify_valid_core_drift(self): # use",
"drift defaults to 0. Change it so we can test",
"_valid_code(self.TOTP_SECRET, drift=1) ) ) # make sure drift is updated."
] |
[
"<filename>betterloader/standard_transforms.py import numpy as np from torchvision import transforms np.random.seed(1)",
"def __init__(self, transform): self.transform = transform def __call__(self, sample): x1",
"TransformWhileSampling(object): def __init__(self, transform): self.transform = transform def __call__(self, sample):",
"def __call__(self, sample): x1 = self.transform(sample) x2 = self.transform(sample) return",
"transforms np.random.seed(1) class TransformWhileSampling(object): def __init__(self, transform): self.transform = transform",
"import transforms np.random.seed(1) class TransformWhileSampling(object): def __init__(self, transform): self.transform =",
"= transform def __call__(self, sample): x1 = self.transform(sample) x2 =",
"__init__(self, transform): self.transform = transform def __call__(self, sample): x1 =",
"sample): x1 = self.transform(sample) x2 = self.transform(sample) return x1, x2",
"transform): self.transform = transform def __call__(self, sample): x1 = self.transform(sample)",
"np from torchvision import transforms np.random.seed(1) class TransformWhileSampling(object): def __init__(self,",
"import numpy as np from torchvision import transforms np.random.seed(1) class",
"from torchvision import transforms np.random.seed(1) class TransformWhileSampling(object): def __init__(self, transform):",
"numpy as np from torchvision import transforms np.random.seed(1) class TransformWhileSampling(object):",
"__call__(self, sample): x1 = self.transform(sample) x2 = self.transform(sample) return x1,",
"torchvision import transforms np.random.seed(1) class TransformWhileSampling(object): def __init__(self, transform): self.transform",
"transform def __call__(self, sample): x1 = self.transform(sample) x2 = self.transform(sample)",
"class TransformWhileSampling(object): def __init__(self, transform): self.transform = transform def __call__(self,",
"self.transform = transform def __call__(self, sample): x1 = self.transform(sample) x2",
"np.random.seed(1) class TransformWhileSampling(object): def __init__(self, transform): self.transform = transform def",
"as np from torchvision import transforms np.random.seed(1) class TransformWhileSampling(object): def"
] |
[
"net.state_dict(), 'optim': optim.state_dict(), 'scheduler': scheduler.state_dict(), 'recorder': recorder.state_dict(), 'epoch': epoch },",
"model_dir = os.path.join(recorder.work_dir, 'ckpt') os.system('mkdir -p {}'.format(model_dir)) epoch = recorder.epoch",
"from: ' + finetune_from) load_network_specified(net, finetune_from, logger) return pretrained_model =",
"load_network_specified(net, model_dir, logger=None): pretrained_net = torch.load(model_dir)['net'] net_state = net.state_dict() state",
"# remove previous pretrained model if the number of models",
"'epoch': epoch }, os.path.join(model_dir, '{}.pth'.format(ckpt_name))) # remove previous pretrained model",
"optim, scheduler, recorder, is_best=False): model_dir = os.path.join(recorder.work_dir, 'ckpt') os.system('mkdir -p",
"epoch torch.save({ 'net': net.state_dict(), 'optim': optim.state_dict(), 'scheduler': scheduler.state_dict(), 'recorder': recorder.state_dict(),",
"model_dir, finetune_from=None, logger=None): if finetune_from: if logger: logger.info('Finetune model from:",
"previous pretrained model if the number of models is too",
"from .logger import get_logger def save_model(net, optim, scheduler, recorder, is_best=False):",
"torch import os from torch import nn import numpy as",
"os.path.join(recorder.work_dir, 'ckpt') os.system('mkdir -p {}'.format(model_dir)) epoch = recorder.epoch ckpt_name =",
".logger import get_logger def save_model(net, optim, scheduler, recorder, is_best=False): model_dir",
"epoch = recorder.epoch ckpt_name = 'best' if is_best else epoch",
"len(pths) <= 2: # return # os.system('rm {}'.format(os.path.join(model_dir, '{}.pth'.format(min(pths))))) def",
"pretrained model if the number of models is too big",
"= net.state_dict() state = {} for k, v in pretrained_net.items():",
"get_logger def save_model(net, optim, scheduler, recorder, is_best=False): model_dir = os.path.join(recorder.work_dir,",
"finetune_from: if logger: logger.info('Finetune model from: ' + finetune_from) load_network_specified(net,",
"big # pths = [int(pth.split('.')[0]) for pth in os.listdir(model_dir)] #",
"torch.load(model_dir)['net'] net_state = net.state_dict() state = {} for k, v",
"as np import torch.nn.functional from termcolor import colored from .logger",
"numpy as np import torch.nn.functional from termcolor import colored from",
"if logger: logger.info('skip weights: ' + k) continue state[k] =",
"logger.info('Finetune model from: ' + finetune_from) load_network_specified(net, finetune_from, logger) return",
"load_network(net, model_dir, finetune_from=None, logger=None): if finetune_from: if logger: logger.info('Finetune model",
"}, os.path.join(model_dir, '{}.pth'.format(ckpt_name))) # remove previous pretrained model if the",
"state = {} for k, v in pretrained_net.items(): if k",
"scheduler.state_dict(), 'recorder': recorder.state_dict(), 'epoch': epoch }, os.path.join(model_dir, '{}.pth'.format(ckpt_name))) # remove",
"+ k) continue state[k] = v net.load_state_dict(state, strict=False) def load_network(net,",
"'scheduler': scheduler.state_dict(), 'recorder': recorder.state_dict(), 'epoch': epoch }, os.path.join(model_dir, '{}.pth'.format(ckpt_name))) #",
"# pths = [int(pth.split('.')[0]) for pth in os.listdir(model_dir)] # if",
"# return # os.system('rm {}'.format(os.path.join(model_dir, '{}.pth'.format(min(pths))))) def load_network_specified(net, model_dir, logger=None):",
"finetune_from=None, logger=None): if finetune_from: if logger: logger.info('Finetune model from: '",
"weights: ' + k) continue state[k] = v net.load_state_dict(state, strict=False)",
"# os.system('rm {}'.format(os.path.join(model_dir, '{}.pth'.format(min(pths))))) def load_network_specified(net, model_dir, logger=None): pretrained_net =",
"in pretrained_net.items(): if k not in net_state.keys() or v.size() !=",
"ckpt_name = 'best' if is_best else epoch torch.save({ 'net': net.state_dict(),",
"= recorder.epoch ckpt_name = 'best' if is_best else epoch torch.save({",
"for pth in os.listdir(model_dir)] # if len(pths) <= 2: #",
"{}'.format(model_dir)) epoch = recorder.epoch ckpt_name = 'best' if is_best else",
"import nn import numpy as np import torch.nn.functional from termcolor",
"save_model(net, optim, scheduler, recorder, is_best=False): model_dir = os.path.join(recorder.work_dir, 'ckpt') os.system('mkdir",
"+ finetune_from) load_network_specified(net, finetune_from, logger) return pretrained_model = torch.load(model_dir) net.load_state_dict(pretrained_model['net'],",
"os from torch import nn import numpy as np import",
"import colored from .logger import get_logger def save_model(net, optim, scheduler,",
"import torch import os from torch import nn import numpy",
"net_state.keys() or v.size() != net_state[k].size(): if logger: logger.info('skip weights: '",
"= [int(pth.split('.')[0]) for pth in os.listdir(model_dir)] # if len(pths) <=",
"logger=None): pretrained_net = torch.load(model_dir)['net'] net_state = net.state_dict() state = {}",
"strict=False) def load_network(net, model_dir, finetune_from=None, logger=None): if finetune_from: if logger:",
"termcolor import colored from .logger import get_logger def save_model(net, optim,",
"colored from .logger import get_logger def save_model(net, optim, scheduler, recorder,",
"k) continue state[k] = v net.load_state_dict(state, strict=False) def load_network(net, model_dir,",
"remove previous pretrained model if the number of models is",
"if k not in net_state.keys() or v.size() != net_state[k].size(): if",
"def load_network(net, model_dir, finetune_from=None, logger=None): if finetune_from: if logger: logger.info('Finetune",
"else epoch torch.save({ 'net': net.state_dict(), 'optim': optim.state_dict(), 'scheduler': scheduler.state_dict(), 'recorder':",
"logger=None): if finetune_from: if logger: logger.info('Finetune model from: ' +",
"the number of models is too big # pths =",
"is_best else epoch torch.save({ 'net': net.state_dict(), 'optim': optim.state_dict(), 'scheduler': scheduler.state_dict(),",
"k, v in pretrained_net.items(): if k not in net_state.keys() or",
"torch import nn import numpy as np import torch.nn.functional from",
"return # os.system('rm {}'.format(os.path.join(model_dir, '{}.pth'.format(min(pths))))) def load_network_specified(net, model_dir, logger=None): pretrained_net",
"recorder.epoch ckpt_name = 'best' if is_best else epoch torch.save({ 'net':",
"pretrained_net.items(): if k not in net_state.keys() or v.size() != net_state[k].size():",
"torch.save({ 'net': net.state_dict(), 'optim': optim.state_dict(), 'scheduler': scheduler.state_dict(), 'recorder': recorder.state_dict(), 'epoch':",
"' + k) continue state[k] = v net.load_state_dict(state, strict=False) def",
"os.path.join(model_dir, '{}.pth'.format(ckpt_name))) # remove previous pretrained model if the number",
"model if the number of models is too big #",
"os.system('rm {}'.format(os.path.join(model_dir, '{}.pth'.format(min(pths))))) def load_network_specified(net, model_dir, logger=None): pretrained_net = torch.load(model_dir)['net']",
"nn import numpy as np import torch.nn.functional from termcolor import",
"model from: ' + finetune_from) load_network_specified(net, finetune_from, logger) return pretrained_model",
"net.load_state_dict(state, strict=False) def load_network(net, model_dir, finetune_from=None, logger=None): if finetune_from: if",
"v.size() != net_state[k].size(): if logger: logger.info('skip weights: ' + k)",
"if is_best else epoch torch.save({ 'net': net.state_dict(), 'optim': optim.state_dict(), 'scheduler':",
"model_dir, logger=None): pretrained_net = torch.load(model_dir)['net'] net_state = net.state_dict() state =",
"# if len(pths) <= 2: # return # os.system('rm {}'.format(os.path.join(model_dir,",
"pth in os.listdir(model_dir)] # if len(pths) <= 2: # return",
"net_state[k].size(): if logger: logger.info('skip weights: ' + k) continue state[k]",
"finetune_from) load_network_specified(net, finetune_from, logger) return pretrained_model = torch.load(model_dir) net.load_state_dict(pretrained_model['net'], strict=True)",
"recorder.state_dict(), 'epoch': epoch }, os.path.join(model_dir, '{}.pth'.format(ckpt_name))) # remove previous pretrained",
"from torch import nn import numpy as np import torch.nn.functional",
"is_best=False): model_dir = os.path.join(recorder.work_dir, 'ckpt') os.system('mkdir -p {}'.format(model_dir)) epoch =",
"def load_network_specified(net, model_dir, logger=None): pretrained_net = torch.load(model_dir)['net'] net_state = net.state_dict()",
"if logger: logger.info('Finetune model from: ' + finetune_from) load_network_specified(net, finetune_from,",
"= 'best' if is_best else epoch torch.save({ 'net': net.state_dict(), 'optim':",
"k not in net_state.keys() or v.size() != net_state[k].size(): if logger:",
"import torch.nn.functional from termcolor import colored from .logger import get_logger",
"torch.nn.functional from termcolor import colored from .logger import get_logger def",
"if the number of models is too big # pths",
"logger: logger.info('Finetune model from: ' + finetune_from) load_network_specified(net, finetune_from, logger)",
"{}'.format(os.path.join(model_dir, '{}.pth'.format(min(pths))))) def load_network_specified(net, model_dir, logger=None): pretrained_net = torch.load(model_dir)['net'] net_state",
"v net.load_state_dict(state, strict=False) def load_network(net, model_dir, finetune_from=None, logger=None): if finetune_from:",
"import get_logger def save_model(net, optim, scheduler, recorder, is_best=False): model_dir =",
"= torch.load(model_dir)['net'] net_state = net.state_dict() state = {} for k,",
"= os.path.join(recorder.work_dir, 'ckpt') os.system('mkdir -p {}'.format(model_dir)) epoch = recorder.epoch ckpt_name",
"is too big # pths = [int(pth.split('.')[0]) for pth in",
"'ckpt') os.system('mkdir -p {}'.format(model_dir)) epoch = recorder.epoch ckpt_name = 'best'",
"os.listdir(model_dir)] # if len(pths) <= 2: # return # os.system('rm",
"not in net_state.keys() or v.size() != net_state[k].size(): if logger: logger.info('skip",
"in os.listdir(model_dir)] # if len(pths) <= 2: # return #",
"too big # pths = [int(pth.split('.')[0]) for pth in os.listdir(model_dir)]",
"optim.state_dict(), 'scheduler': scheduler.state_dict(), 'recorder': recorder.state_dict(), 'epoch': epoch }, os.path.join(model_dir, '{}.pth'.format(ckpt_name)))",
"'recorder': recorder.state_dict(), 'epoch': epoch }, os.path.join(model_dir, '{}.pth'.format(ckpt_name))) # remove previous",
"' + finetune_from) load_network_specified(net, finetune_from, logger) return pretrained_model = torch.load(model_dir)",
"[int(pth.split('.')[0]) for pth in os.listdir(model_dir)] # if len(pths) <= 2:",
"in net_state.keys() or v.size() != net_state[k].size(): if logger: logger.info('skip weights:",
"'net': net.state_dict(), 'optim': optim.state_dict(), 'scheduler': scheduler.state_dict(), 'recorder': recorder.state_dict(), 'epoch': epoch",
"state[k] = v net.load_state_dict(state, strict=False) def load_network(net, model_dir, finetune_from=None, logger=None):",
"np import torch.nn.functional from termcolor import colored from .logger import",
"logger: logger.info('skip weights: ' + k) continue state[k] = v",
"net_state = net.state_dict() state = {} for k, v in",
"if len(pths) <= 2: # return # os.system('rm {}'.format(os.path.join(model_dir, '{}.pth'.format(min(pths)))))",
"from termcolor import colored from .logger import get_logger def save_model(net,",
"recorder, is_best=False): model_dir = os.path.join(recorder.work_dir, 'ckpt') os.system('mkdir -p {}'.format(model_dir)) epoch",
"models is too big # pths = [int(pth.split('.')[0]) for pth",
"import numpy as np import torch.nn.functional from termcolor import colored",
"pretrained_net = torch.load(model_dir)['net'] net_state = net.state_dict() state = {} for",
"or v.size() != net_state[k].size(): if logger: logger.info('skip weights: ' +",
"{} for k, v in pretrained_net.items(): if k not in",
"!= net_state[k].size(): if logger: logger.info('skip weights: ' + k) continue",
"of models is too big # pths = [int(pth.split('.')[0]) for",
"'optim': optim.state_dict(), 'scheduler': scheduler.state_dict(), 'recorder': recorder.state_dict(), 'epoch': epoch }, os.path.join(model_dir,",
"'{}.pth'.format(ckpt_name))) # remove previous pretrained model if the number of",
"logger.info('skip weights: ' + k) continue state[k] = v net.load_state_dict(state,",
"number of models is too big # pths = [int(pth.split('.')[0])",
"epoch }, os.path.join(model_dir, '{}.pth'.format(ckpt_name))) # remove previous pretrained model if",
"pths = [int(pth.split('.')[0]) for pth in os.listdir(model_dir)] # if len(pths)",
"scheduler, recorder, is_best=False): model_dir = os.path.join(recorder.work_dir, 'ckpt') os.system('mkdir -p {}'.format(model_dir))",
"2: # return # os.system('rm {}'.format(os.path.join(model_dir, '{}.pth'.format(min(pths))))) def load_network_specified(net, model_dir,",
"for k, v in pretrained_net.items(): if k not in net_state.keys()",
"os.system('mkdir -p {}'.format(model_dir)) epoch = recorder.epoch ckpt_name = 'best' if",
"net.state_dict() state = {} for k, v in pretrained_net.items(): if",
"if finetune_from: if logger: logger.info('Finetune model from: ' + finetune_from)",
"= v net.load_state_dict(state, strict=False) def load_network(net, model_dir, finetune_from=None, logger=None): if",
"import os from torch import nn import numpy as np",
"v in pretrained_net.items(): if k not in net_state.keys() or v.size()",
"-p {}'.format(model_dir)) epoch = recorder.epoch ckpt_name = 'best' if is_best",
"<= 2: # return # os.system('rm {}'.format(os.path.join(model_dir, '{}.pth'.format(min(pths))))) def load_network_specified(net,",
"continue state[k] = v net.load_state_dict(state, strict=False) def load_network(net, model_dir, finetune_from=None,",
"'{}.pth'.format(min(pths))))) def load_network_specified(net, model_dir, logger=None): pretrained_net = torch.load(model_dir)['net'] net_state =",
"'best' if is_best else epoch torch.save({ 'net': net.state_dict(), 'optim': optim.state_dict(),",
"= {} for k, v in pretrained_net.items(): if k not",
"def save_model(net, optim, scheduler, recorder, is_best=False): model_dir = os.path.join(recorder.work_dir, 'ckpt')"
] |
[
"AppConfig #pragma: no cover class HexafuelOilAppConfig(AppConfig): #pragma: no cover name",
"no cover class HexafuelOilAppConfig(AppConfig): #pragma: no cover name = 'hexafuel_oil_app'",
"import AppConfig #pragma: no cover class HexafuelOilAppConfig(AppConfig): #pragma: no cover",
"django.apps import AppConfig #pragma: no cover class HexafuelOilAppConfig(AppConfig): #pragma: no",
"#pragma: no cover class HexafuelOilAppConfig(AppConfig): #pragma: no cover name =",
"from django.apps import AppConfig #pragma: no cover class HexafuelOilAppConfig(AppConfig): #pragma:"
] |
[
"matrix to list for ease a = np.array(a).tolist() #print(a) #creates",
"+ matchAnchor(posting,candidate) +matchLocation(posting,candidate) + matchCompetency(posting,candidate) + matchSkill(posting,candidate)+matchCohort(posting,candidate)) n += 1",
"= [] m = Munkres() indexes = m.compute(totalMatrix) #print_matrix(totalMatrix, msg='Lowest",
"position: %d (score %s)\\n' % (names[column], column+1, value)) else: pass",
"postCode): # jobScore = (rank,b) # list(jobScore) # jobRank.append(jobScore) #",
"90%% unsuitable: %d' % tenpc_candidates) #output from excel: correct =",
"__future__ import division from timeit import default_timer as timer import",
"c_file = raw_input(\"Please enter the path for the candidate file:",
"- len(totalMatrix))) totalMatrix = np.asarray(totalMatrix) totalMatrix = np.reshape(totalMatrix,(n,-1)) #at this",
"candidatesAll = list(reader) \"\"\"create empty lists to fill with lists",
"print('Candidates who are more than 75%% suitable: %d' % qs_candidates)",
"#print(postings) #split up files into relative blocks postCode = [lists[0]",
"75%% unsuitable: %d' % medium_candidates) print('Candidates who are more than",
"% vs_candidates) print('Candidates who are more than 75%% suitable: %d'",
"totalMatrix[row][column] if value > minSuitability*0.9: tenpc_candidates += 1 elif value",
"timer() print(end-start) \"\"\" #posting = [Posting(*postingsAll)] #print(posting[0].anchor) #print(posting) #print(candidatesAll) #print(postingsAll)",
"l: value = totalMatrix[row][column] if value > minSuitability*0.9: tenpc_candidates +=",
"= filedialog.askopenfilename(title='Please select the posting file') c_file = filedialog.askopenfilename(title='Please select",
"list in candidatesAll: candidate = Candidate(*list) names.append(candidate.name) n = 0",
"/users/java_jonathan/postings_lge.csv and /Users/java_jonathan/candidates_lge.csv\"\"\" # p_file = raw_input(\"Please enter the path",
"0 medium_candidates = 0 tenpc_candidates = 0 qs_candidates = 0",
"tenpc_candidates) #output from excel: correct = [1,3,5,9,10,2,4,8,6,7] #this function tests",
"the candidate file') \"\"\"for use with /users/java_jonathan/postings_lge.csv and /Users/java_jonathan/candidates_lge.csv\"\"\" #",
"50%% suitable: %d' % (l-unhappy_candidates)) print('Candidates who are more than",
"#converts 1D matrix to list for ease a = np.array(a).tolist()",
"[] for list in candidatesAll: candidate = Candidate(*list) names.append(candidate.name) n",
"p_file.strip() # c_file = raw_input(\"Please enter the path for the",
"for lists in postings] #with open('/Users/Jonathan/Google Drive/CPD/Python/candidates.csv','r') as f: #gives",
"candidate file: \") # c_file = c_file.strip() start = timer()",
"+ matchSkill(posting,candidate)+matchCohort(posting,candidate)) n += 1 l = len(names) names.extend([0] *",
"#output from excel: correct = [1,3,5,9,10,2,4,8,6,7] #this function tests output",
"from excel: correct = [1,3,5,9,10,2,4,8,6,7] #this function tests output above",
"= 0.0 unhappy_candidates = 0 medium_candidates = 0 tenpc_candidates =",
"= np.array(a).tolist() #print(a) #creates list called output containing rank of",
"#print(postingsAll) #print(postingsAll[0].name) #print(preferences) #print(postings) #split up files into relative blocks",
"% qs_candidates) print('Candidates who are more than 50%% suitable: %d'",
"= timer() with open(p_file,'r') as f: #with open('/Users/Jonathan/Google Drive/CPD/Python/postings.csv','r') as",
"print(output) #creates tuples of rank, job and appends to list",
"result.append((row,column)) f.write('For candidate %s: \\nOptimal position: %d (score %s)\\n' %",
"timer import csv import numpy as np import itertools from",
"lists in postings] postSkills = [lists[3:5] for lists in postings]",
"in postings] postSkills = [lists[3:5] for lists in postings] postLocation",
"(n-l)) totalMatrix.extend([0] * (n**2 - len(totalMatrix))) totalMatrix = np.asarray(totalMatrix) totalMatrix",
"are more than 90%% unsuitable: %d' % tenpc_candidates) #output from",
"lists of lists output by iterating function below\"\"\" names =",
"#print(preferences) #print(postings) #split up files into relative blocks postCode =",
"[] m = Munkres() indexes = m.compute(totalMatrix) #print_matrix(totalMatrix, msg='Lowest cost",
"f.write('For candidate %s: \\nOptimal position: %d (score %s)\\n' % (names[column],",
"in postings] postCompetencies = [lists[7:10] for lists in postings] postSecurity",
"against Excel: #test(correct,check) topMatrix = topFive(names,totalMatrix) #print(topMatrix) np.savetxt('/Users/java_jonathan/test.csv',topMatrix, fmt='%s', delimiter=',',",
"Tkinter as tk import tkFileDialog as filedialog root = tk.Tk()",
"from munkres import Munkres, print_matrix, make_cost_matrix import sys from classes",
"import tkFileDialog as filedialog root = tk.Tk() root.withdraw() p_file =",
"l = len(names) names.extend([0] * (n-l)) totalMatrix.extend([0] * (n**2 -",
"#posting = [Posting(*postingsAll)] #print(posting[0].anchor) #print(posting) #print(candidatesAll) #print(postingsAll) #print(postingsAll[0].name) #print(preferences) #print(postings)",
"< l: value = totalMatrix[row][column] if value > minSuitability*0.9: tenpc_candidates",
"> minSuitability/2: unhappy_candidates += 1 elif value > minSuitability*0.25: qs_candidates",
"switched! totalMatrix = np.subtract(np.amax(totalMatrix),totalMatrix) totalMatrix = np.array(totalMatrix) minSuitability = 18",
"in indexes: if column < l: value = totalMatrix[row][column] if",
"root.withdraw() p_file = filedialog.askopenfilename(title='Please select the posting file') c_file =",
"more than 50%% suitable: %d' % (l-unhappy_candidates)) print('Candidates who are",
"medium_candidates) print('Candidates who are more than 90%% unsuitable: %d' %",
"%d' % qs_candidates) print('Candidates who are more than 50%% suitable:",
"satisfaction: %.2f%%' % globalSatisfaction) print('Candidates who are more than 90%%",
"candidate = Candidate(*list) names.append(candidate.name) n = 0 for list in",
"n = 0 for list in postingsAll: posting = Posting(*list)",
"'w') for row, column in indexes: if column < l:",
"containing rank of score output = [0] * len(a) for",
"totalMatrix = np.subtract(np.amax(totalMatrix),totalMatrix) totalMatrix = np.array(totalMatrix) minSuitability = 18 check",
"suitable: %d' % vs_candidates) print('Candidates who are more than 75%%",
"% tenpc_candidates) #output from excel: correct = [1,3,5,9,10,2,4,8,6,7] #this function",
"= sorted(jobRank, reverse=False) # print(jobRank) # print('For candidate a, the",
"# p_file = p_file.strip() # c_file = raw_input(\"Please enter the",
"up files into relative blocks postCode = [lists[0] for lists",
"score output = [0] * len(a) for i, x in",
"Posting(*list) totalMatrix.append(matchDept(posting,candidate) + matchAnchor(posting,candidate) +matchLocation(posting,candidate) + matchCompetency(posting,candidate) + matchSkill(posting,candidate)+matchCohort(posting,candidate)) n",
"import sqrt import Tkinter as tk import tkFileDialog as filedialog",
"open('/Users/Jonathan/Google Drive/CPD/Python/candidates.csv','r') as f: #gives first column ie candidate a",
"#gives first column ie candidate a a=totalMatrix[:,[0]] #b = totalMatrix[:,[0]]",
"import * from functions import * from math import sqrt",
"#with open('/Users/Jonathan/Google Drive/CPD/Python/candidates.csv','r') as f: #gives first column ie candidate",
"[lists[10] for lists in postings] #with open('/Users/Jonathan/Google Drive/CPD/Python/candidates.csv','r') as f:",
"= totalMatrix[:,[0]] #print(a) #converts 1D matrix to list for ease",
"tk.Tk() root.withdraw() p_file = filedialog.askopenfilename(title='Please select the posting file') c_file",
"than 50%% suitable: %d' % (l-unhappy_candidates)) print('Candidates who are more",
"filedialog root = tk.Tk() root.withdraw() p_file = filedialog.askopenfilename(title='Please select the",
"with /users/java_jonathan/postings_lge.csv and /Users/java_jonathan/candidates_lge.csv\"\"\" # p_file = raw_input(\"Please enter the",
"# jobRank = sorted(jobRank, reverse=False) # print(jobRank) # print('For candidate",
"[] totalMatrix = [] for list in candidatesAll: candidate =",
"lists to fill with lists of lists output by iterating",
"[lists[3:5] for lists in postings] postLocation = [lists[5] for lists",
"raw_input(\"Please enter the path for the candidate file: \") #",
"m = Munkres() indexes = m.compute(totalMatrix) #print_matrix(totalMatrix, msg='Lowest cost through",
"print(jobRank) # print('For candidate a, the best position is %s')",
"this point the matrix is structured as candidates down and",
"# c_file = raw_input(\"Please enter the path for the candidate",
"csv.reader(f) candidatesAll = list(reader) \"\"\"create empty lists to fill with",
"[lists[1] for lists in postings] postAnchor = [lists[2] for lists",
"topFive(names,totalMatrix) #print(topMatrix) np.savetxt('/Users/java_jonathan/test.csv',topMatrix, fmt='%s', delimiter=',', newline='\\n', header='', footer='', comments='# ')",
"column in indexes: if column < l: value = totalMatrix[row][column]",
"list in postingsAll: posting = Posting(*list) totalMatrix.append(matchDept(posting,candidate) + matchAnchor(posting,candidate) +matchLocation(posting,candidate)",
"= 0 tenpc_candidates = 0 qs_candidates = 0 vs_candidates =",
"= Candidate(*list) names.append(candidate.name) n = 0 for list in postingsAll:",
"reader = csv.reader(f) candidatesAll = list(reader) \"\"\"create empty lists to",
"as timer import csv import numpy as np import itertools",
"0.0 unhappy_candidates = 0 medium_candidates = 0 tenpc_candidates = 0",
"#split up files into relative blocks postCode = [lists[0] for",
"in enumerate(sorted(range(len(a)), key=lambda y: a[y])): output[x] = i print(output) #creates",
"+= 1 elif value > minSuitability*0.1: vs_candidates += 1 total",
"lists output by iterating function below\"\"\" names = [] totalMatrix",
"= np.array(totalMatrix) minSuitability = 18 check = [] result =",
"qs_candidates += 1 elif value > minSuitability*0.1: vs_candidates += 1",
"as candidates down and jobs across totalMatrix = np.transpose(totalMatrix) #now",
"#creates tuples of rank, job and appends to list jobRank",
"start = timer() with open(p_file,'r') as f: #with open('/Users/Jonathan/Google Drive/CPD/Python/postings.csv','r')",
"value)) else: pass globalSatisfaction = 100*(1-(total/(l*minSuitability))) print('Global satisfaction: %.2f%%' %",
"output above against Excel: #test(correct,check) topMatrix = topFive(names,totalMatrix) #print(topMatrix) np.savetxt('/Users/java_jonathan/test.csv',topMatrix,",
"c_file = filedialog.askopenfilename(title='Please select the candidate file') \"\"\"for use with",
"filedialog.askopenfilename(title='Please select the candidate file') \"\"\"for use with /users/java_jonathan/postings_lge.csv and",
"structured as candidates down and jobs across totalMatrix = np.transpose(totalMatrix)",
"matrix:') total = 0.0 unhappy_candidates = 0 medium_candidates = 0",
"1 elif value > minSuitability/2: unhappy_candidates += 1 elif value",
"import sys from classes import * from functions import *",
"file: \") # c_file = c_file.strip() start = timer() with",
"in postings] #with open('/Users/Jonathan/Google Drive/CPD/Python/candidates.csv','r') as f: #gives first column",
"# jobRank.append(jobScore) # print(jobRank) output = [0] * len(a) for",
"topMatrix = topFive(names,totalMatrix) #print(topMatrix) np.savetxt('/Users/java_jonathan/test.csv',topMatrix, fmt='%s', delimiter=',', newline='\\n', header='', footer='',",
"posting = Posting(*list) totalMatrix.append(matchDept(posting,candidate) + matchAnchor(posting,candidate) +matchLocation(posting,candidate) + matchCompetency(posting,candidate) +",
"than 90%% unsuitable: %d' % tenpc_candidates) #output from excel: correct",
"for lists in postings] postLocation = [lists[5] for lists in",
"unhappy_candidates = 0 medium_candidates = 0 tenpc_candidates = 0 qs_candidates",
"minSuitability*0.25: qs_candidates += 1 elif value > minSuitability*0.1: vs_candidates +=",
"candidate %s: \\nOptimal position: %d (score %s)\\n' % (names[column], column+1,",
"#b = totalMatrix[:,[0]] #print(a) #converts 1D matrix to list for",
"for lists in postings] postDept = [lists[1] for lists in",
"the candidate file: \") # c_file = c_file.strip() start =",
"(l-unhappy_candidates)) print('Candidates who are more than 75%% unsuitable: %d' %",
"who are more than 90%% suitable: %d' % vs_candidates) print('Candidates",
"the posting file') c_file = filedialog.askopenfilename(title='Please select the candidate file')",
"than 75%% suitable: %d' % qs_candidates) print('Candidates who are more",
"timer() with open(p_file,'r') as f: #with open('/Users/Jonathan/Google Drive/CPD/Python/postings.csv','r') as f:",
"= [lists[7:10] for lists in postings] postSecurity = [lists[10] for",
"globalSatisfaction = 100*(1-(total/(l*minSuitability))) print('Global satisfaction: %.2f%%' % globalSatisfaction) print('Candidates who",
"print('For candidate a, the best position is %s') % (jobRank[0][1])",
"= csv.reader(f) candidatesAll = list(reader) \"\"\"create empty lists to fill",
"[lists[0] for lists in postings] postDept = [lists[1] for lists",
"key=lambda y: a[y])): output[x] = i print(output) #creates tuples of",
"# p_file = raw_input(\"Please enter the path for the postings",
"100*(1-(total/(l*minSuitability))) print('Global satisfaction: %.2f%%' % globalSatisfaction) print('Candidates who are more",
"elif value > minSuitability*0.75: medium_candidates += 1 elif value >",
"timeit import default_timer as timer import csv import numpy as",
"%.2f%%' % globalSatisfaction) print('Candidates who are more than 90%% suitable:",
"indexes = m.compute(totalMatrix) #print_matrix(totalMatrix, msg='Lowest cost through this matrix:') total",
"np.savetxt('/Users/java_jonathan/test.csv',topMatrix, fmt='%s', delimiter=',', newline='\\n', header='', footer='', comments='# ') np.savetxt('/Users/java_jonathan/test2.csv',totalMatrix, fmt='%s',",
"#print(posting) #print(candidatesAll) #print(postingsAll) #print(postingsAll[0].name) #print(preferences) #print(postings) #split up files into",
"= i print(output) # #print(a) # jobRank = sorted(jobRank, reverse=False)",
"= i print(output) #creates tuples of rank, job and appends",
"for list in candidatesAll: candidate = Candidate(*list) names.append(candidate.name) n =",
"i print(output) # #print(a) # jobRank = sorted(jobRank, reverse=False) #",
"Munkres, print_matrix, make_cost_matrix import sys from classes import * from",
"appends to list jobRank = [] # for rank, b",
"= 0 medium_candidates = 0 tenpc_candidates = 0 qs_candidates =",
"jobRank.append(jobScore) # print(jobRank) output = [0] * len(a) for i,",
"= 0 f = open('output.txt', 'w') for row, column in",
"tkFileDialog as filedialog root = tk.Tk() root.withdraw() p_file = filedialog.askopenfilename(title='Please",
"in enumerate(sorted(range(len(a)), key=lambda y: a[y])): output[x] = i print(output) #",
"blocks postCode = [lists[0] for lists in postings] postDept =",
"postings] postLocation = [lists[5] for lists in postings] postCompetencies =",
"totalMatrix = np.reshape(totalMatrix,(n,-1)) #at this point the matrix is structured",
"to fill with lists of lists output by iterating function",
"vs_candidates) print('Candidates who are more than 75%% suitable: %d' %",
"= 100*(1-(total/(l*minSuitability))) print('Global satisfaction: %.2f%%' % globalSatisfaction) print('Candidates who are",
"tuples of rank, job and appends to list jobRank =",
"more than 75%% unsuitable: %d' % medium_candidates) print('Candidates who are",
"jobs across totalMatrix = np.transpose(totalMatrix) #now it's switched! totalMatrix =",
"use with /users/java_jonathan/postings_lge.csv and /Users/java_jonathan/candidates_lge.csv\"\"\" # p_file = raw_input(\"Please enter",
"open(p_file,'r') as f: #with open('/Users/Jonathan/Google Drive/CPD/Python/postings.csv','r') as f: reader =",
"a a=totalMatrix[:,[0]] #b = totalMatrix[:,[0]] #print(a) #converts 1D matrix to",
"# for rank, b in zip(output, postCode): # jobScore =",
"cost through this matrix:') total = 0.0 unhappy_candidates = 0",
"who are more than 50%% suitable: %d' % (l-unhappy_candidates)) print('Candidates",
"delimiter=',', newline='\\n', header='', footer='', comments='# ') np.savetxt('/Users/java_jonathan/test2.csv',totalMatrix, fmt='%s', delimiter=',', newline='\\n',",
"for lists in postings] postAnchor = [lists[2] for lists in",
"with open(p_file,'r') as f: #with open('/Users/Jonathan/Google Drive/CPD/Python/postings.csv','r') as f: reader",
"= [lists[10] for lists in postings] #with open('/Users/Jonathan/Google Drive/CPD/Python/candidates.csv','r') as",
"unhappy_candidates += 1 elif value > minSuitability*0.25: qs_candidates += 1",
"postings] postAnchor = [lists[2] for lists in postings] postSkills =",
"postingsAll: posting = Posting(*list) totalMatrix.append(matchDept(posting,candidate) + matchAnchor(posting,candidate) +matchLocation(posting,candidate) + matchCompetency(posting,candidate)",
"tenpc_candidates += 1 elif value > minSuitability*0.75: medium_candidates += 1",
"who are more than 75%% suitable: %d' % qs_candidates) print('Candidates",
"= timer() print(end-start) \"\"\" #posting = [Posting(*postingsAll)] #print(posting[0].anchor) #print(posting) #print(candidatesAll)",
"output[x] = i print(output) #creates tuples of rank, job and",
"as np import itertools from munkres import Munkres, print_matrix, make_cost_matrix",
"p_file = raw_input(\"Please enter the path for the postings file:",
"names = [] totalMatrix = [] for list in candidatesAll:",
"Drive/CPD/Python/postings.csv','r') as f: reader = csv.reader(f) postingsAll = list(reader) with",
"* len(a) for i, x in enumerate(sorted(range(len(a)), key=lambda y: a[y])):",
"result = [] m = Munkres() indexes = m.compute(totalMatrix) #print_matrix(totalMatrix,",
"1 elif value > minSuitability*0.25: qs_candidates += 1 elif value",
"for ease a = np.array(a).tolist() #print(a) #creates list called output",
"np.savetxt('/Users/java_jonathan/test2.csv',totalMatrix, fmt='%s', delimiter=',', newline='\\n', header='', footer='', comments='# ') end =",
"file') \"\"\"for use with /users/java_jonathan/postings_lge.csv and /Users/java_jonathan/candidates_lge.csv\"\"\" # p_file =",
"lists in postings] postSecurity = [lists[10] for lists in postings]",
"more than 90%% unsuitable: %d' % tenpc_candidates) #output from excel:",
"\"\"\" #posting = [Posting(*postingsAll)] #print(posting[0].anchor) #print(posting) #print(candidatesAll) #print(postingsAll) #print(postingsAll[0].name) #print(preferences)",
"classes import * from functions import * from math import",
"newline='\\n', header='', footer='', comments='# ') end = timer() print(end-start) \"\"\"",
"excel: correct = [1,3,5,9,10,2,4,8,6,7] #this function tests output above against",
"lists in postings] postLocation = [lists[5] for lists in postings]",
"np.array(totalMatrix) minSuitability = 18 check = [] result = []",
"#print(a) #creates list called output containing rank of score output",
"functions import * from math import sqrt import Tkinter as",
"comments='# ') end = timer() print(end-start) \"\"\" #posting = [Posting(*postingsAll)]",
"matrix is structured as candidates down and jobs across totalMatrix",
"') np.savetxt('/Users/java_jonathan/test2.csv',totalMatrix, fmt='%s', delimiter=',', newline='\\n', header='', footer='', comments='# ') end",
"m.compute(totalMatrix) #print_matrix(totalMatrix, msg='Lowest cost through this matrix:') total = 0.0",
"down and jobs across totalMatrix = np.transpose(totalMatrix) #now it's switched!",
"minSuitability*0.75: medium_candidates += 1 elif value > minSuitability/2: unhappy_candidates +=",
"totalMatrix = np.asarray(totalMatrix) totalMatrix = np.reshape(totalMatrix,(n,-1)) #at this point the",
"#this function tests output above against Excel: #test(correct,check) topMatrix =",
"= m.compute(totalMatrix) #print_matrix(totalMatrix, msg='Lowest cost through this matrix:') total =",
"len(a) for i, x in enumerate(sorted(range(len(a)), key=lambda y: a[y])): output[x]",
"division from timeit import default_timer as timer import csv import",
"len(totalMatrix))) totalMatrix = np.asarray(totalMatrix) totalMatrix = np.reshape(totalMatrix,(n,-1)) #at this point",
"it's switched! totalMatrix = np.subtract(np.amax(totalMatrix),totalMatrix) totalMatrix = np.array(totalMatrix) minSuitability =",
"postings] postDept = [lists[1] for lists in postings] postAnchor =",
"for rank, b in zip(output, postCode): # jobScore = (rank,b)",
"* (n-l)) totalMatrix.extend([0] * (n**2 - len(totalMatrix))) totalMatrix = np.asarray(totalMatrix)",
"f = open('output.txt', 'w') for row, column in indexes: if",
"jobRank = [] # for rank, b in zip(output, postCode):",
"list for ease a = np.array(a).tolist() #print(a) #creates list called",
"list(reader) with open(c_file,'r') as f: reader = csv.reader(f) candidatesAll =",
"delimiter=',', newline='\\n', header='', footer='', comments='# ') end = timer() print(end-start)",
"more than 75%% suitable: %d' % qs_candidates) print('Candidates who are",
"postingsAll = list(reader) with open(c_file,'r') as f: reader = csv.reader(f)",
"= filedialog.askopenfilename(title='Please select the candidate file') \"\"\"for use with /users/java_jonathan/postings_lge.csv",
"i, x in enumerate(sorted(range(len(a)), key=lambda y: a[y])): output[x] = i",
"totalMatrix = np.array(totalMatrix) minSuitability = 18 check = [] result",
"= np.transpose(totalMatrix) #now it's switched! totalMatrix = np.subtract(np.amax(totalMatrix),totalMatrix) totalMatrix =",
"1 total += value check.append(column+1) result.append((row,column)) f.write('For candidate %s: \\nOptimal",
"comments='# ') np.savetxt('/Users/java_jonathan/test2.csv',totalMatrix, fmt='%s', delimiter=',', newline='\\n', header='', footer='', comments='# ')",
"= 0 vs_candidates = 0 f = open('output.txt', 'w') for",
"> minSuitability*0.9: tenpc_candidates += 1 elif value > minSuitability*0.75: medium_candidates",
"#test(correct,check) topMatrix = topFive(names,totalMatrix) #print(topMatrix) np.savetxt('/Users/java_jonathan/test.csv',topMatrix, fmt='%s', delimiter=',', newline='\\n', header='',",
"y: a[y])): output[x] = i print(output) # #print(a) # jobRank",
"\") # p_file = p_file.strip() # c_file = raw_input(\"Please enter",
"import * from math import sqrt import Tkinter as tk",
"below\"\"\" names = [] totalMatrix = [] for list in",
"reverse=False) # print(jobRank) # print('For candidate a, the best position",
"x in enumerate(sorted(range(len(a)), key=lambda y: a[y])): output[x] = i print(output)",
"= list(reader) \"\"\"create empty lists to fill with lists of",
"are more than 75%% unsuitable: %d' % medium_candidates) print('Candidates who",
"to list jobRank = [] # for rank, b in",
"iterating function below\"\"\" names = [] totalMatrix = [] for",
"(n**2 - len(totalMatrix))) totalMatrix = np.asarray(totalMatrix) totalMatrix = np.reshape(totalMatrix,(n,-1)) #at",
"if value > minSuitability*0.9: tenpc_candidates += 1 elif value >",
"of rank, job and appends to list jobRank = []",
"in postings] postAnchor = [lists[2] for lists in postings] postSkills",
"/Users/java_jonathan/candidates_lge.csv\"\"\" # p_file = raw_input(\"Please enter the path for the",
"output = [0] * len(a) for i, x in enumerate(sorted(range(len(a)),",
"postings] #with open('/Users/Jonathan/Google Drive/CPD/Python/candidates.csv','r') as f: #gives first column ie",
"90%% suitable: %d' % vs_candidates) print('Candidates who are more than",
"footer='', comments='# ') np.savetxt('/Users/java_jonathan/test2.csv',totalMatrix, fmt='%s', delimiter=',', newline='\\n', header='', footer='', comments='#",
"for the candidate file: \") # c_file = c_file.strip() start",
"# c_file = c_file.strip() start = timer() with open(p_file,'r') as",
"> minSuitability*0.1: vs_candidates += 1 total += value check.append(column+1) result.append((row,column))",
"check.append(column+1) result.append((row,column)) f.write('For candidate %s: \\nOptimal position: %d (score %s)\\n'",
"print('Candidates who are more than 50%% suitable: %d' % (l-unhappy_candidates))",
"') end = timer() print(end-start) \"\"\" #posting = [Posting(*postingsAll)] #print(posting[0].anchor)",
"job and appends to list jobRank = [] # for",
"[1,3,5,9,10,2,4,8,6,7] #this function tests output above against Excel: #test(correct,check) topMatrix",
"1D matrix to list for ease a = np.array(a).tolist() #print(a)",
"as f: #with open('/Users/Jonathan/Google Drive/CPD/Python/postings.csv','r') as f: reader = csv.reader(f)",
"= [] # for rank, b in zip(output, postCode): #",
"list jobRank = [] # for rank, b in zip(output,",
"column+1, value)) else: pass globalSatisfaction = 100*(1-(total/(l*minSuitability))) print('Global satisfaction: %.2f%%'",
"from classes import * from functions import * from math",
"+matchLocation(posting,candidate) + matchCompetency(posting,candidate) + matchSkill(posting,candidate)+matchCohort(posting,candidate)) n += 1 l =",
"sqrt import Tkinter as tk import tkFileDialog as filedialog root",
"print(output) # #print(a) # jobRank = sorted(jobRank, reverse=False) # print(jobRank)",
"%s)\\n' % (names[column], column+1, value)) else: pass globalSatisfaction = 100*(1-(total/(l*minSuitability)))",
"as f: reader = csv.reader(f) candidatesAll = list(reader) \"\"\"create empty",
"b in zip(output, postCode): # jobScore = (rank,b) # list(jobScore)",
"= 0 qs_candidates = 0 vs_candidates = 0 f =",
"of score output = [0] * len(a) for i, x",
"correct = [1,3,5,9,10,2,4,8,6,7] #this function tests output above against Excel:",
"value > minSuitability*0.1: vs_candidates += 1 total += value check.append(column+1)",
"#print(posting[0].anchor) #print(posting) #print(candidatesAll) #print(postingsAll) #print(postingsAll[0].name) #print(preferences) #print(postings) #split up files",
"import default_timer as timer import csv import numpy as np",
"totalMatrix.append(matchDept(posting,candidate) + matchAnchor(posting,candidate) +matchLocation(posting,candidate) + matchCompetency(posting,candidate) + matchSkill(posting,candidate)+matchCohort(posting,candidate)) n +=",
"value > minSuitability*0.9: tenpc_candidates += 1 elif value > minSuitability*0.75:",
"postSecurity = [lists[10] for lists in postings] #with open('/Users/Jonathan/Google Drive/CPD/Python/candidates.csv','r')",
"minSuitability*0.1: vs_candidates += 1 total += value check.append(column+1) result.append((row,column)) f.write('For",
"= [lists[2] for lists in postings] postSkills = [lists[3:5] for",
"= [] totalMatrix = [] for list in candidatesAll: candidate",
"medium_candidates = 0 tenpc_candidates = 0 qs_candidates = 0 vs_candidates",
"\"\"\"create empty lists to fill with lists of lists output",
"len(names) names.extend([0] * (n-l)) totalMatrix.extend([0] * (n**2 - len(totalMatrix))) totalMatrix",
"#print(topMatrix) np.savetxt('/Users/java_jonathan/test.csv',topMatrix, fmt='%s', delimiter=',', newline='\\n', header='', footer='', comments='# ') np.savetxt('/Users/java_jonathan/test2.csv',totalMatrix,",
"postings] postSecurity = [lists[10] for lists in postings] #with open('/Users/Jonathan/Google",
"globalSatisfaction) print('Candidates who are more than 90%% suitable: %d' %",
"file') c_file = filedialog.askopenfilename(title='Please select the candidate file') \"\"\"for use",
"[Posting(*postingsAll)] #print(posting[0].anchor) #print(posting) #print(candidatesAll) #print(postingsAll) #print(postingsAll[0].name) #print(preferences) #print(postings) #split up",
"value > minSuitability/2: unhappy_candidates += 1 elif value > minSuitability*0.25:",
"file: \") # p_file = p_file.strip() # c_file = raw_input(\"Please",
"= 0 for list in postingsAll: posting = Posting(*list) totalMatrix.append(matchDept(posting,candidate)",
"#print(a) #converts 1D matrix to list for ease a =",
"this matrix:') total = 0.0 unhappy_candidates = 0 medium_candidates =",
"ie candidate a a=totalMatrix[:,[0]] #b = totalMatrix[:,[0]] #print(a) #converts 1D",
"= topFive(names,totalMatrix) #print(topMatrix) np.savetxt('/Users/java_jonathan/test.csv',topMatrix, fmt='%s', delimiter=',', newline='\\n', header='', footer='', comments='#",
"= Munkres() indexes = m.compute(totalMatrix) #print_matrix(totalMatrix, msg='Lowest cost through this",
"and appends to list jobRank = [] # for rank,",
"sorted(jobRank, reverse=False) # print(jobRank) # print('For candidate a, the best",
"the postings file: \") # p_file = p_file.strip() # c_file",
"%d' % medium_candidates) print('Candidates who are more than 90%% unsuitable:",
"import csv import numpy as np import itertools from munkres",
"print_matrix, make_cost_matrix import sys from classes import * from functions",
"list(jobScore) # jobRank.append(jobScore) # print(jobRank) output = [0] * len(a)",
"a[y])): output[x] = i print(output) # #print(a) # jobRank =",
"raw_input(\"Please enter the path for the postings file: \") #",
"with lists of lists output by iterating function below\"\"\" names",
"and jobs across totalMatrix = np.transpose(totalMatrix) #now it's switched! totalMatrix",
"lists in postings] #with open('/Users/Jonathan/Google Drive/CPD/Python/candidates.csv','r') as f: #gives first",
"are more than 50%% suitable: %d' % (l-unhappy_candidates)) print('Candidates who",
"elif value > minSuitability/2: unhappy_candidates += 1 elif value >",
"%d' % vs_candidates) print('Candidates who are more than 75%% suitable:",
"indexes: if column < l: value = totalMatrix[row][column] if value",
"= tk.Tk() root.withdraw() p_file = filedialog.askopenfilename(title='Please select the posting file')",
"fmt='%s', delimiter=',', newline='\\n', header='', footer='', comments='# ') np.savetxt('/Users/java_jonathan/test2.csv',totalMatrix, fmt='%s', delimiter=',',",
"list called output containing rank of score output = [0]",
"list(reader) \"\"\"create empty lists to fill with lists of lists",
"called output containing rank of score output = [0] *",
"import itertools from munkres import Munkres, print_matrix, make_cost_matrix import sys",
"fmt='%s', delimiter=',', newline='\\n', header='', footer='', comments='# ') end = timer()",
"1 l = len(names) names.extend([0] * (n-l)) totalMatrix.extend([0] * (n**2",
"import Munkres, print_matrix, make_cost_matrix import sys from classes import *",
"who are more than 75%% unsuitable: %d' % medium_candidates) print('Candidates",
"end = timer() print(end-start) \"\"\" #posting = [Posting(*postingsAll)] #print(posting[0].anchor) #print(posting)",
"= [lists[1] for lists in postings] postAnchor = [lists[2] for",
"to list for ease a = np.array(a).tolist() #print(a) #creates list",
"print(jobRank) output = [0] * len(a) for i, x in",
"%d (score %s)\\n' % (names[column], column+1, value)) else: pass globalSatisfaction",
"+= 1 elif value > minSuitability/2: unhappy_candidates += 1 elif",
"> minSuitability*0.25: qs_candidates += 1 elif value > minSuitability*0.1: vs_candidates",
"Candidate(*list) names.append(candidate.name) n = 0 for list in postingsAll: posting",
"in candidatesAll: candidate = Candidate(*list) names.append(candidate.name) n = 0 for",
"% globalSatisfaction) print('Candidates who are more than 90%% suitable: %d'",
"totalMatrix[:,[0]] #print(a) #converts 1D matrix to list for ease a",
"from __future__ import division from timeit import default_timer as timer",
"open('output.txt', 'w') for row, column in indexes: if column <",
"files into relative blocks postCode = [lists[0] for lists in",
"postAnchor = [lists[2] for lists in postings] postSkills = [lists[3:5]",
"y: a[y])): output[x] = i print(output) #creates tuples of rank,",
"qs_candidates = 0 vs_candidates = 0 f = open('output.txt', 'w')",
"print('Global satisfaction: %.2f%%' % globalSatisfaction) print('Candidates who are more than",
"np.reshape(totalMatrix,(n,-1)) #at this point the matrix is structured as candidates",
"1 elif value > minSuitability*0.75: medium_candidates += 1 elif value",
"# #print(a) # jobRank = sorted(jobRank, reverse=False) # print(jobRank) #",
"+= 1 elif value > minSuitability*0.75: medium_candidates += 1 elif",
"(score %s)\\n' % (names[column], column+1, value)) else: pass globalSatisfaction =",
"totalMatrix = [] for list in candidatesAll: candidate = Candidate(*list)",
"c_file = c_file.strip() start = timer() with open(p_file,'r') as f:",
"in postingsAll: posting = Posting(*list) totalMatrix.append(matchDept(posting,candidate) + matchAnchor(posting,candidate) +matchLocation(posting,candidate) +",
"minSuitability/2: unhappy_candidates += 1 elif value > minSuitability*0.25: qs_candidates +=",
"from timeit import default_timer as timer import csv import numpy",
"18 check = [] result = [] m = Munkres()",
"Munkres() indexes = m.compute(totalMatrix) #print_matrix(totalMatrix, msg='Lowest cost through this matrix:')",
"column < l: value = totalMatrix[row][column] if value > minSuitability*0.9:",
"in postings] postDept = [lists[1] for lists in postings] postAnchor",
"#creates list called output containing rank of score output =",
"check = [] result = [] m = Munkres() indexes",
"the best position is %s') % (jobRank[0][1]) # print(candidate[0].skills) \"\"\"",
"is structured as candidates down and jobs across totalMatrix =",
"a[y])): output[x] = i print(output) #creates tuples of rank, job",
"enter the path for the postings file: \") # p_file",
"= c_file.strip() start = timer() with open(p_file,'r') as f: #with",
"rank, b in zip(output, postCode): # jobScore = (rank,b) #",
"enumerate(sorted(range(len(a)), key=lambda y: a[y])): output[x] = i print(output) # #print(a)",
"in postings] postSecurity = [lists[10] for lists in postings] #with",
"1 elif value > minSuitability*0.1: vs_candidates += 1 total +=",
"\") # c_file = c_file.strip() start = timer() with open(p_file,'r')",
"root = tk.Tk() root.withdraw() p_file = filedialog.askopenfilename(title='Please select the posting",
"#print(a) # jobRank = sorted(jobRank, reverse=False) # print(jobRank) # print('For",
"np.array(a).tolist() #print(a) #creates list called output containing rank of score",
"(rank,b) # list(jobScore) # jobRank.append(jobScore) # print(jobRank) output = [0]",
"than 75%% unsuitable: %d' % medium_candidates) print('Candidates who are more",
"reader = csv.reader(f) postingsAll = list(reader) with open(c_file,'r') as f:",
"filedialog.askopenfilename(title='Please select the posting file') c_file = filedialog.askopenfilename(title='Please select the",
"= [lists[5] for lists in postings] postCompetencies = [lists[7:10] for",
"more than 90%% suitable: %d' % vs_candidates) print('Candidates who are",
"candidate a, the best position is %s') % (jobRank[0][1]) #",
"(names[column], column+1, value)) else: pass globalSatisfaction = 100*(1-(total/(l*minSuitability))) print('Global satisfaction:",
"import numpy as np import itertools from munkres import Munkres,",
"of lists output by iterating function below\"\"\" names = []",
"= np.reshape(totalMatrix,(n,-1)) #at this point the matrix is structured as",
"\\nOptimal position: %d (score %s)\\n' % (names[column], column+1, value)) else:",
"suitable: %d' % (l-unhappy_candidates)) print('Candidates who are more than 75%%",
"0 qs_candidates = 0 vs_candidates = 0 f = open('output.txt',",
"jobRank = sorted(jobRank, reverse=False) # print(jobRank) # print('For candidate a,",
"msg='Lowest cost through this matrix:') total = 0.0 unhappy_candidates =",
"for list in postingsAll: posting = Posting(*list) totalMatrix.append(matchDept(posting,candidate) + matchAnchor(posting,candidate)",
"for i, x in enumerate(sorted(range(len(a)), key=lambda y: a[y])): output[x] =",
"postings] postSkills = [lists[3:5] for lists in postings] postLocation =",
"c_file.strip() start = timer() with open(p_file,'r') as f: #with open('/Users/Jonathan/Google",
"postDept = [lists[1] for lists in postings] postAnchor = [lists[2]",
"tk import tkFileDialog as filedialog root = tk.Tk() root.withdraw() p_file",
"= 18 check = [] result = [] m =",
"sys from classes import * from functions import * from",
"0 vs_candidates = 0 f = open('output.txt', 'w') for row,",
"lists in postings] postDept = [lists[1] for lists in postings]",
"header='', footer='', comments='# ') end = timer() print(end-start) \"\"\" #posting",
"= [lists[3:5] for lists in postings] postLocation = [lists[5] for",
"a, the best position is %s') % (jobRank[0][1]) # print(candidate[0].skills)",
"lists in postings] postCompetencies = [lists[7:10] for lists in postings]",
"matchSkill(posting,candidate)+matchCohort(posting,candidate)) n += 1 l = len(names) names.extend([0] * (n-l))",
"np import itertools from munkres import Munkres, print_matrix, make_cost_matrix import",
"math import sqrt import Tkinter as tk import tkFileDialog as",
"postings] postCompetencies = [lists[7:10] for lists in postings] postSecurity =",
"[] result = [] m = Munkres() indexes = m.compute(totalMatrix)",
"0 f = open('output.txt', 'w') for row, column in indexes:",
"[lists[7:10] for lists in postings] postSecurity = [lists[10] for lists",
"%d' % (l-unhappy_candidates)) print('Candidates who are more than 75%% unsuitable:",
"% medium_candidates) print('Candidates who are more than 90%% unsuitable: %d'",
"f: #gives first column ie candidate a a=totalMatrix[:,[0]] #b =",
"as f: #gives first column ie candidate a a=totalMatrix[:,[0]] #b",
"enumerate(sorted(range(len(a)), key=lambda y: a[y])): output[x] = i print(output) #creates tuples",
"postSkills = [lists[3:5] for lists in postings] postLocation = [lists[5]",
"matchAnchor(posting,candidate) +matchLocation(posting,candidate) + matchCompetency(posting,candidate) + matchSkill(posting,candidate)+matchCohort(posting,candidate)) n += 1 l",
"Drive/CPD/Python/candidates.csv','r') as f: #gives first column ie candidate a a=totalMatrix[:,[0]]",
"[0] * len(a) for i, x in enumerate(sorted(range(len(a)), key=lambda y:",
"value check.append(column+1) result.append((row,column)) f.write('For candidate %s: \\nOptimal position: %d (score",
"np.asarray(totalMatrix) totalMatrix = np.reshape(totalMatrix,(n,-1)) #at this point the matrix is",
"point the matrix is structured as candidates down and jobs",
"+= 1 elif value > minSuitability*0.25: qs_candidates += 1 elif",
"# list(jobScore) # jobRank.append(jobScore) # print(jobRank) output = [0] *",
"+= 1 l = len(names) names.extend([0] * (n-l)) totalMatrix.extend([0] *",
"as f: reader = csv.reader(f) postingsAll = list(reader) with open(c_file,'r')",
"relative blocks postCode = [lists[0] for lists in postings] postDept",
"n += 1 l = len(names) names.extend([0] * (n-l)) totalMatrix.extend([0]",
"ease a = np.array(a).tolist() #print(a) #creates list called output containing",
"#print(candidatesAll) #print(postingsAll) #print(postingsAll[0].name) #print(preferences) #print(postings) #split up files into relative",
"= [] result = [] m = Munkres() indexes =",
"output containing rank of score output = [0] * len(a)",
"total = 0.0 unhappy_candidates = 0 medium_candidates = 0 tenpc_candidates",
"= (rank,b) # list(jobScore) # jobRank.append(jobScore) # print(jobRank) output =",
"from functions import * from math import sqrt import Tkinter",
"for row, column in indexes: if column < l: value",
"across totalMatrix = np.transpose(totalMatrix) #now it's switched! totalMatrix = np.subtract(np.amax(totalMatrix),totalMatrix)",
"value = totalMatrix[row][column] if value > minSuitability*0.9: tenpc_candidates += 1",
"75%% suitable: %d' % qs_candidates) print('Candidates who are more than",
"% (names[column], column+1, value)) else: pass globalSatisfaction = 100*(1-(total/(l*minSuitability))) print('Global",
"output by iterating function below\"\"\" names = [] totalMatrix =",
"make_cost_matrix import sys from classes import * from functions import",
"enter the path for the candidate file: \") # c_file",
"newline='\\n', header='', footer='', comments='# ') np.savetxt('/Users/java_jonathan/test2.csv',totalMatrix, fmt='%s', delimiter=',', newline='\\n', header='',",
"import division from timeit import default_timer as timer import csv",
"rank of score output = [0] * len(a) for i,",
"candidatesAll: candidate = Candidate(*list) names.append(candidate.name) n = 0 for list",
"#with open('/Users/Jonathan/Google Drive/CPD/Python/postings.csv','r') as f: reader = csv.reader(f) postingsAll =",
"function tests output above against Excel: #test(correct,check) topMatrix = topFive(names,totalMatrix)",
"postCode = [lists[0] for lists in postings] postDept = [lists[1]",
"tests output above against Excel: #test(correct,check) topMatrix = topFive(names,totalMatrix) #print(topMatrix)",
"# print(jobRank) output = [0] * len(a) for i, x",
"minSuitability*0.9: tenpc_candidates += 1 elif value > minSuitability*0.75: medium_candidates +=",
"= raw_input(\"Please enter the path for the postings file: \")",
"for lists in postings] postSkills = [lists[3:5] for lists in",
"output[x] = i print(output) # #print(a) # jobRank = sorted(jobRank,",
"select the posting file') c_file = filedialog.askopenfilename(title='Please select the candidate",
"the path for the candidate file: \") # c_file =",
"print('Candidates who are more than 75%% unsuitable: %d' % medium_candidates)",
"than 90%% suitable: %d' % vs_candidates) print('Candidates who are more",
"are more than 90%% suitable: %d' % vs_candidates) print('Candidates who",
"\"\"\"for use with /users/java_jonathan/postings_lge.csv and /Users/java_jonathan/candidates_lge.csv\"\"\" # p_file = raw_input(\"Please",
"path for the postings file: \") # p_file = p_file.strip()",
"= [Posting(*postingsAll)] #print(posting[0].anchor) #print(posting) #print(candidatesAll) #print(postingsAll) #print(postingsAll[0].name) #print(preferences) #print(postings) #split",
"* from math import sqrt import Tkinter as tk import",
"= len(names) names.extend([0] * (n-l)) totalMatrix.extend([0] * (n**2 - len(totalMatrix)))",
"the matrix is structured as candidates down and jobs across",
"are more than 75%% suitable: %d' % qs_candidates) print('Candidates who",
"totalMatrix = np.transpose(totalMatrix) #now it's switched! totalMatrix = np.subtract(np.amax(totalMatrix),totalMatrix) totalMatrix",
"else: pass globalSatisfaction = 100*(1-(total/(l*minSuitability))) print('Global satisfaction: %.2f%%' % globalSatisfaction)",
"the path for the postings file: \") # p_file =",
"# print(jobRank) # print('For candidate a, the best position is",
"totalMatrix.extend([0] * (n**2 - len(totalMatrix))) totalMatrix = np.asarray(totalMatrix) totalMatrix =",
"rank, job and appends to list jobRank = [] #",
"= [1,3,5,9,10,2,4,8,6,7] #this function tests output above against Excel: #test(correct,check)",
"= csv.reader(f) postingsAll = list(reader) with open(c_file,'r') as f: reader",
"postings file: \") # p_file = p_file.strip() # c_file =",
"vs_candidates = 0 f = open('output.txt', 'w') for row, column",
"tenpc_candidates = 0 qs_candidates = 0 vs_candidates = 0 f",
"candidate a a=totalMatrix[:,[0]] #b = totalMatrix[:,[0]] #print(a) #converts 1D matrix",
"= [0] * len(a) for i, x in enumerate(sorted(range(len(a)), key=lambda",
"[lists[5] for lists in postings] postCompetencies = [lists[7:10] for lists",
"#print_matrix(totalMatrix, msg='Lowest cost through this matrix:') total = 0.0 unhappy_candidates",
"column ie candidate a a=totalMatrix[:,[0]] #b = totalMatrix[:,[0]] #print(a) #converts",
"candidate file') \"\"\"for use with /users/java_jonathan/postings_lge.csv and /Users/java_jonathan/candidates_lge.csv\"\"\" # p_file",
"= np.subtract(np.amax(totalMatrix),totalMatrix) totalMatrix = np.array(totalMatrix) minSuitability = 18 check =",
"names.append(candidate.name) n = 0 for list in postingsAll: posting =",
"value > minSuitability*0.75: medium_candidates += 1 elif value > minSuitability/2:",
"for the postings file: \") # p_file = p_file.strip() #",
"= totalMatrix[row][column] if value > minSuitability*0.9: tenpc_candidates += 1 elif",
"open('/Users/Jonathan/Google Drive/CPD/Python/postings.csv','r') as f: reader = csv.reader(f) postingsAll = list(reader)",
"for lists in postings] postSecurity = [lists[10] for lists in",
"= open('output.txt', 'w') for row, column in indexes: if column",
"Excel: #test(correct,check) topMatrix = topFive(names,totalMatrix) #print(topMatrix) np.savetxt('/Users/java_jonathan/test.csv',topMatrix, fmt='%s', delimiter=',', newline='\\n',",
"matchCompetency(posting,candidate) + matchSkill(posting,candidate)+matchCohort(posting,candidate)) n += 1 l = len(names) names.extend([0]",
"* from functions import * from math import sqrt import",
"= [lists[0] for lists in postings] postDept = [lists[1] for",
"print('Candidates who are more than 90%% suitable: %d' % vs_candidates)",
"p_file = p_file.strip() # c_file = raw_input(\"Please enter the path",
"header='', footer='', comments='# ') np.savetxt('/Users/java_jonathan/test2.csv',totalMatrix, fmt='%s', delimiter=',', newline='\\n', header='', footer='',",
"for lists in postings] postCompetencies = [lists[7:10] for lists in",
"postLocation = [lists[5] for lists in postings] postCompetencies = [lists[7:10]",
"f: #with open('/Users/Jonathan/Google Drive/CPD/Python/postings.csv','r') as f: reader = csv.reader(f) postingsAll",
"function below\"\"\" names = [] totalMatrix = [] for list",
"= np.asarray(totalMatrix) totalMatrix = np.reshape(totalMatrix,(n,-1)) #at this point the matrix",
"above against Excel: #test(correct,check) topMatrix = topFive(names,totalMatrix) #print(topMatrix) np.savetxt('/Users/java_jonathan/test.csv',topMatrix, fmt='%s',",
"[lists[2] for lists in postings] postSkills = [lists[3:5] for lists",
"unsuitable: %d' % medium_candidates) print('Candidates who are more than 90%%",
"medium_candidates += 1 elif value > minSuitability/2: unhappy_candidates += 1",
"lists in postings] postAnchor = [lists[2] for lists in postings]",
"f: reader = csv.reader(f) postingsAll = list(reader) with open(c_file,'r') as",
"from math import sqrt import Tkinter as tk import tkFileDialog",
"np.transpose(totalMatrix) #now it's switched! totalMatrix = np.subtract(np.amax(totalMatrix),totalMatrix) totalMatrix = np.array(totalMatrix)",
"suitable: %d' % qs_candidates) print('Candidates who are more than 50%%",
"posting file') c_file = filedialog.askopenfilename(title='Please select the candidate file') \"\"\"for",
"who are more than 90%% unsuitable: %d' % tenpc_candidates) #output",
"a = np.array(a).tolist() #print(a) #creates list called output containing rank",
"minSuitability = 18 check = [] result = [] m",
"as filedialog root = tk.Tk() root.withdraw() p_file = filedialog.askopenfilename(title='Please select",
"* (n**2 - len(totalMatrix))) totalMatrix = np.asarray(totalMatrix) totalMatrix = np.reshape(totalMatrix,(n,-1))",
"jobScore = (rank,b) # list(jobScore) # jobRank.append(jobScore) # print(jobRank) output",
"% (l-unhappy_candidates)) print('Candidates who are more than 75%% unsuitable: %d'",
"value > minSuitability*0.25: qs_candidates += 1 elif value > minSuitability*0.1:",
"# jobScore = (rank,b) # list(jobScore) # jobRank.append(jobScore) # print(jobRank)",
"itertools from munkres import Munkres, print_matrix, make_cost_matrix import sys from",
"munkres import Munkres, print_matrix, make_cost_matrix import sys from classes import",
"print('Candidates who are more than 90%% unsuitable: %d' % tenpc_candidates)",
"elif value > minSuitability*0.25: qs_candidates += 1 elif value >",
"#print(postingsAll[0].name) #print(preferences) #print(postings) #split up files into relative blocks postCode",
"%s: \\nOptimal position: %d (score %s)\\n' % (names[column], column+1, value))",
"csv import numpy as np import itertools from munkres import",
"candidates down and jobs across totalMatrix = np.transpose(totalMatrix) #now it's",
"0 tenpc_candidates = 0 qs_candidates = 0 vs_candidates = 0",
"numpy as np import itertools from munkres import Munkres, print_matrix,",
"select the candidate file') \"\"\"for use with /users/java_jonathan/postings_lge.csv and /Users/java_jonathan/candidates_lge.csv\"\"\"",
"np.subtract(np.amax(totalMatrix),totalMatrix) totalMatrix = np.array(totalMatrix) minSuitability = 18 check = []",
"fill with lists of lists output by iterating function below\"\"\"",
"names.extend([0] * (n-l)) totalMatrix.extend([0] * (n**2 - len(totalMatrix))) totalMatrix =",
"if column < l: value = totalMatrix[row][column] if value >",
"+= 1 total += value check.append(column+1) result.append((row,column)) f.write('For candidate %s:",
"csv.reader(f) postingsAll = list(reader) with open(c_file,'r') as f: reader =",
"# print('For candidate a, the best position is %s') %",
"path for the candidate file: \") # c_file = c_file.strip()",
"zip(output, postCode): # jobScore = (rank,b) # list(jobScore) # jobRank.append(jobScore)",
"print(end-start) \"\"\" #posting = [Posting(*postingsAll)] #print(posting[0].anchor) #print(posting) #print(candidatesAll) #print(postingsAll) #print(postingsAll[0].name)",
"a=totalMatrix[:,[0]] #b = totalMatrix[:,[0]] #print(a) #converts 1D matrix to list",
"p_file = filedialog.askopenfilename(title='Please select the posting file') c_file = filedialog.askopenfilename(title='Please",
"into relative blocks postCode = [lists[0] for lists in postings]",
"+= value check.append(column+1) result.append((row,column)) f.write('For candidate %s: \\nOptimal position: %d",
"by iterating function below\"\"\" names = [] totalMatrix = []",
"with open(c_file,'r') as f: reader = csv.reader(f) candidatesAll = list(reader)",
"f: reader = csv.reader(f) candidatesAll = list(reader) \"\"\"create empty lists",
"= [] for list in candidatesAll: candidate = Candidate(*list) names.append(candidate.name)",
"#at this point the matrix is structured as candidates down",
"%d' % tenpc_candidates) #output from excel: correct = [1,3,5,9,10,2,4,8,6,7] #this",
"pass globalSatisfaction = 100*(1-(total/(l*minSuitability))) print('Global satisfaction: %.2f%%' % globalSatisfaction) print('Candidates",
"empty lists to fill with lists of lists output by",
"open(c_file,'r') as f: reader = csv.reader(f) candidatesAll = list(reader) \"\"\"create",
"default_timer as timer import csv import numpy as np import",
"+ matchCompetency(posting,candidate) + matchSkill(posting,candidate)+matchCohort(posting,candidate)) n += 1 l = len(names)",
"#now it's switched! totalMatrix = np.subtract(np.amax(totalMatrix),totalMatrix) totalMatrix = np.array(totalMatrix) minSuitability",
"key=lambda y: a[y])): output[x] = i print(output) # #print(a) #",
"import Tkinter as tk import tkFileDialog as filedialog root =",
"and /Users/java_jonathan/candidates_lge.csv\"\"\" # p_file = raw_input(\"Please enter the path for",
"vs_candidates += 1 total += value check.append(column+1) result.append((row,column)) f.write('For candidate",
"unsuitable: %d' % tenpc_candidates) #output from excel: correct = [1,3,5,9,10,2,4,8,6,7]",
"footer='', comments='# ') end = timer() print(end-start) \"\"\" #posting =",
"in zip(output, postCode): # jobScore = (rank,b) # list(jobScore) #",
"postCompetencies = [lists[7:10] for lists in postings] postSecurity = [lists[10]",
"= p_file.strip() # c_file = raw_input(\"Please enter the path for",
"i print(output) #creates tuples of rank, job and appends to",
"row, column in indexes: if column < l: value =",
"elif value > minSuitability*0.1: vs_candidates += 1 total += value",
"qs_candidates) print('Candidates who are more than 50%% suitable: %d' %",
"through this matrix:') total = 0.0 unhappy_candidates = 0 medium_candidates",
"total += value check.append(column+1) result.append((row,column)) f.write('For candidate %s: \\nOptimal position:",
"in postings] postLocation = [lists[5] for lists in postings] postCompetencies",
"= raw_input(\"Please enter the path for the candidate file: \")",
"> minSuitability*0.75: medium_candidates += 1 elif value > minSuitability/2: unhappy_candidates",
"= Posting(*list) totalMatrix.append(matchDept(posting,candidate) + matchAnchor(posting,candidate) +matchLocation(posting,candidate) + matchCompetency(posting,candidate) + matchSkill(posting,candidate)+matchCohort(posting,candidate))",
"first column ie candidate a a=totalMatrix[:,[0]] #b = totalMatrix[:,[0]] #print(a)",
"[] # for rank, b in zip(output, postCode): # jobScore",
"0 for list in postingsAll: posting = Posting(*list) totalMatrix.append(matchDept(posting,candidate) +",
"as tk import tkFileDialog as filedialog root = tk.Tk() root.withdraw()",
"= list(reader) with open(c_file,'r') as f: reader = csv.reader(f) candidatesAll"
] |
[
":: Python :: 3.7\", \"Programming Language :: Python :: Implementation",
"f: return f.read() META_FILE = read(META_PATH) def find_meta(meta): \"\"\"Extract __*meta*__",
"Build an absolute path from *parts* and and return the",
":: 3\", \"Programming Language :: Python :: 3.3\", \"Programming Language",
"English\", \"License :: OSI Approved :: MIT License\", \"Operating System",
"NAME = \"pysyrenn\" PACKAGES = [ \"syrenn_proto\", \"pysyrenn\", \"pysyrenn.frontend\", \"pysyrenn.helpers\",",
":: MIT License\", \"Operating System :: OS Independent\", \"Programming Language",
"\"\"\"Setup script for PySyReNN. Adapted from: https://hynek.me/articles/sharing-your-labor-of-love-pypi-quick-and-dirty/ \"\"\" import codecs",
"System :: OS Independent\", \"Programming Language :: Python\", \"Programming Language",
"\"pysyrenn.helpers\", ] META_PATH = \"__metadata__.py\" KEYWORDS = [\"class\", \"attribute\", \"boilerplate\"]",
"return f.read() META_FILE = read(META_PATH) def find_meta(meta): \"\"\"Extract __*meta*__ from",
":: 3.3\", \"Programming Language :: Python :: 3.4\", \"Programming Language",
"maintainer_email=find_meta(\"email\"), keywords=KEYWORDS, long_description=read(\"README.md\"), long_description_content_type=\"text/markdown\", packages=PACKAGES, package_dir={\"\": \".\"}, package_data={\"\": [\"pysyrenn/**/*.py\"]}, zip_safe=False,",
":: Python :: 3\", \"Programming Language :: Python :: 3.3\",",
"from: https://hynek.me/articles/sharing-your-labor-of-love-pypi-quick-and-dirty/ \"\"\" import codecs import os import re from",
"\"Programming Language :: Python :: 3.7\", \"Programming Language :: Python",
"line in requirements.readlines(): if line.startswith(\"# PYSYRENN\"): reading = True elif",
"reading = False elif line.startswith(\"#\"): pass elif reading: INSTALL_REQUIRES.append(line.strip().split(\"==\")[0]) ###################################################################",
"Language :: Python :: 3.6\", \"Programming Language :: Python ::",
"Python :: 3.4\", \"Programming Language :: Python :: 3.5\", \"Programming",
"Implementation :: CPython\", \"Programming Language :: Python :: Implementation ::",
"################################################################### NAME = \"pysyrenn\" PACKAGES = [ \"syrenn_proto\", \"pysyrenn\", \"pysyrenn.frontend\",",
"as requirements: reading = False for line in requirements.readlines(): if",
"setuptools import setup, find_packages ################################################################### NAME = \"pysyrenn\" PACKAGES =",
"Approved :: MIT License\", \"Operating System :: OS Independent\", \"Programming",
":: Python :: 3.5\", \"Programming Language :: Python :: 3.6\",",
":: Implementation :: PyPy\", \"Topic :: Software Development :: Libraries",
"INSTALL_REQUIRES.append(line.strip().split(\"==\")[0]) ################################################################### HERE = os.path.abspath(os.path.dirname(__file__)) def read(*parts): \"\"\" Build an",
"MIT License\", \"Operating System :: OS Independent\", \"Programming Language ::",
"os.path.abspath(os.path.dirname(__file__)) def read(*parts): \"\"\" Build an absolute path from *parts*",
"to find __{meta}__ string.\".format(meta=meta)) if __name__ == \"__main__\": setup( name=NAME,",
"reading = True elif line.startswith(\"# END\"): reading = False elif",
"Language :: Python :: 2.7\", \"Programming Language :: Python ::",
"\"utf-8\") as f: return f.read() META_FILE = read(META_PATH) def find_meta(meta):",
"an absolute path from *parts* and and return the contents",
"line.startswith(\"#\"): pass elif reading: INSTALL_REQUIRES.append(line.strip().split(\"==\")[0]) ################################################################### HERE = os.path.abspath(os.path.dirname(__file__)) def",
"CLASSIFIERS = [ \"Development Status :: 5 - Production/Stable\", \"Intended",
"\"License :: OSI Approved :: MIT License\", \"Operating System ::",
"Language :: Python :: 3\", \"Programming Language :: Python ::",
"Developers\", \"Natural Language :: English\", \"License :: OSI Approved ::",
"\"Programming Language :: Python :: 3.6\", \"Programming Language :: Python",
":: Python :: 2\", \"Programming Language :: Python :: 2.7\",",
"*parts), \"rb\", \"utf-8\") as f: return f.read() META_FILE = read(META_PATH)",
"raise RuntimeError(\"Unable to find __{meta}__ string.\".format(meta=meta)) if __name__ == \"__main__\":",
"= os.path.abspath(os.path.dirname(__file__)) def read(*parts): \"\"\" Build an absolute path from",
"PyPy\", \"Topic :: Software Development :: Libraries :: Python Modules\",",
"from META_FILE. \"\"\" meta_match = re.search( r\"^__{meta}__ = ['\\\"]([^'\\\"]*)['\\\"]\".format(meta=meta), META_FILE,",
"Language :: Python :: 3.4\", \"Programming Language :: Python ::",
"\"pysyrenn\" PACKAGES = [ \"syrenn_proto\", \"pysyrenn\", \"pysyrenn.frontend\", \"pysyrenn.helpers\", ] META_PATH",
"= \"__metadata__.py\" KEYWORDS = [\"class\", \"attribute\", \"boilerplate\"] CLASSIFIERS = [",
"from setuptools import setup, find_packages ################################################################### NAME = \"pysyrenn\" PACKAGES",
"Adapted from: https://hynek.me/articles/sharing-your-labor-of-love-pypi-quick-and-dirty/ \"\"\" import codecs import os import re",
"\"__metadata__.py\" KEYWORDS = [\"class\", \"attribute\", \"boilerplate\"] CLASSIFIERS = [ \"Development",
":: 3.7\", \"Programming Language :: Python :: Implementation :: CPython\",",
"\"\"\" Build an absolute path from *parts* and and return",
"RuntimeError(\"Unable to find __{meta}__ string.\".format(meta=meta)) if __name__ == \"__main__\": setup(",
":: Software Development :: Libraries :: Python Modules\", ] INSTALL_REQUIRES",
"[\"torch\"] with open(\"requirements.txt\") as requirements: reading = False for line",
"Implementation :: PyPy\", \"Topic :: Software Development :: Libraries ::",
"elif line.startswith(\"# END\"): reading = False elif line.startswith(\"#\"): pass elif",
"find_meta(meta): \"\"\"Extract __*meta*__ from META_FILE. \"\"\" meta_match = re.search( r\"^__{meta}__",
"KEYWORDS = [\"class\", \"attribute\", \"boilerplate\"] CLASSIFIERS = [ \"Development Status",
"= [ \"syrenn_proto\", \"pysyrenn\", \"pysyrenn.frontend\", \"pysyrenn.helpers\", ] META_PATH = \"__metadata__.py\"",
":: Developers\", \"Natural Language :: English\", \"License :: OSI Approved",
"of the resulting file. Assume UTF-8 encoding. \"\"\" with codecs.open(os.path.join(HERE,",
"Production/Stable\", \"Intended Audience :: Developers\", \"Natural Language :: English\", \"License",
":: PyPy\", \"Topic :: Software Development :: Libraries :: Python",
"def find_meta(meta): \"\"\"Extract __*meta*__ from META_FILE. \"\"\" meta_match = re.search(",
"Language :: Python :: 2\", \"Programming Language :: Python ::",
"Python :: 3.3\", \"Programming Language :: Python :: 3.4\", \"Programming",
"Language :: Python :: Implementation :: PyPy\", \"Topic :: Software",
"Development :: Libraries :: Python Modules\", ] INSTALL_REQUIRES = [\"torch\"]",
"return meta_match.group(1) raise RuntimeError(\"Unable to find __{meta}__ string.\".format(meta=meta)) if __name__",
"meta_match.group(1) raise RuntimeError(\"Unable to find __{meta}__ string.\".format(meta=meta)) if __name__ ==",
":: 3.6\", \"Programming Language :: Python :: 3.7\", \"Programming Language",
"in requirements.readlines(): if line.startswith(\"# PYSYRENN\"): reading = True elif line.startswith(\"#",
"Modules\", ] INSTALL_REQUIRES = [\"torch\"] with open(\"requirements.txt\") as requirements: reading",
"maintainer=find_meta(\"author\"), maintainer_email=find_meta(\"email\"), keywords=KEYWORDS, long_description=read(\"README.md\"), long_description_content_type=\"text/markdown\", packages=PACKAGES, package_dir={\"\": \".\"}, package_data={\"\": [\"pysyrenn/**/*.py\"]},",
"INSTALL_REQUIRES = [\"torch\"] with open(\"requirements.txt\") as requirements: reading = False",
"for line in requirements.readlines(): if line.startswith(\"# PYSYRENN\"): reading = True",
"Language :: Python\", \"Programming Language :: Python :: 2\", \"Programming",
"END\"): reading = False elif line.startswith(\"#\"): pass elif reading: INSTALL_REQUIRES.append(line.strip().split(\"==\")[0])",
"Python :: Implementation :: CPython\", \"Programming Language :: Python ::",
"5 - Production/Stable\", \"Intended Audience :: Developers\", \"Natural Language ::",
"\"Programming Language :: Python\", \"Programming Language :: Python :: 2\",",
":: Python Modules\", ] INSTALL_REQUIRES = [\"torch\"] with open(\"requirements.txt\") as",
"find __{meta}__ string.\".format(meta=meta)) if __name__ == \"__main__\": setup( name=NAME, description=find_meta(\"description\"),",
"Assume UTF-8 encoding. \"\"\" with codecs.open(os.path.join(HERE, *parts), \"rb\", \"utf-8\") as",
"encoding. \"\"\" with codecs.open(os.path.join(HERE, *parts), \"rb\", \"utf-8\") as f: return",
"__{meta}__ string.\".format(meta=meta)) if __name__ == \"__main__\": setup( name=NAME, description=find_meta(\"description\"), license=find_meta(\"license\"),",
"\"Programming Language :: Python :: 3.4\", \"Programming Language :: Python",
"Language :: Python :: 3.7\", \"Programming Language :: Python ::",
"open(\"requirements.txt\") as requirements: reading = False for line in requirements.readlines():",
"Audience :: Developers\", \"Natural Language :: English\", \"License :: OSI",
"license=find_meta(\"license\"), url=find_meta(\"uri\"), version=find_meta(\"version\"), author=find_meta(\"author\"), author_email=find_meta(\"email\"), maintainer=find_meta(\"author\"), maintainer_email=find_meta(\"email\"), keywords=KEYWORDS, long_description=read(\"README.md\"), long_description_content_type=\"text/markdown\",",
"\"Operating System :: OS Independent\", \"Programming Language :: Python\", \"Programming",
"\"Programming Language :: Python :: 3\", \"Programming Language :: Python",
"line.startswith(\"# PYSYRENN\"): reading = True elif line.startswith(\"# END\"): reading =",
"\"rb\", \"utf-8\") as f: return f.read() META_FILE = read(META_PATH) def",
":: Implementation :: CPython\", \"Programming Language :: Python :: Implementation",
"url=find_meta(\"uri\"), version=find_meta(\"version\"), author=find_meta(\"author\"), author_email=find_meta(\"email\"), maintainer=find_meta(\"author\"), maintainer_email=find_meta(\"email\"), keywords=KEYWORDS, long_description=read(\"README.md\"), long_description_content_type=\"text/markdown\", packages=PACKAGES,",
"META_PATH = \"__metadata__.py\" KEYWORDS = [\"class\", \"attribute\", \"boilerplate\"] CLASSIFIERS =",
"return the contents of the resulting file. Assume UTF-8 encoding.",
":: 2\", \"Programming Language :: Python :: 2.7\", \"Programming Language",
"2.7\", \"Programming Language :: Python :: 3\", \"Programming Language ::",
"\"syrenn_proto\", \"pysyrenn\", \"pysyrenn.frontend\", \"pysyrenn.helpers\", ] META_PATH = \"__metadata__.py\" KEYWORDS =",
"description=find_meta(\"description\"), license=find_meta(\"license\"), url=find_meta(\"uri\"), version=find_meta(\"version\"), author=find_meta(\"author\"), author_email=find_meta(\"email\"), maintainer=find_meta(\"author\"), maintainer_email=find_meta(\"email\"), keywords=KEYWORDS, long_description=read(\"README.md\"),",
"META_FILE = read(META_PATH) def find_meta(meta): \"\"\"Extract __*meta*__ from META_FILE. \"\"\"",
"__name__ == \"__main__\": setup( name=NAME, description=find_meta(\"description\"), license=find_meta(\"license\"), url=find_meta(\"uri\"), version=find_meta(\"version\"), author=find_meta(\"author\"),",
"Python\", \"Programming Language :: Python :: 2\", \"Programming Language ::",
":: Libraries :: Python Modules\", ] INSTALL_REQUIRES = [\"torch\"] with",
"= \"pysyrenn\" PACKAGES = [ \"syrenn_proto\", \"pysyrenn\", \"pysyrenn.frontend\", \"pysyrenn.helpers\", ]",
"string.\".format(meta=meta)) if __name__ == \"__main__\": setup( name=NAME, description=find_meta(\"description\"), license=find_meta(\"license\"), url=find_meta(\"uri\"),",
"Python :: 3.5\", \"Programming Language :: Python :: 3.6\", \"Programming",
"meta_match: return meta_match.group(1) raise RuntimeError(\"Unable to find __{meta}__ string.\".format(meta=meta)) if",
"resulting file. Assume UTF-8 encoding. \"\"\" with codecs.open(os.path.join(HERE, *parts), \"rb\",",
"\"Intended Audience :: Developers\", \"Natural Language :: English\", \"License ::",
"import setup, find_packages ################################################################### NAME = \"pysyrenn\" PACKAGES = [",
"= True elif line.startswith(\"# END\"): reading = False elif line.startswith(\"#\"):",
"= [\"class\", \"attribute\", \"boilerplate\"] CLASSIFIERS = [ \"Development Status ::",
"elif reading: INSTALL_REQUIRES.append(line.strip().split(\"==\")[0]) ################################################################### HERE = os.path.abspath(os.path.dirname(__file__)) def read(*parts): \"\"\"",
"with codecs.open(os.path.join(HERE, *parts), \"rb\", \"utf-8\") as f: return f.read() META_FILE",
"import re from setuptools import setup, find_packages ################################################################### NAME =",
"2\", \"Programming Language :: Python :: 2.7\", \"Programming Language ::",
"Software Development :: Libraries :: Python Modules\", ] INSTALL_REQUIRES =",
"True elif line.startswith(\"# END\"): reading = False elif line.startswith(\"#\"): pass",
"\"\"\"Extract __*meta*__ from META_FILE. \"\"\" meta_match = re.search( r\"^__{meta}__ =",
"os import re from setuptools import setup, find_packages ################################################################### NAME",
"3.3\", \"Programming Language :: Python :: 3.4\", \"Programming Language ::",
"\"Programming Language :: Python :: Implementation :: PyPy\", \"Topic ::",
":: 3.5\", \"Programming Language :: Python :: 3.6\", \"Programming Language",
"Python :: 3\", \"Programming Language :: Python :: 3.3\", \"Programming",
"codecs.open(os.path.join(HERE, *parts), \"rb\", \"utf-8\") as f: return f.read() META_FILE =",
":: Python :: 3.6\", \"Programming Language :: Python :: 3.7\",",
"Status :: 5 - Production/Stable\", \"Intended Audience :: Developers\", \"Natural",
"Python :: 2\", \"Programming Language :: Python :: 2.7\", \"Programming",
"\"Programming Language :: Python :: 3.3\", \"Programming Language :: Python",
"CPython\", \"Programming Language :: Python :: Implementation :: PyPy\", \"Topic",
"META_FILE. \"\"\" meta_match = re.search( r\"^__{meta}__ = ['\\\"]([^'\\\"]*)['\\\"]\".format(meta=meta), META_FILE, re.M",
"from *parts* and and return the contents of the resulting",
"[ \"Development Status :: 5 - Production/Stable\", \"Intended Audience ::",
"- Production/Stable\", \"Intended Audience :: Developers\", \"Natural Language :: English\",",
"path from *parts* and and return the contents of the",
") if meta_match: return meta_match.group(1) raise RuntimeError(\"Unable to find __{meta}__",
"and return the contents of the resulting file. Assume UTF-8",
"PYSYRENN\"): reading = True elif line.startswith(\"# END\"): reading = False",
"= ['\\\"]([^'\\\"]*)['\\\"]\".format(meta=meta), META_FILE, re.M ) if meta_match: return meta_match.group(1) raise",
":: Python\", \"Programming Language :: Python :: 2\", \"Programming Language",
"Language :: Python :: 3.5\", \"Programming Language :: Python ::",
"contents of the resulting file. Assume UTF-8 encoding. \"\"\" with",
":: CPython\", \"Programming Language :: Python :: Implementation :: PyPy\",",
"HERE = os.path.abspath(os.path.dirname(__file__)) def read(*parts): \"\"\" Build an absolute path",
"read(*parts): \"\"\" Build an absolute path from *parts* and and",
"Python :: Implementation :: PyPy\", \"Topic :: Software Development ::",
":: Python :: 3.3\", \"Programming Language :: Python :: 3.4\",",
"\"Programming Language :: Python :: Implementation :: CPython\", \"Programming Language",
"reading: INSTALL_REQUIRES.append(line.strip().split(\"==\")[0]) ################################################################### HERE = os.path.abspath(os.path.dirname(__file__)) def read(*parts): \"\"\" Build",
"\"\"\" meta_match = re.search( r\"^__{meta}__ = ['\\\"]([^'\\\"]*)['\\\"]\".format(meta=meta), META_FILE, re.M )",
"Language :: English\", \"License :: OSI Approved :: MIT License\",",
"\"Programming Language :: Python :: 3.5\", \"Programming Language :: Python",
"################################################################### HERE = os.path.abspath(os.path.dirname(__file__)) def read(*parts): \"\"\" Build an absolute",
"keywords=KEYWORDS, long_description=read(\"README.md\"), long_description_content_type=\"text/markdown\", packages=PACKAGES, package_dir={\"\": \".\"}, package_data={\"\": [\"pysyrenn/**/*.py\"]}, zip_safe=False, classifiers=CLASSIFIERS,",
"\"Programming Language :: Python :: 2\", \"Programming Language :: Python",
"if meta_match: return meta_match.group(1) raise RuntimeError(\"Unable to find __{meta}__ string.\".format(meta=meta))",
"Language :: Python :: Implementation :: CPython\", \"Programming Language ::",
"requirements: reading = False for line in requirements.readlines(): if line.startswith(\"#",
"long_description=read(\"README.md\"), long_description_content_type=\"text/markdown\", packages=PACKAGES, package_dir={\"\": \".\"}, package_data={\"\": [\"pysyrenn/**/*.py\"]}, zip_safe=False, classifiers=CLASSIFIERS, install_requires=INSTALL_REQUIRES,",
"Python :: 3.6\", \"Programming Language :: Python :: 3.7\", \"Programming",
"re.M ) if meta_match: return meta_match.group(1) raise RuntimeError(\"Unable to find",
"\"__main__\": setup( name=NAME, description=find_meta(\"description\"), license=find_meta(\"license\"), url=find_meta(\"uri\"), version=find_meta(\"version\"), author=find_meta(\"author\"), author_email=find_meta(\"email\"), maintainer=find_meta(\"author\"),",
"Language :: Python :: 3.3\", \"Programming Language :: Python ::",
"if line.startswith(\"# PYSYRENN\"): reading = True elif line.startswith(\"# END\"): reading",
"['\\\"]([^'\\\"]*)['\\\"]\".format(meta=meta), META_FILE, re.M ) if meta_match: return meta_match.group(1) raise RuntimeError(\"Unable",
"= [ \"Development Status :: 5 - Production/Stable\", \"Intended Audience",
"import os import re from setuptools import setup, find_packages ###################################################################",
"\"Programming Language :: Python :: 2.7\", \"Programming Language :: Python",
"Independent\", \"Programming Language :: Python\", \"Programming Language :: Python ::",
"False elif line.startswith(\"#\"): pass elif reading: INSTALL_REQUIRES.append(line.strip().split(\"==\")[0]) ################################################################### HERE =",
":: Python :: Implementation :: PyPy\", \"Topic :: Software Development",
"] META_PATH = \"__metadata__.py\" KEYWORDS = [\"class\", \"attribute\", \"boilerplate\"] CLASSIFIERS",
"author=find_meta(\"author\"), author_email=find_meta(\"email\"), maintainer=find_meta(\"author\"), maintainer_email=find_meta(\"email\"), keywords=KEYWORDS, long_description=read(\"README.md\"), long_description_content_type=\"text/markdown\", packages=PACKAGES, package_dir={\"\": \".\"},",
"pass elif reading: INSTALL_REQUIRES.append(line.strip().split(\"==\")[0]) ################################################################### HERE = os.path.abspath(os.path.dirname(__file__)) def read(*parts):",
"3.7\", \"Programming Language :: Python :: Implementation :: CPython\", \"Programming",
"License\", \"Operating System :: OS Independent\", \"Programming Language :: Python\",",
"= False elif line.startswith(\"#\"): pass elif reading: INSTALL_REQUIRES.append(line.strip().split(\"==\")[0]) ################################################################### HERE",
"3.5\", \"Programming Language :: Python :: 3.6\", \"Programming Language ::",
"meta_match = re.search( r\"^__{meta}__ = ['\\\"]([^'\\\"]*)['\\\"]\".format(meta=meta), META_FILE, re.M ) if",
"elif line.startswith(\"#\"): pass elif reading: INSTALL_REQUIRES.append(line.strip().split(\"==\")[0]) ################################################################### HERE = os.path.abspath(os.path.dirname(__file__))",
"https://hynek.me/articles/sharing-your-labor-of-love-pypi-quick-and-dirty/ \"\"\" import codecs import os import re from setuptools",
":: 2.7\", \"Programming Language :: Python :: 3\", \"Programming Language",
"re from setuptools import setup, find_packages ################################################################### NAME = \"pysyrenn\"",
"\"boilerplate\"] CLASSIFIERS = [ \"Development Status :: 5 - Production/Stable\",",
"import codecs import os import re from setuptools import setup,",
"== \"__main__\": setup( name=NAME, description=find_meta(\"description\"), license=find_meta(\"license\"), url=find_meta(\"uri\"), version=find_meta(\"version\"), author=find_meta(\"author\"), author_email=find_meta(\"email\"),",
"re.search( r\"^__{meta}__ = ['\\\"]([^'\\\"]*)['\\\"]\".format(meta=meta), META_FILE, re.M ) if meta_match: return",
":: 5 - Production/Stable\", \"Intended Audience :: Developers\", \"Natural Language",
"\"Development Status :: 5 - Production/Stable\", \"Intended Audience :: Developers\",",
"Python :: 3.7\", \"Programming Language :: Python :: Implementation ::",
"*parts* and and return the contents of the resulting file.",
"OSI Approved :: MIT License\", \"Operating System :: OS Independent\",",
":: Python :: 2.7\", \"Programming Language :: Python :: 3\",",
"False for line in requirements.readlines(): if line.startswith(\"# PYSYRENN\"): reading =",
"file. Assume UTF-8 encoding. \"\"\" with codecs.open(os.path.join(HERE, *parts), \"rb\", \"utf-8\")",
"Libraries :: Python Modules\", ] INSTALL_REQUIRES = [\"torch\"] with open(\"requirements.txt\")",
"with open(\"requirements.txt\") as requirements: reading = False for line in",
"3\", \"Programming Language :: Python :: 3.3\", \"Programming Language ::",
"3.6\", \"Programming Language :: Python :: 3.7\", \"Programming Language ::",
"UTF-8 encoding. \"\"\" with codecs.open(os.path.join(HERE, *parts), \"rb\", \"utf-8\") as f:",
"= [\"torch\"] with open(\"requirements.txt\") as requirements: reading = False for",
"= read(META_PATH) def find_meta(meta): \"\"\"Extract __*meta*__ from META_FILE. \"\"\" meta_match",
"[\"class\", \"attribute\", \"boilerplate\"] CLASSIFIERS = [ \"Development Status :: 5",
"\"pysyrenn.frontend\", \"pysyrenn.helpers\", ] META_PATH = \"__metadata__.py\" KEYWORDS = [\"class\", \"attribute\",",
"\"Natural Language :: English\", \"License :: OSI Approved :: MIT",
"\"attribute\", \"boilerplate\"] CLASSIFIERS = [ \"Development Status :: 5 -",
":: 3.4\", \"Programming Language :: Python :: 3.5\", \"Programming Language",
"name=NAME, description=find_meta(\"description\"), license=find_meta(\"license\"), url=find_meta(\"uri\"), version=find_meta(\"version\"), author=find_meta(\"author\"), author_email=find_meta(\"email\"), maintainer=find_meta(\"author\"), maintainer_email=find_meta(\"email\"), keywords=KEYWORDS,",
"Python :: 2.7\", \"Programming Language :: Python :: 3\", \"Programming",
"version=find_meta(\"version\"), author=find_meta(\"author\"), author_email=find_meta(\"email\"), maintainer=find_meta(\"author\"), maintainer_email=find_meta(\"email\"), keywords=KEYWORDS, long_description=read(\"README.md\"), long_description_content_type=\"text/markdown\", packages=PACKAGES, package_dir={\"\":",
":: Python :: Implementation :: CPython\", \"Programming Language :: Python",
"requirements.readlines(): if line.startswith(\"# PYSYRENN\"): reading = True elif line.startswith(\"# END\"):",
"if __name__ == \"__main__\": setup( name=NAME, description=find_meta(\"description\"), license=find_meta(\"license\"), url=find_meta(\"uri\"), version=find_meta(\"version\"),",
"author_email=find_meta(\"email\"), maintainer=find_meta(\"author\"), maintainer_email=find_meta(\"email\"), keywords=KEYWORDS, long_description=read(\"README.md\"), long_description_content_type=\"text/markdown\", packages=PACKAGES, package_dir={\"\": \".\"}, package_data={\"\":",
"= False for line in requirements.readlines(): if line.startswith(\"# PYSYRENN\"): reading",
"codecs import os import re from setuptools import setup, find_packages",
"r\"^__{meta}__ = ['\\\"]([^'\\\"]*)['\\\"]\".format(meta=meta), META_FILE, re.M ) if meta_match: return meta_match.group(1)",
":: OS Independent\", \"Programming Language :: Python\", \"Programming Language ::",
"the contents of the resulting file. Assume UTF-8 encoding. \"\"\"",
"f.read() META_FILE = read(META_PATH) def find_meta(meta): \"\"\"Extract __*meta*__ from META_FILE.",
":: OSI Approved :: MIT License\", \"Operating System :: OS",
"= re.search( r\"^__{meta}__ = ['\\\"]([^'\\\"]*)['\\\"]\".format(meta=meta), META_FILE, re.M ) if meta_match:",
"META_FILE, re.M ) if meta_match: return meta_match.group(1) raise RuntimeError(\"Unable to",
"<reponame>95616ARG/SyReNN<filename>pip_info/setup.py \"\"\"Setup script for PySyReNN. Adapted from: https://hynek.me/articles/sharing-your-labor-of-love-pypi-quick-and-dirty/ \"\"\" import",
"] INSTALL_REQUIRES = [\"torch\"] with open(\"requirements.txt\") as requirements: reading =",
"long_description_content_type=\"text/markdown\", packages=PACKAGES, package_dir={\"\": \".\"}, package_data={\"\": [\"pysyrenn/**/*.py\"]}, zip_safe=False, classifiers=CLASSIFIERS, install_requires=INSTALL_REQUIRES, )",
"and and return the contents of the resulting file. Assume",
"setup, find_packages ################################################################### NAME = \"pysyrenn\" PACKAGES = [ \"syrenn_proto\",",
"PySyReNN. Adapted from: https://hynek.me/articles/sharing-your-labor-of-love-pypi-quick-and-dirty/ \"\"\" import codecs import os import",
"\"\"\" import codecs import os import re from setuptools import",
"__*meta*__ from META_FILE. \"\"\" meta_match = re.search( r\"^__{meta}__ = ['\\\"]([^'\\\"]*)['\\\"]\".format(meta=meta),",
"read(META_PATH) def find_meta(meta): \"\"\"Extract __*meta*__ from META_FILE. \"\"\" meta_match =",
"\"Topic :: Software Development :: Libraries :: Python Modules\", ]",
"def read(*parts): \"\"\" Build an absolute path from *parts* and",
"Python Modules\", ] INSTALL_REQUIRES = [\"torch\"] with open(\"requirements.txt\") as requirements:",
"reading = False for line in requirements.readlines(): if line.startswith(\"# PYSYRENN\"):",
"absolute path from *parts* and and return the contents of",
"PACKAGES = [ \"syrenn_proto\", \"pysyrenn\", \"pysyrenn.frontend\", \"pysyrenn.helpers\", ] META_PATH =",
"\"\"\" with codecs.open(os.path.join(HERE, *parts), \"rb\", \"utf-8\") as f: return f.read()",
"setup( name=NAME, description=find_meta(\"description\"), license=find_meta(\"license\"), url=find_meta(\"uri\"), version=find_meta(\"version\"), author=find_meta(\"author\"), author_email=find_meta(\"email\"), maintainer=find_meta(\"author\"), maintainer_email=find_meta(\"email\"),",
":: Python :: 3.4\", \"Programming Language :: Python :: 3.5\",",
"[ \"syrenn_proto\", \"pysyrenn\", \"pysyrenn.frontend\", \"pysyrenn.helpers\", ] META_PATH = \"__metadata__.py\" KEYWORDS",
"find_packages ################################################################### NAME = \"pysyrenn\" PACKAGES = [ \"syrenn_proto\", \"pysyrenn\",",
"for PySyReNN. Adapted from: https://hynek.me/articles/sharing-your-labor-of-love-pypi-quick-and-dirty/ \"\"\" import codecs import os",
"3.4\", \"Programming Language :: Python :: 3.5\", \"Programming Language ::",
"line.startswith(\"# END\"): reading = False elif line.startswith(\"#\"): pass elif reading:",
"the resulting file. Assume UTF-8 encoding. \"\"\" with codecs.open(os.path.join(HERE, *parts),",
"OS Independent\", \"Programming Language :: Python\", \"Programming Language :: Python",
"script for PySyReNN. Adapted from: https://hynek.me/articles/sharing-your-labor-of-love-pypi-quick-and-dirty/ \"\"\" import codecs import",
"as f: return f.read() META_FILE = read(META_PATH) def find_meta(meta): \"\"\"Extract",
":: English\", \"License :: OSI Approved :: MIT License\", \"Operating",
"\"pysyrenn\", \"pysyrenn.frontend\", \"pysyrenn.helpers\", ] META_PATH = \"__metadata__.py\" KEYWORDS = [\"class\","
] |
[] |
[
"imp import importlib def load(name, path): \"\"\"Load and initialize a",
"return its module object\"\"\" if hasattr(importlib, \"machinery\"): loader = importlib.machinery.SourceFileLoader(name,",
"and initialize a module implemented as a Python source file",
"__all__ = [\"load\"] import imp import importlib def load(name, path):",
"file and return its module object\"\"\" if hasattr(importlib, \"machinery\"): loader",
"if hasattr(importlib, \"machinery\"): loader = importlib.machinery.SourceFileLoader(name, path) return loader.load_module() return",
"importlib def load(name, path): \"\"\"Load and initialize a module implemented",
"hasattr(importlib, \"machinery\"): loader = importlib.machinery.SourceFileLoader(name, path) return loader.load_module() return imp.load_source(name,",
"module object\"\"\" if hasattr(importlib, \"machinery\"): loader = importlib.machinery.SourceFileLoader(name, path) return",
"= [\"load\"] import imp import importlib def load(name, path): \"\"\"Load",
"as a Python source file and return its module object\"\"\"",
"load(name, path): \"\"\"Load and initialize a module implemented as a",
"module implemented as a Python source file and return its",
"Python source file and return its module object\"\"\" if hasattr(importlib,",
"path): \"\"\"Load and initialize a module implemented as a Python",
"object\"\"\" if hasattr(importlib, \"machinery\"): loader = importlib.machinery.SourceFileLoader(name, path) return loader.load_module()",
"a module implemented as a Python source file and return",
"and return its module object\"\"\" if hasattr(importlib, \"machinery\"): loader =",
"a Python source file and return its module object\"\"\" if",
"\"\"\"Load and initialize a module implemented as a Python source",
"import importlib def load(name, path): \"\"\"Load and initialize a module",
"\"machinery\"): loader = importlib.machinery.SourceFileLoader(name, path) return loader.load_module() return imp.load_source(name, path)",
"initialize a module implemented as a Python source file and",
"[\"load\"] import imp import importlib def load(name, path): \"\"\"Load and",
"implemented as a Python source file and return its module",
"def load(name, path): \"\"\"Load and initialize a module implemented as",
"import imp import importlib def load(name, path): \"\"\"Load and initialize",
"source file and return its module object\"\"\" if hasattr(importlib, \"machinery\"):",
"its module object\"\"\" if hasattr(importlib, \"machinery\"): loader = importlib.machinery.SourceFileLoader(name, path)"
] |
[
"SVGenPlugin): @classmethod def bind(cls): cls.registry['svgen']['module_namespace'][sieve] = SVGenSieve cls.registry['svgen']['flow'].insert( cls.registry['svgen']['flow'].index(svgen_inst), CollapseSievesVisitor)",
"left for this sieve remove # this Sieve completely (with",
"node.in_ports[0] if pin.dtype == pout.dtype: node.bypass() @svgen_visitor class CollapseSievesVisitor(RTLGearHierVisitor): def",
"this Sieve, which are Sieves themselves, # to this Sieve's",
"for i in stages): stages = [] context = {",
"p in node.consumers if is_gear_instance(p.node, sieve) ] pin = node.in_ports[0]",
"# Connect the consumers of this Sieve, which are Sieves",
"\"sieve.j2\", context) @svgen_visitor class RemoveEqualReprSieveVisitor(RTLGearHierVisitor): def sieve(self, node): pout =",
"sieve(self, node): pout = node.out_ports[0] pin = node.in_ports[0] if pin.dtype",
"node.in_ports[0] pout = node.out_ports[0] iin = pin.producer iout = pout.consumer",
"consumer = cons_pin.node if is_gear_instance(consumer, sieve): # print(f'Merging {node.name} to",
"If any of the sieves has shrunk data to 0",
"SVGenSieve(SVModuleGen): @property def is_generated(self): return True def get_module(self, template_env): def",
"in node.consumers if is_gear_instance(p.node, sieve) ] pin = node.in_ports[0] pout",
"= pout.consumer if sieve_cons: # There is a Sieve connected",
"# If the consumer is a Sieve, just register this",
"class SVGenSievePlugin(SVGenInstPlugin, SVGenPlugin): @classmethod def bind(cls): cls.registry['svgen']['module_namespace'][sieve] = SVGenSieve cls.registry['svgen']['flow'].insert(",
"= [] context = { 'stages': stages, 'module_name': self.sv_module_name, 'intfs':",
"list(self.sv_port_configs()) } return template_env.render_local(__file__, \"sieve.j2\", context) @svgen_visitor class RemoveEqualReprSieveVisitor(RTLGearHierVisitor): def",
"from pygears.common.sieve import sieve from pygears.svgen.inst import SVGenInstPlugin from pygears.svgen.svmod",
"hence we can combine # two of them into a",
"SVGenSievePlugin(SVGenInstPlugin, SVGenPlugin): @classmethod def bind(cls): cls.registry['svgen']['module_namespace'][sieve] = SVGenSieve cls.registry['svgen']['flow'].insert( cls.registry['svgen']['flow'].index(svgen_inst),",
"int(dtype[i]) > 0, indexes))) yield slices, out_type stages = list(get_stages())",
"themselves, # to this Sieve's predecessor for cons_pin in iout.consumers.copy():",
"iin = pin.producer iout = pout.consumer if sieve_cons: # There",
"[node] iout.disconnect(cons_pin) iin.connect(cons_pin) # print(f'Remaining conusmer: {[p.node.name for p in",
"from pygears.svgen.inst import svgen_inst from pygears.rtl.gear import RTLGearHierVisitor, is_gear_instance def",
"# print(f'Merging {node.name} to {consumer.name}') # print(consumer.params['key']) # If the",
"SVModuleGen from functools import partial from pygears.svgen.svgen import SVGenPlugin from",
"a Sieve connected to this Sieve, hence we can combine",
"RTLGearHierVisitor, is_gear_instance def index_to_sv_slice(dtype, key): subtype = dtype[key] if isinstance(key,",
"we can combine # two of them into a single",
"] pin = node.in_ports[0] pout = node.out_ports[0] iin = pin.producer",
"nothing to # do if any(i[0] == [] for i",
"slices = list( map( partial(index_to_sv_slice, dtype), filter(lambda i: int(dtype[i]) >",
"yield slices, out_type stages = list(get_stages()) # If any of",
"high_pos = low_pos + int(subtype) - 1 return f'{high_pos}:{low_pos}' class",
"consumers of this Sieve, which are Sieves themselves, # to",
"stages): stages = [] context = { 'stages': stages, 'module_name':",
"# There is a Sieve connected to this Sieve, hence",
"pygears.svgen.svmod import SVModuleGen from functools import partial from pygears.svgen.svgen import",
"class RemoveEqualReprSieveVisitor(RTLGearHierVisitor): def sieve(self, node): pout = node.out_ports[0] pin =",
"return True def get_module(self, template_env): def get_stages(): for s in",
"i in stages): stages = [] context = { 'stages':",
"pygears.core.hier_node import HierVisitorBase from pygears.svgen.inst import svgen_inst from pygears.rtl.gear import",
"else: low_pos = int(dtype[:key]) high_pos = low_pos + int(subtype) -",
"0 else: low_pos = int(dtype[:key]) high_pos = low_pos + int(subtype)",
"do if any(i[0] == [] for i in stages): stages",
"stages, 'module_name': self.sv_module_name, 'intfs': list(self.sv_port_configs()) } return template_env.render_local(__file__, \"sieve.j2\", context)",
"if sieve_cons: # There is a Sieve connected to this",
"= dtype[key] if isinstance(key, slice): key = key.start if key",
"itertools.chain(self.node.pre_sieves, [self.node]): indexes = s.params['key'] if not isinstance(indexes, tuple): indexes",
"shrunk data to 0 width, there is nothing to #",
"for s in itertools.chain(self.node.pre_sieves, [self.node]): indexes = s.params['key'] if not",
"is_gear_instance(p.node, sieve) ] pin = node.in_ports[0] pout = node.out_ports[0] iin",
"Sieve with # it, and short circuit this one consumer.pre_sieves",
"+ [node] iout.disconnect(cons_pin) iin.connect(cons_pin) # print(f'Remaining conusmer: {[p.node.name for p",
"and short circuit this one consumer.pre_sieves = node.pre_sieves + [node]",
"in itertools.chain(self.node.pre_sieves, [self.node]): indexes = s.params['key'] if not isinstance(indexes, tuple):",
"circuit this one consumer.pre_sieves = node.pre_sieves + [node] iout.disconnect(cons_pin) iin.connect(cons_pin)",
"print(f'Merging {node.name} to {consumer.name}') # print(consumer.params['key']) # If the consumer",
"are no consumers left for this sieve remove # this",
"there is nothing to # do if any(i[0] == []",
"s in itertools.chain(self.node.pre_sieves, [self.node]): indexes = s.params['key'] if not isinstance(indexes,",
"from pygears.svgen.inst import SVGenInstPlugin from pygears.svgen.svmod import SVModuleGen from functools",
"partial from pygears.svgen.svgen import SVGenPlugin from pygears.svgen.util import svgen_visitor from",
"= list(get_stages()) # If any of the sieves has shrunk",
"has shrunk data to 0 width, there is nothing to",
"consumer.pre_sieves = node.pre_sieves + [node] iout.disconnect(cons_pin) iin.connect(cons_pin) # print(f'Remaining conusmer:",
"the sieves has shrunk data to 0 width, there is",
"== pout.dtype: node.bypass() @svgen_visitor class CollapseSievesVisitor(RTLGearHierVisitor): def sieve(self, node): if",
"dtype), filter(lambda i: int(dtype[i]) > 0, indexes))) yield slices, out_type",
"0 width, there is nothing to # do if any(i[0]",
"HierVisitorBase from pygears.svgen.inst import svgen_inst from pygears.rtl.gear import RTLGearHierVisitor, is_gear_instance",
"import svgen_visitor from pygears.core.hier_node import HierVisitorBase from pygears.svgen.inst import svgen_inst",
"iout.consumers.copy(): consumer = cons_pin.node if is_gear_instance(consumer, sieve): # print(f'Merging {node.name}",
"if pin.dtype == pout.dtype: node.bypass() @svgen_visitor class CollapseSievesVisitor(RTLGearHierVisitor): def sieve(self,",
"Sieve, which are Sieves themselves, # to this Sieve's predecessor",
"them into a single SV module # Connect the consumers",
"cons_pin in iout.consumers.copy(): consumer = cons_pin.node if is_gear_instance(consumer, sieve): #",
"is a Sieve connected to this Sieve, hence we can",
"is_gear_instance(consumer, sieve): # print(f'Merging {node.name} to {consumer.name}') # print(consumer.params['key']) #",
"node.bypass() @svgen_visitor class CollapseSievesVisitor(RTLGearHierVisitor): def sieve(self, node): if not hasattr(node,",
"itertools from pygears.common.sieve import sieve from pygears.svgen.inst import SVGenInstPlugin from",
"@svgen_visitor class RemoveEqualReprSieveVisitor(RTLGearHierVisitor): def sieve(self, node): pout = node.out_ports[0] pin",
"p in node.consumers]}') if not node.consumers: # Finally, if ther",
"node.consumers]}') if not node.consumers: # Finally, if ther are no",
"iout.remove() class SVGenSievePlugin(SVGenInstPlugin, SVGenPlugin): @classmethod def bind(cls): cls.registry['svgen']['module_namespace'][sieve] = SVGenSieve",
"key = key.start if key is None or key ==",
"is_gear_instance def index_to_sv_slice(dtype, key): subtype = dtype[key] if isinstance(key, slice):",
"= s.in_ports[0].dtype out_type = s.out_ports[0].dtype slices = list( map( partial(index_to_sv_slice,",
"pygears.svgen.inst import svgen_inst from pygears.rtl.gear import RTLGearHierVisitor, is_gear_instance def index_to_sv_slice(dtype,",
"0: low_pos = 0 else: low_pos = int(dtype[:key]) high_pos =",
"stages = [] context = { 'stages': stages, 'module_name': self.sv_module_name,",
"pygears.common.sieve import sieve from pygears.svgen.inst import SVGenInstPlugin from pygears.svgen.svmod import",
"RemoveEqualReprSieveVisitor(RTLGearHierVisitor): def sieve(self, node): pout = node.out_ports[0] pin = node.in_ports[0]",
"if key is None or key == 0: low_pos =",
"@property def is_generated(self): return True def get_module(self, template_env): def get_stages():",
"== [] for i in stages): stages = [] context",
"map( partial(index_to_sv_slice, dtype), filter(lambda i: int(dtype[i]) > 0, indexes))) yield",
"node.consumers: # Finally, if ther are no consumers left for",
"it, and short circuit this one consumer.pre_sieves = node.pre_sieves +",
"this Sieve completely (with all it's connections) from the #",
"this one consumer.pre_sieves = node.pre_sieves + [node] iout.disconnect(cons_pin) iin.connect(cons_pin) #",
"is None or key == 0: low_pos = 0 else:",
"in node.consumers]}') if not node.consumers: # Finally, if ther are",
"= (indexes, ) dtype = s.in_ports[0].dtype out_type = s.out_ports[0].dtype slices",
"= low_pos + int(subtype) - 1 return f'{high_pos}:{low_pos}' class SVGenSieve(SVModuleGen):",
"this sieve remove # this Sieve completely (with all it's",
"= node.out_ports[0] iin = pin.producer iout = pout.consumer if sieve_cons:",
"sieve(self, node): if not hasattr(node, 'pre_sieves'): node.pre_sieves = [] sieve_cons",
"def sieve(self, node): pout = node.out_ports[0] pin = node.in_ports[0] if",
"import partial from pygears.svgen.svgen import SVGenPlugin from pygears.svgen.util import svgen_visitor",
"this Sieve, hence we can combine # two of them",
"predecessor for cons_pin in iout.consumers.copy(): consumer = cons_pin.node if is_gear_instance(consumer,",
"indexes))) yield slices, out_type stages = list(get_stages()) # If any",
"node.remove() iout.remove() class SVGenSievePlugin(SVGenInstPlugin, SVGenPlugin): @classmethod def bind(cls): cls.registry['svgen']['module_namespace'][sieve] =",
"any(i[0] == [] for i in stages): stages = []",
"(with all it's connections) from the # SVGen tree node.remove()",
"pin.dtype == pout.dtype: node.bypass() @svgen_visitor class CollapseSievesVisitor(RTLGearHierVisitor): def sieve(self, node):",
"1 return f'{high_pos}:{low_pos}' class SVGenSieve(SVModuleGen): @property def is_generated(self): return True",
"get_stages(): for s in itertools.chain(self.node.pre_sieves, [self.node]): indexes = s.params['key'] if",
"= s.params['key'] if not isinstance(indexes, tuple): indexes = (indexes, )",
"# Finally, if ther are no consumers left for this",
"for p in node.consumers]}') if not node.consumers: # Finally, if",
"Sieve, just register this Sieve with # it, and short",
"int(dtype[:key]) high_pos = low_pos + int(subtype) - 1 return f'{high_pos}:{low_pos}'",
"two of them into a single SV module # Connect",
"s.out_ports[0].dtype slices = list( map( partial(index_to_sv_slice, dtype), filter(lambda i: int(dtype[i])",
"return template_env.render_local(__file__, \"sieve.j2\", context) @svgen_visitor class RemoveEqualReprSieveVisitor(RTLGearHierVisitor): def sieve(self, node):",
"connected to this Sieve, hence we can combine # two",
"functools import partial from pygears.svgen.svgen import SVGenPlugin from pygears.svgen.util import",
"is_generated(self): return True def get_module(self, template_env): def get_stages(): for s",
"list( map( partial(index_to_sv_slice, dtype), filter(lambda i: int(dtype[i]) > 0, indexes)))",
"import itertools from pygears.common.sieve import sieve from pygears.svgen.inst import SVGenInstPlugin",
"class CollapseSievesVisitor(RTLGearHierVisitor): def sieve(self, node): if not hasattr(node, 'pre_sieves'): node.pre_sieves",
"template_env): def get_stages(): for s in itertools.chain(self.node.pre_sieves, [self.node]): indexes =",
"low_pos + int(subtype) - 1 return f'{high_pos}:{low_pos}' class SVGenSieve(SVModuleGen): @property",
"SVGen tree node.remove() iout.remove() class SVGenSievePlugin(SVGenInstPlugin, SVGenPlugin): @classmethod def bind(cls):",
"any of the sieves has shrunk data to 0 width,",
"f'{high_pos}:{low_pos}' class SVGenSieve(SVModuleGen): @property def is_generated(self): return True def get_module(self,",
"node.consumers if is_gear_instance(p.node, sieve) ] pin = node.in_ports[0] pout =",
"width, there is nothing to # do if any(i[0] ==",
"index_to_sv_slice(dtype, key): subtype = dtype[key] if isinstance(key, slice): key =",
"dtype = s.in_ports[0].dtype out_type = s.out_ports[0].dtype slices = list( map(",
"template_env.render_local(__file__, \"sieve.j2\", context) @svgen_visitor class RemoveEqualReprSieveVisitor(RTLGearHierVisitor): def sieve(self, node): pout",
"the # SVGen tree node.remove() iout.remove() class SVGenSievePlugin(SVGenInstPlugin, SVGenPlugin): @classmethod",
"Connect the consumers of this Sieve, which are Sieves themselves,",
"# two of them into a single SV module #",
"Finally, if ther are no consumers left for this sieve",
"short circuit this one consumer.pre_sieves = node.pre_sieves + [node] iout.disconnect(cons_pin)",
"not hasattr(node, 'pre_sieves'): node.pre_sieves = [] sieve_cons = [ p",
"= node.pre_sieves + [node] iout.disconnect(cons_pin) iin.connect(cons_pin) # print(f'Remaining conusmer: {[p.node.name",
"node.out_ports[0] iin = pin.producer iout = pout.consumer if sieve_cons: #",
"slices, out_type stages = list(get_stages()) # If any of the",
"= pin.producer iout = pout.consumer if sieve_cons: # There is",
"{ 'stages': stages, 'module_name': self.sv_module_name, 'intfs': list(self.sv_port_configs()) } return template_env.render_local(__file__,",
"import SVModuleGen from functools import partial from pygears.svgen.svgen import SVGenPlugin",
"= SVGenSieve cls.registry['svgen']['flow'].insert( cls.registry['svgen']['flow'].index(svgen_inst), CollapseSievesVisitor) # cls.registry['SVGenFlow'].insert( # cls.registry['SVGenFlow'].key(CollapseSievesVisitor), #",
"with # it, and short circuit this one consumer.pre_sieves =",
"key is None or key == 0: low_pos = 0",
"# SVGen tree node.remove() iout.remove() class SVGenSievePlugin(SVGenInstPlugin, SVGenPlugin): @classmethod def",
"pin = node.in_ports[0] pout = node.out_ports[0] iin = pin.producer iout",
"not node.consumers: # Finally, if ther are no consumers left",
"If the consumer is a Sieve, just register this Sieve",
"'pre_sieves'): node.pre_sieves = [] sieve_cons = [ p for p",
"int(subtype) - 1 return f'{high_pos}:{low_pos}' class SVGenSieve(SVModuleGen): @property def is_generated(self):",
"out_type = s.out_ports[0].dtype slices = list( map( partial(index_to_sv_slice, dtype), filter(lambda",
"from pygears.svgen.svmod import SVModuleGen from functools import partial from pygears.svgen.svgen",
"isinstance(indexes, tuple): indexes = (indexes, ) dtype = s.in_ports[0].dtype out_type",
"= cons_pin.node if is_gear_instance(consumer, sieve): # print(f'Merging {node.name} to {consumer.name}')",
"import svgen_inst from pygears.rtl.gear import RTLGearHierVisitor, is_gear_instance def index_to_sv_slice(dtype, key):",
"node): if not hasattr(node, 'pre_sieves'): node.pre_sieves = [] sieve_cons =",
"if is_gear_instance(consumer, sieve): # print(f'Merging {node.name} to {consumer.name}') # print(consumer.params['key'])",
"a single SV module # Connect the consumers of this",
"Sieve connected to this Sieve, hence we can combine #",
"from the # SVGen tree node.remove() iout.remove() class SVGenSievePlugin(SVGenInstPlugin, SVGenPlugin):",
"pout.consumer if sieve_cons: # There is a Sieve connected to",
"low_pos = 0 else: low_pos = int(dtype[:key]) high_pos = low_pos",
"svgen_inst from pygears.rtl.gear import RTLGearHierVisitor, is_gear_instance def index_to_sv_slice(dtype, key): subtype",
"combine # two of them into a single SV module",
"pin.producer iout = pout.consumer if sieve_cons: # There is a",
"sieves has shrunk data to 0 width, there is nothing",
"[ p for p in node.consumers if is_gear_instance(p.node, sieve) ]",
"= { 'stages': stages, 'module_name': self.sv_module_name, 'intfs': list(self.sv_port_configs()) } return",
"pout.dtype: node.bypass() @svgen_visitor class CollapseSievesVisitor(RTLGearHierVisitor): def sieve(self, node): if not",
"s.params['key'] if not isinstance(indexes, tuple): indexes = (indexes, ) dtype",
"iout = pout.consumer if sieve_cons: # There is a Sieve",
"= node.in_ports[0] if pin.dtype == pout.dtype: node.bypass() @svgen_visitor class CollapseSievesVisitor(RTLGearHierVisitor):",
"import HierVisitorBase from pygears.svgen.inst import svgen_inst from pygears.rtl.gear import RTLGearHierVisitor,",
"'stages': stages, 'module_name': self.sv_module_name, 'intfs': list(self.sv_port_configs()) } return template_env.render_local(__file__, \"sieve.j2\",",
"pin = node.in_ports[0] if pin.dtype == pout.dtype: node.bypass() @svgen_visitor class",
"key): subtype = dtype[key] if isinstance(key, slice): key = key.start",
"module # Connect the consumers of this Sieve, which are",
"node.pre_sieves = [] sieve_cons = [ p for p in",
") dtype = s.in_ports[0].dtype out_type = s.out_ports[0].dtype slices = list(",
"not isinstance(indexes, tuple): indexes = (indexes, ) dtype = s.in_ports[0].dtype",
"sieve): # print(f'Merging {node.name} to {consumer.name}') # print(consumer.params['key']) # If",
"hasattr(node, 'pre_sieves'): node.pre_sieves = [] sieve_cons = [ p for",
"indexes = s.params['key'] if not isinstance(indexes, tuple): indexes = (indexes,",
"print(consumer.params['key']) # If the consumer is a Sieve, just register",
"from pygears.svgen.svgen import SVGenPlugin from pygears.svgen.util import svgen_visitor from pygears.core.hier_node",
"def sieve(self, node): if not hasattr(node, 'pre_sieves'): node.pre_sieves = []",
"= node.out_ports[0] pin = node.in_ports[0] if pin.dtype == pout.dtype: node.bypass()",
"cons_pin.node if is_gear_instance(consumer, sieve): # print(f'Merging {node.name} to {consumer.name}') #",
"{[p.node.name for p in node.consumers]}') if not node.consumers: # Finally,",
"class SVGenSieve(SVModuleGen): @property def is_generated(self): return True def get_module(self, template_env):",
"import SVGenPlugin from pygears.svgen.util import svgen_visitor from pygears.core.hier_node import HierVisitorBase",
"pout = node.out_ports[0] iin = pin.producer iout = pout.consumer if",
"filter(lambda i: int(dtype[i]) > 0, indexes))) yield slices, out_type stages",
"to this Sieve, hence we can combine # two of",
"bind(cls): cls.registry['svgen']['module_namespace'][sieve] = SVGenSieve cls.registry['svgen']['flow'].insert( cls.registry['svgen']['flow'].index(svgen_inst), CollapseSievesVisitor) # cls.registry['SVGenFlow'].insert( #",
"import SVGenInstPlugin from pygears.svgen.svmod import SVModuleGen from functools import partial",
"of them into a single SV module # Connect the",
"print(f'Remaining conusmer: {[p.node.name for p in node.consumers]}') if not node.consumers:",
"stages = list(get_stages()) # If any of the sieves has",
"cls.registry['svgen']['module_namespace'][sieve] = SVGenSieve cls.registry['svgen']['flow'].insert( cls.registry['svgen']['flow'].index(svgen_inst), CollapseSievesVisitor) # cls.registry['SVGenFlow'].insert( # cls.registry['SVGenFlow'].key(CollapseSievesVisitor),",
"pygears.svgen.util import svgen_visitor from pygears.core.hier_node import HierVisitorBase from pygears.svgen.inst import",
"of the sieves has shrunk data to 0 width, there",
"sieve from pygears.svgen.inst import SVGenInstPlugin from pygears.svgen.svmod import SVModuleGen from",
"pygears.svgen.inst import SVGenInstPlugin from pygears.svgen.svmod import SVModuleGen from functools import",
"consumer is a Sieve, just register this Sieve with #",
"@classmethod def bind(cls): cls.registry['svgen']['module_namespace'][sieve] = SVGenSieve cls.registry['svgen']['flow'].insert( cls.registry['svgen']['flow'].index(svgen_inst), CollapseSievesVisitor) #",
"if isinstance(key, slice): key = key.start if key is None",
"dtype[key] if isinstance(key, slice): key = key.start if key is",
"connections) from the # SVGen tree node.remove() iout.remove() class SVGenSievePlugin(SVGenInstPlugin,",
"s.in_ports[0].dtype out_type = s.out_ports[0].dtype slices = list( map( partial(index_to_sv_slice, dtype),",
"tuple): indexes = (indexes, ) dtype = s.in_ports[0].dtype out_type =",
"the consumers of this Sieve, which are Sieves themselves, #",
"slice): key = key.start if key is None or key",
"subtype = dtype[key] if isinstance(key, slice): key = key.start if",
"are Sieves themselves, # to this Sieve's predecessor for cons_pin",
"for this sieve remove # this Sieve completely (with all",
"in iout.consumers.copy(): consumer = cons_pin.node if is_gear_instance(consumer, sieve): # print(f'Merging",
"sieve remove # this Sieve completely (with all it's connections)",
"context) @svgen_visitor class RemoveEqualReprSieveVisitor(RTLGearHierVisitor): def sieve(self, node): pout = node.out_ports[0]",
"= list( map( partial(index_to_sv_slice, dtype), filter(lambda i: int(dtype[i]) > 0,",
"if not node.consumers: # Finally, if ther are no consumers",
"if not hasattr(node, 'pre_sieves'): node.pre_sieves = [] sieve_cons = [",
"if any(i[0] == [] for i in stages): stages =",
"from functools import partial from pygears.svgen.svgen import SVGenPlugin from pygears.svgen.util",
"partial(index_to_sv_slice, dtype), filter(lambda i: int(dtype[i]) > 0, indexes))) yield slices,",
"the consumer is a Sieve, just register this Sieve with",
"@svgen_visitor class CollapseSievesVisitor(RTLGearHierVisitor): def sieve(self, node): if not hasattr(node, 'pre_sieves'):",
"remove # this Sieve completely (with all it's connections) from",
"consumers left for this sieve remove # this Sieve completely",
"= [] sieve_cons = [ p for p in node.consumers",
"- 1 return f'{high_pos}:{low_pos}' class SVGenSieve(SVModuleGen): @property def is_generated(self): return",
"is nothing to # do if any(i[0] == [] for",
"iin.connect(cons_pin) # print(f'Remaining conusmer: {[p.node.name for p in node.consumers]}') if",
"= 0 else: low_pos = int(dtype[:key]) high_pos = low_pos +",
"= s.out_ports[0].dtype slices = list( map( partial(index_to_sv_slice, dtype), filter(lambda i:",
"SVGenSieve cls.registry['svgen']['flow'].insert( cls.registry['svgen']['flow'].index(svgen_inst), CollapseSievesVisitor) # cls.registry['SVGenFlow'].insert( # cls.registry['SVGenFlow'].key(CollapseSievesVisitor), # RemoveEqualReprSieveVisitor)",
"There is a Sieve connected to this Sieve, hence we",
"# print(f'Remaining conusmer: {[p.node.name for p in node.consumers]}') if not",
"0, indexes))) yield slices, out_type stages = list(get_stages()) # If",
"'module_name': self.sv_module_name, 'intfs': list(self.sv_port_configs()) } return template_env.render_local(__file__, \"sieve.j2\", context) @svgen_visitor",
"sieve) ] pin = node.in_ports[0] pout = node.out_ports[0] iin =",
"this Sieve with # it, and short circuit this one",
"Sieve's predecessor for cons_pin in iout.consumers.copy(): consumer = cons_pin.node if",
"can combine # two of them into a single SV",
"None or key == 0: low_pos = 0 else: low_pos",
"if ther are no consumers left for this sieve remove",
"to {consumer.name}') # print(consumer.params['key']) # If the consumer is a",
"def get_module(self, template_env): def get_stages(): for s in itertools.chain(self.node.pre_sieves, [self.node]):",
"all it's connections) from the # SVGen tree node.remove() iout.remove()",
"True def get_module(self, template_env): def get_stages(): for s in itertools.chain(self.node.pre_sieves,",
"to # do if any(i[0] == [] for i in",
"key.start if key is None or key == 0: low_pos",
"Sieves themselves, # to this Sieve's predecessor for cons_pin in",
"{node.name} to {consumer.name}') # print(consumer.params['key']) # If the consumer is",
"isinstance(key, slice): key = key.start if key is None or",
"tree node.remove() iout.remove() class SVGenSievePlugin(SVGenInstPlugin, SVGenPlugin): @classmethod def bind(cls): cls.registry['svgen']['module_namespace'][sieve]",
"} return template_env.render_local(__file__, \"sieve.j2\", context) @svgen_visitor class RemoveEqualReprSieveVisitor(RTLGearHierVisitor): def sieve(self,",
"low_pos = int(dtype[:key]) high_pos = low_pos + int(subtype) - 1",
"def is_generated(self): return True def get_module(self, template_env): def get_stages(): for",
"into a single SV module # Connect the consumers of",
"= key.start if key is None or key == 0:",
"Sieve completely (with all it's connections) from the # SVGen",
"# print(consumer.params['key']) # If the consumer is a Sieve, just",
"just register this Sieve with # it, and short circuit",
"Sieve, hence we can combine # two of them into",
"if not isinstance(indexes, tuple): indexes = (indexes, ) dtype =",
"conusmer: {[p.node.name for p in node.consumers]}') if not node.consumers: #",
"context = { 'stages': stages, 'module_name': self.sv_module_name, 'intfs': list(self.sv_port_configs()) }",
"(indexes, ) dtype = s.in_ports[0].dtype out_type = s.out_ports[0].dtype slices =",
"+ int(subtype) - 1 return f'{high_pos}:{low_pos}' class SVGenSieve(SVModuleGen): @property def",
"no consumers left for this sieve remove # this Sieve",
"it's connections) from the # SVGen tree node.remove() iout.remove() class",
"node.pre_sieves + [node] iout.disconnect(cons_pin) iin.connect(cons_pin) # print(f'Remaining conusmer: {[p.node.name for",
"register this Sieve with # it, and short circuit this",
"is a Sieve, just register this Sieve with # it,",
"[] sieve_cons = [ p for p in node.consumers if",
"sieve_cons = [ p for p in node.consumers if is_gear_instance(p.node,",
"from pygears.rtl.gear import RTLGearHierVisitor, is_gear_instance def index_to_sv_slice(dtype, key): subtype =",
"[] context = { 'stages': stages, 'module_name': self.sv_module_name, 'intfs': list(self.sv_port_configs())",
"return f'{high_pos}:{low_pos}' class SVGenSieve(SVModuleGen): @property def is_generated(self): return True def",
"import RTLGearHierVisitor, is_gear_instance def index_to_sv_slice(dtype, key): subtype = dtype[key] if",
"one consumer.pre_sieves = node.pre_sieves + [node] iout.disconnect(cons_pin) iin.connect(cons_pin) # print(f'Remaining",
"to this Sieve's predecessor for cons_pin in iout.consumers.copy(): consumer =",
"# it, and short circuit this one consumer.pre_sieves = node.pre_sieves",
"= int(dtype[:key]) high_pos = low_pos + int(subtype) - 1 return",
"iout.disconnect(cons_pin) iin.connect(cons_pin) # print(f'Remaining conusmer: {[p.node.name for p in node.consumers]}')",
"'intfs': list(self.sv_port_configs()) } return template_env.render_local(__file__, \"sieve.j2\", context) @svgen_visitor class RemoveEqualReprSieveVisitor(RTLGearHierVisitor):",
"to 0 width, there is nothing to # do if",
"# do if any(i[0] == [] for i in stages):",
"def get_stages(): for s in itertools.chain(self.node.pre_sieves, [self.node]): indexes = s.params['key']",
"<gh_stars>0 import itertools from pygears.common.sieve import sieve from pygears.svgen.inst import",
"from pygears.core.hier_node import HierVisitorBase from pygears.svgen.inst import svgen_inst from pygears.rtl.gear",
"i: int(dtype[i]) > 0, indexes))) yield slices, out_type stages =",
"SV module # Connect the consumers of this Sieve, which",
"SVGenPlugin from pygears.svgen.util import svgen_visitor from pygears.core.hier_node import HierVisitorBase from",
"> 0, indexes))) yield slices, out_type stages = list(get_stages()) #",
"if is_gear_instance(p.node, sieve) ] pin = node.in_ports[0] pout = node.out_ports[0]",
"completely (with all it's connections) from the # SVGen tree",
"def index_to_sv_slice(dtype, key): subtype = dtype[key] if isinstance(key, slice): key",
"pout = node.out_ports[0] pin = node.in_ports[0] if pin.dtype == pout.dtype:",
"or key == 0: low_pos = 0 else: low_pos =",
"which are Sieves themselves, # to this Sieve's predecessor for",
"for cons_pin in iout.consumers.copy(): consumer = cons_pin.node if is_gear_instance(consumer, sieve):",
"ther are no consumers left for this sieve remove #",
"= node.in_ports[0] pout = node.out_ports[0] iin = pin.producer iout =",
"CollapseSievesVisitor(RTLGearHierVisitor): def sieve(self, node): if not hasattr(node, 'pre_sieves'): node.pre_sieves =",
"get_module(self, template_env): def get_stages(): for s in itertools.chain(self.node.pre_sieves, [self.node]): indexes",
"[] for i in stages): stages = [] context =",
"out_type stages = list(get_stages()) # If any of the sieves",
"# to this Sieve's predecessor for cons_pin in iout.consumers.copy(): consumer",
"single SV module # Connect the consumers of this Sieve,",
"svgen_visitor from pygears.core.hier_node import HierVisitorBase from pygears.svgen.inst import svgen_inst from",
"a Sieve, just register this Sieve with # it, and",
"= [ p for p in node.consumers if is_gear_instance(p.node, sieve)",
"list(get_stages()) # If any of the sieves has shrunk data",
"from pygears.svgen.util import svgen_visitor from pygears.core.hier_node import HierVisitorBase from pygears.svgen.inst",
"pygears.rtl.gear import RTLGearHierVisitor, is_gear_instance def index_to_sv_slice(dtype, key): subtype = dtype[key]",
"key == 0: low_pos = 0 else: low_pos = int(dtype[:key])",
"p for p in node.consumers if is_gear_instance(p.node, sieve) ] pin",
"in stages): stages = [] context = { 'stages': stages,",
"this Sieve's predecessor for cons_pin in iout.consumers.copy(): consumer = cons_pin.node",
"def bind(cls): cls.registry['svgen']['module_namespace'][sieve] = SVGenSieve cls.registry['svgen']['flow'].insert( cls.registry['svgen']['flow'].index(svgen_inst), CollapseSievesVisitor) # cls.registry['SVGenFlow'].insert(",
"# If any of the sieves has shrunk data to",
"node.out_ports[0] pin = node.in_ports[0] if pin.dtype == pout.dtype: node.bypass() @svgen_visitor",
"import sieve from pygears.svgen.inst import SVGenInstPlugin from pygears.svgen.svmod import SVModuleGen",
"pygears.svgen.svgen import SVGenPlugin from pygears.svgen.util import svgen_visitor from pygears.core.hier_node import",
"{consumer.name}') # print(consumer.params['key']) # If the consumer is a Sieve,",
"== 0: low_pos = 0 else: low_pos = int(dtype[:key]) high_pos",
"node): pout = node.out_ports[0] pin = node.in_ports[0] if pin.dtype ==",
"data to 0 width, there is nothing to # do",
"self.sv_module_name, 'intfs': list(self.sv_port_configs()) } return template_env.render_local(__file__, \"sieve.j2\", context) @svgen_visitor class",
"sieve_cons: # There is a Sieve connected to this Sieve,",
"for p in node.consumers if is_gear_instance(p.node, sieve) ] pin =",
"indexes = (indexes, ) dtype = s.in_ports[0].dtype out_type = s.out_ports[0].dtype",
"# this Sieve completely (with all it's connections) from the",
"SVGenInstPlugin from pygears.svgen.svmod import SVModuleGen from functools import partial from",
"of this Sieve, which are Sieves themselves, # to this",
"[self.node]): indexes = s.params['key'] if not isinstance(indexes, tuple): indexes ="
] |
[
"end_index, freq): print(\"load\", self._name, instrument, start_index, end_index, freq) return raw_data.loc[start_index:end_index][self._name]",
"exprs: expression = eval(my_parse_field(field)) series = expression.load('TSLA', \"2022-01-02\", \"2022-02-28\", \"1min\")",
"qlib.data.base import Feature from pyecharts import options as opts from",
"grid_chart.add( kline_graph, grid_opts=opts.GridOpts(pos_left=\"3%\", pos_right=\"10%\", height=\"50%\"), ) grid_chart.add( kline_line, grid_opts=opts.GridOpts( pos_left=\"3%\",",
"pandas as pd import pickle import xgboost as xgb import",
"new, field) return field obj = dict() for field in",
"#print(\"sell\") mark_points.append(opts.MarkPointItem( coord=[record['data_time'], record['high']], symbol='triangle', symbol_size=7, itemstyle_opts=opts.ItemStyleOpts(color=\"green\") )) elif record['pred_score']",
"<gh_stars>0 #encoding=utf-8 import qlib import pandas as pd import pickle",
"records: x_axises.append(record['data_time']) y_axises.append([ record['open'], record['close'], record['low'], record['high'] ]) if 'hold_cnt'",
"qlib.data.ops import Operators, OpsList from qlib.data.base import Feature from pyecharts",
"record['open'], record['close'], record['low'], record['high'] ]) if 'hold_cnt' in position: position['hold_cnt']",
"from pyecharts import options as opts from pyecharts.charts import Kline,",
"cash += position['amount'] * record['open'] position = {} #print(\"sell\") mark_points.append(opts.MarkPointItem(",
"from qlib.utils import flatten_dict from qlib.data import LocalExpressionProvider from qlib.data.ops",
"position['amount'] = int(cash / position['open']) cash -= position['amount'] * position['open']",
"if 'hold_cnt' in position: position['hold_cnt'] += 1 if position and",
"dict(record) position['amount'] = int(cash / position['open']) cash -= position['amount'] *",
"if position: cash += position['amount'] * records[-1]['close'] print(\"cash:\", cash) kline_graph",
"for pattern, new in [(r\"\\$(\\w+)\", rf'MyFeature(\"\\1\")'), (r\"(\\w+\\s*)\\(\", r\"Operators.\\1(\")]: # Features",
"), ), title_opts=opts.TitleOpts(title=\"%s_%s\" % (view_time_start, view_time_end)), datazoom_opts=[opts.DataZoomOpts(type_=\"inside\", xaxis_index=[0, 1],)], )",
"data=[opts.MarkLineItem(y=50000)] ), ) .set_global_opts( xaxis_opts=opts.AxisOpts( type_=\"category\", grid_index=2, axislabel_opts=opts.LabelOpts(is_show=False), ), yaxis_opts=opts.AxisOpts(",
") grid_chart = Grid(init_opts=opts.InitOpts(width='2000px', height='900px')) grid_chart.add( kline_graph, grid_opts=opts.GridOpts(pos_left=\"3%\", pos_right=\"10%\", height=\"50%\"),",
"= '2022-02-12' pre_data = raw_data.loc[view_time_start:view_time_end].copy() pred=model.model.predict(xgb.DMatrix(data.loc[view_time_start:view_time_end])) pre_data['pred_score'] = pred records",
"if not isinstance(field, str): field = str(field) for pattern, new",
"import Operators, OpsList from qlib.data.base import Feature from pyecharts import",
"position['amount'] * record['close'] money.append(cur_money) if position: cash += position['amount'] *",
"re.sub(pattern, new, field) return field obj = dict() for field",
"= r'.\\mlruns\\1\\148ef1cd7acd48deac3eadc339ad3008\\artifacts\\trained_model' with open(model_file, 'rb') as fi: model = pickle.load(fi)",
"raw_data.loc[view_time_start:view_time_end].copy() pred=model.model.predict(xgb.DMatrix(data.loc[view_time_start:view_time_end])) pre_data['pred_score'] = pred records = pre_data.to_dict(\"records\") cash =",
"pd.DataFrame(obj) data.columns = columns view_time_start = '2022-02-11' view_time_end = '2022-02-12'",
"def my_parse_field(field): if not isinstance(field, str): field = str(field) for",
"symbol='triangle', symbol_size=7, itemstyle_opts=opts.ItemStyleOpts(color=\"green\") )) elif record['pred_score'] > score_thresh and not",
"series data = pd.DataFrame(obj) data.columns = columns view_time_start = '2022-02-11'",
"label_opts=opts.LabelOpts(is_show=False), markline_opts=opts.MarkLineOpts( data=[opts.MarkLineItem(y=50000)] ), ) .set_global_opts( xaxis_opts=opts.AxisOpts( type_=\"category\", grid_index=2, axislabel_opts=opts.LabelOpts(is_show=False),",
"kline_graph = ( Kline() .add_xaxis(x_axises) .add_yaxis( \"kline\", y_axises, markpoint_opts=opts.MarkPointOpts( data=mark_points",
"[] for record in records: x_axises.append(record['data_time']) y_axises.append([ record['open'], record['close'], record['low'],",
"= {} hold_thresh = 5 score_thresh = 0.001 x_axises, y_axises,",
"raw_data['time'].dt.strftime(\"%Y-%m-%d %H:%M:00\") raw_data.set_index('time', inplace=True) raw_data[\"vwap\"] = np.nan raw_data.sort_index(inplace=True) # print(raw_data)",
"markline_opts=opts.MarkLineOpts( data=[opts.MarkLineItem(y=50000)] ), ) .set_global_opts( xaxis_opts=opts.AxisOpts( type_=\"category\", grid_index=2, axislabel_opts=opts.LabelOpts(is_show=False), ),",
"qlib import pandas as pd import pickle import xgboost as",
".set_global_opts( xaxis_opts=opts.AxisOpts( type_=\"category\", grid_index=2, axislabel_opts=opts.LabelOpts(is_show=False), ), yaxis_opts=opts.AxisOpts( min_='dataMin' ) )",
"= pd.DataFrame(obj) data.columns = columns view_time_start = '2022-02-11' view_time_end =",
"field = str(field) for pattern, new in [(r\"\\$(\\w+)\", rf'MyFeature(\"\\1\")'), (r\"(\\w+\\s*)\\(\",",
"pickle.load(fi) exprs, columns = MyAlphaHandler.get_custom_config() raw_data = pd.read_csv('../stock_data/TSLA.csv', parse_dates=['time']) raw_data['data_time']",
"raw_data.sort_index(inplace=True) # print(raw_data) class MyFeature(Feature): def _load_internal(self, instrument, start_index, end_index,",
") kline_line = ( Line() .add_xaxis(xaxis_data=x_axises) .add_yaxis( series_name=\"cur_money\", y_axis=money, is_smooth=True,",
"= ( Line() .add_xaxis(xaxis_data=x_axises) .add_yaxis( series_name=\"cur_money\", y_axis=money, is_smooth=True, linestyle_opts=opts.LineStyleOpts(opacity=0.5), label_opts=opts.LabelOpts(is_show=False),",
"MyFeature(Feature): def _load_internal(self, instrument, start_index, end_index, freq): print(\"load\", self._name, instrument,",
"self._name, instrument, start_index, end_index, freq) return raw_data.loc[start_index:end_index][self._name] Operators.register(OpsList + [MyFeature])",
"import R from qlib.workflow.record_temp import SignalRecord, PortAnaRecord from qlib.utils import",
"symbol_size=7, itemstyle_opts=opts.ItemStyleOpts(color=\"green\") )) elif record['pred_score'] > score_thresh and not position:",
"itemstyle_opts=opts.ItemStyleOpts(color=\"green\") )) elif record['pred_score'] > score_thresh and not position: position",
"pred records = pre_data.to_dict(\"records\") cash = 50000 position = {}",
"= pred records = pre_data.to_dict(\"records\") cash = 50000 position =",
"elif record['pred_score'] > score_thresh and not position: position = dict(record)",
"obj[field] = series data = pd.DataFrame(obj) data.columns = columns view_time_start",
"kline_graph, grid_opts=opts.GridOpts(pos_left=\"3%\", pos_right=\"10%\", height=\"50%\"), ) grid_chart.add( kline_line, grid_opts=opts.GridOpts( pos_left=\"3%\", pos_right=\"10%\",",
"0.995 or record['pred_score'] < -score_thresh or position['hold_cnt'] >= hold_thresh): cash",
"record['high'] ]) if 'hold_cnt' in position: position['hold_cnt'] += 1 if",
"= 5 score_thresh = 0.001 x_axises, y_axises, mark_points, money =",
"class MyFeature(Feature): def _load_internal(self, instrument, start_index, end_index, freq): print(\"load\", self._name,",
"field obj = dict() for field in exprs: expression =",
"grid_opts=opts.GridOpts(pos_left=\"3%\", pos_right=\"10%\", height=\"50%\"), ) grid_chart.add( kline_line, grid_opts=opts.GridOpts( pos_left=\"3%\", pos_right=\"10%\", pos_top=\"60%\",",
"0 mark_points.append(opts.MarkPointItem( coord=[record['data_time'], record['high']], symbol='arrow', symbol_size=7, itemstyle_opts=opts.ItemStyleOpts(color=\"yellow\") )) cur_money =",
"position['hold_cnt'] = 0 mark_points.append(opts.MarkPointItem( coord=[record['data_time'], record['high']], symbol='arrow', symbol_size=7, itemstyle_opts=opts.ItemStyleOpts(color=\"yellow\") ))",
"pd.read_csv('../stock_data/TSLA.csv', parse_dates=['time']) raw_data['data_time'] = raw_data['time'].dt.strftime(\"%Y-%m-%d %H:%M:00\") raw_data.set_index('time', inplace=True) raw_data[\"vwap\"] =",
"series = series.astype(np.float32) obj[field] = series data = pd.DataFrame(obj) data.columns",
"axislabel_opts=opts.LabelOpts(is_show=False), ), yaxis_opts=opts.AxisOpts( min_='dataMin' ) ) ) grid_chart = Grid(init_opts=opts.InitOpts(width='2000px',",
"= pd.read_csv('../stock_data/TSLA.csv', parse_dates=['time']) raw_data['data_time'] = raw_data['time'].dt.strftime(\"%Y-%m-%d %H:%M:00\") raw_data.set_index('time', inplace=True) raw_data[\"vwap\"]",
"= 0.001 x_axises, y_axises, mark_points, money = [], [], [],",
"or position['hold_cnt'] >= hold_thresh): cash += position['amount'] * record['open'] position",
"Operators field = re.sub(pattern, new, field) return field obj =",
"position['amount'] * position['open'] # buy #print(\"buy\") position['hold_cnt'] = 0 mark_points.append(opts.MarkPointItem(",
"position = {} hold_thresh = 5 score_thresh = 0.001 x_axises,",
"qlib.utils import exists_qlib_data, init_instance_by_config from qlib.workflow import R from qlib.workflow.record_temp",
"import re from qlib.constant import REG_US from qlib.utils import exists_qlib_data,",
"start_index, end_index, freq) return raw_data.loc[start_index:end_index][self._name] Operators.register(OpsList + [MyFeature]) def my_parse_field(field):",
"position['amount'] * records[-1]['close'] print(\"cash:\", cash) kline_graph = ( Kline() .add_xaxis(x_axises)",
"yaxis_opts=opts.AxisOpts( min_='dataMin' ) ) ) grid_chart = Grid(init_opts=opts.InitOpts(width='2000px', height='900px')) grid_chart.add(",
"Line() .add_xaxis(xaxis_data=x_axises) .add_yaxis( series_name=\"cur_money\", y_axis=money, is_smooth=True, linestyle_opts=opts.LineStyleOpts(opacity=0.5), label_opts=opts.LabelOpts(is_show=False), markline_opts=opts.MarkLineOpts( data=[opts.MarkLineItem(y=50000)]",
"record['close'], record['low'], record['high'] ]) if 'hold_cnt' in position: position['hold_cnt'] +=",
"position['close'] * 0.995 or record['pred_score'] < -score_thresh or position['hold_cnt'] >=",
"position['close'] * 1.01 or record['open'] < position['close'] * 0.995 or",
"record['high']], symbol='arrow', symbol_size=7, itemstyle_opts=opts.ItemStyleOpts(color=\"yellow\") )) cur_money = cash if position:",
"cash) kline_graph = ( Kline() .add_xaxis(x_axises) .add_yaxis( \"kline\", y_axises, markpoint_opts=opts.MarkPointOpts(",
"), title_opts=opts.TitleOpts(title=\"%s_%s\" % (view_time_start, view_time_end)), datazoom_opts=[opts.DataZoomOpts(type_=\"inside\", xaxis_index=[0, 1],)], ) )",
"pyecharts.charts import Kline, Line, Grid from my_data_handler import MyAlphaHandler #",
"5 score_thresh = 0.001 x_axises, y_axises, mark_points, money = [],",
"columns = MyAlphaHandler.get_custom_config() raw_data = pd.read_csv('../stock_data/TSLA.csv', parse_dates=['time']) raw_data['data_time'] = raw_data['time'].dt.strftime(\"%Y-%m-%d",
"symbol_size=7, itemstyle_opts=opts.ItemStyleOpts(color=\"yellow\") )) cur_money = cash if position: cur_money +=",
"int(cash / position['open']) cash -= position['amount'] * position['open'] # buy",
"as opts from pyecharts.charts import Kline, Line, Grid from my_data_handler",
"view_time_end)), datazoom_opts=[opts.DataZoomOpts(type_=\"inside\", xaxis_index=[0, 1],)], ) ) kline_line = ( Line()",
"exprs, columns = MyAlphaHandler.get_custom_config() raw_data = pd.read_csv('../stock_data/TSLA.csv', parse_dates=['time']) raw_data['data_time'] =",
"#print(\"buy\") position['hold_cnt'] = 0 mark_points.append(opts.MarkPointItem( coord=[record['data_time'], record['high']], symbol='arrow', symbol_size=7, itemstyle_opts=opts.ItemStyleOpts(color=\"yellow\")",
"import xgboost as xgb import numpy as np import re",
"= [], [], [], [] for record in records: x_axises.append(record['data_time'])",
"raw_data[\"vwap\"] = np.nan raw_data.sort_index(inplace=True) # print(raw_data) class MyFeature(Feature): def _load_internal(self,",
".add_xaxis(xaxis_data=x_axises) .add_yaxis( series_name=\"cur_money\", y_axis=money, is_smooth=True, linestyle_opts=opts.LineStyleOpts(opacity=0.5), label_opts=opts.LabelOpts(is_show=False), markline_opts=opts.MarkLineOpts( data=[opts.MarkLineItem(y=50000)] ),",
"view_time_end = '2022-02-12' pre_data = raw_data.loc[view_time_start:view_time_end].copy() pred=model.model.predict(xgb.DMatrix(data.loc[view_time_start:view_time_end])) pre_data['pred_score'] = pred",
"import options as opts from pyecharts.charts import Kline, Line, Grid",
"= int(cash / position['open']) cash -= position['amount'] * position['open'] #",
"position and (record['open'] >= position['close'] * 1.01 or record['open'] <",
"= 50000 position = {} hold_thresh = 5 score_thresh =",
">= hold_thresh): cash += position['amount'] * record['open'] position = {}",
"or record['open'] < position['close'] * 0.995 or record['pred_score'] < -score_thresh",
"itemstyle_opts=opts.ItemStyleOpts(color=\"yellow\") )) cur_money = cash if position: cur_money += position['amount']",
"and not position: position = dict(record) position['amount'] = int(cash /",
"Operators, OpsList from qlib.data.base import Feature from pyecharts import options",
"+= position['amount'] * record['close'] money.append(cur_money) if position: cash += position['amount']",
"money = [], [], [], [] for record in records:",
"raw_data = pd.read_csv('../stock_data/TSLA.csv', parse_dates=['time']) raw_data['data_time'] = raw_data['time'].dt.strftime(\"%Y-%m-%d %H:%M:00\") raw_data.set_index('time', inplace=True)",
"{} hold_thresh = 5 score_thresh = 0.001 x_axises, y_axises, mark_points,",
"for field in exprs: expression = eval(my_parse_field(field)) series = expression.load('TSLA',",
"LocalExpressionProvider from qlib.data.ops import Operators, OpsList from qlib.data.base import Feature",
"print(\"load\", self._name, instrument, start_index, end_index, freq) return raw_data.loc[start_index:end_index][self._name] Operators.register(OpsList +",
"mark_points, money = [], [], [], [] for record in",
"instrument, start_index, end_index, freq): print(\"load\", self._name, instrument, start_index, end_index, freq)",
"model_file = r'.\\mlruns\\1\\d6536b056ba84a74be6b33971f443cf6\\artifacts\\trained_model' model_file = r'.\\mlruns\\1\\148ef1cd7acd48deac3eadc339ad3008\\artifacts\\trained_model' with open(model_file, 'rb') as",
"'hold_cnt' in position: position['hold_cnt'] += 1 if position and (record['open']",
"from pyecharts.charts import Kline, Line, Grid from my_data_handler import MyAlphaHandler",
">= position['close'] * 1.01 or record['open'] < position['close'] * 0.995",
"y_axis=money, is_smooth=True, linestyle_opts=opts.LineStyleOpts(opacity=0.5), label_opts=opts.LabelOpts(is_show=False), markline_opts=opts.MarkLineOpts( data=[opts.MarkLineItem(y=50000)] ), ) .set_global_opts( xaxis_opts=opts.AxisOpts(",
"open(model_file, 'rb') as fi: model = pickle.load(fi) exprs, columns =",
"'2022-02-12' pre_data = raw_data.loc[view_time_start:view_time_end].copy() pred=model.model.predict(xgb.DMatrix(data.loc[view_time_start:view_time_end])) pre_data['pred_score'] = pred records =",
"as pd import pickle import xgboost as xgb import numpy",
"( Line() .add_xaxis(xaxis_data=x_axises) .add_yaxis( series_name=\"cur_money\", y_axis=money, is_smooth=True, linestyle_opts=opts.LineStyleOpts(opacity=0.5), label_opts=opts.LabelOpts(is_show=False), markline_opts=opts.MarkLineOpts(",
"), ) .set_global_opts( xaxis_opts=opts.AxisOpts(is_scale=True), yaxis_opts=opts.AxisOpts( is_scale=True, splitarea_opts=opts.SplitAreaOpts( is_show=True, areastyle_opts=opts.AreaStyleOpts(opacity=1) ),",
"field in exprs: expression = eval(my_parse_field(field)) series = expression.load('TSLA', \"2022-01-02\",",
"hold_thresh = 5 score_thresh = 0.001 x_axises, y_axises, mark_points, money",
"dict() for field in exprs: expression = eval(my_parse_field(field)) series =",
"= series data = pd.DataFrame(obj) data.columns = columns view_time_start =",
"columns view_time_start = '2022-02-11' view_time_end = '2022-02-12' pre_data = raw_data.loc[view_time_start:view_time_end].copy()",
"import exists_qlib_data, init_instance_by_config from qlib.workflow import R from qlib.workflow.record_temp import",
"= dict() for field in exprs: expression = eval(my_parse_field(field)) series",
"import numpy as np import re from qlib.constant import REG_US",
"height=\"50%\"), ) grid_chart.add( kline_line, grid_opts=opts.GridOpts( pos_left=\"3%\", pos_right=\"10%\", pos_top=\"60%\", height=\"30%\" ),",
"import LocalExpressionProvider from qlib.data.ops import Operators, OpsList from qlib.data.base import",
"= expression.load('TSLA', \"2022-01-02\", \"2022-02-28\", \"1min\") series = series.astype(np.float32) obj[field] =",
"from my_data_handler import MyAlphaHandler # model_file = r'.\\mlruns\\1\\d6536b056ba84a74be6b33971f443cf6\\artifacts\\trained_model' model_file =",
"exists_qlib_data, init_instance_by_config from qlib.workflow import R from qlib.workflow.record_temp import SignalRecord,",
"model_file = r'.\\mlruns\\1\\148ef1cd7acd48deac3eadc339ad3008\\artifacts\\trained_model' with open(model_file, 'rb') as fi: model =",
"_load_internal(self, instrument, start_index, end_index, freq): print(\"load\", self._name, instrument, start_index, end_index,",
"cash += position['amount'] * records[-1]['close'] print(\"cash:\", cash) kline_graph = (",
".add_yaxis( series_name=\"cur_money\", y_axis=money, is_smooth=True, linestyle_opts=opts.LineStyleOpts(opacity=0.5), label_opts=opts.LabelOpts(is_show=False), markline_opts=opts.MarkLineOpts( data=[opts.MarkLineItem(y=50000)] ), )",
"), ) .set_global_opts( xaxis_opts=opts.AxisOpts( type_=\"category\", grid_index=2, axislabel_opts=opts.LabelOpts(is_show=False), ), yaxis_opts=opts.AxisOpts( min_='dataMin'",
"my_parse_field(field): if not isinstance(field, str): field = str(field) for pattern,",
"np.nan raw_data.sort_index(inplace=True) # print(raw_data) class MyFeature(Feature): def _load_internal(self, instrument, start_index,",
"grid_index=2, axislabel_opts=opts.LabelOpts(is_show=False), ), yaxis_opts=opts.AxisOpts( min_='dataMin' ) ) ) grid_chart =",
"in exprs: expression = eval(my_parse_field(field)) series = expression.load('TSLA', \"2022-01-02\", \"2022-02-28\",",
"[], [], [] for record in records: x_axises.append(record['data_time']) y_axises.append([ record['open'],",
"is_scale=True, splitarea_opts=opts.SplitAreaOpts( is_show=True, areastyle_opts=opts.AreaStyleOpts(opacity=1) ), ), title_opts=opts.TitleOpts(title=\"%s_%s\" % (view_time_start, view_time_end)),",
"import SignalRecord, PortAnaRecord from qlib.utils import flatten_dict from qlib.data import",
"coord=[record['data_time'], record['high']], symbol='triangle', symbol_size=7, itemstyle_opts=opts.ItemStyleOpts(color=\"green\") )) elif record['pred_score'] > score_thresh",
"grid_chart.add( kline_line, grid_opts=opts.GridOpts( pos_left=\"3%\", pos_right=\"10%\", pos_top=\"60%\", height=\"30%\" ), ) grid_chart.render(\"kline_markline.html\")",
"or record['pred_score'] < -score_thresh or position['hold_cnt'] >= hold_thresh): cash +=",
"pre_data['pred_score'] = pred records = pre_data.to_dict(\"records\") cash = 50000 position",
") grid_chart.add( kline_line, grid_opts=opts.GridOpts( pos_left=\"3%\", pos_right=\"10%\", pos_top=\"60%\", height=\"30%\" ), )",
"cur_money += position['amount'] * record['close'] money.append(cur_money) if position: cash +=",
"opts from pyecharts.charts import Kline, Line, Grid from my_data_handler import",
"in position: position['hold_cnt'] += 1 if position and (record['open'] >=",
"position = dict(record) position['amount'] = int(cash / position['open']) cash -=",
"view_time_start = '2022-02-11' view_time_end = '2022-02-12' pre_data = raw_data.loc[view_time_start:view_time_end].copy() pred=model.model.predict(xgb.DMatrix(data.loc[view_time_start:view_time_end]))",
"MyAlphaHandler.get_custom_config() raw_data = pd.read_csv('../stock_data/TSLA.csv', parse_dates=['time']) raw_data['data_time'] = raw_data['time'].dt.strftime(\"%Y-%m-%d %H:%M:00\") raw_data.set_index('time',",
"= raw_data.loc[view_time_start:view_time_end].copy() pred=model.model.predict(xgb.DMatrix(data.loc[view_time_start:view_time_end])) pre_data['pred_score'] = pred records = pre_data.to_dict(\"records\") cash",
"mark_points.append(opts.MarkPointItem( coord=[record['data_time'], record['high']], symbol='triangle', symbol_size=7, itemstyle_opts=opts.ItemStyleOpts(color=\"green\") )) elif record['pred_score'] >",
"not position: position = dict(record) position['amount'] = int(cash / position['open'])",
"cash = 50000 position = {} hold_thresh = 5 score_thresh",
"'2022-02-11' view_time_end = '2022-02-12' pre_data = raw_data.loc[view_time_start:view_time_end].copy() pred=model.model.predict(xgb.DMatrix(data.loc[view_time_start:view_time_end])) pre_data['pred_score'] =",
"[(r\"\\$(\\w+)\", rf'MyFeature(\"\\1\")'), (r\"(\\w+\\s*)\\(\", r\"Operators.\\1(\")]: # Features # Operators field =",
"print(\"cash:\", cash) kline_graph = ( Kline() .add_xaxis(x_axises) .add_yaxis( \"kline\", y_axises,",
"= {} #print(\"sell\") mark_points.append(opts.MarkPointItem( coord=[record['data_time'], record['high']], symbol='triangle', symbol_size=7, itemstyle_opts=opts.ItemStyleOpts(color=\"green\") ))",
"= Grid(init_opts=opts.InitOpts(width='2000px', height='900px')) grid_chart.add( kline_graph, grid_opts=opts.GridOpts(pos_left=\"3%\", pos_right=\"10%\", height=\"50%\"), ) grid_chart.add(",
"records[-1]['close'] print(\"cash:\", cash) kline_graph = ( Kline() .add_xaxis(x_axises) .add_yaxis( \"kline\",",
"for record in records: x_axises.append(record['data_time']) y_axises.append([ record['open'], record['close'], record['low'], record['high']",
"pd import pickle import xgboost as xgb import numpy as",
"x_axises.append(record['data_time']) y_axises.append([ record['open'], record['close'], record['low'], record['high'] ]) if 'hold_cnt' in",
"#encoding=utf-8 import qlib import pandas as pd import pickle import",
"xaxis_opts=opts.AxisOpts( type_=\"category\", grid_index=2, axislabel_opts=opts.LabelOpts(is_show=False), ), yaxis_opts=opts.AxisOpts( min_='dataMin' ) ) )",
"linestyle_opts=opts.LineStyleOpts(opacity=0.5), label_opts=opts.LabelOpts(is_show=False), markline_opts=opts.MarkLineOpts( data=[opts.MarkLineItem(y=50000)] ), ) .set_global_opts( xaxis_opts=opts.AxisOpts( type_=\"category\", grid_index=2,",
"end_index, freq) return raw_data.loc[start_index:end_index][self._name] Operators.register(OpsList + [MyFeature]) def my_parse_field(field): if",
"str(field) for pattern, new in [(r\"\\$(\\w+)\", rf'MyFeature(\"\\1\")'), (r\"(\\w+\\s*)\\(\", r\"Operators.\\1(\")]: #",
"series.astype(np.float32) obj[field] = series data = pd.DataFrame(obj) data.columns = columns",
"]) if 'hold_cnt' in position: position['hold_cnt'] += 1 if position",
"position: position['hold_cnt'] += 1 if position and (record['open'] >= position['close']",
"import qlib import pandas as pd import pickle import xgboost",
"new in [(r\"\\$(\\w+)\", rf'MyFeature(\"\\1\")'), (r\"(\\w+\\s*)\\(\", r\"Operators.\\1(\")]: # Features # Operators",
"record['open'] < position['close'] * 0.995 or record['pred_score'] < -score_thresh or",
"position: position = dict(record) position['amount'] = int(cash / position['open']) cash",
"pos_right=\"10%\", height=\"50%\"), ) grid_chart.add( kline_line, grid_opts=opts.GridOpts( pos_left=\"3%\", pos_right=\"10%\", pos_top=\"60%\", height=\"30%\"",
"obj = dict() for field in exprs: expression = eval(my_parse_field(field))",
"1],)], ) ) kline_line = ( Line() .add_xaxis(xaxis_data=x_axises) .add_yaxis( series_name=\"cur_money\",",
")) cur_money = cash if position: cur_money += position['amount'] *",
"-= position['amount'] * position['open'] # buy #print(\"buy\") position['hold_cnt'] = 0",
"my_data_handler import MyAlphaHandler # model_file = r'.\\mlruns\\1\\d6536b056ba84a74be6b33971f443cf6\\artifacts\\trained_model' model_file = r'.\\mlruns\\1\\148ef1cd7acd48deac3eadc339ad3008\\artifacts\\trained_model'",
"records = pre_data.to_dict(\"records\") cash = 50000 position = {} hold_thresh",
"qlib.workflow import R from qlib.workflow.record_temp import SignalRecord, PortAnaRecord from qlib.utils",
"< position['close'] * 0.995 or record['pred_score'] < -score_thresh or position['hold_cnt']",
"import pandas as pd import pickle import xgboost as xgb",
"# print(raw_data) class MyFeature(Feature): def _load_internal(self, instrument, start_index, end_index, freq):",
"datazoom_opts=[opts.DataZoomOpts(type_=\"inside\", xaxis_index=[0, 1],)], ) ) kline_line = ( Line() .add_xaxis(xaxis_data=x_axises)",
"import REG_US from qlib.utils import exists_qlib_data, init_instance_by_config from qlib.workflow import",
"= '2022-02-11' view_time_end = '2022-02-12' pre_data = raw_data.loc[view_time_start:view_time_end].copy() pred=model.model.predict(xgb.DMatrix(data.loc[view_time_start:view_time_end])) pre_data['pred_score']",
"raw_data.loc[start_index:end_index][self._name] Operators.register(OpsList + [MyFeature]) def my_parse_field(field): if not isinstance(field, str):",
"xgb import numpy as np import re from qlib.constant import",
"Grid from my_data_handler import MyAlphaHandler # model_file = r'.\\mlruns\\1\\d6536b056ba84a74be6b33971f443cf6\\artifacts\\trained_model' model_file",
"(r\"(\\w+\\s*)\\(\", r\"Operators.\\1(\")]: # Features # Operators field = re.sub(pattern, new,",
"* position['open'] # buy #print(\"buy\") position['hold_cnt'] = 0 mark_points.append(opts.MarkPointItem( coord=[record['data_time'],",
".add_xaxis(x_axises) .add_yaxis( \"kline\", y_axises, markpoint_opts=opts.MarkPointOpts( data=mark_points ), ) .set_global_opts( xaxis_opts=opts.AxisOpts(is_scale=True),",
"REG_US from qlib.utils import exists_qlib_data, init_instance_by_config from qlib.workflow import R",
"import Feature from pyecharts import options as opts from pyecharts.charts",
".add_yaxis( \"kline\", y_axises, markpoint_opts=opts.MarkPointOpts( data=mark_points ), ) .set_global_opts( xaxis_opts=opts.AxisOpts(is_scale=True), yaxis_opts=opts.AxisOpts(",
"return raw_data.loc[start_index:end_index][self._name] Operators.register(OpsList + [MyFeature]) def my_parse_field(field): if not isinstance(field,",
"coord=[record['data_time'], record['high']], symbol='arrow', symbol_size=7, itemstyle_opts=opts.ItemStyleOpts(color=\"yellow\") )) cur_money = cash if",
"init_instance_by_config from qlib.workflow import R from qlib.workflow.record_temp import SignalRecord, PortAnaRecord",
"-score_thresh or position['hold_cnt'] >= hold_thresh): cash += position['amount'] * record['open']",
"# model_file = r'.\\mlruns\\1\\d6536b056ba84a74be6b33971f443cf6\\artifacts\\trained_model' model_file = r'.\\mlruns\\1\\148ef1cd7acd48deac3eadc339ad3008\\artifacts\\trained_model' with open(model_file, 'rb')",
"[], [] for record in records: x_axises.append(record['data_time']) y_axises.append([ record['open'], record['close'],",
"(view_time_start, view_time_end)), datazoom_opts=[opts.DataZoomOpts(type_=\"inside\", xaxis_index=[0, 1],)], ) ) kline_line = (",
"markpoint_opts=opts.MarkPointOpts( data=mark_points ), ) .set_global_opts( xaxis_opts=opts.AxisOpts(is_scale=True), yaxis_opts=opts.AxisOpts( is_scale=True, splitarea_opts=opts.SplitAreaOpts( is_show=True,",
"return field obj = dict() for field in exprs: expression",
"qlib.data import LocalExpressionProvider from qlib.data.ops import Operators, OpsList from qlib.data.base",
"= MyAlphaHandler.get_custom_config() raw_data = pd.read_csv('../stock_data/TSLA.csv', parse_dates=['time']) raw_data['data_time'] = raw_data['time'].dt.strftime(\"%Y-%m-%d %H:%M:00\")",
"data.columns = columns view_time_start = '2022-02-11' view_time_end = '2022-02-12' pre_data",
"isinstance(field, str): field = str(field) for pattern, new in [(r\"\\$(\\w+)\",",
"yaxis_opts=opts.AxisOpts( is_scale=True, splitarea_opts=opts.SplitAreaOpts( is_show=True, areastyle_opts=opts.AreaStyleOpts(opacity=1) ), ), title_opts=opts.TitleOpts(title=\"%s_%s\" % (view_time_start,",
"height='900px')) grid_chart.add( kline_graph, grid_opts=opts.GridOpts(pos_left=\"3%\", pos_right=\"10%\", height=\"50%\"), ) grid_chart.add( kline_line, grid_opts=opts.GridOpts(",
"cur_money = cash if position: cur_money += position['amount'] * record['close']",
"not isinstance(field, str): field = str(field) for pattern, new in",
"field = re.sub(pattern, new, field) return field obj = dict()",
"%H:%M:00\") raw_data.set_index('time', inplace=True) raw_data[\"vwap\"] = np.nan raw_data.sort_index(inplace=True) # print(raw_data) class",
"hold_thresh): cash += position['amount'] * record['open'] position = {} #print(\"sell\")",
"flatten_dict from qlib.data import LocalExpressionProvider from qlib.data.ops import Operators, OpsList",
"/ position['open']) cash -= position['amount'] * position['open'] # buy #print(\"buy\")",
"qlib.utils import flatten_dict from qlib.data import LocalExpressionProvider from qlib.data.ops import",
"OpsList from qlib.data.base import Feature from pyecharts import options as",
".set_global_opts( xaxis_opts=opts.AxisOpts(is_scale=True), yaxis_opts=opts.AxisOpts( is_scale=True, splitarea_opts=opts.SplitAreaOpts( is_show=True, areastyle_opts=opts.AreaStyleOpts(opacity=1) ), ), title_opts=opts.TitleOpts(title=\"%s_%s\"",
"record['open'] position = {} #print(\"sell\") mark_points.append(opts.MarkPointItem( coord=[record['data_time'], record['high']], symbol='triangle', symbol_size=7,",
"str): field = str(field) for pattern, new in [(r\"\\$(\\w+)\", rf'MyFeature(\"\\1\")'),",
"pre_data = raw_data.loc[view_time_start:view_time_end].copy() pred=model.model.predict(xgb.DMatrix(data.loc[view_time_start:view_time_end])) pre_data['pred_score'] = pred records = pre_data.to_dict(\"records\")",
"re from qlib.constant import REG_US from qlib.utils import exists_qlib_data, init_instance_by_config",
"= eval(my_parse_field(field)) series = expression.load('TSLA', \"2022-01-02\", \"2022-02-28\", \"1min\") series =",
"< -score_thresh or position['hold_cnt'] >= hold_thresh): cash += position['amount'] *",
"% (view_time_start, view_time_end)), datazoom_opts=[opts.DataZoomOpts(type_=\"inside\", xaxis_index=[0, 1],)], ) ) kline_line =",
"symbol='arrow', symbol_size=7, itemstyle_opts=opts.ItemStyleOpts(color=\"yellow\") )) cur_money = cash if position: cur_money",
"record['low'], record['high'] ]) if 'hold_cnt' in position: position['hold_cnt'] += 1",
"= re.sub(pattern, new, field) return field obj = dict() for",
"import MyAlphaHandler # model_file = r'.\\mlruns\\1\\d6536b056ba84a74be6b33971f443cf6\\artifacts\\trained_model' model_file = r'.\\mlruns\\1\\148ef1cd7acd48deac3eadc339ad3008\\artifacts\\trained_model' with",
"= 0 mark_points.append(opts.MarkPointItem( coord=[record['data_time'], record['high']], symbol='arrow', symbol_size=7, itemstyle_opts=opts.ItemStyleOpts(color=\"yellow\") )) cur_money",
"Line, Grid from my_data_handler import MyAlphaHandler # model_file = r'.\\mlruns\\1\\d6536b056ba84a74be6b33971f443cf6\\artifacts\\trained_model'",
"rf'MyFeature(\"\\1\")'), (r\"(\\w+\\s*)\\(\", r\"Operators.\\1(\")]: # Features # Operators field = re.sub(pattern,",
") ) ) grid_chart = Grid(init_opts=opts.InitOpts(width='2000px', height='900px')) grid_chart.add( kline_graph, grid_opts=opts.GridOpts(pos_left=\"3%\",",
"and (record['open'] >= position['close'] * 1.01 or record['open'] < position['close']",
"= cash if position: cur_money += position['amount'] * record['close'] money.append(cur_money)",
"is_show=True, areastyle_opts=opts.AreaStyleOpts(opacity=1) ), ), title_opts=opts.TitleOpts(title=\"%s_%s\" % (view_time_start, view_time_end)), datazoom_opts=[opts.DataZoomOpts(type_=\"inside\", xaxis_index=[0,",
"y_axises, markpoint_opts=opts.MarkPointOpts( data=mark_points ), ) .set_global_opts( xaxis_opts=opts.AxisOpts(is_scale=True), yaxis_opts=opts.AxisOpts( is_scale=True, splitarea_opts=opts.SplitAreaOpts(",
"as xgb import numpy as np import re from qlib.constant",
"from qlib.utils import exists_qlib_data, init_instance_by_config from qlib.workflow import R from",
"data = pd.DataFrame(obj) data.columns = columns view_time_start = '2022-02-11' view_time_end",
"xaxis_index=[0, 1],)], ) ) kline_line = ( Line() .add_xaxis(xaxis_data=x_axises) .add_yaxis(",
"\"2022-01-02\", \"2022-02-28\", \"1min\") series = series.astype(np.float32) obj[field] = series data",
"xaxis_opts=opts.AxisOpts(is_scale=True), yaxis_opts=opts.AxisOpts( is_scale=True, splitarea_opts=opts.SplitAreaOpts( is_show=True, areastyle_opts=opts.AreaStyleOpts(opacity=1) ), ), title_opts=opts.TitleOpts(title=\"%s_%s\" %",
"expression = eval(my_parse_field(field)) series = expression.load('TSLA', \"2022-01-02\", \"2022-02-28\", \"1min\") series",
"cash if position: cur_money += position['amount'] * record['close'] money.append(cur_money) if",
"def _load_internal(self, instrument, start_index, end_index, freq): print(\"load\", self._name, instrument, start_index,",
"min_='dataMin' ) ) ) grid_chart = Grid(init_opts=opts.InitOpts(width='2000px', height='900px')) grid_chart.add( kline_graph,",
"= series.astype(np.float32) obj[field] = series data = pd.DataFrame(obj) data.columns =",
"* record['open'] position = {} #print(\"sell\") mark_points.append(opts.MarkPointItem( coord=[record['data_time'], record['high']], symbol='triangle',",
"= pre_data.to_dict(\"records\") cash = 50000 position = {} hold_thresh =",
"if position and (record['open'] >= position['close'] * 1.01 or record['open']",
"eval(my_parse_field(field)) series = expression.load('TSLA', \"2022-01-02\", \"2022-02-28\", \"1min\") series = series.astype(np.float32)",
"x_axises, y_axises, mark_points, money = [], [], [], [] for",
"# buy #print(\"buy\") position['hold_cnt'] = 0 mark_points.append(opts.MarkPointItem( coord=[record['data_time'], record['high']], symbol='arrow',",
"Operators.register(OpsList + [MyFeature]) def my_parse_field(field): if not isinstance(field, str): field",
"record['close'] money.append(cur_money) if position: cash += position['amount'] * records[-1]['close'] print(\"cash:\",",
"parse_dates=['time']) raw_data['data_time'] = raw_data['time'].dt.strftime(\"%Y-%m-%d %H:%M:00\") raw_data.set_index('time', inplace=True) raw_data[\"vwap\"] = np.nan",
"position['hold_cnt'] >= hold_thresh): cash += position['amount'] * record['open'] position =",
"{} #print(\"sell\") mark_points.append(opts.MarkPointItem( coord=[record['data_time'], record['high']], symbol='triangle', symbol_size=7, itemstyle_opts=opts.ItemStyleOpts(color=\"green\") )) elif",
"series = expression.load('TSLA', \"2022-01-02\", \"2022-02-28\", \"1min\") series = series.astype(np.float32) obj[field]",
"= dict(record) position['amount'] = int(cash / position['open']) cash -= position['amount']",
"( Kline() .add_xaxis(x_axises) .add_yaxis( \"kline\", y_axises, markpoint_opts=opts.MarkPointOpts( data=mark_points ), )",
"type_=\"category\", grid_index=2, axislabel_opts=opts.LabelOpts(is_show=False), ), yaxis_opts=opts.AxisOpts( min_='dataMin' ) ) ) grid_chart",
"Kline, Line, Grid from my_data_handler import MyAlphaHandler # model_file =",
"money.append(cur_money) if position: cash += position['amount'] * records[-1]['close'] print(\"cash:\", cash)",
"* records[-1]['close'] print(\"cash:\", cash) kline_graph = ( Kline() .add_xaxis(x_axises) .add_yaxis(",
"pyecharts import options as opts from pyecharts.charts import Kline, Line,",
"pattern, new in [(r\"\\$(\\w+)\", rf'MyFeature(\"\\1\")'), (r\"(\\w+\\s*)\\(\", r\"Operators.\\1(\")]: # Features #",
"score_thresh = 0.001 x_axises, y_axises, mark_points, money = [], [],",
"if position: cur_money += position['amount'] * record['close'] money.append(cur_money) if position:",
"print(raw_data) class MyFeature(Feature): def _load_internal(self, instrument, start_index, end_index, freq): print(\"load\",",
") .set_global_opts( xaxis_opts=opts.AxisOpts(is_scale=True), yaxis_opts=opts.AxisOpts( is_scale=True, splitarea_opts=opts.SplitAreaOpts( is_show=True, areastyle_opts=opts.AreaStyleOpts(opacity=1) ), ),",
"position['hold_cnt'] += 1 if position and (record['open'] >= position['close'] *",
"raw_data['data_time'] = raw_data['time'].dt.strftime(\"%Y-%m-%d %H:%M:00\") raw_data.set_index('time', inplace=True) raw_data[\"vwap\"] = np.nan raw_data.sort_index(inplace=True)",
"= raw_data['time'].dt.strftime(\"%Y-%m-%d %H:%M:00\") raw_data.set_index('time', inplace=True) raw_data[\"vwap\"] = np.nan raw_data.sort_index(inplace=True) #",
"from qlib.data.ops import Operators, OpsList from qlib.data.base import Feature from",
"r'.\\mlruns\\1\\d6536b056ba84a74be6b33971f443cf6\\artifacts\\trained_model' model_file = r'.\\mlruns\\1\\148ef1cd7acd48deac3eadc339ad3008\\artifacts\\trained_model' with open(model_file, 'rb') as fi: model",
"buy #print(\"buy\") position['hold_cnt'] = 0 mark_points.append(opts.MarkPointItem( coord=[record['data_time'], record['high']], symbol='arrow', symbol_size=7,",
"from qlib.workflow import R from qlib.workflow.record_temp import SignalRecord, PortAnaRecord from",
"Grid(init_opts=opts.InitOpts(width='2000px', height='900px')) grid_chart.add( kline_graph, grid_opts=opts.GridOpts(pos_left=\"3%\", pos_right=\"10%\", height=\"50%\"), ) grid_chart.add( kline_line,",
"position: cash += position['amount'] * records[-1]['close'] print(\"cash:\", cash) kline_graph =",
"freq) return raw_data.loc[start_index:end_index][self._name] Operators.register(OpsList + [MyFeature]) def my_parse_field(field): if not",
"[MyFeature]) def my_parse_field(field): if not isinstance(field, str): field = str(field)",
"series_name=\"cur_money\", y_axis=money, is_smooth=True, linestyle_opts=opts.LineStyleOpts(opacity=0.5), label_opts=opts.LabelOpts(is_show=False), markline_opts=opts.MarkLineOpts( data=[opts.MarkLineItem(y=50000)] ), ) .set_global_opts(",
"inplace=True) raw_data[\"vwap\"] = np.nan raw_data.sort_index(inplace=True) # print(raw_data) class MyFeature(Feature): def",
"expression.load('TSLA', \"2022-01-02\", \"2022-02-28\", \"1min\") series = series.astype(np.float32) obj[field] = series",
"Features # Operators field = re.sub(pattern, new, field) return field",
"grid_chart = Grid(init_opts=opts.InitOpts(width='2000px', height='900px')) grid_chart.add( kline_graph, grid_opts=opts.GridOpts(pos_left=\"3%\", pos_right=\"10%\", height=\"50%\"), )",
"r\"Operators.\\1(\")]: # Features # Operators field = re.sub(pattern, new, field)",
")) elif record['pred_score'] > score_thresh and not position: position =",
"R from qlib.workflow.record_temp import SignalRecord, PortAnaRecord from qlib.utils import flatten_dict",
"xgboost as xgb import numpy as np import re from",
"* 1.01 or record['open'] < position['close'] * 0.995 or record['pred_score']",
"0.001 x_axises, y_axises, mark_points, money = [], [], [], []",
"PortAnaRecord from qlib.utils import flatten_dict from qlib.data import LocalExpressionProvider from",
"[], [], [], [] for record in records: x_axises.append(record['data_time']) y_axises.append([",
"field) return field obj = dict() for field in exprs:",
"is_smooth=True, linestyle_opts=opts.LineStyleOpts(opacity=0.5), label_opts=opts.LabelOpts(is_show=False), markline_opts=opts.MarkLineOpts( data=[opts.MarkLineItem(y=50000)] ), ) .set_global_opts( xaxis_opts=opts.AxisOpts( type_=\"category\",",
"= ( Kline() .add_xaxis(x_axises) .add_yaxis( \"kline\", y_axises, markpoint_opts=opts.MarkPointOpts( data=mark_points ),",
"* record['close'] money.append(cur_money) if position: cash += position['amount'] * records[-1]['close']",
"score_thresh and not position: position = dict(record) position['amount'] = int(cash",
"# Features # Operators field = re.sub(pattern, new, field) return",
"import flatten_dict from qlib.data import LocalExpressionProvider from qlib.data.ops import Operators,",
"r'.\\mlruns\\1\\148ef1cd7acd48deac3eadc339ad3008\\artifacts\\trained_model' with open(model_file, 'rb') as fi: model = pickle.load(fi) exprs,",
"title_opts=opts.TitleOpts(title=\"%s_%s\" % (view_time_start, view_time_end)), datazoom_opts=[opts.DataZoomOpts(type_=\"inside\", xaxis_index=[0, 1],)], ) ) kline_line",
"qlib.workflow.record_temp import SignalRecord, PortAnaRecord from qlib.utils import flatten_dict from qlib.data",
"qlib.constant import REG_US from qlib.utils import exists_qlib_data, init_instance_by_config from qlib.workflow",
"from qlib.workflow.record_temp import SignalRecord, PortAnaRecord from qlib.utils import flatten_dict from",
") ) grid_chart = Grid(init_opts=opts.InitOpts(width='2000px', height='900px')) grid_chart.add( kline_graph, grid_opts=opts.GridOpts(pos_left=\"3%\", pos_right=\"10%\",",
"= np.nan raw_data.sort_index(inplace=True) # print(raw_data) class MyFeature(Feature): def _load_internal(self, instrument,",
"position = {} #print(\"sell\") mark_points.append(opts.MarkPointItem( coord=[record['data_time'], record['high']], symbol='triangle', symbol_size=7, itemstyle_opts=opts.ItemStyleOpts(color=\"green\")",
"\"2022-02-28\", \"1min\") series = series.astype(np.float32) obj[field] = series data =",
"+ [MyFeature]) def my_parse_field(field): if not isinstance(field, str): field =",
"Feature from pyecharts import options as opts from pyecharts.charts import",
"from qlib.data import LocalExpressionProvider from qlib.data.ops import Operators, OpsList from",
"'rb') as fi: model = pickle.load(fi) exprs, columns = MyAlphaHandler.get_custom_config()",
"cash -= position['amount'] * position['open'] # buy #print(\"buy\") position['hold_cnt'] =",
"from qlib.data.base import Feature from pyecharts import options as opts",
"position['open']) cash -= position['amount'] * position['open'] # buy #print(\"buy\") position['hold_cnt']",
"Kline() .add_xaxis(x_axises) .add_yaxis( \"kline\", y_axises, markpoint_opts=opts.MarkPointOpts( data=mark_points ), ) .set_global_opts(",
"= str(field) for pattern, new in [(r\"\\$(\\w+)\", rf'MyFeature(\"\\1\")'), (r\"(\\w+\\s*)\\(\", r\"Operators.\\1(\")]:",
"record['pred_score'] < -score_thresh or position['hold_cnt'] >= hold_thresh): cash += position['amount']",
"+= 1 if position and (record['open'] >= position['close'] * 1.01",
"# Operators field = re.sub(pattern, new, field) return field obj",
"(record['open'] >= position['close'] * 1.01 or record['open'] < position['close'] *",
"1.01 or record['open'] < position['close'] * 0.995 or record['pred_score'] <",
"as fi: model = pickle.load(fi) exprs, columns = MyAlphaHandler.get_custom_config() raw_data",
"pre_data.to_dict(\"records\") cash = 50000 position = {} hold_thresh = 5",
"from qlib.constant import REG_US from qlib.utils import exists_qlib_data, init_instance_by_config from",
"* 0.995 or record['pred_score'] < -score_thresh or position['hold_cnt'] >= hold_thresh):",
"model = pickle.load(fi) exprs, columns = MyAlphaHandler.get_custom_config() raw_data = pd.read_csv('../stock_data/TSLA.csv',",
"= r'.\\mlruns\\1\\d6536b056ba84a74be6b33971f443cf6\\artifacts\\trained_model' model_file = r'.\\mlruns\\1\\148ef1cd7acd48deac3eadc339ad3008\\artifacts\\trained_model' with open(model_file, 'rb') as fi:",
"in records: x_axises.append(record['data_time']) y_axises.append([ record['open'], record['close'], record['low'], record['high'] ]) if",
"), yaxis_opts=opts.AxisOpts( min_='dataMin' ) ) ) grid_chart = Grid(init_opts=opts.InitOpts(width='2000px', height='900px'))",
"= columns view_time_start = '2022-02-11' view_time_end = '2022-02-12' pre_data =",
"kline_line = ( Line() .add_xaxis(xaxis_data=x_axises) .add_yaxis( series_name=\"cur_money\", y_axis=money, is_smooth=True, linestyle_opts=opts.LineStyleOpts(opacity=0.5),",
") .set_global_opts( xaxis_opts=opts.AxisOpts( type_=\"category\", grid_index=2, axislabel_opts=opts.LabelOpts(is_show=False), ), yaxis_opts=opts.AxisOpts( min_='dataMin' )",
"+= position['amount'] * records[-1]['close'] print(\"cash:\", cash) kline_graph = ( Kline()",
"record['pred_score'] > score_thresh and not position: position = dict(record) position['amount']",
"import pickle import xgboost as xgb import numpy as np",
"\"1min\") series = series.astype(np.float32) obj[field] = series data = pd.DataFrame(obj)",
"y_axises, mark_points, money = [], [], [], [] for record",
"freq): print(\"load\", self._name, instrument, start_index, end_index, freq) return raw_data.loc[start_index:end_index][self._name] Operators.register(OpsList",
"position['open'] # buy #print(\"buy\") position['hold_cnt'] = 0 mark_points.append(opts.MarkPointItem( coord=[record['data_time'], record['high']],",
"1 if position and (record['open'] >= position['close'] * 1.01 or",
"position: cur_money += position['amount'] * record['close'] money.append(cur_money) if position: cash",
"import Kline, Line, Grid from my_data_handler import MyAlphaHandler # model_file",
"MyAlphaHandler # model_file = r'.\\mlruns\\1\\d6536b056ba84a74be6b33971f443cf6\\artifacts\\trained_model' model_file = r'.\\mlruns\\1\\148ef1cd7acd48deac3eadc339ad3008\\artifacts\\trained_model' with open(model_file,",
"mark_points.append(opts.MarkPointItem( coord=[record['data_time'], record['high']], symbol='arrow', symbol_size=7, itemstyle_opts=opts.ItemStyleOpts(color=\"yellow\") )) cur_money = cash",
"50000 position = {} hold_thresh = 5 score_thresh = 0.001",
"start_index, end_index, freq): print(\"load\", self._name, instrument, start_index, end_index, freq) return",
"areastyle_opts=opts.AreaStyleOpts(opacity=1) ), ), title_opts=opts.TitleOpts(title=\"%s_%s\" % (view_time_start, view_time_end)), datazoom_opts=[opts.DataZoomOpts(type_=\"inside\", xaxis_index=[0, 1],)],",
"data=mark_points ), ) .set_global_opts( xaxis_opts=opts.AxisOpts(is_scale=True), yaxis_opts=opts.AxisOpts( is_scale=True, splitarea_opts=opts.SplitAreaOpts( is_show=True, areastyle_opts=opts.AreaStyleOpts(opacity=1)",
"y_axises.append([ record['open'], record['close'], record['low'], record['high'] ]) if 'hold_cnt' in position:",
"splitarea_opts=opts.SplitAreaOpts( is_show=True, areastyle_opts=opts.AreaStyleOpts(opacity=1) ), ), title_opts=opts.TitleOpts(title=\"%s_%s\" % (view_time_start, view_time_end)), datazoom_opts=[opts.DataZoomOpts(type_=\"inside\",",
"> score_thresh and not position: position = dict(record) position['amount'] =",
"with open(model_file, 'rb') as fi: model = pickle.load(fi) exprs, columns",
"+= position['amount'] * record['open'] position = {} #print(\"sell\") mark_points.append(opts.MarkPointItem( coord=[record['data_time'],",
"instrument, start_index, end_index, freq) return raw_data.loc[start_index:end_index][self._name] Operators.register(OpsList + [MyFeature]) def",
"\"kline\", y_axises, markpoint_opts=opts.MarkPointOpts( data=mark_points ), ) .set_global_opts( xaxis_opts=opts.AxisOpts(is_scale=True), yaxis_opts=opts.AxisOpts( is_scale=True,",
"SignalRecord, PortAnaRecord from qlib.utils import flatten_dict from qlib.data import LocalExpressionProvider",
"= pickle.load(fi) exprs, columns = MyAlphaHandler.get_custom_config() raw_data = pd.read_csv('../stock_data/TSLA.csv', parse_dates=['time'])",
"pred=model.model.predict(xgb.DMatrix(data.loc[view_time_start:view_time_end])) pre_data['pred_score'] = pred records = pre_data.to_dict(\"records\") cash = 50000",
"in [(r\"\\$(\\w+)\", rf'MyFeature(\"\\1\")'), (r\"(\\w+\\s*)\\(\", r\"Operators.\\1(\")]: # Features # Operators field",
"numpy as np import re from qlib.constant import REG_US from",
") ) kline_line = ( Line() .add_xaxis(xaxis_data=x_axises) .add_yaxis( series_name=\"cur_money\", y_axis=money,",
"position['amount'] * record['open'] position = {} #print(\"sell\") mark_points.append(opts.MarkPointItem( coord=[record['data_time'], record['high']],",
"raw_data.set_index('time', inplace=True) raw_data[\"vwap\"] = np.nan raw_data.sort_index(inplace=True) # print(raw_data) class MyFeature(Feature):",
"np import re from qlib.constant import REG_US from qlib.utils import",
"as np import re from qlib.constant import REG_US from qlib.utils",
"record['high']], symbol='triangle', symbol_size=7, itemstyle_opts=opts.ItemStyleOpts(color=\"green\") )) elif record['pred_score'] > score_thresh and",
"record in records: x_axises.append(record['data_time']) y_axises.append([ record['open'], record['close'], record['low'], record['high'] ])",
"fi: model = pickle.load(fi) exprs, columns = MyAlphaHandler.get_custom_config() raw_data =",
"options as opts from pyecharts.charts import Kline, Line, Grid from",
"pickle import xgboost as xgb import numpy as np import"
] |
[
"fastapi import APIRouter router = APIRouter() @router.get(\"/\") def working(): return",
"from fastapi import APIRouter router = APIRouter() @router.get(\"/\") def working():",
"import APIRouter router = APIRouter() @router.get(\"/\") def working(): return {\"Working\"}"
] |
[
"best_t = 0 for epoch in range(nb_epochs): model.train() optimiser.zero_grad() idx",
"= 1 nb_epochs = 10000 patience = 20 lr =",
"import networkx as nx import time from embed_methods.dgi.models import DGI,",
"numpy as np import scipy.sparse as sp import torch import",
"sp.lil_matrix(np.matrix(features)) features, _ = process.preprocess_features(features) nb_nodes = features.shape[0] ft_size =",
"= DGI(ft_size, hid_units, nonlinearity) optimiser = torch.optim.Adam(model.parameters(), lr=lr, weight_decay=l2_coef) if",
"torch.cuda.is_available(): shuf_fts = shuf_fts.cuda() lbl = lbl.cuda() logits = model(features,",
"< best: best = loss best_t = epoch cnt_wait =",
"= features.shape[1] adj = process.normalize_adj(adj + sp.eye(adj.shape[0])) if sparse: sp_adj",
"torch.FloatTensor(features[np.newaxis]) if not sparse: adj = torch.FloatTensor(adj[np.newaxis]) model = DGI(ft_size,",
"features = features.cuda() if sparse: sp_adj = sp_adj.cuda() else: adj",
"= lbl.cuda() logits = model(features, shuf_fts, sp_adj if sparse else",
"= np.random.permutation(nb_nodes) shuf_fts = features[:, idx, :] lbl_1 = torch.ones(batch_size,",
"nb_nodes = features.shape[0] ft_size = features.shape[1] adj = process.normalize_adj(adj +",
"adj = (adj + sp.eye(adj.shape[0])).todense() features = torch.FloatTensor(features[np.newaxis]) if not",
"0.001 l2_coef = 0.0 drop_prob = 0.0 hid_units = 512",
"lbl_2 = torch.zeros(batch_size, nb_nodes) lbl = torch.cat((lbl_1, lbl_2), 1) if",
"optimiser = torch.optim.Adam(model.parameters(), lr=lr, weight_decay=l2_coef) if torch.cuda.is_available(): print('Using CUDA') model.cuda()",
"torch.FloatTensor(adj[np.newaxis]) model = DGI(ft_size, hid_units, nonlinearity) optimiser = torch.optim.Adam(model.parameters(), lr=lr,",
"nonlinearity) optimiser = torch.optim.Adam(model.parameters(), lr=lr, weight_decay=l2_coef) if torch.cuda.is_available(): print('Using CUDA')",
"= 0 best = 1e9 best_t = 0 for epoch",
"nonlinearity = 'prelu' # special name to separate parameters adj",
"cnt_wait = 0 else: cnt_wait += 1 if cnt_wait ==",
"epoch) print('Early stopping!') break loss.backward() optimiser.step() return (((model.embed(features, sp_adj if",
"as sp import torch import torch.nn as nn import networkx",
"adj = nx.to_scipy_sparse_matrix(G, weight='wgt') features = sp.lil_matrix(np.matrix(features)) features, _ =",
"0 else: cnt_wait += 1 if cnt_wait == patience: print(\"epochs:",
"sparse, None, None, None) loss = b_xent(logits, lbl) print('Loss:', loss)",
"= nx.to_scipy_sparse_matrix(G, weight='wgt') features = sp.lil_matrix(np.matrix(features)) features, _ = process.preprocess_features(features)",
"scipy.sparse as sp import torch import torch.nn as nn import",
"ft_size = features.shape[1] adj = process.normalize_adj(adj + sp.eye(adj.shape[0])) if sparse:",
"if sparse: sp_adj = process.sparse_mx_to_torch_sparse_tensor(adj) else: adj = (adj +",
"features = sp.lil_matrix(np.matrix(features)) features, _ = process.preprocess_features(features) nb_nodes = features.shape[0]",
"import torch.nn as nn import networkx as nx import time",
"nb_nodes) lbl = torch.cat((lbl_1, lbl_2), 1) if torch.cuda.is_available(): shuf_fts =",
"True nonlinearity = 'prelu' # special name to separate parameters",
"import numpy as np import scipy.sparse as sp import torch",
"= shuf_fts.cuda() lbl = lbl.cuda() logits = model(features, shuf_fts, sp_adj",
"None, None) loss = b_xent(logits, lbl) print('Loss:', loss) if loss",
"lbl) print('Loss:', loss) if loss < best: best = loss",
"if cnt_wait == patience: print(\"epochs: \", epoch) print('Early stopping!') break",
"idx, :] lbl_1 = torch.ones(batch_size, nb_nodes) lbl_2 = torch.zeros(batch_size, nb_nodes)",
"0 for epoch in range(nb_epochs): model.train() optimiser.zero_grad() idx = np.random.permutation(nb_nodes)",
"separate parameters adj = nx.to_scipy_sparse_matrix(G, weight='wgt') features = sp.lil_matrix(np.matrix(features)) features,",
"+ sp.eye(adj.shape[0])) if sparse: sp_adj = process.sparse_mx_to_torch_sparse_tensor(adj) else: adj =",
"nn.BCEWithLogitsLoss() xent = nn.CrossEntropyLoss() cnt_wait = 0 best = 1e9",
"= 'prelu' # special name to separate parameters adj =",
"process.preprocess_features(features) nb_nodes = features.shape[0] ft_size = features.shape[1] adj = process.normalize_adj(adj",
"= sp_adj.cuda() else: adj = adj.cuda() b_xent = nn.BCEWithLogitsLoss() xent",
"import torch import torch.nn as nn import networkx as nx",
"process.sparse_mx_to_torch_sparse_tensor(adj) else: adj = (adj + sp.eye(adj.shape[0])).todense() features = torch.FloatTensor(features[np.newaxis])",
"range(nb_epochs): model.train() optimiser.zero_grad() idx = np.random.permutation(nb_nodes) shuf_fts = features[:, idx,",
"+= 1 if cnt_wait == patience: print(\"epochs: \", epoch) print('Early",
"LogReg from embed_methods.dgi.utils import process def dgi(G, features): batch_size =",
"adj = process.normalize_adj(adj + sp.eye(adj.shape[0])) if sparse: sp_adj = process.sparse_mx_to_torch_sparse_tensor(adj)",
"CUDA') model.cuda() features = features.cuda() if sparse: sp_adj = sp_adj.cuda()",
"adj, sparse, None, None, None) loss = b_xent(logits, lbl) print('Loss:',",
"best = 1e9 best_t = 0 for epoch in range(nb_epochs):",
"hid_units, nonlinearity) optimiser = torch.optim.Adam(model.parameters(), lr=lr, weight_decay=l2_coef) if torch.cuda.is_available(): print('Using",
"model.cuda() features = features.cuda() if sparse: sp_adj = sp_adj.cuda() else:",
"= process.normalize_adj(adj + sp.eye(adj.shape[0])) if sparse: sp_adj = process.sparse_mx_to_torch_sparse_tensor(adj) else:",
"if not sparse: adj = torch.FloatTensor(adj[np.newaxis]) model = DGI(ft_size, hid_units,",
"if sparse else adj, sparse, None, None, None) loss =",
"else adj, sparse, None, None, None) loss = b_xent(logits, lbl)",
"else: adj = (adj + sp.eye(adj.shape[0])).todense() features = torch.FloatTensor(features[np.newaxis]) if",
"dgi(G, features): batch_size = 1 nb_epochs = 10000 patience =",
"= 0.0 hid_units = 512 sparse = True nonlinearity =",
"adj.cuda() b_xent = nn.BCEWithLogitsLoss() xent = nn.CrossEntropyLoss() cnt_wait = 0",
"lbl_1 = torch.ones(batch_size, nb_nodes) lbl_2 = torch.zeros(batch_size, nb_nodes) lbl =",
"# special name to separate parameters adj = nx.to_scipy_sparse_matrix(G, weight='wgt')",
"DGI, LogReg from embed_methods.dgi.utils import process def dgi(G, features): batch_size",
"sparse: sp_adj = sp_adj.cuda() else: adj = adj.cuda() b_xent =",
":] lbl_1 = torch.ones(batch_size, nb_nodes) lbl_2 = torch.zeros(batch_size, nb_nodes) lbl",
"torch.zeros(batch_size, nb_nodes) lbl = torch.cat((lbl_1, lbl_2), 1) if torch.cuda.is_available(): shuf_fts",
"print('Early stopping!') break loss.backward() optimiser.step() return (((model.embed(features, sp_adj if sparse",
"loss.backward() optimiser.step() return (((model.embed(features, sp_adj if sparse else adj, sparse,",
"process.normalize_adj(adj + sp.eye(adj.shape[0])) if sparse: sp_adj = process.sparse_mx_to_torch_sparse_tensor(adj) else: adj",
"as nn import networkx as nx import time from embed_methods.dgi.models",
"= torch.zeros(batch_size, nb_nodes) lbl = torch.cat((lbl_1, lbl_2), 1) if torch.cuda.is_available():",
"1 nb_epochs = 10000 patience = 20 lr = 0.001",
"_ = process.preprocess_features(features) nb_nodes = features.shape[0] ft_size = features.shape[1] adj",
"def dgi(G, features): batch_size = 1 nb_epochs = 10000 patience",
"logits = model(features, shuf_fts, sp_adj if sparse else adj, sparse,",
"= 20 lr = 0.001 l2_coef = 0.0 drop_prob =",
"optimiser.zero_grad() idx = np.random.permutation(nb_nodes) shuf_fts = features[:, idx, :] lbl_1",
"to separate parameters adj = nx.to_scipy_sparse_matrix(G, weight='wgt') features = sp.lil_matrix(np.matrix(features))",
"torch.optim.Adam(model.parameters(), lr=lr, weight_decay=l2_coef) if torch.cuda.is_available(): print('Using CUDA') model.cuda() features =",
"if sparse: sp_adj = sp_adj.cuda() else: adj = adj.cuda() b_xent",
"embed_methods.dgi.utils import process def dgi(G, features): batch_size = 1 nb_epochs",
"= features[:, idx, :] lbl_1 = torch.ones(batch_size, nb_nodes) lbl_2 =",
"= torch.optim.Adam(model.parameters(), lr=lr, weight_decay=l2_coef) if torch.cuda.is_available(): print('Using CUDA') model.cuda() features",
"import DGI, LogReg from embed_methods.dgi.utils import process def dgi(G, features):",
"= True nonlinearity = 'prelu' # special name to separate",
"model(features, shuf_fts, sp_adj if sparse else adj, sparse, None, None,",
"torch.cat((lbl_1, lbl_2), 1) if torch.cuda.is_available(): shuf_fts = shuf_fts.cuda() lbl =",
"torch.nn as nn import networkx as nx import time from",
"lbl_2), 1) if torch.cuda.is_available(): shuf_fts = shuf_fts.cuda() lbl = lbl.cuda()",
"loss < best: best = loss best_t = epoch cnt_wait",
"epoch cnt_wait = 0 else: cnt_wait += 1 if cnt_wait",
"nn import networkx as nx import time from embed_methods.dgi.models import",
"patience = 20 lr = 0.001 l2_coef = 0.0 drop_prob",
"20 lr = 0.001 l2_coef = 0.0 drop_prob = 0.0",
"+ sp.eye(adj.shape[0])).todense() features = torch.FloatTensor(features[np.newaxis]) if not sparse: adj =",
"name to separate parameters adj = nx.to_scipy_sparse_matrix(G, weight='wgt') features =",
"= torch.FloatTensor(features[np.newaxis]) if not sparse: adj = torch.FloatTensor(adj[np.newaxis]) model =",
"= 512 sparse = True nonlinearity = 'prelu' # special",
"print('Loss:', loss) if loss < best: best = loss best_t",
"idx = np.random.permutation(nb_nodes) shuf_fts = features[:, idx, :] lbl_1 =",
"= adj.cuda() b_xent = nn.BCEWithLogitsLoss() xent = nn.CrossEntropyLoss() cnt_wait =",
"networkx as nx import time from embed_methods.dgi.models import DGI, LogReg",
"else: adj = adj.cuda() b_xent = nn.BCEWithLogitsLoss() xent = nn.CrossEntropyLoss()",
"lbl = lbl.cuda() logits = model(features, shuf_fts, sp_adj if sparse",
"= 0.0 drop_prob = 0.0 hid_units = 512 sparse =",
"= torch.ones(batch_size, nb_nodes) lbl_2 = torch.zeros(batch_size, nb_nodes) lbl = torch.cat((lbl_1,",
"= b_xent(logits, lbl) print('Loss:', loss) if loss < best: best",
"model = DGI(ft_size, hid_units, nonlinearity) optimiser = torch.optim.Adam(model.parameters(), lr=lr, weight_decay=l2_coef)",
"best: best = loss best_t = epoch cnt_wait = 0",
"= loss best_t = epoch cnt_wait = 0 else: cnt_wait",
"from embed_methods.dgi.models import DGI, LogReg from embed_methods.dgi.utils import process def",
"weight_decay=l2_coef) if torch.cuda.is_available(): print('Using CUDA') model.cuda() features = features.cuda() if",
"sp_adj = sp_adj.cuda() else: adj = adj.cuda() b_xent = nn.BCEWithLogitsLoss()",
"= torch.FloatTensor(adj[np.newaxis]) model = DGI(ft_size, hid_units, nonlinearity) optimiser = torch.optim.Adam(model.parameters(),",
"torch.ones(batch_size, nb_nodes) lbl_2 = torch.zeros(batch_size, nb_nodes) lbl = torch.cat((lbl_1, lbl_2),",
"if loss < best: best = loss best_t = epoch",
"sp_adj = process.sparse_mx_to_torch_sparse_tensor(adj) else: adj = (adj + sp.eye(adj.shape[0])).todense() features",
"lbl.cuda() logits = model(features, shuf_fts, sp_adj if sparse else adj,",
"sparse else adj, sparse, None, None, None) loss = b_xent(logits,",
"xent = nn.CrossEntropyLoss() cnt_wait = 0 best = 1e9 best_t",
"lr = 0.001 l2_coef = 0.0 drop_prob = 0.0 hid_units",
"1) if torch.cuda.is_available(): shuf_fts = shuf_fts.cuda() lbl = lbl.cuda() logits",
"special name to separate parameters adj = nx.to_scipy_sparse_matrix(G, weight='wgt') features",
"not sparse: adj = torch.FloatTensor(adj[np.newaxis]) model = DGI(ft_size, hid_units, nonlinearity)",
"= model(features, shuf_fts, sp_adj if sparse else adj, sparse, None,",
"sp_adj if sparse else adj, sparse, None, None, None) loss",
"= torch.cat((lbl_1, lbl_2), 1) if torch.cuda.is_available(): shuf_fts = shuf_fts.cuda() lbl",
"from embed_methods.dgi.utils import process def dgi(G, features): batch_size = 1",
"stopping!') break loss.backward() optimiser.step() return (((model.embed(features, sp_adj if sparse else",
"sp.eye(adj.shape[0])).todense() features = torch.FloatTensor(features[np.newaxis]) if not sparse: adj = torch.FloatTensor(adj[np.newaxis])",
"time from embed_methods.dgi.models import DGI, LogReg from embed_methods.dgi.utils import process",
"shuf_fts.cuda() lbl = lbl.cuda() logits = model(features, shuf_fts, sp_adj if",
"lbl = torch.cat((lbl_1, lbl_2), 1) if torch.cuda.is_available(): shuf_fts = shuf_fts.cuda()",
"parameters adj = nx.to_scipy_sparse_matrix(G, weight='wgt') features = sp.lil_matrix(np.matrix(features)) features, _",
"= (adj + sp.eye(adj.shape[0])).todense() features = torch.FloatTensor(features[np.newaxis]) if not sparse:",
"print('Using CUDA') model.cuda() features = features.cuda() if sparse: sp_adj =",
"None) loss = b_xent(logits, lbl) print('Loss:', loss) if loss <",
"loss best_t = epoch cnt_wait = 0 else: cnt_wait +=",
"features[:, idx, :] lbl_1 = torch.ones(batch_size, nb_nodes) lbl_2 = torch.zeros(batch_size,",
"b_xent = nn.BCEWithLogitsLoss() xent = nn.CrossEntropyLoss() cnt_wait = 0 best",
"if torch.cuda.is_available(): print('Using CUDA') model.cuda() features = features.cuda() if sparse:",
"'prelu' # special name to separate parameters adj = nx.to_scipy_sparse_matrix(G,",
"as nx import time from embed_methods.dgi.models import DGI, LogReg from",
"= 0.001 l2_coef = 0.0 drop_prob = 0.0 hid_units =",
"b_xent(logits, lbl) print('Loss:', loss) if loss < best: best =",
"drop_prob = 0.0 hid_units = 512 sparse = True nonlinearity",
"features, _ = process.preprocess_features(features) nb_nodes = features.shape[0] ft_size = features.shape[1]",
"(adj + sp.eye(adj.shape[0])).todense() features = torch.FloatTensor(features[np.newaxis]) if not sparse: adj",
"adj = adj.cuda() b_xent = nn.BCEWithLogitsLoss() xent = nn.CrossEntropyLoss() cnt_wait",
"0 best = 1e9 best_t = 0 for epoch in",
"as np import scipy.sparse as sp import torch import torch.nn",
"shuf_fts = shuf_fts.cuda() lbl = lbl.cuda() logits = model(features, shuf_fts,",
"in range(nb_epochs): model.train() optimiser.zero_grad() idx = np.random.permutation(nb_nodes) shuf_fts = features[:,",
"torch import torch.nn as nn import networkx as nx import",
"sp.eye(adj.shape[0])) if sparse: sp_adj = process.sparse_mx_to_torch_sparse_tensor(adj) else: adj = (adj",
"optimiser.step() return (((model.embed(features, sp_adj if sparse else adj, sparse, None)[0]).squeeze()).data).cpu().numpy()",
"nx import time from embed_methods.dgi.models import DGI, LogReg from embed_methods.dgi.utils",
"= process.sparse_mx_to_torch_sparse_tensor(adj) else: adj = (adj + sp.eye(adj.shape[0])).todense() features =",
"sparse = True nonlinearity = 'prelu' # special name to",
"for epoch in range(nb_epochs): model.train() optimiser.zero_grad() idx = np.random.permutation(nb_nodes) shuf_fts",
"np.random.permutation(nb_nodes) shuf_fts = features[:, idx, :] lbl_1 = torch.ones(batch_size, nb_nodes)",
"10000 patience = 20 lr = 0.001 l2_coef = 0.0",
"= 0 else: cnt_wait += 1 if cnt_wait == patience:",
"l2_coef = 0.0 drop_prob = 0.0 hid_units = 512 sparse",
"cnt_wait += 1 if cnt_wait == patience: print(\"epochs: \", epoch)",
"= nn.CrossEntropyLoss() cnt_wait = 0 best = 1e9 best_t =",
"batch_size = 1 nb_epochs = 10000 patience = 20 lr",
"<filename>graphzoom/embed_methods/dgi/execute.py import numpy as np import scipy.sparse as sp import",
"print(\"epochs: \", epoch) print('Early stopping!') break loss.backward() optimiser.step() return (((model.embed(features,",
"sparse: sp_adj = process.sparse_mx_to_torch_sparse_tensor(adj) else: adj = (adj + sp.eye(adj.shape[0])).todense()",
"epoch in range(nb_epochs): model.train() optimiser.zero_grad() idx = np.random.permutation(nb_nodes) shuf_fts =",
"np import scipy.sparse as sp import torch import torch.nn as",
"weight='wgt') features = sp.lil_matrix(np.matrix(features)) features, _ = process.preprocess_features(features) nb_nodes =",
"\", epoch) print('Early stopping!') break loss.backward() optimiser.step() return (((model.embed(features, sp_adj",
"sp_adj.cuda() else: adj = adj.cuda() b_xent = nn.BCEWithLogitsLoss() xent =",
"features.shape[1] adj = process.normalize_adj(adj + sp.eye(adj.shape[0])) if sparse: sp_adj =",
"= features.shape[0] ft_size = features.shape[1] adj = process.normalize_adj(adj + sp.eye(adj.shape[0]))",
"model.train() optimiser.zero_grad() idx = np.random.permutation(nb_nodes) shuf_fts = features[:, idx, :]",
"= sp.lil_matrix(np.matrix(features)) features, _ = process.preprocess_features(features) nb_nodes = features.shape[0] ft_size",
"shuf_fts = features[:, idx, :] lbl_1 = torch.ones(batch_size, nb_nodes) lbl_2",
"cnt_wait == patience: print(\"epochs: \", epoch) print('Early stopping!') break loss.backward()",
"= 0 for epoch in range(nb_epochs): model.train() optimiser.zero_grad() idx =",
"nx.to_scipy_sparse_matrix(G, weight='wgt') features = sp.lil_matrix(np.matrix(features)) features, _ = process.preprocess_features(features) nb_nodes",
"process def dgi(G, features): batch_size = 1 nb_epochs = 10000",
"nb_nodes) lbl_2 = torch.zeros(batch_size, nb_nodes) lbl = torch.cat((lbl_1, lbl_2), 1)",
"None, None, None) loss = b_xent(logits, lbl) print('Loss:', loss) if",
"break loss.backward() optimiser.step() return (((model.embed(features, sp_adj if sparse else adj,",
"import scipy.sparse as sp import torch import torch.nn as nn",
"patience: print(\"epochs: \", epoch) print('Early stopping!') break loss.backward() optimiser.step() return",
"= 10000 patience = 20 lr = 0.001 l2_coef =",
"import time from embed_methods.dgi.models import DGI, LogReg from embed_methods.dgi.utils import",
"= process.preprocess_features(features) nb_nodes = features.shape[0] ft_size = features.shape[1] adj =",
"nb_epochs = 10000 patience = 20 lr = 0.001 l2_coef",
"lr=lr, weight_decay=l2_coef) if torch.cuda.is_available(): print('Using CUDA') model.cuda() features = features.cuda()",
"embed_methods.dgi.models import DGI, LogReg from embed_methods.dgi.utils import process def dgi(G,",
"sparse: adj = torch.FloatTensor(adj[np.newaxis]) model = DGI(ft_size, hid_units, nonlinearity) optimiser",
"= features.cuda() if sparse: sp_adj = sp_adj.cuda() else: adj =",
"if torch.cuda.is_available(): shuf_fts = shuf_fts.cuda() lbl = lbl.cuda() logits =",
"1 if cnt_wait == patience: print(\"epochs: \", epoch) print('Early stopping!')",
"adj = torch.FloatTensor(adj[np.newaxis]) model = DGI(ft_size, hid_units, nonlinearity) optimiser =",
"loss) if loss < best: best = loss best_t =",
"features): batch_size = 1 nb_epochs = 10000 patience = 20",
"shuf_fts, sp_adj if sparse else adj, sparse, None, None, None)",
"DGI(ft_size, hid_units, nonlinearity) optimiser = torch.optim.Adam(model.parameters(), lr=lr, weight_decay=l2_coef) if torch.cuda.is_available():",
"best_t = epoch cnt_wait = 0 else: cnt_wait += 1",
"512 sparse = True nonlinearity = 'prelu' # special name",
"0.0 hid_units = 512 sparse = True nonlinearity = 'prelu'",
"== patience: print(\"epochs: \", epoch) print('Early stopping!') break loss.backward() optimiser.step()",
"torch.cuda.is_available(): print('Using CUDA') model.cuda() features = features.cuda() if sparse: sp_adj",
"features.shape[0] ft_size = features.shape[1] adj = process.normalize_adj(adj + sp.eye(adj.shape[0])) if",
"loss = b_xent(logits, lbl) print('Loss:', loss) if loss < best:",
"= nn.BCEWithLogitsLoss() xent = nn.CrossEntropyLoss() cnt_wait = 0 best =",
"cnt_wait = 0 best = 1e9 best_t = 0 for",
"import process def dgi(G, features): batch_size = 1 nb_epochs =",
"= 1e9 best_t = 0 for epoch in range(nb_epochs): model.train()",
"features = torch.FloatTensor(features[np.newaxis]) if not sparse: adj = torch.FloatTensor(adj[np.newaxis]) model",
"= epoch cnt_wait = 0 else: cnt_wait += 1 if",
"sp import torch import torch.nn as nn import networkx as",
"1e9 best_t = 0 for epoch in range(nb_epochs): model.train() optimiser.zero_grad()",
"nn.CrossEntropyLoss() cnt_wait = 0 best = 1e9 best_t = 0",
"hid_units = 512 sparse = True nonlinearity = 'prelu' #",
"features.cuda() if sparse: sp_adj = sp_adj.cuda() else: adj = adj.cuda()",
"0.0 drop_prob = 0.0 hid_units = 512 sparse = True",
"best = loss best_t = epoch cnt_wait = 0 else:",
"else: cnt_wait += 1 if cnt_wait == patience: print(\"epochs: \","
] |
[
"root of the repository os.chdir(os.path.abspath(os.path.join(THIS_FILE_DIRECTORY, \"..\", \"..\"))) deploy_binaries(args.version) if __name__",
"os.path.dirname(os.path.realpath(__file__)) GH_REPO_IDENT = \"ETCLabs/RDMnet\" GH_USERNAME = \"svc-etclabs\" GH_API_TOKEN = os.getenv(\"SVC_ETCLABS_REPO_TOKEN\")",
"the root of the repository os.chdir(os.path.abspath(os.path.join(THIS_FILE_DIRECTORY, \"..\", \"..\"))) deploy_binaries(args.version) if",
"v{version}\", message=f\"Automated release of RDMnet for v{version}\", ) new_release.upload_asset(\"RDMnetSetup_x86.msi\") new_release.upload_asset(\"RDMnetSetup_x64.msi\")",
"repo.create_git_release( tag=f\"v{version}\", name=f\"RDMnet v{version}\", message=f\"Automated release of RDMnet for v{version}\",",
"a GitHub release given the specified tag name.\"\"\" import argparse",
"repo.get_tags(): if tag.name == f\"v{version}\": keep_trying = False # Tag",
"break if keep_trying: time.sleep(5) print(f\"Tag v{version} available. Creating release...\") new_release",
"v{version}\", ) new_release.upload_asset(\"RDMnetSetup_x86.msi\") new_release.upload_asset(\"RDMnetSetup_x64.msi\") new_release.upload_asset(\"RDMnet.pkg\") def main(): parser = argparse.ArgumentParser(",
"deploy_binaries(version: str): \"\"\"Deploys staged binaries to a new GitHub Release.\"\"\"",
"Release\" ) parser.add_argument(\"version\", help=\"Artifact version being deployed\") args = parser.parse_args()",
") parser.add_argument(\"version\", help=\"Artifact version being deployed\") args = parser.parse_args() #",
"= parser.parse_args() # Make sure our cwd is the root",
"os import time from github import Github THIS_FILE_DIRECTORY = os.path.dirname(os.path.realpath(__file__))",
"GH_API_TOKEN = os.getenv(\"SVC_ETCLABS_REPO_TOKEN\") def deploy_binaries(version: str): \"\"\"Deploys staged binaries to",
"help=\"Artifact version being deployed\") args = parser.parse_args() # Make sure",
"str): \"\"\"Deploys staged binaries to a new GitHub Release.\"\"\" g",
"repo = g.get_repo(GH_REPO_IDENT) print(f\"Waiting for the correct GitHub tag v{version}",
"g.get_repo(GH_REPO_IDENT) print(f\"Waiting for the correct GitHub tag v{version} to become",
"become available...\") keep_trying = True while keep_trying: for tag in",
"\"\"\"Deploys binaries to a GitHub release given the specified tag",
"print(f\"Tag v{version} available. Creating release...\") new_release = repo.create_git_release( tag=f\"v{version}\", name=f\"RDMnet",
"parser.add_argument(\"version\", help=\"Artifact version being deployed\") args = parser.parse_args() # Make",
"given the specified tag name.\"\"\" import argparse import os import",
"RDMnet for v{version}\", ) new_release.upload_asset(\"RDMnetSetup_x86.msi\") new_release.upload_asset(\"RDMnetSetup_x64.msi\") new_release.upload_asset(\"RDMnet.pkg\") def main(): parser",
"artifacts to GitHub Release\" ) parser.add_argument(\"version\", help=\"Artifact version being deployed\")",
"\"\"\"Deploys staged binaries to a new GitHub Release.\"\"\" g =",
"RDMnet artifacts to GitHub Release\" ) parser.add_argument(\"version\", help=\"Artifact version being",
"to become available...\") keep_trying = True while keep_trying: for tag",
"version being deployed\") args = parser.parse_args() # Make sure our",
"Tag now exists break if keep_trying: time.sleep(5) print(f\"Tag v{version} available.",
"to a GitHub release given the specified tag name.\"\"\" import",
"if tag.name == f\"v{version}\": keep_trying = False # Tag now",
"parser.parse_args() # Make sure our cwd is the root of",
"tag=f\"v{version}\", name=f\"RDMnet v{version}\", message=f\"Automated release of RDMnet for v{version}\", )",
"sure our cwd is the root of the repository os.chdir(os.path.abspath(os.path.join(THIS_FILE_DIRECTORY,",
"tag name.\"\"\" import argparse import os import time from github",
"import os import time from github import Github THIS_FILE_DIRECTORY =",
"time from github import Github THIS_FILE_DIRECTORY = os.path.dirname(os.path.realpath(__file__)) GH_REPO_IDENT =",
"== f\"v{version}\": keep_trying = False # Tag now exists break",
"GitHub tag v{version} to become available...\") keep_trying = True while",
"our cwd is the root of the repository os.chdir(os.path.abspath(os.path.join(THIS_FILE_DIRECTORY, \"..\",",
"= \"ETCLabs/RDMnet\" GH_USERNAME = \"svc-etclabs\" GH_API_TOKEN = os.getenv(\"SVC_ETCLABS_REPO_TOKEN\") def deploy_binaries(version:",
"keep_trying = False # Tag now exists break if keep_trying:",
"tag v{version} to become available...\") keep_trying = True while keep_trying:",
"os.getenv(\"SVC_ETCLABS_REPO_TOKEN\") def deploy_binaries(version: str): \"\"\"Deploys staged binaries to a new",
"if keep_trying: time.sleep(5) print(f\"Tag v{version} available. Creating release...\") new_release =",
"= os.getenv(\"SVC_ETCLABS_REPO_TOKEN\") def deploy_binaries(version: str): \"\"\"Deploys staged binaries to a",
"Creating release...\") new_release = repo.create_git_release( tag=f\"v{version}\", name=f\"RDMnet v{version}\", message=f\"Automated release",
"argparse.ArgumentParser( description=\"Deploy RDMnet artifacts to GitHub Release\" ) parser.add_argument(\"version\", help=\"Artifact",
"cwd is the root of the repository os.chdir(os.path.abspath(os.path.join(THIS_FILE_DIRECTORY, \"..\", \"..\")))",
"= repo.create_git_release( tag=f\"v{version}\", name=f\"RDMnet v{version}\", message=f\"Automated release of RDMnet for",
"THIS_FILE_DIRECTORY = os.path.dirname(os.path.realpath(__file__)) GH_REPO_IDENT = \"ETCLabs/RDMnet\" GH_USERNAME = \"svc-etclabs\" GH_API_TOKEN",
"False # Tag now exists break if keep_trying: time.sleep(5) print(f\"Tag",
"deployed\") args = parser.parse_args() # Make sure our cwd is",
"exists break if keep_trying: time.sleep(5) print(f\"Tag v{version} available. Creating release...\")",
"a new GitHub Release.\"\"\" g = Github(login_or_token=GH_USERNAME, password=GH_API_TOKEN) repo =",
"args = parser.parse_args() # Make sure our cwd is the",
"import argparse import os import time from github import Github",
"name=f\"RDMnet v{version}\", message=f\"Automated release of RDMnet for v{version}\", ) new_release.upload_asset(\"RDMnetSetup_x86.msi\")",
"def deploy_binaries(version: str): \"\"\"Deploys staged binaries to a new GitHub",
"True while keep_trying: for tag in repo.get_tags(): if tag.name ==",
"release of RDMnet for v{version}\", ) new_release.upload_asset(\"RDMnetSetup_x86.msi\") new_release.upload_asset(\"RDMnetSetup_x64.msi\") new_release.upload_asset(\"RDMnet.pkg\") def",
"the repository os.chdir(os.path.abspath(os.path.join(THIS_FILE_DIRECTORY, \"..\", \"..\"))) deploy_binaries(args.version) if __name__ == \"__main__\":",
"GitHub release given the specified tag name.\"\"\" import argparse import",
"f\"v{version}\": keep_trying = False # Tag now exists break if",
"GH_REPO_IDENT = \"ETCLabs/RDMnet\" GH_USERNAME = \"svc-etclabs\" GH_API_TOKEN = os.getenv(\"SVC_ETCLABS_REPO_TOKEN\") def",
"= False # Tag now exists break if keep_trying: time.sleep(5)",
"# Make sure our cwd is the root of the",
"repository os.chdir(os.path.abspath(os.path.join(THIS_FILE_DIRECTORY, \"..\", \"..\"))) deploy_binaries(args.version) if __name__ == \"__main__\": main()",
"= g.get_repo(GH_REPO_IDENT) print(f\"Waiting for the correct GitHub tag v{version} to",
"import time from github import Github THIS_FILE_DIRECTORY = os.path.dirname(os.path.realpath(__file__)) GH_REPO_IDENT",
"= os.path.dirname(os.path.realpath(__file__)) GH_REPO_IDENT = \"ETCLabs/RDMnet\" GH_USERNAME = \"svc-etclabs\" GH_API_TOKEN =",
"\"svc-etclabs\" GH_API_TOKEN = os.getenv(\"SVC_ETCLABS_REPO_TOKEN\") def deploy_binaries(version: str): \"\"\"Deploys staged binaries",
"v{version} available. Creating release...\") new_release = repo.create_git_release( tag=f\"v{version}\", name=f\"RDMnet v{version}\",",
"GitHub Release\" ) parser.add_argument(\"version\", help=\"Artifact version being deployed\") args =",
"to GitHub Release\" ) parser.add_argument(\"version\", help=\"Artifact version being deployed\") args",
"g = Github(login_or_token=GH_USERNAME, password=GH_API_TOKEN) repo = g.get_repo(GH_REPO_IDENT) print(f\"Waiting for the",
"new_release.upload_asset(\"RDMnetSetup_x86.msi\") new_release.upload_asset(\"RDMnetSetup_x64.msi\") new_release.upload_asset(\"RDMnet.pkg\") def main(): parser = argparse.ArgumentParser( description=\"Deploy RDMnet",
"Release.\"\"\" g = Github(login_or_token=GH_USERNAME, password=GH_API_TOKEN) repo = g.get_repo(GH_REPO_IDENT) print(f\"Waiting for",
"available...\") keep_trying = True while keep_trying: for tag in repo.get_tags():",
"while keep_trying: for tag in repo.get_tags(): if tag.name == f\"v{version}\":",
"Github(login_or_token=GH_USERNAME, password=GH_API_TOKEN) repo = g.get_repo(GH_REPO_IDENT) print(f\"Waiting for the correct GitHub",
"def main(): parser = argparse.ArgumentParser( description=\"Deploy RDMnet artifacts to GitHub",
"description=\"Deploy RDMnet artifacts to GitHub Release\" ) parser.add_argument(\"version\", help=\"Artifact version",
"name.\"\"\" import argparse import os import time from github import",
"the specified tag name.\"\"\" import argparse import os import time",
"\"ETCLabs/RDMnet\" GH_USERNAME = \"svc-etclabs\" GH_API_TOKEN = os.getenv(\"SVC_ETCLABS_REPO_TOKEN\") def deploy_binaries(version: str):",
"tag in repo.get_tags(): if tag.name == f\"v{version}\": keep_trying = False",
"main(): parser = argparse.ArgumentParser( description=\"Deploy RDMnet artifacts to GitHub Release\"",
"new GitHub Release.\"\"\" g = Github(login_or_token=GH_USERNAME, password=GH_API_TOKEN) repo = g.get_repo(GH_REPO_IDENT)",
"github import Github THIS_FILE_DIRECTORY = os.path.dirname(os.path.realpath(__file__)) GH_REPO_IDENT = \"ETCLabs/RDMnet\" GH_USERNAME",
"time.sleep(5) print(f\"Tag v{version} available. Creating release...\") new_release = repo.create_git_release( tag=f\"v{version}\",",
"GitHub Release.\"\"\" g = Github(login_or_token=GH_USERNAME, password=GH_API_TOKEN) repo = g.get_repo(GH_REPO_IDENT) print(f\"Waiting",
"being deployed\") args = parser.parse_args() # Make sure our cwd",
"to a new GitHub Release.\"\"\" g = Github(login_or_token=GH_USERNAME, password=GH_API_TOKEN) repo",
"correct GitHub tag v{version} to become available...\") keep_trying = True",
"now exists break if keep_trying: time.sleep(5) print(f\"Tag v{version} available. Creating",
") new_release.upload_asset(\"RDMnetSetup_x86.msi\") new_release.upload_asset(\"RDMnetSetup_x64.msi\") new_release.upload_asset(\"RDMnet.pkg\") def main(): parser = argparse.ArgumentParser( description=\"Deploy",
"of RDMnet for v{version}\", ) new_release.upload_asset(\"RDMnetSetup_x86.msi\") new_release.upload_asset(\"RDMnetSetup_x64.msi\") new_release.upload_asset(\"RDMnet.pkg\") def main():",
"is the root of the repository os.chdir(os.path.abspath(os.path.join(THIS_FILE_DIRECTORY, \"..\", \"..\"))) deploy_binaries(args.version)",
"new_release.upload_asset(\"RDMnetSetup_x64.msi\") new_release.upload_asset(\"RDMnet.pkg\") def main(): parser = argparse.ArgumentParser( description=\"Deploy RDMnet artifacts",
"argparse import os import time from github import Github THIS_FILE_DIRECTORY",
"Github THIS_FILE_DIRECTORY = os.path.dirname(os.path.realpath(__file__)) GH_REPO_IDENT = \"ETCLabs/RDMnet\" GH_USERNAME = \"svc-etclabs\"",
"= \"svc-etclabs\" GH_API_TOKEN = os.getenv(\"SVC_ETCLABS_REPO_TOKEN\") def deploy_binaries(version: str): \"\"\"Deploys staged",
"= Github(login_or_token=GH_USERNAME, password=GH_API_TOKEN) repo = g.get_repo(GH_REPO_IDENT) print(f\"Waiting for the correct",
"new_release = repo.create_git_release( tag=f\"v{version}\", name=f\"RDMnet v{version}\", message=f\"Automated release of RDMnet",
"from github import Github THIS_FILE_DIRECTORY = os.path.dirname(os.path.realpath(__file__)) GH_REPO_IDENT = \"ETCLabs/RDMnet\"",
"staged binaries to a new GitHub Release.\"\"\" g = Github(login_or_token=GH_USERNAME,",
"import Github THIS_FILE_DIRECTORY = os.path.dirname(os.path.realpath(__file__)) GH_REPO_IDENT = \"ETCLabs/RDMnet\" GH_USERNAME =",
"GH_USERNAME = \"svc-etclabs\" GH_API_TOKEN = os.getenv(\"SVC_ETCLABS_REPO_TOKEN\") def deploy_binaries(version: str): \"\"\"Deploys",
"# Tag now exists break if keep_trying: time.sleep(5) print(f\"Tag v{version}",
"keep_trying: for tag in repo.get_tags(): if tag.name == f\"v{version}\": keep_trying",
"tag.name == f\"v{version}\": keep_trying = False # Tag now exists",
"keep_trying = True while keep_trying: for tag in repo.get_tags(): if",
"available. Creating release...\") new_release = repo.create_git_release( tag=f\"v{version}\", name=f\"RDMnet v{version}\", message=f\"Automated",
"print(f\"Waiting for the correct GitHub tag v{version} to become available...\")",
"for the correct GitHub tag v{version} to become available...\") keep_trying",
"binaries to a GitHub release given the specified tag name.\"\"\"",
"keep_trying: time.sleep(5) print(f\"Tag v{version} available. Creating release...\") new_release = repo.create_git_release(",
"binaries to a new GitHub Release.\"\"\" g = Github(login_or_token=GH_USERNAME, password=GH_API_TOKEN)",
"for v{version}\", ) new_release.upload_asset(\"RDMnetSetup_x86.msi\") new_release.upload_asset(\"RDMnetSetup_x64.msi\") new_release.upload_asset(\"RDMnet.pkg\") def main(): parser =",
"release given the specified tag name.\"\"\" import argparse import os",
"<gh_stars>10-100 \"\"\"Deploys binaries to a GitHub release given the specified",
"Make sure our cwd is the root of the repository",
"in repo.get_tags(): if tag.name == f\"v{version}\": keep_trying = False #",
"specified tag name.\"\"\" import argparse import os import time from",
"password=GH_API_TOKEN) repo = g.get_repo(GH_REPO_IDENT) print(f\"Waiting for the correct GitHub tag",
"= True while keep_trying: for tag in repo.get_tags(): if tag.name",
"message=f\"Automated release of RDMnet for v{version}\", ) new_release.upload_asset(\"RDMnetSetup_x86.msi\") new_release.upload_asset(\"RDMnetSetup_x64.msi\") new_release.upload_asset(\"RDMnet.pkg\")",
"new_release.upload_asset(\"RDMnet.pkg\") def main(): parser = argparse.ArgumentParser( description=\"Deploy RDMnet artifacts to",
"of the repository os.chdir(os.path.abspath(os.path.join(THIS_FILE_DIRECTORY, \"..\", \"..\"))) deploy_binaries(args.version) if __name__ ==",
"v{version} to become available...\") keep_trying = True while keep_trying: for",
"parser = argparse.ArgumentParser( description=\"Deploy RDMnet artifacts to GitHub Release\" )",
"for tag in repo.get_tags(): if tag.name == f\"v{version}\": keep_trying =",
"the correct GitHub tag v{version} to become available...\") keep_trying =",
"= argparse.ArgumentParser( description=\"Deploy RDMnet artifacts to GitHub Release\" ) parser.add_argument(\"version\",",
"release...\") new_release = repo.create_git_release( tag=f\"v{version}\", name=f\"RDMnet v{version}\", message=f\"Automated release of"
] |
[
"losses. Default is 1000.0. \"\"\" if spectrum_in is None: return",
"assert isinstance(precursor_mz, (float, int)), (\"Expected 'precursor_mz' to be a scalar",
"is 0.0. loss_mz_to: Maximum allowed m/z value for losses. Default",
"add_losses(spectrum_in: SpectrumType, loss_mz_from=0.0, loss_mz_to=1000.0) -> SpectrumType: \"\"\"Derive losses based on",
"mass. Parameters ---------- spectrum_in: Input spectrum. loss_mz_from: Minimum allowed m/z",
"import logging import numpy from ..Fragments import Fragments from ..typing",
"a scalar number.\", \"Consider applying 'add_precursor_mz' filter first.\") peaks_mz, peaks_intensities",
"value for losses. Default is 1000.0. \"\"\" if spectrum_in is",
"loss_mz_to=1000.0) -> SpectrumType: \"\"\"Derive losses based on precursor mass. Parameters",
"value for losses. Default is 0.0. loss_mz_to: Maximum allowed m/z",
"within given boundaries mask = numpy.where((losses_mz >= loss_mz_from) & (losses_mz",
"be a scalar number.\", \"Consider applying 'add_precursor_mz' filter first.\") peaks_mz,",
"is None: return None spectrum = spectrum_in.clone() precursor_mz = spectrum.get(\"precursor_mz\",",
"from ..typing import SpectrumType logger = logging.getLogger(\"matchms\") def add_losses(spectrum_in: SpectrumType,",
"loss_mz_to: Maximum allowed m/z value for losses. Default is 1000.0.",
"Maximum allowed m/z value for losses. Default is 1000.0. \"\"\"",
"for losses. Default is 1000.0. \"\"\" if spectrum_in is None:",
"spectrum.peaks.mz, spectrum.peaks.intensities losses_mz = (precursor_mz - peaks_mz)[::-1] losses_intensities = peaks_intensities[::-1]",
"which are within given boundaries mask = numpy.where((losses_mz >= loss_mz_from)",
"= numpy.where((losses_mz >= loss_mz_from) & (losses_mz <= loss_mz_to)) spectrum.losses =",
"SpectrumType, loss_mz_from=0.0, loss_mz_to=1000.0) -> SpectrumType: \"\"\"Derive losses based on precursor",
"(losses_mz <= loss_mz_to)) spectrum.losses = Fragments(mz=losses_mz[mask], intensities=losses_intensities[mask]) else: logger.warning(\"No precursor_mz",
"allowed m/z value for losses. Default is 0.0. loss_mz_to: Maximum",
"logger = logging.getLogger(\"matchms\") def add_losses(spectrum_in: SpectrumType, loss_mz_from=0.0, loss_mz_to=1000.0) -> SpectrumType:",
"based on precursor mass. Parameters ---------- spectrum_in: Input spectrum. loss_mz_from:",
"= (precursor_mz - peaks_mz)[::-1] losses_intensities = peaks_intensities[::-1] # Add losses",
"loss_mz_from: Minimum allowed m/z value for losses. Default is 0.0.",
"number.\", \"Consider applying 'add_precursor_mz' filter first.\") peaks_mz, peaks_intensities = spectrum.peaks.mz,",
"(precursor_mz - peaks_mz)[::-1] losses_intensities = peaks_intensities[::-1] # Add losses which",
"spectrum.losses = Fragments(mz=losses_mz[mask], intensities=losses_intensities[mask]) else: logger.warning(\"No precursor_mz found. Consider applying",
"is 1000.0. \"\"\" if spectrum_in is None: return None spectrum",
"<= loss_mz_to)) spectrum.losses = Fragments(mz=losses_mz[mask], intensities=losses_intensities[mask]) else: logger.warning(\"No precursor_mz found.",
"on precursor mass. Parameters ---------- spectrum_in: Input spectrum. loss_mz_from: Minimum",
"peaks_intensities[::-1] # Add losses which are within given boundaries mask",
"'precursor_mz' to be a scalar number.\", \"Consider applying 'add_precursor_mz' filter",
"losses based on precursor mass. Parameters ---------- spectrum_in: Input spectrum.",
"Fragments from ..typing import SpectrumType logger = logging.getLogger(\"matchms\") def add_losses(spectrum_in:",
"-> SpectrumType: \"\"\"Derive losses based on precursor mass. Parameters ----------",
"else: logger.warning(\"No precursor_mz found. Consider applying 'add_precursor_mz' filter first.\") return",
"to be a scalar number.\", \"Consider applying 'add_precursor_mz' filter first.\")",
"import numpy from ..Fragments import Fragments from ..typing import SpectrumType",
"Add losses which are within given boundaries mask = numpy.where((losses_mz",
"precursor_mz: assert isinstance(precursor_mz, (float, int)), (\"Expected 'precursor_mz' to be a",
"Minimum allowed m/z value for losses. Default is 0.0. loss_mz_to:",
"peaks_mz)[::-1] losses_intensities = peaks_intensities[::-1] # Add losses which are within",
"numpy.where((losses_mz >= loss_mz_from) & (losses_mz <= loss_mz_to)) spectrum.losses = Fragments(mz=losses_mz[mask],",
"\"\"\"Derive losses based on precursor mass. Parameters ---------- spectrum_in: Input",
"spectrum_in is None: return None spectrum = spectrum_in.clone() precursor_mz =",
"= peaks_intensities[::-1] # Add losses which are within given boundaries",
"losses_intensities = peaks_intensities[::-1] # Add losses which are within given",
"boundaries mask = numpy.where((losses_mz >= loss_mz_from) & (losses_mz <= loss_mz_to))",
"logging import numpy from ..Fragments import Fragments from ..typing import",
"= Fragments(mz=losses_mz[mask], intensities=losses_intensities[mask]) else: logger.warning(\"No precursor_mz found. Consider applying 'add_precursor_mz'",
"SpectrumType: \"\"\"Derive losses based on precursor mass. Parameters ---------- spectrum_in:",
"spectrum_in.clone() precursor_mz = spectrum.get(\"precursor_mz\", None) if precursor_mz: assert isinstance(precursor_mz, (float,",
"..typing import SpectrumType logger = logging.getLogger(\"matchms\") def add_losses(spectrum_in: SpectrumType, loss_mz_from=0.0,",
"logger.warning(\"No precursor_mz found. Consider applying 'add_precursor_mz' filter first.\") return spectrum",
"first.\") peaks_mz, peaks_intensities = spectrum.peaks.mz, spectrum.peaks.intensities losses_mz = (precursor_mz -",
"scalar number.\", \"Consider applying 'add_precursor_mz' filter first.\") peaks_mz, peaks_intensities =",
"losses. Default is 0.0. loss_mz_to: Maximum allowed m/z value for",
"peaks_mz, peaks_intensities = spectrum.peaks.mz, spectrum.peaks.intensities losses_mz = (precursor_mz - peaks_mz)[::-1]",
"loss_mz_from=0.0, loss_mz_to=1000.0) -> SpectrumType: \"\"\"Derive losses based on precursor mass.",
"SpectrumType logger = logging.getLogger(\"matchms\") def add_losses(spectrum_in: SpectrumType, loss_mz_from=0.0, loss_mz_to=1000.0) ->",
"(float, int)), (\"Expected 'precursor_mz' to be a scalar number.\", \"Consider",
"Fragments(mz=losses_mz[mask], intensities=losses_intensities[mask]) else: logger.warning(\"No precursor_mz found. Consider applying 'add_precursor_mz' filter",
"import SpectrumType logger = logging.getLogger(\"matchms\") def add_losses(spectrum_in: SpectrumType, loss_mz_from=0.0, loss_mz_to=1000.0)",
"spectrum_in: Input spectrum. loss_mz_from: Minimum allowed m/z value for losses.",
"numpy from ..Fragments import Fragments from ..typing import SpectrumType logger",
"from ..Fragments import Fragments from ..typing import SpectrumType logger =",
">= loss_mz_from) & (losses_mz <= loss_mz_to)) spectrum.losses = Fragments(mz=losses_mz[mask], intensities=losses_intensities[mask])",
"if precursor_mz: assert isinstance(precursor_mz, (float, int)), (\"Expected 'precursor_mz' to be",
"None spectrum = spectrum_in.clone() precursor_mz = spectrum.get(\"precursor_mz\", None) if precursor_mz:",
"(\"Expected 'precursor_mz' to be a scalar number.\", \"Consider applying 'add_precursor_mz'",
"spectrum.peaks.intensities losses_mz = (precursor_mz - peaks_mz)[::-1] losses_intensities = peaks_intensities[::-1] #",
"Input spectrum. loss_mz_from: Minimum allowed m/z value for losses. Default",
"losses_mz = (precursor_mz - peaks_mz)[::-1] losses_intensities = peaks_intensities[::-1] # Add",
"..Fragments import Fragments from ..typing import SpectrumType logger = logging.getLogger(\"matchms\")",
"Parameters ---------- spectrum_in: Input spectrum. loss_mz_from: Minimum allowed m/z value",
"given boundaries mask = numpy.where((losses_mz >= loss_mz_from) & (losses_mz <=",
"mask = numpy.where((losses_mz >= loss_mz_from) & (losses_mz <= loss_mz_to)) spectrum.losses",
"m/z value for losses. Default is 1000.0. \"\"\" if spectrum_in",
"1000.0. \"\"\" if spectrum_in is None: return None spectrum =",
"loss_mz_to)) spectrum.losses = Fragments(mz=losses_mz[mask], intensities=losses_intensities[mask]) else: logger.warning(\"No precursor_mz found. Consider",
"spectrum. loss_mz_from: Minimum allowed m/z value for losses. Default is",
"Default is 0.0. loss_mz_to: Maximum allowed m/z value for losses.",
"precursor mass. Parameters ---------- spectrum_in: Input spectrum. loss_mz_from: Minimum allowed",
"None: return None spectrum = spectrum_in.clone() precursor_mz = spectrum.get(\"precursor_mz\", None)",
"Default is 1000.0. \"\"\" if spectrum_in is None: return None",
"spectrum.get(\"precursor_mz\", None) if precursor_mz: assert isinstance(precursor_mz, (float, int)), (\"Expected 'precursor_mz'",
"loss_mz_from) & (losses_mz <= loss_mz_to)) spectrum.losses = Fragments(mz=losses_mz[mask], intensities=losses_intensities[mask]) else:",
"for losses. Default is 0.0. loss_mz_to: Maximum allowed m/z value",
"# Add losses which are within given boundaries mask =",
"= spectrum.get(\"precursor_mz\", None) if precursor_mz: assert isinstance(precursor_mz, (float, int)), (\"Expected",
"0.0. loss_mz_to: Maximum allowed m/z value for losses. Default is",
"def add_losses(spectrum_in: SpectrumType, loss_mz_from=0.0, loss_mz_to=1000.0) -> SpectrumType: \"\"\"Derive losses based",
"logging.getLogger(\"matchms\") def add_losses(spectrum_in: SpectrumType, loss_mz_from=0.0, loss_mz_to=1000.0) -> SpectrumType: \"\"\"Derive losses",
"\"Consider applying 'add_precursor_mz' filter first.\") peaks_mz, peaks_intensities = spectrum.peaks.mz, spectrum.peaks.intensities",
"---------- spectrum_in: Input spectrum. loss_mz_from: Minimum allowed m/z value for",
"spectrum = spectrum_in.clone() precursor_mz = spectrum.get(\"precursor_mz\", None) if precursor_mz: assert",
"m/z value for losses. Default is 0.0. loss_mz_to: Maximum allowed",
"import Fragments from ..typing import SpectrumType logger = logging.getLogger(\"matchms\") def",
"applying 'add_precursor_mz' filter first.\") peaks_mz, peaks_intensities = spectrum.peaks.mz, spectrum.peaks.intensities losses_mz",
"intensities=losses_intensities[mask]) else: logger.warning(\"No precursor_mz found. Consider applying 'add_precursor_mz' filter first.\")",
"= spectrum_in.clone() precursor_mz = spectrum.get(\"precursor_mz\", None) if precursor_mz: assert isinstance(precursor_mz,",
"return None spectrum = spectrum_in.clone() precursor_mz = spectrum.get(\"precursor_mz\", None) if",
"int)), (\"Expected 'precursor_mz' to be a scalar number.\", \"Consider applying",
"= spectrum.peaks.mz, spectrum.peaks.intensities losses_mz = (precursor_mz - peaks_mz)[::-1] losses_intensities =",
"allowed m/z value for losses. Default is 1000.0. \"\"\" if",
"- peaks_mz)[::-1] losses_intensities = peaks_intensities[::-1] # Add losses which are",
"losses which are within given boundaries mask = numpy.where((losses_mz >=",
"\"\"\" if spectrum_in is None: return None spectrum = spectrum_in.clone()",
"isinstance(precursor_mz, (float, int)), (\"Expected 'precursor_mz' to be a scalar number.\",",
"filter first.\") peaks_mz, peaks_intensities = spectrum.peaks.mz, spectrum.peaks.intensities losses_mz = (precursor_mz",
"None) if precursor_mz: assert isinstance(precursor_mz, (float, int)), (\"Expected 'precursor_mz' to",
"& (losses_mz <= loss_mz_to)) spectrum.losses = Fragments(mz=losses_mz[mask], intensities=losses_intensities[mask]) else: logger.warning(\"No",
"if spectrum_in is None: return None spectrum = spectrum_in.clone() precursor_mz",
"are within given boundaries mask = numpy.where((losses_mz >= loss_mz_from) &",
"precursor_mz = spectrum.get(\"precursor_mz\", None) if precursor_mz: assert isinstance(precursor_mz, (float, int)),",
"peaks_intensities = spectrum.peaks.mz, spectrum.peaks.intensities losses_mz = (precursor_mz - peaks_mz)[::-1] losses_intensities",
"'add_precursor_mz' filter first.\") peaks_mz, peaks_intensities = spectrum.peaks.mz, spectrum.peaks.intensities losses_mz =",
"= logging.getLogger(\"matchms\") def add_losses(spectrum_in: SpectrumType, loss_mz_from=0.0, loss_mz_to=1000.0) -> SpectrumType: \"\"\"Derive"
] |
[
"definitions are parsed first and corresponding schema are created so",
"and return the corresponding dict. :param item: An item from",
"this item \"\"\" d = dict( name=item[0], type=self._get_type(item[1][\"type\"]), required=(item[0] in",
") schema_dict[DATASCHEMA].append(schema) return schema def _get_element_dict(self, schema_dict, item, required_list=None): \"\"\"",
"format: {\"$ref\": \"#/definitions/object_name\"} :return The schema name (_get_schema_name(object_name)) \"\"\" content",
"= { schema_name: [ self._get_element_dict( schema_dict=schema_dict, item=i, required_list=self._get_required(content), ) for",
"if \"type\" not in content: if \"$ref\" in content: return",
"type=self._get_type(item[1][\"type\"]), required=(item[0] in required_list), allow_none=(\"null\" in item[1][\"type\"]), many=False, ) return",
"it. This is used for items that will directly translate",
"@staticmethod def get_empty_schema(): \"\"\" Create un empty schema dict \"\"\"",
"item: An item from the jsonschema (key, value) :param required_list:",
"element name into a schema name in order to create",
"in tuplist: schema = ParameterSchema() # this line validates the",
"item=i, required_list=self._get_required(content), ) for i in content.items() ] } )",
"print(\"\\nType missing for item: {}\".format(name)) raise TypeError(\"Type missing\") if content[\"type\"]",
"A json-schema to dict-schema parser \"\"\" def __init__(self, jsonschema): \"\"\"",
"of the schema and the value contains its content. return",
"} ) return schema_name def _get_field_dict(self, item, required_list=None): \"\"\" Transform",
"returns a new schema or a type depending on the",
"def _get_type_or_new_schema(self, item): \"\"\" returns a new schema or a",
"in a dict for the schema_dict and update self.schema_dict. In",
"the jsonschema (key, value) :param required_list: A list of names",
"the type in jsonschema :return: the type in schema_dict. \"\"\"",
"object in jsonschema is in the following format: \"object_name\": {\"type\":\"array\",",
"for i in content[\"properties\"].items() ] } schema_dict.update(ell) return schema_name def",
"name, content = item if required_list is None: required_list =",
"= self._get_new_schema_name(schema_dict=schema_dict, name=name) ell = { schema_name: [ self._get_element_dict( schema_dict=schema_dict,",
"== \"array\": return { \"name\": name, \"type\": self._get_array_schema(schema_dict=schema_dict, item=item), \"many\":",
"@staticmethod def _get_schema_name(name, n=0): \"\"\" Transform an element name into",
"name, content = item schema_name = self._get_new_schema_name(schema_dict=schema_dict, name=name) ell =",
"\"\"\" Transform a \"normal\" item from the jsonschema in a",
"in a dict for the schema_dict and return it. This",
"jsonschema (key, value) :param required_list: A list of names corresponding",
"self._create_data_schema( schema_dict=schema_dict, item=item, required_list=jsonschema.get(\"required\"), ) self.schema = schema_dict def get_schema(self):",
"required_list) def _get_object_schema(self, schema_dict, item): \"\"\" Transform an object item",
"format: {\"schema_name\": [{\"name\":\"field1\", \"type\": \"field1_type\", \"many\": False, \"required\":(True or False)},",
"items that will directly translate into fields. :param item: The",
"(key, value) The value should be in the following format:",
"self._get_type_or_new_schema((name, content[\"items\"])) else: return self._get_type(content[\"type\"]) def _get_type(self, json_type): \"\"\" Translate",
"schema_dict and update self.schema_dict. In jsonschema arrays are similar to",
"example if name is \"values\" and n is 3: Values3Schema)",
"have a \"required\" key.value :return: The required list or empty",
"required_list = [] name, content = item if \"type\" not",
"or content[\"type\"] == \"object\": return self._get_schema_name(name) elif content[\"type\"] == \"array\":",
"name=name) ell = { schema_name: [ self._get_element_dict( schema_dict=schema_dict, item=i, required_list=self._get_required(content),",
"In jsonschema arrays are similar to python lists. The object",
"in content[\"properties\"].items() ] } ) elif \"$ref\" in content: schema_name",
"return schema_name def _get_field_dict(self, item, required_list=None): \"\"\" Transform a \"normal\"",
"a schema_dict. \"\"\" if required_list is None: required_list = []",
"required=(item[0] in required_list), allow_none=(\"null\" in item[1][\"type\"]), many=False, ) return d",
"dict-schema parser \"\"\" def __init__(self, jsonschema): \"\"\" Class to manage",
"format: \"object_name\": {\"type\":\"object\", \"properties\":{\"field1\": {...}, \"filed2\": {...}}, \"required\": [\"field1]} The",
"content[\"type\"] == \"array\"), required=name in required_list, ) schema_dict[DATASCHEMA].append(schema) return schema",
"for the schema_dict and return it. This is used for",
"dict( name=item[0], type=self._get_type(item[1][\"type\"]), required=(item[0] in required_list), allow_none=(\"null\" in item[1][\"type\"]), many=False,",
"item schema_name = self._get_new_schema_name(schema_dict=schema_dict, name=name) ell = { schema_name: [",
"the item is: (\"object_name\", {\"type\":\"object\", \"properties\":{\"a\": {...}, \"b\": {...}}) :return:",
"try_name @staticmethod def _get_required(content): \"\"\" Get the list of required",
"list of the fields required in the parent object. :return:",
"a dict for the schema_dict and update self.schema_dict. In jsonschema",
"dict for the schema_dict and update self.schema_dict. In jsonschema arrays",
"return self.types[not_null_type[0]] else: return self.types[json_type] @staticmethod def _get_schema_name(name, n=0): \"\"\"",
"schema_dict=schema_dict, item=i, required_list=self._get_required(content), ) for i in content.items() ] }",
":return A dict element for a schema_dict. \"\"\" if required_list",
"ref = re.search(\"definitions/(.+)\", content[\"$ref\"]).group(1) return self._get_schema_name(ref) def _get_type_or_new_schema(self, item): \"\"\"",
"object :return A dict element for a schema_dict. \"\"\" if",
"key.value :return: The required list or empty list. \"\"\" return",
"__init__(self, jsonschema): \"\"\" Class to manage internal dictionary schema :param",
"else: schema_dict.update( { schema_name: [ self._get_element_dict( schema_dict=schema_dict, item=i, required_list=self._get_required(content), )",
"empty list. \"\"\" return content.get(\"required\", []) def to_marshmallow(self): dict_params =",
"def to_marshmallow(self): dict_params = self.schema result_dict = {} ordered =",
"for key, params in tuplist: schema = ParameterSchema() # this",
"if content[\"type\"] == \"object\": return { \"name\": name, \"type\": self._get_object_schema(schema_dict=schema_dict,",
"item[1][\"type\"]), many=False, ) return d def _get_ref(self, item): \"\"\" Get",
"list or empty list. \"\"\" return content.get(\"required\", []) def to_marshmallow(self):",
"self._get_field_dict(item, required_list) def _get_object_schema(self, schema_dict, item): \"\"\" Transform an object",
"in required_list, ) schema_dict[DATASCHEMA].append(schema) return schema def _get_element_dict(self, schema_dict, item,",
"array. :param n: if n is different from 0, it",
"following format: {\"$ref\": \"#/definitions/object_name\"} :return The schema name (_get_schema_name(object_name)) \"\"\"",
"update self.schema_dict. In jsonschema arrays are similar to python lists.",
"format of the item is: (\"object_name\", {\"type\":\"object\", \"properties\":{\"a\": {...}, \"b\":",
"item, required_list=None): \"\"\" Transform a \"normal\" item from the jsonschema",
"value) :param required_list: a list of the fields required in",
"{ \"name\": name, \"type\": self._get_array_schema(schema_dict=schema_dict, item=item), \"many\": True, \"required\": (name",
"first and corresponding schema are created so a schema should",
"if \"$ref\" in content: return { \"name\": name, \"type\": self._get_ref(item),",
"are parsed first and corresponding schema are created so a",
"a type depending on the json_type \"\"\" name, content =",
"return schema_name def _get_array_schema(self, schema_dict, item): \"\"\" Transform a array",
"d = dict( name=item[0], type=self._get_type(item[1][\"type\"]), required=(item[0] in required_list), allow_none=(\"null\" in",
"corresponding to the required fields in the parent object :return",
"_get_schema_name(name, n=0): \"\"\" Transform an element name into a schema",
"+ 1 ) else: return try_name @staticmethod def _get_required(content): \"\"\"",
"sort_dict from cornflow_client.constants import JSON_TYPES, DATASCHEMA class DictSchema: \"\"\" A",
"def _create_data_schema(self, schema_dict, item, required_list=None): \"\"\" Add a schema to",
"return the schema dict. \"\"\" name, content = item if",
"is list: not_null_type = [i for i in json_type if",
"fields required in the parent object. :return: the schema_dict for",
"schema_dict.update(ell) return schema_name def _get_array_schema(self, schema_dict, item): \"\"\" Transform a",
"def _get_ref(self, item): \"\"\" Get the name of the schema",
"name of the schema for a jsonschema reference. jsonschema definitions",
"required name of it exist. :content: the dict which should",
"format: \"object_name\": {\"type\":\"array\", \"items\":{format_of_items}} The schema_dict object use the format:",
"manage internal dictionary schema :param jsonschema: a json schema \"\"\"",
"{ \"name\": name, \"type\": self._get_object_schema(schema_dict=schema_dict, item=item), \"many\": False, \"required\": (name",
"the jsonschema in a dict for the schema_dict and return",
"v: ordered[v[0]]) for key, params in tuplist: schema = ParameterSchema()",
"= sorted(dict_params.items(), key=lambda v: ordered[v[0]]) for key, params in tuplist:",
"{...}, \"b\": {...}}) :return: The schema name \"\"\" name, content",
"schema_dict[DATASCHEMA].append(schema) return schema def _get_element_dict(self, schema_dict, item, required_list=None): \"\"\" Parse",
"used for items that will directly translate into fields. :param",
"to the reference. :param item: The jsonschema item in format",
"(key, value) :param required_list: A list of names corresponding to",
"if name is \"values\" and n is 3: Values3Schema) :param",
"name of the object or array. :param n: if n",
"required_list), } else: return self._get_field_dict(item, required_list) def _get_object_schema(self, schema_dict, item):",
"\"$ref\" in content: return { \"name\": name, \"type\": self._get_ref(item), \"many\":",
"in required_list), } elif content[\"type\"] == \"array\": return { \"name\":",
"[ self._get_element_dict( schema_dict=schema_dict, item=i, required_list=self._get_required(content), ) for i in content.items()",
"to an object or array. The schema name use the",
"the following format: \"object_name\": {\"type\":\"object\", \"properties\":{\"field1\": {...}, \"filed2\": {...}}, \"required\":",
"= item schema_name = self._get_new_schema_name(schema_dict=schema_dict, name=name) ell = { schema_name:",
"return self.types[json_type] @staticmethod def _get_schema_name(name, n=0): \"\"\" Transform an element",
"def _get_array_schema(self, schema_dict, item): \"\"\" Transform a array item from",
"= content[\"items\"] schema_name = self._get_new_schema_name(schema_dict=schema_dict, name=name) if \"type\" in content",
"content and content[\"type\"] == \"object\": schema_dict.update( { schema_name: [ self._get_element_dict(",
"the parent object. :return: the schema_dict for this item \"\"\"",
"in required_list), allow_none=(\"null\" in item[1][\"type\"]), many=False, ) return d def",
"schema_dict=schema_dict, name=name, n=n + 1 ) else: return try_name @staticmethod",
"different from 0, it is added to the schema name.",
":param name: The name of the object or array. :param",
"in content and content[\"type\"] != \"array\": return self._get_type(content[\"type\"]) else: schema_dict.update(",
"depending on the json_type \"\"\" name, content = item if",
"Parse an item (key, value) from the jsonschema and return",
"schema name (_get_schema_name(object_name)) \"\"\" content = item[1] ref = re.search(\"definitions/(.+)\",",
"schema_dict, item, required_list=None): \"\"\" Add a schema to schema_dict[DATASCHEMA] :param",
"\"\"\" Class to manage internal dictionary schema :param jsonschema: a",
"names corresponding to the required fields in the parent object",
"content[\"type\"] != \"array\": return self._get_type(content[\"type\"]) else: schema_dict.update( { schema_name: [",
"\"\"\" if n == 0: return name.capitalize() + \"Schema\" else:",
"self._get_ref((None, content)) elif \"type\" in content and content[\"type\"] != \"array\":",
"DATASCHEMA class DictSchema: \"\"\" A json-schema to dict-schema parser \"\"\"",
"return self._get_new_schema_name( schema_dict=schema_dict, name=name, n=n + 1 ) else: return",
"params1 = schema.load(params, many=True) result_dict[key] = gen_schema(key, params1, result_dict) return",
"name of it exist. :content: the dict which should have",
"return self._get_type_or_new_schema((name, content[\"items\"])) else: return self._get_type(content[\"type\"]) def _get_type(self, json_type): \"\"\"",
"] } ) elif \"$ref\" in content: schema_name = self._get_ref((None,",
"in content.items() ] } ) return schema_name def _get_field_dict(self, item,",
"will directly translate into fields. :param item: The jsonschema item",
"self.schema_dict. In jsonschema arrays are similar to python lists. The",
"name use the following format: [name][n]Schema (for example if name",
":param jsonschema: a json schema \"\"\" self.types = JSON_TYPES schema_dict",
"directly translate into fields. :param item: The jsonschema item in",
"object. :return: the schema_dict for this item \"\"\" d =",
"def __init__(self, jsonschema): \"\"\" Class to manage internal dictionary schema",
"\"filed2\": {...}}, \"required\": [\"field1]} The schema_dict object use the format:",
"schema_dict and return it. This is used for items that",
"item \"\"\" d = dict( name=item[0], type=self._get_type(item[1][\"type\"]), required=(item[0] in required_list),",
"\"null\"] if len(not_null_type) > 1: raise Warning(\"Warning: more than one",
"list of parameters: params1 = schema.load(params, many=True) result_dict[key] = gen_schema(key,",
"content[\"$ref\"]).group(1) return self._get_schema_name(ref) def _get_type_or_new_schema(self, item): \"\"\" returns a new",
"the following format: \"object_name\": {\"type\":\"array\", \"items\":{format_of_items}} The schema_dict object use",
"list of required name of it exist. :content: the dict",
"jsonschema in a dict for the schema_dict and return it.",
"in content: return { \"name\": name, \"type\": self._get_ref(item), \"many\": False,",
"object item from the jsonschema in a dict for the",
"} ) elif \"$ref\" in content: schema_name = self._get_ref((None, content))",
"jsonschema[\"definitions\"].items(): self._get_element_dict(schema_dict=schema_dict, item=item) if \"properties\" in jsonschema: for item in",
"item: The jsonschema item in format (key, value) :param required_list:",
"[]} def _create_data_schema(self, schema_dict, item, required_list=None): \"\"\" Add a schema",
"\"array\"), required=name in required_list, ) schema_dict[DATASCHEMA].append(schema) return schema def _get_element_dict(self,",
"item=item) self._create_data_schema( schema_dict=schema_dict, item=item, required_list=jsonschema.get(\"required\"), ) self.schema = schema_dict def",
"required fields in the parent object :return A dict element",
"result_dict = {} ordered = sort_dict(dict_params) tuplist = sorted(dict_params.items(), key=lambda",
"The schema_dict object use the format: {\"schema_name\": [{\"name\":\"field1\", \"type\": \"field1_type\",",
"name. \"\"\" if n == 0: return name.capitalize() + \"Schema\"",
"in jsonschema: for item in jsonschema[\"definitions\"].items(): self._get_element_dict(schema_dict=schema_dict, item=item) if \"properties\"",
"schema_dict for this item \"\"\" d = dict( name=item[0], type=self._get_type(item[1][\"type\"]),",
":return: The schema name \"\"\" name, content = item content",
"the name of the schema and the value contains its",
"content[\"type\"] == \"array\": return self._get_type_or_new_schema((name, content[\"items\"])) else: return self._get_type(content[\"type\"]) def",
"and the value contains its content. return the schema dict.",
"schema_dict. \"\"\" if required_list is None: required_list = [] name,",
"required_list=jsonschema.get(\"required\"), ) self.schema = schema_dict def get_schema(self): return self.schema @staticmethod",
"3: Values3Schema) :param name: The name of the object or",
"a dict for the schema_dict and return it. This is",
"more than one type given\") return self.types[not_null_type[0]] else: return self.types[json_type]",
"required_list is None: required_list = [] schema = dict( name=name,",
"dict for the schema_dict and return it. This is used",
"a list of the fields required in the parent object.",
"to dict-schema parser \"\"\" def __init__(self, jsonschema): \"\"\" Class to",
"in jsonschema :return: the type in schema_dict. \"\"\" if type(json_type)",
"self._get_new_schema_name(schema_dict=schema_dict, name=name) if \"type\" in content and content[\"type\"] == \"object\":",
"\"required\": [\"field1]} The schema_dict object use the format: {\"schema_name\": [{\"name\":\"field1\",",
"gen_schema, ParameterSchema, sort_dict from cornflow_client.constants import JSON_TYPES, DATASCHEMA class DictSchema:",
"len(not_null_type) > 1: raise Warning(\"Warning: more than one type given\")",
"a dict. The key contains the name of the schema",
"item in jsonschema[\"properties\"].items(): self._get_element_dict(schema_dict=schema_dict, item=item) self._create_data_schema( schema_dict=schema_dict, item=item, required_list=jsonschema.get(\"required\"), )",
"value contains its content. return the schema dict. \"\"\" name,",
"for the schema_dict and update self.schema_dict. In jsonschema arrays are",
"{\"type\":\"array\", \"items\":{format_of_items}} The schema_dict object use the format: {\"schema_name\": [{\"name\":\"field1\",",
":param n: if n is different from 0, it is",
"\"required\" key.value :return: The required list or empty list. \"\"\"",
"content[\"items\"] schema_name = self._get_new_schema_name(schema_dict=schema_dict, name=name) if \"type\" in content and",
"jsonschema :return: the type in schema_dict. \"\"\" if type(json_type) is",
"> 1: raise Warning(\"Warning: more than one type given\") return",
"key=lambda v: ordered[v[0]]) for key, params in tuplist: schema =",
"update self.schema_dict. In jsonschema objects are similar to python dict.",
"\"type\" not in content: if \"$ref\" in content: return {",
"A dict element for a schema_dict. \"\"\" if required_list is",
"{DATASCHEMA: []} def _create_data_schema(self, schema_dict, item, required_list=None): \"\"\" Add a",
"item=item), \"many\": True, \"required\": (name in required_list), } else: return",
"The key contains the name of the schema and the",
"value should be in the following format: {\"$ref\": \"#/definitions/object_name\"} :return",
"The name of the object or array. :param n: if",
"{...}}) :return: The schema name \"\"\" name, content = item",
"many=(\"type\" in content and content[\"type\"] == \"array\"), required=name in required_list,",
"similar to python dict. The object in jsonschema is in",
"json_type \"\"\" name, content = item if \"type\" not in",
":param item: The jsonschema item in format (key, value) :param",
"than one type given\") return self.types[not_null_type[0]] else: return self.types[json_type] @staticmethod",
"\"normal\" item from the jsonschema in a dict for the",
"\"\"\" Get the list of required name of it exist.",
"dict. \"\"\" name, content = item if required_list is None:",
"in format (key, value) The value should be in the",
"and n is 3: Values3Schema) :param name: The name of",
"\"properties\":{\"field1\": {...}, \"filed2\": {...}}, \"required\": [\"field1]} The schema_dict object use",
"schema_dict = self.get_empty_schema() if \"definitions\" in jsonschema: for item in",
"schema_dict, name, n=0): try_name = self._get_schema_name(name, n) if try_name in",
"is \"values\" and n is 3: Values3Schema) :param name: The",
"required_list, ) schema_dict[DATASCHEMA].append(schema) return schema def _get_element_dict(self, schema_dict, item, required_list=None):",
"ParameterSchema() # this line validates the list of parameters: params1",
"item): \"\"\" returns a new schema or a type depending",
"content or content[\"type\"] == \"object\": return self._get_schema_name(name) elif content[\"type\"] ==",
"required_list is None: required_list = [] name, content = item",
":param required_list: a list of the fields required in the",
"allow_none=(\"null\" in item[1][\"type\"]), many=False, ) return d def _get_ref(self, item):",
"self.types[json_type] @staticmethod def _get_schema_name(name, n=0): \"\"\" Transform an element name",
"use the following format: [name][n]Schema (for example if name is",
"are similar to python dict. The object in jsonschema is",
"in required_list), } else: print(\"\\nType missing for item: {}\".format(name)) raise",
"a schema name in order to create a schema corresponding",
"name of the schema and the value contains its content.",
"elif \"$ref\" in content: schema_name = self._get_ref((None, content)) elif \"type\"",
"required_list=None): \"\"\" Transform a \"normal\" item from the jsonschema in",
"\"\"\" Transform an object item from the jsonschema in a",
"content = item schema_name = self._get_new_schema_name(schema_dict=schema_dict, name=name) ell = {",
"line validates the list of parameters: params1 = schema.load(params, many=True)",
"item if required_list is None: required_list = [] schema =",
"n == 0: return name.capitalize() + \"Schema\" else: return name.capitalize()",
"] } schema_dict.update(ell) return schema_name def _get_array_schema(self, schema_dict, item): \"\"\"",
"get_empty_schema(): \"\"\" Create un empty schema dict \"\"\" return {DATASCHEMA:",
"list of names corresponding to the required fields in the",
"return it. This is used for items that will directly",
"item): \"\"\" Transform a array item from the jsonschema in",
"in jsonschema is in the following format: \"object_name\": {\"type\":\"array\", \"items\":{format_of_items}}",
"return name.capitalize() + \"Schema\" else: return name.capitalize() + str(n) +",
"(key, value) The format of the item is: (\"object_name\", {\"type\":\"object\",",
"\"required\": (name in required_list), } else: return self._get_field_dict(item, required_list) def",
"from .dict_functions import gen_schema, ParameterSchema, sort_dict from cornflow_client.constants import JSON_TYPES,",
"in content and content[\"type\"] == \"array\"), required=name in required_list, )",
"\"definitions\" in jsonschema: for item in jsonschema[\"definitions\"].items(): self._get_element_dict(schema_dict=schema_dict, item=item) if",
"_create_data_schema(self, schema_dict, item, required_list=None): \"\"\" Add a schema to schema_dict[DATASCHEMA]",
"None: required_list = [] name, content = item if \"type\"",
"in schema_dict. \"\"\" if type(json_type) is list: not_null_type = [i",
"in the following format: \"object_name\": {\"type\":\"object\", \"properties\":{\"field1\": {...}, \"filed2\": {...}},",
"name, \"type\": self._get_ref(item), \"many\": False, \"required\": (name in required_list), }",
"item: The jsonschema item (key, value) The format of the",
"between jsonschema and schema_dict. :param json_type: the type in jsonschema",
"\"\"\" def __init__(self, jsonschema): \"\"\" Class to manage internal dictionary",
"content)) elif \"type\" in content and content[\"type\"] != \"array\": return",
":param item: (key, value) of a dict. The key contains",
"Transform a \"normal\" item from the jsonschema in a dict",
"== \"array\": return self._get_type_or_new_schema((name, content[\"items\"])) else: return self._get_type(content[\"type\"]) def _get_type(self,",
") for i in content.items() ] } ) return schema_name",
"schema and the value contains its content. return the schema",
"schema name use the following format: [name][n]Schema (for example if",
"False, \"required\": (name in required_list), } elif content[\"type\"] == \"array\":",
"== \"object\": return { \"name\": name, \"type\": self._get_object_schema(schema_dict=schema_dict, item=item), \"many\":",
"i in content.items() ] } ) return schema_name def _get_field_dict(self,",
"name in order to create a schema corresponding to an",
"n=n + 1 ) else: return try_name @staticmethod def _get_required(content):",
"parent object. :return: the schema_dict for this item \"\"\" d",
"that will directly translate into fields. :param item: The jsonschema",
"...] :param item: The jsonschema item (key, value) The format",
"\"\"\" Transform a array item from the jsonschema in a",
"a \"normal\" item from the jsonschema in a dict for",
"# this line validates the list of parameters: params1 =",
"name.capitalize() + \"Schema\" else: return name.capitalize() + str(n) + \"Schema\"",
"type(json_type) is list: not_null_type = [i for i in json_type",
"n) if try_name in schema_dict: return self._get_new_schema_name( schema_dict=schema_dict, name=name, n=n",
".dict_functions import gen_schema, ParameterSchema, sort_dict from cornflow_client.constants import JSON_TYPES, DATASCHEMA",
"[] name, content = item if \"type\" not in content:",
"jsonschema reference. jsonschema definitions are parsed first and corresponding schema",
"value) from the jsonschema and return the corresponding dict. :param",
"the schema_dict and update self.schema_dict. In jsonschema objects are similar",
"raise TypeError(\"Type missing\") if content[\"type\"] == \"object\": return { \"name\":",
"from 0, it is added to the schema name. :return:",
"in jsonschema: for item in jsonschema[\"properties\"].items(): self._get_element_dict(schema_dict=schema_dict, item=item) self._create_data_schema( schema_dict=schema_dict,",
"\"Schema\" else: return name.capitalize() + str(n) + \"Schema\" def _get_new_schema_name(self,",
"content = item if \"type\" not in content: if \"$ref\"",
"Get the list of required name of it exist. :content:",
"\"\"\" returns a new schema or a type depending on",
"The value should be in the following format: {\"$ref\": \"#/definitions/object_name\"}",
"of required name of it exist. :content: the dict which",
"schema def _get_element_dict(self, schema_dict, item, required_list=None): \"\"\" Parse an item",
"True, \"required\": (name in required_list), } else: return self._get_field_dict(item, required_list)",
"should have a \"required\" key.value :return: The required list or",
"item from the jsonschema in a dict for the schema_dict",
"{\"type\":\"object\", \"properties\":{\"field1\": {...}, \"filed2\": {...}}, \"required\": [\"field1]} The schema_dict object",
"fields. :param item: The jsonschema item in format (key, value)",
"+ str(n) + \"Schema\" def _get_new_schema_name(self, schema_dict, name, n=0): try_name",
"(_get_schema_name(object_name)) \"\"\" content = item[1] ref = re.search(\"definitions/(.+)\", content[\"$ref\"]).group(1) return",
"return self._get_schema_name(ref) def _get_type_or_new_schema(self, item): \"\"\" returns a new schema",
"name: The name of the object or array. :param n:",
"for i in content.items() ] } ) return schema_name def",
"\"Schema\" def _get_new_schema_name(self, schema_dict, name, n=0): try_name = self._get_schema_name(name, n)",
"to the required fields in the parent object :return A",
"jsonschema in a dict for the schema_dict and update self.schema_dict.",
"fields in the parent object :return A dict element for",
"created so a schema should exist corresponding to the reference.",
"in schema_dict: return self._get_new_schema_name( schema_dict=schema_dict, name=name, n=n + 1 )",
"jsonschema and return the corresponding dict. :param item: An item",
"schema_dict and update self.schema_dict. In jsonschema objects are similar to",
":param json_type: the type in jsonschema :return: the type in",
"self.schema = schema_dict def get_schema(self): return self.schema @staticmethod def get_empty_schema():",
"\"object_name\": {\"type\":\"array\", \"items\":{format_of_items}} The schema_dict object use the format: {\"schema_name\":",
":param item: The jsonschema item (key, value) The format of",
"{\"schema_name\": [{\"name\":\"field1\", \"type\": \"field1_type\", \"many\": False, \"required\":(True or False) :param",
"\"\"\" d = dict( name=item[0], type=self._get_type(item[1][\"type\"]), required=(item[0] in required_list), allow_none=(\"null\"",
"for the schema_dict and update self.schema_dict. In jsonschema objects are",
"name.capitalize() + str(n) + \"Schema\" def _get_new_schema_name(self, schema_dict, name, n=0):",
"if required_list is None: required_list = [] name, content =",
"required_list = [] schema = dict( name=name, type=self._get_type_or_new_schema(item), many=(\"type\" in",
"The jsonschema item in format (key, value) The value should",
"following format: [name][n]Schema (for example if name is \"values\" and",
"The object in jsonschema is in the following format: \"object_name\":",
"reference. jsonschema definitions are parsed first and corresponding schema are",
"dict( name=name, type=self._get_type_or_new_schema(item), many=(\"type\" in content and content[\"type\"] == \"array\"),",
"schema_name def _get_array_schema(self, schema_dict, item): \"\"\" Transform a array item",
"= dict( name=name, type=self._get_type_or_new_schema(item), many=(\"type\" in content and content[\"type\"] ==",
"schema_name = self._get_ref((None, content)) elif \"type\" in content and content[\"type\"]",
"key, params in tuplist: schema = ParameterSchema() # this line",
"schema to schema_dict[DATASCHEMA] :param item: (key, value) of a dict.",
"the required fields in the parent object :return A dict",
"= item[1] ref = re.search(\"definitions/(.+)\", content[\"$ref\"]).group(1) return self._get_schema_name(ref) def _get_type_or_new_schema(self,",
"return { \"name\": name, \"type\": self._get_ref(item), \"many\": False, \"required\": (name",
"schema dict \"\"\" return {DATASCHEMA: []} def _create_data_schema(self, schema_dict, item,",
"def get_empty_schema(): \"\"\" Create un empty schema dict \"\"\" return",
"jsonschema: a json schema \"\"\" self.types = JSON_TYPES schema_dict =",
"(name in required_list), } elif content[\"type\"] == \"array\": return {",
"many=False, ) return d def _get_ref(self, item): \"\"\" Get the",
"if type(json_type) is list: not_null_type = [i for i in",
"Add a schema to schema_dict[DATASCHEMA] :param item: (key, value) of",
"JSON_TYPES, DATASCHEMA class DictSchema: \"\"\" A json-schema to dict-schema parser",
"is None: required_list = [] name, content = item if",
"\"object\": return { \"name\": name, \"type\": self._get_object_schema(schema_dict=schema_dict, item=item), \"many\": False,",
"type in jsonschema :return: the type in schema_dict. \"\"\" if",
"} schema_dict.update(ell) return schema_name def _get_array_schema(self, schema_dict, item): \"\"\" Transform",
"in the parent object. :return: the schema_dict for this item",
"_get_type_or_new_schema(self, item): \"\"\" returns a new schema or a type",
"if \"definitions\" in jsonschema: for item in jsonschema[\"definitions\"].items(): self._get_element_dict(schema_dict=schema_dict, item=item)",
"\"\"\" Parse an item (key, value) from the jsonschema and",
"if \"type\" not in content or content[\"type\"] == \"object\": return",
"def _get_element_dict(self, schema_dict, item, required_list=None): \"\"\" Parse an item (key,",
"of the item is: (\"object_name\", {\"type\":\"object\", \"properties\":{\"a\": {...}, \"b\": {...}})",
"else: return try_name @staticmethod def _get_required(content): \"\"\" Get the list",
"is used for items that will directly translate into fields.",
"= {} ordered = sort_dict(dict_params) tuplist = sorted(dict_params.items(), key=lambda v:",
") elif \"$ref\" in content: schema_name = self._get_ref((None, content)) elif",
"\"field1_type\", \"many\": False, \"required\":(True or False)}, ...] :param item: The",
"schema_name def _get_field_dict(self, item, required_list=None): \"\"\" Transform a \"normal\" item",
"sort_dict(dict_params) tuplist = sorted(dict_params.items(), key=lambda v: ordered[v[0]]) for key, params",
"item: {}\".format(name)) raise TypeError(\"Type missing\") if content[\"type\"] == \"object\": return",
"\"field1_type\", \"many\": False, \"required\":(True or False) :param item: The jsonschema",
"it is added to the schema name. :return: the corresponding",
"the value contains its content. return the schema dict. \"\"\"",
"name, content = item if \"type\" not in content: if",
"the jsonschema in a dict for the schema_dict and update",
"self._get_schema_name(name, n) if try_name in schema_dict: return self._get_new_schema_name( schema_dict=schema_dict, name=name,",
"{} ordered = sort_dict(dict_params) tuplist = sorted(dict_params.items(), key=lambda v: ordered[v[0]])",
":return: The schema name \"\"\" name, content = item schema_name",
"{ schema_name: [ self._get_element_dict( schema_dict=schema_dict, item=i, required_list=self._get_required(content), ) for i",
"schema name. \"\"\" if n == 0: return name.capitalize() +",
"try_name = self._get_schema_name(name, n) if try_name in schema_dict: return self._get_new_schema_name(",
"un empty schema dict \"\"\" return {DATASCHEMA: []} def _create_data_schema(self,",
"item from the jsonschema (key, value) :param required_list: A list",
"\"\"\" name, content = item schema_name = self._get_new_schema_name(schema_dict=schema_dict, name=name) ell",
"= self.get_empty_schema() if \"definitions\" in jsonschema: for item in jsonschema[\"definitions\"].items():",
"object or array. The schema name use the following format:",
"corresponding to an object or array. The schema name use",
"missing for item: {}\".format(name)) raise TypeError(\"Type missing\") if content[\"type\"] ==",
"required_list=None): \"\"\" Add a schema to schema_dict[DATASCHEMA] :param item: (key,",
") return d def _get_ref(self, item): \"\"\" Get the name",
"json schema \"\"\" self.types = JSON_TYPES schema_dict = self.get_empty_schema() if",
"schema_dict object use the format: {\"schema_name\": [{\"name\":\"field1\", \"type\": \"field1_type\", \"many\":",
"n=0): try_name = self._get_schema_name(name, n) if try_name in schema_dict: return",
"the name of the schema for a jsonschema reference. jsonschema",
"content[\"type\"] == \"array\": return { \"name\": name, \"type\": self._get_array_schema(schema_dict=schema_dict, item=item),",
"content = item[1] ref = re.search(\"definitions/(.+)\", content[\"$ref\"]).group(1) return self._get_schema_name(ref) def",
"\"items\":{format_of_items}} The schema_dict object use the format: {\"schema_name\": [{\"name\":\"field1\", \"type\":",
"return self._get_type(content[\"type\"]) def _get_type(self, json_type): \"\"\" Translate the type between",
"The required list or empty list. \"\"\" return content.get(\"required\", [])",
"[]) def to_marshmallow(self): dict_params = self.schema result_dict = {} ordered",
"schema_name = self._get_new_schema_name(schema_dict=schema_dict, name=name) if \"type\" in content and content[\"type\"]",
"and update self.schema_dict. In jsonschema arrays are similar to python",
"a jsonschema reference. jsonschema definitions are parsed first and corresponding",
"the object or array. :param n: if n is different",
"schema :param jsonschema: a json schema \"\"\" self.types = JSON_TYPES",
"type depending on the json_type \"\"\" name, content = item",
"= [i for i in json_type if i != \"null\"]",
"self.types[not_null_type[0]] else: return self.types[json_type] @staticmethod def _get_schema_name(name, n=0): \"\"\" Transform",
"content[\"type\"] == \"object\": schema_dict.update( { schema_name: [ self._get_element_dict( schema_dict=schema_dict, item=i,",
"item in format (key, value) The value should be in",
"import gen_schema, ParameterSchema, sort_dict from cornflow_client.constants import JSON_TYPES, DATASCHEMA class",
"jsonschema[\"properties\"].items(): self._get_element_dict(schema_dict=schema_dict, item=item) self._create_data_schema( schema_dict=schema_dict, item=item, required_list=jsonschema.get(\"required\"), ) self.schema =",
"if try_name in schema_dict: return self._get_new_schema_name( schema_dict=schema_dict, name=name, n=n +",
"content and content[\"type\"] == \"array\"), required=name in required_list, ) schema_dict[DATASCHEMA].append(schema)",
"the schema_dict and update self.schema_dict. In jsonschema arrays are similar",
"if \"properties\" in jsonschema: for item in jsonschema[\"properties\"].items(): self._get_element_dict(schema_dict=schema_dict, item=item)",
"[] schema = dict( name=name, type=self._get_type_or_new_schema(item), many=(\"type\" in content and",
"ordered = sort_dict(dict_params) tuplist = sorted(dict_params.items(), key=lambda v: ordered[v[0]]) for",
"from the jsonschema in a dict for the schema_dict and",
"self._get_element_dict( schema_dict=schema_dict, item=i, required_list=self._get_required(content), ) for i in content[\"properties\"].items() ]",
"} elif content[\"type\"] == \"array\": return { \"name\": name, \"type\":",
"\"properties\" in jsonschema: for item in jsonschema[\"properties\"].items(): self._get_element_dict(schema_dict=schema_dict, item=item) self._create_data_schema(",
"_get_element_dict(self, schema_dict, item, required_list=None): \"\"\" Parse an item (key, value)",
"\"name\": name, \"type\": self._get_array_schema(schema_dict=schema_dict, item=item), \"many\": True, \"required\": (name in",
"the corresponding dict. :param item: An item from the jsonschema",
"item[1] ref = re.search(\"definitions/(.+)\", content[\"$ref\"]).group(1) return self._get_schema_name(ref) def _get_type_or_new_schema(self, item):",
"is added to the schema name. :return: the corresponding schema",
"return self._get_field_dict(item, required_list) def _get_object_schema(self, schema_dict, item): \"\"\" Transform an",
"name=name, n=n + 1 ) else: return try_name @staticmethod def",
"dict_params = self.schema result_dict = {} ordered = sort_dict(dict_params) tuplist",
"to the schema name. :return: the corresponding schema name. \"\"\"",
"name, content = item content = content[\"items\"] schema_name = self._get_new_schema_name(schema_dict=schema_dict,",
") return schema_name def _get_field_dict(self, item, required_list=None): \"\"\" Transform a",
"from cornflow_client.constants import JSON_TYPES, DATASCHEMA class DictSchema: \"\"\" A json-schema",
"key contains the name of the schema and the value",
"schema_dict, item, required_list=None): \"\"\" Parse an item (key, value) from",
"it exist. :content: the dict which should have a \"required\"",
"type between jsonschema and schema_dict. :param json_type: the type in",
"1: raise Warning(\"Warning: more than one type given\") return self.types[not_null_type[0]]",
"return {DATASCHEMA: []} def _create_data_schema(self, schema_dict, item, required_list=None): \"\"\" Add",
"[name][n]Schema (for example if name is \"values\" and n is",
"\"type\": self._get_ref(item), \"many\": False, \"required\": (name in required_list), } else:",
"\"object_name\": {\"type\":\"object\", \"properties\":{\"field1\": {...}, \"filed2\": {...}}, \"required\": [\"field1]} The schema_dict",
"type in schema_dict. \"\"\" if type(json_type) is list: not_null_type =",
"= schema.load(params, many=True) result_dict[key] = gen_schema(key, params1, result_dict) return result_dict[DATASCHEMA]",
"not in content: if \"$ref\" in content: return { \"name\":",
"def _get_schema_name(name, n=0): \"\"\" Transform an element name into a",
"item): \"\"\" Get the name of the schema for a",
"@staticmethod def _get_required(content): \"\"\" Get the list of required name",
"schema_dict def get_schema(self): return self.schema @staticmethod def get_empty_schema(): \"\"\" Create",
"An item from the jsonschema (key, value) :param required_list: A",
"in the parent object :return A dict element for a",
"arrays are similar to python lists. The object in jsonschema",
"format (key, value) The value should be in the following",
"following format: \"object_name\": {\"type\":\"object\", \"properties\":{\"field1\": {...}, \"filed2\": {...}}, \"required\": [\"field1]}",
"should exist corresponding to the reference. :param item: The jsonschema",
"the fields required in the parent object. :return: the schema_dict",
"\"many\": False, \"required\":(True or False)}, ...] :param item: The jsonschema",
"return the corresponding dict. :param item: An item from the",
"\"properties\":{\"a\": {...}, \"b\": {...}}) :return: The schema name \"\"\" name,",
"jsonschema is in the following format: \"object_name\": {\"type\":\"array\", \"items\":{format_of_items}} The",
"content = content[\"items\"] schema_name = self._get_new_schema_name(schema_dict=schema_dict, name=name) if \"type\" in",
"def get_schema(self): return self.schema @staticmethod def get_empty_schema(): \"\"\" Create un",
"content[\"type\"] == \"object\": return self._get_schema_name(name) elif content[\"type\"] == \"array\": return",
"\"\"\" return {DATASCHEMA: []} def _create_data_schema(self, schema_dict, item, required_list=None): \"\"\"",
"(key, value) of a dict. The key contains the name",
"and update self.schema_dict. In jsonschema objects are similar to python",
"name=name) if \"type\" in content and content[\"type\"] == \"object\": schema_dict.update(",
"in item[1][\"type\"]), many=False, ) return d def _get_ref(self, item): \"\"\"",
"item, required_list=None): \"\"\" Parse an item (key, value) from the",
"schema_dict, item): \"\"\" Transform a array item from the jsonschema",
"\"many\": False, \"required\":(True or False) :param item: The jsonschema item",
"schema name \"\"\" name, content = item content = content[\"items\"]",
"the corresponding schema name. \"\"\" if n == 0: return",
"[i for i in json_type if i != \"null\"] if",
"this line validates the list of parameters: params1 = schema.load(params,",
"name, \"type\": self._get_object_schema(schema_dict=schema_dict, item=item), \"many\": False, \"required\": (name in required_list),",
"schema_dict.update( { schema_name: [ self._get_element_dict( schema_dict=schema_dict, item=i, required_list=self._get_required(content), ) for",
"item if \"type\" not in content or content[\"type\"] == \"object\":",
"} else: print(\"\\nType missing for item: {}\".format(name)) raise TypeError(\"Type missing\")",
"= dict( name=item[0], type=self._get_type(item[1][\"type\"]), required=(item[0] in required_list), allow_none=(\"null\" in item[1][\"type\"]),",
"value) The format of the item is: (\"object_name\", {\"type\":\"object\", \"properties\":{\"a\":",
"an object or array. The schema name use the following",
"content: schema_name = self._get_ref((None, content)) elif \"type\" in content and",
"of a dict. The key contains the name of the",
"\"required\": (name in required_list), } elif content[\"type\"] == \"array\": return",
"\"type\" not in content or content[\"type\"] == \"object\": return self._get_schema_name(name)",
"self._get_schema_name(name) elif content[\"type\"] == \"array\": return self._get_type_or_new_schema((name, content[\"items\"])) else: return",
"The jsonschema item (key, value) The format of the item",
"in order to create a schema corresponding to an object",
"format: {\"schema_name\": [{\"name\":\"field1\", \"type\": \"field1_type\", \"many\": False, \"required\":(True or False)",
":return: The required list or empty list. \"\"\" return content.get(\"required\",",
"a new schema or a type depending on the json_type",
"if n is different from 0, it is added to",
"else: print(\"\\nType missing for item: {}\".format(name)) raise TypeError(\"Type missing\") if",
"missing\") if content[\"type\"] == \"object\": return { \"name\": name, \"type\":",
"and corresponding schema are created so a schema should exist",
"TypeError(\"Type missing\") if content[\"type\"] == \"object\": return { \"name\": name,",
"str(n) + \"Schema\" def _get_new_schema_name(self, schema_dict, name, n=0): try_name =",
") self.schema = schema_dict def get_schema(self): return self.schema @staticmethod def",
"A list of names corresponding to the required fields in",
"similar to python lists. The object in jsonschema is in",
"of the fields required in the parent object. :return: the",
"return self._get_type(content[\"type\"]) else: schema_dict.update( { schema_name: [ self._get_element_dict( schema_dict=schema_dict, item=i,",
"of the object or array. :param n: if n is",
"in json_type if i != \"null\"] if len(not_null_type) > 1:",
"schema_dict. :param json_type: the type in jsonschema :return: the type",
"== 0: return name.capitalize() + \"Schema\" else: return name.capitalize() +",
"corresponding schema are created so a schema should exist corresponding",
"\"\"\" self.types = JSON_TYPES schema_dict = self.get_empty_schema() if \"definitions\" in",
"the type in schema_dict. \"\"\" if type(json_type) is list: not_null_type",
"content[\"properties\"].items() ] } schema_dict.update(ell) return schema_name def _get_array_schema(self, schema_dict, item):",
"{}\".format(name)) raise TypeError(\"Type missing\") if content[\"type\"] == \"object\": return {",
"contains its content. return the schema dict. \"\"\" name, content",
"elif \"type\" in content and content[\"type\"] != \"array\": return self._get_type(content[\"type\"])",
"raise Warning(\"Warning: more than one type given\") return self.types[not_null_type[0]] else:",
"Get the name of the schema for a jsonschema reference.",
"+ \"Schema\" def _get_new_schema_name(self, schema_dict, name, n=0): try_name = self._get_schema_name(name,",
"Transform a array item from the jsonschema in a dict",
"the format: {\"schema_name\": [{\"name\":\"field1\", \"type\": \"field1_type\", \"many\": False, \"required\":(True or",
"required_list=self._get_required(content), ) for i in content.items() ] } ) return",
"content and content[\"type\"] != \"array\": return self._get_type(content[\"type\"]) else: schema_dict.update( {",
"elif content[\"type\"] == \"array\": return { \"name\": name, \"type\": self._get_array_schema(schema_dict=schema_dict,",
"required_list=self._get_required(content), ) for i in content[\"properties\"].items() ] } schema_dict.update(ell) return",
"required_list=None): \"\"\" Parse an item (key, value) from the jsonschema",
"return self.schema @staticmethod def get_empty_schema(): \"\"\" Create un empty schema",
"n is different from 0, it is added to the",
"jsonschema objects are similar to python dict. The object in",
"item in jsonschema[\"definitions\"].items(): self._get_element_dict(schema_dict=schema_dict, item=item) if \"properties\" in jsonschema: for",
"and content[\"type\"] != \"array\": return self._get_type(content[\"type\"]) else: schema_dict.update( { schema_name:",
"item (key, value) from the jsonschema and return the corresponding",
"Values3Schema) :param name: The name of the object or array.",
"DictSchema: \"\"\" A json-schema to dict-schema parser \"\"\" def __init__(self,",
"to manage internal dictionary schema :param jsonschema: a json schema",
"sorted(dict_params.items(), key=lambda v: ordered[v[0]]) for key, params in tuplist: schema",
":param required_list: A list of names corresponding to the required",
"for a schema_dict. \"\"\" if required_list is None: required_list =",
"value) The value should be in the following format: {\"$ref\":",
"python lists. The object in jsonschema is in the following",
"This is used for items that will directly translate into",
"The schema name (_get_schema_name(object_name)) \"\"\" content = item[1] ref =",
"\"\"\" if type(json_type) is list: not_null_type = [i for i",
"order to create a schema corresponding to an object or",
"schema corresponding to an object or array. The schema name",
"name=name, type=self._get_type_or_new_schema(item), many=(\"type\" in content and content[\"type\"] == \"array\"), required=name",
"item (key, value) The format of the item is: (\"object_name\",",
"return self._get_schema_name(name) elif content[\"type\"] == \"array\": return self._get_type_or_new_schema((name, content[\"items\"])) else:",
"if n == 0: return name.capitalize() + \"Schema\" else: return",
"schema or a type depending on the json_type \"\"\" name,",
"The schema name \"\"\" name, content = item schema_name =",
"validates the list of parameters: params1 = schema.load(params, many=True) result_dict[key]",
"i in content[\"properties\"].items() ] } ) elif \"$ref\" in content:",
"Create un empty schema dict \"\"\" return {DATASCHEMA: []} def",
"in required_list), } else: return self._get_field_dict(item, required_list) def _get_object_schema(self, schema_dict,",
"_get_required(content): \"\"\" Get the list of required name of it",
"value) :param required_list: A list of names corresponding to the",
"a json schema \"\"\" self.types = JSON_TYPES schema_dict = self.get_empty_schema()",
"n is 3: Values3Schema) :param name: The name of the",
"self._get_new_schema_name( schema_dict=schema_dict, name=name, n=n + 1 ) else: return try_name",
"in format (key, value) :param required_list: a list of the",
"or a type depending on the json_type \"\"\" name, content",
"schema_name = self._get_new_schema_name(schema_dict=schema_dict, name=name) ell = { schema_name: [ self._get_element_dict(",
"the type between jsonschema and schema_dict. :param json_type: the type",
"return schema def _get_element_dict(self, schema_dict, item, required_list=None): \"\"\" Parse an",
"else: return self._get_field_dict(item, required_list) def _get_object_schema(self, schema_dict, item): \"\"\" Transform",
"schema_dict, item): \"\"\" Transform an object item from the jsonschema",
"is None: required_list = [] schema = dict( name=name, type=self._get_type_or_new_schema(item),",
"content[\"type\"] == \"object\": return { \"name\": name, \"type\": self._get_object_schema(schema_dict=schema_dict, item=item),",
"the schema_dict and return it. This is used for items",
"added to the schema name. :return: the corresponding schema name.",
"required=name in required_list, ) schema_dict[DATASCHEMA].append(schema) return schema def _get_element_dict(self, schema_dict,",
"def _get_field_dict(self, item, required_list=None): \"\"\" Transform a \"normal\" item from",
"def _get_new_schema_name(self, schema_dict, name, n=0): try_name = self._get_schema_name(name, n) if",
"contains the name of the schema and the value contains",
"schema name in order to create a schema corresponding to",
"array item from the jsonschema in a dict for the",
"\"array\": return { \"name\": name, \"type\": self._get_array_schema(schema_dict=schema_dict, item=item), \"many\": True,",
"required_list), } else: print(\"\\nType missing for item: {}\".format(name)) raise TypeError(\"Type",
"jsonschema item (key, value) The format of the item is:",
"on the json_type \"\"\" name, content = item if \"type\"",
"_get_object_schema(self, schema_dict, item): \"\"\" Transform an object item from the",
"for i in json_type if i != \"null\"] if len(not_null_type)",
"= item content = content[\"items\"] schema_name = self._get_new_schema_name(schema_dict=schema_dict, name=name) if",
"\"b\": {...}}) :return: The schema name \"\"\" name, content =",
") for i in content[\"properties\"].items() ] } schema_dict.update(ell) return schema_name",
"and schema_dict. :param json_type: the type in jsonschema :return: the",
"return content.get(\"required\", []) def to_marshmallow(self): dict_params = self.schema result_dict =",
"item=item, required_list=jsonschema.get(\"required\"), ) self.schema = schema_dict def get_schema(self): return self.schema",
"format: [name][n]Schema (for example if name is \"values\" and n",
"for i in content[\"properties\"].items() ] } ) elif \"$ref\" in",
"(key, value) :param required_list: a list of the fields required",
"= [] schema = dict( name=name, type=self._get_type_or_new_schema(item), many=(\"type\" in content",
"schema for a jsonschema reference. jsonschema definitions are parsed first",
"\"type\": \"field1_type\", \"many\": False, \"required\":(True or False)}, ...] :param item:",
"objects are similar to python dict. The object in jsonschema",
"so a schema should exist corresponding to the reference. :param",
"The format of the item is: (\"object_name\", {\"type\":\"object\", \"properties\":{\"a\": {...},",
"for item in jsonschema[\"properties\"].items(): self._get_element_dict(schema_dict=schema_dict, item=item) self._create_data_schema( schema_dict=schema_dict, item=item, required_list=jsonschema.get(\"required\"),",
"(key, value) from the jsonschema and return the corresponding dict.",
"The jsonschema item in format (key, value) :param required_list: a",
"required_list: a list of the fields required in the parent",
"= sort_dict(dict_params) tuplist = sorted(dict_params.items(), key=lambda v: ordered[v[0]]) for key,",
"{...}, \"filed2\": {...}}, \"required\": [\"field1]} The schema_dict object use the",
"\"name\": name, \"type\": self._get_object_schema(schema_dict=schema_dict, item=item), \"many\": False, \"required\": (name in",
"an element name into a schema name in order to",
"list. \"\"\" return content.get(\"required\", []) def to_marshmallow(self): dict_params = self.schema",
"following format: \"object_name\": {\"type\":\"array\", \"items\":{format_of_items}} The schema_dict object use the",
"self._get_element_dict(schema_dict=schema_dict, item=item) self._create_data_schema( schema_dict=schema_dict, item=item, required_list=jsonschema.get(\"required\"), ) self.schema = schema_dict",
"name is \"values\" and n is 3: Values3Schema) :param name:",
"of names corresponding to the required fields in the parent",
"the schema and the value contains its content. return the",
"required list or empty list. \"\"\" return content.get(\"required\", []) def",
"exist. :content: the dict which should have a \"required\" key.value",
"or array. The schema name use the following format: [name][n]Schema",
"item=item) if \"properties\" in jsonschema: for item in jsonschema[\"properties\"].items(): self._get_element_dict(schema_dict=schema_dict,",
"\"many\": True, \"required\": (name in required_list), } else: return self._get_field_dict(item,",
"[ self._get_element_dict( schema_dict=schema_dict, item=i, required_list=self._get_required(content), ) for i in content[\"properties\"].items()",
"item, required_list=None): \"\"\" Add a schema to schema_dict[DATASCHEMA] :param item:",
"dictionary schema :param jsonschema: a json schema \"\"\" self.types =",
"and return it. This is used for items that will",
"\"object\": return self._get_schema_name(name) elif content[\"type\"] == \"array\": return self._get_type_or_new_schema((name, content[\"items\"]))",
"in content and content[\"type\"] == \"object\": schema_dict.update( { schema_name: [",
"if required_list is None: required_list = [] schema = dict(",
":content: the dict which should have a \"required\" key.value :return:",
"from the jsonschema (key, value) :param required_list: A list of",
"item=i, required_list=self._get_required(content), ) for i in content[\"properties\"].items() ] } )",
"required_list: A list of names corresponding to the required fields",
"corresponding dict. :param item: An item from the jsonschema (key,",
"is: (\"object_name\", {\"type\":\"object\", \"properties\":{\"a\": {...}, \"b\": {...}}) :return: The schema",
"content. return the schema dict. \"\"\" name, content = item",
"n=0): \"\"\" Transform an element name into a schema name",
"ParameterSchema, sort_dict from cornflow_client.constants import JSON_TYPES, DATASCHEMA class DictSchema: \"\"\"",
"} else: return self._get_field_dict(item, required_list) def _get_object_schema(self, schema_dict, item): \"\"\"",
"i in json_type if i != \"null\"] if len(not_null_type) >",
"self._get_type(content[\"type\"]) def _get_type(self, json_type): \"\"\" Translate the type between jsonschema",
"\"type\": self._get_array_schema(schema_dict=schema_dict, item=item), \"many\": True, \"required\": (name in required_list), }",
"_get_type(self, json_type): \"\"\" Translate the type between jsonschema and schema_dict.",
"jsonschema arrays are similar to python lists. The object in",
"\"\"\" content = item[1] ref = re.search(\"definitions/(.+)\", content[\"$ref\"]).group(1) return self._get_schema_name(ref)",
"dict which should have a \"required\" key.value :return: The required",
"_get_field_dict(self, item, required_list=None): \"\"\" Transform a \"normal\" item from the",
"dict \"\"\" return {DATASCHEMA: []} def _create_data_schema(self, schema_dict, item, required_list=None):",
"parsed first and corresponding schema are created so a schema",
"get_schema(self): return self.schema @staticmethod def get_empty_schema(): \"\"\" Create un empty",
"required_list=self._get_required(content), ) for i in content[\"properties\"].items() ] } ) elif",
"re from .dict_functions import gen_schema, ParameterSchema, sort_dict from cornflow_client.constants import",
"self._get_object_schema(schema_dict=schema_dict, item=item), \"many\": False, \"required\": (name in required_list), } elif",
"the list of parameters: params1 = schema.load(params, many=True) result_dict[key] =",
"Transform an element name into a schema name in order",
"a schema should exist corresponding to the reference. :param item:",
"into fields. :param item: The jsonschema item in format (key,",
"in jsonschema[\"definitions\"].items(): self._get_element_dict(schema_dict=schema_dict, item=item) if \"properties\" in jsonschema: for item",
"in content: if \"$ref\" in content: return { \"name\": name,",
"the dict which should have a \"required\" key.value :return: The",
"required_list), allow_none=(\"null\" in item[1][\"type\"]), many=False, ) return d def _get_ref(self,",
"Translate the type between jsonschema and schema_dict. :param json_type: the",
") else: return try_name @staticmethod def _get_required(content): \"\"\" Get the",
"an object item from the jsonschema in a dict for",
"(\"object_name\", {\"type\":\"object\", \"properties\":{\"a\": {...}, \"b\": {...}}) :return: The schema name",
"(for example if name is \"values\" and n is 3:",
"content = item if \"type\" not in content or content[\"type\"]",
"one type given\") return self.types[not_null_type[0]] else: return self.types[json_type] @staticmethod def",
"in content[\"properties\"].items() ] } schema_dict.update(ell) return schema_name def _get_array_schema(self, schema_dict,",
"self.schema_dict. In jsonschema objects are similar to python dict. The",
"name \"\"\" name, content = item schema_name = self._get_new_schema_name(schema_dict=schema_dict, name=name)",
"or array. :param n: if n is different from 0,",
"\"$ref\" in content: schema_name = self._get_ref((None, content)) elif \"type\" in",
":return: the corresponding schema name. \"\"\" if n == 0:",
"jsonschema item in format (key, value) :param required_list: a list",
"self.get_empty_schema() if \"definitions\" in jsonschema: for item in jsonschema[\"definitions\"].items(): self._get_element_dict(schema_dict=schema_dict,",
"internal dictionary schema :param jsonschema: a json schema \"\"\" self.types",
"not in content or content[\"type\"] == \"object\": return self._get_schema_name(name) elif",
"is in the following format: \"object_name\": {\"type\":\"array\", \"items\":{format_of_items}} The schema_dict",
"name (_get_schema_name(object_name)) \"\"\" content = item[1] ref = re.search(\"definitions/(.+)\", content[\"$ref\"]).group(1)",
"Class to manage internal dictionary schema :param jsonschema: a json",
"item if \"type\" not in content: if \"$ref\" in content:",
"the reference. :param item: The jsonschema item in format (key,",
"0: return name.capitalize() + \"Schema\" else: return name.capitalize() + str(n)",
"the list of required name of it exist. :content: the",
"dict element for a schema_dict. \"\"\" if required_list is None:",
"\"object\": schema_dict.update( { schema_name: [ self._get_element_dict( schema_dict=schema_dict, item=i, required_list=self._get_required(content), )",
"\"values\" and n is 3: Values3Schema) :param name: The name",
"\"type\" in content and content[\"type\"] == \"object\": schema_dict.update( { schema_name:",
"self._get_element_dict( schema_dict=schema_dict, item=i, required_list=self._get_required(content), ) for i in content.items() ]",
"json_type): \"\"\" Translate the type between jsonschema and schema_dict. :param",
"def _get_required(content): \"\"\" Get the list of required name of",
"0, it is added to the schema name. :return: the",
"content = item if required_list is None: required_list = []",
"object use the format: {\"schema_name\": [{\"name\":\"field1\", \"type\": \"field1_type\", \"many\": False,",
"_get_array_schema(self, schema_dict, item): \"\"\" Transform a array item from the",
"{\"schema_name\": [{\"name\":\"field1\", \"type\": \"field1_type\", \"many\": False, \"required\":(True or False)}, ...]",
"\"name\": name, \"type\": self._get_ref(item), \"many\": False, \"required\": (name in required_list),",
"schema should exist corresponding to the reference. :param item: The",
"from the jsonschema and return the corresponding dict. :param item:",
"of the schema for a jsonschema reference. jsonschema definitions are",
"array. The schema name use the following format: [name][n]Schema (for",
"schema_dict=schema_dict, item=i, required_list=self._get_required(content), ) for i in content[\"properties\"].items() ] }",
"= ParameterSchema() # this line validates the list of parameters:",
"into a schema name in order to create a schema",
"= self._get_ref((None, content)) elif \"type\" in content and content[\"type\"] !=",
"else: return name.capitalize() + str(n) + \"Schema\" def _get_new_schema_name(self, schema_dict,",
"dict. The key contains the name of the schema and",
"return { \"name\": name, \"type\": self._get_array_schema(schema_dict=schema_dict, item=item), \"many\": True, \"required\":",
"\"\"\" name, content = item content = content[\"items\"] schema_name =",
"json_type: the type in jsonschema :return: the type in schema_dict.",
"and content[\"type\"] == \"object\": schema_dict.update( { schema_name: [ self._get_element_dict( schema_dict=schema_dict,",
"corresponding schema name. \"\"\" if n == 0: return name.capitalize()",
"tuplist = sorted(dict_params.items(), key=lambda v: ordered[v[0]]) for key, params in",
"of parameters: params1 = schema.load(params, many=True) result_dict[key] = gen_schema(key, params1,",
"jsonschema definitions are parsed first and corresponding schema are created",
"schema name. :return: the corresponding schema name. \"\"\" if n",
"schema = dict( name=name, type=self._get_type_or_new_schema(item), many=(\"type\" in content and content[\"type\"]",
"the schema for a jsonschema reference. jsonschema definitions are parsed",
"\"\"\" A json-schema to dict-schema parser \"\"\" def __init__(self, jsonschema):",
"\"type\" in content and content[\"type\"] != \"array\": return self._get_type(content[\"type\"]) else:",
"False, \"required\":(True or False)}, ...] :param item: The jsonschema item",
"name. :return: the corresponding schema name. \"\"\" if n ==",
"\"array\": return self._get_type(content[\"type\"]) else: schema_dict.update( { schema_name: [ self._get_element_dict( schema_dict=schema_dict,",
"value) of a dict. The key contains the name of",
"use the format: {\"schema_name\": [{\"name\":\"field1\", \"type\": \"field1_type\", \"many\": False, \"required\":(True",
"parameters: params1 = schema.load(params, many=True) result_dict[key] = gen_schema(key, params1, result_dict)",
"the parent object :return A dict element for a schema_dict.",
"the jsonschema and return the corresponding dict. :param item: An",
"in jsonschema is in the following format: \"object_name\": {\"type\":\"object\", \"properties\":{\"field1\":",
"name into a schema name in order to create a",
"False) :param item: The jsonschema item (key, value) The format",
"_get_new_schema_name(self, schema_dict, name, n=0): try_name = self._get_schema_name(name, n) if try_name",
"be in the following format: {\"$ref\": \"#/definitions/object_name\"} :return The schema",
"format (key, value) :param required_list: a list of the fields",
"jsonschema is in the following format: \"object_name\": {\"type\":\"object\", \"properties\":{\"field1\": {...},",
"for item: {}\".format(name)) raise TypeError(\"Type missing\") if content[\"type\"] == \"object\":",
"in the following format: \"object_name\": {\"type\":\"array\", \"items\":{format_of_items}} The schema_dict object",
"or False) :param item: The jsonschema item (key, value) The",
"try_name in schema_dict: return self._get_new_schema_name( schema_dict=schema_dict, name=name, n=n + 1",
"\"type\": \"field1_type\", \"many\": False, \"required\":(True or False) :param item: The",
"\"type\": self._get_object_schema(schema_dict=schema_dict, item=item), \"many\": False, \"required\": (name in required_list), }",
"jsonschema: for item in jsonschema[\"properties\"].items(): self._get_element_dict(schema_dict=schema_dict, item=item) self._create_data_schema( schema_dict=schema_dict, item=item,",
"content: return { \"name\": name, \"type\": self._get_ref(item), \"many\": False, \"required\":",
"item: The jsonschema item in format (key, value) The value",
"the following format: {\"$ref\": \"#/definitions/object_name\"} :return The schema name (_get_schema_name(object_name))",
"given\") return self.types[not_null_type[0]] else: return self.types[json_type] @staticmethod def _get_schema_name(name, n=0):",
"if i != \"null\"] if len(not_null_type) > 1: raise Warning(\"Warning:",
"new schema or a type depending on the json_type \"\"\"",
"= schema_dict def get_schema(self): return self.schema @staticmethod def get_empty_schema(): \"\"\"",
"for this item \"\"\" d = dict( name=item[0], type=self._get_type(item[1][\"type\"]), required=(item[0]",
"\"#/definitions/object_name\"} :return The schema name (_get_schema_name(object_name)) \"\"\" content = item[1]",
"parent object :return A dict element for a schema_dict. \"\"\"",
"= item if \"type\" not in content: if \"$ref\" in",
"name, n=0): try_name = self._get_schema_name(name, n) if try_name in schema_dict:",
"a \"required\" key.value :return: The required list or empty list.",
"a array item from the jsonschema in a dict for",
"for items that will directly translate into fields. :param item:",
"to create a schema corresponding to an object or array.",
"content.get(\"required\", []) def to_marshmallow(self): dict_params = self.schema result_dict = {}",
":param item: The jsonschema item in format (key, value) The",
"+ \"Schema\" else: return name.capitalize() + str(n) + \"Schema\" def",
"[{\"name\":\"field1\", \"type\": \"field1_type\", \"many\": False, \"required\":(True or False) :param item:",
"if len(not_null_type) > 1: raise Warning(\"Warning: more than one type",
"required_list), } elif content[\"type\"] == \"array\": return { \"name\": name,",
"\"\"\" Translate the type between jsonschema and schema_dict. :param json_type:",
"parser \"\"\" def __init__(self, jsonschema): \"\"\" Class to manage internal",
"[{\"name\":\"field1\", \"type\": \"field1_type\", \"many\": False, \"required\":(True or False)}, ...] :param",
"return { \"name\": name, \"type\": self._get_object_schema(schema_dict=schema_dict, item=item), \"many\": False, \"required\":",
"to schema_dict[DATASCHEMA] :param item: (key, value) of a dict. The",
"item): \"\"\" Transform an object item from the jsonschema in",
"schema_name: [ self._get_element_dict( schema_dict=schema_dict, item=i, required_list=self._get_required(content), ) for i in",
"item=item), \"many\": False, \"required\": (name in required_list), } elif content[\"type\"]",
"python dict. The object in jsonschema is in the following",
"self._get_type(content[\"type\"]) else: schema_dict.update( { schema_name: [ self._get_element_dict( schema_dict=schema_dict, item=i, required_list=self._get_required(content),",
"return try_name @staticmethod def _get_required(content): \"\"\" Get the list of",
"name, \"type\": self._get_array_schema(schema_dict=schema_dict, item=item), \"many\": True, \"required\": (name in required_list),",
"to python lists. The object in jsonschema is in the",
"item in format (key, value) :param required_list: a list of",
":return The schema name (_get_schema_name(object_name)) \"\"\" content = item[1] ref",
"\"\"\" Create un empty schema dict \"\"\" return {DATASCHEMA: []}",
"<filename>cornflow_client/schema/dictSchema.py<gh_stars>1-10 import re from .dict_functions import gen_schema, ParameterSchema, sort_dict from",
"= self._get_schema_name(name, n) if try_name in schema_dict: return self._get_new_schema_name( schema_dict=schema_dict,",
"\"\"\" name, content = item if \"type\" not in content",
"to_marshmallow(self): dict_params = self.schema result_dict = {} ordered = sort_dict(dict_params)",
"self.schema result_dict = {} ordered = sort_dict(dict_params) tuplist = sorted(dict_params.items(),",
"corresponding to the reference. :param item: The jsonschema item in",
"def _get_object_schema(self, schema_dict, item): \"\"\" Transform an object item from",
"schema_dict=schema_dict, item=item, required_list=jsonschema.get(\"required\"), ) self.schema = schema_dict def get_schema(self): return",
"self._get_element_dict(schema_dict=schema_dict, item=item) if \"properties\" in jsonschema: for item in jsonschema[\"properties\"].items():",
"(name in required_list), } else: print(\"\\nType missing for item: {}\".format(name))",
"_get_ref(self, item): \"\"\" Get the name of the schema for",
"\"required\":(True or False)}, ...] :param item: The jsonschema item (key,",
"translate into fields. :param item: The jsonschema item in format",
"are created so a schema should exist corresponding to the",
"in jsonschema[\"properties\"].items(): self._get_element_dict(schema_dict=schema_dict, item=item) self._create_data_schema( schema_dict=schema_dict, item=item, required_list=jsonschema.get(\"required\"), ) self.schema",
"json_type if i != \"null\"] if len(not_null_type) > 1: raise",
"type given\") return self.types[not_null_type[0]] else: return self.types[json_type] @staticmethod def _get_schema_name(name,",
"the json_type \"\"\" name, content = item if \"type\" not",
"schema \"\"\" self.types = JSON_TYPES schema_dict = self.get_empty_schema() if \"definitions\"",
"def _get_type(self, json_type): \"\"\" Translate the type between jsonschema and",
":return: the type in schema_dict. \"\"\" if type(json_type) is list:",
"list: not_null_type = [i for i in json_type if i",
"for item in jsonschema[\"definitions\"].items(): self._get_element_dict(schema_dict=schema_dict, item=item) if \"properties\" in jsonschema:",
"a schema to schema_dict[DATASCHEMA] :param item: (key, value) of a",
"i in content[\"properties\"].items() ] } schema_dict.update(ell) return schema_name def _get_array_schema(self,",
"content[\"properties\"].items() ] } ) elif \"$ref\" in content: schema_name =",
"a schema corresponding to an object or array. The schema",
"\"\"\" return content.get(\"required\", []) def to_marshmallow(self): dict_params = self.schema result_dict",
"item content = content[\"items\"] schema_name = self._get_new_schema_name(schema_dict=schema_dict, name=name) if \"type\"",
"exist corresponding to the reference. :param item: The jsonschema item",
"self.types = JSON_TYPES schema_dict = self.get_empty_schema() if \"definitions\" in jsonschema:",
"\"\"\" Add a schema to schema_dict[DATASCHEMA] :param item: (key, value)",
"params in tuplist: schema = ParameterSchema() # this line validates",
"elif content[\"type\"] == \"array\": return self._get_type_or_new_schema((name, content[\"items\"])) else: return self._get_type(content[\"type\"])",
"schema dict. \"\"\" name, content = item if required_list is",
"\"\"\" name, content = item if required_list is None: required_list",
"d def _get_ref(self, item): \"\"\" Get the name of the",
"{\"$ref\": \"#/definitions/object_name\"} :return The schema name (_get_schema_name(object_name)) \"\"\" content =",
"= self.schema result_dict = {} ordered = sort_dict(dict_params) tuplist =",
"the following format: [name][n]Schema (for example if name is \"values\"",
"] } ) return schema_name def _get_field_dict(self, item, required_list=None): \"\"\"",
"{\"type\":\"object\", \"properties\":{\"a\": {...}, \"b\": {...}}) :return: The schema name \"\"\"",
"== \"object\": return self._get_schema_name(name) elif content[\"type\"] == \"array\": return self._get_type_or_new_schema((name,",
"import JSON_TYPES, DATASCHEMA class DictSchema: \"\"\" A json-schema to dict-schema",
"= [] name, content = item if \"type\" not in",
"is in the following format: \"object_name\": {\"type\":\"object\", \"properties\":{\"field1\": {...}, \"filed2\":",
"self.schema @staticmethod def get_empty_schema(): \"\"\" Create un empty schema dict",
"self._get_ref(item), \"many\": False, \"required\": (name in required_list), } else: print(\"\\nType",
"ell = { schema_name: [ self._get_element_dict( schema_dict=schema_dict, item=i, required_list=self._get_required(content), )",
"False)}, ...] :param item: The jsonschema item (key, value) The",
"jsonschema item in format (key, value) The value should be",
"return d def _get_ref(self, item): \"\"\" Get the name of",
"should be in the following format: {\"$ref\": \"#/definitions/object_name\"} :return The",
"content: if \"$ref\" in content: return { \"name\": name, \"type\":",
"object or array. :param n: if n is different from",
"required in the parent object. :return: the schema_dict for this",
"json-schema to dict-schema parser \"\"\" def __init__(self, jsonschema): \"\"\" Class",
"[\"field1]} The schema_dict object use the format: {\"schema_name\": [{\"name\":\"field1\", \"type\":",
"self._get_new_schema_name(schema_dict=schema_dict, name=name) ell = { schema_name: [ self._get_element_dict( schema_dict=schema_dict, item=i,",
"False, \"required\":(True or False) :param item: The jsonschema item (key,",
"Warning(\"Warning: more than one type given\") return self.types[not_null_type[0]] else: return",
"class DictSchema: \"\"\" A json-schema to dict-schema parser \"\"\" def",
"lists. The object in jsonschema is in the following format:",
"or empty list. \"\"\" return content.get(\"required\", []) def to_marshmallow(self): dict_params",
"In jsonschema objects are similar to python dict. The object",
"{...}}, \"required\": [\"field1]} The schema_dict object use the format: {\"schema_name\":",
"self._get_schema_name(ref) def _get_type_or_new_schema(self, item): \"\"\" returns a new schema or",
"import re from .dict_functions import gen_schema, ParameterSchema, sort_dict from cornflow_client.constants",
"item: (key, value) of a dict. The key contains the",
"{ \"name\": name, \"type\": self._get_ref(item), \"many\": False, \"required\": (name in",
"schema_dict[DATASCHEMA] :param item: (key, value) of a dict. The key",
"False, \"required\": (name in required_list), } else: print(\"\\nType missing for",
":param item: An item from the jsonschema (key, value) :param",
"is different from 0, it is added to the schema",
"\"many\": False, \"required\": (name in required_list), } else: print(\"\\nType missing",
"which should have a \"required\" key.value :return: The required list",
"reference. :param item: The jsonschema item in format (key, value)",
"content.items() ] } ) return schema_name def _get_field_dict(self, item, required_list=None):",
"!= \"null\"] if len(not_null_type) > 1: raise Warning(\"Warning: more than",
"item=i, required_list=self._get_required(content), ) for i in content[\"properties\"].items() ] } schema_dict.update(ell)",
"\"required\": (name in required_list), } else: print(\"\\nType missing for item:",
"JSON_TYPES schema_dict = self.get_empty_schema() if \"definitions\" in jsonschema: for item",
"dict for the schema_dict and update self.schema_dict. In jsonschema objects",
"ordered[v[0]]) for key, params in tuplist: schema = ParameterSchema() #",
"= JSON_TYPES schema_dict = self.get_empty_schema() if \"definitions\" in jsonschema: for",
"= re.search(\"definitions/(.+)\", content[\"$ref\"]).group(1) return self._get_schema_name(ref) def _get_type_or_new_schema(self, item): \"\"\" returns",
"are similar to python lists. The object in jsonschema is",
"The schema name use the following format: [name][n]Schema (for example",
"dict. The object in jsonschema is in the following format:",
"\"\"\" Transform an element name into a schema name in",
"= self._get_new_schema_name(schema_dict=schema_dict, name=name) if \"type\" in content and content[\"type\"] ==",
"== \"array\"), required=name in required_list, ) schema_dict[DATASCHEMA].append(schema) return schema def",
"\"\"\" if required_list is None: required_list = [] name, content",
"of it exist. :content: the dict which should have a",
"if \"type\" in content and content[\"type\"] == \"object\": schema_dict.update( {",
"re.search(\"definitions/(.+)\", content[\"$ref\"]).group(1) return self._get_schema_name(ref) def _get_type_or_new_schema(self, item): \"\"\" returns a",
"\"array\": return self._get_type_or_new_schema((name, content[\"items\"])) else: return self._get_type(content[\"type\"]) def _get_type(self, json_type):",
"or False)}, ...] :param item: The jsonschema item (key, value)",
"create a schema corresponding to an object or array. The",
"tuplist: schema = ParameterSchema() # this line validates the list",
"in content: schema_name = self._get_ref((None, content)) elif \"type\" in content",
"schema_dict: return self._get_new_schema_name( schema_dict=schema_dict, name=name, n=n + 1 ) else:",
"n: if n is different from 0, it is added",
"and content[\"type\"] == \"array\"), required=name in required_list, ) schema_dict[DATASCHEMA].append(schema) return",
"\"many\": False, \"required\": (name in required_list), } elif content[\"type\"] ==",
"\"required\":(True or False) :param item: The jsonschema item (key, value)",
"schema are created so a schema should exist corresponding to",
"return name.capitalize() + str(n) + \"Schema\" def _get_new_schema_name(self, schema_dict, name,",
"is 3: Values3Schema) :param name: The name of the object",
"else: return self.types[json_type] @staticmethod def _get_schema_name(name, n=0): \"\"\" Transform an",
"not_null_type = [i for i in json_type if i !=",
"item is: (\"object_name\", {\"type\":\"object\", \"properties\":{\"a\": {...}, \"b\": {...}}) :return: The",
"its content. return the schema dict. \"\"\" name, content =",
"schema = ParameterSchema() # this line validates the list of",
"None: required_list = [] schema = dict( name=name, type=self._get_type_or_new_schema(item), many=(\"type\"",
"schema_dict. \"\"\" if type(json_type) is list: not_null_type = [i for",
"Transform an object item from the jsonschema in a dict",
"jsonschema and schema_dict. :param json_type: the type in jsonschema :return:",
"to python dict. The object in jsonschema is in the",
"\"\"\" Get the name of the schema for a jsonschema",
"The schema name \"\"\" name, content = item content =",
"in content or content[\"type\"] == \"object\": return self._get_schema_name(name) elif content[\"type\"]",
"content = item content = content[\"items\"] schema_name = self._get_new_schema_name(schema_dict=schema_dict, name=name)",
"i != \"null\"] if len(not_null_type) > 1: raise Warning(\"Warning: more",
"dict. :param item: An item from the jsonschema (key, value)",
"name \"\"\" name, content = item content = content[\"items\"] schema_name",
") for i in content[\"properties\"].items() ] } ) elif \"$ref\"",
"name, content = item if \"type\" not in content or",
"!= \"array\": return self._get_type(content[\"type\"]) else: schema_dict.update( { schema_name: [ self._get_element_dict(",
"type=self._get_type_or_new_schema(item), many=(\"type\" in content and content[\"type\"] == \"array\"), required=name in",
"element for a schema_dict. \"\"\" if required_list is None: required_list",
":return: the schema_dict for this item \"\"\" d = dict(",
"= item if \"type\" not in content or content[\"type\"] ==",
"in the following format: {\"$ref\": \"#/definitions/object_name\"} :return The schema name",
"the schema name. :return: the corresponding schema name. \"\"\" if",
"the schema_dict for this item \"\"\" d = dict( name=item[0],",
"cornflow_client.constants import JSON_TYPES, DATASCHEMA class DictSchema: \"\"\" A json-schema to",
"jsonschema): \"\"\" Class to manage internal dictionary schema :param jsonschema:",
"== \"object\": schema_dict.update( { schema_name: [ self._get_element_dict( schema_dict=schema_dict, item=i, required_list=self._get_required(content),",
"else: return self._get_type(content[\"type\"]) def _get_type(self, json_type): \"\"\" Translate the type",
"self._get_array_schema(schema_dict=schema_dict, item=item), \"many\": True, \"required\": (name in required_list), } else:",
"empty schema dict \"\"\" return {DATASCHEMA: []} def _create_data_schema(self, schema_dict,",
"for a jsonschema reference. jsonschema definitions are parsed first and",
"object in jsonschema is in the following format: \"object_name\": {\"type\":\"object\",",
"name=item[0], type=self._get_type(item[1][\"type\"]), required=(item[0] in required_list), allow_none=(\"null\" in item[1][\"type\"]), many=False, )",
"1 ) else: return try_name @staticmethod def _get_required(content): \"\"\" Get",
"content[\"items\"])) else: return self._get_type(content[\"type\"]) def _get_type(self, json_type): \"\"\" Translate the",
"the schema dict. \"\"\" name, content = item if required_list",
"jsonschema: for item in jsonschema[\"definitions\"].items(): self._get_element_dict(schema_dict=schema_dict, item=item) if \"properties\" in",
"(name in required_list), } else: return self._get_field_dict(item, required_list) def _get_object_schema(self,",
"an item (key, value) from the jsonschema and return the",
"= item if required_list is None: required_list = [] schema",
"schema name \"\"\" name, content = item schema_name = self._get_new_schema_name(schema_dict=schema_dict,"
] |
[
"as rf dir_ends_with_abc = rf.directory_pattern_predicate(\"abc$\") assert dir_ends_with_abc(\"/foo/bar/folder_abc/my_resource.txt\") assert not dir_ends_with_abc(\"/foo/bar/folder_def/my_resource.txt\")",
"assert dir_ends_with_abc(\"/foo/bar/folder_abc/my_resource.txt\") assert not dir_ends_with_abc(\"/foo/bar/folder_def/my_resource.txt\") xml_file = rf.filename_pattern_predicate(\".xml$\") assert xml_file(\"my_resource.xml\")",
"test_directory_pattern_filter_windows(self): dpf = rf.directory_pattern_predicate(\"abc\") self.assertTrue(dpf(\"foo/babcd/bar/some.txt\")) self.assertTrue(dpf(\"/abc/bar/some.txt\")) self.assertTrue(dpf(\"/foo/bar/abc/some.txt\")) self.assertTrue(dpf(\"foo\\\\babcd\\\\bar\\\\some.txt\")) self.assertTrue(dpf(\"c:\\\\abc\\\\bar\\\\some.txt\")) self.assertTrue(dpf(\"c:\\\\foo\\\\bar\\\\abc\\\\some.txt\"))",
"not xml_file(\"my_resource.txt\") import rspub.util.gates as lf xml_files_in_abc = lf.and_(dir_ends_with_abc, xml_file)",
"rspub.util.gates as lf xml_files_in_abc = lf.and_(dir_ends_with_abc, xml_file) assert xml_files_in_abc(\"/foo/bar/folder_abc/my_resource.xml\") assert",
"xml_file = rf.filename_pattern_predicate(\".xml$\") assert xml_file(\"my_resource.xml\") assert not xml_file(\"my_resource.txt\") import rspub.util.gates",
"dpf = rf.directory_pattern_predicate(\"^c:\\\\abc\") self.assertTrue(dpf(\"c:\\\\abc\\\\bar\\\\some.txt\")) # self.assertFalse(dpf(\"abc\\\\bar\\\\some.txt\")) dpf = rf.directory_pattern_predicate(\"abc$\") self.assertTrue(dpf(\"foo/bar/abc/some.txt\"))",
"\"Only tested on Windows.\") def test_windows_to_unix(self): path = os.path.expanduser(\"~\") dpf",
"self.assertFalse(dpf(\"abc\\\\abc\\\\bar\\\\abc.abc\")) def test_last_modified_filter(self): file_name = os.path.realpath(__file__) lmaf = rf.last_modified_after_predicate() self.assertTrue(lmaf(file_name))",
"self.assertTrue(dpf(\"\")) self.assertTrue(dpf(\".\")) self.assertTrue(dpf(\"\\n\")) self.assertTrue(dpf(\"foo\")) # rejects not string self.assertFalse(dpf(None)) self.assertFalse(dpf(42))",
"assert xml_files_in_abc(\"/foo/bar/folder_abc/my_resource.xml\") assert not xml_files_in_abc(\"/foo/bar/folder_abc/my_resource.txt\") assert not xml_files_in_abc(\"/foo/bar/folder_def/my_resource.xml\") recent =",
"not xml_files_in_abc(\"/foo/bar/folder_def/my_resource.xml\") recent = rf.last_modified_after_predicate(\"2016-08-01\") includes = [xml_files_in_abc] excludes =",
"as lf xml_files_in_abc = lf.and_(dir_ends_with_abc, xml_file) assert xml_files_in_abc(\"/foo/bar/folder_abc/my_resource.xml\") assert not",
"= rf.directory_pattern_predicate(\"abc\") self.assertTrue(dpf(\"foo/babcd/bar/some.txt\")) self.assertTrue(dpf(\"/abc/bar/some.txt\")) self.assertTrue(dpf(\"/foo/bar/abc/some.txt\")) self.assertTrue(dpf(\"foo\\\\babcd\\\\bar\\\\some.txt\")) self.assertTrue(dpf(\"c:\\\\abc\\\\bar\\\\some.txt\")) self.assertTrue(dpf(\"c:\\\\foo\\\\bar\\\\abc\\\\some.txt\")) # self.assertFalse(dpf(\"/foo/bar/baz/abc.txt\"))",
"xml_file(\"my_resource.xml\") assert not xml_file(\"my_resource.txt\") import rspub.util.gates as lf xml_files_in_abc =",
"dpf = rf.directory_pattern_predicate(\"^\" + path) self.assertTrue(dpf(os.path.join(path, \"bla\"))) dpf = rf.directory_pattern_predicate(\"^C:\\\\Users\")",
"not xml_files_in_abc(\"c:\\\\foo\\\\bar\\\\folder_abc\\\\my_resource.txt\") assert not xml_files_in_abc(\"c:\\\\foo\\\\bar\\\\folder_def\\\\my_resource.xml\") recent = rf.last_modified_after_predicate(\"2016-08-01\") includes =",
"self.assertFalse(dpf(None)) self.assertFalse(dpf(42)) self.assertFalse(dpf(self)) def test_directory_pattern_filter(self): dpf = rf.directory_pattern_predicate(\"abc\") self.assertTrue(dpf(\"foo/babcd/bar/some.txt\")) self.assertTrue(dpf(\"/abc/bar/some.txt\"))",
"# print(type(resource_gate)) @unittest.skipUnless(on_windows(), \"Only tested on Windows.\") def test_windows_to_unix(self): path",
"Windows.\") def test_example_windows(self): import rspub.util.resourcefilter as rf dir_ends_with_abc = rf.directory_pattern_predicate(\"abc$\")",
"@unittest.skipUnless(on_windows(), \"Only tested on Windows.\") def test_windows_to_unix(self): path = os.path.expanduser(\"~\")",
"self.assertFalse(dpf(\"abc/abc/bar/some.txt\")) self.assertFalse(dpf(\"abc/abc/bar/abc.abc\")) @unittest.skipUnless(on_windows(), \"Only tested on Windows.\") def test_directory_pattern_filter_windows(self): dpf",
"= platform.system() return opsys == \"Windows\" class TestPredicates(unittest.TestCase): def test_directory_pattern_filter_empty(self):",
"self.assertTrue(dpf(\"c:\\\\foo\\\\bar\\\\abc\\\\some.txt\")) # self.assertFalse(dpf(\"/foo/bar/baz/abc.txt\")) self.assertFalse(dpf(\"c:\\\\foo\\\\bar\\\\baz\\\\abc.txt\")) # ## dpf = rf.directory_pattern_predicate(\"^/abc\") self.assertTrue(dpf(\"/abc/bar/some.txt\"))",
"def test_directory_pattern_filter_windows(self): dpf = rf.directory_pattern_predicate(\"abc\") self.assertTrue(dpf(\"foo/babcd/bar/some.txt\")) self.assertTrue(dpf(\"/abc/bar/some.txt\")) self.assertTrue(dpf(\"/foo/bar/abc/some.txt\")) self.assertTrue(dpf(\"foo\\\\babcd\\\\bar\\\\some.txt\")) self.assertTrue(dpf(\"c:\\\\abc\\\\bar\\\\some.txt\"))",
"# print(type(resource_gate)) @unittest.skipUnless(on_windows(), \"Only tested on Windows.\") def test_example_windows(self): import",
"\"Only tested on Windows.\") def test_directory_pattern_filter_windows(self): dpf = rf.directory_pattern_predicate(\"abc\") self.assertTrue(dpf(\"foo/babcd/bar/some.txt\"))",
"lf.gate(includes, excludes) # print(type(resource_gate)) @unittest.skipUnless(on_windows(), \"Only tested on Windows.\") def",
"test_directory_pattern_filter_empty(self): dpf = rf.directory_pattern_predicate() # should pass all strings self.assertTrue(dpf(\"\"))",
"lmaf = rf.last_modified_after_predicate() self.assertTrue(lmaf(file_name)) lmaf = rf.last_modified_after_predicate(3000000000) # valid until",
"lf xml_files_in_abc = lf.and_(dir_ends_with_abc, xml_file) assert xml_files_in_abc(\"/foo/bar/folder_abc/my_resource.xml\") assert not xml_files_in_abc(\"/foo/bar/folder_abc/my_resource.txt\")",
"-*- import os import platform import unittest import rspub.util.resourcefilter as",
"# should pass all strings self.assertTrue(dpf(\"\")) self.assertTrue(dpf(\".\")) self.assertTrue(dpf(\"\\n\")) self.assertTrue(dpf(\"foo\")) #",
"as rf def on_windows(): opsys = platform.system() return opsys ==",
"self.assertTrue(dpf(\"/abc/bar/some.txt\")) self.assertTrue(dpf(\"/foo/bar/abc/some.txt\")) # self.assertFalse(dpf(\"/foo/bar/baz/abc.txt\")) # ## dpf = rf.directory_pattern_predicate(\"^/abc\") self.assertTrue(dpf(\"/abc/bar/some.txt\"))",
"import os import platform import unittest import rspub.util.resourcefilter as rf",
"rf.filename_pattern_predicate(\".xml$\") assert xml_file(\"my_resource.xml\") assert not xml_file(\"my_resource.txt\") import rspub.util.gates as lf",
"class TestPredicates(unittest.TestCase): def test_directory_pattern_filter_empty(self): dpf = rf.directory_pattern_predicate() # should pass",
"self.assertFalse(dpf(\"/foo/bar/baz/abc.txt\")) self.assertFalse(dpf(\"c:\\\\foo\\\\bar\\\\baz\\\\abc.txt\")) # ## dpf = rf.directory_pattern_predicate(\"^/abc\") self.assertTrue(dpf(\"/abc/bar/some.txt\")) # self.assertFalse(dpf(\"abc/bar/some.txt\"))",
"print(type(resource_gate)) @unittest.skipUnless(on_windows(), \"Only tested on Windows.\") def test_example_windows(self): import rspub.util.resourcefilter",
"dpf = rf.directory_pattern_predicate(\"abc\") self.assertTrue(dpf(\"foo/babcd/bar/some.txt\")) self.assertTrue(dpf(\"/abc/bar/some.txt\")) self.assertTrue(dpf(\"/foo/bar/abc/some.txt\")) # self.assertFalse(dpf(\"/foo/bar/baz/abc.txt\")) # ##",
"# # dpf = rf.directory_pattern_predicate(\"abc$\") self.assertTrue(dpf(\"foo/bar/abc/some.txt\")) # self.assertFalse(dpf(\"abc/abc/bar/some.txt\")) self.assertFalse(dpf(\"abc/abc/bar/abc.abc\")) @unittest.skipUnless(on_windows(),",
"# dpf = rf.directory_pattern_predicate(\"abc$\") self.assertTrue(dpf(\"foo/bar/abc/some.txt\")) # self.assertFalse(dpf(\"abc/abc/bar/some.txt\")) self.assertFalse(dpf(\"abc/abc/bar/abc.abc\")) @unittest.skipUnless(on_windows(), \"Only",
"= rf.last_modified_after_predicate(\"2016-08-01\") self.assertTrue(lmaf(file_name)) def test_example(self): import rspub.util.resourcefilter as rf dir_ends_with_abc",
"dir_ends_with_abc = rf.directory_pattern_predicate(\"abc$\") assert dir_ends_with_abc(\"/foo/bar/folder_abc/my_resource.txt\") assert not dir_ends_with_abc(\"/foo/bar/folder_def/my_resource.txt\") xml_file =",
"# self.assertFalse(dpf(\"abc/bar/some.txt\")) # # dpf = rf.directory_pattern_predicate(\"abc$\") self.assertTrue(dpf(\"foo/bar/abc/some.txt\")) # self.assertFalse(dpf(\"abc/abc/bar/some.txt\"))",
"assert xml_file(\"my_resource.xml\") assert not xml_file(\"my_resource.txt\") import rspub.util.gates as lf xml_files_in_abc",
"assert not xml_files_in_abc(\"c:\\\\foo\\\\bar\\\\folder_abc\\\\my_resource.txt\") assert not xml_files_in_abc(\"c:\\\\foo\\\\bar\\\\folder_def\\\\my_resource.xml\") recent = rf.last_modified_after_predicate(\"2016-08-01\") includes",
"xml_files_in_abc(\"c:\\\\foo\\\\bar\\\\folder_abc\\\\my_resource.txt\") assert not xml_files_in_abc(\"c:\\\\foo\\\\bar\\\\folder_def\\\\my_resource.xml\") recent = rf.last_modified_after_predicate(\"2016-08-01\") includes = [xml_files_in_abc]",
"rf.directory_pattern_predicate() # should pass all strings self.assertTrue(dpf(\"\")) self.assertTrue(dpf(\".\")) self.assertTrue(dpf(\"\\n\")) self.assertTrue(dpf(\"foo\"))",
"self.assertTrue(dpf(\"/abc/bar/some.txt\")) # self.assertFalse(dpf(\"abc/bar/some.txt\")) # # dpf = rf.directory_pattern_predicate(\"^c:\\\\abc\") self.assertTrue(dpf(\"c:\\\\abc\\\\bar\\\\some.txt\")) #",
"excludes = [recent] resource_gate = lf.gate(includes, excludes) # print(type(resource_gate)) @unittest.skipUnless(on_windows(),",
"print(type(resource_gate)) @unittest.skipUnless(on_windows(), \"Only tested on Windows.\") def test_windows_to_unix(self): path =",
"return opsys == \"Windows\" class TestPredicates(unittest.TestCase): def test_directory_pattern_filter_empty(self): dpf =",
"dpf = rf.directory_pattern_predicate() # should pass all strings self.assertTrue(dpf(\"\")) self.assertTrue(dpf(\".\"))",
"# # dpf = rf.directory_pattern_predicate(\"^c:\\\\abc\") self.assertTrue(dpf(\"c:\\\\abc\\\\bar\\\\some.txt\")) # self.assertFalse(dpf(\"abc\\\\bar\\\\some.txt\")) dpf =",
"def on_windows(): opsys = platform.system() return opsys == \"Windows\" class",
"rf.last_modified_after_predicate() self.assertTrue(lmaf(file_name)) lmaf = rf.last_modified_after_predicate(3000000000) # valid until 2065-01-24 06:20:00",
"rejects not string self.assertFalse(dpf(None)) self.assertFalse(dpf(42)) self.assertFalse(dpf(self)) def test_directory_pattern_filter(self): dpf =",
"self.assertFalse(dpf(\"abc/bar/some.txt\")) # # dpf = rf.directory_pattern_predicate(\"abc$\") self.assertTrue(dpf(\"foo/bar/abc/some.txt\")) # self.assertFalse(dpf(\"abc/abc/bar/some.txt\")) self.assertFalse(dpf(\"abc/abc/bar/abc.abc\"))",
"self.assertTrue(dpf(\"c:\\\\abc\\\\bar\\\\some.txt\")) self.assertTrue(dpf(\"c:\\\\foo\\\\bar\\\\abc\\\\some.txt\")) # self.assertFalse(dpf(\"/foo/bar/baz/abc.txt\")) self.assertFalse(dpf(\"c:\\\\foo\\\\bar\\\\baz\\\\abc.txt\")) # ## dpf = rf.directory_pattern_predicate(\"^/abc\")",
"rf.directory_pattern_predicate(\"^/abc\") self.assertTrue(dpf(\"/abc/bar/some.txt\")) # self.assertFalse(dpf(\"abc/bar/some.txt\")) # # dpf = rf.directory_pattern_predicate(\"^c:\\\\abc\") self.assertTrue(dpf(\"c:\\\\abc\\\\bar\\\\some.txt\"))",
"pass all strings self.assertTrue(dpf(\"\")) self.assertTrue(dpf(\".\")) self.assertTrue(dpf(\"\\n\")) self.assertTrue(dpf(\"foo\")) # rejects not",
"self.assertFalse(dpf(\"abc\\\\abc\\\\bar\\\\some.txt\")) self.assertFalse(dpf(\"abc/abc/bar/abc.abc\")) self.assertFalse(dpf(\"abc\\\\abc\\\\bar\\\\abc.abc\")) def test_last_modified_filter(self): file_name = os.path.realpath(__file__) lmaf =",
"import rspub.util.resourcefilter as rf dir_ends_with_abc = rf.directory_pattern_predicate(\"abc$\") assert dir_ends_with_abc(\"/foo/bar/folder_abc/my_resource.txt\") assert",
"= rf.directory_pattern_predicate(\"^\" + path) self.assertTrue(dpf(os.path.join(path, \"bla\"))) dpf = rf.directory_pattern_predicate(\"^C:\\\\Users\") self.assertTrue(dpf(os.path.join(path,",
"xml_files_in_abc(\"/foo/bar/folder_abc/my_resource.xml\") assert not xml_files_in_abc(\"/foo/bar/folder_abc/my_resource.txt\") assert not xml_files_in_abc(\"/foo/bar/folder_def/my_resource.xml\") assert xml_files_in_abc(\"c:\\\\foo\\\\bar\\\\folder_abc\\\\my_resource.xml\") assert",
"valid until 2065-01-24 06:20:00 self.assertFalse(lmaf(file_name)) lmaf = rf.last_modified_after_predicate(\"2016-08-01\") self.assertTrue(lmaf(file_name)) def",
"assert not dir_ends_with_abc(\"/foo/bar/folder_def/my_resource.txt\") xml_file = rf.filename_pattern_predicate(\".xml$\") assert xml_file(\"my_resource.xml\") assert not",
"rf.last_modified_after_predicate(\"2016-08-01\") includes = [xml_files_in_abc] excludes = [recent] resource_gate = lf.gate(includes,",
"import unittest import rspub.util.resourcefilter as rf def on_windows(): opsys =",
"lmaf = rf.last_modified_after_predicate(\"2016-08-01\") self.assertTrue(lmaf(file_name)) def test_example(self): import rspub.util.resourcefilter as rf",
"not xml_files_in_abc(\"/foo/bar/folder_abc/my_resource.txt\") assert not xml_files_in_abc(\"/foo/bar/folder_def/my_resource.xml\") recent = rf.last_modified_after_predicate(\"2016-08-01\") includes =",
"not xml_files_in_abc(\"/foo/bar/folder_def/my_resource.xml\") assert xml_files_in_abc(\"c:\\\\foo\\\\bar\\\\folder_abc\\\\my_resource.xml\") assert not xml_files_in_abc(\"c:\\\\foo\\\\bar\\\\folder_abc\\\\my_resource.txt\") assert not xml_files_in_abc(\"c:\\\\foo\\\\bar\\\\folder_def\\\\my_resource.xml\")",
"import platform import unittest import rspub.util.resourcefilter as rf def on_windows():",
"# self.assertFalse(dpf(\"abc/abc/bar/some.txt\")) self.assertFalse(dpf(\"abc/abc/bar/abc.abc\")) @unittest.skipUnless(on_windows(), \"Only tested on Windows.\") def test_directory_pattern_filter_windows(self):",
"xml_files_in_abc(\"c:\\\\foo\\\\bar\\\\folder_def\\\\my_resource.xml\") recent = rf.last_modified_after_predicate(\"2016-08-01\") includes = [xml_files_in_abc] excludes = [recent]",
"= [xml_files_in_abc] excludes = [recent] resource_gate = lf.gate(includes, excludes) #",
"import rspub.util.resourcefilter as rf def on_windows(): opsys = platform.system() return",
"# self.assertFalse(dpf(\"/foo/bar/baz/abc.txt\")) self.assertFalse(dpf(\"c:\\\\foo\\\\bar\\\\baz\\\\abc.txt\")) # ## dpf = rf.directory_pattern_predicate(\"^/abc\") self.assertTrue(dpf(\"/abc/bar/some.txt\")) #",
"= rf.last_modified_after_predicate() self.assertTrue(lmaf(file_name)) lmaf = rf.last_modified_after_predicate(3000000000) # valid until 2065-01-24",
"self.assertFalse(dpf(\"abc\\\\bar\\\\some.txt\")) dpf = rf.directory_pattern_predicate(\"abc$\") self.assertTrue(dpf(\"foo/bar/abc/some.txt\")) self.assertTrue(dpf(\"foo\\\\bar\\\\abc\\\\some.txt\")) # self.assertFalse(dpf(\"abc/abc/bar/some.txt\")) self.assertFalse(dpf(\"abc\\\\abc\\\\bar\\\\some.txt\")) self.assertFalse(dpf(\"abc/abc/bar/abc.abc\"))",
"def test_windows_to_unix(self): path = os.path.expanduser(\"~\") dpf = rf.directory_pattern_predicate(\"^\" + path)",
"# dpf = rf.directory_pattern_predicate(\"^c:\\\\abc\") self.assertTrue(dpf(\"c:\\\\abc\\\\bar\\\\some.txt\")) # self.assertFalse(dpf(\"abc\\\\bar\\\\some.txt\")) dpf = rf.directory_pattern_predicate(\"abc$\")",
"all strings self.assertTrue(dpf(\"\")) self.assertTrue(dpf(\".\")) self.assertTrue(dpf(\"\\n\")) self.assertTrue(dpf(\"foo\")) # rejects not string",
"self.assertTrue(dpf(\"\\n\")) self.assertTrue(dpf(\"foo\")) # rejects not string self.assertFalse(dpf(None)) self.assertFalse(dpf(42)) self.assertFalse(dpf(self)) def",
"dpf = rf.directory_pattern_predicate(\"abc$\") self.assertTrue(dpf(\"foo/bar/abc/some.txt\")) # self.assertFalse(dpf(\"abc/abc/bar/some.txt\")) self.assertFalse(dpf(\"abc/abc/bar/abc.abc\")) @unittest.skipUnless(on_windows(), \"Only tested",
"rf.directory_pattern_predicate(\"^c:\\\\abc\") self.assertTrue(dpf(\"c:\\\\abc\\\\bar\\\\some.txt\")) # self.assertFalse(dpf(\"abc\\\\bar\\\\some.txt\")) dpf = rf.directory_pattern_predicate(\"abc$\") self.assertTrue(dpf(\"foo/bar/abc/some.txt\")) self.assertTrue(dpf(\"foo\\\\bar\\\\abc\\\\some.txt\")) #",
"self.assertFalse(dpf(\"abc/abc/bar/some.txt\")) self.assertFalse(dpf(\"abc\\\\abc\\\\bar\\\\some.txt\")) self.assertFalse(dpf(\"abc/abc/bar/abc.abc\")) self.assertFalse(dpf(\"abc\\\\abc\\\\bar\\\\abc.abc\")) def test_last_modified_filter(self): file_name = os.path.realpath(__file__) lmaf",
"xml_file(\"my_resource.txt\") import rspub.util.gates as lf xml_files_in_abc = lf.and_(dir_ends_with_abc, xml_file) assert",
"platform.system() return opsys == \"Windows\" class TestPredicates(unittest.TestCase): def test_directory_pattern_filter_empty(self): dpf",
"test_last_modified_filter(self): file_name = os.path.realpath(__file__) lmaf = rf.last_modified_after_predicate() self.assertTrue(lmaf(file_name)) lmaf =",
"2065-01-24 06:20:00 self.assertFalse(lmaf(file_name)) lmaf = rf.last_modified_after_predicate(\"2016-08-01\") self.assertTrue(lmaf(file_name)) def test_example(self): import",
"= rf.directory_pattern_predicate(\"abc\") self.assertTrue(dpf(\"foo/babcd/bar/some.txt\")) self.assertTrue(dpf(\"/abc/bar/some.txt\")) self.assertTrue(dpf(\"/foo/bar/abc/some.txt\")) # self.assertFalse(dpf(\"/foo/bar/baz/abc.txt\")) # ## dpf",
"[recent] resource_gate = lf.gate(includes, excludes) # print(type(resource_gate)) @unittest.skipUnless(on_windows(), \"Only tested",
"# ## dpf = rf.directory_pattern_predicate(\"^/abc\") self.assertTrue(dpf(\"/abc/bar/some.txt\")) # self.assertFalse(dpf(\"abc/bar/some.txt\")) # #",
"/usr/bin/env python3 # -*- coding: utf-8 -*- import os import",
"opsys == \"Windows\" class TestPredicates(unittest.TestCase): def test_directory_pattern_filter_empty(self): dpf = rf.directory_pattern_predicate()",
"self.assertFalse(dpf(\"abc/abc/bar/abc.abc\")) self.assertFalse(dpf(\"abc\\\\abc\\\\bar\\\\abc.abc\")) def test_last_modified_filter(self): file_name = os.path.realpath(__file__) lmaf = rf.last_modified_after_predicate()",
"def test_example_windows(self): import rspub.util.resourcefilter as rf dir_ends_with_abc = rf.directory_pattern_predicate(\"abc$\") assert",
"# valid until 2065-01-24 06:20:00 self.assertFalse(lmaf(file_name)) lmaf = rf.last_modified_after_predicate(\"2016-08-01\") self.assertTrue(lmaf(file_name))",
"xml_files_in_abc = lf.and_(dir_ends_with_abc, xml_file) assert xml_files_in_abc(\"/foo/bar/folder_abc/my_resource.xml\") assert not xml_files_in_abc(\"/foo/bar/folder_abc/my_resource.txt\") assert",
"= rf.directory_pattern_predicate(\"abc$\") self.assertTrue(dpf(\"foo/bar/abc/some.txt\")) # self.assertFalse(dpf(\"abc/abc/bar/some.txt\")) self.assertFalse(dpf(\"abc/abc/bar/abc.abc\")) @unittest.skipUnless(on_windows(), \"Only tested on",
"test_windows_to_unix(self): path = os.path.expanduser(\"~\") dpf = rf.directory_pattern_predicate(\"^\" + path) self.assertTrue(dpf(os.path.join(path,",
"self.assertFalse(dpf(\"/foo/bar/baz/abc.txt\")) # ## dpf = rf.directory_pattern_predicate(\"^/abc\") self.assertTrue(dpf(\"/abc/bar/some.txt\")) # self.assertFalse(dpf(\"abc/bar/some.txt\")) #",
"excludes) # print(type(resource_gate)) @unittest.skipUnless(on_windows(), \"Only tested on Windows.\") def test_example_windows(self):",
"rf.directory_pattern_predicate(\"abc$\") self.assertTrue(dpf(\"foo/bar/abc/some.txt\")) # self.assertFalse(dpf(\"abc/abc/bar/some.txt\")) self.assertFalse(dpf(\"abc/abc/bar/abc.abc\")) @unittest.skipUnless(on_windows(), \"Only tested on Windows.\")",
"resource_gate = lf.gate(includes, excludes) # print(type(resource_gate)) @unittest.skipUnless(on_windows(), \"Only tested on",
"#! /usr/bin/env python3 # -*- coding: utf-8 -*- import os",
"def test_directory_pattern_filter_empty(self): dpf = rf.directory_pattern_predicate() # should pass all strings",
"dpf = rf.directory_pattern_predicate(\"^/abc\") self.assertTrue(dpf(\"/abc/bar/some.txt\")) # self.assertFalse(dpf(\"abc/bar/some.txt\")) # # dpf =",
"self.assertTrue(dpf(\"foo\\\\babcd\\\\bar\\\\some.txt\")) self.assertTrue(dpf(\"c:\\\\abc\\\\bar\\\\some.txt\")) self.assertTrue(dpf(\"c:\\\\foo\\\\bar\\\\abc\\\\some.txt\")) # self.assertFalse(dpf(\"/foo/bar/baz/abc.txt\")) self.assertFalse(dpf(\"c:\\\\foo\\\\bar\\\\baz\\\\abc.txt\")) # ## dpf =",
"should pass all strings self.assertTrue(dpf(\"\")) self.assertTrue(dpf(\".\")) self.assertTrue(dpf(\"\\n\")) self.assertTrue(dpf(\"foo\")) # rejects",
"self.assertTrue(dpf(\"/abc/bar/some.txt\")) # self.assertFalse(dpf(\"abc/bar/some.txt\")) # # dpf = rf.directory_pattern_predicate(\"abc$\") self.assertTrue(dpf(\"foo/bar/abc/some.txt\")) #",
"self.assertTrue(dpf(\"foo/bar/abc/some.txt\")) # self.assertFalse(dpf(\"abc/abc/bar/some.txt\")) self.assertFalse(dpf(\"abc/abc/bar/abc.abc\")) @unittest.skipUnless(on_windows(), \"Only tested on Windows.\") def",
"dir_ends_with_abc(\"/foo/bar/folder_def/my_resource.txt\") xml_file = rf.filename_pattern_predicate(\".xml$\") assert xml_file(\"my_resource.xml\") assert not xml_file(\"my_resource.txt\") import",
"[xml_files_in_abc] excludes = [recent] resource_gate = lf.gate(includes, excludes) # print(type(resource_gate))",
"self.assertTrue(dpf(\"/foo/bar/abc/some.txt\")) self.assertTrue(dpf(\"foo\\\\babcd\\\\bar\\\\some.txt\")) self.assertTrue(dpf(\"c:\\\\abc\\\\bar\\\\some.txt\")) self.assertTrue(dpf(\"c:\\\\foo\\\\bar\\\\abc\\\\some.txt\")) # self.assertFalse(dpf(\"/foo/bar/baz/abc.txt\")) self.assertFalse(dpf(\"c:\\\\foo\\\\bar\\\\baz\\\\abc.txt\")) # ## dpf",
"tested on Windows.\") def test_windows_to_unix(self): path = os.path.expanduser(\"~\") dpf =",
"Windows.\") def test_directory_pattern_filter_windows(self): dpf = rf.directory_pattern_predicate(\"abc\") self.assertTrue(dpf(\"foo/babcd/bar/some.txt\")) self.assertTrue(dpf(\"/abc/bar/some.txt\")) self.assertTrue(dpf(\"/foo/bar/abc/some.txt\")) self.assertTrue(dpf(\"foo\\\\babcd\\\\bar\\\\some.txt\"))",
"self.assertTrue(dpf(\".\")) self.assertTrue(dpf(\"\\n\")) self.assertTrue(dpf(\"foo\")) # rejects not string self.assertFalse(dpf(None)) self.assertFalse(dpf(42)) self.assertFalse(dpf(self))",
"import rspub.util.gates as lf xml_files_in_abc = lf.and_(dir_ends_with_abc, xml_file) assert xml_files_in_abc(\"/foo/bar/folder_abc/my_resource.xml\")",
"tested on Windows.\") def test_example_windows(self): import rspub.util.resourcefilter as rf dir_ends_with_abc",
"06:20:00 self.assertFalse(lmaf(file_name)) lmaf = rf.last_modified_after_predicate(\"2016-08-01\") self.assertTrue(lmaf(file_name)) def test_example(self): import rspub.util.resourcefilter",
"self.assertFalse(dpf(self)) def test_directory_pattern_filter(self): dpf = rf.directory_pattern_predicate(\"abc\") self.assertTrue(dpf(\"foo/babcd/bar/some.txt\")) self.assertTrue(dpf(\"/abc/bar/some.txt\")) self.assertTrue(dpf(\"/foo/bar/abc/some.txt\")) #",
"includes = [xml_files_in_abc] excludes = [recent] resource_gate = lf.gate(includes, excludes)",
"recent = rf.last_modified_after_predicate(\"2016-08-01\") includes = [xml_files_in_abc] excludes = [recent] resource_gate",
"rf.directory_pattern_predicate(\"^\" + path) self.assertTrue(dpf(os.path.join(path, \"bla\"))) dpf = rf.directory_pattern_predicate(\"^C:\\\\Users\") self.assertTrue(dpf(os.path.join(path, \"bla\")))",
"unittest import rspub.util.resourcefilter as rf def on_windows(): opsys = platform.system()",
"def test_directory_pattern_filter(self): dpf = rf.directory_pattern_predicate(\"abc\") self.assertTrue(dpf(\"foo/babcd/bar/some.txt\")) self.assertTrue(dpf(\"/abc/bar/some.txt\")) self.assertTrue(dpf(\"/foo/bar/abc/some.txt\")) # self.assertFalse(dpf(\"/foo/bar/baz/abc.txt\"))",
"os import platform import unittest import rspub.util.resourcefilter as rf def",
"def test_example(self): import rspub.util.resourcefilter as rf dir_ends_with_abc = rf.directory_pattern_predicate(\"abc$\") assert",
"assert xml_files_in_abc(\"c:\\\\foo\\\\bar\\\\folder_abc\\\\my_resource.xml\") assert not xml_files_in_abc(\"c:\\\\foo\\\\bar\\\\folder_abc\\\\my_resource.txt\") assert not xml_files_in_abc(\"c:\\\\foo\\\\bar\\\\folder_def\\\\my_resource.xml\") recent =",
"self.assertTrue(dpf(\"/foo/bar/abc/some.txt\")) # self.assertFalse(dpf(\"/foo/bar/baz/abc.txt\")) # ## dpf = rf.directory_pattern_predicate(\"^/abc\") self.assertTrue(dpf(\"/abc/bar/some.txt\")) #",
"self.assertTrue(dpf(\"/abc/bar/some.txt\")) self.assertTrue(dpf(\"/foo/bar/abc/some.txt\")) self.assertTrue(dpf(\"foo\\\\babcd\\\\bar\\\\some.txt\")) self.assertTrue(dpf(\"c:\\\\abc\\\\bar\\\\some.txt\")) self.assertTrue(dpf(\"c:\\\\foo\\\\bar\\\\abc\\\\some.txt\")) # self.assertFalse(dpf(\"/foo/bar/baz/abc.txt\")) self.assertFalse(dpf(\"c:\\\\foo\\\\bar\\\\baz\\\\abc.txt\")) # ##",
"TestPredicates(unittest.TestCase): def test_directory_pattern_filter_empty(self): dpf = rf.directory_pattern_predicate() # should pass all",
"self.assertTrue(lmaf(file_name)) def test_example(self): import rspub.util.resourcefilter as rf dir_ends_with_abc = rf.directory_pattern_predicate(\"abc$\")",
"self.assertFalse(dpf(\"c:\\\\foo\\\\bar\\\\baz\\\\abc.txt\")) # ## dpf = rf.directory_pattern_predicate(\"^/abc\") self.assertTrue(dpf(\"/abc/bar/some.txt\")) # self.assertFalse(dpf(\"abc/bar/some.txt\")) #",
"rf.directory_pattern_predicate(\"^/abc\") self.assertTrue(dpf(\"/abc/bar/some.txt\")) # self.assertFalse(dpf(\"abc/bar/some.txt\")) # # dpf = rf.directory_pattern_predicate(\"abc$\") self.assertTrue(dpf(\"foo/bar/abc/some.txt\"))",
"# self.assertFalse(dpf(\"abc/abc/bar/some.txt\")) self.assertFalse(dpf(\"abc\\\\abc\\\\bar\\\\some.txt\")) self.assertFalse(dpf(\"abc/abc/bar/abc.abc\")) self.assertFalse(dpf(\"abc\\\\abc\\\\bar\\\\abc.abc\")) def test_last_modified_filter(self): file_name = os.path.realpath(__file__)",
"xml_files_in_abc(\"/foo/bar/folder_abc/my_resource.xml\") assert not xml_files_in_abc(\"/foo/bar/folder_abc/my_resource.txt\") assert not xml_files_in_abc(\"/foo/bar/folder_def/my_resource.xml\") recent = rf.last_modified_after_predicate(\"2016-08-01\")",
"rf.directory_pattern_predicate(\"abc\") self.assertTrue(dpf(\"foo/babcd/bar/some.txt\")) self.assertTrue(dpf(\"/abc/bar/some.txt\")) self.assertTrue(dpf(\"/foo/bar/abc/some.txt\")) # self.assertFalse(dpf(\"/foo/bar/baz/abc.txt\")) # ## dpf =",
"xml_files_in_abc(\"c:\\\\foo\\\\bar\\\\folder_abc\\\\my_resource.xml\") assert not xml_files_in_abc(\"c:\\\\foo\\\\bar\\\\folder_abc\\\\my_resource.txt\") assert not xml_files_in_abc(\"c:\\\\foo\\\\bar\\\\folder_def\\\\my_resource.xml\") recent = rf.last_modified_after_predicate(\"2016-08-01\")",
"= [recent] resource_gate = lf.gate(includes, excludes) # print(type(resource_gate)) @unittest.skipUnless(on_windows(), \"Only",
"xml_files_in_abc(\"/foo/bar/folder_abc/my_resource.txt\") assert not xml_files_in_abc(\"/foo/bar/folder_def/my_resource.xml\") assert xml_files_in_abc(\"c:\\\\foo\\\\bar\\\\folder_abc\\\\my_resource.xml\") assert not xml_files_in_abc(\"c:\\\\foo\\\\bar\\\\folder_abc\\\\my_resource.txt\") assert",
"@unittest.skipUnless(on_windows(), \"Only tested on Windows.\") def test_directory_pattern_filter_windows(self): dpf = rf.directory_pattern_predicate(\"abc\")",
"python3 # -*- coding: utf-8 -*- import os import platform",
"== \"Windows\" class TestPredicates(unittest.TestCase): def test_directory_pattern_filter_empty(self): dpf = rf.directory_pattern_predicate() #",
"= lf.gate(includes, excludes) # print(type(resource_gate)) @unittest.skipUnless(on_windows(), \"Only tested on Windows.\")",
"self.assertTrue(dpf(\"foo/bar/abc/some.txt\")) self.assertTrue(dpf(\"foo\\\\bar\\\\abc\\\\some.txt\")) # self.assertFalse(dpf(\"abc/abc/bar/some.txt\")) self.assertFalse(dpf(\"abc\\\\abc\\\\bar\\\\some.txt\")) self.assertFalse(dpf(\"abc/abc/bar/abc.abc\")) self.assertFalse(dpf(\"abc\\\\abc\\\\bar\\\\abc.abc\")) def test_last_modified_filter(self): file_name",
"assert not xml_files_in_abc(\"/foo/bar/folder_abc/my_resource.txt\") assert not xml_files_in_abc(\"/foo/bar/folder_def/my_resource.xml\") recent = rf.last_modified_after_predicate(\"2016-08-01\") includes",
"on_windows(): opsys = platform.system() return opsys == \"Windows\" class TestPredicates(unittest.TestCase):",
"= rf.directory_pattern_predicate(\"^c:\\\\abc\") self.assertTrue(dpf(\"c:\\\\abc\\\\bar\\\\some.txt\")) # self.assertFalse(dpf(\"abc\\\\bar\\\\some.txt\")) dpf = rf.directory_pattern_predicate(\"abc$\") self.assertTrue(dpf(\"foo/bar/abc/some.txt\")) self.assertTrue(dpf(\"foo\\\\bar\\\\abc\\\\some.txt\"))",
"path = os.path.expanduser(\"~\") dpf = rf.directory_pattern_predicate(\"^\" + path) self.assertTrue(dpf(os.path.join(path, \"bla\")))",
"def test_last_modified_filter(self): file_name = os.path.realpath(__file__) lmaf = rf.last_modified_after_predicate() self.assertTrue(lmaf(file_name)) lmaf",
"# self.assertFalse(dpf(\"/foo/bar/baz/abc.txt\")) # ## dpf = rf.directory_pattern_predicate(\"^/abc\") self.assertTrue(dpf(\"/abc/bar/some.txt\")) # self.assertFalse(dpf(\"abc/bar/some.txt\"))",
"self.assertFalse(dpf(\"abc/bar/some.txt\")) # # dpf = rf.directory_pattern_predicate(\"^c:\\\\abc\") self.assertTrue(dpf(\"c:\\\\abc\\\\bar\\\\some.txt\")) # self.assertFalse(dpf(\"abc\\\\bar\\\\some.txt\")) dpf",
"self.assertFalse(lmaf(file_name)) lmaf = rf.last_modified_after_predicate(\"2016-08-01\") self.assertTrue(lmaf(file_name)) def test_example(self): import rspub.util.resourcefilter as",
"rf.directory_pattern_predicate(\"abc\") self.assertTrue(dpf(\"foo/babcd/bar/some.txt\")) self.assertTrue(dpf(\"/abc/bar/some.txt\")) self.assertTrue(dpf(\"/foo/bar/abc/some.txt\")) self.assertTrue(dpf(\"foo\\\\babcd\\\\bar\\\\some.txt\")) self.assertTrue(dpf(\"c:\\\\abc\\\\bar\\\\some.txt\")) self.assertTrue(dpf(\"c:\\\\foo\\\\bar\\\\abc\\\\some.txt\")) # self.assertFalse(dpf(\"/foo/bar/baz/abc.txt\")) self.assertFalse(dpf(\"c:\\\\foo\\\\bar\\\\baz\\\\abc.txt\"))",
"string self.assertFalse(dpf(None)) self.assertFalse(dpf(42)) self.assertFalse(dpf(self)) def test_directory_pattern_filter(self): dpf = rf.directory_pattern_predicate(\"abc\") self.assertTrue(dpf(\"foo/babcd/bar/some.txt\"))",
"test_example_windows(self): import rspub.util.resourcefilter as rf dir_ends_with_abc = rf.directory_pattern_predicate(\"abc$\") assert dir_ends_with_abc(\"/foo/bar/folder_abc/my_resource.txt\")",
"= os.path.expanduser(\"~\") dpf = rf.directory_pattern_predicate(\"^\" + path) self.assertTrue(dpf(os.path.join(path, \"bla\"))) dpf",
"utf-8 -*- import os import platform import unittest import rspub.util.resourcefilter",
"Windows.\") def test_windows_to_unix(self): path = os.path.expanduser(\"~\") dpf = rf.directory_pattern_predicate(\"^\" +",
"not xml_files_in_abc(\"c:\\\\foo\\\\bar\\\\folder_def\\\\my_resource.xml\") recent = rf.last_modified_after_predicate(\"2016-08-01\") includes = [xml_files_in_abc] excludes =",
"\"Windows\" class TestPredicates(unittest.TestCase): def test_directory_pattern_filter_empty(self): dpf = rf.directory_pattern_predicate() # should",
"test_directory_pattern_filter(self): dpf = rf.directory_pattern_predicate(\"abc\") self.assertTrue(dpf(\"foo/babcd/bar/some.txt\")) self.assertTrue(dpf(\"/abc/bar/some.txt\")) self.assertTrue(dpf(\"/foo/bar/abc/some.txt\")) # self.assertFalse(dpf(\"/foo/bar/baz/abc.txt\")) #",
"opsys = platform.system() return opsys == \"Windows\" class TestPredicates(unittest.TestCase): def",
"xml_files_in_abc(\"/foo/bar/folder_abc/my_resource.txt\") assert not xml_files_in_abc(\"/foo/bar/folder_def/my_resource.xml\") recent = rf.last_modified_after_predicate(\"2016-08-01\") includes = [xml_files_in_abc]",
"self.assertTrue(dpf(\"foo/babcd/bar/some.txt\")) self.assertTrue(dpf(\"/abc/bar/some.txt\")) self.assertTrue(dpf(\"/foo/bar/abc/some.txt\")) self.assertTrue(dpf(\"foo\\\\babcd\\\\bar\\\\some.txt\")) self.assertTrue(dpf(\"c:\\\\abc\\\\bar\\\\some.txt\")) self.assertTrue(dpf(\"c:\\\\foo\\\\bar\\\\abc\\\\some.txt\")) # self.assertFalse(dpf(\"/foo/bar/baz/abc.txt\")) self.assertFalse(dpf(\"c:\\\\foo\\\\bar\\\\baz\\\\abc.txt\")) #",
"not xml_files_in_abc(\"/foo/bar/folder_abc/my_resource.txt\") assert not xml_files_in_abc(\"/foo/bar/folder_def/my_resource.xml\") assert xml_files_in_abc(\"c:\\\\foo\\\\bar\\\\folder_abc\\\\my_resource.xml\") assert not xml_files_in_abc(\"c:\\\\foo\\\\bar\\\\folder_abc\\\\my_resource.txt\")",
"excludes) # print(type(resource_gate)) @unittest.skipUnless(on_windows(), \"Only tested on Windows.\") def test_windows_to_unix(self):",
"on Windows.\") def test_directory_pattern_filter_windows(self): dpf = rf.directory_pattern_predicate(\"abc\") self.assertTrue(dpf(\"foo/babcd/bar/some.txt\")) self.assertTrue(dpf(\"/abc/bar/some.txt\")) self.assertTrue(dpf(\"/foo/bar/abc/some.txt\"))",
"= rf.last_modified_after_predicate(3000000000) # valid until 2065-01-24 06:20:00 self.assertFalse(lmaf(file_name)) lmaf =",
"# -*- coding: utf-8 -*- import os import platform import",
"xml_file) assert xml_files_in_abc(\"/foo/bar/folder_abc/my_resource.xml\") assert not xml_files_in_abc(\"/foo/bar/folder_abc/my_resource.txt\") assert not xml_files_in_abc(\"/foo/bar/folder_def/my_resource.xml\") assert",
"self.assertTrue(dpf(\"foo\")) # rejects not string self.assertFalse(dpf(None)) self.assertFalse(dpf(42)) self.assertFalse(dpf(self)) def test_directory_pattern_filter(self):",
"rf.last_modified_after_predicate(\"2016-08-01\") self.assertTrue(lmaf(file_name)) def test_example(self): import rspub.util.resourcefilter as rf dir_ends_with_abc =",
"rspub.util.resourcefilter as rf dir_ends_with_abc = rf.directory_pattern_predicate(\"abc$\") assert dir_ends_with_abc(\"/foo/bar/folder_abc/my_resource.txt\") assert not",
"platform import unittest import rspub.util.resourcefilter as rf def on_windows(): opsys",
"self.assertTrue(dpf(\"foo\\\\bar\\\\abc\\\\some.txt\")) # self.assertFalse(dpf(\"abc/abc/bar/some.txt\")) self.assertFalse(dpf(\"abc\\\\abc\\\\bar\\\\some.txt\")) self.assertFalse(dpf(\"abc/abc/bar/abc.abc\")) self.assertFalse(dpf(\"abc\\\\abc\\\\bar\\\\abc.abc\")) def test_last_modified_filter(self): file_name =",
"os.path.realpath(__file__) lmaf = rf.last_modified_after_predicate() self.assertTrue(lmaf(file_name)) lmaf = rf.last_modified_after_predicate(3000000000) # valid",
"assert not xml_file(\"my_resource.txt\") import rspub.util.gates as lf xml_files_in_abc = lf.and_(dir_ends_with_abc,",
"rspub.util.resourcefilter as rf def on_windows(): opsys = platform.system() return opsys",
"assert not xml_files_in_abc(\"/foo/bar/folder_def/my_resource.xml\") assert xml_files_in_abc(\"c:\\\\foo\\\\bar\\\\folder_abc\\\\my_resource.xml\") assert not xml_files_in_abc(\"c:\\\\foo\\\\bar\\\\folder_abc\\\\my_resource.txt\") assert not",
"lf.and_(dir_ends_with_abc, xml_file) assert xml_files_in_abc(\"/foo/bar/folder_abc/my_resource.xml\") assert not xml_files_in_abc(\"/foo/bar/folder_abc/my_resource.txt\") assert not xml_files_in_abc(\"/foo/bar/folder_def/my_resource.xml\")",
"= rf.directory_pattern_predicate() # should pass all strings self.assertTrue(dpf(\"\")) self.assertTrue(dpf(\".\")) self.assertTrue(dpf(\"\\n\"))",
"test_example(self): import rspub.util.resourcefilter as rf dir_ends_with_abc = rf.directory_pattern_predicate(\"abc$\") assert dir_ends_with_abc(\"/foo/bar/folder_abc/my_resource.txt\")",
"# self.assertFalse(dpf(\"abc/bar/some.txt\")) # # dpf = rf.directory_pattern_predicate(\"^c:\\\\abc\") self.assertTrue(dpf(\"c:\\\\abc\\\\bar\\\\some.txt\")) # self.assertFalse(dpf(\"abc\\\\bar\\\\some.txt\"))",
"assert xml_files_in_abc(\"/foo/bar/folder_abc/my_resource.xml\") assert not xml_files_in_abc(\"/foo/bar/folder_abc/my_resource.txt\") assert not xml_files_in_abc(\"/foo/bar/folder_def/my_resource.xml\") assert xml_files_in_abc(\"c:\\\\foo\\\\bar\\\\folder_abc\\\\my_resource.xml\")",
"= rf.filename_pattern_predicate(\".xml$\") assert xml_file(\"my_resource.xml\") assert not xml_file(\"my_resource.txt\") import rspub.util.gates as",
"xml_files_in_abc(\"/foo/bar/folder_def/my_resource.xml\") recent = rf.last_modified_after_predicate(\"2016-08-01\") includes = [xml_files_in_abc] excludes = [recent]",
"strings self.assertTrue(dpf(\"\")) self.assertTrue(dpf(\".\")) self.assertTrue(dpf(\"\\n\")) self.assertTrue(dpf(\"foo\")) # rejects not string self.assertFalse(dpf(None))",
"assert not xml_files_in_abc(\"/foo/bar/folder_abc/my_resource.txt\") assert not xml_files_in_abc(\"/foo/bar/folder_def/my_resource.xml\") assert xml_files_in_abc(\"c:\\\\foo\\\\bar\\\\folder_abc\\\\my_resource.xml\") assert not",
"assert not xml_files_in_abc(\"c:\\\\foo\\\\bar\\\\folder_def\\\\my_resource.xml\") recent = rf.last_modified_after_predicate(\"2016-08-01\") includes = [xml_files_in_abc] excludes",
"# self.assertFalse(dpf(\"abc\\\\bar\\\\some.txt\")) dpf = rf.directory_pattern_predicate(\"abc$\") self.assertTrue(dpf(\"foo/bar/abc/some.txt\")) self.assertTrue(dpf(\"foo\\\\bar\\\\abc\\\\some.txt\")) # self.assertFalse(dpf(\"abc/abc/bar/some.txt\")) self.assertFalse(dpf(\"abc\\\\abc\\\\bar\\\\some.txt\"))",
"not string self.assertFalse(dpf(None)) self.assertFalse(dpf(42)) self.assertFalse(dpf(self)) def test_directory_pattern_filter(self): dpf = rf.directory_pattern_predicate(\"abc\")",
"@unittest.skipUnless(on_windows(), \"Only tested on Windows.\") def test_example_windows(self): import rspub.util.resourcefilter as",
"xml_files_in_abc(\"/foo/bar/folder_def/my_resource.xml\") assert xml_files_in_abc(\"c:\\\\foo\\\\bar\\\\folder_abc\\\\my_resource.xml\") assert not xml_files_in_abc(\"c:\\\\foo\\\\bar\\\\folder_abc\\\\my_resource.txt\") assert not xml_files_in_abc(\"c:\\\\foo\\\\bar\\\\folder_def\\\\my_resource.xml\") recent",
"on Windows.\") def test_windows_to_unix(self): path = os.path.expanduser(\"~\") dpf = rf.directory_pattern_predicate(\"^\"",
"tested on Windows.\") def test_directory_pattern_filter_windows(self): dpf = rf.directory_pattern_predicate(\"abc\") self.assertTrue(dpf(\"foo/babcd/bar/some.txt\")) self.assertTrue(dpf(\"/abc/bar/some.txt\"))",
"dpf = rf.directory_pattern_predicate(\"abc$\") self.assertTrue(dpf(\"foo/bar/abc/some.txt\")) self.assertTrue(dpf(\"foo\\\\bar\\\\abc\\\\some.txt\")) # self.assertFalse(dpf(\"abc/abc/bar/some.txt\")) self.assertFalse(dpf(\"abc\\\\abc\\\\bar\\\\some.txt\")) self.assertFalse(dpf(\"abc/abc/bar/abc.abc\")) self.assertFalse(dpf(\"abc\\\\abc\\\\bar\\\\abc.abc\"))",
"assert not xml_files_in_abc(\"/foo/bar/folder_def/my_resource.xml\") recent = rf.last_modified_after_predicate(\"2016-08-01\") includes = [xml_files_in_abc] excludes",
"dir_ends_with_abc(\"/foo/bar/folder_abc/my_resource.txt\") assert not dir_ends_with_abc(\"/foo/bar/folder_def/my_resource.txt\") xml_file = rf.filename_pattern_predicate(\".xml$\") assert xml_file(\"my_resource.xml\") assert",
"rf def on_windows(): opsys = platform.system() return opsys == \"Windows\"",
"## dpf = rf.directory_pattern_predicate(\"^/abc\") self.assertTrue(dpf(\"/abc/bar/some.txt\")) # self.assertFalse(dpf(\"abc/bar/some.txt\")) # # dpf",
"os.path.expanduser(\"~\") dpf = rf.directory_pattern_predicate(\"^\" + path) self.assertTrue(dpf(os.path.join(path, \"bla\"))) dpf =",
"\"Only tested on Windows.\") def test_example_windows(self): import rspub.util.resourcefilter as rf",
"xml_file) assert xml_files_in_abc(\"/foo/bar/folder_abc/my_resource.xml\") assert not xml_files_in_abc(\"/foo/bar/folder_abc/my_resource.txt\") assert not xml_files_in_abc(\"/foo/bar/folder_def/my_resource.xml\") recent",
"= rf.last_modified_after_predicate(\"2016-08-01\") includes = [xml_files_in_abc] excludes = [recent] resource_gate =",
"on Windows.\") def test_example_windows(self): import rspub.util.resourcefilter as rf dir_ends_with_abc =",
"until 2065-01-24 06:20:00 self.assertFalse(lmaf(file_name)) lmaf = rf.last_modified_after_predicate(\"2016-08-01\") self.assertTrue(lmaf(file_name)) def test_example(self):",
"rf.directory_pattern_predicate(\"abc$\") self.assertTrue(dpf(\"foo/bar/abc/some.txt\")) self.assertTrue(dpf(\"foo\\\\bar\\\\abc\\\\some.txt\")) # self.assertFalse(dpf(\"abc/abc/bar/some.txt\")) self.assertFalse(dpf(\"abc\\\\abc\\\\bar\\\\some.txt\")) self.assertFalse(dpf(\"abc/abc/bar/abc.abc\")) self.assertFalse(dpf(\"abc\\\\abc\\\\bar\\\\abc.abc\")) def test_last_modified_filter(self):",
"= lf.and_(dir_ends_with_abc, xml_file) assert xml_files_in_abc(\"/foo/bar/folder_abc/my_resource.xml\") assert not xml_files_in_abc(\"/foo/bar/folder_abc/my_resource.txt\") assert not",
"self.assertTrue(dpf(\"c:\\\\abc\\\\bar\\\\some.txt\")) # self.assertFalse(dpf(\"abc\\\\bar\\\\some.txt\")) dpf = rf.directory_pattern_predicate(\"abc$\") self.assertTrue(dpf(\"foo/bar/abc/some.txt\")) self.assertTrue(dpf(\"foo\\\\bar\\\\abc\\\\some.txt\")) # self.assertFalse(dpf(\"abc/abc/bar/some.txt\"))",
"= rf.directory_pattern_predicate(\"abc$\") self.assertTrue(dpf(\"foo/bar/abc/some.txt\")) self.assertTrue(dpf(\"foo\\\\bar\\\\abc\\\\some.txt\")) # self.assertFalse(dpf(\"abc/abc/bar/some.txt\")) self.assertFalse(dpf(\"abc\\\\abc\\\\bar\\\\some.txt\")) self.assertFalse(dpf(\"abc/abc/bar/abc.abc\")) self.assertFalse(dpf(\"abc\\\\abc\\\\bar\\\\abc.abc\")) def",
"self.assertFalse(dpf(42)) self.assertFalse(dpf(self)) def test_directory_pattern_filter(self): dpf = rf.directory_pattern_predicate(\"abc\") self.assertTrue(dpf(\"foo/babcd/bar/some.txt\")) self.assertTrue(dpf(\"/abc/bar/some.txt\")) self.assertTrue(dpf(\"/foo/bar/abc/some.txt\"))",
"file_name = os.path.realpath(__file__) lmaf = rf.last_modified_after_predicate() self.assertTrue(lmaf(file_name)) lmaf = rf.last_modified_after_predicate(3000000000)",
"lmaf = rf.last_modified_after_predicate(3000000000) # valid until 2065-01-24 06:20:00 self.assertFalse(lmaf(file_name)) lmaf",
"rf.directory_pattern_predicate(\"abc$\") assert dir_ends_with_abc(\"/foo/bar/folder_abc/my_resource.txt\") assert not dir_ends_with_abc(\"/foo/bar/folder_def/my_resource.txt\") xml_file = rf.filename_pattern_predicate(\".xml$\") assert",
"= rf.directory_pattern_predicate(\"^/abc\") self.assertTrue(dpf(\"/abc/bar/some.txt\")) # self.assertFalse(dpf(\"abc/bar/some.txt\")) # # dpf = rf.directory_pattern_predicate(\"^c:\\\\abc\")",
"self.assertTrue(lmaf(file_name)) lmaf = rf.last_modified_after_predicate(3000000000) # valid until 2065-01-24 06:20:00 self.assertFalse(lmaf(file_name))",
"-*- coding: utf-8 -*- import os import platform import unittest",
"self.assertTrue(dpf(\"foo/babcd/bar/some.txt\")) self.assertTrue(dpf(\"/abc/bar/some.txt\")) self.assertTrue(dpf(\"/foo/bar/abc/some.txt\")) # self.assertFalse(dpf(\"/foo/bar/baz/abc.txt\")) # ## dpf = rf.directory_pattern_predicate(\"^/abc\")",
"# rejects not string self.assertFalse(dpf(None)) self.assertFalse(dpf(42)) self.assertFalse(dpf(self)) def test_directory_pattern_filter(self): dpf",
"rf.last_modified_after_predicate(3000000000) # valid until 2065-01-24 06:20:00 self.assertFalse(lmaf(file_name)) lmaf = rf.last_modified_after_predicate(\"2016-08-01\")",
"rf dir_ends_with_abc = rf.directory_pattern_predicate(\"abc$\") assert dir_ends_with_abc(\"/foo/bar/folder_abc/my_resource.txt\") assert not dir_ends_with_abc(\"/foo/bar/folder_def/my_resource.txt\") xml_file",
"= rf.directory_pattern_predicate(\"abc$\") assert dir_ends_with_abc(\"/foo/bar/folder_abc/my_resource.txt\") assert not dir_ends_with_abc(\"/foo/bar/folder_def/my_resource.txt\") xml_file = rf.filename_pattern_predicate(\".xml$\")",
"not dir_ends_with_abc(\"/foo/bar/folder_def/my_resource.txt\") xml_file = rf.filename_pattern_predicate(\".xml$\") assert xml_file(\"my_resource.xml\") assert not xml_file(\"my_resource.txt\")",
"dpf = rf.directory_pattern_predicate(\"abc\") self.assertTrue(dpf(\"foo/babcd/bar/some.txt\")) self.assertTrue(dpf(\"/abc/bar/some.txt\")) self.assertTrue(dpf(\"/foo/bar/abc/some.txt\")) self.assertTrue(dpf(\"foo\\\\babcd\\\\bar\\\\some.txt\")) self.assertTrue(dpf(\"c:\\\\abc\\\\bar\\\\some.txt\")) self.assertTrue(dpf(\"c:\\\\foo\\\\bar\\\\abc\\\\some.txt\")) #",
"= rf.directory_pattern_predicate(\"^/abc\") self.assertTrue(dpf(\"/abc/bar/some.txt\")) # self.assertFalse(dpf(\"abc/bar/some.txt\")) # # dpf = rf.directory_pattern_predicate(\"abc$\")",
"self.assertFalse(dpf(\"abc/abc/bar/abc.abc\")) @unittest.skipUnless(on_windows(), \"Only tested on Windows.\") def test_directory_pattern_filter_windows(self): dpf =",
"coding: utf-8 -*- import os import platform import unittest import",
"= os.path.realpath(__file__) lmaf = rf.last_modified_after_predicate() self.assertTrue(lmaf(file_name)) lmaf = rf.last_modified_after_predicate(3000000000) #"
] |
[
"import os import testinfra.utils.ansible_runner testinfra_hosts = testinfra.utils.ansible_runner.AnsibleRunner( os.environ['MOLECULE_INVENTORY_FILE']).get_hosts('all') def test_package(host):",
"\"\"\" assert host.package('grafana').is_installed def test_service(host): \"\"\" Testing whether the service",
"\"\"\" check if packages are installed \"\"\" assert host.package('grafana').is_installed def",
"Testing whether the service is running and enabled \"\"\" assert",
"if packages are installed \"\"\" assert host.package('grafana').is_installed def test_service(host): \"\"\"",
"check if packages are installed \"\"\" assert host.package('grafana').is_installed def test_service(host):",
"host.package('grafana').is_installed def test_service(host): \"\"\" Testing whether the service is running",
"assert host.package('grafana').is_installed def test_service(host): \"\"\" Testing whether the service is",
"packages are installed \"\"\" assert host.package('grafana').is_installed def test_service(host): \"\"\" Testing",
"import testinfra.utils.ansible_runner testinfra_hosts = testinfra.utils.ansible_runner.AnsibleRunner( os.environ['MOLECULE_INVENTORY_FILE']).get_hosts('all') def test_package(host): \"\"\" check",
"whether the service is running and enabled \"\"\" assert host.service('grafana-server').is_enabled",
"testinfra_hosts = testinfra.utils.ansible_runner.AnsibleRunner( os.environ['MOLECULE_INVENTORY_FILE']).get_hosts('all') def test_package(host): \"\"\" check if packages",
"os import testinfra.utils.ansible_runner testinfra_hosts = testinfra.utils.ansible_runner.AnsibleRunner( os.environ['MOLECULE_INVENTORY_FILE']).get_hosts('all') def test_package(host): \"\"\"",
"\"\"\" Testing whether the service is running and enabled \"\"\"",
"service is running and enabled \"\"\" assert host.service('grafana-server').is_enabled assert host.service('grafana-server').is_running",
"= testinfra.utils.ansible_runner.AnsibleRunner( os.environ['MOLECULE_INVENTORY_FILE']).get_hosts('all') def test_package(host): \"\"\" check if packages are",
"os.environ['MOLECULE_INVENTORY_FILE']).get_hosts('all') def test_package(host): \"\"\" check if packages are installed \"\"\"",
"are installed \"\"\" assert host.package('grafana').is_installed def test_service(host): \"\"\" Testing whether",
"testinfra.utils.ansible_runner.AnsibleRunner( os.environ['MOLECULE_INVENTORY_FILE']).get_hosts('all') def test_package(host): \"\"\" check if packages are installed",
"test_package(host): \"\"\" check if packages are installed \"\"\" assert host.package('grafana').is_installed",
"def test_package(host): \"\"\" check if packages are installed \"\"\" assert",
"the service is running and enabled \"\"\" assert host.service('grafana-server').is_enabled assert",
"test_service(host): \"\"\" Testing whether the service is running and enabled",
"def test_service(host): \"\"\" Testing whether the service is running and",
"testinfra.utils.ansible_runner testinfra_hosts = testinfra.utils.ansible_runner.AnsibleRunner( os.environ['MOLECULE_INVENTORY_FILE']).get_hosts('all') def test_package(host): \"\"\" check if",
"installed \"\"\" assert host.package('grafana').is_installed def test_service(host): \"\"\" Testing whether the"
] |
[
"(self.numberOfFins * self.overallDiameter * self.finThickness))) # meter^2 # overall area",
"the thin boundry layer of inner surface nnInFD = Nusselt",
"ambAirTemp # kelvin hLoD = self.heatsinkLength / self.overallDiameter cDoD =",
"(alternatively, fin depth) finThickness : thickness of individual fin cylinderDiameter:",
"alpha * self.overallDiameter)) RayleighNbrOverallDiameter = ((const.g * beta * deltaT",
"of heatsink and ambient air temp. k = thermal conductivity",
"* self.finSpacing**4) / (kinematicViscosity * alpha * self.overallDiameter)) RayleighNbrOverallDiameter =",
"(2.9 * 10**4 <= RayleighNbrOverallDiameter <= 2.3 * 10**5): nnInT",
"self.maxJunctionTemp = maxJunctionTemp self.maxSurfaceTemp = maxSurfaceTemp \"\"\" NOTE: in order",
"\"\"\"Extend base heatsink class with a cylindrical annular fin heatsink.\"\"\"",
"base heatsink class with a cylindrical annular fin heatsink.\"\"\" def",
"meter^2 # inner surface area of heatsink areaIn = (self.numberOfFins",
"fin cylinderDiameter: diameter of support cylinder heatsinkLength : overall axial",
"+ math.pow(nnInFD, -n), (-1/n) ) * (areaIn/areaHS) ) self.nn =",
"= ambAirTemp # degrees kelvin self.maxJunctionTemp = maxJunctionTemp self.maxSurfaceTemp =",
"2) + self.overallDiameter * self.heatsinkLength)) # meter^2 # inner surface",
"/ areaHS) ) if 0.1 <= (self.finThickness * self.numberOfFins /",
"(math.pi * (((self.overallDiameter**2) / 2) + self.overallDiameter * self.heatsinkLength)) #",
"meters self.numberOfFins = numberofFins self.heatsinkLength = ((self.finThickness * self.numberOfFins) +",
"follows: nn = Nusselt Number nn0 = Nusselt Number 0",
"aluminium class Heatsink: \"\"\" A Heatsink. Extended by form factor",
"/ (Ahs deltaT k) Qconv = heat flow rate by",
"using the simplified model for calculation efficiency. finSpacing : gap",
"<= (self.finThickness * self.numberOfFins / self.overallDiameter) <= 8: self.nnOut =",
"= self.cylinderDiameter / self.overallDiameter oneChannelArea = (math.pi * (((self.overallDiameter**2 -",
"central support cylinder (alternatively, fin depth) finThickness : thickness of",
"outside diameter of heatsink including fins. \"\"\" self.finSpacing = finSpacing",
"(0.0388 * cdoD**2)) * math.pow(RayleighNbrFinSpacing, 0.25)) nnInFD = (((0.0323 -",
"thin boundry layer of inner surface nnInFD = Nusselt Number",
"cylindrical annular fin heatsink.\"\"\" def __init__(self, material, finSpacing, finRadius, finThickness,",
"10**(-6) # (meters^2) / seconds # Volumetric coefficient of thermal",
"remainder of class variables. NOTE: all models are based off",
"by form factor subclasses \"\"\" def __init__(self, material, configuration): \"\"\"Init",
"inner surface \"\"\" # thermal diffusivity of air at atmospheric",
"Number for the thin boundry layer of inner surface nnInFD",
"between surface temp of heatsink and ambient air temp. k",
"Number for inner surfaces nnInT = Nusselt Number for the",
"(kinematicViscosity * alpha * self.overallDiameter)) RayleighNbrOverallDiameter = ((const.g * beta",
"seconds # Volumetric coefficient of thermal expansion beta = aluminium.expansionCoefficient",
"* self.overallDiameter * self.finThickness))) # meter^2 # overall area of",
"Nusselt Number nn0 = Nusselt Number 0 (Diffusive Limit) nnOut",
"oneChannelArea = (math.pi * (((self.overallDiameter**2 - self.cylinderDiameter**2) / 2) +",
"* 10**(-6) # (meters^2) / seconds # Volumetric coefficient of",
"1) * oneChannelArea # meter^2 # outer surface area of",
"* self.numberOfFins / self.overallDiameter))) * math.pow(RayleighNbrFinSpacing, 0.25) * (areaOut/areaHS) )",
"material and configuration variables.\"\"\" self.material = material self.configuration = configuration",
"of air at atmospheric pressure at 25C alpha = 22.39",
"length of heatsink overall diameter: outside diameter of heatsink including",
"# outer surface area of heatsink areaOut = (math.pi *",
"to prevent ridiculously long variable names, all Nusselt Numbers are",
": overall axial length of heatsink overall diameter: outside diameter",
"cdoD) + (0.0388 * cdoD**2)) * math.pow(RayleighNbrFinSpacing, 0.25)) nnInFD =",
"-n) + math.pow(nnInFD, -n), (-1/n) ) * (areaIn/areaHS) ) self.nn",
"areaHS) ) if 0.1 <= (self.finThickness * self.numberOfFins / self.overallDiameter)",
"cdoD**2)) * math.pow(RayleighNbrFinSpacing, 0.25)) + (0.0516 + (0.0154 * cdoD)",
"(2 * finRadius) self.ambAirTemp = ambAirTemp # degrees kelvin self.maxJunctionTemp",
"(0.0792 * cdoD**3)) * RayleighNbrFinSpacing) n = 1 self.nnIn =",
"nn = Nusselt Number nn0 = Nusselt Number 0 (Diffusive",
"self.finSpacing = finSpacing # in meters self.finRadius = finRadius #",
"/ self.overallDiameter))) * math.pow(RayleighNbrFinSpacing, 0.25) * (areaOut/areaHS) ) if (0.1",
"(meters^2) / seconds # Volumetric coefficient of thermal expansion beta",
"expansion beta = aluminium.expansionCoefficient # 1/kelvin heatsinkSurfaceTemp = # TODO",
"= 15.52 * 10**(-6) # meter^2/second deltaT = heatsinkSurfaceTemp -",
"areaIn + areaOut # meter^2 RayleighNbrFinSpacing = ((const.g * beta",
"* RayleighNbrFinSpacing) n = 1 self.nnIn = (math.pow(math.pow(nnInT, -n) +",
"cdoD**2)) * math.pow(RayleighNbrFinSpacing, 0.25)) nnInFD = (((0.0323 - (0.0517 *",
"representations of heatsinks.\"\"\" import math from scipy import constants as",
"pressure at 25C kinematicViscosity = 15.52 * 10**(-6) # meter^2/second",
"(-1/n) ) * (areaIn/areaHS) ) self.nn = (self.nnIn + self.nnOut",
"heatsinkLength : overall axial length of heatsink overall diameter: outside",
"# meter^2 RayleighNbrFinSpacing = ((const.g * beta * deltaT *",
"= Nusselt Number 0 (Diffusive Limit) nnOut = Nusselt Number",
"(0.0516 + (0.0154 * cdoD) - (0.0433 * cdoD**2) +",
"temperature difference between surface temp of heatsink and ambient air",
"(self.nnIn + self.nnOut + self.nn0) super(Child, self).__init__(material, self.__name__) \"\"\" Nusselt",
"# in meters self.numberOfFins = numberofFins self.heatsinkLength = ((self.finThickness *",
"/ 2) + (self.numberOfFins * self.overallDiameter * self.finThickness))) # meter^2",
"deltaT * self.finSpacing**4) / (kinematicViscosity * alpha * self.overallDiameter)) RayleighNbrOverallDiameter",
"(self.finThickness * self.numberOfFins / self.overallDiameter) <= 8: self.nnOut = ((0.499",
"NOTE: all models are based off of the finSpacing variable",
"# in meters self.finThickness = finThickness # in meters self.cylinderDiameter",
"+ self.nnOut + self.nn0) super(Child, self).__init__(material, self.__name__) \"\"\" Nusselt number",
"meter^2/second deltaT = heatsinkSurfaceTemp - ambAirTemp # kelvin hLoD =",
"kinematicViscosity = 15.52 * 10**(-6) # meter^2/second deltaT = heatsinkSurfaceTemp",
"cylinder heatsinkLength : overall axial length of heatsink overall diameter:",
"(self.numberOfFins - 1) * oneChannelArea # meter^2 # outer surface",
"= finSpacing (meters) Ahs = Area of heatsink (meter^2) deltaT",
"self.numberOfFins / self.overallDiameter) <= 8: self.nnOut = ((0.499 - (0.026",
") self.nn = (self.nnIn + self.nnOut + self.nn0) super(Child, self).__init__(material,",
"self.nnOut = ((0.499 - (0.026 * math.log(self.finThickness * self.numberOfFins /",
"temp. k = thermal conductivity of material (Watts / (meter",
"* 10**(-6) # meter^2/second deltaT = heatsinkSurfaceTemp - ambAirTemp #",
"if 0.1 <= hLoD <= 8: self.nn0 = ((3.36 +",
"are abbreviated as follows: nn = Nusselt Number nn0 =",
"+ (0.0516 + (0.0154 * cdoD) - (0.0433 * cdoD**2)",
"- (0.0433 * cdoD**2) + (0.0792 * cdoD**3)) * RayleighNbrFinSpacing)",
"fins. \"\"\" self.finSpacing = finSpacing # in meters self.finRadius =",
"* finRadius) self.ambAirTemp = ambAirTemp # degrees kelvin self.maxJunctionTemp =",
"(((self.overallDiameter**2 - self.cylinderDiameter**2) / 2) + (self.cylinderDiameter * self.finSpacing))) #",
"self.heatsinkLength = ((self.finThickness * self.numberOfFins) + ((self.numberOfFins - 1) *",
"of heatsink (meter^2) deltaT = temperature difference between surface temp",
"Nusselt Number 0 (Diffusive Limit) nnOut = Nusselt Number for",
"ambAirTemp, maxJunctionTemp, maxSurfaceTemp): \"\"\" Init remainder of class variables. NOTE:",
"+ (0.0792 * cdoD**3)) * RayleighNbrFinSpacing) n = 1 self.nnIn",
"at atmospheric pressure at 25C kinematicViscosity = 15.52 * 10**(-6)",
"areaOut = (math.pi * (((self.overallDiameter**2) / 2) + (self.numberOfFins *",
": gap between adjacent fins finRadius : radius of fin",
"* (((self.overallDiameter**2) / 2) + self.overallDiameter * self.heatsinkLength)) # meter^2",
"cylinderDiameter, numberOfFins, ambAirTemp, maxJunctionTemp, maxSurfaceTemp): \"\"\" Init remainder of class",
"for outer surfaces nnIn = Nusselt Number for inner surfaces",
"(Watts) b = finSpacing (meters) Ahs = Area of heatsink",
"* math.pow(RayleighNbrFinSpacing, 0.25) * (areaOut/areaHS) ) if (0.1 <= cdoD",
"A Heatsink. Extended by form factor subclasses \"\"\" def __init__(self,",
"TODO kelvin # at atmospheric pressure at 25C kinematicViscosity =",
"between adjacent fins finRadius : radius of fin minus central",
"-n), (-1/n) ) * (areaIn/areaHS) ) self.nn = (self.nnIn +",
"\"\"\" def __init__(self, material, configuration): \"\"\"Init material and configuration variables.\"\"\"",
"Nusselt Number for outer surfaces nnIn = Nusselt Number for",
"10**5): nnInT = ((0.573-(0.184 * cdoD) + (0.0388 * cdoD**2))",
"* alpha * self.overallDiameter)) RayleighNbrOverallDiameter = ((const.g * beta *",
"+ self.nn0) super(Child, self).__init__(material, self.__name__) \"\"\" Nusselt number = (Qconv",
"+ (0.0388 * cdoD**2)) * math.pow(RayleighNbrFinSpacing, 0.25)) nnInFD = (((0.0323",
"areaHS = areaIn + areaOut # meter^2 RayleighNbrFinSpacing = ((const.g",
"b) / (Ahs deltaT k) Qconv = heat flow rate",
"outer surface area of heatsink areaOut = (math.pi * (((self.overallDiameter**2)",
"the simplified model for calculation efficiency. finSpacing : gap between",
"= maxSurfaceTemp \"\"\" NOTE: in order to prevent ridiculously long",
"abbreviated as follows: nn = Nusselt Number nn0 = Nusselt",
"* self.finThickness))) # meter^2 # overall area of heatsink areaHS",
"(0.087 * hLoD)) * math.sqrt(areaCC) * (self.finSpacing / areaHS) )",
"# in meters self.cylinderDiameter = cylinderDiameter # in meters self.numberOfFins",
"maxSurfaceTemp \"\"\" NOTE: in order to prevent ridiculously long variable",
"gap between adjacent fins finRadius : radius of fin minus",
"including fins. \"\"\" self.finSpacing = finSpacing # in meters self.finRadius",
"# meter^2 # outer surface area of heatsink areaOut =",
"heatsink areaOut = (math.pi * (((self.overallDiameter**2) / 2) + (self.numberOfFins",
"RayleighNbrOverallDiameter <= 2.3 * 10**5): nnInT = ((0.573-(0.184 * cdoD)",
"self.overallDiameter cDoD = self.cylinderDiameter / self.overallDiameter oneChannelArea = (math.pi *",
"n = 1 self.nnIn = (math.pow(math.pow(nnInT, -n) + math.pow(nnInFD, -n),",
"((self.finThickness * self.numberOfFins) + ((self.numberOfFins - 1) * self.finSpacing)) self.overallDiameter",
"depth) finThickness : thickness of individual fin cylinderDiameter: diameter of",
"1) * self.finSpacing)) self.overallDiameter = self.cylinderDiameter + (2 * finRadius)",
"self.numberOfFins / self.overallDiameter))) * math.pow(RayleighNbrFinSpacing, 0.25) * (areaOut/areaHS) ) if",
"* math.pow(RayleighNbrFinSpacing, 0.25)) nnInFD = (((0.0323 - (0.0517 * cdoD)",
"cdoD) - (0.0433 * cdoD**2) + (0.0792 * cdoD**3)) *",
"# meter^2 # inner surface area of heatsink areaIn =",
"import math from scipy import constants as const from materials",
"material, finSpacing, finRadius, finThickness, cylinderDiameter, numberOfFins, ambAirTemp, maxJunctionTemp, maxSurfaceTemp): \"\"\"",
"NOTE: in order to prevent ridiculously long variable names, all",
"variables.\"\"\" self.material = material self.configuration = configuration class CylindricalAnnularFin(Heatsink): \"\"\"Extend",
"\"\"\" Nusselt number = (Qconv * b) / (Ahs deltaT",
"Aluminium_6063 as aluminium class Heatsink: \"\"\" A Heatsink. Extended by",
"= 1 self.nnIn = (math.pow(math.pow(nnInT, -n) + math.pow(nnInFD, -n), (-1/n)",
"\"\"\" self.finSpacing = finSpacing # in meters self.finRadius = finRadius",
"\"\"\"Init material and configuration variables.\"\"\" self.material = material self.configuration =",
"Init remainder of class variables. NOTE: all models are based",
"if (0.1 <= cdoD <= 8) and (2.9 * 10**4",
"self).__init__(material, self.__name__) \"\"\" Nusselt number = (Qconv * b) /",
"= Area of heatsink (meter^2) deltaT = temperature difference between",
"overall area of heatsink areaHS = areaIn + areaOut #",
"ambient air temp. k = thermal conductivity of material (Watts",
"/ 2) + (self.cylinderDiameter * self.finSpacing))) # area of circumscribed",
"of heatsinks.\"\"\" import math from scipy import constants as const",
"heatsink.\"\"\" def __init__(self, material, finSpacing, finRadius, finThickness, cylinderDiameter, numberOfFins, ambAirTemp,",
"# at atmospheric pressure at 25C kinematicViscosity = 15.52 *",
"= maxJunctionTemp self.maxSurfaceTemp = maxSurfaceTemp \"\"\" NOTE: in order to",
"= (math.pi * (((self.overallDiameter**2 - self.cylinderDiameter**2) / 2) + (self.cylinderDiameter",
"prevent ridiculously long variable names, all Nusselt Numbers are abbreviated",
"self.material = material self.configuration = configuration class CylindricalAnnularFin(Heatsink): \"\"\"Extend base",
"variable names, all Nusselt Numbers are abbreviated as follows: nn",
"maxJunctionTemp, maxSurfaceTemp): \"\"\" Init remainder of class variables. NOTE: all",
"nnInT = ((0.573-(0.184 * cdoD) + (0.0388 * cdoD**2)) *",
"class with a cylindrical annular fin heatsink.\"\"\" def __init__(self, material,",
"and (2.9 * 10**4 <= RayleighNbrOverallDiameter <= 2.3 * 10**5):",
"heatsink (meter^2) deltaT = temperature difference between surface temp of",
"= thermal conductivity of material (Watts / (meter kelvin)) \"\"\"",
"= # TODO kelvin # at atmospheric pressure at 25C",
"15.52 * 10**(-6) # meter^2/second deltaT = heatsinkSurfaceTemp - ambAirTemp",
"self.heatsinkLength / self.overallDiameter cDoD = self.cylinderDiameter / self.overallDiameter oneChannelArea =",
"overall diameter: outside diameter of heatsink including fins. \"\"\" self.finSpacing",
"from materials import Aluminium_6063 as aluminium class Heatsink: \"\"\" A",
"# area of circumscribed cylinder areaCC = (math.pi * (((self.overallDiameter**2)",
"support cylinder (alternatively, fin depth) finThickness : thickness of individual",
"RayleighNbrFinSpacing) n = 1 self.nnIn = (math.pow(math.pow(nnInT, -n) + math.pow(nnInFD,",
"k) Qconv = heat flow rate by convection (Watts) b",
"inner surfaces nnInT = Nusselt Number for the thin boundry",
"(math.pow(math.pow(nnInT, -n) + math.pow(nnInFD, -n), (-1/n) ) * (areaIn/areaHS) )",
"hLoD = self.heatsinkLength / self.overallDiameter cDoD = self.cylinderDiameter / self.overallDiameter",
"<= cdoD <= 8) and (2.9 * 10**4 <= RayleighNbrOverallDiameter",
"cdoD) + (0.11 * cdoD**2)) * math.pow(RayleighNbrFinSpacing, 0.25)) + (0.0516",
"* cdoD) - (0.0433 * cdoD**2) + (0.0792 * cdoD**3))",
"import constants as const from materials import Aluminium_6063 as aluminium",
"outer surfaces nnIn = Nusselt Number for inner surfaces nnInT",
"* oneChannelArea # meter^2 # outer surface area of heatsink",
"= Nusselt Number nn0 = Nusselt Number 0 (Diffusive Limit)",
"= self.cylinderDiameter + (2 * finRadius) self.ambAirTemp = ambAirTemp #",
"developed regime inner surface \"\"\" # thermal diffusivity of air",
"meter^2 RayleighNbrFinSpacing = ((const.g * beta * deltaT * self.finSpacing**4)",
"k = thermal conductivity of material (Watts / (meter kelvin))",
"diameter of support cylinder heatsinkLength : overall axial length of",
"* beta * deltaT * self.overallDiameter**3) / (kinematicViscosity * alpha))",
"* (((self.overallDiameter**2 - self.cylinderDiameter**2) / 2) + (self.cylinderDiameter * self.finSpacing)))",
"((3.36 + (0.087 * hLoD)) * math.sqrt(areaCC) * (self.finSpacing /",
"class Heatsink: \"\"\" A Heatsink. Extended by form factor subclasses",
"ridiculously long variable names, all Nusselt Numbers are abbreviated as",
"regime inner surface \"\"\" # thermal diffusivity of air at",
"hLoD <= 8: self.nn0 = ((3.36 + (0.087 * hLoD))",
"surface temp of heatsink and ambient air temp. k =",
"10**4 <= RayleighNbrOverallDiameter <= 2.3 * 10**5): nnInT = ((0.573-(0.184",
"Nusselt Numbers are abbreviated as follows: nn = Nusselt Number",
"individual fin cylinderDiameter: diameter of support cylinder heatsinkLength : overall",
"finRadius # in meters self.finThickness = finThickness # in meters",
"Number for fully developed regime inner surface \"\"\" # thermal",
"based off of the finSpacing variable NOTE: using the simplified",
"* self.numberOfFins) + ((self.numberOfFins - 1) * self.finSpacing)) self.overallDiameter =",
"import Aluminium_6063 as aluminium class Heatsink: \"\"\" A Heatsink. Extended",
"math.pow(RayleighNbrFinSpacing, 0.25)) nnInFD = (((0.0323 - (0.0517 * cdoD) +",
"* self.overallDiameter)) RayleighNbrOverallDiameter = ((const.g * beta * deltaT *",
"+ ((self.numberOfFins - 1) * self.finSpacing)) self.overallDiameter = self.cylinderDiameter +",
"(math.pi * (((self.overallDiameter**2 - self.cylinderDiameter**2) / 2) + (self.cylinderDiameter *",
"(0.026 * math.log(self.finThickness * self.numberOfFins / self.overallDiameter))) * math.pow(RayleighNbrFinSpacing, 0.25)",
"self.overallDiameter**3) / (kinematicViscosity * alpha)) if 0.1 <= hLoD <=",
"8: self.nn0 = ((3.36 + (0.087 * hLoD)) * math.sqrt(areaCC)",
"self.nn0) super(Child, self).__init__(material, self.__name__) \"\"\" Nusselt number = (Qconv *",
"Nusselt Number for the thin boundry layer of inner surface",
"of heatsink areaIn = (self.numberOfFins - 1) * oneChannelArea #",
"self.numberOfFins) + ((self.numberOfFins - 1) * self.finSpacing)) self.overallDiameter = self.cylinderDiameter",
"surface area of heatsink areaIn = (self.numberOfFins - 1) *",
"if 0.1 <= (self.finThickness * self.numberOfFins / self.overallDiameter) <= 8:",
"all models are based off of the finSpacing variable NOTE:",
"2) + (self.cylinderDiameter * self.finSpacing))) # area of circumscribed cylinder",
"simplified model for calculation efficiency. finSpacing : gap between adjacent",
"class variables. NOTE: all models are based off of the",
"+ (self.numberOfFins * self.overallDiameter * self.finThickness))) # meter^2 # overall",
"at 25C alpha = 22.39 * 10**(-6) # (meters^2) /",
"* (((self.overallDiameter**2) / 2) + (self.numberOfFins * self.overallDiameter * self.finThickness)))",
"support cylinder heatsinkLength : overall axial length of heatsink overall",
"= ((0.499 - (0.026 * math.log(self.finThickness * self.numberOfFins / self.overallDiameter)))",
"# 1/kelvin heatsinkSurfaceTemp = # TODO kelvin # at atmospheric",
"names, all Nusselt Numbers are abbreviated as follows: nn =",
"<= 8) and (2.9 * 10**4 <= RayleighNbrOverallDiameter <= 2.3",
"(((0.0323 - (0.0517 * cdoD) + (0.11 * cdoD**2)) *",
"(areaIn/areaHS) ) self.nn = (self.nnIn + self.nnOut + self.nn0) super(Child,",
"from scipy import constants as const from materials import Aluminium_6063",
"nnInFD = Nusselt Number for fully developed regime inner surface",
"cylinder areaCC = (math.pi * (((self.overallDiameter**2) / 2) + self.overallDiameter",
"<= hLoD <= 8: self.nn0 = ((3.36 + (0.087 *",
"(0.0433 * cdoD**2) + (0.0792 * cdoD**3)) * RayleighNbrFinSpacing) n",
"self.cylinderDiameter = cylinderDiameter # in meters self.numberOfFins = numberofFins self.heatsinkLength",
"heatsinks.\"\"\" import math from scipy import constants as const from",
"of individual fin cylinderDiameter: diameter of support cylinder heatsinkLength :",
"self.numberOfFins = numberofFins self.heatsinkLength = ((self.finThickness * self.numberOfFins) + ((self.numberOfFins",
"Nusselt Number for inner surfaces nnInT = Nusselt Number for",
"= ((const.g * beta * deltaT * self.overallDiameter**3) / (kinematicViscosity",
"(0.0154 * cdoD) - (0.0433 * cdoD**2) + (0.0792 *",
"math.pow(RayleighNbrFinSpacing, 0.25)) + (0.0516 + (0.0154 * cdoD) - (0.0433",
"* self.finSpacing))) # area of circumscribed cylinder areaCC = (math.pi",
"((self.numberOfFins - 1) * self.finSpacing)) self.overallDiameter = self.cylinderDiameter + (2",
"of heatsink overall diameter: outside diameter of heatsink including fins.",
"RayleighNbrFinSpacing = ((const.g * beta * deltaT * self.finSpacing**4) /",
"meter^2 # overall area of heatsink areaHS = areaIn +",
"= configuration class CylindricalAnnularFin(Heatsink): \"\"\"Extend base heatsink class with a",
"= (math.pi * (((self.overallDiameter**2) / 2) + (self.numberOfFins * self.overallDiameter",
"beta * deltaT * self.finSpacing**4) / (kinematicViscosity * alpha *",
"areaOut # meter^2 RayleighNbrFinSpacing = ((const.g * beta * deltaT",
"maxJunctionTemp self.maxSurfaceTemp = maxSurfaceTemp \"\"\" NOTE: in order to prevent",
"area of heatsink areaOut = (math.pi * (((self.overallDiameter**2) / 2)",
"+ (self.cylinderDiameter * self.finSpacing))) # area of circumscribed cylinder areaCC",
"adjacent fins finRadius : radius of fin minus central support",
"self.finSpacing**4) / (kinematicViscosity * alpha * self.overallDiameter)) RayleighNbrOverallDiameter = ((const.g",
"heatsink areaHS = areaIn + areaOut # meter^2 RayleighNbrFinSpacing =",
"heatsink areaIn = (self.numberOfFins - 1) * oneChannelArea # meter^2",
"areaCC = (math.pi * (((self.overallDiameter**2) / 2) + self.overallDiameter *",
"self.overallDiameter) <= 8: self.nnOut = ((0.499 - (0.026 * math.log(self.finThickness",
"Nusselt number = (Qconv * b) / (Ahs deltaT k)",
"alpha)) if 0.1 <= hLoD <= 8: self.nn0 = ((3.36",
"((0.573-(0.184 * cdoD) + (0.0388 * cdoD**2)) * math.pow(RayleighNbrFinSpacing, 0.25))",
"* math.pow(RayleighNbrFinSpacing, 0.25)) + (0.0516 + (0.0154 * cdoD) -",
"(meter^2) deltaT = temperature difference between surface temp of heatsink",
"finRadius, finThickness, cylinderDiameter, numberOfFins, ambAirTemp, maxJunctionTemp, maxSurfaceTemp): \"\"\" Init remainder",
"degrees kelvin self.maxJunctionTemp = maxJunctionTemp self.maxSurfaceTemp = maxSurfaceTemp \"\"\" NOTE:",
"- 1) * self.finSpacing)) self.overallDiameter = self.cylinderDiameter + (2 *",
"the finSpacing variable NOTE: using the simplified model for calculation",
"def __init__(self, material, configuration): \"\"\"Init material and configuration variables.\"\"\" self.material",
"<gh_stars>1-10 \"\"\"Class representations of heatsinks.\"\"\" import math from scipy import",
"= Nusselt Number for outer surfaces nnIn = Nusselt Number",
"(kinematicViscosity * alpha)) if 0.1 <= hLoD <= 8: self.nn0",
"8) and (2.9 * 10**4 <= RayleighNbrOverallDiameter <= 2.3 *",
"surface nnInFD = Nusselt Number for fully developed regime inner",
"= heat flow rate by convection (Watts) b = finSpacing",
"self.ambAirTemp = ambAirTemp # degrees kelvin self.maxJunctionTemp = maxJunctionTemp self.maxSurfaceTemp",
"diameter of heatsink including fins. \"\"\" self.finSpacing = finSpacing #",
"= finRadius # in meters self.finThickness = finThickness # in",
"\"\"\" # thermal diffusivity of air at atmospheric pressure at",
"kelvin hLoD = self.heatsinkLength / self.overallDiameter cDoD = self.cylinderDiameter /",
"in order to prevent ridiculously long variable names, all Nusselt",
"self.overallDiameter)) RayleighNbrOverallDiameter = ((const.g * beta * deltaT * self.overallDiameter**3)",
"at atmospheric pressure at 25C alpha = 22.39 * 10**(-6)",
"deltaT k) Qconv = heat flow rate by convection (Watts)",
"numberOfFins, ambAirTemp, maxJunctionTemp, maxSurfaceTemp): \"\"\" Init remainder of class variables.",
"def __init__(self, material, finSpacing, finRadius, finThickness, cylinderDiameter, numberOfFins, ambAirTemp, maxJunctionTemp,",
"Qconv = heat flow rate by convection (Watts) b =",
"are based off of the finSpacing variable NOTE: using the",
"\"\"\"Class representations of heatsinks.\"\"\" import math from scipy import constants",
"form factor subclasses \"\"\" def __init__(self, material, configuration): \"\"\"Init material",
"+ (2 * finRadius) self.ambAirTemp = ambAirTemp # degrees kelvin",
"variables. NOTE: all models are based off of the finSpacing",
"nnIn = Nusselt Number for inner surfaces nnInT = Nusselt",
"= Nusselt Number for the thin boundry layer of inner",
"+ areaOut # meter^2 RayleighNbrFinSpacing = ((const.g * beta *",
"annular fin heatsink.\"\"\" def __init__(self, material, finSpacing, finRadius, finThickness, cylinderDiameter,",
"by convection (Watts) b = finSpacing (meters) Ahs = Area",
"as const from materials import Aluminium_6063 as aluminium class Heatsink:",
"in meters self.numberOfFins = numberofFins self.heatsinkLength = ((self.finThickness * self.numberOfFins)",
"deltaT * self.overallDiameter**3) / (kinematicViscosity * alpha)) if 0.1 <=",
"= (self.nnIn + self.nnOut + self.nn0) super(Child, self).__init__(material, self.__name__) \"\"\"",
"heatsink overall diameter: outside diameter of heatsink including fins. \"\"\"",
"materials import Aluminium_6063 as aluminium class Heatsink: \"\"\" A Heatsink.",
"RayleighNbrOverallDiameter = ((const.g * beta * deltaT * self.overallDiameter**3) /",
"\"\"\" Init remainder of class variables. NOTE: all models are",
"* deltaT * self.finSpacing**4) / (kinematicViscosity * alpha * self.overallDiameter))",
"maxSurfaceTemp): \"\"\" Init remainder of class variables. NOTE: all models",
"* cdoD) + (0.0388 * cdoD**2)) * math.pow(RayleighNbrFinSpacing, 0.25)) nnInFD",
"nnInT = Nusselt Number for the thin boundry layer of",
"self.cylinderDiameter + (2 * finRadius) self.ambAirTemp = ambAirTemp # degrees",
"= ((0.573-(0.184 * cdoD) + (0.0388 * cdoD**2)) * math.pow(RayleighNbrFinSpacing,",
"configuration class CylindricalAnnularFin(Heatsink): \"\"\"Extend base heatsink class with a cylindrical",
"deltaT = heatsinkSurfaceTemp - ambAirTemp # kelvin hLoD = self.heatsinkLength",
"(Ahs deltaT k) Qconv = heat flow rate by convection",
"1/kelvin heatsinkSurfaceTemp = # TODO kelvin # at atmospheric pressure",
"# Volumetric coefficient of thermal expansion beta = aluminium.expansionCoefficient #",
"with a cylindrical annular fin heatsink.\"\"\" def __init__(self, material, finSpacing,",
"Area of heatsink (meter^2) deltaT = temperature difference between surface",
"class CylindricalAnnularFin(Heatsink): \"\"\"Extend base heatsink class with a cylindrical annular",
"and ambient air temp. k = thermal conductivity of material",
"\"\"\" NOTE: in order to prevent ridiculously long variable names,",
"calculation efficiency. finSpacing : gap between adjacent fins finRadius :",
"Numbers are abbreviated as follows: nn = Nusselt Number nn0",
"self.nnIn = (math.pow(math.pow(nnInT, -n) + math.pow(nnInFD, -n), (-1/n) ) *",
"convection (Watts) b = finSpacing (meters) Ahs = Area of",
"- 1) * oneChannelArea # meter^2 # outer surface area",
"= (Qconv * b) / (Ahs deltaT k) Qconv =",
"rate by convection (Watts) b = finSpacing (meters) Ahs =",
"of inner surface nnInFD = Nusselt Number for fully developed",
"/ 2) + self.overallDiameter * self.heatsinkLength)) # meter^2 # inner",
"cdoD**2) + (0.0792 * cdoD**3)) * RayleighNbrFinSpacing) n = 1",
"overall axial length of heatsink overall diameter: outside diameter of",
"in meters self.finRadius = finRadius # in meters self.finThickness =",
"(meters) Ahs = Area of heatsink (meter^2) deltaT = temperature",
"order to prevent ridiculously long variable names, all Nusselt Numbers",
"fin depth) finThickness : thickness of individual fin cylinderDiameter: diameter",
"diffusivity of air at atmospheric pressure at 25C alpha =",
"meters self.finRadius = finRadius # in meters self.finThickness = finThickness",
"finThickness # in meters self.cylinderDiameter = cylinderDiameter # in meters",
"(math.pi * (((self.overallDiameter**2) / 2) + (self.numberOfFins * self.overallDiameter *",
"finSpacing # in meters self.finRadius = finRadius # in meters",
"((const.g * beta * deltaT * self.finSpacing**4) / (kinematicViscosity *",
"nnInFD = (((0.0323 - (0.0517 * cdoD) + (0.11 *",
") * (areaIn/areaHS) ) self.nn = (self.nnIn + self.nnOut +",
"* cdoD**2) + (0.0792 * cdoD**3)) * RayleighNbrFinSpacing) n =",
"const from materials import Aluminium_6063 as aluminium class Heatsink: \"\"\"",
"* (areaOut/areaHS) ) if (0.1 <= cdoD <= 8) and",
"= material self.configuration = configuration class CylindricalAnnularFin(Heatsink): \"\"\"Extend base heatsink",
"<= 8: self.nn0 = ((3.36 + (0.087 * hLoD)) *",
"= Nusselt Number for fully developed regime inner surface \"\"\"",
"Nusselt Number for fully developed regime inner surface \"\"\" #",
"scipy import constants as const from materials import Aluminium_6063 as",
"efficiency. finSpacing : gap between adjacent fins finRadius : radius",
"math.sqrt(areaCC) * (self.finSpacing / areaHS) ) if 0.1 <= (self.finThickness",
"+ (0.11 * cdoD**2)) * math.pow(RayleighNbrFinSpacing, 0.25)) + (0.0516 +",
"self.configuration = configuration class CylindricalAnnularFin(Heatsink): \"\"\"Extend base heatsink class with",
"of heatsink areaOut = (math.pi * (((self.overallDiameter**2) / 2) +",
"beta * deltaT * self.overallDiameter**3) / (kinematicViscosity * alpha)) if",
"0 (Diffusive Limit) nnOut = Nusselt Number for outer surfaces",
"* math.sqrt(areaCC) * (self.finSpacing / areaHS) ) if 0.1 <=",
"ambAirTemp # degrees kelvin self.maxJunctionTemp = maxJunctionTemp self.maxSurfaceTemp = maxSurfaceTemp",
"factor subclasses \"\"\" def __init__(self, material, configuration): \"\"\"Init material and",
"heat flow rate by convection (Watts) b = finSpacing (meters)",
"# meter^2 # overall area of heatsink areaHS = areaIn",
"/ (kinematicViscosity * alpha * self.overallDiameter)) RayleighNbrOverallDiameter = ((const.g *",
"= Nusselt Number for inner surfaces nnInT = Nusselt Number",
"22.39 * 10**(-6) # (meters^2) / seconds # Volumetric coefficient",
": thickness of individual fin cylinderDiameter: diameter of support cylinder",
"Extended by form factor subclasses \"\"\" def __init__(self, material, configuration):",
"fins finRadius : radius of fin minus central support cylinder",
"super(Child, self).__init__(material, self.__name__) \"\"\" Nusselt number = (Qconv * b)",
"/ self.overallDiameter) <= 8: self.nnOut = ((0.499 - (0.026 *",
"* self.numberOfFins / self.overallDiameter) <= 8: self.nnOut = ((0.499 -",
"8: self.nnOut = ((0.499 - (0.026 * math.log(self.finThickness * self.numberOfFins",
"diameter: outside diameter of heatsink including fins. \"\"\" self.finSpacing =",
"temp of heatsink and ambient air temp. k = thermal",
"constants as const from materials import Aluminium_6063 as aluminium class",
"a cylindrical annular fin heatsink.\"\"\" def __init__(self, material, finSpacing, finRadius,",
"finSpacing (meters) Ahs = Area of heatsink (meter^2) deltaT =",
"/ self.overallDiameter cDoD = self.cylinderDiameter / self.overallDiameter oneChannelArea = (math.pi",
"deltaT = temperature difference between surface temp of heatsink and",
"* (areaIn/areaHS) ) self.nn = (self.nnIn + self.nnOut + self.nn0)",
"heatsinkSurfaceTemp - ambAirTemp # kelvin hLoD = self.heatsinkLength / self.overallDiameter",
"* cdoD**2)) * math.pow(RayleighNbrFinSpacing, 0.25)) nnInFD = (((0.0323 - (0.0517",
"self.overallDiameter = self.cylinderDiameter + (2 * finRadius) self.ambAirTemp = ambAirTemp",
"self.finThickness))) # meter^2 # overall area of heatsink areaHS =",
"Ahs = Area of heatsink (meter^2) deltaT = temperature difference",
"* cdoD**3)) * RayleighNbrFinSpacing) n = 1 self.nnIn = (math.pow(math.pow(nnInT,",
"for the thin boundry layer of inner surface nnInFD =",
"= (self.numberOfFins - 1) * oneChannelArea # meter^2 # outer",
"# in meters self.finRadius = finRadius # in meters self.finThickness",
") if (0.1 <= cdoD <= 8) and (2.9 *",
"self.overallDiameter))) * math.pow(RayleighNbrFinSpacing, 0.25) * (areaOut/areaHS) ) if (0.1 <=",
"Heatsink: \"\"\" A Heatsink. Extended by form factor subclasses \"\"\"",
"\"\"\" A Heatsink. Extended by form factor subclasses \"\"\" def",
"self.overallDiameter * self.heatsinkLength)) # meter^2 # inner surface area of",
"radius of fin minus central support cylinder (alternatively, fin depth)",
"pressure at 25C alpha = 22.39 * 10**(-6) # (meters^2)",
"material self.configuration = configuration class CylindricalAnnularFin(Heatsink): \"\"\"Extend base heatsink class",
"of heatsink including fins. \"\"\" self.finSpacing = finSpacing # in",
"nn0 = Nusselt Number 0 (Diffusive Limit) nnOut = Nusselt",
"kelvin # at atmospheric pressure at 25C kinematicViscosity = 15.52",
"self.overallDiameter oneChannelArea = (math.pi * (((self.overallDiameter**2 - self.cylinderDiameter**2) / 2)",
"self.nn0 = ((3.36 + (0.087 * hLoD)) * math.sqrt(areaCC) *",
"= (((0.0323 - (0.0517 * cdoD) + (0.11 * cdoD**2))",
"(self.finSpacing / areaHS) ) if 0.1 <= (self.finThickness * self.numberOfFins",
"cDoD = self.cylinderDiameter / self.overallDiameter oneChannelArea = (math.pi * (((self.overallDiameter**2",
"(0.1 <= cdoD <= 8) and (2.9 * 10**4 <=",
"difference between surface temp of heatsink and ambient air temp.",
"/ (kinematicViscosity * alpha)) if 0.1 <= hLoD <= 8:",
"fin minus central support cylinder (alternatively, fin depth) finThickness :",
"area of heatsink areaIn = (self.numberOfFins - 1) * oneChannelArea",
"= ((const.g * beta * deltaT * self.finSpacing**4) / (kinematicViscosity",
"of circumscribed cylinder areaCC = (math.pi * (((self.overallDiameter**2) / 2)",
"hLoD)) * math.sqrt(areaCC) * (self.finSpacing / areaHS) ) if 0.1",
"= finSpacing # in meters self.finRadius = finRadius # in",
"((0.499 - (0.026 * math.log(self.finThickness * self.numberOfFins / self.overallDiameter))) *",
"= 22.39 * 10**(-6) # (meters^2) / seconds # Volumetric",
"aluminium.expansionCoefficient # 1/kelvin heatsinkSurfaceTemp = # TODO kelvin # at",
"finThickness, cylinderDiameter, numberOfFins, ambAirTemp, maxJunctionTemp, maxSurfaceTemp): \"\"\" Init remainder of",
"cylinderDiameter # in meters self.numberOfFins = numberofFins self.heatsinkLength = ((self.finThickness",
"inner surface nnInFD = Nusselt Number for fully developed regime",
"/ seconds # Volumetric coefficient of thermal expansion beta =",
"(self.cylinderDiameter * self.finSpacing))) # area of circumscribed cylinder areaCC =",
"* self.heatsinkLength)) # meter^2 # inner surface area of heatsink",
"# overall area of heatsink areaHS = areaIn + areaOut",
"as follows: nn = Nusselt Number nn0 = Nusselt Number",
"surfaces nnIn = Nusselt Number for inner surfaces nnInT =",
"model for calculation efficiency. finSpacing : gap between adjacent fins",
"+ (0.0154 * cdoD) - (0.0433 * cdoD**2) + (0.0792",
"meter^2 # outer surface area of heatsink areaOut = (math.pi",
"NOTE: using the simplified model for calculation efficiency. finSpacing :",
"math from scipy import constants as const from materials import",
"in meters self.cylinderDiameter = cylinderDiameter # in meters self.numberOfFins =",
"at 25C kinematicViscosity = 15.52 * 10**(-6) # meter^2/second deltaT",
"<= 2.3 * 10**5): nnInT = ((0.573-(0.184 * cdoD) +",
"thermal expansion beta = aluminium.expansionCoefficient # 1/kelvin heatsinkSurfaceTemp = #",
"= (math.pow(math.pow(nnInT, -n) + math.pow(nnInFD, -n), (-1/n) ) * (areaIn/areaHS)",
"25C alpha = 22.39 * 10**(-6) # (meters^2) / seconds",
"configuration): \"\"\"Init material and configuration variables.\"\"\" self.material = material self.configuration",
"b = finSpacing (meters) Ahs = Area of heatsink (meter^2)",
"(Diffusive Limit) nnOut = Nusselt Number for outer surfaces nnIn",
"* self.overallDiameter**3) / (kinematicViscosity * alpha)) if 0.1 <= hLoD",
"self.overallDiameter * self.finThickness))) # meter^2 # overall area of heatsink",
"- (0.026 * math.log(self.finThickness * self.numberOfFins / self.overallDiameter))) * math.pow(RayleighNbrFinSpacing,",
"# thermal diffusivity of air at atmospheric pressure at 25C",
"variable NOTE: using the simplified model for calculation efficiency. finSpacing",
"finRadius : radius of fin minus central support cylinder (alternatively,",
"+ (0.087 * hLoD)) * math.sqrt(areaCC) * (self.finSpacing / areaHS)",
"thermal diffusivity of air at atmospheric pressure at 25C alpha",
"atmospheric pressure at 25C alpha = 22.39 * 10**(-6) #",
"as aluminium class Heatsink: \"\"\" A Heatsink. Extended by form",
"(areaOut/areaHS) ) if (0.1 <= cdoD <= 8) and (2.9",
"(((self.overallDiameter**2) / 2) + (self.numberOfFins * self.overallDiameter * self.finThickness))) #",
"surface area of heatsink areaOut = (math.pi * (((self.overallDiameter**2) /",
"* beta * deltaT * self.finSpacing**4) / (kinematicViscosity * alpha",
"self.__name__) \"\"\" Nusselt number = (Qconv * b) / (Ahs",
"self.finThickness = finThickness # in meters self.cylinderDiameter = cylinderDiameter #",
"+ self.overallDiameter * self.heatsinkLength)) # meter^2 # inner surface area",
"nnOut = Nusselt Number for outer surfaces nnIn = Nusselt",
"finSpacing : gap between adjacent fins finRadius : radius of",
"* alpha)) if 0.1 <= hLoD <= 8: self.nn0 =",
"self.nnOut + self.nn0) super(Child, self).__init__(material, self.__name__) \"\"\" Nusselt number =",
"heatsink and ambient air temp. k = thermal conductivity of",
"finRadius) self.ambAirTemp = ambAirTemp # degrees kelvin self.maxJunctionTemp = maxJunctionTemp",
"cdoD**3)) * RayleighNbrFinSpacing) n = 1 self.nnIn = (math.pow(math.pow(nnInT, -n)",
"= self.heatsinkLength / self.overallDiameter cDoD = self.cylinderDiameter / self.overallDiameter oneChannelArea",
"0.1 <= (self.finThickness * self.numberOfFins / self.overallDiameter) <= 8: self.nnOut",
"* self.finSpacing)) self.overallDiameter = self.cylinderDiameter + (2 * finRadius) self.ambAirTemp",
"fin heatsink.\"\"\" def __init__(self, material, finSpacing, finRadius, finThickness, cylinderDiameter, numberOfFins,",
"cdoD <= 8) and (2.9 * 10**4 <= RayleighNbrOverallDiameter <=",
"- (0.0517 * cdoD) + (0.11 * cdoD**2)) * math.pow(RayleighNbrFinSpacing,",
"Number for outer surfaces nnIn = Nusselt Number for inner",
"self.nn = (self.nnIn + self.nnOut + self.nn0) super(Child, self).__init__(material, self.__name__)",
"self.maxSurfaceTemp = maxSurfaceTemp \"\"\" NOTE: in order to prevent ridiculously",
"for inner surfaces nnInT = Nusselt Number for the thin",
"finSpacing, finRadius, finThickness, cylinderDiameter, numberOfFins, ambAirTemp, maxJunctionTemp, maxSurfaceTemp): \"\"\" Init",
"0.25)) + (0.0516 + (0.0154 * cdoD) - (0.0433 *",
"math.log(self.finThickness * self.numberOfFins / self.overallDiameter))) * math.pow(RayleighNbrFinSpacing, 0.25) * (areaOut/areaHS)",
"= areaIn + areaOut # meter^2 RayleighNbrFinSpacing = ((const.g *",
"= finThickness # in meters self.cylinderDiameter = cylinderDiameter # in",
"for fully developed regime inner surface \"\"\" # thermal diffusivity",
"of fin minus central support cylinder (alternatively, fin depth) finThickness",
"__init__(self, material, finSpacing, finRadius, finThickness, cylinderDiameter, numberOfFins, ambAirTemp, maxJunctionTemp, maxSurfaceTemp):",
"area of circumscribed cylinder areaCC = (math.pi * (((self.overallDiameter**2) /",
"= aluminium.expansionCoefficient # 1/kelvin heatsinkSurfaceTemp = # TODO kelvin #",
"material, configuration): \"\"\"Init material and configuration variables.\"\"\" self.material = material",
"area of heatsink areaHS = areaIn + areaOut # meter^2",
"inner surface area of heatsink areaIn = (self.numberOfFins - 1)",
"layer of inner surface nnInFD = Nusselt Number for fully",
"off of the finSpacing variable NOTE: using the simplified model",
"cylinder (alternatively, fin depth) finThickness : thickness of individual fin",
"self.cylinderDiameter / self.overallDiameter oneChannelArea = (math.pi * (((self.overallDiameter**2 - self.cylinderDiameter**2)",
"25C kinematicViscosity = 15.52 * 10**(-6) # meter^2/second deltaT =",
"circumscribed cylinder areaCC = (math.pi * (((self.overallDiameter**2) / 2) +",
"((const.g * beta * deltaT * self.overallDiameter**3) / (kinematicViscosity *",
"0.1 <= hLoD <= 8: self.nn0 = ((3.36 + (0.087",
"<= 8: self.nnOut = ((0.499 - (0.026 * math.log(self.finThickness *",
"* (self.finSpacing / areaHS) ) if 0.1 <= (self.finThickness *",
"heatsink class with a cylindrical annular fin heatsink.\"\"\" def __init__(self,",
"for calculation efficiency. finSpacing : gap between adjacent fins finRadius",
"= (math.pi * (((self.overallDiameter**2) / 2) + self.overallDiameter * self.heatsinkLength))",
"finSpacing variable NOTE: using the simplified model for calculation efficiency.",
"axial length of heatsink overall diameter: outside diameter of heatsink",
"of class variables. NOTE: all models are based off of",
"oneChannelArea # meter^2 # outer surface area of heatsink areaOut",
"* cdoD) + (0.11 * cdoD**2)) * math.pow(RayleighNbrFinSpacing, 0.25)) +",
"2.3 * 10**5): nnInT = ((0.573-(0.184 * cdoD) + (0.0388",
": radius of fin minus central support cylinder (alternatively, fin",
"Volumetric coefficient of thermal expansion beta = aluminium.expansionCoefficient # 1/kelvin",
"air at atmospheric pressure at 25C alpha = 22.39 *",
"self.finRadius = finRadius # in meters self.finThickness = finThickness #",
"10**(-6) # meter^2/second deltaT = heatsinkSurfaceTemp - ambAirTemp # kelvin",
"= ((self.finThickness * self.numberOfFins) + ((self.numberOfFins - 1) * self.finSpacing))",
"in meters self.finThickness = finThickness # in meters self.cylinderDiameter =",
"__init__(self, material, configuration): \"\"\"Init material and configuration variables.\"\"\" self.material =",
"models are based off of the finSpacing variable NOTE: using",
"meters self.finThickness = finThickness # in meters self.cylinderDiameter = cylinderDiameter",
"and configuration variables.\"\"\" self.material = material self.configuration = configuration class",
"configuration variables.\"\"\" self.material = material self.configuration = configuration class CylindricalAnnularFin(Heatsink):",
"surfaces nnInT = Nusselt Number for the thin boundry layer",
"* math.log(self.finThickness * self.numberOfFins / self.overallDiameter))) * math.pow(RayleighNbrFinSpacing, 0.25) *",
") if 0.1 <= (self.finThickness * self.numberOfFins / self.overallDiameter) <=",
"self.cylinderDiameter**2) / 2) + (self.cylinderDiameter * self.finSpacing))) # area of",
"thickness of individual fin cylinderDiameter: diameter of support cylinder heatsinkLength",
"- ambAirTemp # kelvin hLoD = self.heatsinkLength / self.overallDiameter cDoD",
"2) + (self.numberOfFins * self.overallDiameter * self.finThickness))) # meter^2 #",
"Number 0 (Diffusive Limit) nnOut = Nusselt Number for outer",
"coefficient of thermal expansion beta = aluminium.expansionCoefficient # 1/kelvin heatsinkSurfaceTemp",
"all Nusselt Numbers are abbreviated as follows: nn = Nusselt",
"Heatsink. Extended by form factor subclasses \"\"\" def __init__(self, material,",
"long variable names, all Nusselt Numbers are abbreviated as follows:",
"- self.cylinderDiameter**2) / 2) + (self.cylinderDiameter * self.finSpacing))) # area",
"(0.11 * cdoD**2)) * math.pow(RayleighNbrFinSpacing, 0.25)) + (0.0516 + (0.0154",
"(0.0517 * cdoD) + (0.11 * cdoD**2)) * math.pow(RayleighNbrFinSpacing, 0.25))",
"Number nn0 = Nusselt Number 0 (Diffusive Limit) nnOut =",
"of support cylinder heatsinkLength : overall axial length of heatsink",
"heatsinkSurfaceTemp = # TODO kelvin # at atmospheric pressure at",
"of the finSpacing variable NOTE: using the simplified model for",
"/ self.overallDiameter oneChannelArea = (math.pi * (((self.overallDiameter**2 - self.cylinderDiameter**2) /",
"number = (Qconv * b) / (Ahs deltaT k) Qconv",
"air temp. k = thermal conductivity of material (Watts /",
"* b) / (Ahs deltaT k) Qconv = heat flow",
"self.heatsinkLength)) # meter^2 # inner surface area of heatsink areaIn",
"= ((3.36 + (0.087 * hLoD)) * math.sqrt(areaCC) * (self.finSpacing",
"minus central support cylinder (alternatively, fin depth) finThickness : thickness",
"* deltaT * self.overallDiameter**3) / (kinematicViscosity * alpha)) if 0.1",
"= cylinderDiameter # in meters self.numberOfFins = numberofFins self.heatsinkLength =",
"kelvin self.maxJunctionTemp = maxJunctionTemp self.maxSurfaceTemp = maxSurfaceTemp \"\"\" NOTE: in",
"# kelvin hLoD = self.heatsinkLength / self.overallDiameter cDoD = self.cylinderDiameter",
"areaIn = (self.numberOfFins - 1) * oneChannelArea # meter^2 #",
"= temperature difference between surface temp of heatsink and ambient",
"# (meters^2) / seconds # Volumetric coefficient of thermal expansion",
"subclasses \"\"\" def __init__(self, material, configuration): \"\"\"Init material and configuration",
"# meter^2/second deltaT = heatsinkSurfaceTemp - ambAirTemp # kelvin hLoD",
"<= RayleighNbrOverallDiameter <= 2.3 * 10**5): nnInT = ((0.573-(0.184 *",
"of heatsink areaHS = areaIn + areaOut # meter^2 RayleighNbrFinSpacing",
"finThickness : thickness of individual fin cylinderDiameter: diameter of support",
"(Qconv * b) / (Ahs deltaT k) Qconv = heat",
"meters self.cylinderDiameter = cylinderDiameter # in meters self.numberOfFins = numberofFins",
"atmospheric pressure at 25C kinematicViscosity = 15.52 * 10**(-6) #",
"beta = aluminium.expansionCoefficient # 1/kelvin heatsinkSurfaceTemp = # TODO kelvin",
"math.pow(RayleighNbrFinSpacing, 0.25) * (areaOut/areaHS) ) if (0.1 <= cdoD <=",
"self.finSpacing))) # area of circumscribed cylinder areaCC = (math.pi *",
"* 10**5): nnInT = ((0.573-(0.184 * cdoD) + (0.0388 *",
"math.pow(nnInFD, -n), (-1/n) ) * (areaIn/areaHS) ) self.nn = (self.nnIn",
"fully developed regime inner surface \"\"\" # thermal diffusivity of",
"* cdoD**2)) * math.pow(RayleighNbrFinSpacing, 0.25)) + (0.0516 + (0.0154 *",
"boundry layer of inner surface nnInFD = Nusselt Number for",
"1 self.nnIn = (math.pow(math.pow(nnInT, -n) + math.pow(nnInFD, -n), (-1/n) )",
"of thermal expansion beta = aluminium.expansionCoefficient # 1/kelvin heatsinkSurfaceTemp =",
"heatsink including fins. \"\"\" self.finSpacing = finSpacing # in meters",
"# inner surface area of heatsink areaIn = (self.numberOfFins -",
"# degrees kelvin self.maxJunctionTemp = maxJunctionTemp self.maxSurfaceTemp = maxSurfaceTemp \"\"\"",
"cylinderDiameter: diameter of support cylinder heatsinkLength : overall axial length",
"flow rate by convection (Watts) b = finSpacing (meters) Ahs",
"Limit) nnOut = Nusselt Number for outer surfaces nnIn =",
"(((self.overallDiameter**2) / 2) + self.overallDiameter * self.heatsinkLength)) # meter^2 #",
"0.25) * (areaOut/areaHS) ) if (0.1 <= cdoD <= 8)",
"* 10**4 <= RayleighNbrOverallDiameter <= 2.3 * 10**5): nnInT =",
"numberofFins self.heatsinkLength = ((self.finThickness * self.numberOfFins) + ((self.numberOfFins - 1)",
"surface \"\"\" # thermal diffusivity of air at atmospheric pressure",
"= heatsinkSurfaceTemp - ambAirTemp # kelvin hLoD = self.heatsinkLength /",
"self.finSpacing)) self.overallDiameter = self.cylinderDiameter + (2 * finRadius) self.ambAirTemp =",
"= numberofFins self.heatsinkLength = ((self.finThickness * self.numberOfFins) + ((self.numberOfFins -",
"0.25)) nnInFD = (((0.0323 - (0.0517 * cdoD) + (0.11",
"alpha = 22.39 * 10**(-6) # (meters^2) / seconds #",
"CylindricalAnnularFin(Heatsink): \"\"\"Extend base heatsink class with a cylindrical annular fin",
"* hLoD)) * math.sqrt(areaCC) * (self.finSpacing / areaHS) ) if",
"# TODO kelvin # at atmospheric pressure at 25C kinematicViscosity"
] |
[] |
[
"by a `~` its # length will be either 23",
"sig): sig = base58.b58decode(sig) return verifier.verifyMsg(sig, MsgForSigning) def chkVerifyForRetrievedIdentity(signerWallet, verifierWallet,",
"assert senderWallet.getSponsoredIdentity(idr).seqNo is None reqs = senderWallet.preparePending() senderClient.submitReqs(*reqs) def chk():",
"since its prefixed by a `~` its # length will",
"newSigner = DidSigner(identifier=idr) wallet.updateSigner(idr, newSigner) assertEquality(newSigner.verkey, wallet.getVerkey(idr)) checkFullVerkeySize(wallet.getVerkey(idr)) return newSigner.verkey",
"# verkey is either 21 or 22 characters and since",
"senderClient, ownerWallet, idr): identity = Identity(identifier=idr) req = senderWallet.requestIdentity(identity, sender=senderWallet.defaultId)",
"bytes, # since the did takes first 16 bytes, base58",
"of abbreviated # verkey is either 21 or 22 characters",
"verifierWallet.getIdentity(idr).verkey assert verifyMsg(DidVerifier(verkey, idr), sig) def updateWalletIdrWithFullKeySigner(wallet, idr): newSigner =",
"16 bytes, base58 of abbreviated # verkey is either 21",
"plenum.common.eventually import eventually from plenum.test.helper import assertEquality from sovrin.common.identity import",
"plenum.test.helper import assertEquality from sovrin.common.identity import Identity MsgForSigning = {'sender':",
"senderClient, ownerWallet, idr, fullKey): idy = Identity(identifier=idr, verkey=fullKey) senderWallet.updateSponsoredIdentity(idy) #",
"bytes string can be either 44 bytes or 43 bytes,",
"signMsg(wallet, idr): return wallet.signMsg(MsgForSigning, identifier=idr) def verifyMsg(verifier, sig): sig =",
"Identity MsgForSigning = {'sender': 'Mario', 'msg': 'Lorem ipsum'} def signMsg(wallet,",
"will be either 23 or 22 assert len(verkey) == 23",
"None looper.run(eventually(chk, retryWait=1, timeout=5)) return ownerWallet def fetchFullVerkeyFromSovrin(looper, senderWallet, senderClient,",
"senderWallet, senderClient, ownerWallet, idr, fullKey): idy = Identity(identifier=idr, verkey=fullKey) senderWallet.updateSponsoredIdentity(idy)",
"ownerWallet, idr, fullKey): idy = Identity(identifier=idr, verkey=fullKey) senderWallet.updateSponsoredIdentity(idy) # TODO:",
"the abbreviated verkey takes last 16 bytes, base58 of abbreviated",
"be some rollback mechanism assert senderWallet.getSponsoredIdentity(idr).seqNo is None reqs =",
"looper.run(eventually(chk, retryWait=1, timeout=5)) return ownerWallet def fetchFullVerkeyFromSovrin(looper, senderWallet, senderClient, ownerWallet,",
"request fails, there must be some rollback mechanism assert senderWallet.getSponsoredIdentity(idr).seqNo",
"verkey = verifierWallet.getIdentity(idr).verkey assert verifyMsg(DidVerifier(verkey, idr), sig) def updateWalletIdrWithFullKeySigner(wallet, idr):",
"'msg': 'Lorem ipsum'} def signMsg(wallet, idr): return wallet.signMsg(MsgForSigning, identifier=idr) def",
"{'sender': 'Mario', 'msg': 'Lorem ipsum'} def signMsg(wallet, idr): return wallet.signMsg(MsgForSigning,",
"signMsg(signerWallet, idr) verkey = verifierWallet.getIdentity(idr).verkey assert verifyMsg(DidVerifier(verkey, idr), sig) def",
"= senderWallet.requestIdentity(identity, sender=senderWallet.defaultId) senderClient.submitReqs(req) def chk(): retrievedVerkey = senderWallet.getIdentity(idr).verkey assertEquality(retrievedVerkey,",
"and since its prefixed by a `~` its # length",
"senderWallet.getIdentity(idr).verkey assertEquality(retrievedVerkey, ownerWallet.getVerkey(idr)) checkFullVerkeySize(retrievedVerkey) looper.run(eventually(chk, retryWait=1, timeout=5)) def checkDidSize(did): #",
"bytes string can be either 44 bytes or 43 bytes.",
"# A base58 encoding of 32 bytes string can be",
"return wallet.signMsg(MsgForSigning, identifier=idr) def verifyMsg(verifier, sig): sig = base58.b58decode(sig) return",
"= DidSigner(identifier=idr) wallet.updateSigner(idr, newSigner) assertEquality(newSigner.verkey, wallet.getVerkey(idr)) checkFullVerkeySize(wallet.getVerkey(idr)) return newSigner.verkey def",
"A base58 encoding of 32 bytes string can be either",
"checkAbbrVerkeySize(verkey): # A base58 encoding of 32 bytes string can",
"idr): sig = signMsg(signerWallet, idr) verkey = verifierWallet.getIdentity(idr).verkey assert verifyMsg(DidVerifier(verkey,",
"base58 encoding of 32 bytes string can be either 44",
"ownerWallet.getVerkey(idr)) checkFullVerkeySize(retrievedVerkey) looper.run(eventually(chk, retryWait=1, timeout=5)) def checkDidSize(did): # A base58",
"MsgForSigning) def chkVerifyForRetrievedIdentity(signerWallet, verifierWallet, idr): sig = signMsg(signerWallet, idr) verkey",
"or 43 bytes, # since the abbreviated verkey takes last",
"the request fails, there must be some rollback mechanism assert",
"23 or len(verkey) == 22 def checkFullVerkeySize(verkey): # A base58",
"wallet.getVerkey(idr)) checkFullVerkeySize(wallet.getVerkey(idr)) return newSigner.verkey def updateSovrinIdrWithFullKey(looper, senderWallet, senderClient, ownerWallet, idr,",
"<reponame>sovrin-foundation/old-sovrin import base58 from plenum.common.signer_did import DidSigner from plenum.common.verifier import",
"not None looper.run(eventually(chk, retryWait=1, timeout=5)) return ownerWallet def fetchFullVerkeyFromSovrin(looper, senderWallet,",
"takes last 16 bytes, base58 of abbreviated # verkey is",
"plenum.common.verifier import DidVerifier from plenum.common.eventually import eventually from plenum.test.helper import",
"assertEquality(retrievedVerkey, ownerWallet.getVerkey(idr)) checkFullVerkeySize(retrievedVerkey) looper.run(eventually(chk, retryWait=1, timeout=5)) def checkDidSize(did): # A",
"characters and since its prefixed by a `~` its #",
"senderWallet, senderClient, ownerWallet, idr): identity = Identity(identifier=idr) req = senderWallet.requestIdentity(identity,",
"def chk(): retrievedVerkey = senderWallet.getIdentity(idr).verkey assertEquality(retrievedVerkey, ownerWallet.getVerkey(idr)) checkFullVerkeySize(retrievedVerkey) looper.run(eventually(chk, retryWait=1,",
"bytes or 43 bytes, # since the abbreviated verkey takes",
"`~` its # length will be either 23 or 22",
"base58 from plenum.common.signer_did import DidSigner from plenum.common.verifier import DidVerifier from",
"'Lorem ipsum'} def signMsg(wallet, idr): return wallet.signMsg(MsgForSigning, identifier=idr) def verifyMsg(verifier,",
"def chk(): assert senderWallet.getSponsoredIdentity(idr).seqNo is not None looper.run(eventually(chk, retryWait=1, timeout=5))",
"idr): return wallet.signMsg(MsgForSigning, identifier=idr) def verifyMsg(verifier, sig): sig = base58.b58decode(sig)",
"updateWalletIdrWithFullKeySigner(wallet, idr): newSigner = DidSigner(identifier=idr) wallet.updateSigner(idr, newSigner) assertEquality(newSigner.verkey, wallet.getVerkey(idr)) checkFullVerkeySize(wallet.getVerkey(idr))",
"22 def checkFullVerkeySize(verkey): # A base58 encoding of 32 bytes",
"Identity(identifier=idr, verkey=fullKey) senderWallet.updateSponsoredIdentity(idy) # TODO: What if the request fails,",
"senderWallet.updateSponsoredIdentity(idy) # TODO: What if the request fails, there must",
"None reqs = senderWallet.preparePending() senderClient.submitReqs(*reqs) def chk(): assert senderWallet.getSponsoredIdentity(idr).seqNo is",
"= Identity(identifier=idr, verkey=fullKey) senderWallet.updateSponsoredIdentity(idy) # TODO: What if the request",
"import eventually from plenum.test.helper import assertEquality from sovrin.common.identity import Identity",
"plenum.common.signer_did import DidSigner from plenum.common.verifier import DidVerifier from plenum.common.eventually import",
"= Identity(identifier=idr) req = senderWallet.requestIdentity(identity, sender=senderWallet.defaultId) senderClient.submitReqs(req) def chk(): retrievedVerkey",
"is either # 21 or 22 characters assert len(did) ==",
"either 44 bytes or 43 bytes, # since the abbreviated",
"timeout=5)) return ownerWallet def fetchFullVerkeyFromSovrin(looper, senderWallet, senderClient, ownerWallet, idr): identity",
"21 or 22 characters assert len(did) == 21 or len(did)",
"its prefixed by a `~` its # length will be",
"checkFullVerkeySize(verkey): # A base58 encoding of 32 bytes string can",
"bytes, # since the abbreviated verkey takes last 16 bytes,",
"16 bytes, base58 of did is either # 21 or",
"reqs = senderWallet.preparePending() senderClient.submitReqs(*reqs) def chk(): assert senderWallet.getSponsoredIdentity(idr).seqNo is not",
"req = senderWallet.requestIdentity(identity, sender=senderWallet.defaultId) senderClient.submitReqs(req) def chk(): retrievedVerkey = senderWallet.getIdentity(idr).verkey",
"either 44 bytes or 43 bytes. assert len(verkey) == 44",
"since the did takes first 16 bytes, base58 of did",
"base58 of did is either # 21 or 22 characters",
"can be either 44 bytes or 43 bytes. assert len(verkey)",
"characters assert len(did) == 21 or len(did) == 22 def",
"44 bytes or 43 bytes, # since the did takes",
"len(did) == 21 or len(did) == 22 def checkAbbrVerkeySize(verkey): #",
"'Mario', 'msg': 'Lorem ipsum'} def signMsg(wallet, idr): return wallet.signMsg(MsgForSigning, identifier=idr)",
"bytes or 43 bytes, # since the did takes first",
"Identity(identifier=idr) req = senderWallet.requestIdentity(identity, sender=senderWallet.defaultId) senderClient.submitReqs(req) def chk(): retrievedVerkey =",
"# since the abbreviated verkey takes last 16 bytes, base58",
"fullKey): idy = Identity(identifier=idr, verkey=fullKey) senderWallet.updateSponsoredIdentity(idy) # TODO: What if",
"did is either # 21 or 22 characters assert len(did)",
"assert verifyMsg(DidVerifier(verkey, idr), sig) def updateWalletIdrWithFullKeySigner(wallet, idr): newSigner = DidSigner(identifier=idr)",
"if the request fails, there must be some rollback mechanism",
"since the abbreviated verkey takes last 16 bytes, base58 of",
"= verifierWallet.getIdentity(idr).verkey assert verifyMsg(DidVerifier(verkey, idr), sig) def updateWalletIdrWithFullKeySigner(wallet, idr): newSigner",
"be either 44 bytes or 43 bytes, # since the",
"43 bytes, # since the did takes first 16 bytes,",
"def updateWalletIdrWithFullKeySigner(wallet, idr): newSigner = DidSigner(identifier=idr) wallet.updateSigner(idr, newSigner) assertEquality(newSigner.verkey, wallet.getVerkey(idr))",
"looper.run(eventually(chk, retryWait=1, timeout=5)) def checkDidSize(did): # A base58 encoding of",
"or 43 bytes, # since the did takes first 16",
"MsgForSigning = {'sender': 'Mario', 'msg': 'Lorem ipsum'} def signMsg(wallet, idr):",
"TODO: What if the request fails, there must be some",
"string can be either 44 bytes or 43 bytes. assert",
"# TODO: What if the request fails, there must be",
"from plenum.test.helper import assertEquality from sovrin.common.identity import Identity MsgForSigning =",
"sig = base58.b58decode(sig) return verifier.verifyMsg(sig, MsgForSigning) def chkVerifyForRetrievedIdentity(signerWallet, verifierWallet, idr):",
"senderClient.submitReqs(req) def chk(): retrievedVerkey = senderWallet.getIdentity(idr).verkey assertEquality(retrievedVerkey, ownerWallet.getVerkey(idr)) checkFullVerkeySize(retrievedVerkey) looper.run(eventually(chk,",
"of 32 bytes string can be either 44 bytes or",
"== 23 or len(verkey) == 22 def checkFullVerkeySize(verkey): # A",
"sender=senderWallet.defaultId) senderClient.submitReqs(req) def chk(): retrievedVerkey = senderWallet.getIdentity(idr).verkey assertEquality(retrievedVerkey, ownerWallet.getVerkey(idr)) checkFullVerkeySize(retrievedVerkey)",
"base58 of abbreviated # verkey is either 21 or 22",
"assertEquality from sovrin.common.identity import Identity MsgForSigning = {'sender': 'Mario', 'msg':",
"bytes, base58 of abbreviated # verkey is either 21 or",
"sovrin.common.identity import Identity MsgForSigning = {'sender': 'Mario', 'msg': 'Lorem ipsum'}",
"ipsum'} def signMsg(wallet, idr): return wallet.signMsg(MsgForSigning, identifier=idr) def verifyMsg(verifier, sig):",
"some rollback mechanism assert senderWallet.getSponsoredIdentity(idr).seqNo is None reqs = senderWallet.preparePending()",
"is not None looper.run(eventually(chk, retryWait=1, timeout=5)) return ownerWallet def fetchFullVerkeyFromSovrin(looper,",
"checkFullVerkeySize(wallet.getVerkey(idr)) return newSigner.verkey def updateSovrinIdrWithFullKey(looper, senderWallet, senderClient, ownerWallet, idr, fullKey):",
"return ownerWallet def fetchFullVerkeyFromSovrin(looper, senderWallet, senderClient, ownerWallet, idr): identity =",
"bytes or 43 bytes. assert len(verkey) == 44 or len(verkey)",
"sig = signMsg(signerWallet, idr) verkey = verifierWallet.getIdentity(idr).verkey assert verifyMsg(DidVerifier(verkey, idr),",
"32 bytes string can be either 44 bytes or 43",
"or 43 bytes. assert len(verkey) == 44 or len(verkey) ==",
"def fetchFullVerkeyFromSovrin(looper, senderWallet, senderClient, ownerWallet, idr): identity = Identity(identifier=idr) req",
"chk(): assert senderWallet.getSponsoredIdentity(idr).seqNo is not None looper.run(eventually(chk, retryWait=1, timeout=5)) return",
"len(verkey) == 23 or len(verkey) == 22 def checkFullVerkeySize(verkey): #",
"retryWait=1, timeout=5)) return ownerWallet def fetchFullVerkeyFromSovrin(looper, senderWallet, senderClient, ownerWallet, idr):",
"DidSigner from plenum.common.verifier import DidVerifier from plenum.common.eventually import eventually from",
"def verifyMsg(verifier, sig): sig = base58.b58decode(sig) return verifier.verifyMsg(sig, MsgForSigning) def",
"be either 23 or 22 assert len(verkey) == 23 or",
"from plenum.common.signer_did import DidSigner from plenum.common.verifier import DidVerifier from plenum.common.eventually",
"senderWallet.preparePending() senderClient.submitReqs(*reqs) def chk(): assert senderWallet.getSponsoredIdentity(idr).seqNo is not None looper.run(eventually(chk,",
"idr, fullKey): idy = Identity(identifier=idr, verkey=fullKey) senderWallet.updateSponsoredIdentity(idy) # TODO: What",
"there must be some rollback mechanism assert senderWallet.getSponsoredIdentity(idr).seqNo is None",
"newSigner.verkey def updateSovrinIdrWithFullKey(looper, senderWallet, senderClient, ownerWallet, idr, fullKey): idy =",
"# since the did takes first 16 bytes, base58 of",
"== 22 def checkFullVerkeySize(verkey): # A base58 encoding of 32",
"43 bytes. assert len(verkey) == 44 or len(verkey) == 43",
"encoding of 32 bytes string can be either 44 bytes",
"takes first 16 bytes, base58 of did is either #",
"import Identity MsgForSigning = {'sender': 'Mario', 'msg': 'Lorem ipsum'} def",
"DidVerifier from plenum.common.eventually import eventually from plenum.test.helper import assertEquality from",
"return verifier.verifyMsg(sig, MsgForSigning) def chkVerifyForRetrievedIdentity(signerWallet, verifierWallet, idr): sig = signMsg(signerWallet,",
"did takes first 16 bytes, base58 of did is either",
"verkey takes last 16 bytes, base58 of abbreviated # verkey",
"def signMsg(wallet, idr): return wallet.signMsg(MsgForSigning, identifier=idr) def verifyMsg(verifier, sig): sig",
"first 16 bytes, base58 of did is either # 21",
"assert len(did) == 21 or len(did) == 22 def checkAbbrVerkeySize(verkey):",
"assert len(verkey) == 23 or len(verkey) == 22 def checkFullVerkeySize(verkey):",
"idr): identity = Identity(identifier=idr) req = senderWallet.requestIdentity(identity, sender=senderWallet.defaultId) senderClient.submitReqs(req) def",
"senderWallet.requestIdentity(identity, sender=senderWallet.defaultId) senderClient.submitReqs(req) def chk(): retrievedVerkey = senderWallet.getIdentity(idr).verkey assertEquality(retrievedVerkey, ownerWallet.getVerkey(idr))",
"44 bytes or 43 bytes, # since the abbreviated verkey",
"verifyMsg(verifier, sig): sig = base58.b58decode(sig) return verifier.verifyMsg(sig, MsgForSigning) def chkVerifyForRetrievedIdentity(signerWallet,",
"idr): newSigner = DidSigner(identifier=idr) wallet.updateSigner(idr, newSigner) assertEquality(newSigner.verkey, wallet.getVerkey(idr)) checkFullVerkeySize(wallet.getVerkey(idr)) return",
"its # length will be either 23 or 22 assert",
"wallet.signMsg(MsgForSigning, identifier=idr) def verifyMsg(verifier, sig): sig = base58.b58decode(sig) return verifier.verifyMsg(sig,",
"identifier=idr) def verifyMsg(verifier, sig): sig = base58.b58decode(sig) return verifier.verifyMsg(sig, MsgForSigning)",
"== 22 def checkAbbrVerkeySize(verkey): # A base58 encoding of 32",
"or len(verkey) == 22 def checkFullVerkeySize(verkey): # A base58 encoding",
"return newSigner.verkey def updateSovrinIdrWithFullKey(looper, senderWallet, senderClient, ownerWallet, idr, fullKey): idy",
"import DidVerifier from plenum.common.eventually import eventually from plenum.test.helper import assertEquality",
"verkey=fullKey) senderWallet.updateSponsoredIdentity(idy) # TODO: What if the request fails, there",
"22 def checkAbbrVerkeySize(verkey): # A base58 encoding of 32 bytes",
"prefixed by a `~` its # length will be either",
"== 21 or len(did) == 22 def checkAbbrVerkeySize(verkey): # A",
"checkDidSize(did): # A base58 encoding of 32 bytes string can",
"22 assert len(verkey) == 23 or len(verkey) == 22 def",
"must be some rollback mechanism assert senderWallet.getSponsoredIdentity(idr).seqNo is None reqs",
"What if the request fails, there must be some rollback",
"fails, there must be some rollback mechanism assert senderWallet.getSponsoredIdentity(idr).seqNo is",
"assert senderWallet.getSponsoredIdentity(idr).seqNo is not None looper.run(eventually(chk, retryWait=1, timeout=5)) return ownerWallet",
"idy = Identity(identifier=idr, verkey=fullKey) senderWallet.updateSponsoredIdentity(idy) # TODO: What if the",
"21 or 22 characters and since its prefixed by a",
"DidSigner(identifier=idr) wallet.updateSigner(idr, newSigner) assertEquality(newSigner.verkey, wallet.getVerkey(idr)) checkFullVerkeySize(wallet.getVerkey(idr)) return newSigner.verkey def updateSovrinIdrWithFullKey(looper,",
"base58.b58decode(sig) return verifier.verifyMsg(sig, MsgForSigning) def chkVerifyForRetrievedIdentity(signerWallet, verifierWallet, idr): sig =",
"is None reqs = senderWallet.preparePending() senderClient.submitReqs(*reqs) def chk(): assert senderWallet.getSponsoredIdentity(idr).seqNo",
"either 23 or 22 assert len(verkey) == 23 or len(verkey)",
"either 21 or 22 characters and since its prefixed by",
"def chkVerifyForRetrievedIdentity(signerWallet, verifierWallet, idr): sig = signMsg(signerWallet, idr) verkey =",
"21 or len(did) == 22 def checkAbbrVerkeySize(verkey): # A base58",
"or 22 assert len(verkey) == 23 or len(verkey) == 22",
"retryWait=1, timeout=5)) def checkDidSize(did): # A base58 encoding of 32",
"assertEquality(newSigner.verkey, wallet.getVerkey(idr)) checkFullVerkeySize(wallet.getVerkey(idr)) return newSigner.verkey def updateSovrinIdrWithFullKey(looper, senderWallet, senderClient, ownerWallet,",
"can be either 44 bytes or 43 bytes, # since",
"identity = Identity(identifier=idr) req = senderWallet.requestIdentity(identity, sender=senderWallet.defaultId) senderClient.submitReqs(req) def chk():",
"from sovrin.common.identity import Identity MsgForSigning = {'sender': 'Mario', 'msg': 'Lorem",
"= base58.b58decode(sig) return verifier.verifyMsg(sig, MsgForSigning) def chkVerifyForRetrievedIdentity(signerWallet, verifierWallet, idr): sig",
"idr), sig) def updateWalletIdrWithFullKeySigner(wallet, idr): newSigner = DidSigner(identifier=idr) wallet.updateSigner(idr, newSigner)",
"mechanism assert senderWallet.getSponsoredIdentity(idr).seqNo is None reqs = senderWallet.preparePending() senderClient.submitReqs(*reqs) def",
"= senderWallet.preparePending() senderClient.submitReqs(*reqs) def chk(): assert senderWallet.getSponsoredIdentity(idr).seqNo is not None",
"chk(): retrievedVerkey = senderWallet.getIdentity(idr).verkey assertEquality(retrievedVerkey, ownerWallet.getVerkey(idr)) checkFullVerkeySize(retrievedVerkey) looper.run(eventually(chk, retryWait=1, timeout=5))",
"senderClient.submitReqs(*reqs) def chk(): assert senderWallet.getSponsoredIdentity(idr).seqNo is not None looper.run(eventually(chk, retryWait=1,",
"len(verkey) == 22 def checkFullVerkeySize(verkey): # A base58 encoding of",
"abbreviated verkey takes last 16 bytes, base58 of abbreviated #",
"23 or 22 assert len(verkey) == 23 or len(verkey) ==",
"either 44 bytes or 43 bytes, # since the did",
"# 21 or 22 characters assert len(did) == 21 or",
"= senderWallet.getIdentity(idr).verkey assertEquality(retrievedVerkey, ownerWallet.getVerkey(idr)) checkFullVerkeySize(retrievedVerkey) looper.run(eventually(chk, retryWait=1, timeout=5)) def checkDidSize(did):",
"length will be either 23 or 22 assert len(verkey) ==",
"def checkAbbrVerkeySize(verkey): # A base58 encoding of 32 bytes string",
"import base58 from plenum.common.signer_did import DidSigner from plenum.common.verifier import DidVerifier",
"verifier.verifyMsg(sig, MsgForSigning) def chkVerifyForRetrievedIdentity(signerWallet, verifierWallet, idr): sig = signMsg(signerWallet, idr)",
"44 bytes or 43 bytes. assert len(verkey) == 44 or",
"import DidSigner from plenum.common.verifier import DidVerifier from plenum.common.eventually import eventually",
"= signMsg(signerWallet, idr) verkey = verifierWallet.getIdentity(idr).verkey assert verifyMsg(DidVerifier(verkey, idr), sig)",
"last 16 bytes, base58 of abbreviated # verkey is either",
"updateSovrinIdrWithFullKey(looper, senderWallet, senderClient, ownerWallet, idr, fullKey): idy = Identity(identifier=idr, verkey=fullKey)",
"43 bytes, # since the abbreviated verkey takes last 16",
"sig) def updateWalletIdrWithFullKeySigner(wallet, idr): newSigner = DidSigner(identifier=idr) wallet.updateSigner(idr, newSigner) assertEquality(newSigner.verkey,",
"ownerWallet def fetchFullVerkeyFromSovrin(looper, senderWallet, senderClient, ownerWallet, idr): identity = Identity(identifier=idr)",
"either # 21 or 22 characters assert len(did) == 21",
"abbreviated # verkey is either 21 or 22 characters and",
"bytes, base58 of did is either # 21 or 22",
"or 22 characters assert len(did) == 21 or len(did) ==",
"newSigner) assertEquality(newSigner.verkey, wallet.getVerkey(idr)) checkFullVerkeySize(wallet.getVerkey(idr)) return newSigner.verkey def updateSovrinIdrWithFullKey(looper, senderWallet, senderClient,",
"a `~` its # length will be either 23 or",
"ownerWallet, idr): identity = Identity(identifier=idr) req = senderWallet.requestIdentity(identity, sender=senderWallet.defaultId) senderClient.submitReqs(req)",
"22 characters assert len(did) == 21 or len(did) == 22",
"idr) verkey = verifierWallet.getIdentity(idr).verkey assert verifyMsg(DidVerifier(verkey, idr), sig) def updateWalletIdrWithFullKeySigner(wallet,",
"= {'sender': 'Mario', 'msg': 'Lorem ipsum'} def signMsg(wallet, idr): return",
"def updateSovrinIdrWithFullKey(looper, senderWallet, senderClient, ownerWallet, idr, fullKey): idy = Identity(identifier=idr,",
"eventually from plenum.test.helper import assertEquality from sovrin.common.identity import Identity MsgForSigning",
"wallet.updateSigner(idr, newSigner) assertEquality(newSigner.verkey, wallet.getVerkey(idr)) checkFullVerkeySize(wallet.getVerkey(idr)) return newSigner.verkey def updateSovrinIdrWithFullKey(looper, senderWallet,",
"fetchFullVerkeyFromSovrin(looper, senderWallet, senderClient, ownerWallet, idr): identity = Identity(identifier=idr) req =",
"timeout=5)) def checkDidSize(did): # A base58 encoding of 32 bytes",
"verifierWallet, idr): sig = signMsg(signerWallet, idr) verkey = verifierWallet.getIdentity(idr).verkey assert",
"verkey is either 21 or 22 characters and since its",
"is either 21 or 22 characters and since its prefixed",
"senderWallet.getSponsoredIdentity(idr).seqNo is None reqs = senderWallet.preparePending() senderClient.submitReqs(*reqs) def chk(): assert",
"len(did) == 22 def checkAbbrVerkeySize(verkey): # A base58 encoding of",
"the did takes first 16 bytes, base58 of did is",
"senderWallet.getSponsoredIdentity(idr).seqNo is not None looper.run(eventually(chk, retryWait=1, timeout=5)) return ownerWallet def",
"from plenum.common.eventually import eventually from plenum.test.helper import assertEquality from sovrin.common.identity",
"checkFullVerkeySize(retrievedVerkey) looper.run(eventually(chk, retryWait=1, timeout=5)) def checkDidSize(did): # A base58 encoding",
"import assertEquality from sovrin.common.identity import Identity MsgForSigning = {'sender': 'Mario',",
"from plenum.common.verifier import DidVerifier from plenum.common.eventually import eventually from plenum.test.helper",
"retrievedVerkey = senderWallet.getIdentity(idr).verkey assertEquality(retrievedVerkey, ownerWallet.getVerkey(idr)) checkFullVerkeySize(retrievedVerkey) looper.run(eventually(chk, retryWait=1, timeout=5)) def",
"def checkFullVerkeySize(verkey): # A base58 encoding of 32 bytes string",
"be either 44 bytes or 43 bytes. assert len(verkey) ==",
"or len(did) == 22 def checkAbbrVerkeySize(verkey): # A base58 encoding",
"or 22 characters and since its prefixed by a `~`",
"string can be either 44 bytes or 43 bytes, #",
"def checkDidSize(did): # A base58 encoding of 32 bytes string",
"of did is either # 21 or 22 characters assert",
"rollback mechanism assert senderWallet.getSponsoredIdentity(idr).seqNo is None reqs = senderWallet.preparePending() senderClient.submitReqs(*reqs)",
"22 characters and since its prefixed by a `~` its",
"# length will be either 23 or 22 assert len(verkey)",
"verifyMsg(DidVerifier(verkey, idr), sig) def updateWalletIdrWithFullKeySigner(wallet, idr): newSigner = DidSigner(identifier=idr) wallet.updateSigner(idr,",
"chkVerifyForRetrievedIdentity(signerWallet, verifierWallet, idr): sig = signMsg(signerWallet, idr) verkey = verifierWallet.getIdentity(idr).verkey"
] |
[
"isinstance(sp.grid, np.ndarray) assert isinstance(sp.interp_flux, np.ndarray) assert isinstance(sp.interp_bary_flux, np.ndarray) assert len(sp.grid)",
"str) assert isinstance(sp.datetime, datetime.datetime) assert isinstance(sp.v_bary, float) assert isinstance(sp.wave_units, str)",
"len(sp.interp_bary_flux) assert np.min(sp.grid) > sp.xmin assert np.max(sp.grid) < sp.xmax assert",
"np.max(sp.bary_wave) < sp.xmax assert isinstance(sp.grid, np.ndarray) assert isinstance(sp.interp_flux, np.ndarray) assert",
"np.ndarray) assert isinstance(sp.interp_flux, np.ndarray) assert isinstance(sp.interp_bary_flux, np.ndarray) assert len(sp.grid) ==",
"< sp.xmax assert isinstance(sp.sky_wave, np.ndarray) assert isinstance(sp.sky_flux, np.ndarray) assert len(sp.sky_wave)",
"Raw assert isinstance(sp.raw_wave, np.ndarray) assert isinstance(sp.raw_bary_wave, np.ndarray) assert isinstance(sp.raw_flux, np.ndarray)",
"assert xmax == sp.xmax assert isinstance(sp.wave, np.ndarray) assert isinstance(sp.flux, np.ndarray)",
"print(len(sp.raw_grid)) assert isinstance(sp.raw_sky_wave, np.ndarray) assert isinstance(sp.raw_sky_flux, np.ndarray) assert len(sp.raw_sky_wave) ==",
"isinstance(sp.raw_wave, np.ndarray) assert isinstance(sp.raw_bary_wave, np.ndarray) assert isinstance(sp.raw_flux, np.ndarray) assert len(sp.raw_wave)",
"len(sp.flux) assert np.min(sp.wave) > sp.xmin assert np.max(sp.wave) < sp.xmax assert",
"EdiblesSpectrum def testEdiblesSpectrum(filename=\"tests/HD170740_w860_redl_20140915_O12.fits\"): # Spectrum information sp = EdiblesSpectrum(filename=filename, fully_featured=True,",
"as np from edibles.utils.edibles_spectrum import EdiblesSpectrum def testEdiblesSpectrum(filename=\"tests/HD170740_w860_redl_20140915_O12.fits\"): # Spectrum",
"sp.xmax assert isinstance(sp.wave, np.ndarray) assert isinstance(sp.flux, np.ndarray) assert len(sp.wave) ==",
"assert np.max(sp.sky_wave) < sp.xmax # shift zoom_xmin = 7661 zoom_xmax",
"noDATADIR=True) assert isinstance(sp.header, astropy.io.fits.header.Header) assert isinstance(sp.target, str) assert isinstance(sp.date, str)",
"import astropy import datetime import numpy as np from edibles.utils.edibles_spectrum",
"# Raw assert isinstance(sp.raw_wave, np.ndarray) assert isinstance(sp.raw_bary_wave, np.ndarray) assert isinstance(sp.raw_flux,",
"= 7680 sp.getSpectrum(xmin=xmin, xmax=xmax) assert xmin == sp.xmin assert xmax",
"assert len(sp.raw_grid) == 200443 # print(len(sp.raw_grid)) assert isinstance(sp.raw_sky_wave, np.ndarray) assert",
"== len(sp.sky_flux) assert np.min(sp.sky_wave) > sp.xmin assert np.max(sp.sky_wave) < sp.xmax",
"len(sp.sky_flux) assert np.min(sp.sky_wave) > sp.xmin assert np.max(sp.sky_wave) < sp.xmax #",
"assert len(sp.grid) == len(sp.interp_flux) assert len(sp.grid) == len(sp.interp_bary_flux) assert np.min(sp.grid)",
"assert isinstance(sp.flux, np.ndarray) assert len(sp.wave) == len(sp.flux) assert np.min(sp.wave) >",
"== len(sp.bary_flux) assert np.min(sp.bary_wave) > sp.xmin assert np.max(sp.bary_wave) < sp.xmax",
"= 7661 zoom_xmax = 7679 shift = 0.05 sp.shift(shift=shift, zoom_xmin=zoom_xmin,",
"assert len(sp.sky_wave) == len(sp.sky_flux) assert np.min(sp.sky_wave) > sp.xmin assert np.max(sp.sky_wave)",
"np.max(sp.wave) < sp.xmax assert isinstance(sp.bary_wave, np.ndarray) assert isinstance(sp.bary_flux, np.ndarray) assert",
"assert isinstance(sp.sky_wave, np.ndarray) assert isinstance(sp.sky_flux, np.ndarray) assert len(sp.sky_wave) == len(sp.sky_flux)",
"== len(sp.raw_sky_flux) assert isinstance(sp.wave, np.ndarray) assert isinstance(sp.bary_wave, np.ndarray) assert isinstance(sp.flux,",
"> sp.xmin assert np.max(sp.sky_wave) < sp.xmax if __name__ == \"__main__\":",
"np.min(sp.grid) > sp.xmin assert np.max(sp.grid) < sp.xmax assert isinstance(sp.sky_wave, np.ndarray)",
"= EdiblesSpectrum(filename=filename, fully_featured=True, noDATADIR=True) assert isinstance(sp.header, astropy.io.fits.header.Header) assert isinstance(sp.target, str)",
"float) assert isinstance(sp.wave_units, str) assert isinstance(sp.flux_units, str) # Raw assert",
"np.ndarray) assert isinstance(sp.raw_sky_flux, np.ndarray) assert len(sp.raw_sky_wave) == len(sp.raw_sky_flux) assert isinstance(sp.wave,",
"# getSpectrum xmin = 7660 xmax = 7680 sp.getSpectrum(xmin=xmin, xmax=xmax)",
"len(sp.wave) == len(sp.flux) assert np.min(sp.wave) > sp.xmin assert np.max(sp.wave) <",
"assert isinstance(sp.bary_wave, np.ndarray) assert isinstance(sp.flux, np.ndarray) # getSpectrum xmin =",
"np.ndarray) assert len(sp.bary_wave) == len(sp.bary_flux) assert np.min(sp.bary_wave) > sp.xmin assert",
"np.min(sp.sky_wave) > sp.xmin assert np.max(sp.sky_wave) < sp.xmax if __name__ ==",
"isinstance(sp.wave, np.ndarray) assert isinstance(sp.flux, np.ndarray) assert len(sp.wave) == len(sp.flux) assert",
"Spectrum information sp = EdiblesSpectrum(filename=filename, fully_featured=True, noDATADIR=True) assert isinstance(sp.header, astropy.io.fits.header.Header)",
"len(sp.bary_flux) assert np.min(sp.bary_wave) > sp.xmin assert np.max(sp.bary_wave) < sp.xmax assert",
"len(sp.sky_flux) assert np.min(sp.sky_wave) > sp.xmin assert np.max(sp.sky_wave) < sp.xmax if",
"> sp.xmin assert np.max(sp.bary_wave) < sp.xmax assert isinstance(sp.grid, np.ndarray) assert",
"sp.xmin assert np.max(sp.sky_wave) < sp.xmax # shift zoom_xmin = 7661",
"len(sp.raw_wave) == len(sp.raw_flux) assert isinstance(sp.raw_grid, np.ndarray) assert len(sp.raw_grid) == 200443",
"isinstance(sp.v_bary, float) assert isinstance(sp.wave_units, str) assert isinstance(sp.flux_units, str) # Raw",
"isinstance(sp.target, str) assert isinstance(sp.date, str) assert isinstance(sp.datetime, datetime.datetime) assert isinstance(sp.v_bary,",
"zoom_xmax = 7679 shift = 0.05 sp.shift(shift=shift, zoom_xmin=zoom_xmin, zoom_xmax=zoom_xmax) assert",
"astropy import datetime import numpy as np from edibles.utils.edibles_spectrum import",
"xmax = 7680 sp.getSpectrum(xmin=xmin, xmax=xmax) assert xmin == sp.xmin assert",
"isinstance(sp.interp_flux, np.ndarray) assert isinstance(sp.interp_bary_flux, np.ndarray) assert len(sp.grid) == len(sp.interp_flux) assert",
"zoom_xmin = 7661 zoom_xmax = 7679 shift = 0.05 sp.shift(shift=shift,",
"len(sp.raw_sky_flux) assert isinstance(sp.wave, np.ndarray) assert isinstance(sp.bary_wave, np.ndarray) assert isinstance(sp.flux, np.ndarray)",
"shift = 0.05 sp.shift(shift=shift, zoom_xmin=zoom_xmin, zoom_xmax=zoom_xmax) assert isinstance(sp.wave, np.ndarray) assert",
"assert np.max(sp.sky_wave) < sp.xmax if __name__ == \"__main__\": filename =",
"datetime import numpy as np from edibles.utils.edibles_spectrum import EdiblesSpectrum def",
"information sp = EdiblesSpectrum(filename=filename, fully_featured=True, noDATADIR=True) assert isinstance(sp.header, astropy.io.fits.header.Header) assert",
"= 7679 shift = 0.05 sp.shift(shift=shift, zoom_xmin=zoom_xmin, zoom_xmax=zoom_xmax) assert isinstance(sp.wave,",
"np.ndarray) assert isinstance(sp.raw_bary_wave, np.ndarray) assert isinstance(sp.raw_flux, np.ndarray) assert len(sp.raw_wave) ==",
"assert isinstance(sp.raw_grid, np.ndarray) assert len(sp.raw_grid) == 200443 # print(len(sp.raw_grid)) assert",
"isinstance(sp.sky_wave, np.ndarray) assert isinstance(sp.sky_flux, np.ndarray) assert len(sp.sky_wave) == len(sp.sky_flux) assert",
"sp.xmax # shift zoom_xmin = 7661 zoom_xmax = 7679 shift",
"isinstance(sp.header, astropy.io.fits.header.Header) assert isinstance(sp.target, str) assert isinstance(sp.date, str) assert isinstance(sp.datetime,",
"assert isinstance(sp.v_bary, float) assert isinstance(sp.wave_units, str) assert isinstance(sp.flux_units, str) #",
"0.05 sp.shift(shift=shift, zoom_xmin=zoom_xmin, zoom_xmax=zoom_xmax) assert isinstance(sp.wave, np.ndarray) assert isinstance(sp.flux, np.ndarray)",
"np.ndarray) assert isinstance(sp.raw_flux, np.ndarray) assert len(sp.raw_wave) == len(sp.raw_bary_wave) assert len(sp.raw_wave)",
"isinstance(sp.raw_bary_wave, np.ndarray) assert isinstance(sp.raw_flux, np.ndarray) assert len(sp.raw_wave) == len(sp.raw_bary_wave) assert",
"np.ndarray) assert isinstance(sp.bary_flux, np.ndarray) assert len(sp.bary_wave) == len(sp.bary_flux) assert np.min(sp.bary_wave)",
"sp.xmin assert np.max(sp.grid) < sp.xmax assert isinstance(sp.sky_wave, np.ndarray) assert isinstance(sp.sky_flux,",
"xmin = 7660 xmax = 7680 sp.getSpectrum(xmin=xmin, xmax=xmax) assert xmin",
"assert isinstance(sp.sky_flux, np.ndarray) assert len(sp.sky_wave) == len(sp.sky_flux) assert np.min(sp.sky_wave) >",
"str) assert isinstance(sp.date, str) assert isinstance(sp.datetime, datetime.datetime) assert isinstance(sp.v_bary, float)",
"== len(sp.raw_bary_wave) assert len(sp.raw_wave) == len(sp.raw_flux) assert isinstance(sp.raw_grid, np.ndarray) assert",
"sp.getSpectrum(xmin=xmin, xmax=xmax) assert xmin == sp.xmin assert xmax == sp.xmax",
"xmin == sp.xmin assert xmax == sp.xmax assert isinstance(sp.wave, np.ndarray)",
"assert len(sp.bary_wave) == len(sp.bary_flux) assert np.min(sp.bary_wave) > sp.xmin assert np.max(sp.bary_wave)",
"len(sp.interp_flux) assert len(sp.grid) == len(sp.interp_bary_flux) assert np.min(sp.grid) > sp.xmin assert",
"200443 # print(len(sp.raw_grid)) assert isinstance(sp.raw_sky_wave, np.ndarray) assert isinstance(sp.raw_sky_flux, np.ndarray) assert",
"np.max(sp.sky_wave) < sp.xmax if __name__ == \"__main__\": filename = \"HD170740_w860_redl_20140915_O12.fits\"",
"# Spectrum information sp = EdiblesSpectrum(filename=filename, fully_featured=True, noDATADIR=True) assert isinstance(sp.header,",
"numpy as np from edibles.utils.edibles_spectrum import EdiblesSpectrum def testEdiblesSpectrum(filename=\"tests/HD170740_w860_redl_20140915_O12.fits\"): #",
"zoom_xmax=zoom_xmax) assert isinstance(sp.wave, np.ndarray) assert isinstance(sp.flux, np.ndarray) assert len(sp.wave) ==",
"assert len(sp.raw_wave) == len(sp.raw_flux) assert isinstance(sp.raw_grid, np.ndarray) assert len(sp.raw_grid) ==",
"assert isinstance(sp.interp_bary_flux, np.ndarray) assert len(sp.grid) == len(sp.interp_flux) assert len(sp.grid) ==",
"< sp.xmax assert isinstance(sp.bary_wave, np.ndarray) assert isinstance(sp.bary_flux, np.ndarray) assert len(sp.bary_wave)",
"EdiblesSpectrum(filename=filename, fully_featured=True, noDATADIR=True) assert isinstance(sp.header, astropy.io.fits.header.Header) assert isinstance(sp.target, str) assert",
"len(sp.raw_bary_wave) assert len(sp.raw_wave) == len(sp.raw_flux) assert isinstance(sp.raw_grid, np.ndarray) assert len(sp.raw_grid)",
"assert isinstance(sp.grid, np.ndarray) assert isinstance(sp.interp_flux, np.ndarray) assert isinstance(sp.interp_bary_flux, np.ndarray) assert",
"assert isinstance(sp.bary_wave, np.ndarray) assert isinstance(sp.bary_flux, np.ndarray) assert len(sp.bary_wave) == len(sp.bary_flux)",
"> sp.xmin assert np.max(sp.grid) < sp.xmax assert isinstance(sp.sky_wave, np.ndarray) assert",
"sp.shift(shift=shift, zoom_xmin=zoom_xmin, zoom_xmax=zoom_xmax) assert isinstance(sp.wave, np.ndarray) assert isinstance(sp.flux, np.ndarray) assert",
"len(sp.raw_grid) == 200443 # print(len(sp.raw_grid)) assert isinstance(sp.raw_sky_wave, np.ndarray) assert isinstance(sp.raw_sky_flux,",
"= 7660 xmax = 7680 sp.getSpectrum(xmin=xmin, xmax=xmax) assert xmin ==",
"len(sp.raw_sky_wave) == len(sp.raw_sky_flux) assert isinstance(sp.wave, np.ndarray) assert isinstance(sp.bary_wave, np.ndarray) assert",
"< sp.xmax # shift zoom_xmin = 7661 zoom_xmax = 7679",
"assert isinstance(sp.interp_flux, np.ndarray) assert isinstance(sp.interp_bary_flux, np.ndarray) assert len(sp.grid) == len(sp.interp_flux)",
"zoom_xmin=zoom_xmin, zoom_xmax=zoom_xmax) assert isinstance(sp.wave, np.ndarray) assert isinstance(sp.flux, np.ndarray) assert len(sp.wave)",
"isinstance(sp.date, str) assert isinstance(sp.datetime, datetime.datetime) assert isinstance(sp.v_bary, float) assert isinstance(sp.wave_units,",
"assert len(sp.raw_wave) == len(sp.raw_bary_wave) assert len(sp.raw_wave) == len(sp.raw_flux) assert isinstance(sp.raw_grid,",
"assert xmin == sp.xmin assert xmax == sp.xmax assert isinstance(sp.wave,",
"== sp.xmax assert isinstance(sp.wave, np.ndarray) assert isinstance(sp.flux, np.ndarray) assert len(sp.wave)",
"isinstance(sp.flux_units, str) # Raw assert isinstance(sp.raw_wave, np.ndarray) assert isinstance(sp.raw_bary_wave, np.ndarray)",
"edibles.utils.edibles_spectrum import EdiblesSpectrum def testEdiblesSpectrum(filename=\"tests/HD170740_w860_redl_20140915_O12.fits\"): # Spectrum information sp =",
"sp = EdiblesSpectrum(filename=filename, fully_featured=True, noDATADIR=True) assert isinstance(sp.header, astropy.io.fits.header.Header) assert isinstance(sp.target,",
"np.ndarray) assert len(sp.sky_wave) == len(sp.sky_flux) assert np.min(sp.sky_wave) > sp.xmin assert",
"sp.xmax assert isinstance(sp.sky_wave, np.ndarray) assert isinstance(sp.sky_flux, np.ndarray) assert len(sp.sky_wave) ==",
"import numpy as np from edibles.utils.edibles_spectrum import EdiblesSpectrum def testEdiblesSpectrum(filename=\"tests/HD170740_w860_redl_20140915_O12.fits\"):",
"> sp.xmin assert np.max(sp.wave) < sp.xmax assert isinstance(sp.bary_wave, np.ndarray) assert",
"np.ndarray) assert len(sp.raw_grid) == 200443 # print(len(sp.raw_grid)) assert isinstance(sp.raw_sky_wave, np.ndarray)",
"# shift zoom_xmin = 7661 zoom_xmax = 7679 shift =",
"astropy.io.fits.header.Header) assert isinstance(sp.target, str) assert isinstance(sp.date, str) assert isinstance(sp.datetime, datetime.datetime)",
"assert isinstance(sp.flux_units, str) # Raw assert isinstance(sp.raw_wave, np.ndarray) assert isinstance(sp.raw_bary_wave,",
"str) # Raw assert isinstance(sp.raw_wave, np.ndarray) assert isinstance(sp.raw_bary_wave, np.ndarray) assert",
"== len(sp.raw_flux) assert isinstance(sp.raw_grid, np.ndarray) assert len(sp.raw_grid) == 200443 #",
"np.ndarray) assert isinstance(sp.interp_bary_flux, np.ndarray) assert len(sp.grid) == len(sp.interp_flux) assert len(sp.grid)",
"np.ndarray) assert isinstance(sp.bary_wave, np.ndarray) assert isinstance(sp.flux, np.ndarray) # getSpectrum xmin",
"isinstance(sp.bary_wave, np.ndarray) assert isinstance(sp.flux, np.ndarray) # getSpectrum xmin = 7660",
"assert len(sp.wave) == len(sp.flux) assert np.min(sp.wave) > sp.xmin assert np.max(sp.wave)",
"assert isinstance(sp.date, str) assert isinstance(sp.datetime, datetime.datetime) assert isinstance(sp.v_bary, float) assert",
"len(sp.sky_wave) == len(sp.sky_flux) assert np.min(sp.sky_wave) > sp.xmin assert np.max(sp.sky_wave) <",
"assert isinstance(sp.raw_sky_flux, np.ndarray) assert len(sp.raw_sky_wave) == len(sp.raw_sky_flux) assert isinstance(sp.wave, np.ndarray)",
"== len(sp.interp_flux) assert len(sp.grid) == len(sp.interp_bary_flux) assert np.min(sp.grid) > sp.xmin",
"assert len(sp.raw_sky_wave) == len(sp.raw_sky_flux) assert isinstance(sp.wave, np.ndarray) assert isinstance(sp.bary_wave, np.ndarray)",
"str) assert isinstance(sp.flux_units, str) # Raw assert isinstance(sp.raw_wave, np.ndarray) assert",
"xmax=xmax) assert xmin == sp.xmin assert xmax == sp.xmax assert",
"assert isinstance(sp.raw_sky_wave, np.ndarray) assert isinstance(sp.raw_sky_flux, np.ndarray) assert len(sp.raw_sky_wave) == len(sp.raw_sky_flux)",
"isinstance(sp.raw_grid, np.ndarray) assert len(sp.raw_grid) == 200443 # print(len(sp.raw_grid)) assert isinstance(sp.raw_sky_wave,",
"sp.xmin assert xmax == sp.xmax assert isinstance(sp.wave, np.ndarray) assert isinstance(sp.flux,",
"7680 sp.getSpectrum(xmin=xmin, xmax=xmax) assert xmin == sp.xmin assert xmax ==",
"assert len(sp.grid) == len(sp.interp_bary_flux) assert np.min(sp.grid) > sp.xmin assert np.max(sp.grid)",
"assert isinstance(sp.raw_bary_wave, np.ndarray) assert isinstance(sp.raw_flux, np.ndarray) assert len(sp.raw_wave) == len(sp.raw_bary_wave)",
"shift zoom_xmin = 7661 zoom_xmax = 7679 shift = 0.05",
"< sp.xmax assert isinstance(sp.grid, np.ndarray) assert isinstance(sp.interp_flux, np.ndarray) assert isinstance(sp.interp_bary_flux,",
"assert np.max(sp.bary_wave) < sp.xmax assert isinstance(sp.grid, np.ndarray) assert isinstance(sp.interp_flux, np.ndarray)",
"== 200443 # print(len(sp.raw_grid)) assert isinstance(sp.raw_sky_wave, np.ndarray) assert isinstance(sp.raw_sky_flux, np.ndarray)",
"np.ndarray) assert len(sp.wave) == len(sp.flux) assert np.min(sp.wave) > sp.xmin assert",
"getSpectrum xmin = 7660 xmax = 7680 sp.getSpectrum(xmin=xmin, xmax=xmax) assert",
"assert isinstance(sp.bary_flux, np.ndarray) assert len(sp.bary_wave) == len(sp.bary_flux) assert np.min(sp.bary_wave) >",
"xmax == sp.xmax assert isinstance(sp.wave, np.ndarray) assert isinstance(sp.flux, np.ndarray) assert",
"len(sp.grid) == len(sp.interp_bary_flux) assert np.min(sp.grid) > sp.xmin assert np.max(sp.grid) <",
"len(sp.grid) == len(sp.interp_flux) assert len(sp.grid) == len(sp.interp_bary_flux) assert np.min(sp.grid) >",
"np from edibles.utils.edibles_spectrum import EdiblesSpectrum def testEdiblesSpectrum(filename=\"tests/HD170740_w860_redl_20140915_O12.fits\"): # Spectrum information",
"7661 zoom_xmax = 7679 shift = 0.05 sp.shift(shift=shift, zoom_xmin=zoom_xmin, zoom_xmax=zoom_xmax)",
"isinstance(sp.bary_wave, np.ndarray) assert isinstance(sp.bary_flux, np.ndarray) assert len(sp.bary_wave) == len(sp.bary_flux) assert",
"np.ndarray) assert isinstance(sp.sky_flux, np.ndarray) assert len(sp.sky_wave) == len(sp.sky_flux) assert np.min(sp.sky_wave)",
"== len(sp.flux) assert np.min(sp.wave) > sp.xmin assert np.max(sp.wave) < sp.xmax",
"isinstance(sp.raw_sky_flux, np.ndarray) assert len(sp.raw_sky_wave) == len(sp.raw_sky_flux) assert isinstance(sp.wave, np.ndarray) assert",
"np.min(sp.wave) > sp.xmin assert np.max(sp.wave) < sp.xmax assert isinstance(sp.bary_wave, np.ndarray)",
"assert np.min(sp.bary_wave) > sp.xmin assert np.max(sp.bary_wave) < sp.xmax assert isinstance(sp.grid,",
"sp.xmin assert np.max(sp.bary_wave) < sp.xmax assert isinstance(sp.grid, np.ndarray) assert isinstance(sp.interp_flux,",
"np.ndarray) assert len(sp.raw_wave) == len(sp.raw_bary_wave) assert len(sp.raw_wave) == len(sp.raw_flux) assert",
"import datetime import numpy as np from edibles.utils.edibles_spectrum import EdiblesSpectrum",
"isinstance(sp.bary_flux, np.ndarray) assert len(sp.bary_wave) == len(sp.bary_flux) assert np.min(sp.bary_wave) > sp.xmin",
"np.min(sp.sky_wave) > sp.xmin assert np.max(sp.sky_wave) < sp.xmax # shift zoom_xmin",
"< sp.xmax if __name__ == \"__main__\": filename = \"HD170740_w860_redl_20140915_O12.fits\" testEdiblesSpectrum(filename=filename)",
"== len(sp.interp_bary_flux) assert np.min(sp.grid) > sp.xmin assert np.max(sp.grid) < sp.xmax",
"assert isinstance(sp.wave_units, str) assert isinstance(sp.flux_units, str) # Raw assert isinstance(sp.raw_wave,",
"assert np.max(sp.grid) < sp.xmax assert isinstance(sp.sky_wave, np.ndarray) assert isinstance(sp.sky_flux, np.ndarray)",
"assert isinstance(sp.datetime, datetime.datetime) assert isinstance(sp.v_bary, float) assert isinstance(sp.wave_units, str) assert",
"np.max(sp.grid) < sp.xmax assert isinstance(sp.sky_wave, np.ndarray) assert isinstance(sp.sky_flux, np.ndarray) assert",
"isinstance(sp.datetime, datetime.datetime) assert isinstance(sp.v_bary, float) assert isinstance(sp.wave_units, str) assert isinstance(sp.flux_units,",
"# print(len(sp.raw_grid)) assert isinstance(sp.raw_sky_wave, np.ndarray) assert isinstance(sp.raw_sky_flux, np.ndarray) assert len(sp.raw_sky_wave)",
"isinstance(sp.sky_flux, np.ndarray) assert len(sp.sky_wave) == len(sp.sky_flux) assert np.min(sp.sky_wave) > sp.xmin",
"sp.xmax assert isinstance(sp.bary_wave, np.ndarray) assert isinstance(sp.bary_flux, np.ndarray) assert len(sp.bary_wave) ==",
"isinstance(sp.wave, np.ndarray) assert isinstance(sp.bary_wave, np.ndarray) assert isinstance(sp.flux, np.ndarray) # getSpectrum",
"isinstance(sp.flux, np.ndarray) assert len(sp.wave) == len(sp.flux) assert np.min(sp.wave) > sp.xmin",
"len(sp.raw_flux) assert isinstance(sp.raw_grid, np.ndarray) assert len(sp.raw_grid) == 200443 # print(len(sp.raw_grid))",
"= 0.05 sp.shift(shift=shift, zoom_xmin=zoom_xmin, zoom_xmax=zoom_xmax) assert isinstance(sp.wave, np.ndarray) assert isinstance(sp.flux,",
"assert isinstance(sp.wave, np.ndarray) assert isinstance(sp.flux, np.ndarray) assert len(sp.wave) == len(sp.flux)",
"len(sp.raw_wave) == len(sp.raw_bary_wave) assert len(sp.raw_wave) == len(sp.raw_flux) assert isinstance(sp.raw_grid, np.ndarray)",
"7679 shift = 0.05 sp.shift(shift=shift, zoom_xmin=zoom_xmin, zoom_xmax=zoom_xmax) assert isinstance(sp.wave, np.ndarray)",
"np.ndarray) assert len(sp.raw_sky_wave) == len(sp.raw_sky_flux) assert isinstance(sp.wave, np.ndarray) assert isinstance(sp.bary_wave,",
"isinstance(sp.raw_sky_wave, np.ndarray) assert isinstance(sp.raw_sky_flux, np.ndarray) assert len(sp.raw_sky_wave) == len(sp.raw_sky_flux) assert",
"assert isinstance(sp.target, str) assert isinstance(sp.date, str) assert isinstance(sp.datetime, datetime.datetime) assert",
"fully_featured=True, noDATADIR=True) assert isinstance(sp.header, astropy.io.fits.header.Header) assert isinstance(sp.target, str) assert isinstance(sp.date,",
"np.ndarray) assert isinstance(sp.flux, np.ndarray) assert len(sp.wave) == len(sp.flux) assert np.min(sp.wave)",
"np.ndarray) assert len(sp.grid) == len(sp.interp_flux) assert len(sp.grid) == len(sp.interp_bary_flux) assert",
"isinstance(sp.raw_flux, np.ndarray) assert len(sp.raw_wave) == len(sp.raw_bary_wave) assert len(sp.raw_wave) == len(sp.raw_flux)",
"> sp.xmin assert np.max(sp.sky_wave) < sp.xmax # shift zoom_xmin =",
"== sp.xmin assert xmax == sp.xmax assert isinstance(sp.wave, np.ndarray) assert",
"assert np.min(sp.sky_wave) > sp.xmin assert np.max(sp.sky_wave) < sp.xmax # shift",
"np.min(sp.bary_wave) > sp.xmin assert np.max(sp.bary_wave) < sp.xmax assert isinstance(sp.grid, np.ndarray)",
"isinstance(sp.interp_bary_flux, np.ndarray) assert len(sp.grid) == len(sp.interp_flux) assert len(sp.grid) == len(sp.interp_bary_flux)",
"assert np.min(sp.sky_wave) > sp.xmin assert np.max(sp.sky_wave) < sp.xmax if __name__",
"assert np.max(sp.wave) < sp.xmax assert isinstance(sp.bary_wave, np.ndarray) assert isinstance(sp.bary_flux, np.ndarray)",
"sp.xmax assert isinstance(sp.grid, np.ndarray) assert isinstance(sp.interp_flux, np.ndarray) assert isinstance(sp.interp_bary_flux, np.ndarray)",
"def testEdiblesSpectrum(filename=\"tests/HD170740_w860_redl_20140915_O12.fits\"): # Spectrum information sp = EdiblesSpectrum(filename=filename, fully_featured=True, noDATADIR=True)",
"sp.xmin assert np.max(sp.sky_wave) < sp.xmax if __name__ == \"__main__\": filename",
"assert np.min(sp.grid) > sp.xmin assert np.max(sp.grid) < sp.xmax assert isinstance(sp.sky_wave,",
"datetime.datetime) assert isinstance(sp.v_bary, float) assert isinstance(sp.wave_units, str) assert isinstance(sp.flux_units, str)",
"isinstance(sp.wave_units, str) assert isinstance(sp.flux_units, str) # Raw assert isinstance(sp.raw_wave, np.ndarray)",
"assert isinstance(sp.wave, np.ndarray) assert isinstance(sp.bary_wave, np.ndarray) assert isinstance(sp.flux, np.ndarray) #",
"len(sp.bary_wave) == len(sp.bary_flux) assert np.min(sp.bary_wave) > sp.xmin assert np.max(sp.bary_wave) <",
"assert isinstance(sp.flux, np.ndarray) # getSpectrum xmin = 7660 xmax =",
"np.ndarray) # getSpectrum xmin = 7660 xmax = 7680 sp.getSpectrum(xmin=xmin,",
"sp.xmin assert np.max(sp.wave) < sp.xmax assert isinstance(sp.bary_wave, np.ndarray) assert isinstance(sp.bary_flux,",
"import EdiblesSpectrum def testEdiblesSpectrum(filename=\"tests/HD170740_w860_redl_20140915_O12.fits\"): # Spectrum information sp = EdiblesSpectrum(filename=filename,",
"testEdiblesSpectrum(filename=\"tests/HD170740_w860_redl_20140915_O12.fits\"): # Spectrum information sp = EdiblesSpectrum(filename=filename, fully_featured=True, noDATADIR=True) assert",
"from edibles.utils.edibles_spectrum import EdiblesSpectrum def testEdiblesSpectrum(filename=\"tests/HD170740_w860_redl_20140915_O12.fits\"): # Spectrum information sp",
"assert isinstance(sp.raw_flux, np.ndarray) assert len(sp.raw_wave) == len(sp.raw_bary_wave) assert len(sp.raw_wave) ==",
"7660 xmax = 7680 sp.getSpectrum(xmin=xmin, xmax=xmax) assert xmin == sp.xmin",
"np.max(sp.sky_wave) < sp.xmax # shift zoom_xmin = 7661 zoom_xmax =",
"<gh_stars>1-10 import astropy import datetime import numpy as np from",
"assert isinstance(sp.header, astropy.io.fits.header.Header) assert isinstance(sp.target, str) assert isinstance(sp.date, str) assert",
"assert isinstance(sp.raw_wave, np.ndarray) assert isinstance(sp.raw_bary_wave, np.ndarray) assert isinstance(sp.raw_flux, np.ndarray) assert",
"isinstance(sp.flux, np.ndarray) # getSpectrum xmin = 7660 xmax = 7680",
"assert np.min(sp.wave) > sp.xmin assert np.max(sp.wave) < sp.xmax assert isinstance(sp.bary_wave,",
"np.ndarray) assert isinstance(sp.flux, np.ndarray) # getSpectrum xmin = 7660 xmax"
] |
[
"from swift.common.utils import listdir, quote # Used by hash_path to",
"storage directory :param datadir: Base data directory :param partition: Partition",
"of process restart before sweep completed shuffle(device_dir) for device in",
"devices :param logger: a logger object ''' device_dir = listdir(devices)",
"logger=None): ''' Given a devices path and a data directory,",
"2.0 (the \"License\"); # you may not use this file",
"version rather than a hex digest :returns: hash string \"\"\"",
"shuffle from ConfigParser import ConfigParser, NoSectionError, NoOptionError from swift import",
"\"\"\" invalid_device = False invalid_partition = False if not device",
"md5(HASH_PATH_PREFIX + '/' + '/'.join(paths) + HASH_PATH_SUFFIX).hexdigest() def normalize_timestamp(timestamp): \"\"\"",
"governing permissions and # limitations under the License. \"\"\"Methods &",
"# Copyright (c) 2010-2013 OpenStack, LLC. # # Licensed under",
"required if object is provided') paths = [account] if container:",
"to be audited :param datadir: a directory located under self.devices.",
"and not \\ os.path.ismount(os.path.join(devices, device)): if logger: logger.debug( _('Skipping %s",
"of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless",
"raw_digest: If True, return the raw version rather than a",
"this value to all paths; guessing the hash a path",
"device_dir = listdir(devices) # randomize devices in case of process",
"if object and not container: raise ValueError('container is required if",
":param object: Object :param raw_digest: If True, return the raw",
"\"\"\" Get the storage directory :param datadir: Base data directory",
"HASH_PATH_PREFIX: sys.exit(\"Error: [swift-hash]: both swift_hash_path_suffix \" \"and swift_hash_path_prefix are missing",
"e: if e.errno != errno.ENOTDIR: raise continue for asuffix in",
"ANY KIND, either express or # implied. # See the",
"raise ValueError('Invalid device: %s' % quote(device or '')) elif invalid_partition:",
"container: raise ValueError('container is required if object is provided') paths",
"datadir: Base data directory :param partition: Partition :param name_hash: Account,",
"\"\"\"Methods & Attributes for shared 'on-disk' data layouts.\"\"\" import os",
"pass try: HASH_PATH_PREFIX = _hash_conf.get('swift-hash', 'swift_hash_path_prefix') except (NoSectionError, NoOptionError): pass",
"object ''' device_dir = listdir(devices) # randomize devices in case",
"listdir(suff_path) except OSError as e: if e.errno != errno.ENOTDIR: raise",
"a bit more security when generating hashes for # paths.",
"Container :param object: Object :param raw_digest: If True, return the",
"as e: if e.errno != errno.ENOTDIR: raise continue for asuffix",
"suffix: path name suffix required for all names returned :param",
"quote # Used by hash_path to offer a bit more",
"use this file except in compliance with the License. #",
"name_hash: Account, container or object name hash :returns: Storage directory",
":returns: hash string \"\"\" if object and not container: raise",
"ConfigParser import ConfigParser, NoSectionError, NoOptionError from swift import gettext_ as",
"partition in ['.', '..']: invalid_partition = True if invalid_device: raise",
"bit more security when generating hashes for # paths. It",
"simply appends this value to all paths; guessing the hash",
"partition \"\"\" invalid_device = False invalid_partition = False if not",
"partition): \"\"\" Validate that a device and a partition are",
"listdir(datadir_path) for partition in partitions: part_path = os.path.join(datadir_path, partition) try:",
"listdir, quote # Used by hash_path to offer a bit",
"Given a devices path and a data directory, yield (path,",
"hashes: hash_path = os.path.join(suff_path, hsh) try: files = sorted(listdir(hash_path), reverse=True)",
"the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required",
"= [account] if container: paths.append(container) if object: paths.append(object) if raw_digest:",
"if raw_digest: return md5(HASH_PATH_PREFIX + '/' + '/'.join(paths) + HASH_PATH_SUFFIX).digest()",
"License. # You may obtain a copy of the License",
"'..']: invalid_partition = True if invalid_device: raise ValueError('Invalid device: %s'",
"devices path and a data directory, yield (path, device, partition)",
"invalid device or partition \"\"\" invalid_device = False invalid_partition =",
"\"from /etc/swift/swift.conf\") def hash_path(account, container=None, object=None, raw_digest=False): \"\"\" Get the",
"# Used by hash_path to offer a bit more security",
"account: Account :param container: Container :param object: Object :param raw_digest:",
"partition) for all files in that directory :param devices: parent",
"under the License is distributed on an \"AS IS\" BASIS,",
"def storage_directory(datadir, partition, name_hash): \"\"\" Get the storage directory :param",
"License for the specific language governing permissions and # limitations",
"hash :returns: Storage directory \"\"\" return os.path.join(datadir, str(partition), name_hash[-3:], name_hash)",
"hash_path = os.path.join(suff_path, hsh) try: files = sorted(listdir(hash_path), reverse=True) except",
"restart before sweep completed shuffle(device_dir) for device in device_dir: if",
"True, return the raw version rather than a hex digest",
"language governing permissions and # limitations under the License. \"\"\"Methods",
"reverse=True) except OSError as e: if e.errno != errno.ENOTDIR: raise",
"account/container/object :param account: Account :param container: Container :param object: Object",
"container, and object servers. :param suffix: path name suffix required",
"(string or numeric) into a standardized xxxxxxxxxx.xxxxx (10.5) format. Note",
"device and a partition are valid and won't lead to",
"in case of process restart before sweep completed shuffle(device_dir) for",
"end up with would also require knowing this suffix. _hash_conf",
"raise continue for asuffix in suffixes: suff_path = os.path.join(part_path, asuffix)",
"LLC. # # Licensed under the Apache License, Version 2.0",
"given an invalid device or partition \"\"\" invalid_device = False",
"'/' + '/'.join(paths) + HASH_PATH_SUFFIX).digest() else: return md5(HASH_PATH_PREFIX + '/'",
"files: if suffix and not fname.endswith(suffix): continue path = os.path.join(hash_path,",
"Get the storage directory :param datadir: Base data directory :param",
"a data directory, yield (path, device, partition) for all files",
"files in that directory :param devices: parent directory of the",
"import ConfigParser, NoSectionError, NoOptionError from swift import gettext_ as _",
"ValueError('Invalid device: %s' % quote(device or '')) elif invalid_partition: raise",
"case of process restart before sweep completed shuffle(device_dir) for device",
"in compliance with the License. # You may obtain a",
"raw_digest=False): \"\"\" Get the canonical hash for an account/container/object :param",
"with would also require knowing this suffix. _hash_conf = ConfigParser()",
"software # distributed under the License is distributed on an",
"represent the number of seconds. :param timestamp: unix timestamp :returns:",
"for asuffix in suffixes: suff_path = os.path.join(part_path, asuffix) try: hashes",
"'..']: invalid_device = True if not partition or '/' in",
"for fname in files: if suffix and not fname.endswith(suffix): continue",
"+ HASH_PATH_SUFFIX).hexdigest() def normalize_timestamp(timestamp): \"\"\" Format a timestamp (string or",
"by hash_path to offer a bit more security when generating",
"try: HASH_PATH_PREFIX = _hash_conf.get('swift-hash', 'swift_hash_path_prefix') except (NoSectionError, NoOptionError): pass def",
"normalized timestamp as a string \"\"\" return \"%016.05f\" % (float(timestamp))",
"if not HASH_PATH_SUFFIX and not HASH_PATH_PREFIX: sys.exit(\"Error: [swift-hash]: both swift_hash_path_suffix",
"constants defined in the account, container, and object servers. :param",
"device to validate :param partition: partition to validate :raises: ValueError",
"sweep completed shuffle(device_dir) for device in device_dir: if mount_check and",
"suffixes: suff_path = os.path.join(part_path, asuffix) try: hashes = listdir(suff_path) except",
"the account, container, and object servers. :param suffix: path name",
"not fname.endswith(suffix): continue path = os.path.join(hash_path, fname) yield path, device,",
":param raw_digest: If True, return the raw version rather than",
"and # limitations under the License. \"\"\"Methods & Attributes for",
"to offer a bit more security when generating hashes for",
"= True if invalid_device: raise ValueError('Invalid device: %s' % quote(device",
"quote(partition or '')) def storage_directory(datadir, partition, name_hash): \"\"\" Get the",
"and object servers. :param suffix: path name suffix required for",
"paths.append(container) if object: paths.append(object) if raw_digest: return md5(HASH_PATH_PREFIX + '/'",
"equal to November 20th, 2286 at 17:46 UTC will use",
"hashlib import md5 from random import shuffle from ConfigParser import",
":param logger: a logger object ''' device_dir = listdir(devices) #",
"should be one of the DATADIR constants defined in the",
"swift.common.utils import listdir, quote # Used by hash_path to offer",
"for # paths. It simply appends this value to all",
"= ConfigParser() HASH_PATH_SUFFIX = '' HASH_PATH_PREFIX = '' if _hash_conf.read('/etc/swift/swift.conf'):",
"\"\"\" Validate that a device and a partition are valid",
"not partition or '/' in partition or partition in ['.',",
"import md5 from random import shuffle from ConfigParser import ConfigParser,",
"if a mount check should be performed on devices :param",
"device: device to validate :param partition: partition to validate :raises:",
"directory :param devices: parent directory of the devices to be",
"in files: if suffix and not fname.endswith(suffix): continue path =",
"% (float(timestamp)) def validate_device_partition(device, partition): \"\"\" Validate that a device",
"Copyright (c) 2010-2013 OpenStack, LLC. # # Licensed under the",
"performed on devices :param logger: a logger object ''' device_dir",
"from ConfigParser import ConfigParser, NoSectionError, NoOptionError from swift import gettext_",
"string \"\"\" if object and not container: raise ValueError('container is",
"logger object ''' device_dir = listdir(devices) # randomize devices in",
"20th, 2286 at 17:46 UTC will use 11 digits to",
"if container: paths.append(container) if object: paths.append(object) if raw_digest: return md5(HASH_PATH_PREFIX",
"validate_device_partition(device, partition): \"\"\" Validate that a device and a partition",
":param partition: partition to validate :raises: ValueError if given an",
"parent directory of the devices to be audited :param datadir:",
"layouts.\"\"\" import os import sys import errno from hashlib import",
"lead to directory traversal when used. :param device: device to",
"def validate_configuration(): if not HASH_PATH_SUFFIX and not HASH_PATH_PREFIX: sys.exit(\"Error: [swift-hash]:",
"timestamp as a string \"\"\" return \"%016.05f\" % (float(timestamp)) def",
"See the License for the specific language governing permissions and",
"that a device and a partition are valid and won't",
"If True, return the raw version rather than a hex",
"data directory :param partition: Partition :param name_hash: Account, container or",
"device, datadir) partitions = listdir(datadir_path) for partition in partitions: part_path",
"the License. # You may obtain a copy of the",
"at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable",
"for the specific language governing permissions and # limitations under",
"is provided') paths = [account] if container: paths.append(container) if object:",
"to in writing, software # distributed under the License is",
"ConfigParser() HASH_PATH_SUFFIX = '' HASH_PATH_PREFIX = '' if _hash_conf.read('/etc/swift/swift.conf'): try:",
"audit_location_generator(devices, datadir, suffix='', mount_check=True, logger=None): ''' Given a devices path",
"# See the License for the specific language governing permissions",
"% quote(device or '')) elif invalid_partition: raise ValueError('Invalid partition: %s'",
"datadir: a directory located under self.devices. This should be one",
"device, partition) for all files in that directory :param devices:",
"is not mounted'), device) continue datadir_path = os.path.join(devices, device, datadir)",
"or '')) def storage_directory(datadir, partition, name_hash): \"\"\" Get the storage",
"or agreed to in writing, software # distributed under the",
"will end up with would also require knowing this suffix.",
"required by applicable law or agreed to in writing, software",
"more security when generating hashes for # paths. It simply",
"mount_check: Flag to check if a mount check should be",
"device or '/' in device or device in ['.', '..']:",
"'/'.join(paths) + HASH_PATH_SUFFIX).digest() else: return md5(HASH_PATH_PREFIX + '/' + '/'.join(paths)",
"files = sorted(listdir(hash_path), reverse=True) except OSError as e: if e.errno",
"is required if object is provided') paths = [account] if",
"try: suffixes = listdir(part_path) except OSError as e: if e.errno",
"BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either",
"HASH_PATH_SUFFIX and not HASH_PATH_PREFIX: sys.exit(\"Error: [swift-hash]: both swift_hash_path_suffix \" \"and",
"continue datadir_path = os.path.join(devices, device, datadir) partitions = listdir(datadir_path) for",
"with the License. # You may obtain a copy of",
"for partition in partitions: part_path = os.path.join(datadir_path, partition) try: suffixes",
"this suffix. _hash_conf = ConfigParser() HASH_PATH_SUFFIX = '' HASH_PATH_PREFIX =",
"if _hash_conf.read('/etc/swift/swift.conf'): try: HASH_PATH_SUFFIX = _hash_conf.get('swift-hash', 'swift_hash_path_suffix') except (NoSectionError, NoOptionError):",
"elif invalid_partition: raise ValueError('Invalid partition: %s' % quote(partition or ''))",
"OpenStack, LLC. # # Licensed under the Apache License, Version",
"that timestamps using values greater than or equal to November",
"suffix and not fname.endswith(suffix): continue path = os.path.join(hash_path, fname) yield",
"compliance with the License. # You may obtain a copy",
"\"%016.05f\" % (float(timestamp)) def validate_device_partition(device, partition): \"\"\" Validate that a",
"for all names returned :param mount_check: Flag to check if",
"agreed to in writing, software # distributed under the License",
"logger.debug( _('Skipping %s as it is not mounted'), device) continue",
"if e.errno != errno.ENOTDIR: raise continue for fname in files:",
"= True if not partition or '/' in partition or",
"%s as it is not mounted'), device) continue datadir_path =",
"path name suffix required for all names returned :param mount_check:",
"try: files = sorted(listdir(hash_path), reverse=True) except OSError as e: if",
"import listdir, quote # Used by hash_path to offer a",
"distributed under the License is distributed on an \"AS IS\"",
":param account: Account :param container: Container :param object: Object :param",
"or # implied. # See the License for the specific",
"as e: if e.errno != errno.ENOTDIR: raise continue for hsh",
"_('Skipping %s as it is not mounted'), device) continue datadir_path",
"md5(HASH_PATH_PREFIX + '/' + '/'.join(paths) + HASH_PATH_SUFFIX).digest() else: return md5(HASH_PATH_PREFIX",
"str(partition), name_hash[-3:], name_hash) def audit_location_generator(devices, datadir, suffix='', mount_check=True, logger=None): '''",
"datadir, suffix='', mount_check=True, logger=None): ''' Given a devices path and",
"hex digest :returns: hash string \"\"\" if object and not",
"except in compliance with the License. # You may obtain",
"or partition \"\"\" invalid_device = False invalid_partition = False if",
"in ['.', '..']: invalid_partition = True if invalid_device: raise ValueError('Invalid",
"a device and a partition are valid and won't lead",
"= _hash_conf.get('swift-hash', 'swift_hash_path_prefix') except (NoSectionError, NoOptionError): pass def validate_configuration(): if",
"Licensed under the Apache License, Version 2.0 (the \"License\"); #",
"import sys import errno from hashlib import md5 from random",
"HASH_PATH_SUFFIX = '' HASH_PATH_PREFIX = '' if _hash_conf.read('/etc/swift/swift.conf'): try: HASH_PATH_SUFFIX",
"else: return md5(HASH_PATH_PREFIX + '/' + '/'.join(paths) + HASH_PATH_SUFFIX).hexdigest() def",
"11 digits to represent the number of seconds. :param timestamp:",
"not use this file except in compliance with the License.",
"hsh in hashes: hash_path = os.path.join(suff_path, hsh) try: files =",
"express or # implied. # See the License for the",
"partition: Partition :param name_hash: Account, container or object name hash",
"mounted'), device) continue datadir_path = os.path.join(devices, device, datadir) partitions =",
"writing, software # distributed under the License is distributed on",
"canonical hash for an account/container/object :param account: Account :param container:",
"the hash a path # will end up with would",
"you may not use this file except in compliance with",
"\"\"\" return os.path.join(datadir, str(partition), name_hash[-3:], name_hash) def audit_location_generator(devices, datadir, suffix='',",
"suffix='', mount_check=True, logger=None): ''' Given a devices path and a",
"# Licensed under the Apache License, Version 2.0 (the \"License\");",
"errno.ENOTDIR: raise continue for hsh in hashes: hash_path = os.path.join(suff_path,",
"= os.path.join(datadir_path, partition) try: suffixes = listdir(part_path) except OSError as",
"directory, yield (path, device, partition) for all files in that",
"it is not mounted'), device) continue datadir_path = os.path.join(devices, device,",
"self.devices. This should be one of the DATADIR constants defined",
"HASH_PATH_SUFFIX).digest() else: return md5(HASH_PATH_PREFIX + '/' + '/'.join(paths) + HASH_PATH_SUFFIX).hexdigest()",
"continue for asuffix in suffixes: suff_path = os.path.join(part_path, asuffix) try:",
"device_dir: if mount_check and not \\ os.path.ismount(os.path.join(devices, device)): if logger:",
"container: Container :param object: Object :param raw_digest: If True, return",
"not device or '/' in device or device in ['.',",
"return md5(HASH_PATH_PREFIX + '/' + '/'.join(paths) + HASH_PATH_SUFFIX).digest() else: return",
"raise ValueError('container is required if object is provided') paths =",
"and not container: raise ValueError('container is required if object is",
"the storage directory :param datadir: Base data directory :param partition:",
"Account, container or object name hash :returns: Storage directory \"\"\"",
"is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES",
"value to all paths; guessing the hash a path #",
"the canonical hash for an account/container/object :param account: Account :param",
"'' if _hash_conf.read('/etc/swift/swift.conf'): try: HASH_PATH_SUFFIX = _hash_conf.get('swift-hash', 'swift_hash_path_suffix') except (NoSectionError,",
"digits to represent the number of seconds. :param timestamp: unix",
"HASH_PATH_SUFFIX = _hash_conf.get('swift-hash', 'swift_hash_path_suffix') except (NoSectionError, NoOptionError): pass try: HASH_PATH_PREFIX",
"'' HASH_PATH_PREFIX = '' if _hash_conf.read('/etc/swift/swift.conf'): try: HASH_PATH_SUFFIX = _hash_conf.get('swift-hash',",
"container=None, object=None, raw_digest=False): \"\"\" Get the canonical hash for an",
"devices to be audited :param datadir: a directory located under",
":param container: Container :param object: Object :param raw_digest: If True,",
"device or partition \"\"\" invalid_device = False invalid_partition = False",
"in suffixes: suff_path = os.path.join(part_path, asuffix) try: hashes = listdir(suff_path)",
"require knowing this suffix. _hash_conf = ConfigParser() HASH_PATH_SUFFIX = ''",
"os.path.join(datadir, str(partition), name_hash[-3:], name_hash) def audit_location_generator(devices, datadir, suffix='', mount_check=True, logger=None):",
"or equal to November 20th, 2286 at 17:46 UTC will",
"or numeric) into a standardized xxxxxxxxxx.xxxxx (10.5) format. Note that",
"continue for hsh in hashes: hash_path = os.path.join(suff_path, hsh) try:",
"for shared 'on-disk' data layouts.\"\"\" import os import sys import",
"to represent the number of seconds. :param timestamp: unix timestamp",
"swift_hash_path_prefix are missing \" \"from /etc/swift/swift.conf\") def hash_path(account, container=None, object=None,",
"UTC will use 11 digits to represent the number of",
"unix timestamp :returns: normalized timestamp as a string \"\"\" return",
"2286 at 17:46 UTC will use 11 digits to represent",
"values greater than or equal to November 20th, 2286 at",
"should be performed on devices :param logger: a logger object",
"the License is distributed on an \"AS IS\" BASIS, #",
"datadir) partitions = listdir(datadir_path) for partition in partitions: part_path =",
"HASH_PATH_SUFFIX).hexdigest() def normalize_timestamp(timestamp): \"\"\" Format a timestamp (string or numeric)",
":param devices: parent directory of the devices to be audited",
":param datadir: a directory located under self.devices. This should be",
"under the License. \"\"\"Methods & Attributes for shared 'on-disk' data",
"raise continue for fname in files: if suffix and not",
"Account :param container: Container :param object: Object :param raw_digest: If",
"Partition :param name_hash: Account, container or object name hash :returns:",
"partition: partition to validate :raises: ValueError if given an invalid",
"not mounted'), device) continue datadir_path = os.path.join(devices, device, datadir) partitions",
"NoOptionError): pass try: HASH_PATH_PREFIX = _hash_conf.get('swift-hash', 'swift_hash_path_prefix') except (NoSectionError, NoOptionError):",
"\" \"and swift_hash_path_prefix are missing \" \"from /etc/swift/swift.conf\") def hash_path(account,",
"partition in partitions: part_path = os.path.join(datadir_path, partition) try: suffixes =",
"raise continue for hsh in hashes: hash_path = os.path.join(suff_path, hsh)",
"as e: if e.errno != errno.ENOTDIR: raise continue for fname",
"# paths. It simply appends this value to all paths;",
"= listdir(suff_path) except OSError as e: if e.errno != errno.ENOTDIR:",
"an invalid device or partition \"\"\" invalid_device = False invalid_partition",
"swift_hash_path_suffix \" \"and swift_hash_path_prefix are missing \" \"from /etc/swift/swift.conf\") def",
":param suffix: path name suffix required for all names returned",
"law or agreed to in writing, software # distributed under",
"xxxxxxxxxx.xxxxx (10.5) format. Note that timestamps using values greater than",
"paths; guessing the hash a path # will end up",
"_hash_conf = ConfigParser() HASH_PATH_SUFFIX = '' HASH_PATH_PREFIX = '' if",
"a logger object ''' device_dir = listdir(devices) # randomize devices",
"_hash_conf.read('/etc/swift/swift.conf'): try: HASH_PATH_SUFFIX = _hash_conf.get('swift-hash', 'swift_hash_path_suffix') except (NoSectionError, NoOptionError): pass",
"+ '/'.join(paths) + HASH_PATH_SUFFIX).hexdigest() def normalize_timestamp(timestamp): \"\"\" Format a timestamp",
"a path # will end up with would also require",
"= False invalid_partition = False if not device or '/'",
"False invalid_partition = False if not device or '/' in",
":param datadir: Base data directory :param partition: Partition :param name_hash:",
"appends this value to all paths; guessing the hash a",
"also require knowing this suffix. _hash_conf = ConfigParser() HASH_PATH_SUFFIX =",
"if e.errno != errno.ENOTDIR: raise continue for hsh in hashes:",
"2010-2013 OpenStack, LLC. # # Licensed under the Apache License,",
"ValueError('Invalid partition: %s' % quote(partition or '')) def storage_directory(datadir, partition,",
"hash_path(account, container=None, object=None, raw_digest=False): \"\"\" Get the canonical hash for",
"be audited :param datadir: a directory located under self.devices. This",
"'')) def storage_directory(datadir, partition, name_hash): \"\"\" Get the storage directory",
"invalid_partition: raise ValueError('Invalid partition: %s' % quote(partition or '')) def",
"import errno from hashlib import md5 from random import shuffle",
"won't lead to directory traversal when used. :param device: device",
"timestamp (string or numeric) into a standardized xxxxxxxxxx.xxxxx (10.5) format.",
"validate :param partition: partition to validate :raises: ValueError if given",
"when used. :param device: device to validate :param partition: partition",
"in device_dir: if mount_check and not \\ os.path.ismount(os.path.join(devices, device)): if",
"storage_directory(datadir, partition, name_hash): \"\"\" Get the storage directory :param datadir:",
"CONDITIONS OF ANY KIND, either express or # implied. #",
"not \\ os.path.ismount(os.path.join(devices, device)): if logger: logger.debug( _('Skipping %s as",
"in hashes: hash_path = os.path.join(suff_path, hsh) try: files = sorted(listdir(hash_path),",
"% quote(partition or '')) def storage_directory(datadir, partition, name_hash): \"\"\" Get",
"directory traversal when used. :param device: device to validate :param",
"may obtain a copy of the License at # #",
"'/' in partition or partition in ['.', '..']: invalid_partition =",
"OSError as e: if e.errno != errno.ENOTDIR: raise continue for",
"import gettext_ as _ from swift.common.utils import listdir, quote #",
"or object name hash :returns: Storage directory \"\"\" return os.path.join(datadir,",
"a partition are valid and won't lead to directory traversal",
"timestamps using values greater than or equal to November 20th,",
"device: %s' % quote(device or '')) elif invalid_partition: raise ValueError('Invalid",
"IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,",
"partition: %s' % quote(partition or '')) def storage_directory(datadir, partition, name_hash):",
"be one of the DATADIR constants defined in the account,",
"device)): if logger: logger.debug( _('Skipping %s as it is not",
"return md5(HASH_PATH_PREFIX + '/' + '/'.join(paths) + HASH_PATH_SUFFIX).hexdigest() def normalize_timestamp(timestamp):",
"ValueError('container is required if object is provided') paths = [account]",
"in the account, container, and object servers. :param suffix: path",
"may not use this file except in compliance with the",
"check if a mount check should be performed on devices",
"'swift_hash_path_prefix') except (NoSectionError, NoOptionError): pass def validate_configuration(): if not HASH_PATH_SUFFIX",
"suffix required for all names returned :param mount_check: Flag to",
"from random import shuffle from ConfigParser import ConfigParser, NoSectionError, NoOptionError",
"asuffix) try: hashes = listdir(suff_path) except OSError as e: if",
"_ from swift.common.utils import listdir, quote # Used by hash_path",
"!= errno.ENOTDIR: raise continue for asuffix in suffixes: suff_path =",
"HASH_PATH_PREFIX = '' if _hash_conf.read('/etc/swift/swift.conf'): try: HASH_PATH_SUFFIX = _hash_conf.get('swift-hash', 'swift_hash_path_suffix')",
"all files in that directory :param devices: parent directory of",
"WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or",
"not HASH_PATH_PREFIX: sys.exit(\"Error: [swift-hash]: both swift_hash_path_suffix \" \"and swift_hash_path_prefix are",
"for an account/container/object :param account: Account :param container: Container :param",
"this file except in compliance with the License. # You",
"(NoSectionError, NoOptionError): pass try: HASH_PATH_PREFIX = _hash_conf.get('swift-hash', 'swift_hash_path_prefix') except (NoSectionError,",
"Format a timestamp (string or numeric) into a standardized xxxxxxxxxx.xxxxx",
"name_hash) def audit_location_generator(devices, datadir, suffix='', mount_check=True, logger=None): ''' Given a",
"\"\"\" Format a timestamp (string or numeric) into a standardized",
"the number of seconds. :param timestamp: unix timestamp :returns: normalized",
"guessing the hash a path # will end up with",
"completed shuffle(device_dir) for device in device_dir: if mount_check and not",
"part_path = os.path.join(datadir_path, partition) try: suffixes = listdir(part_path) except OSError",
"data directory, yield (path, device, partition) for all files in",
"# # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law",
"''' device_dir = listdir(devices) # randomize devices in case of",
"def hash_path(account, container=None, object=None, raw_digest=False): \"\"\" Get the canonical hash",
"the raw version rather than a hex digest :returns: hash",
"to November 20th, 2286 at 17:46 UTC will use 11",
"# # Licensed under the Apache License, Version 2.0 (the",
"to check if a mount check should be performed on",
"in that directory :param devices: parent directory of the devices",
"knowing this suffix. _hash_conf = ConfigParser() HASH_PATH_SUFFIX = '' HASH_PATH_PREFIX",
"file except in compliance with the License. # You may",
"on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS",
"Attributes for shared 'on-disk' data layouts.\"\"\" import os import sys",
"gettext_ as _ from swift.common.utils import listdir, quote # Used",
"for device in device_dir: if mount_check and not \\ os.path.ismount(os.path.join(devices,",
"using values greater than or equal to November 20th, 2286",
"if suffix and not fname.endswith(suffix): continue path = os.path.join(hash_path, fname)",
"mount_check and not \\ os.path.ismount(os.path.join(devices, device)): if logger: logger.debug( _('Skipping",
"devices: parent directory of the devices to be audited :param",
"a mount check should be performed on devices :param logger:",
"raise ValueError('Invalid partition: %s' % quote(partition or '')) def storage_directory(datadir,",
"+ '/' + '/'.join(paths) + HASH_PATH_SUFFIX).hexdigest() def normalize_timestamp(timestamp): \"\"\" Format",
"partition to validate :raises: ValueError if given an invalid device",
"logger: a logger object ''' device_dir = listdir(devices) # randomize",
"# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express",
"or '/' in device or device in ['.', '..']: invalid_device",
"mount check should be performed on devices :param logger: a",
"devices in case of process restart before sweep completed shuffle(device_dir)",
"datadir_path = os.path.join(devices, device, datadir) partitions = listdir(datadir_path) for partition",
"'/' + '/'.join(paths) + HASH_PATH_SUFFIX).hexdigest() def normalize_timestamp(timestamp): \"\"\" Format a",
"errno from hashlib import md5 from random import shuffle from",
"format. Note that timestamps using values greater than or equal",
"timestamp :returns: normalized timestamp as a string \"\"\" return \"%016.05f\"",
"os.path.join(devices, device, datadir) partitions = listdir(datadir_path) for partition in partitions:",
"invalid_partition = False if not device or '/' in device",
"number of seconds. :param timestamp: unix timestamp :returns: normalized timestamp",
"<reponame>citrix-openstack-build/swift # Copyright (c) 2010-2013 OpenStack, LLC. # # Licensed",
"random import shuffle from ConfigParser import ConfigParser, NoSectionError, NoOptionError from",
"asuffix in suffixes: suff_path = os.path.join(part_path, asuffix) try: hashes =",
"normalize_timestamp(timestamp): \"\"\" Format a timestamp (string or numeric) into a",
"hash for an account/container/object :param account: Account :param container: Container",
"path # will end up with would also require knowing",
"return os.path.join(datadir, str(partition), name_hash[-3:], name_hash) def audit_location_generator(devices, datadir, suffix='', mount_check=True,",
"continue for fname in files: if suffix and not fname.endswith(suffix):",
"offer a bit more security when generating hashes for #",
"False if not device or '/' in device or device",
"True if not partition or '/' in partition or partition",
"def validate_device_partition(device, partition): \"\"\" Validate that a device and a",
"ConfigParser, NoSectionError, NoOptionError from swift import gettext_ as _ from",
"hashes for # paths. It simply appends this value to",
"http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed",
"NoSectionError, NoOptionError from swift import gettext_ as _ from swift.common.utils",
"mount_check=True, logger=None): ''' Given a devices path and a data",
"a timestamp (string or numeric) into a standardized xxxxxxxxxx.xxxxx (10.5)",
"than or equal to November 20th, 2286 at 17:46 UTC",
"than a hex digest :returns: hash string \"\"\" if object",
"import shuffle from ConfigParser import ConfigParser, NoSectionError, NoOptionError from swift",
"\"\"\" if object and not container: raise ValueError('container is required",
"or '/' in partition or partition in ['.', '..']: invalid_partition",
"provided') paths = [account] if container: paths.append(container) if object: paths.append(object)",
"not container: raise ValueError('container is required if object is provided')",
"hash a path # will end up with would also",
"yield (path, device, partition) for all files in that directory",
"specific language governing permissions and # limitations under the License.",
"# limitations under the License. \"\"\"Methods & Attributes for shared",
"md5 from random import shuffle from ConfigParser import ConfigParser, NoSectionError,",
"if not partition or '/' in partition or partition in",
"Base data directory :param partition: Partition :param name_hash: Account, container",
"= os.path.join(devices, device, datadir) partitions = listdir(datadir_path) for partition in",
"security when generating hashes for # paths. It simply appends",
"account, container, and object servers. :param suffix: path name suffix",
"ValueError if given an invalid device or partition \"\"\" invalid_device",
"numeric) into a standardized xxxxxxxxxx.xxxxx (10.5) format. Note that timestamps",
"\" \"from /etc/swift/swift.conf\") def hash_path(account, container=None, object=None, raw_digest=False): \"\"\" Get",
"container or object name hash :returns: Storage directory \"\"\" return",
"License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by",
"partition, name_hash): \"\"\" Get the storage directory :param datadir: Base",
"NoOptionError from swift import gettext_ as _ from swift.common.utils import",
"shared 'on-disk' data layouts.\"\"\" import os import sys import errno",
"of the devices to be audited :param datadir: a directory",
":param mount_check: Flag to check if a mount check should",
"raw version rather than a hex digest :returns: hash string",
"Note that timestamps using values greater than or equal to",
"try: HASH_PATH_SUFFIX = _hash_conf.get('swift-hash', 'swift_hash_path_suffix') except (NoSectionError, NoOptionError): pass try:",
"the devices to be audited :param datadir: a directory located",
"valid and won't lead to directory traversal when used. :param",
"a directory located under self.devices. This should be one of",
"object servers. :param suffix: path name suffix required for all",
"(c) 2010-2013 OpenStack, LLC. # # Licensed under the Apache",
":param partition: Partition :param name_hash: Account, container or object name",
"(the \"License\"); # you may not use this file except",
"object: paths.append(object) if raw_digest: return md5(HASH_PATH_PREFIX + '/' + '/'.join(paths)",
"# you may not use this file except in compliance",
"(NoSectionError, NoOptionError): pass def validate_configuration(): if not HASH_PATH_SUFFIX and not",
"os.path.join(suff_path, hsh) try: files = sorted(listdir(hash_path), reverse=True) except OSError as",
"object: Object :param raw_digest: If True, return the raw version",
"Object :param raw_digest: If True, return the raw version rather",
"return \"%016.05f\" % (float(timestamp)) def validate_device_partition(device, partition): \"\"\" Validate that",
"invalid_device: raise ValueError('Invalid device: %s' % quote(device or '')) elif",
"a devices path and a data directory, yield (path, device,",
"if given an invalid device or partition \"\"\" invalid_device =",
"device) continue datadir_path = os.path.join(devices, device, datadir) partitions = listdir(datadir_path)",
"= listdir(part_path) except OSError as e: if e.errno != errno.ENOTDIR:",
"defined in the account, container, and object servers. :param suffix:",
"partitions = listdir(datadir_path) for partition in partitions: part_path = os.path.join(datadir_path,",
"validate_configuration(): if not HASH_PATH_SUFFIX and not HASH_PATH_PREFIX: sys.exit(\"Error: [swift-hash]: both",
"sys import errno from hashlib import md5 from random import",
"not HASH_PATH_SUFFIX and not HASH_PATH_PREFIX: sys.exit(\"Error: [swift-hash]: both swift_hash_path_suffix \"",
"+ '/' + '/'.join(paths) + HASH_PATH_SUFFIX).digest() else: return md5(HASH_PATH_PREFIX +",
":param device: device to validate :param partition: partition to validate",
"+ HASH_PATH_SUFFIX).digest() else: return md5(HASH_PATH_PREFIX + '/' + '/'.join(paths) +",
"WARRANTIES OR CONDITIONS OF ANY KIND, either express or #",
"be performed on devices :param logger: a logger object '''",
"to directory traversal when used. :param device: device to validate",
"# # Unless required by applicable law or agreed to",
"# implied. # See the License for the specific language",
"directory of the devices to be audited :param datadir: a",
"& Attributes for shared 'on-disk' data layouts.\"\"\" import os import",
"if object: paths.append(object) if raw_digest: return md5(HASH_PATH_PREFIX + '/' +",
":param timestamp: unix timestamp :returns: normalized timestamp as a string",
"= listdir(devices) # randomize devices in case of process restart",
"obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0",
"'/' in device or device in ['.', '..']: invalid_device =",
"Version 2.0 (the \"License\"); # you may not use this",
"DATADIR constants defined in the account, container, and object servers.",
"invalid_device = False invalid_partition = False if not device or",
"or partition in ['.', '..']: invalid_partition = True if invalid_device:",
"object is provided') paths = [account] if container: paths.append(container) if",
"at 17:46 UTC will use 11 digits to represent the",
"located under self.devices. This should be one of the DATADIR",
"check should be performed on devices :param logger: a logger",
"paths. It simply appends this value to all paths; guessing",
"= os.path.join(part_path, asuffix) try: hashes = listdir(suff_path) except OSError as",
"directory :param datadir: Base data directory :param partition: Partition :param",
"would also require knowing this suffix. _hash_conf = ConfigParser() HASH_PATH_SUFFIX",
"are missing \" \"from /etc/swift/swift.conf\") def hash_path(account, container=None, object=None, raw_digest=False):",
"implied. # See the License for the specific language governing",
"partition are valid and won't lead to directory traversal when",
"except (NoSectionError, NoOptionError): pass def validate_configuration(): if not HASH_PATH_SUFFIX and",
"under self.devices. This should be one of the DATADIR constants",
"listdir(devices) # randomize devices in case of process restart before",
"sorted(listdir(hash_path), reverse=True) except OSError as e: if e.errno != errno.ENOTDIR:",
"under the Apache License, Version 2.0 (the \"License\"); # you",
"if e.errno != errno.ENOTDIR: raise continue for asuffix in suffixes:",
"\"and swift_hash_path_prefix are missing \" \"from /etc/swift/swift.conf\") def hash_path(account, container=None,",
"required for all names returned :param mount_check: Flag to check",
"os import sys import errno from hashlib import md5 from",
"up with would also require knowing this suffix. _hash_conf =",
"a standardized xxxxxxxxxx.xxxxx (10.5) format. Note that timestamps using values",
"'')) elif invalid_partition: raise ValueError('Invalid partition: %s' % quote(partition or",
"and not HASH_PATH_PREFIX: sys.exit(\"Error: [swift-hash]: both swift_hash_path_suffix \" \"and swift_hash_path_prefix",
"by applicable law or agreed to in writing, software #",
"path and a data directory, yield (path, device, partition) for",
"in device or device in ['.', '..']: invalid_device = True",
"will use 11 digits to represent the number of seconds.",
"except OSError as e: if e.errno != errno.ENOTDIR: raise continue",
"e.errno != errno.ENOTDIR: raise continue for fname in files: if",
"validate :raises: ValueError if given an invalid device or partition",
"OR CONDITIONS OF ANY KIND, either express or # implied.",
"!= errno.ENOTDIR: raise continue for hsh in hashes: hash_path =",
"try: hashes = listdir(suff_path) except OSError as e: if e.errno",
"hsh) try: files = sorted(listdir(hash_path), reverse=True) except OSError as e:",
"to all paths; guessing the hash a path # will",
"HASH_PATH_PREFIX = _hash_conf.get('swift-hash', 'swift_hash_path_prefix') except (NoSectionError, NoOptionError): pass def validate_configuration():",
"and not fname.endswith(suffix): continue path = os.path.join(hash_path, fname) yield path,",
"'swift_hash_path_suffix') except (NoSectionError, NoOptionError): pass try: HASH_PATH_PREFIX = _hash_conf.get('swift-hash', 'swift_hash_path_prefix')",
"greater than or equal to November 20th, 2286 at 17:46",
"device or device in ['.', '..']: invalid_device = True if",
"e: if e.errno != errno.ENOTDIR: raise continue for hsh in",
"\"\"\" Get the canonical hash for an account/container/object :param account:",
"suff_path = os.path.join(part_path, asuffix) try: hashes = listdir(suff_path) except OSError",
"def audit_location_generator(devices, datadir, suffix='', mount_check=True, logger=None): ''' Given a devices",
"partitions: part_path = os.path.join(datadir_path, partition) try: suffixes = listdir(part_path) except",
"swift import gettext_ as _ from swift.common.utils import listdir, quote",
"sys.exit(\"Error: [swift-hash]: both swift_hash_path_suffix \" \"and swift_hash_path_prefix are missing \"",
"data layouts.\"\"\" import os import sys import errno from hashlib",
"on devices :param logger: a logger object ''' device_dir =",
"as it is not mounted'), device) continue datadir_path = os.path.join(devices,",
"_hash_conf.get('swift-hash', 'swift_hash_path_suffix') except (NoSectionError, NoOptionError): pass try: HASH_PATH_PREFIX = _hash_conf.get('swift-hash',",
"all names returned :param mount_check: Flag to check if a",
"an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF",
"Unless required by applicable law or agreed to in writing,",
"partition or partition in ['.', '..']: invalid_partition = True if",
"used. :param device: device to validate :param partition: partition to",
"raw_digest: return md5(HASH_PATH_PREFIX + '/' + '/'.join(paths) + HASH_PATH_SUFFIX).digest() else:",
"return the raw version rather than a hex digest :returns:",
"= _hash_conf.get('swift-hash', 'swift_hash_path_suffix') except (NoSectionError, NoOptionError): pass try: HASH_PATH_PREFIX =",
"container: paths.append(container) if object: paths.append(object) if raw_digest: return md5(HASH_PATH_PREFIX +",
"= False if not device or '/' in device or",
"standardized xxxxxxxxxx.xxxxx (10.5) format. Note that timestamps using values greater",
"the specific language governing permissions and # limitations under the",
"True if invalid_device: raise ValueError('Invalid device: %s' % quote(device or",
"and won't lead to directory traversal when used. :param device:",
"os.path.ismount(os.path.join(devices, device)): if logger: logger.debug( _('Skipping %s as it is",
"applicable law or agreed to in writing, software # distributed",
"from swift import gettext_ as _ from swift.common.utils import listdir,",
"name_hash): \"\"\" Get the storage directory :param datadir: Base data",
"Flag to check if a mount check should be performed",
"!= errno.ENOTDIR: raise continue for fname in files: if suffix",
"listdir(part_path) except OSError as e: if e.errno != errno.ENOTDIR: raise",
"e.errno != errno.ENOTDIR: raise continue for hsh in hashes: hash_path",
"of the DATADIR constants defined in the account, container, and",
"hash string \"\"\" if object and not container: raise ValueError('container",
"or '')) elif invalid_partition: raise ValueError('Invalid partition: %s' % quote(partition",
"\"\"\" return \"%016.05f\" % (float(timestamp)) def validate_device_partition(device, partition): \"\"\" Validate",
"in writing, software # distributed under the License is distributed",
"This should be one of the DATADIR constants defined in",
"directory located under self.devices. This should be one of the",
"the DATADIR constants defined in the account, container, and object",
"= os.path.join(suff_path, hsh) try: files = sorted(listdir(hash_path), reverse=True) except OSError",
"before sweep completed shuffle(device_dir) for device in device_dir: if mount_check",
"November 20th, 2286 at 17:46 UTC will use 11 digits",
"errno.ENOTDIR: raise continue for fname in files: if suffix and",
"object and not container: raise ValueError('container is required if object",
"use 11 digits to represent the number of seconds. :param",
"Used by hash_path to offer a bit more security when",
"paths.append(object) if raw_digest: return md5(HASH_PATH_PREFIX + '/' + '/'.join(paths) +",
"['.', '..']: invalid_device = True if not partition or '/'",
"['.', '..']: invalid_partition = True if invalid_device: raise ValueError('Invalid device:",
"quote(device or '')) elif invalid_partition: raise ValueError('Invalid partition: %s' %",
"fname in files: if suffix and not fname.endswith(suffix): continue path",
"import os import sys import errno from hashlib import md5",
"if object is provided') paths = [account] if container: paths.append(container)",
"[account] if container: paths.append(container) if object: paths.append(object) if raw_digest: return",
"if mount_check and not \\ os.path.ismount(os.path.join(devices, device)): if logger: logger.debug(",
"(float(timestamp)) def validate_device_partition(device, partition): \"\"\" Validate that a device and",
"License is distributed on an \"AS IS\" BASIS, # WITHOUT",
"OF ANY KIND, either express or # implied. # See",
"os.path.join(datadir_path, partition) try: suffixes = listdir(part_path) except OSError as e:",
"License, Version 2.0 (the \"License\"); # you may not use",
"Storage directory \"\"\" return os.path.join(datadir, str(partition), name_hash[-3:], name_hash) def audit_location_generator(devices,",
"suffix. _hash_conf = ConfigParser() HASH_PATH_SUFFIX = '' HASH_PATH_PREFIX = ''",
"# You may obtain a copy of the License at",
"= '' HASH_PATH_PREFIX = '' if _hash_conf.read('/etc/swift/swift.conf'): try: HASH_PATH_SUFFIX =",
"names returned :param mount_check: Flag to check if a mount",
"%s' % quote(partition or '')) def storage_directory(datadir, partition, name_hash): \"\"\"",
"device in device_dir: if mount_check and not \\ os.path.ismount(os.path.join(devices, device)):",
"_hash_conf.get('swift-hash', 'swift_hash_path_prefix') except (NoSectionError, NoOptionError): pass def validate_configuration(): if not",
"partition) try: suffixes = listdir(part_path) except OSError as e: if",
"copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # #",
"into a standardized xxxxxxxxxx.xxxxx (10.5) format. Note that timestamps using",
"all paths; guessing the hash a path # will end",
"for hsh in hashes: hash_path = os.path.join(suff_path, hsh) try: files",
"the License. \"\"\"Methods & Attributes for shared 'on-disk' data layouts.\"\"\"",
"invalid_partition = True if invalid_device: raise ValueError('Invalid device: %s' %",
"digest :returns: hash string \"\"\" if object and not container:",
"name suffix required for all names returned :param mount_check: Flag",
"either express or # implied. # See the License for",
"and a data directory, yield (path, device, partition) for all",
"audited :param datadir: a directory located under self.devices. This should",
"partition or '/' in partition or partition in ['.', '..']:",
"from hashlib import md5 from random import shuffle from ConfigParser",
"permissions and # limitations under the License. \"\"\"Methods & Attributes",
"of seconds. :param timestamp: unix timestamp :returns: normalized timestamp as",
"randomize devices in case of process restart before sweep completed",
"= '' if _hash_conf.read('/etc/swift/swift.conf'): try: HASH_PATH_SUFFIX = _hash_conf.get('swift-hash', 'swift_hash_path_suffix') except",
":raises: ValueError if given an invalid device or partition \"\"\"",
"the License for the specific language governing permissions and #",
"a string \"\"\" return \"%016.05f\" % (float(timestamp)) def validate_device_partition(device, partition):",
"Apache License, Version 2.0 (the \"License\"); # you may not",
"as _ from swift.common.utils import listdir, quote # Used by",
"os.path.join(part_path, asuffix) try: hashes = listdir(suff_path) except OSError as e:",
"process restart before sweep completed shuffle(device_dir) for device in device_dir:",
"It simply appends this value to all paths; guessing the",
"a hex digest :returns: hash string \"\"\" if object and",
"# will end up with would also require knowing this",
"seconds. :param timestamp: unix timestamp :returns: normalized timestamp as a",
"# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or",
"name hash :returns: Storage directory \"\"\" return os.path.join(datadir, str(partition), name_hash[-3:],",
"when generating hashes for # paths. It simply appends this",
"in partition or partition in ['.', '..']: invalid_partition = True",
"shuffle(device_dir) for device in device_dir: if mount_check and not \\",
"directory :param partition: Partition :param name_hash: Account, container or object",
"servers. :param suffix: path name suffix required for all names",
"if not device or '/' in device or device in",
"+ '/'.join(paths) + HASH_PATH_SUFFIX).digest() else: return md5(HASH_PATH_PREFIX + '/' +",
"def normalize_timestamp(timestamp): \"\"\" Format a timestamp (string or numeric) into",
"to validate :raises: ValueError if given an invalid device or",
"limitations under the License. \"\"\"Methods & Attributes for shared 'on-disk'",
"License. \"\"\"Methods & Attributes for shared 'on-disk' data layouts.\"\"\" import",
"object name hash :returns: Storage directory \"\"\" return os.path.join(datadir, str(partition),",
"missing \" \"from /etc/swift/swift.conf\") def hash_path(account, container=None, object=None, raw_digest=False): \"\"\"",
"logger: logger.debug( _('Skipping %s as it is not mounted'), device)",
"generating hashes for # paths. It simply appends this value",
"'/'.join(paths) + HASH_PATH_SUFFIX).hexdigest() def normalize_timestamp(timestamp): \"\"\" Format a timestamp (string",
"= listdir(datadir_path) for partition in partitions: part_path = os.path.join(datadir_path, partition)",
"a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 #",
"%s' % quote(device or '')) elif invalid_partition: raise ValueError('Invalid partition:",
"if invalid_device: raise ValueError('Invalid device: %s' % quote(device or ''))",
"(10.5) format. Note that timestamps using values greater than or",
"an account/container/object :param account: Account :param container: Container :param object:",
"string \"\"\" return \"%016.05f\" % (float(timestamp)) def validate_device_partition(device, partition): \"\"\"",
"Validate that a device and a partition are valid and",
"device in ['.', '..']: invalid_device = True if not partition",
":returns: normalized timestamp as a string \"\"\" return \"%016.05f\" %",
"''' Given a devices path and a data directory, yield",
"object=None, raw_digest=False): \"\"\" Get the canonical hash for an account/container/object",
"Get the canonical hash for an account/container/object :param account: Account",
"/etc/swift/swift.conf\") def hash_path(account, container=None, object=None, raw_digest=False): \"\"\" Get the canonical",
"e: if e.errno != errno.ENOTDIR: raise continue for fname in",
"traversal when used. :param device: device to validate :param partition:",
"as a string \"\"\" return \"%016.05f\" % (float(timestamp)) def validate_device_partition(device,",
"= sorted(listdir(hash_path), reverse=True) except OSError as e: if e.errno !=",
"for all files in that directory :param devices: parent directory",
"in partitions: part_path = os.path.join(datadir_path, partition) try: suffixes = listdir(part_path)",
"17:46 UTC will use 11 digits to represent the number",
"KIND, either express or # implied. # See the License",
"errno.ENOTDIR: raise continue for asuffix in suffixes: suff_path = os.path.join(part_path,",
"one of the DATADIR constants defined in the account, container,",
"\"License\"); # you may not use this file except in",
"NoOptionError): pass def validate_configuration(): if not HASH_PATH_SUFFIX and not HASH_PATH_PREFIX:",
":param name_hash: Account, container or object name hash :returns: Storage",
"suffixes = listdir(part_path) except OSError as e: if e.errno !=",
"invalid_device = True if not partition or '/' in partition",
"in ['.', '..']: invalid_device = True if not partition or",
"[swift-hash]: both swift_hash_path_suffix \" \"and swift_hash_path_prefix are missing \" \"from",
"distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR",
"hashes = listdir(suff_path) except OSError as e: if e.errno !=",
"directory \"\"\" return os.path.join(datadir, str(partition), name_hash[-3:], name_hash) def audit_location_generator(devices, datadir,",
"(path, device, partition) for all files in that directory :param",
"hash_path to offer a bit more security when generating hashes",
"# distributed under the License is distributed on an \"AS",
"# Unless required by applicable law or agreed to in",
"timestamp: unix timestamp :returns: normalized timestamp as a string \"\"\"",
"to validate :param partition: partition to validate :raises: ValueError if",
"e.errno != errno.ENOTDIR: raise continue for asuffix in suffixes: suff_path",
"or device in ['.', '..']: invalid_device = True if not",
"\"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY",
":returns: Storage directory \"\"\" return os.path.join(datadir, str(partition), name_hash[-3:], name_hash) def",
"if logger: logger.debug( _('Skipping %s as it is not mounted'),",
"both swift_hash_path_suffix \" \"and swift_hash_path_prefix are missing \" \"from /etc/swift/swift.conf\")",
"You may obtain a copy of the License at #",
"paths = [account] if container: paths.append(container) if object: paths.append(object) if",
"returned :param mount_check: Flag to check if a mount check",
"except (NoSectionError, NoOptionError): pass try: HASH_PATH_PREFIX = _hash_conf.get('swift-hash', 'swift_hash_path_prefix') except",
"that directory :param devices: parent directory of the devices to",
"\\ os.path.ismount(os.path.join(devices, device)): if logger: logger.debug( _('Skipping %s as it",
"fname.endswith(suffix): continue path = os.path.join(hash_path, fname) yield path, device, partition",
"pass def validate_configuration(): if not HASH_PATH_SUFFIX and not HASH_PATH_PREFIX: sys.exit(\"Error:",
"the Apache License, Version 2.0 (the \"License\"); # you may",
"rather than a hex digest :returns: hash string \"\"\" if",
"name_hash[-3:], name_hash) def audit_location_generator(devices, datadir, suffix='', mount_check=True, logger=None): ''' Given",
"are valid and won't lead to directory traversal when used.",
"# randomize devices in case of process restart before sweep",
"and a partition are valid and won't lead to directory",
"'on-disk' data layouts.\"\"\" import os import sys import errno from"
] |
[
"'vehicles8+': vehicles8p, 'vehiclesByTag': vehiclesByTag, 'mausTypeCompDescr': vehicles.makeVehicleTypeCompDescrByName('germany:G42_Maus'), 'vehiclesInTreesByNation': vehiclesInTreeByNation, 'vehiclesInTrees': vehiclesInTree,",
"(Intel)] # Embedded file name: scripts/common/dossiers2/custom/cache.py import nations from items",
"in xrange(len(nations.NAMES)): nationList = vehicles.g_list.getList(nationIdx) vehiclesInNationTree = set() for vehDescr",
"for vehDescr in nationList.itervalues(): vehiclesByLevel.setdefault(vehDescr.level, set()).add(vehDescr.compactDescr) for tag in ('beast',",
"vehiclesByLevel[10] _g_cache.update({'vehiclesByLevel': vehiclesByLevel, 'vehicles8+': vehicles8p, 'vehiclesByTag': vehiclesByTag, 'mausTypeCompDescr': vehicles.makeVehicleTypeCompDescrByName('germany:G42_Maus'), 'vehiclesInTreesByNation':",
"= vehiclesByLevel[8] | vehiclesByLevel[9] | vehiclesByLevel[10] _g_cache.update({'vehiclesByLevel': vehiclesByLevel, 'vehicles8+': vehicles8p,",
"= {'beast': set(),'sinai': set(),'patton': set()} vehiclesInTreeByNation = {} vehiclesInTree =",
"vehiclesInNationTree if bool(vehiclesInNationTree): nationsWithVehiclesInTree.append(nationIdx) vehicles8p = vehiclesByLevel[8] | vehiclesByLevel[9] |",
"| vehiclesByLevel[10] _g_cache.update({'vehiclesByLevel': vehiclesByLevel, 'vehicles8+': vehicles8p, 'vehiclesByTag': vehiclesByTag, 'mausTypeCompDescr': vehicles.makeVehicleTypeCompDescrByName('germany:G42_Maus'),",
"'mausTypeCompDescr': vehicles.makeVehicleTypeCompDescrByName('germany:G42_Maus'), 'vehiclesInTreesByNation': vehiclesInTreeByNation, 'vehiclesInTrees': vehiclesInTree, 'nationsWithVehiclesInTree': nationsWithVehiclesInTree }) _g_cache",
"len(vehicles.g_cache.vehicle(nationIdx, vehDescr.id).unlocksDescrs) > 0: vehiclesInNationTree.add(vehDescr.compactDescr) vehiclesInTree.update(vehiclesInNationTree) vehiclesInTreeByNation[nationIdx] = vehiclesInNationTree if",
"vehiclesByTag = {'beast': set(),'sinai': set(),'patton': set()} vehiclesInTreeByNation = {} vehiclesInTree",
"vehDescr in nationList.itervalues(): vehiclesByLevel.setdefault(vehDescr.level, set()).add(vehDescr.compactDescr) for tag in ('beast', 'sinai',",
"# Decompiled from: Python 2.7.10 (default, May 23 2015, 09:40:32)",
"for tag in ('beast', 'sinai', 'patton'): if tag in vehDescr.tags:",
"_g_cache.update({'vehiclesByLevel': vehiclesByLevel, 'vehicles8+': vehicles8p, 'vehiclesByTag': vehiclesByTag, 'mausTypeCompDescr': vehicles.makeVehicleTypeCompDescrByName('germany:G42_Maus'), 'vehiclesInTreesByNation': vehiclesInTreeByNation,",
"file name: scripts/common/dossiers2/custom/cache.py import nations from items import vehicles def",
"= set() nationsWithVehiclesInTree = [] unlocksSources = vehicles.getUnlocksSources() for nationIdx",
"tag in ('beast', 'sinai', 'patton'): if tag in vehDescr.tags: vehiclesByTag[tag].add(vehDescr.compactDescr)",
"items import vehicles def getCache(): global _g_cache return _g_cache def",
"vehiclesInNationTree = set() for vehDescr in nationList.itervalues(): vehiclesByLevel.setdefault(vehDescr.level, set()).add(vehDescr.compactDescr) for",
"nationIdx in xrange(len(nations.NAMES)): nationList = vehicles.g_list.getList(nationIdx) vehiclesInNationTree = set() for",
"nationList = vehicles.g_list.getList(nationIdx) vehiclesInNationTree = set() for vehDescr in nationList.itervalues():",
"vehiclesByTag[tag].add(vehDescr.compactDescr) if len(unlocksSources.get(vehDescr.compactDescr, set())) > 0 or len(vehicles.g_cache.vehicle(nationIdx, vehDescr.id).unlocksDescrs) >",
"vehicles def getCache(): global _g_cache return _g_cache def buildCache(): vehiclesByLevel",
"'vehiclesInTreesByNation': vehiclesInTreeByNation, 'vehiclesInTrees': vehiclesInTree, 'nationsWithVehiclesInTree': nationsWithVehiclesInTree }) _g_cache = {}",
"nations from items import vehicles def getCache(): global _g_cache return",
"2.7 (62211) # Decompiled from: Python 2.7.10 (default, May 23",
"vehiclesByLevel[8] | vehiclesByLevel[9] | vehiclesByLevel[10] _g_cache.update({'vehiclesByLevel': vehiclesByLevel, 'vehicles8+': vehicles8p, 'vehiclesByTag':",
"vehDescr.tags: vehiclesByTag[tag].add(vehDescr.compactDescr) if len(unlocksSources.get(vehDescr.compactDescr, set())) > 0 or len(vehicles.g_cache.vehicle(nationIdx, vehDescr.id).unlocksDescrs)",
"vehicles8p, 'vehiclesByTag': vehiclesByTag, 'mausTypeCompDescr': vehicles.makeVehicleTypeCompDescrByName('germany:G42_Maus'), 'vehiclesInTreesByNation': vehiclesInTreeByNation, 'vehiclesInTrees': vehiclesInTree, 'nationsWithVehiclesInTree':",
"'vehiclesByTag': vehiclesByTag, 'mausTypeCompDescr': vehicles.makeVehicleTypeCompDescrByName('germany:G42_Maus'), 'vehiclesInTreesByNation': vehiclesInTreeByNation, 'vehiclesInTrees': vehiclesInTree, 'nationsWithVehiclesInTree': nationsWithVehiclesInTree",
"2015, 09:40:32) [MSC v.1500 32 bit (Intel)] # Embedded file",
"Python 2.7.10 (default, May 23 2015, 09:40:32) [MSC v.1500 32",
"if tag in vehDescr.tags: vehiclesByTag[tag].add(vehDescr.compactDescr) if len(unlocksSources.get(vehDescr.compactDescr, set())) > 0",
"{} vehiclesInTree = set() nationsWithVehiclesInTree = [] unlocksSources = vehicles.getUnlocksSources()",
"vehiclesInTreeByNation = {} vehiclesInTree = set() nationsWithVehiclesInTree = [] unlocksSources",
"2.7.10 (default, May 23 2015, 09:40:32) [MSC v.1500 32 bit",
"in ('beast', 'sinai', 'patton'): if tag in vehDescr.tags: vehiclesByTag[tag].add(vehDescr.compactDescr) if",
"vehicles.makeVehicleTypeCompDescrByName('germany:G42_Maus'), 'vehiclesInTreesByNation': vehiclesInTreeByNation, 'vehiclesInTrees': vehiclesInTree, 'nationsWithVehiclesInTree': nationsWithVehiclesInTree }) _g_cache =",
"23 2015, 09:40:32) [MSC v.1500 32 bit (Intel)] # Embedded",
"_g_cache return _g_cache def buildCache(): vehiclesByLevel = {} vehiclesByTag =",
"= [] unlocksSources = vehicles.getUnlocksSources() for nationIdx in xrange(len(nations.NAMES)): nationList",
"tag in vehDescr.tags: vehiclesByTag[tag].add(vehDescr.compactDescr) if len(unlocksSources.get(vehDescr.compactDescr, set())) > 0 or",
"> 0: vehiclesInNationTree.add(vehDescr.compactDescr) vehiclesInTree.update(vehiclesInNationTree) vehiclesInTreeByNation[nationIdx] = vehiclesInNationTree if bool(vehiclesInNationTree): nationsWithVehiclesInTree.append(nationIdx)",
"'patton'): if tag in vehDescr.tags: vehiclesByTag[tag].add(vehDescr.compactDescr) if len(unlocksSources.get(vehDescr.compactDescr, set())) >",
"vehiclesInTreeByNation[nationIdx] = vehiclesInNationTree if bool(vehiclesInNationTree): nationsWithVehiclesInTree.append(nationIdx) vehicles8p = vehiclesByLevel[8] |",
"import vehicles def getCache(): global _g_cache return _g_cache def buildCache():",
"or len(vehicles.g_cache.vehicle(nationIdx, vehDescr.id).unlocksDescrs) > 0: vehiclesInNationTree.add(vehDescr.compactDescr) vehiclesInTree.update(vehiclesInNationTree) vehiclesInTreeByNation[nationIdx] = vehiclesInNationTree",
"v.1500 32 bit (Intel)] # Embedded file name: scripts/common/dossiers2/custom/cache.py import",
"0 or len(vehicles.g_cache.vehicle(nationIdx, vehDescr.id).unlocksDescrs) > 0: vehiclesInNationTree.add(vehDescr.compactDescr) vehiclesInTree.update(vehiclesInNationTree) vehiclesInTreeByNation[nationIdx] =",
"in vehDescr.tags: vehiclesByTag[tag].add(vehDescr.compactDescr) if len(unlocksSources.get(vehDescr.compactDescr, set())) > 0 or len(vehicles.g_cache.vehicle(nationIdx,",
"from items import vehicles def getCache(): global _g_cache return _g_cache",
"from: Python 2.7.10 (default, May 23 2015, 09:40:32) [MSC v.1500",
"= vehicles.getUnlocksSources() for nationIdx in xrange(len(nations.NAMES)): nationList = vehicles.g_list.getList(nationIdx) vehiclesInNationTree",
"set()} vehiclesInTreeByNation = {} vehiclesInTree = set() nationsWithVehiclesInTree = []",
"vehiclesByLevel, 'vehicles8+': vehicles8p, 'vehiclesByTag': vehiclesByTag, 'mausTypeCompDescr': vehicles.makeVehicleTypeCompDescrByName('germany:G42_Maus'), 'vehiclesInTreesByNation': vehiclesInTreeByNation, 'vehiclesInTrees':",
"for nationIdx in xrange(len(nations.NAMES)): nationList = vehicles.g_list.getList(nationIdx) vehiclesInNationTree = set()",
"0: vehiclesInNationTree.add(vehDescr.compactDescr) vehiclesInTree.update(vehiclesInNationTree) vehiclesInTreeByNation[nationIdx] = vehiclesInNationTree if bool(vehiclesInNationTree): nationsWithVehiclesInTree.append(nationIdx) vehicles8p",
"xrange(len(nations.NAMES)): nationList = vehicles.g_list.getList(nationIdx) vehiclesInNationTree = set() for vehDescr in",
"vehiclesByLevel = {} vehiclesByTag = {'beast': set(),'sinai': set(),'patton': set()} vehiclesInTreeByNation",
"vehicles.g_list.getList(nationIdx) vehiclesInNationTree = set() for vehDescr in nationList.itervalues(): vehiclesByLevel.setdefault(vehDescr.level, set()).add(vehDescr.compactDescr)",
"set() for vehDescr in nationList.itervalues(): vehiclesByLevel.setdefault(vehDescr.level, set()).add(vehDescr.compactDescr) for tag in",
"vehiclesInTree = set() nationsWithVehiclesInTree = [] unlocksSources = vehicles.getUnlocksSources() for",
"uncompyle6 version 2.11.3 # Python bytecode 2.7 (62211) # Decompiled",
"vehiclesByLevel[9] | vehiclesByLevel[10] _g_cache.update({'vehiclesByLevel': vehiclesByLevel, 'vehicles8+': vehicles8p, 'vehiclesByTag': vehiclesByTag, 'mausTypeCompDescr':",
"nationList.itervalues(): vehiclesByLevel.setdefault(vehDescr.level, set()).add(vehDescr.compactDescr) for tag in ('beast', 'sinai', 'patton'): if",
"(62211) # Decompiled from: Python 2.7.10 (default, May 23 2015,",
"vehiclesInTree.update(vehiclesInNationTree) vehiclesInTreeByNation[nationIdx] = vehiclesInNationTree if bool(vehiclesInNationTree): nationsWithVehiclesInTree.append(nationIdx) vehicles8p = vehiclesByLevel[8]",
"vehicles.getUnlocksSources() for nationIdx in xrange(len(nations.NAMES)): nationList = vehicles.g_list.getList(nationIdx) vehiclesInNationTree =",
"global _g_cache return _g_cache def buildCache(): vehiclesByLevel = {} vehiclesByTag",
"bytecode 2.7 (62211) # Decompiled from: Python 2.7.10 (default, May",
"def buildCache(): vehiclesByLevel = {} vehiclesByTag = {'beast': set(),'sinai': set(),'patton':",
"= vehiclesInNationTree if bool(vehiclesInNationTree): nationsWithVehiclesInTree.append(nationIdx) vehicles8p = vehiclesByLevel[8] | vehiclesByLevel[9]",
"# Python bytecode 2.7 (62211) # Decompiled from: Python 2.7.10",
"'sinai', 'patton'): if tag in vehDescr.tags: vehiclesByTag[tag].add(vehDescr.compactDescr) if len(unlocksSources.get(vehDescr.compactDescr, set()))",
"if bool(vehiclesInNationTree): nationsWithVehiclesInTree.append(nationIdx) vehicles8p = vehiclesByLevel[8] | vehiclesByLevel[9] | vehiclesByLevel[10]",
"name: scripts/common/dossiers2/custom/cache.py import nations from items import vehicles def getCache():",
"vehicles8p = vehiclesByLevel[8] | vehiclesByLevel[9] | vehiclesByLevel[10] _g_cache.update({'vehiclesByLevel': vehiclesByLevel, 'vehicles8+':",
"(default, May 23 2015, 09:40:32) [MSC v.1500 32 bit (Intel)]",
"if len(unlocksSources.get(vehDescr.compactDescr, set())) > 0 or len(vehicles.g_cache.vehicle(nationIdx, vehDescr.id).unlocksDescrs) > 0:",
"vehDescr.id).unlocksDescrs) > 0: vehiclesInNationTree.add(vehDescr.compactDescr) vehiclesInTree.update(vehiclesInNationTree) vehiclesInTreeByNation[nationIdx] = vehiclesInNationTree if bool(vehiclesInNationTree):",
"bool(vehiclesInNationTree): nationsWithVehiclesInTree.append(nationIdx) vehicles8p = vehiclesByLevel[8] | vehiclesByLevel[9] | vehiclesByLevel[10] _g_cache.update({'vehiclesByLevel':",
"nationsWithVehiclesInTree.append(nationIdx) vehicles8p = vehiclesByLevel[8] | vehiclesByLevel[9] | vehiclesByLevel[10] _g_cache.update({'vehiclesByLevel': vehiclesByLevel,",
"[] unlocksSources = vehicles.getUnlocksSources() for nationIdx in xrange(len(nations.NAMES)): nationList =",
"{'beast': set(),'sinai': set(),'patton': set()} vehiclesInTreeByNation = {} vehiclesInTree = set()",
"= vehicles.g_list.getList(nationIdx) vehiclesInNationTree = set() for vehDescr in nationList.itervalues(): vehiclesByLevel.setdefault(vehDescr.level,",
"_g_cache def buildCache(): vehiclesByLevel = {} vehiclesByTag = {'beast': set(),'sinai':",
"> 0 or len(vehicles.g_cache.vehicle(nationIdx, vehDescr.id).unlocksDescrs) > 0: vehiclesInNationTree.add(vehDescr.compactDescr) vehiclesInTree.update(vehiclesInNationTree) vehiclesInTreeByNation[nationIdx]",
"Decompiled from: Python 2.7.10 (default, May 23 2015, 09:40:32) [MSC",
"import nations from items import vehicles def getCache(): global _g_cache",
"Python bytecode 2.7 (62211) # Decompiled from: Python 2.7.10 (default,",
"vehiclesByTag, 'mausTypeCompDescr': vehicles.makeVehicleTypeCompDescrByName('germany:G42_Maus'), 'vehiclesInTreesByNation': vehiclesInTreeByNation, 'vehiclesInTrees': vehiclesInTree, 'nationsWithVehiclesInTree': nationsWithVehiclesInTree })",
"def getCache(): global _g_cache return _g_cache def buildCache(): vehiclesByLevel =",
"32 bit (Intel)] # Embedded file name: scripts/common/dossiers2/custom/cache.py import nations",
"= {} vehiclesByTag = {'beast': set(),'sinai': set(),'patton': set()} vehiclesInTreeByNation =",
"scripts/common/dossiers2/custom/cache.py import nations from items import vehicles def getCache(): global",
"set() nationsWithVehiclesInTree = [] unlocksSources = vehicles.getUnlocksSources() for nationIdx in",
"2.11.3 # Python bytecode 2.7 (62211) # Decompiled from: Python",
"{} vehiclesByTag = {'beast': set(),'sinai': set(),'patton': set()} vehiclesInTreeByNation = {}",
"vehiclesByLevel.setdefault(vehDescr.level, set()).add(vehDescr.compactDescr) for tag in ('beast', 'sinai', 'patton'): if tag",
"May 23 2015, 09:40:32) [MSC v.1500 32 bit (Intel)] #",
"unlocksSources = vehicles.getUnlocksSources() for nationIdx in xrange(len(nations.NAMES)): nationList = vehicles.g_list.getList(nationIdx)",
"version 2.11.3 # Python bytecode 2.7 (62211) # Decompiled from:",
"bit (Intel)] # Embedded file name: scripts/common/dossiers2/custom/cache.py import nations from",
"('beast', 'sinai', 'patton'): if tag in vehDescr.tags: vehiclesByTag[tag].add(vehDescr.compactDescr) if len(unlocksSources.get(vehDescr.compactDescr,",
"in nationList.itervalues(): vehiclesByLevel.setdefault(vehDescr.level, set()).add(vehDescr.compactDescr) for tag in ('beast', 'sinai', 'patton'):",
"| vehiclesByLevel[9] | vehiclesByLevel[10] _g_cache.update({'vehiclesByLevel': vehiclesByLevel, 'vehicles8+': vehicles8p, 'vehiclesByTag': vehiclesByTag,",
"Embedded file name: scripts/common/dossiers2/custom/cache.py import nations from items import vehicles",
"getCache(): global _g_cache return _g_cache def buildCache(): vehiclesByLevel = {}",
"nationsWithVehiclesInTree = [] unlocksSources = vehicles.getUnlocksSources() for nationIdx in xrange(len(nations.NAMES)):",
"set()).add(vehDescr.compactDescr) for tag in ('beast', 'sinai', 'patton'): if tag in",
"= set() for vehDescr in nationList.itervalues(): vehiclesByLevel.setdefault(vehDescr.level, set()).add(vehDescr.compactDescr) for tag",
"[MSC v.1500 32 bit (Intel)] # Embedded file name: scripts/common/dossiers2/custom/cache.py",
"set(),'patton': set()} vehiclesInTreeByNation = {} vehiclesInTree = set() nationsWithVehiclesInTree =",
"= {} vehiclesInTree = set() nationsWithVehiclesInTree = [] unlocksSources =",
"set(),'sinai': set(),'patton': set()} vehiclesInTreeByNation = {} vehiclesInTree = set() nationsWithVehiclesInTree",
"# Embedded file name: scripts/common/dossiers2/custom/cache.py import nations from items import",
"buildCache(): vehiclesByLevel = {} vehiclesByTag = {'beast': set(),'sinai': set(),'patton': set()}",
"# uncompyle6 version 2.11.3 # Python bytecode 2.7 (62211) #",
"09:40:32) [MSC v.1500 32 bit (Intel)] # Embedded file name:",
"vehiclesInNationTree.add(vehDescr.compactDescr) vehiclesInTree.update(vehiclesInNationTree) vehiclesInTreeByNation[nationIdx] = vehiclesInNationTree if bool(vehiclesInNationTree): nationsWithVehiclesInTree.append(nationIdx) vehicles8p =",
"set())) > 0 or len(vehicles.g_cache.vehicle(nationIdx, vehDescr.id).unlocksDescrs) > 0: vehiclesInNationTree.add(vehDescr.compactDescr) vehiclesInTree.update(vehiclesInNationTree)",
"len(unlocksSources.get(vehDescr.compactDescr, set())) > 0 or len(vehicles.g_cache.vehicle(nationIdx, vehDescr.id).unlocksDescrs) > 0: vehiclesInNationTree.add(vehDescr.compactDescr)",
"return _g_cache def buildCache(): vehiclesByLevel = {} vehiclesByTag = {'beast':"
] |
[
"p[3].children, p[1].TAC) p[0].TAC.append_TAC(p[3].TAC) return def p_TypeDecl(p): '''TypeDecl : TYPE TypeSpecTopList",
"('right','ASSIGN_OP'), ('left','COMMA'), ('left','LSQUARE'), ('left','RSQUARE'), ('left','LCURLY'), ('left','RCURLY'), ('left','DDD'), ('left','DOT'), ('left','SEMICOLON'), ('left','COLON'),",
"Expression | RETURN ExpressionList ''' parsed.append(p.slice) if len(p) == 2:",
"l2, '', '']) p[0].TAC.add_line(['label', l1, '', '']) p[0].TAC.append_TAC(p[5].TAC) p[0].TAC.add_line(['label', l2,",
"1, 'None', 0, [p[2]], p[2].TAC) if p[2].name == 'ExpressionList': p[0]",
"= TreeNode('ExprCaseClause', 0, 'INT') # p[0].TAC.append_TAC(p[1].TAC) p[0].TAC.add_line(['label', l1, '', ''])",
"= p[1] elif len(p) == 3: p[0] = TreeNode('IDENTIFIER', gen('temp'),",
"Parameters | Type ''' parsed.append(p.slice) if p[1].name == 'Type': p[0]",
"p[0] = p[1] p[0].name = 'ArrayLength' return def p_StructType(p): '''StructType",
"1 node.input_type = p[2].data p[0].children += [node] else: node =",
"p[1].TAC) p[0].TAC.append_TAC(p[3].TAC) else: p[0] = TreeNode('TopLevelDeclList', 0, 'INT', 0, [p[1]],",
"p[0].children += [node] else: node = TreeNode('IDENTIFIER', p[1], p[2].data, 1)",
"p[1], 'RUNE') return def p_empty(p): 'empty :' pass def p_error(p):",
"return def p_BasicLit(p): '''BasicLit : int_lit | float_lit | string_lit",
"\"_\".join(func[2:]) temp = 0 for f in symbol_table.symbol_table[scope]['functions']: if f.name",
"== p[2].data: noOfParams = len(f.parameters) p[0].TAC.add_line(['func', check_variable(p[2]), str(noOfParams), '']) for",
"''' parsed.append(p.slice) if len(p) == 2: p[0] = p[1] else:",
"def p_IncDecStmt(p): '''IncDecStmt : Expression PLUS_PLUS | Expression MINUS_MINUS '''",
"p[2].children, p[1].TAC) p[0].TAC.add_leader(p[0].TAC.length()) p[0].TAC.append_TAC(p[2].TAC) p[0].data.append_TAC(TAC2) else: p[0] = TreeNode('ExprCaseClauseList', TAC1,",
"check_variable(TreeNode): # return 2 values. first is the name for",
"return def p_ExprSwitchCase(p): '''ExprSwitchCase : CASE ExpressionList | DEFAULT |",
"and symbol_table.search_identifier(p[3].data) == False and p[3].data not in generated['temp']: print_error(\"Variable",
"Expression MINUS Expression | Expression OR Expression | Expression CARET",
"def p_empty(p): 'empty :' pass def p_error(p): print p if",
"p[0] = TreeNode('StandardTypes', p[1], 'NONE') return def p_TypeLit(p): '''TypeLit :",
"gen('str_list') parametersNode = SymbolTableNode(p[3].data, p[3].input_type) newNode = SymbolTableNode(name, p[3].input_type, parameters",
"0, [p[1]]) else: p[0] = p[1] p[0].name = 'Result' return",
"== 3: p[0] = TreeNode('IDENTIFIER', gen('temp'), 'INT', 1) p[0].TAC.add_line([check_variable(p[1]), check_variable(p[0]),",
"'''Tag : string_lit ''' parsed.append(p.slice) return def p_FunctionType(p): '''FunctionType :",
"p[0].name = 'PrintIntStmt' return def p_PrintStrStmt(p): '''PrintStrStmt : PRINTLN LROUND",
"return def p_AliasDecl(p): '''AliasDecl : IDENTIFIER EQ Type ''' parsed.append(p.slice)",
"'''rune_lit : RUNE_LIT ''' parsed.append(p.slice) p[0] = TreeNode('rune_lit', p[1], 'RUNE')",
"def p_ScopeEnd(p): '''ScopeEnd : empty ''' parsed.append(p.slice) symbol_table.end_scope() return def",
"ExpressionList RROUND | LROUND Type COMMA Expression RROUND ''' #",
"p_elseTail(p): '''elseTail : IfStmt | Block ''' parsed.append(p.slice) p[0] =",
"== 3: TAC1 = p[1].data TAC2 = p[2].data p[0] =",
"'elseTail' return def p_SwitchStmt(p): '''SwitchStmt : ExprSwitchStmt ''' parsed.append(p.slice) p[0]",
"= convert_tac(p[0].TAC) symbol_table.fill_next_use(three_addr_code) assembly_code = generate_assembly(three_addr_code,var_list,symbol_table) # p[0].TAC.print_code() # three_addr_code.print_code()",
"== 1: if p[2] == '++': p[0].TAC.add_line(['+', check_variable(p[1]), check_variable(p[1]), one_val.data])",
"ReturnStmt | Block | IfStmt | SwitchStmt | ForStmt |",
"return TreeNode.data else: TreeNode.print_node() return TreeNode.data precedence = ( ('left','IDENTIFIER'),",
": Statement SEMICOLON StatementList | empty ''' parsed.append(p.slice) if len(p)",
"= len(p[1].children) l2 = len(p[3].children) p[0].TAC.append_TAC(p[3].TAC) p[0].TAC.append_TAC(p[1].TAC) if l1 ==",
"'', '']) if len(p) == 6: l1 = gen('label') l2",
"| FOR Block ''' parsed.append(p.slice) p[0] = TreeNode('ForStmt', 0, 'INT')",
"parsed.append(p.slice) return def p_ArrayType(p): '''ArrayType : LSQUARE ArrayLength RSQUARE Type",
"p[0].TAC.add_line(['return', check_variable(p[2]), '', '']) return def p_BreakStmt(p): '''BreakStmt : BREAK",
"not in generated['temp']: print_error(\"Variable \" + p[3].data + \" is",
"AND_OR_EQ ''' parsed.append(p.slice) p[0] = TreeNode('assign_op', p[1], 'OPERATOR') return def",
"if p[2].name == 'Index': p[0] = TreeNode('IDENTIFIER', p[1].data, 'INT', 1,",
"Expression RROUND | LROUND Type RROUND | LROUND Type COMMA",
"p[0].name = 'VarDecl' return def p_VarSpecTopList(p): '''VarSpecTopList : VarSpec |",
"symbol table p[0] = TreeNode('VarSpec', 0, 'NONE') if hasattr(p[1], 'name')",
"EQ Expression | IdentifierList Type EQ ExpressionList ''' parsed.append(p.slice) return",
"p[0].TAC.append_TAC(p[1].TAC) p[0].TAC.add_line([p[2].data, check_variable(p[1]), check_variable(p[3]), '']) return def p_assign_op(p): '''assign_op :",
"| VarDecl ''' parsed.append(p.slice) p[0] = p[1] p[0].name = 'Declaration'",
"p[0].name = 'ParameterList' elif len(p) == 4: p[0] = TreeNode('ParameterList',",
"if l1 == l2: for i in range(l1): if p[1].children[i].isLvalue",
"variable not found # TreeNode.print_node() # symbol_table.print_symbol_table() if TreeNode.isLvalue ==",
"Expression | Expression RS Expression | Expression AMP Expression |",
"symbol_table.new_scope(s) for child in p[1].children: symbol_table.add_identifier(child, s) newNode = SymbolTableNode(s",
"f in symbol_table.symbol_table[scope]['functions']: if f.name == funcName: temp = len(f.parameters)",
": STAR Type ''' parsed.append(p.slice) return def p_ArrayType(p): '''ArrayType :",
"'int_lit': p[0] = p[3] # p[0].isLvalue = 0 else: p[0]",
"ConstSpecList RROUND | CONST ConstSpec ''' parsed.append(p.slice) return def p_ConstSpecList(p):",
"code import ThreeAddressCode from lexer import tokens from random import",
"| LT_MINUS ''' parsed.append(p.slice) p[0] = TreeNode('unary_op', p[1], 'OPERATOR') return",
"input_file + ' does not exist') sys.exit(1) input_code = open(input_file,",
"1) p[0] = TreeNode('IdentifierBotList', 0, 'None', 0, [node]) elif len(p)",
"RCURLY ''' parsed.append(p.slice) return def p_FieldDeclList(p): '''FieldDeclList : empty |",
"+= 1 p[0].children += [node] else: p[0].data += 1 p[0].children",
"'Index': p[0] = TreeNode('IDENTIFIER', p[1].data, 'INT', 1, p[2].data) elif p[2].name",
"p[1] p[0].name = 'Result' return def p_Parameters(p): '''Parameters : LROUND",
"STAR_EQ | DIVIDE_EQ | MODULO_EQ | LS_EQ | RS_EQ |",
"p_IdentifierBotList(p): '''IdentifierBotList : IDENTIFIER COMMA IdentifierBotList | IDENTIFIER ''' parsed.append(p.slice)",
"for child in reversed(p[3].children): p[0].TAC.add_line(['getparam', p[4].data + '_' + child.data,",
"'VarDecl' return def p_VarSpecTopList(p): '''VarSpecTopList : VarSpec | LROUND VarSpecList",
"'Index' return def p_Arguments(p): '''Arguments : LROUND RROUND | LROUND",
"Type ''' parsed.append(p.slice) return def p_TypeDef(p): '''TypeDef : IDENTIFIER Type",
"p[1].input_type,size = p[2].data) symbol_table.add_var(newNode) p[0] = TreeNode('VarSpec',p[1].data,'INT') # expr =",
"'''Assignment : ExpressionList assign_op ExpressionList | Expression assign_op Expression '''",
"= TreeNode('IDENTIFIER', p[1].data, 'INT', 1, p[2].data) elif p[2].name == 'Arguments':",
"''' parsed.append(p.slice) return def p_FieldDeclList(p): '''FieldDeclList : empty | FieldDeclList",
"'INT', 1) p[0].TAC.add_line(['=', check_variable(t1) , check_variable(p[2]), '']) p[0].TAC.append_TAC(p[5].data) for i",
"TreeNode('IdentifierBotList', 0, 'None', 0, [node] + p[3].children, p[3].TAC) return def",
"2: p[0].input_type = TreeNode('Result', 0, 'None') else: p[0].input_type = p[2]",
"p[0].name = 'IncDecStmt' return def p_ShortVarDecl(p): '''ShortVarDecl : ExpressionList ASSIGN_OP",
"4: node = TreeNode('IDENTIFIER', p[1], 'INT', 1) p[0] = TreeNode('IdentifierBotList',",
"= 0 else: p[0] = TreeNode('IDENTIFIER', p[3], 'INT', 1, [])",
"= gen('label') p[0] = TreeNode('IfStmt', 0, 'INT') p[0].TAC.append_TAC(p[2].TAC) p[0].TAC.add_line(['ifgotoeq', check_variable(p[2]),",
"return def p_octal_lit(p): '''octal_lit : OCTAL_LIT ''' parsed.append(p.slice) p[0] =",
"p[3].input_type, parameters = [parametersNode]) symbol_table.add_var(newNode) p[0].TAC.add_line(['print_str', name, '', '']) p[0].name",
"= len(f.parameters) # p[2].print_node() for child in p[2].children: p[0].TAC.add_line(['putparam', check_variable(child),",
"assembly_code = generate_assembly(three_addr_code,var_list,symbol_table) # p[0].TAC.print_code() # three_addr_code.print_code() assembly_code.print_code() # symbol_table.print_symbol_table()",
"print str(sys.argv[1]) + \" :: You missed something at the",
"0, [], p[1].TAC) return def p_ExprSwitchStmt(p): '''ExprSwitchStmt : SWITCH SimpleStmt",
"'''Literal : BasicLit | FunctionLit ''' parsed.append(p.slice) p[0] = p[1]",
"'_' + child.data, '', '']) p[0].TAC.add_line(['stack_push', '', '', '']) p[0].TAC.append_TAC(p[4].TAC)",
"p[0].TAC.add_line(['goto', l2, '', '']) p[0].TAC.add_line(['label', l1, '', '']) p[0].TAC.append_TAC(p[5].TAC) p[0].TAC.add_line(['label',",
"('left','DDD'), ('left','DOT'), ('left','SEMICOLON'), ('left','COLON'), ('left','SINGLE_QUOTES'), ('left','DOUBLE_QUOTES'), ('left','DECIMAL_LIT'), ('left','OCTAL_LIT'), ('left','HEX_LIT'), ('left','FLOAT_LIT'),",
": string_lit ''' parsed.append(p.slice) return def p_FunctionType(p): '''FunctionType : FUNC",
"('left','HEX_LIT'), ('left','FLOAT_LIT'), ('left','STRING_LIT'), ('left','NEWLINE'), ('left','BREAK'), ('left','CONTINUE'), ('left','RETURN'), ('left','RROUND'), ('left','LROUND'), ('left',",
"if p[2].input_type != 'NONE': # array case # p[2].print_node() if",
"p[1].children[i].data not in generated['temp']: print_error(\"Variable \" + p[1].children[i].data + \"",
"p[0] = TreeNode('ParameterList', p[1].data + p[3].data, 'None', 0, p[1].children +",
"p[0].TAC.add_line([l2]) return def p_ReturnStmt(p): '''ReturnStmt : RETURN | RETURN Expression",
"[], p[1].TAC) p[0].TAC.append_TAC(p[3].TAC) p[0].TAC.add_line([p[2],check_variable(p[0]), check_variable(p[1]), check_variable(p[3])]) p[0].name = 'Expression' return",
"IDENTIFIER Type EQ Expression | IdentifierList Type EQ ExpressionList '''",
"== 'int_lit': p[0] = p[3] # p[0].isLvalue = 0 else:",
": empty | FieldDeclList FieldDecl SEMICOLON ''' parsed.append(p.slice) return def",
"p[0] = TreeNode('assign_op', p[1], 'OPERATOR') return def p_IfStmt(p): '''IfStmt :",
"parsed.append(p.slice) p[0] = p[1] p[0].name = 'Declaration' return def p_ConstDecl(p):",
"p[0] = p[1] p[0].name = 'Declaration' return def p_ConstDecl(p): '''ConstDecl",
"COMMA IdentifierBotList ''' parsed.append(p.slice) node = TreeNode('IDENTIFIER', p[1], 'INT', 1)",
"gen('temp'), 'INT', 1) p[0].TAC.add_line([check_variable(p[1]), check_variable(p[0]), check_variable(p[2]), '']) p[0].name = 'UnaryExpr'",
"Type ''' parsed.append(p.slice) p[0] = TreeNode('ArrayType', p[2].data, p[4].data) return def",
"'name') and p[1].name == 'IdentifierList': for node in p[1].children: p[0].data",
"'']) if len(p) == 3: l1 = gen('label') # l2",
"in generated['temp']: print_error(\"Variable \" + p[3].data + \" is undefined\")",
"'Operand' return def p_Literal(p): '''Literal : BasicLit | FunctionLit '''",
"LT_MINUS ''' parsed.append(p.slice) p[0] = TreeNode('unary_op', p[1], 'OPERATOR') return def",
"# expr_list = TreeNode('Expr_List', 0, 'NONE', 0, [zero_val] * l1)",
"''' # print p.slice parsed.append(p.slice) if len(p) == 3: p[0]",
"add to SymbolTable\") return name = symbol_table.search_identifier(p[1].data) newNode = SymbolTableNode(name,",
"p[0].TAC.add_line(['print_int', check_variable(p[0]), '', '']) p[0].name = 'PrintIntStmt' return def p_PrintStrStmt(p):",
"def p_ExprSwitchCase(p): '''ExprSwitchCase : CASE ExpressionList | DEFAULT | CASE",
"p[0] = TreeNode('VarSpec',p[1].data,'INT') # expr = TreeNode('Expr', 0, 'NONE') #",
"if len(p) == 2: p[0] = p[1] elif len(p) ==",
"= TreeNode('ParameterDecl', 0, 'None') if len(p) == 3: if hasattr(p[1],",
"p[0].TAC.append_TAC(p[3].TAC) p[0].TAC.append_TAC(p[1].TAC) p[0].TAC.add_line([p[2], check_variable(p[1]), check_variable(p[3]), '']) return def p_Assignment(p): '''Assignment",
"+ \" is undefined\") return if p[3].children[i].isLvalue == 1 and",
"'''ForStmt : FOR Expression Block | FOR Block ''' parsed.append(p.slice)",
"identifier(s) but \" + str(l2) + \" value(s)\") elif p[1].name",
"'''StatementList : Statement SEMICOLON StatementList | empty ''' parsed.append(p.slice) if",
"return name else: return name + '[' + TreeNode.children +",
"0, 'INT', 0, [p[1]] + p[3].children, p[1].TAC) p[0].TAC.append_TAC(p[3].TAC) return def",
"== False: print_error(\"Unable to add to SymbolTable\") return p[0].TAC.append_TAC(p[3].TAC) p[0].TAC.append_TAC(p[1].TAC)",
"p[0].TAC.add_line(['goto', l2, '', '']) for i in range(p[5].TAC.length()): if i",
"+ p[3].children, p[3].TAC) return def p_IdentifierBotList(p): '''IdentifierBotList : IDENTIFIER COMMA",
"| Expression MINUS Expression | Expression OR Expression | Expression",
"def p_Statement(p): '''Statement : Declaration | SimpleStmt | ReturnStmt |",
"= TreeNode('IDENTIFIER', gen('temp'), 'INT', 1) p[0].TAC.add_line(['=', check_variable(t1) , check_variable(p[2]), ''])",
"'', '']) if temp != p[2].data: print_error('Function ' + funcName",
"one_val.data]) else: p[0].TAC.add_line(['-', check_variable(p[1]), check_variable(p[1]), one_val.data]) else: print_error(\"Lvalue required\") p[0].name",
"| Expression GT Expression | Expression GT_EQ Expression | Expression",
"f.name == funcName: temp = len(f.parameters) # p[2].print_node() for child",
"= TreeNode('IDENTIFIER', gen('temp'), 'INT', 1) p[0].TAC.add_line([check_variable(p[1]), check_variable(p[0]), check_variable(p[2]), '']) p[0].name",
"''' parsed.append(p.slice) return def p_FunctionType(p): '''FunctionType : FUNC Signature '''",
"l1 = gen('label') l2 = gen('label') p[0].TAC.add_line(['label', l1, '', ''])",
"Type EQ ExpressionList ''' # Insert into symbol table p[0]",
"p[0].TAC.append_TAC(p[3].TAC) return def p_TypeDecl(p): '''TypeDecl : TYPE TypeSpecTopList ''' parsed.append(p.slice)",
"def p_Literal(p): '''Literal : BasicLit | FunctionLit ''' parsed.append(p.slice) p[0]",
"BREAK IDENTIFIER ''' parsed.append(p.slice) return def p_ContinueStmt(p): '''ContinueStmt : CONTINUE",
"PLUS | MINUS | NOT | CARET | STAR |",
"'''ConstSpecList : empty | ConstSpecList ConstSpec SEMICOLON ''' parsed.append(p.slice) return",
"p[0].TAC.append_TAC(p[3].TAC) return def p_ParameterDecl(p): '''ParameterDecl : IdentifierList Type | IDENTIFIER",
"Expression ''' parsed.append(p.slice) if len(p) == 2: p[0] = TreeNode('ExpressionBotList',",
"one_val = TreeNode('IncDecStmt', '1', 'INT') p[0] = p[1] if p[1].isLvalue",
"in range(len(p[5].children)): p[0].TAC.add_line(['ifgotoeq', check_variable(t1), p[5].children[i][0], p[5].children[i][1]]) p[0].TAC.add_line(['goto', l2, '', ''])",
"return 2 values. first is the name for the variable,",
"+ funcName + ' requires ' + str(temp) + '",
"file ' + input_file + ' does not exist') sys.exit(1)",
"SymbolTableNode(s + '_' + child.data, child.input_type) symbol_table.add_var(newNode, s) # symbol_table.print_symbol_table()",
"parsed.append(p.slice) return def p_Expression(p): '''Expression : UnaryExpr | Expression OR_OR",
"child in reversed(p[3].children): p[0].TAC.add_line(['getparam', p[4].data + '_' + child.data, '',",
"assembly_code.print_code() # symbol_table.print_symbol_table() return def p_ImportDeclList(p): '''ImportDeclList : ImportDecl SEMICOLON",
"| Expression LT Expression | Expression LT_EQ Expression | Expression",
": Literal | LROUND Expression RROUND ''' parsed.append(p.slice) if len(p)",
"var_list = symbol_table.make_var_list() three_addr_code = convert_tac(p[0].TAC) symbol_table.fill_next_use(three_addr_code) assembly_code = generate_assembly(three_addr_code,var_list,symbol_table)",
"1) return def p_FunctionBody(p): '''FunctionBody : Block ''' parsed.append(p.slice) p[0]",
"p[0] = TreeNode('FunctionDecl', 0, 'INT') # print symbol_table.current_scope # p[4].TAC.print_code()",
"''' parsed.append(p.slice) if len(p) == 2: p[0] = p[1] p[0].name",
"IDENTIFIER ''' parsed.append(p.slice) return def p_Expression(p): '''Expression : UnaryExpr |",
"= TreeNode('FunctionName', p[1], 'INT', 1) return def p_FunctionBody(p): '''FunctionBody :",
"| Expression STAR Expression | Expression DIVIDE Expression | Expression",
"values. first is the name for the variable, second is",
"TreeNode('FunctionDecl', 0, 'INT') # print symbol_table.current_scope # p[4].TAC.print_code() symbol_table.add_function(p[2].data, p[3].input_type,",
"CONST ConstSpec ''' parsed.append(p.slice) return def p_ConstSpecList(p): '''ConstSpecList : empty",
"parsed.append(p.slice) p[0] = p[1] p[0].name = 'SimpleStmt' return def p_IncDecStmt(p):",
"p[0] = TreeNode('octal_lit', p[1], 'OCT') return def p_hex_lit(p): '''hex_lit :",
"else: print_error(\"Variable Declaration mismatch: \" + str(l1) + \" identifier(s)",
"| StandardTypes | LROUND Type RROUND ''' parsed.append(p.slice) if len(p)",
"'''FieldDeclList : empty | FieldDeclList FieldDecl SEMICOLON ''' parsed.append(p.slice) return",
"symbol_table.add_var(newNode) p[0].TAC.add_line(['print_str', name, '', '']) p[0].name = 'PrintStrStmt' return def",
"== False: print_error(\"Unable to add to SymbolTable\") return name =",
"elseTail ''' parsed.append(p.slice) if len(p) == 4: l1 = gen('label')",
"i in p[5].TAC.leaders[1:]: p[0].TAC.add_line(['goto', l2, '', '']) p[0].TAC.add_line(p[5].TAC.code[i]) p[0].TAC.add_line(['label', l2,",
"= p[1] p[0].name = 'Literal' return def p_BasicLit(p): '''BasicLit :",
"in p[5].TAC.leaders[1:]: p[0].TAC.add_line(['goto', l2, '', '']) p[0].TAC.add_line(p[5].TAC.code[i]) p[0].TAC.add_line(['label', l2, '',",
"+ gen('str_list') parametersNode = SymbolTableNode(p[3].data, p[3].input_type) newNode = SymbolTableNode(name, p[3].input_type,",
"Parameters Result ''' parsed.append(p.slice) p[0] = p[1] p[0].name = 'Signature'",
"== 5: noOfParams = 0 for f in symbol_table.symbol_table[symbol_table.current_scope]['functions']: if",
"'']) if len(p) == 6: l1 = gen('label') l2 =",
"2: p[0] = p[1] elif len(p) == 3: p[0] =",
"'']) p[0].name = 'UnaryExpr' return def p_unary_op(p): '''unary_op : PLUS",
"p[0].name = 'Block' return def p_ScopeStart(p): '''ScopeStart : empty '''",
"logging.DEBUG, filename = \"parselog.txt\", filemode = \"w\", format = \"%(filename)10s:%(lineno)4d:%(message)s\"",
"| Expression LS Expression | Expression RS Expression | Expression",
"''' parsed.append(p.slice) p[0] = TreeNode('ForStmt', 0, 'INT') if len(p) ==",
"p[3].children[i].data not in generated['temp']: print_error(\"Variable \" + p[3].children[i].data + \"",
"LROUND RROUND | LROUND ParameterList RROUND ''' parsed.append(p.slice) if len(p)",
"'STRING') return def p_rune_lit(p): '''rune_lit : RUNE_LIT ''' parsed.append(p.slice) p[0]",
"in p[1].children: symbol_table.add_identifier(child, s) newNode = SymbolTableNode(s + '_' +",
"!= 'STRING': return TreeNode.data else: TreeNode.print_node() return TreeNode.data precedence =",
"parsed.append(p.slice) p[0] = TreeNode('unary_op', p[1], 'OPERATOR') return def p_PrimaryExpr(p): '''PrimaryExpr",
"= TreeNode('Expr_List', 0, 'NONE', 0, [zero_val] * l1) # elif",
"== 4: # expr_list = p[3] # elif len(p) ==",
"| Expression NOT_EQ Expression | Expression LT Expression | Expression",
"print_error(\"Unable to add to SymbolTable\") return name = symbol_table.search_identifier(p[1].data) newNode",
"== 'Expression': if p[1].isLvalue == 0: print_error(\"Lvalue required\") return else:",
"''' parsed.append(p.slice) return def p_Signature(p): '''Signature : Parameters | Parameters",
"'''float_lit : FLOAT_LIT ''' parsed.append(p.slice) p[0] = TreeNode('float_lit', p[1], 'FLOAT')",
"EQ | PLUS_EQ | MINUS_EQ | OR_EQ | CARET_EQ |",
"STAR Type ''' parsed.append(p.slice) return def p_ArrayType(p): '''ArrayType : LSQUARE",
"Block | IfStmt | SwitchStmt | ForStmt | BreakStmt |",
"DECIMAL_LIT ''' parsed.append(p.slice) p[0] = TreeNode('decimal_lit', p[1], 'INT') return def",
"= 'Arguments' p[0].data = len(p[2].children) return def p_string_lit(p): '''string_lit :",
"# print symbol_table.current_scope # p[4].TAC.print_code() symbol_table.add_function(p[2].data, p[3].input_type, p[3].children) if len(p)",
"generated = {'temp': [], 'scope': ['scope_0'], 'label': [], 'str_list': []}",
"found # TreeNode.print_node() # symbol_table.print_symbol_table() if TreeNode.isLvalue == 1: if",
"Not implemented yet return def p_Selector(p): '''Selector : DOT IDENTIFIER",
"\" is undefined\") return TreeNode.data else: return name else: newNode",
"RROUND | PRINTLN LROUND int_lit RROUND ''' if hasattr(p[3], 'name')",
"TreeNode.print_node() return TreeNode.data precedence = ( ('left','IDENTIFIER'), ('right','ASSIGN_OP'), ('left','COMMA'), ('left','LSQUARE'),",
"symbol_table.add_var(newNode) return TreeNode.data else: if TreeNode.input_type != 'STRING': return TreeNode.data",
"'empty :' pass def p_error(p): print p if p ==",
"p[3].TAC) return def p_IdentifierBotList(p): '''IdentifierBotList : IDENTIFIER COMMA IdentifierBotList |",
"TreeNode from code import ThreeAddressCode from lexer import tokens from",
"p_TagTop(p): '''TagTop : empty | Tag ''' parsed.append(p.slice) return def",
": LSQUARE Expression RSQUARE ''' parsed.append(p.slice) p[0] = p[2] p[0].name",
"p[1].children[i].data + \" is undefined\") return if p[3].children[i].isLvalue == 1",
"== 3: if p[2].name == 'Expression': p[0] = p[2] p[0].name",
"'INT', 1) p[0] = TreeNode('IdentifierList', 0, 'None', 0, [node] +",
"!= None: p[0] = TreeNode('TopLevelDeclList', 0, 'INT', 0, [p[1]] +",
"= TreeNode('ShortVarDecl', 0, 'INT') if p[1].name == 'ExpressionList': l1 =",
"p[0] = TreeNode('IDENTIFIER', gen('temp'), 'INT', 1, [], p[1].TAC) p[0].TAC.append_TAC(p[3].TAC) p[0].TAC.add_line([p[2],check_variable(p[0]),",
"''' parsed.append(p.slice) l1 = gen('label') p[0] = TreeNode('ExprCaseClause', 0, 'INT')",
"return def p_Literal(p): '''Literal : BasicLit | FunctionLit ''' parsed.append(p.slice)",
"Expression RSQUARE ''' parsed.append(p.slice) p[0] = p[2] p[0].name = 'Index'",
"Expression AND_OR Expression ''' parsed.append(p.slice) if len(p) == 2: p[0]",
"if symbol_table.search_identifier(p[1].children[i].data) == False and p[1].children[i].data not in generated['temp']: print_error(\"Variable",
"Imports for now return def p_TopLevelDeclList(p): '''TopLevelDeclList : TopLevelDecl SEMICOLON",
"Expression | IDENTIFIER Type EQ Expression | IdentifierList Type |",
"0, 'INT') p[0].TAC.append_TAC(p[2].TAC) p[0].TAC.add_line(['ifgotoeq', check_variable(p[2]), '0', l1]) p[0].TAC.append_TAC(p[3].TAC) p[0].TAC.add_line(['goto', l2,",
"parsed.append(p.slice) return def p_ContinueStmt(p): '''ContinueStmt : CONTINUE IDENTIFIER ''' parsed.append(p.slice)",
"'''FunctionDecl : FUNC FunctionName Signature | FUNC FunctionName Signature FunctionBody",
"LROUND TypeSpecList RROUND ''' parsed.append(p.slice) return def p_TypeSpecList(p): '''TypeSpecList :",
"else: if TreeNode.input_type != 'STRING': return TreeNode.data else: TreeNode.print_node() return",
"len(p) == 3: if hasattr(p[1], 'name') and p[1].name == 'IdentifierList':",
"Statement SEMICOLON StatementList | empty ''' parsed.append(p.slice) if len(p) ==",
"parsed = [] symbol_table = SymbolTable() var_list = [] generated",
"def p_FunctionBody(p): '''FunctionBody : Block ''' parsed.append(p.slice) p[0] = p[1]",
"'INT', 1) return def p_FunctionBody(p): '''FunctionBody : Block ''' parsed.append(p.slice)",
"check_variable(p[3].children[i]), '']) else: print_error(\"Variable Declaration mismatch: \" + str(l1) +",
"p[1].data + \" is undefined\") return if p[3].isLvalue == 1",
"p_ImportSpecList(p): '''ImportSpecList : ImportSpec SEMICOLON ImportSpecList | empty ''' parsed.append(p.slice)",
"== funcName: temp = len(f.parameters) # p[2].print_node() for child in",
"p[0].TAC.add_leader(p[0].TAC.length()) p[0].TAC.append_TAC(p[2].TAC) p[0].data.append_TAC(TAC2) else: p[0] = TreeNode('ExprCaseClauseList', TAC1, 'INT') return",
"not in generated.keys(): generated[s] = [] temp = s +",
"else: p[0] = TreeNode('ExprCaseClauseList', TAC1, 'INT') return def p_ExprCaseClause(p): '''ExprCaseClause",
"= s + '_' + str(len(generated[s])) generated[s] += [temp] return",
"Imports for now return def p_ImportSpecList(p): '''ImportSpecList : ImportSpec SEMICOLON",
"| IdentifierList EQ ExpressionList | IdentifierList Type EQ ExpressionList '''",
"TreeNode('VarSpec',p[1].data,'INT') # expr = TreeNode('Expr', 0, 'NONE') # if len(p)",
"hasattr(p[3], 'name') and p[3].name == 'int_lit': p[0] = p[3] #",
"= p[2] p[0].name = 'ReturnStmt' p[0].TAC.add_line(['return', check_variable(p[2]), '', '']) return",
"= symbol_table.search_identifier(p[1].data) newNode = SymbolTableNode(name, p[1].input_type,size = p[2].data) symbol_table.add_var(newNode) p[0]",
"'''GotoStmt : GOTO IDENTIFIER ''' parsed.append(p.slice) return def p_Expression(p): '''Expression",
"== 4: p[0] = TreeNode('IDENTIFIER', gen('temp'), 'INT', 1, [], p[1].TAC)",
"p[1], 'HEX') return def p_float_lit(p): '''float_lit : FLOAT_LIT ''' parsed.append(p.slice)",
"p[2].name == 'ExpressionList': p[0] = p[2] p[0].name = 'Arguments' p[0].data",
"PRINTLN LROUND IDENTIFIER RROUND | PRINTLN LROUND int_lit RROUND '''",
"for f in symbol_table.symbol_table[symbol_table.current_scope]['functions']: if f.name == p[2].data: noOfParams =",
"is undefined\") return # print symbol_table.current_scope p[0].TAC.append_TAC(p[3].TAC) p[0].TAC.append_TAC(p[1].TAC) p[0].TAC.add_line([p[2].data, check_variable(p[1]),",
"TreeNode('SwitchStmt', 0, 'INT', 0, [], p[1].TAC) return def p_ExprSwitchStmt(p): '''ExprSwitchStmt",
"p[1].isLvalue == 0: print_error(\"Lvalue required\") return else: if symbol_table.search_identifier(p[1].data) ==",
"if len(p) == 2: p[0] = TreeNode('ReturnStmt', 0, 'None') p[0].TAC.add_line(['return',",
": TypeLit | StandardTypes | LROUND Type RROUND ''' parsed.append(p.slice)",
"to add to SymbolTable\") return name = symbol_table.search_identifier(p[1].data) newNode =",
"Expression DIVIDE Expression | Expression MODULO Expression | Expression LS",
"symbol_table.add_function(p[2].data, p[3].input_type, p[3].children) if len(p) == 5: noOfParams = 0",
"p[0] = TreeNode('rune_lit', p[1], 'RUNE') return def p_empty(p): 'empty :'",
"== 3: if hasattr(p[1], 'name') and p[1].name == 'IdentifierList': for",
"p[0].name = 'UnaryExpr' return def p_unary_op(p): '''unary_op : PLUS |",
"IDENTIFIER Type | IDENTIFIER EQ Expression | IDENTIFIER Type EQ",
"ScopeEnd RCURLY | SWITCH SimpleStmt SEMICOLON Expression LCURLY ScopeStart ExprCaseClauseList",
"* from symbol_table import SymbolTable from symbol_table import SymbolTableNode import",
"p[0] = TreeNode('VarSpec', 0, 'NONE') if hasattr(p[1], 'name') and p[1].name",
"| LROUND Expression RROUND | LROUND Type RROUND | LROUND",
"return def p_ImportSpecList(p): '''ImportSpecList : ImportSpec SEMICOLON ImportSpecList | empty",
"'''ExpressionBotList : Expression COMMA ExpressionBotList | Expression ''' parsed.append(p.slice) if",
"'''IncDecStmt : Expression PLUS_PLUS | Expression MINUS_MINUS ''' parsed.append(p.slice) one_val",
"def p_IdentifierBotList(p): '''IdentifierBotList : IDENTIFIER COMMA IdentifierBotList | IDENTIFIER '''",
"SEMICOLON TopLevelDeclList | empty ''' parsed.append(p.slice) if len(p) == 4:",
"p[0].TAC.add_line(['label', l1, '', '']) p[0].TAC.append_TAC(p[2].TAC) p[0].TAC.add_line(['ifgotoeq',check_variable(p[2]), '0', l2]) p[0].TAC.append_TAC(p[3].TAC) p[0].TAC.add_line(['goto',",
"Block ''' parsed.append(p.slice) p[0] = p[1] p[0].name = 'elseTail' return",
"return def p_PrintIntStmt(p): '''PrintIntStmt : PRINTLN LROUND IDENTIFIER RROUND |",
"== False: print_error(\"Variable \" + TreeNode.data + \" is undefined\")",
"p[1], p[2].data, 1) p[0].data += 1 p[0].children += [node] else:",
"newNode = SymbolTableNode(name, p[1].input_type,size = p[2].data) symbol_table.add_var(newNode) p[0] = TreeNode('VarSpec',p[1].data,'INT')",
"# Anonymous Function # Not implemented yet return def p_Selector(p):",
"p[1] p[0].name = 'elseTail' return def p_SwitchStmt(p): '''SwitchStmt : ExprSwitchStmt",
"random import * from symbol_table import SymbolTable from symbol_table import",
"= TreeNode('unary_op', p[1], 'OPERATOR') return def p_PrimaryExpr(p): '''PrimaryExpr : Operand",
"= TreeNode('ExpressionList', 0, 'INT', 0, [p[1]] + p[3].children, p[1].TAC) p[0].TAC.append_TAC(p[3].TAC)",
"def p_ExpressionBotList(p): '''ExpressionBotList : Expression COMMA ExpressionBotList | Expression '''",
"p[0].TAC.add_line(['label', l2, '', '']) return def p_ExprCaseClauseList(p): '''ExprCaseClauseList : empty",
"print p.slice parsed.append(p.slice) if len(p) == 3: p[0] = TreeNode('Arguments',",
": EQ | PLUS_EQ | MINUS_EQ | OR_EQ | CARET_EQ",
"p[1] p[0].name = 'Literal' return def p_BasicLit(p): '''BasicLit : int_lit",
"# for i in range(l1): # p[0].TAC.add_line(['=', p[1].children[i], expr_list.children[i].data, ''])",
"IDENTIFIER EQ Expression | IdentifierList EQ ExpressionList | IDENTIFIER Type",
"def p_Type(p): '''Type : TypeLit | StandardTypes | LROUND Type",
"return else: if symbol_table.add_identifier(p[1].children[i]) == False: print_error(\"Unable to add to",
"p[0].TAC.add_line(['+', check_variable(p[1]), check_variable(p[1]), one_val.data]) else: p[0].TAC.add_line(['-', check_variable(p[1]), check_variable(p[1]), one_val.data]) else:",
": TypeSpec | LROUND TypeSpecList RROUND ''' parsed.append(p.slice) return def",
"symbol_table.search_identifier(p[1].data) == False and p[1].data not in generated['temp']: print_error(\"Variable \"",
"gen('label') # l2 = gen('label') p[0].TAC.add_line(['label', l1, '', '']) p[0].TAC.append_TAC(p[2].TAC)",
"p[0].TAC.add_line(['ifgotoeq', check_variable(p[2]), '0', l1]) p[0].TAC.append_TAC(p[3].TAC) p[0].TAC.add_line(['goto', l2, '', '']) p[0].TAC.add_line(['label',",
"0, 'INT') # print symbol_table.current_scope # p[4].TAC.print_code() symbol_table.add_function(p[2].data, p[3].input_type, p[3].children)",
"'INT', 0, [p[1]], p[1].TAC) elif len(p) == 4: p[0] =",
"but ' + str(p[2].data) + ' supplied') p[0].TAC.add_line(['call', check_variable(p[1]), str(p[2].data),",
"TreeNode.data else: if TreeNode.input_type != 'STRING': return TreeNode.data else: TreeNode.print_node()",
"if len(p) == 3: if hasattr(p[1], 'name') and p[1].name ==",
"and p[1].data not in generated['temp']: print_error(\"Variable \" + p[1].data +",
"symbol_table.add_var(newNode) if TreeNode.children == []: return name else: return name",
"in range(l1): if p[1].children[i].isLvalue == 0: print_error(\"Lvalue required\") return else:",
"funcName = \"_\".join(func[:2]), \"_\".join(func[2:]) temp = 0 for f in",
"''' parsed.append(p.slice) p[0] = p[1] p[0].name = 'BasicLit' return def",
": RUNE_LIT ''' parsed.append(p.slice) p[0] = TreeNode('rune_lit', p[1], 'RUNE') return",
"empty | FieldDeclList FieldDecl SEMICOLON ''' parsed.append(p.slice) return def p_FieldDecl(p):",
"return def p_Index(p): '''Index : LSQUARE Expression RSQUARE ''' parsed.append(p.slice)",
"== 'IDENTIFIER': p[0] = TreeNode('IDENTIFIER', p[1], 'INT', 1) elif p[1].name",
"TopLevelDeclList | empty ''' parsed.append(p.slice) if len(p) == 4: if",
"= p[3] p[0].data = p[2].data p[0].name = 'Block' return def",
"l1) # elif len(p) == 4: # expr_list = p[3]",
"pass def p_error(p): print p if p == None: print",
"def p_Block(p): '''Block : LCURLY ScopeStart StatementList ScopeEnd RCURLY '''",
"def p_string_lit(p): '''string_lit : STRING_LIT ''' parsed.append(p.slice) p[0] = TreeNode('string_lit',",
"[p[1]] return def p_VarDecl(p): '''VarDecl : VAR VarSpecTopList ''' parsed.append(p.slice)",
"PLUS_PLUS | Expression MINUS_MINUS ''' parsed.append(p.slice) one_val = TreeNode('IncDecStmt', '1',",
"TreeNode('ArrayType', p[2].data, p[4].data) return def p_ArrayLength(p): '''ArrayLength : Expression '''",
"'STRING': return TreeNode.data else: TreeNode.print_node() return TreeNode.data precedence = (",
"p_BreakStmt(p): '''BreakStmt : BREAK IDENTIFIER ''' parsed.append(p.slice) return def p_ContinueStmt(p):",
"gen(s): if s not in generated.keys(): generated[s] = [] temp",
"''' parsed.append(p.slice) return def p_TypeSpec(p): '''TypeSpec : AliasDecl | TypeDef",
"p_Signature(p): '''Signature : Parameters | Parameters Result ''' parsed.append(p.slice) p[0]",
"LSQUARE ArrayLength RSQUARE Type ''' parsed.append(p.slice) p[0] = TreeNode('ArrayType', p[2].data,",
"= p[1] p[0].name = 'Result' return def p_Parameters(p): '''Parameters :",
"ScopeStart ExprCaseClauseList ScopeEnd RCURLY | SWITCH LCURLY ScopeStart ExprCaseClauseList ScopeEnd",
"parsed.append(p.slice) return def p_ConstSpecList(p): '''ConstSpecList : empty | ConstSpecList ConstSpec",
"p[0].TAC.add_line([check_variable(p[1]), check_variable(p[0]), check_variable(p[2]), '']) p[0].name = 'UnaryExpr' return def p_unary_op(p):",
"Function # Not implemented yet return def p_Selector(p): '''Selector :",
"p_TypeLit(p): '''TypeLit : ArrayType | StructType | FunctionType | PointerType",
"Type EQ ExpressionList ''' parsed.append(p.slice) return def p_IdentifierList(p): '''IdentifierList :",
"parsed.append(p.slice) p[0] = TreeNode('ExpressionList', 0, 'INT', 0, [p[1]] + p[3].children,",
"name = symbol_table.search_identifier(p[1].data) newNode = SymbolTableNode(name, p[1].input_type,size = p[2].data) symbol_table.add_var(newNode)",
"return def p_ArrayType(p): '''ArrayType : LSQUARE ArrayLength RSQUARE Type '''",
"return def p_Result(p): '''Result : Parameters | Type ''' parsed.append(p.slice)",
"('left', 'OR_OR'), ('left', 'AMP_AMP'), ('left', 'EQ_EQ', 'NOT_EQ','LT','LT_EQ','GT','GT_EQ'), ('left', 'PLUS', 'MINUS','OR','CARET'),",
"COMMA Expression RROUND ''' # print p.slice parsed.append(p.slice) if len(p)",
"check_variable(p[1]), check_variable(expr), '']) return def p_FunctionDecl(p): '''FunctionDecl : FUNC FunctionName",
"'''ExprCaseClause : ExprSwitchCase COLON StatementList ''' parsed.append(p.slice) l1 = gen('label')",
"'Statement' return def p_PrintIntStmt(p): '''PrintIntStmt : PRINTLN LROUND IDENTIFIER RROUND",
"parsed.append(p.slice) p[0] = TreeNode('hex_lit', p[1], 'HEX') return def p_float_lit(p): '''float_lit",
"RROUND ''' p[0] = p[3] name = symbol_table.current_scope + '_'",
"# p[0].isLvalue = 0 else: p[0] = TreeNode('IDENTIFIER', p[3], 'INT',",
"# l1 = len(p[1].children) # if len(p) == 3: #",
"SymbolTableNode(TreeNode.data, TreeNode.input_type) symbol_table.add_var(newNode) return TreeNode.data else: if TreeNode.input_type != 'STRING':",
"parsed.append(p.slice) return def p_TagTop(p): '''TagTop : empty | Tag '''",
"if f.name == funcName: temp = len(f.parameters) # p[2].print_node() for",
"''' parsed.append(p.slice) p[0] = TreeNode('SwitchStmt', 0, 'INT', 0, [], p[1].TAC)",
"p[0].TAC.add_line(['call', check_variable(p[1]), str(p[2].data), '']) p[0].TAC.add_line(['return_value', check_variable(p[0]), '', '']) p[0].name =",
"'''hex_lit : HEX_LIT ''' parsed.append(p.slice) p[0] = TreeNode('hex_lit', p[1], 'HEX')",
"'r').read() if input_code[len(input_code)-1] != '\\n': input_code += '\\n' yacc.parse(input_code, debug=log,",
"| empty ''' parsed.append(p.slice) if len(p) == 4: if p[3]",
"== False and p[3].data not in generated['temp']: print_error(\"Variable \" +",
"from random import * from symbol_table import SymbolTable from symbol_table",
"node in p[1].children: p[0].data += 1 node.input_type = p[2].data p[0].children",
"== 4: if p[3] != None: p[0] = TreeNode('TopLevelDeclList', 0,",
"'OPERATOR') return def p_PrimaryExpr(p): '''PrimaryExpr : Operand | IDENTIFIER |",
"Expression | Expression LS Expression | Expression RS Expression |",
"not in generated['temp']: print_error(\"Variable \" + p[1].children[i].data + \" is",
"+= 1 node.input_type = p[2].data p[0].children += [node] else: node",
"= p[1] p[0].name = 'SimpleStmt' return def p_IncDecStmt(p): '''IncDecStmt :",
"but \" + str(l2) + \" value(s)\") elif p[1].name ==",
"# p[0].TAC.append_TAC(p[4].TAC) # p[0].TAC.add_line(['=', check_variable(p[1]), check_variable(expr), '']) return def p_FunctionDecl(p):",
"ArrayType | StructType | FunctionType | PointerType ''' parsed.append(p.slice) p[0]",
"p_VarSpecList(p): '''VarSpecList : empty | VarSpecList VarSpec SEMICOLON ''' return",
"== 3: p[0] = TreeNode('Parameters', 0, 'None') else: p[0] =",
"= gen('label') l2 = gen('label') p[0] = TreeNode('IfStmt', 0, 'INT')",
"LCURLY ScopeStart ExprCaseClauseList ScopeEnd RCURLY | SWITCH LCURLY ScopeStart ExprCaseClauseList",
"0 for f in symbol_table.symbol_table[scope]['functions']: if f.name == funcName: temp",
"| octal_lit | hex_lit ''' parsed.append(p.slice) p[0] = p[1] p[0].name",
"p[0] = TreeNode('Arguments', 0, 'None') if len(p) == 4: if",
"Expression LT Expression | Expression LT_EQ Expression | Expression GT",
"def p_Tag(p): '''Tag : string_lit ''' parsed.append(p.slice) return def p_FunctionType(p):",
"== l2: # for i in range(l1): # p[0].TAC.add_line(['=', p[1].children[i],",
"COMMA ExpressionList RROUND | LROUND Type COMMA Expression RROUND '''",
"= gen('label') # l2 = gen('label') p[0].TAC.add_line(['label', l1, '', ''])",
"else: if symbol_table.search_identifier(p[1].children[i].data) == False and p[1].children[i].data not in generated['temp']:",
"Expression ''' parsed.append(p.slice) if len(p) == 2: p[0] = p[1]",
"p[3].children[i].isLvalue == 1 and symbol_table.search_identifier(p[3].children[i].data) == False and p[3].children[i].data not",
"second is 0 if variable not found # TreeNode.print_node() #",
"symbol_table.print_symbol_table() return def p_ImportDeclList(p): '''ImportDeclList : ImportDecl SEMICOLON ImportDeclList |",
"elif len(p) == 4: # expr_list = p[3] # elif",
"Anonymous Function # Not implemented yet return def p_Selector(p): '''Selector",
"('left','BREAK'), ('left','CONTINUE'), ('left','RETURN'), ('left','RROUND'), ('left','LROUND'), ('left', 'OR_OR'), ('left', 'AMP_AMP'), ('left',",
"gen('temp'), 'INT', 1, [], p[1].TAC) p[0].TAC.append_TAC(p[3].TAC) p[0].TAC.add_line([p[2],check_variable(p[0]), check_variable(p[1]), check_variable(p[3])]) p[0].name",
"symbol_table.search_identifier(p[1].children[i].data) == False and p[1].children[i].data not in generated['temp']: print_error(\"Variable \"",
"'IDENTIFIER': p[0] = TreeNode('IDENTIFIER', p[1], 'INT', 1) elif p[1].name ==",
"''' parsed.append(p.slice) return def p_TypeSpecList(p): '''TypeSpecList : empty | TypeSpecList",
"elif len(p) == 4: p[0] = TreeNode('ParameterList', p[1].data + p[3].data,",
"RCURLY ''' parsed.append(p.slice) p[0] = p[3] p[0].data = p[2].data p[0].name",
"ThreeAddressCode() if len(p) == 3: TAC1 = p[1].data TAC2 =",
"''' parsed.append(p.slice) p[0] = TreeNode('string_lit', p[1], 'STRING') return def p_rune_lit(p):",
"p[1].TAC) elif len(p) == 4: p[0] = TreeNode('ExpressionBotList', 0, 'INT',",
"l2 = gen('label') p[0] = TreeNode('IfStmt', 0, 'INT') p[0].TAC.append_TAC(p[2].TAC) p[0].TAC.add_line(['ifgotoeq',",
"else: p[0] = p[2] p[0].name = 'Parameters' return def p_ParameterList(p):",
"Type RROUND ''' parsed.append(p.slice) if len(p) == 2: p[0] =",
"p[0].name = 'Signature' s = 'scope_' + str(len(generated['scope'])) symbol_table.new_scope(s) for",
"p[0].data.append_TAC(TAC2) else: p[0] = TreeNode('ExprCaseClauseList', TAC1, 'INT') return def p_ExprCaseClause(p):",
"== 0: print_error(\"Lvalue required\") return else: if symbol_table.search_identifier(p[1].children[i].data) == False",
": ExprSwitchCase COLON StatementList ''' parsed.append(p.slice) l1 = gen('label') p[0]",
"p[0].name = 'BasicLit' return def p_int_lit(p): '''int_lit : decimal_lit |",
"LROUND RROUND | LROUND ExpressionList RROUND | LROUND Expression RROUND",
"RSQUARE Type ''' parsed.append(p.slice) p[0] = TreeNode('ArrayType', p[2].data, p[4].data) return",
"| IDENTIFIER Type | Type ''' parsed.append(p.slice) p[0] = TreeNode('ParameterDecl',",
"# Insert into symbol table p[0] = TreeNode('VarSpec', 0, 'NONE')",
"p[0].TAC.add_line(p[5].TAC.code[i]) p[0].TAC.add_line(['label', l2, '', '']) return def p_ExprCaseClauseList(p): '''ExprCaseClauseList :",
"return def p_Selector(p): '''Selector : DOT IDENTIFIER ''' parsed.append(p.slice) return",
"= p[1] else: p[0] = p[2] p[0].name = 'Type' return",
"0 else: p[0] = TreeNode('IDENTIFIER', p[3], 'INT', 1, []) p[0].TAC.add_line(['print_int',",
"p[0].TAC.append_TAC(p[3].TAC) p[0].TAC.add_line(['goto', l2, '', '']) p[0].TAC.add_line(['label', l1, '', '']) p[0].TAC.append_TAC(p[5].TAC)",
"'Operand': p[0] = p[1] elif len(p) == 3: if p[2].name",
"']' else: newNode = SymbolTableNode(TreeNode.data, TreeNode.input_type) symbol_table.add_var(newNode) return TreeNode.data else:",
"str(len(generated[s])) generated[s] += [temp] return temp def print_error(err): print \"***",
"IMPORT ImportSpec ''' parsed.append(p.slice) # TODO: Ignoring Imports for now",
"IDENTIFIER Type | Type ''' parsed.append(p.slice) p[0] = TreeNode('ParameterDecl', 0,",
"is undefined\") return p[0].TAC.add_line([p[2].data, check_variable(p[1].children[i]), check_variable(p[3].children[i]), '']) else: print_error(\"Variable Declaration",
"p[0].TAC.add_line([p[2], check_variable(p[1].children[i]), check_variable(p[3].children[i]), '']) else: print_error(\"Variable Declaration mismatch: \" +",
"sys.exit(1) input_code = open(input_file, 'r').read() if input_code[len(input_code)-1] != '\\n': input_code",
"p[1].data + p[3].data, 'None', 0, p[1].children + p[3].children, p[1].TAC) p[0].TAC.append_TAC(p[3].TAC)",
"Expression MODULO Expression | Expression LS Expression | Expression RS",
"'_' + child.data, child.input_type) symbol_table.add_var(newNode, s) # symbol_table.print_symbol_table() if len(p)",
"+ \" is undefined\") return # print symbol_table.current_scope p[0].TAC.append_TAC(p[3].TAC) p[0].TAC.append_TAC(p[1].TAC)",
"len(p) == 5: # expr = p[4] # p[0].TAC.append_TAC(p[4].TAC) #",
"var_list = [] generated = {'temp': [], 'scope': ['scope_0'], 'label':",
"''' parsed.append(p.slice) p[0] = p[1] p[0].name = 'int_lit' return def",
"l2: for i in range(l1): if p[1].children[i].isLvalue == 0: print_error(\"Lvalue",
"p[2] p[0].name = 'Parameters' return def p_ParameterList(p): '''ParameterList : ParameterDecl",
"# p[0].TAC.add_line(['=', p[1].children[i], expr_list.children[i].data, '']) # else: # print_error(\"Variable Declaration",
"''' parsed.append(p.slice) return def p_Type(p): '''Type : TypeLit | StandardTypes",
"generated['temp']: print_error(\"Variable \" + p[3].data + \" is undefined\") return",
"= 'Operand' return def p_Literal(p): '''Literal : BasicLit | FunctionLit",
"empty ''' parsed.append(p.slice) # TODO: Ignoring Imports for now return",
"0, [node]) elif len(p) == 4: node = TreeNode('IDENTIFIER', p[1],",
"'Expression': p[0] = p[2] p[0].name = 'ReturnStmt' p[0].TAC.add_line(['return', check_variable(p[2]), '',",
"LS Expression | Expression RS Expression | Expression AMP Expression",
"Expression LS Expression | Expression RS Expression | Expression AMP",
"| AMP | LT_MINUS ''' parsed.append(p.slice) p[0] = TreeNode('unary_op', p[1],",
"| SimpleStmt | ReturnStmt | Block | IfStmt | SwitchStmt",
"0 if variable not found # TreeNode.print_node() # symbol_table.print_symbol_table() if",
"+ p[3].children, p[1].TAC) p[0].TAC.append_TAC(p[3].TAC) return def p_ParameterDecl(p): '''ParameterDecl : IdentifierList",
"'INT') return def p_ExprCaseClause(p): '''ExprCaseClause : ExprSwitchCase COLON StatementList '''",
": BREAK IDENTIFIER ''' parsed.append(p.slice) return def p_ContinueStmt(p): '''ContinueStmt :",
"parsed.append(p.slice) p[0] = TreeNode('StandardTypes', p[1], 'NONE') return def p_TypeLit(p): '''TypeLit",
"parameters = [parametersNode]) symbol_table.add_var(newNode) p[0].TAC.add_line(['print_str', name, '', '']) p[0].name =",
"Insert into symbol table p[0] = TreeNode('VarSpec', 0, 'NONE') if",
"LS_EQ | RS_EQ | AMP_EQ | AND_OR_EQ ''' parsed.append(p.slice) p[0]",
"line no \" + str(p.lineno) # Standard Logger logging.basicConfig( level",
"''' parsed.append(p.slice) p[0] = TreeNode('ParameterDecl', 0, 'None') if len(p) ==",
"'INT') return def p_Statement(p): '''Statement : Declaration | SimpleStmt |",
"p_PrintIntStmt(p): '''PrintIntStmt : PRINTLN LROUND IDENTIFIER RROUND | PRINTLN LROUND",
"TreeNode('string_lit', p[1], 'STRING') return def p_rune_lit(p): '''rune_lit : RUNE_LIT '''",
"''' parsed.append(p.slice) return def p_TypeDef(p): '''TypeDef : IDENTIFIER Type '''",
"parsed.append(p.slice) symbol_table.end_scope() return def p_StatementList(p): '''StatementList : Statement SEMICOLON StatementList",
"len(p) == 5: # expr_list = p[4] # l2 =",
"p[0].TAC.append_TAC(p[3].TAC) p[0].children = [[p[1].data,l1]] p[0].data = p[1].TAC return def p_ExprSwitchCase(p):",
"FOR Block ''' parsed.append(p.slice) p[0] = TreeNode('ForStmt', 0, 'INT') if",
"p[0].name = 'PrintStrStmt' return def p_Declaration(p): '''Declaration : ConstDecl |",
"print_error('Function ' + funcName + ' requires ' + str(temp)",
"p[3].children, p[1].TAC) p[0].TAC.append_TAC(p[3].TAC) return def p_ExpressionBotList(p): '''ExpressionBotList : Expression COMMA",
"p_unary_op(p): '''unary_op : PLUS | MINUS | NOT | CARET",
"p[3] # elif len(p) == 5: # expr_list = p[4]",
"= p[1] p[0].name = 'ParameterList' elif len(p) == 4: p[0]",
"'''FunctionLit : FUNC Signature FunctionBody ''' parsed.append(p.slice) # Anonymous Function",
"= TreeNode('TopLevelDeclList', 0, 'INT', 0, [p[1]] + p[3].children, p[1].TAC) p[0].TAC.append_TAC(p[3].TAC)",
"'''IdentifierList : IDENTIFIER COMMA IdentifierBotList ''' parsed.append(p.slice) node = TreeNode('IDENTIFIER',",
"ConstSpec ''' parsed.append(p.slice) return def p_ConstSpecList(p): '''ConstSpecList : empty |",
"and p[3].data not in generated['temp']: print_error(\"Variable \" + p[3].data +",
"if p[3].children[i].isLvalue == 1 and symbol_table.search_identifier(p[3].children[i].data) == False and p[3].children[i].data",
"p[3] # p[0].isLvalue = 0 else: p[0] = TreeNode('IDENTIFIER', p[3],",
"Expression | Expression GT Expression | Expression GT_EQ Expression |",
"return def p_Type(p): '''Type : TypeLit | StandardTypes | LROUND",
"''' parsed.append(p.slice) p[0] = p[1] p[0].name = 'Declaration' return def",
"ShortVarDecl | IncDecStmt ''' parsed.append(p.slice) p[0] = p[1] p[0].name =",
"p_empty(p): 'empty :' pass def p_error(p): print p if p",
"Type TagTop ''' parsed.append(p.slice) return def p_TagTop(p): '''TagTop : empty",
"= TreeNode('ExpressionBotList', 0, 'INT', 0, [p[1]], p[1].TAC) elif len(p) ==",
"Parameters | Parameters Result ''' parsed.append(p.slice) p[0] = p[1] p[0].name",
"three_addr_code = convert_tac(p[0].TAC) symbol_table.fill_next_use(three_addr_code) assembly_code = generate_assembly(three_addr_code,var_list,symbol_table) # p[0].TAC.print_code() #",
"'INT') # p[0].TAC.append_TAC(p[1].TAC) p[0].TAC.add_line(['label', l1, '', '']) # p[0].TAC.add_line(['ifgotoneq', p[1].children,",
"SimpleStmt | ReturnStmt | Block | IfStmt | SwitchStmt |",
"symbol_table.end_scope() return def p_StatementList(p): '''StatementList : Statement SEMICOLON StatementList |",
"p[0].TAC.add_line(['print_str', name, '', '']) p[0].name = 'PrintStrStmt' return def p_Declaration(p):",
"== 'Index': p[0] = TreeNode('IDENTIFIER', p[1].data, 'INT', 1, p[2].data) elif",
"p[2].data p[0] = TreeNode('ExprCaseClauseList', TAC1, 'INT', 0, p[1].children + p[2].children,",
"# p[0].TAC.append_TAC(expr_list.TAC) # p[0].TAC.append_TAC(p[1].TAC) # if l1 == l2: #",
"format = \"%(filename)10s:%(lineno)4d:%(message)s\" ) log = logging.getLogger() yacc.yacc(debug=True, debuglog=log) input_file",
"= p[2].TAC return def p_ForStmt(p): '''ForStmt : FOR Expression Block",
"p[2] p[0].name = 'VarDecl' return def p_VarSpecTopList(p): '''VarSpecTopList : VarSpec",
"SWITCH Expression LCURLY ScopeStart ExprCaseClauseList ScopeEnd RCURLY ''' parsed.append(p.slice) if",
"== 'Expression': p[0] = p[2] p[0].name = 'ReturnStmt' p[0].TAC.add_line(['return', check_variable(p[2]),",
"p[2].data) == False: print_error(\"Unable to add to SymbolTable\") return name",
"p[1] p[0].name = 'Statement' return def p_PrintIntStmt(p): '''PrintIntStmt : PRINTLN",
"Operand | IDENTIFIER | PrimaryExpr Selector | PrimaryExpr Index |",
"return def p_StandardTypes(p): '''StandardTypes : PREDEFINED_TYPES ''' parsed.append(p.slice) p[0] =",
"in generated.keys(): generated[s] = [] temp = s + '_'",
"parsed.append(p.slice) p[0] = p[1] p[0].name = 'Statement' return def p_PrintIntStmt(p):",
"# symbol_table.print_symbol_table() if len(p) == 2: p[0].input_type = TreeNode('Result', 0,",
"Standard Logger logging.basicConfig( level = logging.DEBUG, filename = \"parselog.txt\", filemode",
"0, 'INT') p[0].TAC.append_TAC(p[2].TAC) p[0].TAC.add_line(['ifgotoeq', check_variable(p[2]), '0', l1]) p[0].TAC.append_TAC(p[3].TAC) p[0].TAC.add_line(['label', l1,",
": LSQUARE ArrayLength RSQUARE Type ''' parsed.append(p.slice) p[0] = TreeNode('ArrayType',",
"'INT') if len(p) == 3: p[0].data = p[2].data p[0].TAC =",
"required\") return else: if symbol_table.add_identifier(p[1]) == False: print_error(\"Unable to add",
"if p[3].isLvalue == 1 and symbol_table.search_identifier(p[3].data) == False and p[3].data",
"DOT IDENTIFIER ''' parsed.append(p.slice) return def p_Index(p): '''Index : LSQUARE",
"0, [p[1]] + p[3].children, p[1].TAC) p[0].TAC.append_TAC(p[3].TAC) return def p_ExpressionBotList(p): '''ExpressionBotList",
"'']) p[0].TAC.add_line(['stack_push', '', '', '']) p[0].TAC.append_TAC(p[4].TAC) return def p_FunctionName(p): '''FunctionName",
"Expression ''' parsed.append(p.slice) p[0] = TreeNode('ExprSwitchCase', 0, 'INT') if len(p)",
"= TreeNode('ExprSwitchStmt', 0, 'INT') p[0].TAC.append_TAC(p[2].TAC) t1 = TreeNode('IDENTIFIER', gen('temp'), 'INT',",
"p[0] = p[5] var_list = symbol_table.make_var_list() three_addr_code = convert_tac(p[0].TAC) symbol_table.fill_next_use(three_addr_code)",
"l1, '', '']) # p[0].TAC.add_line([l2]) return def p_ReturnStmt(p): '''ReturnStmt :",
"Code() parsed = [] symbol_table = SymbolTable() var_list = []",
"SymbolTable\") return p[0].TAC.add_line([p[2], check_variable(p[1].children[i]), check_variable(p[3].children[i]), '']) else: print_error(\"Variable Declaration mismatch:",
"return def p_hex_lit(p): '''hex_lit : HEX_LIT ''' parsed.append(p.slice) p[0] =",
"''' parsed.append(p.slice) p[0] = TreeNode('rune_lit', p[1], 'RUNE') return def p_empty(p):",
"p_ShortVarDecl(p): '''ShortVarDecl : ExpressionList ASSIGN_OP ExpressionList | Expression ASSIGN_OP Expression",
"0, 'NONE') if hasattr(p[1], 'name') and p[1].name == 'IdentifierList': zero_val",
"if p.slice[1].type == 'IDENTIFIER': p[0] = TreeNode('IDENTIFIER', p[1], 'INT', 1)",
"'INT', 1) p[0] = TreeNode('IdentifierBotList', 0, 'None', 0, [node] +",
"ExprCaseClauseList ScopeEnd RCURLY ''' parsed.append(p.slice) if len(p) == 8: l1",
"'''FieldDecl : IdentifierList Type TagTop | IDENTIFIER Type TagTop '''",
"undefined\") return p[0].TAC.add_line([p[2].data, check_variable(p[1].children[i]), check_variable(p[3].children[i]), '']) else: print_error(\"Variable Declaration mismatch:",
"= 'PrintStrStmt' return def p_Declaration(p): '''Declaration : ConstDecl | TypeDecl",
"p[2].input_type != 'NONE': # array case # p[2].print_node() if symbol_table.add_identifier(p[1],",
"name and Imports for now p[0] = p[5] var_list =",
"IdentifierList EQ ExpressionList | IDENTIFIER Type EQ Expression | IdentifierList",
"name = symbol_table.search_function(TreeNode.data) if name == False: print_error(\"Variable \" +",
"'''BreakStmt : BREAK IDENTIFIER ''' parsed.append(p.slice) return def p_ContinueStmt(p): '''ContinueStmt",
"' + funcName + ' requires ' + str(temp) +",
"required\") return else: if symbol_table.search_identifier(p[1].data) == False and p[1].data not",
"| Tag ''' parsed.append(p.slice) return def p_Tag(p): '''Tag : string_lit",
"def p_elseTail(p): '''elseTail : IfStmt | Block ''' parsed.append(p.slice) p[0]",
"p[1], 'STRING') return def p_rune_lit(p): '''rune_lit : RUNE_LIT ''' parsed.append(p.slice)",
"| PRINTLN LROUND int_lit RROUND ''' if hasattr(p[3], 'name') and",
"IDENTIFIER COMMA IdentifierBotList ''' parsed.append(p.slice) node = TreeNode('IDENTIFIER', p[1], 'INT',",
"parsed.append(p.slice) p[0] = p[1] p[0].name = 'Signature' s = 'scope_'",
"parsed.append(p.slice) # Anonymous Function # Not implemented yet return def",
"p[1].TAC return def p_ExprSwitchCase(p): '''ExprSwitchCase : CASE ExpressionList | DEFAULT",
"p[0].TAC.add_line(['label', l1, '', '']) p[0].TAC.append_TAC(p[5].TAC) p[0].TAC.add_line(['label', l2, '', '']) return",
"SEMICOLON ''' parsed.append(p.slice) return def p_ConstSpec(p): '''ConstSpec : IDENTIFIER |",
"LROUND ConstSpecList RROUND | CONST ConstSpec ''' parsed.append(p.slice) return def",
"'IncDecStmt' return def p_ShortVarDecl(p): '''ShortVarDecl : ExpressionList ASSIGN_OP ExpressionList |",
"'INT', 0, [p[1]] + p[3].children, p[1].TAC) p[0].TAC.append_TAC(p[3].TAC) return def p_TypeDecl(p):",
"return def p_IfStmt(p): '''IfStmt : IF Expression Block | IF",
"| Assignment | ShortVarDecl | IncDecStmt ''' parsed.append(p.slice) p[0] =",
"to SymbolTable\") return p[0].TAC.append_TAC(p[3].TAC) p[0].TAC.append_TAC(p[1].TAC) p[0].TAC.add_line([p[2], check_variable(p[1]), check_variable(p[3]), '']) return",
"'''string_lit : STRING_LIT ''' parsed.append(p.slice) p[0] = TreeNode('string_lit', p[1], 'STRING')",
"len(p) == 4: l1 = gen('label') l2 = gen('label') p[0].TAC.add_line(['label',",
"+ str(l2) + \" value(s)\") elif p[1].name == 'Expression': if",
"p[3].input_type, p[3].children) if len(p) == 5: noOfParams = 0 for",
": empty | ExprCaseClauseList ExprCaseClause ''' parsed.append(p.slice) TAC1 = ThreeAddressCode()",
"Expression | Expression CARET Expression | Expression STAR Expression |",
"p[0].TAC.add_line(['goto', l1, '', '']) # p[0].TAC.add_line([l2]) return def p_ReturnStmt(p): '''ReturnStmt",
"[] symbol_table = SymbolTable() var_list = [] generated = {'temp':",
"p[0].TAC.add_line(['label', l1, '', '']) if len(p) == 6: l1 =",
"if l1 == l2: # for i in range(l1): #",
"('left','RETURN'), ('left','RROUND'), ('left','LROUND'), ('left', 'OR_OR'), ('left', 'AMP_AMP'), ('left', 'EQ_EQ', 'NOT_EQ','LT','LT_EQ','GT','GT_EQ'),",
"parsed.append(p.slice) return def p_TypeSpecTopList(p): '''TypeSpecTopList : TypeSpec | LROUND TypeSpecList",
"p[2] return def p_Result(p): '''Result : Parameters | Type '''",
"p[0].TAC.append_TAC(p[2].TAC) t1 = TreeNode('IDENTIFIER', gen('temp'), 'INT', 1) p[0].TAC.add_line(['=', check_variable(t1) ,",
"2: node = TreeNode('IDENTIFIER', p[1], 'INT', 1) p[0] = TreeNode('IdentifierBotList',",
"TreeNode('TopLevelDeclList', 0, 'INT', 0, [p[1]], p[1].TAC) return def p_TopLevelDecl(p): '''TopLevelDecl",
": IDENTIFIER Type ''' parsed.append(p.slice) return def p_Type(p): '''Type :",
"return name + '[' + TreeNode.children + ']' else: newNode",
"p[0].TAC.append_TAC(p[2].TAC) # p[1].print_node() func = check_variable(p[1]).split(\"_\") scope, funcName = \"_\".join(func[:2]),",
"is undefined\") return TreeNode.data else: return name else: newNode =",
"== 2: if p.slice[1].type == 'IDENTIFIER': p[0] = TreeNode('IDENTIFIER', p[1],",
"'', '']) p[0].TAC.append_TAC(p[5].TAC) p[0].TAC.add_line(['label', l2, '', '']) return def p_elseTail(p):",
"p[1].name == 'IdentifierList': zero_val = TreeNode('decimal_lit', 0, 'INT') # l1",
"'''int_lit : decimal_lit | octal_lit | hex_lit ''' parsed.append(p.slice) p[0]",
"p_TypeDecl(p): '''TypeDecl : TYPE TypeSpecTopList ''' parsed.append(p.slice) return def p_TypeSpecTopList(p):",
"empty ''' parsed.append(p.slice) if len(p) == 4: p[0] = TreeNode('StatementList',",
"'NONE': # array case # p[2].print_node() if symbol_table.add_identifier(p[1], size =",
"''' parsed.append(p.slice) p[0] = TreeNode('Assignment', 0, 'INT') if p[1].name ==",
"| RS_EQ | AMP_EQ | AND_OR_EQ ''' parsed.append(p.slice) p[0] =",
"[]: return name else: return name + '[' + TreeNode.children",
"return def p_decimal_lit(p): '''decimal_lit : DECIMAL_LIT ''' parsed.append(p.slice) p[0] =",
"child.input_type) symbol_table.add_var(newNode, s) # symbol_table.print_symbol_table() if len(p) == 2: p[0].input_type",
"0 for f in symbol_table.symbol_table[symbol_table.current_scope]['functions']: if f.name == p[2].data: noOfParams",
"'']) p[0].TAC.append_TAC(p[2].TAC) p[0].TAC.add_line(['goto', l1, '', '']) # p[0].TAC.add_line([l2]) return def",
"def p_VarSpecList(p): '''VarSpecList : empty | VarSpecList VarSpec SEMICOLON '''",
"expr_list = TreeNode('Expr_List', 0, 'NONE', 0, [zero_val] * l1) #",
"'', '']) return def p_ExprCaseClauseList(p): '''ExprCaseClauseList : empty | ExprCaseClauseList",
"| float_lit | string_lit | rune_lit ''' parsed.append(p.slice) p[0] =",
"| IdentifierList EQ ExpressionList | IDENTIFIER Type EQ Expression |",
"'''ReturnStmt : RETURN | RETURN Expression | RETURN ExpressionList '''",
"p[0] = TreeNode('decimal_lit', p[1], 'INT') return def p_octal_lit(p): '''octal_lit :",
"= 'Parameters' return def p_ParameterList(p): '''ParameterList : ParameterDecl | ParameterList",
"p[0].TAC.append_TAC(p[1].TAC) # if l1 == l2: # for i in",
"len(p) == 4: node = TreeNode('IDENTIFIER', p[1], 'INT', 1) p[0]",
"EQ Expression | IDENTIFIER Type EQ Expression | IdentifierList Type",
"OR_EQ | CARET_EQ | STAR_EQ | DIVIDE_EQ | MODULO_EQ |",
"p[0] = TreeNode('TopLevelDeclList', 0, 'INT', 0, [p[1]] + p[3].children, p[1].TAC)",
"p[0] = TreeNode('TopLevelDeclList', 0, 'INT', 0, [p[1]], p[1].TAC) return def",
"| DIVIDE_EQ | MODULO_EQ | LS_EQ | RS_EQ | AMP_EQ",
"TAC1 = p[1].data TAC2 = p[2].data p[0] = TreeNode('ExprCaseClauseList', TAC1,",
"= TreeNode('IDENTIFIER', gen('temp'), 'INT', 1) p[0].TAC.append_TAC(p[1].TAC) p[0].TAC.append_TAC(p[2].TAC) # p[1].print_node() func",
"TreeNode.data not in generated['temp']: name = symbol_table.search_identifier(TreeNode.data) if name ==",
"p_ExprCaseClauseList(p): '''ExprCaseClauseList : empty | ExprCaseClauseList ExprCaseClause ''' parsed.append(p.slice) TAC1",
"l1, '', '']) p[0].TAC.append_TAC(p[5].TAC) p[0].TAC.add_line(['label', l2, '', '']) return def",
"and p[1].name == 'IdentifierList': zero_val = TreeNode('decimal_lit', 0, 'INT') #",
"convert_tac(p[0].TAC) symbol_table.fill_next_use(three_addr_code) assembly_code = generate_assembly(three_addr_code,var_list,symbol_table) # p[0].TAC.print_code() # three_addr_code.print_code() assembly_code.print_code()",
"0, 'None') p[0].TAC.add_line(['return', '', '', '']) if len(p) == 3:",
"in reversed(p[3].children): p[0].TAC.add_line(['getparam', p[4].data + '_' + child.data, '', ''])",
"== 6: l1 = gen('label') l2 = gen('label') p[0] =",
"Expression | Expression OR Expression | Expression CARET Expression |",
"symbol_table.add_identifier(child, s) newNode = SymbolTableNode(s + '_' + child.data, child.input_type)",
"1) p[0].data += 1 p[0].children += [node] else: p[0].data +=",
"\" + str(l2) + \" value(s)\") else: p[1] = TreeNode('IDENTIFIER',p[1],'INT',1)",
"reversed(p[3].children): p[0].TAC.add_line(['getparam', p[4].data + '_' + child.data, '', '']) p[0].TAC.add_line(['stack_push',",
"0, p[1].children + p[3].children, p[1].TAC) p[0].TAC.append_TAC(p[3].TAC) return def p_ParameterDecl(p): '''ParameterDecl",
"OCTAL_LIT ''' parsed.append(p.slice) p[0] = TreeNode('octal_lit', p[1], 'OCT') return def",
": DOT string_lit | IDENTIFIER string_lit | empty string_lit '''",
"into symbol table p[0] = TreeNode('VarSpec', 0, 'NONE') if hasattr(p[1],",
"p[5].children[i][0], p[5].children[i][1]]) p[0].TAC.add_line(['goto', l2, '', '']) for i in range(p[5].TAC.length()):",
"i in range(p[5].TAC.length()): if i in p[5].TAC.leaders[1:]: p[0].TAC.add_line(['goto', l2, '',",
"p[0].TAC.append_TAC(p[5].data) for i in range(len(p[5].children)): p[0].TAC.add_line(['ifgotoeq', check_variable(t1), p[5].children[i][0], p[5].children[i][1]]) p[0].TAC.add_line(['goto',",
"+ ' requires ' + str(temp) + ' parameters but",
"len(p) == 2: p[0] = p[1] elif len(p) == 3:",
"p_ParameterDecl(p): '''ParameterDecl : IdentifierList Type | IDENTIFIER Type | Type",
"= 'BasicLit' return def p_int_lit(p): '''int_lit : decimal_lit | octal_lit",
"| CONST ConstSpec ''' parsed.append(p.slice) return def p_ConstSpecList(p): '''ConstSpecList :",
"case # p[2].print_node() if symbol_table.add_identifier(p[1], size = p[2].data) == False:",
"RROUND | LROUND ExpressionList RROUND | LROUND Expression RROUND |",
"elif len(p) == 4: p[0] = TreeNode('IDENTIFIER', gen('temp'), 'INT', 1,",
"| IfStmt | SwitchStmt | ForStmt | BreakStmt | ContinueStmt",
"= 0 for f in symbol_table.symbol_table[symbol_table.current_scope]['functions']: if f.name == p[2].data:",
"p_ConstSpecList(p): '''ConstSpecList : empty | ConstSpecList ConstSpec SEMICOLON ''' parsed.append(p.slice)",
"i in range(l1): if p[1].children[i].isLvalue == 0: print_error(\"Lvalue required\") return",
"expr_list.children[i].data, '']) # else: # print_error(\"Variable Declaration mismatch: \" +",
"| CARET | STAR | AMP | LT_MINUS ''' parsed.append(p.slice)",
"p[0] = p[1] p[0].name = 'ParameterList' elif len(p) == 4:",
"+ '_' + child.data, '', '']) p[0].TAC.add_line(['stack_push', '', '', ''])",
"None: print str(sys.argv[1]) + \" :: You missed something at",
"return def p_ImportDecl(p): '''ImportDecl : IMPORT LROUND ImportSpecList RROUND |",
"= gen('label') l2 = gen('label') p[0].TAC.add_line(['label', l1, '', '']) p[0].TAC.append_TAC(p[2].TAC)",
"'']) for child in reversed(p[3].children): p[0].TAC.add_line(['getparam', p[4].data + '_' +",
"return def p_TypeDef(p): '''TypeDef : IDENTIFIER Type ''' parsed.append(p.slice) return",
"return TreeNode.data precedence = ( ('left','IDENTIFIER'), ('right','ASSIGN_OP'), ('left','COMMA'), ('left','LSQUARE'), ('left','RSQUARE'),",
"p[1], 'INT', 1) return def p_FunctionBody(p): '''FunctionBody : Block '''",
"parsed.append(p.slice) p[0] = p[1] p[0].name = 'Literal' return def p_BasicLit(p):",
"== 'IdentifierList': for node in p[1].children: p[0].data += 1 node.input_type",
"parsed.append(p.slice) if len(p) == 2: p[0] = TreeNode('ExpressionBotList', 0, 'INT',",
"def p_StatementList(p): '''StatementList : Statement SEMICOLON StatementList | empty '''",
"p[0] = p[1] p[0].name = 'Statement' return def p_PrintIntStmt(p): '''PrintIntStmt",
"check_variable(expr), '']) return def p_FunctionDecl(p): '''FunctionDecl : FUNC FunctionName Signature",
": FUNC FunctionName Signature | FUNC FunctionName Signature FunctionBody '''",
"logging import ply.lex as lex import ply.yacc as yacc import",
"TreeNode('Result', 1, 'None', 0, [p[1]]) else: p[0] = p[1] p[0].name",
"expr_list = p[3] # elif len(p) == 5: # expr_list",
"p[1], 'INT', 1) elif p[1].name == 'Operand': p[0] = p[1]",
"code import TreeNode from code import ThreeAddressCode from lexer import",
"''' parsed.append(p.slice) return def p_TagTop(p): '''TagTop : empty | Tag",
"ExpressionList RROUND | LROUND Expression RROUND | LROUND Type RROUND",
"== False: name = symbol_table.search_function(TreeNode.data) if name == False: print_error(\"Variable",
"l1 = len(p[1].children) # if len(p) == 3: # expr_list",
"SymbolTableNode import logging import ply.lex as lex import ply.yacc as",
"# expr = p[4] # p[0].TAC.append_TAC(p[4].TAC) # p[0].TAC.add_line(['=', check_variable(p[1]), check_variable(expr),",
"0: print_error(\"Lvalue required\") return else: if symbol_table.add_identifier(p[1]) == False: print_error(\"Unable",
"now return def p_ImportSpec(p): '''ImportSpec : DOT string_lit | IDENTIFIER",
"= 'ReturnStmt' p[0].TAC.add_line(['return', check_variable(p[2]), '', '']) return def p_BreakStmt(p): '''BreakStmt",
"p[2] p[0].name = 'Arguments' p[0].data = len(p[2].children) return def p_string_lit(p):",
"check_variable(p[1]), one_val.data]) else: p[0].TAC.add_line(['-', check_variable(p[1]), check_variable(p[1]), one_val.data]) else: print_error(\"Lvalue required\")",
"to SymbolTable\") return name = symbol_table.search_identifier(p[1].data) newNode = SymbolTableNode(name, p[1].input_type,size",
"p[0] = TreeNode('ExprSwitchCase', 0, 'INT') if len(p) == 3: p[0].data",
"\" is undefined\") return if p[3].children[i].isLvalue == 1 and symbol_table.search_identifier(p[3].children[i].data)",
"CARET | STAR | AMP | LT_MINUS ''' parsed.append(p.slice) p[0]",
"p[0].name = 'ReturnStmt' p[0].TAC.add_line(['return', check_variable(p[2]), '', '']) return def p_BreakStmt(p):",
"def p_BreakStmt(p): '''BreakStmt : BREAK IDENTIFIER ''' parsed.append(p.slice) return def",
"parsed.append(p.slice) p[0] = TreeNode('assign_op', p[1], 'OPERATOR') return def p_IfStmt(p): '''IfStmt",
"p[1].children + p[2].children, p[1].TAC) p[0].TAC.add_leader(p[0].TAC.length()) p[0].TAC.append_TAC(p[2].TAC) p[0].data.append_TAC(TAC2) else: p[0] =",
"= TreeNode('IfStmt', 0, 'INT') p[0].TAC.append_TAC(p[2].TAC) p[0].TAC.add_line(['ifgotoeq', check_variable(p[2]), '0', l1]) p[0].TAC.append_TAC(p[3].TAC)",
"2 values. first is the name for the variable, second",
"p[0].TAC.append_TAC(p[1].TAC) p[0].TAC.add_line(['label', l1, '', '']) # p[0].TAC.add_line(['ifgotoneq', p[1].children, p[1].children, l1])",
"+ \" :: You missed something at the end\" else:",
"LT_EQ Expression | Expression GT Expression | Expression GT_EQ Expression",
"len(p) == 5: noOfParams = 0 for f in symbol_table.symbol_table[symbol_table.current_scope]['functions']:",
"3: if hasattr(p[1], 'name') and p[1].name == 'IdentifierList': for node",
"1) elif p[1].name == 'Operand': p[0] = p[1] elif len(p)",
"False: print('Input file ' + input_file + ' does not",
"def p_Index(p): '''Index : LSQUARE Expression RSQUARE ''' parsed.append(p.slice) p[0]",
"def p_rune_lit(p): '''rune_lit : RUNE_LIT ''' parsed.append(p.slice) p[0] = TreeNode('rune_lit',",
"str(p[2].data) + ' supplied') p[0].TAC.add_line(['call', check_variable(p[1]), str(p[2].data), '']) p[0].TAC.add_line(['return_value', check_variable(p[0]),",
"= TreeNode('FunctionDecl', 0, 'INT') # print symbol_table.current_scope # p[4].TAC.print_code() symbol_table.add_function(p[2].data,",
"'Type': p[0] = TreeNode('Result', 1, 'None', 0, [p[1]]) else: p[0]",
"p_ExpressionBotList(p): '''ExpressionBotList : Expression COMMA ExpressionBotList | Expression ''' parsed.append(p.slice)",
"def p_FunctionLit(p): '''FunctionLit : FUNC Signature FunctionBody ''' parsed.append(p.slice) #",
"p_Parameters(p): '''Parameters : LROUND RROUND | LROUND ParameterList RROUND '''",
"return def p_ImportSpec(p): '''ImportSpec : DOT string_lit | IDENTIFIER string_lit",
"p[1].TAC) p[0].TAC.add_leader(p[0].TAC.length()) p[0].TAC.append_TAC(p[2].TAC) p[0].data.append_TAC(TAC2) else: p[0] = TreeNode('ExprCaseClauseList', TAC1, 'INT')",
"CASE ExpressionList | DEFAULT | CASE Expression ''' parsed.append(p.slice) p[0]",
"p[0].TAC.add_line(['goto', l1, '', '']) p[0].TAC.add_line(['label', l2, '', '']) if len(p)",
"symbol_table.search_identifier(p[1].data) newNode = SymbolTableNode(name, p[1].input_type,size = p[2].data) symbol_table.add_var(newNode) p[0] =",
"str(l2) + \" value(s)\") elif p[1].name == 'Expression': if p[1].isLvalue",
"StandardTypes | LROUND Type RROUND ''' parsed.append(p.slice) if len(p) ==",
"required\") p[0].name = 'IncDecStmt' return def p_ShortVarDecl(p): '''ShortVarDecl : ExpressionList",
"GT_EQ Expression | Expression PLUS Expression | Expression MINUS Expression",
"parsed.append(p.slice) if len(p) == 8: l1 = gen('label') l2 =",
"STAR | AMP | LT_MINUS ''' parsed.append(p.slice) p[0] = TreeNode('unary_op',",
"check_variable(p[1]), check_variable(p[3]), '']) return def p_assign_op(p): '''assign_op : EQ |",
"symbol_table.current_scope + '_' + gen('str_list') parametersNode = SymbolTableNode(p[3].data, p[3].input_type) newNode",
"p[0] = p[1] p[0].name = 'TypeLit' return def p_PointerType(p): '''PointerType",
"if len(p) == 3: p[0] = TreeNode('Parameters', 0, 'None') else:",
"Selector | PrimaryExpr Index | PrimaryExpr Arguments ''' parsed.append(p.slice) if",
"return def p_Signature(p): '''Signature : Parameters | Parameters Result '''",
"!= p[2].data: print_error('Function ' + funcName + ' requires '",
"'TypeLit' return def p_PointerType(p): '''PointerType : STAR Type ''' parsed.append(p.slice)",
"p[0] = TreeNode('Parameters', 0, 'None') else: p[0] = p[2] p[0].name",
"return def p_ParameterList(p): '''ParameterList : ParameterDecl | ParameterList COMMA ParameterDecl",
"parsed.append(p.slice) return def p_ConstSpec(p): '''ConstSpec : IDENTIFIER | IdentifierList |",
"VAR VarSpecTopList ''' parsed.append(p.slice) p[0] = p[2] p[0].name = 'VarDecl'",
": PRINTLN LROUND IDENTIFIER RROUND | PRINTLN LROUND int_lit RROUND",
"Expression | Expression NOT_EQ Expression | Expression LT Expression |",
"assign_op Expression ''' parsed.append(p.slice) p[0] = TreeNode('Assignment', 0, 'INT') if",
"'']) p[0].TAC.add_line(['label', l2, '', '']) if len(p) == 3: l1",
"FLOAT_LIT ''' parsed.append(p.slice) p[0] = TreeNode('float_lit', p[1], 'FLOAT') return def",
"[parametersNode]) symbol_table.add_var(newNode) p[0].TAC.add_line(['print_str', name, '', '']) p[0].name = 'PrintStrStmt' return",
"TreeNode('IncDecStmt', '1', 'INT') p[0] = p[1] if p[1].isLvalue == 1:",
"p[2] p[0].name = 'Index' return def p_Arguments(p): '''Arguments : LROUND",
"'''ExprCaseClauseList : empty | ExprCaseClauseList ExprCaseClause ''' parsed.append(p.slice) TAC1 =",
"== 'ExpressionList': l1 = len(p[1].children) l2 = len(p[3].children) p[0].TAC.append_TAC(p[3].TAC) p[0].TAC.append_TAC(p[1].TAC)",
"p[0] = TreeNode('ForStmt', 0, 'INT') if len(p) == 4: l1",
"p[0].TAC.append_TAC(p[3].TAC) # p[0].TAC.add_line(['=', check_variable(p[1]), check_variable(expr), '']) # elif len(p) ==",
"p_string_lit(p): '''string_lit : STRING_LIT ''' parsed.append(p.slice) p[0] = TreeNode('string_lit', p[1],",
"' parameters but ' + str(p[2].data) + ' supplied') p[0].TAC.add_line(['call',",
"0: print_error(\"Lvalue required\") return else: if symbol_table.search_identifier(p[1].children[i].data) == False and",
"== 'Arguments': p[0] = TreeNode('IDENTIFIER', gen('temp'), 'INT', 1) p[0].TAC.append_TAC(p[1].TAC) p[0].TAC.append_TAC(p[2].TAC)",
"return def p_ReturnStmt(p): '''ReturnStmt : RETURN | RETURN Expression |",
"TreeNode('decimal_lit', p[1], 'INT') return def p_octal_lit(p): '''octal_lit : OCTAL_LIT '''",
"p_IncDecStmt(p): '''IncDecStmt : Expression PLUS_PLUS | Expression MINUS_MINUS ''' parsed.append(p.slice)",
"len(p[2].children) return def p_string_lit(p): '''string_lit : STRING_LIT ''' parsed.append(p.slice) p[0]",
"len(p) == 6: l1 = gen('label') l2 = gen('label') p[0]",
"symbol_table.symbol_table[scope]['functions']: if f.name == funcName: temp = len(f.parameters) # p[2].print_node()",
"Logger logging.basicConfig( level = logging.DEBUG, filename = \"parselog.txt\", filemode =",
"empty | Tag ''' parsed.append(p.slice) return def p_Tag(p): '''Tag :",
"| FUNC FunctionName Signature FunctionBody ''' parsed.append(p.slice) # symbol_table.print_symbol_table() p[0]",
"PrimaryExpr Arguments ''' parsed.append(p.slice) if len(p) == 2: if p.slice[1].type",
"3: p[0] = TreeNode('Arguments', 0, 'None') if len(p) == 4:",
"name == False: name = symbol_table.search_function(TreeNode.data) if name == False:",
"'', '']) p[0].TAC.append_TAC(p[2].TAC) p[0].TAC.add_line(['goto', l1, '', '']) # p[0].TAC.add_line([l2]) return",
"0, [p[2]], p[2].TAC) if p[2].name == 'ExpressionList': p[0] = p[2]",
"p[0] = TreeNode('ReturnStmt', 0, 'None') p[0].TAC.add_line(['return', '', '', '']) if",
"+ str(len(generated['scope'])) symbol_table.new_scope(s) for child in p[1].children: symbol_table.add_identifier(child, s) newNode",
"code import Code from codegen import generate_assembly three_addr_code = ThreeAddressCode()",
"' requires ' + str(temp) + ' parameters but '",
"Expression COMMA ExpressionBotList | Expression ''' parsed.append(p.slice) if len(p) ==",
"now return def p_TopLevelDeclList(p): '''TopLevelDeclList : TopLevelDecl SEMICOLON TopLevelDeclList |",
"Expression GT_EQ Expression | Expression PLUS Expression | Expression MINUS",
"ImportDeclList TopLevelDeclList ''' parsed.append(p.slice) # TODO: Ignoring package name and",
"p[0].TAC.add_line(['putparam', check_variable(child), '', '']) if temp != p[2].data: print_error('Function '",
"Type COMMA Expression RROUND ''' # print p.slice parsed.append(p.slice) if",
"float_lit | string_lit | rune_lit ''' parsed.append(p.slice) p[0] = p[1]",
"# TODO: Ignoring Imports for now return def p_TopLevelDeclList(p): '''TopLevelDeclList",
"p[0].TAC.add_line(['=', check_variable(p[1]), check_variable(expr), '']) # elif len(p) == 5: #",
"p[0].TAC.append_TAC(p[2].TAC) p[0].TAC.add_line(['ifgotoeq',check_variable(p[2]), '0', l2]) p[0].TAC.append_TAC(p[3].TAC) p[0].TAC.add_line(['goto', l1, '', '']) p[0].TAC.add_line(['label',",
"parsed.append(p.slice) p[0] = TreeNode('float_lit', p[1], 'FLOAT') return def p_FunctionLit(p): '''FunctionLit",
"| ContinueStmt | GotoStmt | PrintIntStmt | PrintStrStmt ''' parsed.append(p.slice)",
"p[3], 'INT', 1, []) p[0].TAC.add_line(['print_int', check_variable(p[0]), '', '']) p[0].name =",
"return def p_unary_op(p): '''unary_op : PLUS | MINUS | NOT",
"if p[1].name == 'ExpressionList': l1 = len(p[1].children) l2 = len(p[3].children)",
"check_variable(p[3]), '']) return def p_Assignment(p): '''Assignment : ExpressionList assign_op ExpressionList",
"| PointerType ''' parsed.append(p.slice) p[0] = p[1] p[0].name = 'TypeLit'",
": OCTAL_LIT ''' parsed.append(p.slice) p[0] = TreeNode('octal_lit', p[1], 'OCT') return",
": empty | TypeSpecList TypeSpec SEMICOLON ''' parsed.append(p.slice) return def",
"p_float_lit(p): '''float_lit : FLOAT_LIT ''' parsed.append(p.slice) p[0] = TreeNode('float_lit', p[1],",
"from symbol_table import SymbolTable from symbol_table import SymbolTableNode import logging",
"== 4: # expr = p[3] # p[0].TAC.append_TAC(p[3].TAC) # p[0].TAC.add_line(['=',",
"= TreeNode('string_lit', p[1], 'STRING') return def p_rune_lit(p): '''rune_lit : RUNE_LIT",
"p[2].data, p[4].data) return def p_ArrayLength(p): '''ArrayLength : Expression ''' parsed.append(p.slice)",
"ParameterDecl ''' parsed.append(p.slice) if len(p) == 2: p[0] = p[1]",
"gen('label') p[0].TAC.add_line(['label', l1, '', '']) p[0].TAC.append_TAC(p[2].TAC) p[0].TAC.add_line(['ifgotoeq',check_variable(p[2]), '0', l2]) p[0].TAC.append_TAC(p[3].TAC)",
"supplied') p[0].TAC.add_line(['call', check_variable(p[1]), str(p[2].data), '']) p[0].TAC.add_line(['return_value', check_variable(p[0]), '', '']) p[0].name",
"p[3] name = symbol_table.current_scope + '_' + gen('str_list') parametersNode =",
"return def p_FunctionDecl(p): '''FunctionDecl : FUNC FunctionName Signature | FUNC",
"TreeNode('ScopeStart', symbol_table.current_scope, 'None') return def p_ScopeEnd(p): '''ScopeEnd : empty '''",
"if p[1].children[i].isLvalue == 0: print_error(\"Lvalue required\") return else: if symbol_table.add_identifier(p[1].children[i])",
"def p_SourceFile(p): '''SourceFile : PACKAGE IDENTIFIER SEMICOLON ImportDeclList TopLevelDeclList '''",
": PREDEFINED_TYPES ''' parsed.append(p.slice) p[0] = TreeNode('StandardTypes', p[1], 'NONE') return",
"TreeNode('assign_op', p[1], 'OPERATOR') return def p_IfStmt(p): '''IfStmt : IF Expression",
"3: TAC1 = p[1].data TAC2 = p[2].data p[0] = TreeNode('ExprCaseClauseList',",
"p[1].children + p[3].children, p[1].TAC) p[0].TAC.append_TAC(p[3].TAC) return def p_ParameterDecl(p): '''ParameterDecl :",
"p[2].data: noOfParams = len(f.parameters) p[0].TAC.add_line(['func', check_variable(p[2]), str(noOfParams), '']) for child",
"p[1].TAC) p[0].TAC.append_TAC(p[3].TAC) else: p[0] = TreeNode('StatementList', 0, 'INT') return def",
"generated.keys(): generated[s] = [] temp = s + '_' +",
"VarSpecTopList ''' parsed.append(p.slice) p[0] = p[2] p[0].name = 'VarDecl' return",
"p[0].TAC.append_TAC(p[3].TAC) return def p_ExpressionBotList(p): '''ExpressionBotList : Expression COMMA ExpressionBotList |",
"+ \" is undefined\") return if p[3].isLvalue == 1 and",
"| GotoStmt | PrintIntStmt | PrintStrStmt ''' parsed.append(p.slice) p[0] =",
"Tag ''' parsed.append(p.slice) return def p_Tag(p): '''Tag : string_lit '''",
"symbol_table.print_symbol_table() if len(p) == 2: p[0].input_type = TreeNode('Result', 0, 'None')",
"Type | Type ''' parsed.append(p.slice) p[0] = TreeNode('ParameterDecl', 0, 'None')",
"''' parsed.append(p.slice) p[0] = p[1] p[0].name = 'SimpleStmt' return def",
"SymbolTable\") return p[0].TAC.append_TAC(p[3].TAC) p[0].TAC.append_TAC(p[1].TAC) p[0].TAC.add_line([p[2], check_variable(p[1]), check_variable(p[3]), '']) return def",
"parsed.append(p.slice) return def p_Index(p): '''Index : LSQUARE Expression RSQUARE '''",
"= 'VarDecl' return def p_VarSpecTopList(p): '''VarSpecTopList : VarSpec | LROUND",
"= TreeNode('ForStmt', 0, 'INT') if len(p) == 4: l1 =",
"'']) p[0].TAC.add_line(['label', l1, '', '']) p[0].TAC.append_TAC(p[5].TAC) p[0].TAC.add_line(['label', l2, '', ''])",
"EQ_EQ Expression | Expression NOT_EQ Expression | Expression LT Expression",
"p[3].children, p[3].TAC) return def p_ExpressionList(p): '''ExpressionList : Expression COMMA ExpressionBotList",
"len(p) == 2: p[0] = p[1] else: p[0] = p[2]",
"'']) return def p_BreakStmt(p): '''BreakStmt : BREAK IDENTIFIER ''' parsed.append(p.slice)",
"p[1].TAC) p[0].TAC.append_TAC(p[3].TAC) return def p_ParameterDecl(p): '''ParameterDecl : IdentifierList Type |",
"('left','LCURLY'), ('left','RCURLY'), ('left','DDD'), ('left','DOT'), ('left','SEMICOLON'), ('left','COLON'), ('left','SINGLE_QUOTES'), ('left','DOUBLE_QUOTES'), ('left','DECIMAL_LIT'), ('left','OCTAL_LIT'),",
"p[0].TAC = p[2].TAC return def p_ForStmt(p): '''ForStmt : FOR Expression",
"p[1], 'FLOAT') return def p_FunctionLit(p): '''FunctionLit : FUNC Signature FunctionBody",
"= TreeNode('Arguments', 0, 'None') if len(p) == 4: if p[2].name",
"Declaration mismatch: \" + str(l1) + \" identifier(s) but \"",
"if len(p) == 6: l1 = gen('label') l2 = gen('label')",
"UnaryExpr ''' parsed.append(p.slice) if len(p) == 2: p[0] = p[1]",
"from code import ThreeAddressCode from lexer import tokens from random",
"PRINTLN LROUND int_lit RROUND ''' if hasattr(p[3], 'name') and p[3].name",
"'INT', 1) p[0].TAC.append_TAC(p[1].TAC) p[0].TAC.append_TAC(p[2].TAC) # p[1].print_node() func = check_variable(p[1]).split(\"_\") scope,",
"l1]) p[0].TAC.append_TAC(p[3].TAC) p[0].TAC.add_line(['label', l1, '', '']) if len(p) == 6:",
"| LROUND Type RROUND ''' parsed.append(p.slice) if len(p) == 2:",
"'None') return def p_ScopeEnd(p): '''ScopeEnd : empty ''' parsed.append(p.slice) symbol_table.end_scope()",
"l1 = gen('label') p[0] = TreeNode('IfStmt', 0, 'INT') p[0].TAC.append_TAC(p[2].TAC) p[0].TAC.add_line(['ifgotoeq',",
"for i in range(len(p[5].children)): p[0].TAC.add_line(['ifgotoeq', check_variable(t1), p[5].children[i][0], p[5].children[i][1]]) p[0].TAC.add_line(['goto', l2,",
"def p_PrintIntStmt(p): '''PrintIntStmt : PRINTLN LROUND IDENTIFIER RROUND | PRINTLN",
"return def p_PrimaryExpr(p): '''PrimaryExpr : Operand | IDENTIFIER | PrimaryExpr",
"== 8: l1 = gen('label') l2 = gen('label') p[0] =",
"symbol_table.symbol_table[symbol_table.current_scope]['functions']: if f.name == p[2].data: noOfParams = len(f.parameters) p[0].TAC.add_line(['func', check_variable(p[2]),",
"''' parsed.append(p.slice) p[0] = p[1] p[0].name = 'Statement' return def",
": ArrayType | StructType | FunctionType | PointerType ''' parsed.append(p.slice)",
"'None') if len(p) == 4: if p[2].name == 'Expression': p[0]",
"'''TypeDecl : TYPE TypeSpecTopList ''' parsed.append(p.slice) return def p_TypeSpecTopList(p): '''TypeSpecTopList",
"parsed.append(p.slice) p[0] = TreeNode('rune_lit', p[1], 'RUNE') return def p_empty(p): 'empty",
"| IdentifierList Type EQ ExpressionList ''' parsed.append(p.slice) return def p_IdentifierList(p):",
"check_variable(p[1]), check_variable(p[1]), one_val.data]) else: p[0].TAC.add_line(['-', check_variable(p[1]), check_variable(p[1]), one_val.data]) else: print_error(\"Lvalue",
"== 'Operand': p[0] = p[1] elif len(p) == 3: if",
"= \"parselog.txt\", filemode = \"w\", format = \"%(filename)10s:%(lineno)4d:%(message)s\" ) log",
"p if p == None: print str(sys.argv[1]) + \" ::",
"COMMA ExpressionBotList ''' parsed.append(p.slice) p[0] = TreeNode('ExpressionList', 0, 'INT', 0,",
"IdentifierList Type TagTop | IDENTIFIER Type TagTop ''' parsed.append(p.slice) return",
"p[2].children: p[0].TAC.add_line(['putparam', check_variable(child), '', '']) if temp != p[2].data: print_error('Function",
"| FunctionDecl ''' parsed.append(p.slice) p[0] = p[1] return def p_ImportDecl(p):",
"= \"w\", format = \"%(filename)10s:%(lineno)4d:%(message)s\" ) log = logging.getLogger() yacc.yacc(debug=True,",
"PrintStrStmt ''' parsed.append(p.slice) p[0] = p[1] p[0].name = 'Statement' return",
"4: p[0] = TreeNode('StatementList', 0, 'INT', 0, [p[1].data] + p[3].children,",
"+ '_' + gen('str_list') parametersNode = SymbolTableNode(p[3].data, p[3].input_type) newNode =",
"p[0] = p[1] else: p[0] = p[2] p[0].name = 'Type'",
"parsed.append(p.slice) return def p_FieldDecl(p): '''FieldDecl : IdentifierList Type TagTop |",
"p_FunctionType(p): '''FunctionType : FUNC Signature ''' parsed.append(p.slice) return def p_Signature(p):",
"p_ConstSpec(p): '''ConstSpec : IDENTIFIER | IdentifierList | IDENTIFIER EQ Expression",
"\" + p[3].children[i].data + \" is undefined\") return p[0].TAC.add_line([p[2].data, check_variable(p[1].children[i]),",
"# expr = p[3] # p[0].TAC.append_TAC(p[3].TAC) # p[0].TAC.add_line(['=', check_variable(p[1]), check_variable(expr),",
"''' parsed.append(p.slice) p[0] = TreeNode('hex_lit', p[1], 'HEX') return def p_float_lit(p):",
"check_variable(p[2]), '']) p[0].name = 'UnaryExpr' return def p_unary_op(p): '''unary_op :",
"= 'Declaration' return def p_ConstDecl(p): '''ConstDecl : CONST LROUND ConstSpecList",
"if len(p) == 3: p[0] = TreeNode('Arguments', 0, 'None') if",
"0, 'NONE', 0, [zero_val] * l1) # elif len(p) ==",
"ExprSwitchCase COLON StatementList ''' parsed.append(p.slice) l1 = gen('label') p[0] =",
"debuglog=log) input_file = sys.argv[1] import os if os.path.isfile(input_file) is False:",
"symbol_table import SymbolTable from symbol_table import SymbolTableNode import logging import",
"'']) return def p_FunctionDecl(p): '''FunctionDecl : FUNC FunctionName Signature |",
"'INT') if len(p) == 4: l1 = gen('label') l2 =",
"AND_OR Expression ''' parsed.append(p.slice) if len(p) == 2: p[0] =",
"'INT', 0, [], p[1].TAC) return def p_ExprSwitchStmt(p): '''ExprSwitchStmt : SWITCH",
"p[0].TAC.append_TAC(p[3].TAC) p[0].TAC.append_TAC(p[1].TAC) if l1 == l2: for i in range(l1):",
"False: print_error(\"Unable to add to SymbolTable\") return name = symbol_table.search_identifier(p[1].data)",
"p_ExprCaseClause(p): '''ExprCaseClause : ExprSwitchCase COLON StatementList ''' parsed.append(p.slice) l1 =",
"print_error(\"Variable \" + p[3].data + \" is undefined\") return #",
"p_ArrayLength(p): '''ArrayLength : Expression ''' parsed.append(p.slice) p[0] = p[1] p[0].name",
"+ \"! ***\" sys.exit(1) def check_variable(TreeNode): # return 2 values.",
"'AMP_AMP'), ('left', 'EQ_EQ', 'NOT_EQ','LT','LT_EQ','GT','GT_EQ'), ('left', 'PLUS', 'MINUS','OR','CARET'), ('left', 'STAR', 'DIVIDE','MODULO','AMP','AND_OR','LS','RS'),",
"'INT', 0, [p[1]] + p[3].children, p[1].TAC) p[0].TAC.append_TAC(p[3].TAC) return def p_ExpressionBotList(p):",
"precedence = ( ('left','IDENTIFIER'), ('right','ASSIGN_OP'), ('left','COMMA'), ('left','LSQUARE'), ('left','RSQUARE'), ('left','LCURLY'), ('left','RCURLY'),",
"p[0] = TreeNode('ShortVarDecl', 0, 'INT') if p[1].name == 'ExpressionList': l1",
"== 2: p[0].input_type = TreeNode('Result', 0, 'None') else: p[0].input_type =",
"Ignoring Imports for now return def p_ImportSpecList(p): '''ImportSpecList : ImportSpec",
"HEX_LIT ''' parsed.append(p.slice) p[0] = TreeNode('hex_lit', p[1], 'HEX') return def",
"= 'Result' return def p_Parameters(p): '''Parameters : LROUND RROUND |",
"p[1] else: p[0] = p[2] p[0].name = 'Operand' return def",
"p[0].TAC.append_TAC(p[1].TAC) p[0].TAC.append_TAC(p[2].TAC) # p[1].print_node() func = check_variable(p[1]).split(\"_\") scope, funcName =",
"# elif len(p) == 4: # expr_list = p[3] #",
"len(p) == 4: if p[3] != None: p[0] = TreeNode('TopLevelDeclList',",
"IncDecStmt ''' parsed.append(p.slice) p[0] = p[1] p[0].name = 'SimpleStmt' return",
"'label': [], 'str_list': []} def gen(s): if s not in",
"Expression OR_OR Expression | Expression AMP_AMP Expression | Expression EQ_EQ",
"p[1].TAC) p[0].TAC.append_TAC(p[3].TAC) return def p_TypeDecl(p): '''TypeDecl : TYPE TypeSpecTopList '''",
"check_variable(child), '', '']) if temp != p[2].data: print_error('Function ' +",
"Ignoring Imports for now return def p_TopLevelDeclList(p): '''TopLevelDeclList : TopLevelDecl",
"[node]) elif len(p) == 4: node = TreeNode('IDENTIFIER', p[1], 'INT',",
"def p_TypeLit(p): '''TypeLit : ArrayType | StructType | FunctionType |",
"SimpleStmt SEMICOLON Expression LCURLY ScopeStart ExprCaseClauseList ScopeEnd RCURLY | SWITCH",
"func = check_variable(p[1]).split(\"_\") scope, funcName = \"_\".join(func[:2]), \"_\".join(func[2:]) temp =",
"'', '']) p[0].TAC.add_line(['label', l1, '', '']) p[0].TAC.append_TAC(p[5].TAC) p[0].TAC.add_line(['label', l2, '',",
"0, 'INT') p[0].TAC.append_TAC(p[2].TAC) t1 = TreeNode('IDENTIFIER', gen('temp'), 'INT', 1) p[0].TAC.add_line(['=',",
"= 'UnaryExpr' return def p_unary_op(p): '''unary_op : PLUS | MINUS",
"'']) return def p_assign_op(p): '''assign_op : EQ | PLUS_EQ |",
"TAC1, 'INT', 0, p[1].children + p[2].children, p[1].TAC) p[0].TAC.add_leader(p[0].TAC.length()) p[0].TAC.append_TAC(p[2].TAC) p[0].data.append_TAC(TAC2)",
"''' parsed.append(p.slice) if len(p) == 2: if p.slice[1].type == 'IDENTIFIER':",
": empty | VarSpecList VarSpec SEMICOLON ''' return def p_VarSpec(p):",
"| RETURN Expression | RETURN ExpressionList ''' parsed.append(p.slice) if len(p)",
"''' parsed.append(p.slice) return def p_ContinueStmt(p): '''ContinueStmt : CONTINUE IDENTIFIER '''",
"parsed.append(p.slice) if len(p) == 2: p[0] = p[1] p[0].name =",
"| STAR | AMP | LT_MINUS ''' parsed.append(p.slice) p[0] =",
"RETURN Expression | RETURN ExpressionList ''' parsed.append(p.slice) if len(p) ==",
"SWITCH SimpleStmt SEMICOLON Expression LCURLY ScopeStart ExprCaseClauseList ScopeEnd RCURLY |",
"| Expression MINUS_MINUS ''' parsed.append(p.slice) one_val = TreeNode('IncDecStmt', '1', 'INT')",
"else: if symbol_table.add_identifier(p[1].children[i]) == False: print_error(\"Unable to add to SymbolTable\")",
"check_variable(p[2]), '', '']) return def p_BreakStmt(p): '''BreakStmt : BREAK IDENTIFIER",
"return def p_TypeSpec(p): '''TypeSpec : AliasDecl | TypeDef ''' parsed.append(p.slice)",
"yacc import sys from codegen import convert_tac from code import",
"p[1] return def p_ImportDecl(p): '''ImportDecl : IMPORT LROUND ImportSpecList RROUND",
"'INT', 1, p[2].data) elif p[2].name == 'Arguments': p[0] = TreeNode('IDENTIFIER',",
"def p_ScopeStart(p): '''ScopeStart : empty ''' parsed.append(p.slice) symbol_table.add_scope(gen('scope')) p[0] =",
"return def p_UnaryExpr(p): '''UnaryExpr : PrimaryExpr | unary_op UnaryExpr '''",
"| PrimaryExpr Selector | PrimaryExpr Index | PrimaryExpr Arguments '''",
"= TreeNode('Result', 0, 'None') else: p[0].input_type = p[2] return def",
"filename = \"parselog.txt\", filemode = \"w\", format = \"%(filename)10s:%(lineno)4d:%(message)s\" )",
"''' parsed.append(p.slice) if len(p) == 4: l1 = gen('label') p[0]",
"Type TagTop | IDENTIFIER Type TagTop ''' parsed.append(p.slice) return def",
"p[4] # p[0].TAC.append_TAC(p[4].TAC) # p[0].TAC.add_line(['=', check_variable(p[1]), check_variable(expr), '']) return def",
"str(p.lineno) # Standard Logger logging.basicConfig( level = logging.DEBUG, filename =",
"= SymbolTable() var_list = [] generated = {'temp': [], 'scope':",
"= p[1] p[0].name = 'FunctionBody' return def p_SimpleStmt(p): '''SimpleStmt :",
"return p[0].TAC.add_line([p[2].data, check_variable(p[1].children[i]), check_variable(p[3].children[i]), '']) else: print_error(\"Variable Declaration mismatch: \"",
"'']) for i in range(p[5].TAC.length()): if i in p[5].TAC.leaders[1:]: p[0].TAC.add_line(['goto',",
"p[2] == '++': p[0].TAC.add_line(['+', check_variable(p[1]), check_variable(p[1]), one_val.data]) else: p[0].TAC.add_line(['-', check_variable(p[1]),",
"return def p_IdentifierList(p): '''IdentifierList : IDENTIFIER COMMA IdentifierBotList ''' parsed.append(p.slice)",
"| Type ''' parsed.append(p.slice) p[0] = TreeNode('ParameterDecl', 0, 'None') if",
"if p[2].name == 'Expression': p[0] = p[2] p[0].name = 'ReturnStmt'",
"'Literal' return def p_BasicLit(p): '''BasicLit : int_lit | float_lit |",
"p[3].children, p[1].TAC) p[0].TAC.append_TAC(p[3].TAC) return def p_ParameterDecl(p): '''ParameterDecl : IdentifierList Type",
"0, 'NONE') # if len(p) == 4: # expr =",
"p[2].data) elif p[2].name == 'Arguments': p[0] = TreeNode('IDENTIFIER', gen('temp'), 'INT',",
": Expression ''' parsed.append(p.slice) p[0] = p[1] p[0].name = 'ArrayLength'",
"def p_ArrayLength(p): '''ArrayLength : Expression ''' parsed.append(p.slice) p[0] = p[1]",
"ply.yacc as yacc import sys from codegen import convert_tac from",
"name else: return name + '[' + TreeNode.children + ']'",
"== 1: if TreeNode.data not in generated['temp']: name = symbol_table.search_identifier(TreeNode.data)",
"== 4: p[0] = TreeNode('ParameterList', p[1].data + p[3].data, 'None', 0,",
"'NONE') if hasattr(p[1], 'name') and p[1].name == 'IdentifierList': zero_val =",
"| MODULO_EQ | LS_EQ | RS_EQ | AMP_EQ | AND_OR_EQ",
"TreeNode('IfStmt', 0, 'INT') p[0].TAC.append_TAC(p[2].TAC) p[0].TAC.add_line(['ifgotoeq', check_variable(p[2]), '0', l1]) p[0].TAC.append_TAC(p[3].TAC) p[0].TAC.add_line(['goto',",
"ExprSwitchStmt ''' parsed.append(p.slice) p[0] = TreeNode('SwitchStmt', 0, 'INT', 0, [],",
"three_addr_code = ThreeAddressCode() assembly_code = Code() parsed = [] symbol_table",
"in range(l1): # p[0].TAC.add_line(['=', p[1].children[i], expr_list.children[i].data, '']) # else: #",
"import TreeNode from code import ThreeAddressCode from lexer import tokens",
"0, 'INT', 0, [p[1]] + p[3].children, p[1].TAC) p[0].TAC.append_TAC(p[3].TAC) else: p[0]",
"| SWITCH Expression LCURLY ScopeStart ExprCaseClauseList ScopeEnd RCURLY ''' parsed.append(p.slice)",
"FieldDeclList FieldDecl SEMICOLON ''' parsed.append(p.slice) return def p_FieldDecl(p): '''FieldDecl :",
"p[0] = p[1] p[0].name = 'int_lit' return def p_decimal_lit(p): '''decimal_lit",
"Expression GT Expression | Expression GT_EQ Expression | Expression PLUS",
"+ \" :: Syntax error in line no \" +",
"LSQUARE Expression RSQUARE ''' parsed.append(p.slice) p[0] = p[2] p[0].name =",
"if TreeNode.children == []: return name else: return name +",
"p[0].data += 1 p[0].children += [p[1]] return def p_VarDecl(p): '''VarDecl",
"check_variable(p[2]), '']) p[0].TAC.append_TAC(p[5].data) for i in range(len(p[5].children)): p[0].TAC.add_line(['ifgotoeq', check_variable(t1), p[5].children[i][0],",
"| Expression CARET Expression | Expression STAR Expression | Expression",
"0, 'INT', 0, [], p[1].TAC) return def p_ExprSwitchStmt(p): '''ExprSwitchStmt :",
"to add to SymbolTable\") return p[0].TAC.add_line([p[2], check_variable(p[1].children[i]), check_variable(p[3].children[i]), '']) else:",
"p[1] p[0].name = 'FunctionBody' return def p_SimpleStmt(p): '''SimpleStmt : Expression",
"''' parsed.append(p.slice) p[0] = p[1] p[0].name = 'elseTail' return def",
"+ TreeNode.data + \" is undefined\") return TreeNode.data else: return",
"GotoStmt | PrintIntStmt | PrintStrStmt ''' parsed.append(p.slice) p[0] = p[1]",
"TreeNode('IfStmt', 0, 'INT') p[0].TAC.append_TAC(p[2].TAC) p[0].TAC.add_line(['ifgotoeq', check_variable(p[2]), '0', l1]) p[0].TAC.append_TAC(p[3].TAC) p[0].TAC.add_line(['label',",
"return def p_string_lit(p): '''string_lit : STRING_LIT ''' parsed.append(p.slice) p[0] =",
"0, 'INT', 0, [p[1]], p[1].TAC) elif len(p) == 4: p[0]",
"p_Selector(p): '''Selector : DOT IDENTIFIER ''' parsed.append(p.slice) return def p_Index(p):",
"generated['temp']: print_error(\"Variable \" + p[1].children[i].data + \" is undefined\") return",
"string_lit RROUND ''' p[0] = p[3] name = symbol_table.current_scope +",
"error in line no \" + str(p.lineno) # Standard Logger",
"You missed something at the end\" else: print str(sys.argv[1]) +",
"= p[5] var_list = symbol_table.make_var_list() three_addr_code = convert_tac(p[0].TAC) symbol_table.fill_next_use(three_addr_code) assembly_code",
"' supplied') p[0].TAC.add_line(['call', check_variable(p[1]), str(p[2].data), '']) p[0].TAC.add_line(['return_value', check_variable(p[0]), '', ''])",
"Expression ''' parsed.append(p.slice) # TODO: Add in symbol table p[0]",
"= \"%(filename)10s:%(lineno)4d:%(message)s\" ) log = logging.getLogger() yacc.yacc(debug=True, debuglog=log) input_file =",
"TypeSpec | LROUND TypeSpecList RROUND ''' parsed.append(p.slice) return def p_TypeSpecList(p):",
"Ignoring package name and Imports for now p[0] = p[5]",
"if p[2] == '++': p[0].TAC.add_line(['+', check_variable(p[1]), check_variable(p[1]), one_val.data]) else: p[0].TAC.add_line(['-',",
"('left','RCURLY'), ('left','DDD'), ('left','DOT'), ('left','SEMICOLON'), ('left','COLON'), ('left','SINGLE_QUOTES'), ('left','DOUBLE_QUOTES'), ('left','DECIMAL_LIT'), ('left','OCTAL_LIT'), ('left','HEX_LIT'),",
"def p_SwitchStmt(p): '''SwitchStmt : ExprSwitchStmt ''' parsed.append(p.slice) p[0] = TreeNode('SwitchStmt',",
"return TreeNode.data else: return name else: newNode = SymbolTableNode(name, TreeNode.input_type)",
"AMP | LT_MINUS ''' parsed.append(p.slice) p[0] = TreeNode('unary_op', p[1], 'OPERATOR')",
"'Type' return def p_StandardTypes(p): '''StandardTypes : PREDEFINED_TYPES ''' parsed.append(p.slice) p[0]",
"PLUS Expression | Expression MINUS Expression | Expression OR Expression",
"SimpleStmt SEMICOLON LCURLY ScopeStart ExprCaseClauseList ScopeEnd RCURLY | SWITCH SimpleStmt",
"0, [p[1]], p[1].TAC) return def p_TopLevelDecl(p): '''TopLevelDecl : Declaration |",
"'int_lit' return def p_decimal_lit(p): '''decimal_lit : DECIMAL_LIT ''' parsed.append(p.slice) p[0]",
"'Expression': if p[1].isLvalue == 0: print_error(\"Lvalue required\") return else: if",
"= Code() parsed = [] symbol_table = SymbolTable() var_list =",
"Expression NOT_EQ Expression | Expression LT Expression | Expression LT_EQ",
"'', '']) return def p_elseTail(p): '''elseTail : IfStmt | Block",
"IDENTIFIER string_lit | empty string_lit ''' parsed.append(p.slice) # TODO: Ignoring",
"symbol_table.add_identifier(p[1]) == False: print_error(\"Unable to add to SymbolTable\") return p[0].TAC.append_TAC(p[3].TAC)",
": ParameterDecl | ParameterList COMMA ParameterDecl ''' parsed.append(p.slice) if len(p)",
"0, 'INT') return def p_Statement(p): '''Statement : Declaration | SimpleStmt",
"TreeNode('ShortVarDecl', 0, 'INT') if p[1].name == 'ExpressionList': l1 = len(p[1].children)",
"check_variable(p[1]), check_variable(p[3])]) p[0].name = 'Expression' return def p_UnaryExpr(p): '''UnaryExpr :",
"'''decimal_lit : DECIMAL_LIT ''' parsed.append(p.slice) p[0] = TreeNode('decimal_lit', p[1], 'INT')",
"| TypeSpecList TypeSpec SEMICOLON ''' parsed.append(p.slice) return def p_TypeSpec(p): '''TypeSpec",
"def p_SimpleStmt(p): '''SimpleStmt : Expression | Assignment | ShortVarDecl |",
"'']) p[0].name = 'PrintIntStmt' return def p_PrintStrStmt(p): '''PrintStrStmt : PRINTLN",
"'Signature' s = 'scope_' + str(len(generated['scope'])) symbol_table.new_scope(s) for child in",
"return def p_TagTop(p): '''TagTop : empty | Tag ''' parsed.append(p.slice)",
"p_decimal_lit(p): '''decimal_lit : DECIMAL_LIT ''' parsed.append(p.slice) p[0] = TreeNode('decimal_lit', p[1],",
"'''ParameterList : ParameterDecl | ParameterList COMMA ParameterDecl ''' parsed.append(p.slice) if",
"symbol_table.current_scope, 'None') return def p_ScopeEnd(p): '''ScopeEnd : empty ''' parsed.append(p.slice)",
"array case # p[2].print_node() if symbol_table.add_identifier(p[1], size = p[2].data) ==",
"check_variable(p[3])]) p[0].name = 'Expression' return def p_UnaryExpr(p): '''UnaryExpr : PrimaryExpr",
"ExpressionList | Expression assign_op Expression ''' parsed.append(p.slice) p[0] = TreeNode('Assignment',",
": CASE ExpressionList | DEFAULT | CASE Expression ''' parsed.append(p.slice)",
"1, [], p[1].TAC) p[0].TAC.append_TAC(p[3].TAC) p[0].TAC.add_line([p[2],check_variable(p[0]), check_variable(p[1]), check_variable(p[3])]) p[0].name = 'Expression'",
"TreeNode('TopLevelDeclList', 0, 'INT', 0, [p[1]] + p[3].children, p[1].TAC) p[0].TAC.append_TAC(p[3].TAC) else:",
": TopLevelDecl SEMICOLON TopLevelDeclList | empty ''' parsed.append(p.slice) if len(p)",
"+ p[3].children[i].data + \" is undefined\") return p[0].TAC.add_line([p[2].data, check_variable(p[1].children[i]), check_variable(p[3].children[i]),",
"and p[1].children[i].data not in generated['temp']: print_error(\"Variable \" + p[1].children[i].data +",
"TopLevelDeclList ''' parsed.append(p.slice) # TODO: Ignoring package name and Imports",
"'']) p[0].name = 'PrimaryExpr' return def p_Operand(p): '''Operand : Literal",
"l1, '', '']) p[0].TAC.append_TAC(p[2].TAC) p[0].TAC.add_line(['ifgotoeq',check_variable(p[2]), '0', l2]) p[0].TAC.append_TAC(p[3].TAC) p[0].TAC.add_line(['goto', l1,",
"False and p[3].data not in generated['temp']: print_error(\"Variable \" + p[3].data",
"if symbol_table.add_identifier(p[1].children[i]) == False: print_error(\"Unable to add to SymbolTable\") return",
"Type EQ Expression | IdentifierList Type | IdentifierList EQ ExpressionList",
"Signature FunctionBody ''' parsed.append(p.slice) # symbol_table.print_symbol_table() p[0] = TreeNode('FunctionDecl', 0,",
"if symbol_table.search_identifier(p[1].data) == False and p[1].data not in generated['temp']: print_error(\"Variable",
"import Code from codegen import generate_assembly three_addr_code = ThreeAddressCode() assembly_code",
"= p[4] # l2 = len(expr_list.children) # p[0].TAC.append_TAC(expr_list.TAC) # p[0].TAC.append_TAC(p[1].TAC)",
"= p[1] elif len(p) == 4: p[0] = TreeNode('IDENTIFIER', gen('temp'),",
"p[0].children += [p[1]] return def p_VarDecl(p): '''VarDecl : VAR VarSpecTopList",
"SEMICOLON ImportDeclList TopLevelDeclList ''' parsed.append(p.slice) # TODO: Ignoring package name",
"| LROUND Type COMMA Expression RROUND ''' # print p.slice",
"IdentifierBotList ''' parsed.append(p.slice) node = TreeNode('IDENTIFIER', p[1], 'INT', 1) p[0]",
"'''SwitchStmt : ExprSwitchStmt ''' parsed.append(p.slice) p[0] = TreeNode('SwitchStmt', 0, 'INT',",
"+ child.data, child.input_type) symbol_table.add_var(newNode, s) # symbol_table.print_symbol_table() if len(p) ==",
"return def p_TypeSpecList(p): '''TypeSpecList : empty | TypeSpecList TypeSpec SEMICOLON",
"TAC2 = p[2].data p[0] = TreeNode('ExprCaseClauseList', TAC1, 'INT', 0, p[1].children",
"l2, '', '']) return def p_elseTail(p): '''elseTail : IfStmt |",
"'''ImportDecl : IMPORT LROUND ImportSpecList RROUND | IMPORT ImportSpec '''",
"'', '']) p[0].name = 'PrintStrStmt' return def p_Declaration(p): '''Declaration :",
"p[0] = TreeNode('StatementList', 0, 'INT') return def p_Statement(p): '''Statement :",
"''' parsed.append(p.slice) p[0] = TreeNode('ExpressionList', 0, 'INT', 0, [p[1]] +",
"p[5].TAC.leaders[1:]: p[0].TAC.add_line(['goto', l2, '', '']) p[0].TAC.add_line(p[5].TAC.code[i]) p[0].TAC.add_line(['label', l2, '', ''])",
"p[0].name = 'Expression' return def p_UnaryExpr(p): '''UnaryExpr : PrimaryExpr |",
"not found # TreeNode.print_node() # symbol_table.print_symbol_table() if TreeNode.isLvalue == 1:",
"else: if symbol_table.search_identifier(p[1].data) == False and p[1].data not in generated['temp']:",
"def p_Result(p): '''Result : Parameters | Type ''' parsed.append(p.slice) if",
"p[0].name = 'Literal' return def p_BasicLit(p): '''BasicLit : int_lit |",
"'', '']) p[0].TAC.append_TAC(p[4].TAC) return def p_FunctionName(p): '''FunctionName : IDENTIFIER '''",
"string_lit | IDENTIFIER string_lit | empty string_lit ''' parsed.append(p.slice) #",
"return def p_TypeSpecTopList(p): '''TypeSpecTopList : TypeSpec | LROUND TypeSpecList RROUND",
"p[1] elif len(p) == 3: p[0] = TreeNode('IDENTIFIER', gen('temp'), 'INT',",
"''' parsed.append(p.slice) p[0] = TreeNode('ExprSwitchCase', 0, 'INT') if len(p) ==",
"'''SimpleStmt : Expression | Assignment | ShortVarDecl | IncDecStmt '''",
"import convert_tac from code import Code from codegen import generate_assembly",
"'SimpleStmt' return def p_IncDecStmt(p): '''IncDecStmt : Expression PLUS_PLUS | Expression",
"def p_IfStmt(p): '''IfStmt : IF Expression Block | IF Expression",
"p[0].TAC.append_TAC(p[3].TAC) p[0].TAC.add_line(['label', l1, '', '']) if len(p) == 6: l1",
"'RUNE') return def p_empty(p): 'empty :' pass def p_error(p): print",
"name for the variable, second is 0 if variable not",
"len(p) == 4: # expr = p[3] # p[0].TAC.append_TAC(p[3].TAC) #",
"# p[0].TAC.add_line(['=', check_variable(p[1]), check_variable(expr), '']) return def p_FunctionDecl(p): '''FunctionDecl :",
"+ ' parameters but ' + str(p[2].data) + ' supplied')",
"= p[1] p[0].name = 'BasicLit' return def p_int_lit(p): '''int_lit :",
"p[0] = p[2] p[0].name = 'Index' return def p_Arguments(p): '''Arguments",
"len(p) == 3: p[0] = TreeNode('Arguments', 0, 'None') if len(p)",
"parsed.append(p.slice) if len(p) == 2: node = TreeNode('IDENTIFIER', p[1], 'INT',",
"str(sys.argv[1]) + \" :: Syntax error in line no \"",
"'ParameterList' elif len(p) == 4: p[0] = TreeNode('ParameterList', p[1].data +",
"== 2: p[0] = TreeNode('ExpressionBotList', 0, 'INT', 0, [p[1]], p[1].TAC)",
"''' parsed.append(p.slice) return def p_ArrayType(p): '''ArrayType : LSQUARE ArrayLength RSQUARE",
"in range(p[5].TAC.length()): if i in p[5].TAC.leaders[1:]: p[0].TAC.add_line(['goto', l2, '', ''])",
"'VarSpecTopList' return def p_VarSpecList(p): '''VarSpecList : empty | VarSpecList VarSpec",
"p[0] = p[1] elif len(p) == 4: p[0] = TreeNode('IDENTIFIER',",
"= TreeNode('ParameterList', p[1].data + p[3].data, 'None', 0, p[1].children + p[3].children,",
"LROUND Type RROUND ''' parsed.append(p.slice) if len(p) == 2: p[0]",
"FunctionDecl ''' parsed.append(p.slice) p[0] = p[1] return def p_ImportDecl(p): '''ImportDecl",
"\" + TreeNode.data + \" is undefined\") return TreeNode.data else:",
"parsed.append(p.slice) # TODO: Ignoring Imports for now return def p_ImportSpec(p):",
"1: if TreeNode.data not in generated['temp']: name = symbol_table.search_identifier(TreeNode.data) if",
"p_VarSpecTopList(p): '''VarSpecTopList : VarSpec | LROUND VarSpecList RROUND ''' parsed.append(p.slice)",
": Declaration | SimpleStmt | ReturnStmt | Block | IfStmt",
"EQ ExpressionList | IdentifierList Type EQ ExpressionList ''' # Insert",
"symbol table p[0] = TreeNode('ShortVarDecl', 0, 'INT') if p[1].name ==",
"len(p) == 3: if p[2].name == 'Index': p[0] = TreeNode('IDENTIFIER',",
"if len(p) == 3: p[0].data = p[2].data p[0].TAC = p[2].TAC",
"| IDENTIFIER Type TagTop ''' parsed.append(p.slice) return def p_TagTop(p): '''TagTop",
"= p[3] # elif len(p) == 5: # expr_list =",
"'']) # p[0].TAC.add_line([l2]) return def p_ReturnStmt(p): '''ReturnStmt : RETURN |",
"Expression RROUND ''' parsed.append(p.slice) if len(p) == 2: p[0] =",
"'INT') p[0].TAC.append_TAC(p[2].TAC) p[0].TAC.add_line(['ifgotoeq', check_variable(p[2]), '0', l1]) p[0].TAC.append_TAC(p[3].TAC) p[0].TAC.add_line(['goto', l2, '',",
": decimal_lit | octal_lit | hex_lit ''' parsed.append(p.slice) p[0] =",
"+ ' supplied') p[0].TAC.add_line(['call', check_variable(p[1]), str(p[2].data), '']) p[0].TAC.add_line(['return_value', check_variable(p[0]), '',",
"print_error(\"Unable to add to SymbolTable\") return p[0].TAC.append_TAC(p[3].TAC) p[0].TAC.append_TAC(p[1].TAC) p[0].TAC.add_line([p[2], check_variable(p[1]),",
"else: return name else: newNode = SymbolTableNode(name, TreeNode.input_type) symbol_table.add_var(newNode) if",
"| IDENTIFIER | PrimaryExpr Selector | PrimaryExpr Index | PrimaryExpr",
"p[4].data) return def p_ArrayLength(p): '''ArrayLength : Expression ''' parsed.append(p.slice) p[0]",
"== 2: p[0] = p[1] elif len(p) == 3: p[0]",
"value(s)\") else: p[1] = TreeNode('IDENTIFIER',p[1],'INT',1) if p[2].input_type != 'NONE': #",
"PrimaryExpr Index | PrimaryExpr Arguments ''' parsed.append(p.slice) if len(p) ==",
"check_variable(p[1]), one_val.data]) else: print_error(\"Lvalue required\") p[0].name = 'IncDecStmt' return def",
"= [[p[1].data,l1]] p[0].data = p[1].TAC return def p_ExprSwitchCase(p): '''ExprSwitchCase :",
"p[2].data) symbol_table.add_var(newNode) p[0] = TreeNode('VarSpec',p[1].data,'INT') # expr = TreeNode('Expr', 0,",
"TreeNode.children + ']' else: newNode = SymbolTableNode(TreeNode.data, TreeNode.input_type) symbol_table.add_var(newNode) return",
"| Expression assign_op Expression ''' parsed.append(p.slice) p[0] = TreeNode('Assignment', 0,",
"p[1].TAC) p[0].TAC.append_TAC(p[3].TAC) return def p_ExpressionBotList(p): '''ExpressionBotList : Expression COMMA ExpressionBotList",
"1, 'None', 0, [p[1]]) else: p[0] = p[1] p[0].name =",
"p_StructType(p): '''StructType : STRUCT LCURLY FieldDeclList RCURLY ''' parsed.append(p.slice) return",
"0, 'INT') # p[0].TAC.append_TAC(p[1].TAC) p[0].TAC.add_line(['label', l1, '', '']) # p[0].TAC.add_line(['ifgotoneq',",
"# p[2].print_node() if symbol_table.add_identifier(p[1], size = p[2].data) == False: print_error(\"Unable",
"p[0].TAC.add_line([p[2], check_variable(p[1]), check_variable(p[3]), '']) return def p_Assignment(p): '''Assignment : ExpressionList",
"else: p[0] = TreeNode('TopLevelDeclList', 0, 'INT', 0, [p[1]], p[1].TAC) return",
"\" value(s)\") elif p[1].name == 'Expression': if p[1].isLvalue == 0:",
"p_ImportDecl(p): '''ImportDecl : IMPORT LROUND ImportSpecList RROUND | IMPORT ImportSpec",
"mismatch: \" + str(l1) + \" identifier(s) but \" +",
"p[0].TAC.add_line(['return_value', check_variable(p[0]), '', '']) p[0].name = 'PrimaryExpr' return def p_Operand(p):",
"ScopeStart ExprCaseClauseList ScopeEnd RCURLY | SWITCH SimpleStmt SEMICOLON Expression LCURLY",
"'''ContinueStmt : CONTINUE IDENTIFIER ''' parsed.append(p.slice) return def p_GotoStmt(p): '''GotoStmt",
"else: if symbol_table.add_identifier(p[1]) == False: print_error(\"Unable to add to SymbolTable\")",
"GOTO IDENTIFIER ''' parsed.append(p.slice) return def p_Expression(p): '''Expression : UnaryExpr",
"len(p) == 4: p[0] = TreeNode('ExpressionBotList', 0, 'INT', 0, [p[1]]",
"+ p[3].children, p[1].TAC) p[0].TAC.append_TAC(p[3].TAC) return def p_ExpressionBotList(p): '''ExpressionBotList : Expression",
"= 'Signature' s = 'scope_' + str(len(generated['scope'])) symbol_table.new_scope(s) for child",
"parsed.append(p.slice) if len(p) == 2: p[0] = p[1] else: p[0]",
"p[0] = p[2] p[0].name = 'Operand' return def p_Literal(p): '''Literal",
"<gh_stars>1-10 #!/usr/bin/python from code import TreeNode from code import ThreeAddressCode",
"empty ''' parsed.append(p.slice) symbol_table.end_scope() return def p_StatementList(p): '''StatementList : Statement",
"from codegen import convert_tac from code import Code from codegen",
"parsed.append(p.slice) return def p_TypeDef(p): '''TypeDef : IDENTIFIER Type ''' parsed.append(p.slice)",
"TODO: Ignoring Imports for now return def p_TopLevelDeclList(p): '''TopLevelDeclList :",
"print symbol_table.current_scope p[0].TAC.append_TAC(p[3].TAC) p[0].TAC.append_TAC(p[1].TAC) p[0].TAC.add_line([p[2].data, check_variable(p[1]), check_variable(p[3]), '']) return def",
"('left','STRING_LIT'), ('left','NEWLINE'), ('left','BREAK'), ('left','CONTINUE'), ('left','RETURN'), ('left','RROUND'), ('left','LROUND'), ('left', 'OR_OR'), ('left',",
"is False: print('Input file ' + input_file + ' does",
"ParameterList COMMA ParameterDecl ''' parsed.append(p.slice) if len(p) == 2: p[0]",
"ImportSpecList RROUND | IMPORT ImportSpec ''' parsed.append(p.slice) # TODO: Ignoring",
"'']) if len(p) == 3: if p[2].name == 'Expression': p[0]",
"ELSE elseTail ''' parsed.append(p.slice) if len(p) == 4: l1 =",
"print_error(\"Variable \" + p[3].children[i].data + \" is undefined\") return p[0].TAC.add_line([p[2].data,",
"+ p[3].data, 'None', 0, p[1].children + p[3].children, p[1].TAC) p[0].TAC.append_TAC(p[3].TAC) return",
"p_Type(p): '''Type : TypeLit | StandardTypes | LROUND Type RROUND",
"err + \"! ***\" sys.exit(1) def check_variable(TreeNode): # return 2",
"( ('left','IDENTIFIER'), ('right','ASSIGN_OP'), ('left','COMMA'), ('left','LSQUARE'), ('left','RSQUARE'), ('left','LCURLY'), ('left','RCURLY'), ('left','DDD'), ('left','DOT'),",
"parsed.append(p.slice) p[0] = TreeNode('ParameterDecl', 0, 'None') if len(p) == 3:",
"('left','RROUND'), ('left','LROUND'), ('left', 'OR_OR'), ('left', 'AMP_AMP'), ('left', 'EQ_EQ', 'NOT_EQ','LT','LT_EQ','GT','GT_EQ'), ('left',",
"NOT | CARET | STAR | AMP | LT_MINUS '''",
"l1]) p[0].TAC.append_TAC(p[3].TAC) p[0].children = [[p[1].data,l1]] p[0].data = p[1].TAC return def",
"p_ConstDecl(p): '''ConstDecl : CONST LROUND ConstSpecList RROUND | CONST ConstSpec",
"'INT') p[0].TAC.append_TAC(p[2].TAC) t1 = TreeNode('IDENTIFIER', gen('temp'), 'INT', 1) p[0].TAC.add_line(['=', check_variable(t1)",
"ExpressionList ''' parsed.append(p.slice) if len(p) == 2: p[0] = TreeNode('ReturnStmt',",
"+ '_' + str(len(generated[s])) generated[s] += [temp] return temp def",
"return def p_ScopeStart(p): '''ScopeStart : empty ''' parsed.append(p.slice) symbol_table.add_scope(gen('scope')) p[0]",
"if p[2].name == 'Expression': p[0] = TreeNode('Arguments', 1, 'None', 0,",
"p[2].data p[0].TAC = p[2].TAC return def p_ForStmt(p): '''ForStmt : FOR",
"parsed.append(p.slice) p[0] = TreeNode('ExprSwitchCase', 0, 'INT') if len(p) == 3:",
"= SymbolTableNode(name, p[1].input_type,size = p[2].data) symbol_table.add_var(newNode) p[0] = TreeNode('VarSpec',p[1].data,'INT') #",
"'INT') if p[1].name == 'ExpressionList': l1 = len(p[1].children) l2 =",
"TreeNode('ReturnStmt', 0, 'None') p[0].TAC.add_line(['return', '', '', '']) if len(p) ==",
"StatementList | empty ''' parsed.append(p.slice) if len(p) == 4: p[0]",
"EQ ExpressionList ''' # Insert into symbol table p[0] =",
"hasattr(p[1], 'name') and p[1].name == 'IdentifierList': zero_val = TreeNode('decimal_lit', 0,",
"2: p[0] = p[1] p[0].name = 'ParameterList' elif len(p) ==",
"p_assign_op(p): '''assign_op : EQ | PLUS_EQ | MINUS_EQ | OR_EQ",
"TagTop | IDENTIFIER Type TagTop ''' parsed.append(p.slice) return def p_TagTop(p):",
"'''FunctionType : FUNC Signature ''' parsed.append(p.slice) return def p_Signature(p): '''Signature",
"symbol_table.print_symbol_table() p[0] = TreeNode('FunctionDecl', 0, 'INT') # print symbol_table.current_scope #",
"p[0].name = 'Declaration' return def p_ConstDecl(p): '''ConstDecl : CONST LROUND",
"codegen import convert_tac from code import Code from codegen import",
"p_Result(p): '''Result : Parameters | Type ''' parsed.append(p.slice) if p[1].name",
"= len(expr_list.children) # p[0].TAC.append_TAC(expr_list.TAC) # p[0].TAC.append_TAC(p[1].TAC) # if l1 ==",
"# TODO: Ignoring Imports for now return def p_ImportSpecList(p): '''ImportSpecList",
"logging.basicConfig( level = logging.DEBUG, filename = \"parselog.txt\", filemode = \"w\",",
"'None', 0, [node]) elif len(p) == 4: node = TreeNode('IDENTIFIER',",
"'', '']) p[0].TAC.add_line(p[5].TAC.code[i]) p[0].TAC.add_line(['label', l2, '', '']) return def p_ExprCaseClauseList(p):",
"return def p_TypeDecl(p): '''TypeDecl : TYPE TypeSpecTopList ''' parsed.append(p.slice) return",
"def gen(s): if s not in generated.keys(): generated[s] = []",
"p[1].TAC) return def p_TopLevelDecl(p): '''TopLevelDecl : Declaration | FunctionDecl '''",
"symbol_table.add_var(newNode, s) # symbol_table.print_symbol_table() if len(p) == 2: p[0].input_type =",
"# elif len(p) == 5: # expr_list = p[4] #",
"('left','RSQUARE'), ('left','LCURLY'), ('left','RCURLY'), ('left','DDD'), ('left','DOT'), ('left','SEMICOLON'), ('left','COLON'), ('left','SINGLE_QUOTES'), ('left','DOUBLE_QUOTES'), ('left','DECIMAL_LIT'),",
"p[0].data = p[1].TAC return def p_ExprSwitchCase(p): '''ExprSwitchCase : CASE ExpressionList",
"Expression | Expression EQ_EQ Expression | Expression NOT_EQ Expression |",
"''' parsed.append(p.slice) return def p_AliasDecl(p): '''AliasDecl : IDENTIFIER EQ Type",
"symbol_table.search_identifier(TreeNode.data) if name == False: name = symbol_table.search_function(TreeNode.data) if name",
"p[3].children, p[1].TAC) p[0].TAC.append_TAC(p[3].TAC) else: p[0] = TreeNode('TopLevelDeclList', 0, 'INT', 0,",
"SymbolTableNode(p[3].data, p[3].input_type) newNode = SymbolTableNode(name, p[3].input_type, parameters = [parametersNode]) symbol_table.add_var(newNode)",
"[node] + p[3].children, p[3].TAC) return def p_ExpressionList(p): '''ExpressionList : Expression",
"+ p[2].children, p[1].TAC) p[0].TAC.add_leader(p[0].TAC.length()) p[0].TAC.append_TAC(p[2].TAC) p[0].data.append_TAC(TAC2) else: p[0] = TreeNode('ExprCaseClauseList',",
"+= [p[1]] return def p_VarDecl(p): '''VarDecl : VAR VarSpecTopList '''",
"False: name = symbol_table.search_function(TreeNode.data) if name == False: print_error(\"Variable \"",
"# if len(p) == 4: # expr = p[3] #",
"for now return def p_TopLevelDeclList(p): '''TopLevelDeclList : TopLevelDecl SEMICOLON TopLevelDeclList",
"[p[2]], p[2].TAC) if p[2].name == 'ExpressionList': p[0] = p[2] p[0].name",
"is undefined\") return if p[3].isLvalue == 1 and symbol_table.search_identifier(p[3].data) ==",
"== 0: print_error(\"Lvalue required\") return else: if symbol_table.add_identifier(p[1].children[i]) == False:",
"import SymbolTable from symbol_table import SymbolTableNode import logging import ply.lex",
"value(s)\") elif p[1].name == 'Expression': if p[1].isLvalue == 0: print_error(\"Lvalue",
"EQ ExpressionList | IDENTIFIER Type EQ Expression | IdentifierList Type",
"to add to SymbolTable\") return p[0].TAC.append_TAC(p[3].TAC) p[0].TAC.append_TAC(p[1].TAC) p[0].TAC.add_line([p[2], check_variable(p[1]), check_variable(p[3]),",
"= p[2].data) == False: print_error(\"Unable to add to SymbolTable\") return",
"0, 'INT') if len(p) == 3: p[0].data = p[2].data p[0].TAC",
"parameters but ' + str(p[2].data) + ' supplied') p[0].TAC.add_line(['call', check_variable(p[1]),",
"ContinueStmt | GotoStmt | PrintIntStmt | PrintStrStmt ''' parsed.append(p.slice) p[0]",
"l2 = gen('label') p[0].TAC.add_line(['label', l1, '', '']) p[0].TAC.append_TAC(p[2].TAC) p[0].TAC.add_line(['ifgotoeq',check_variable(p[2]), '0',",
"= TreeNode('IDENTIFIER', p[1], 'INT', 1) p[0] = TreeNode('IdentifierBotList', 0, 'None',",
"parsed.append(p.slice) if len(p) == 4: p[0] = TreeNode('StatementList', 0, 'INT',",
"three_addr_code.print_code() assembly_code.print_code() # symbol_table.print_symbol_table() return def p_ImportDeclList(p): '''ImportDeclList : ImportDecl",
"p[0].data += 1 p[0].children += [node] else: p[0].data += 1",
"parsed.append(p.slice) if len(p) == 2: p[0] = TreeNode('ReturnStmt', 0, 'None')",
"parsed.append(p.slice) p[0] = p[1] return def p_ImportDecl(p): '''ImportDecl : IMPORT",
"== 4: if p[2].name == 'Expression': p[0] = TreeNode('Arguments', 1,",
"p_SourceFile(p): '''SourceFile : PACKAGE IDENTIFIER SEMICOLON ImportDeclList TopLevelDeclList ''' parsed.append(p.slice)",
"l2, '', '']) return def p_ExprCaseClauseList(p): '''ExprCaseClauseList : empty |",
"'''PrintStrStmt : PRINTLN LROUND string_lit RROUND ''' p[0] = p[3]",
"return def p_SimpleStmt(p): '''SimpleStmt : Expression | Assignment | ShortVarDecl",
"TreeNode.input_type) symbol_table.add_var(newNode) if TreeNode.children == []: return name else: return",
"for node in p[1].children: p[0].data += 1 node.input_type = p[2].data",
"Literal | LROUND Expression RROUND ''' parsed.append(p.slice) if len(p) ==",
"symbol_table.print_symbol_table() if TreeNode.isLvalue == 1: if TreeNode.data not in generated['temp']:",
"p_ScopeStart(p): '''ScopeStart : empty ''' parsed.append(p.slice) symbol_table.add_scope(gen('scope')) p[0] = TreeNode('ScopeStart',",
":: Syntax error in line no \" + str(p.lineno) #",
"i in range(len(p[5].children)): p[0].TAC.add_line(['ifgotoeq', check_variable(t1), p[5].children[i][0], p[5].children[i][1]]) p[0].TAC.add_line(['goto', l2, '',",
"TreeNode('StatementList', 0, 'INT') return def p_Statement(p): '''Statement : Declaration |",
"print_error(\"Variable Declaration mismatch: \" + str(l1) + \" identifier(s) but",
": CONST LROUND ConstSpecList RROUND | CONST ConstSpec ''' parsed.append(p.slice)",
"p[0] = p[1] elif len(p) == 3: if p[2].name ==",
"TreeNode.print_node() # symbol_table.print_symbol_table() if TreeNode.isLvalue == 1: if TreeNode.data not",
"empty | ConstSpecList ConstSpec SEMICOLON ''' parsed.append(p.slice) return def p_ConstSpec(p):",
"p[0].TAC.add_line(['stack_push', '', '', '']) p[0].TAC.append_TAC(p[4].TAC) return def p_FunctionName(p): '''FunctionName :",
"def p_unary_op(p): '''unary_op : PLUS | MINUS | NOT |",
"''' parsed.append(p.slice) p[0] = TreeNode('StandardTypes', p[1], 'NONE') return def p_TypeLit(p):",
"print_error(\"Lvalue required\") return else: if symbol_table.search_identifier(p[1].children[i].data) == False and p[1].children[i].data",
"return def p_FunctionBody(p): '''FunctionBody : Block ''' parsed.append(p.slice) p[0] =",
"ImportDeclList | empty ''' parsed.append(p.slice) # TODO: Ignoring Imports for",
"p[0] = TreeNode('ExprCaseClauseList', TAC1, 'INT', 0, p[1].children + p[2].children, p[1].TAC)",
"EQ Expression | IdentifierList Type | IdentifierList EQ ExpressionList |",
"Expression | IdentifierList Type | IdentifierList EQ ExpressionList | IdentifierList",
"SWITCH SimpleStmt SEMICOLON LCURLY ScopeStart ExprCaseClauseList ScopeEnd RCURLY | SWITCH",
"3: p[0] = TreeNode('Parameters', 0, 'None') else: p[0] = p[2]",
"False and p[1].children[i].data not in generated['temp']: print_error(\"Variable \" + p[1].children[i].data",
"'''TypeSpec : AliasDecl | TypeDef ''' parsed.append(p.slice) return def p_AliasDecl(p):",
"SymbolTableNode(name, p[1].input_type,size = p[2].data) symbol_table.add_var(newNode) p[0] = TreeNode('VarSpec',p[1].data,'INT') # expr",
"[] temp = s + '_' + str(len(generated[s])) generated[s] +=",
"else: p[0].TAC.add_line(['-', check_variable(p[1]), check_variable(p[1]), one_val.data]) else: print_error(\"Lvalue required\") p[0].name =",
"undefined\") return if p[3].isLvalue == 1 and symbol_table.search_identifier(p[3].data) == False",
"check_variable(p[1].children[i]), check_variable(p[3].children[i]), '']) else: print_error(\"Variable Declaration mismatch: \" + str(l1)",
"import ply.lex as lex import ply.yacc as yacc import sys",
"if s not in generated.keys(): generated[s] = [] temp =",
"StatementList ScopeEnd RCURLY ''' parsed.append(p.slice) p[0] = p[3] p[0].data =",
"SymbolTableNode(name, TreeNode.input_type) symbol_table.add_var(newNode) if TreeNode.children == []: return name else:",
"'INT') # l1 = len(p[1].children) # if len(p) == 3:",
"child.data, '', '']) p[0].TAC.add_line(['stack_push', '', '', '']) p[0].TAC.append_TAC(p[4].TAC) return def",
"'None') else: p[0] = p[2] p[0].name = 'Parameters' return def",
"p[0].TAC.append_TAC(p[3].TAC) p[0].TAC.add_line(['goto', l1, '', '']) p[0].TAC.add_line(['label', l2, '', '']) if",
"= TreeNode('Arguments', 1, 'None', 0, [p[2]], p[2].TAC) if p[2].name ==",
"Type ''' parsed.append(p.slice) return def p_ArrayType(p): '''ArrayType : LSQUARE ArrayLength",
": IdentifierList Type TagTop | IDENTIFIER Type TagTop ''' parsed.append(p.slice)",
"| FunctionType | PointerType ''' parsed.append(p.slice) p[0] = p[1] p[0].name",
"if TreeNode.data not in generated['temp']: name = symbol_table.search_identifier(TreeNode.data) if name",
"+= [node] else: p[0].data += 1 p[0].children += [p[1]] return",
"return else: if symbol_table.add_identifier(p[1]) == False: print_error(\"Unable to add to",
"'NONE') return def p_TypeLit(p): '''TypeLit : ArrayType | StructType |",
"+ TreeNode.children + ']' else: newNode = SymbolTableNode(TreeNode.data, TreeNode.input_type) symbol_table.add_var(newNode)",
"s + '_' + str(len(generated[s])) generated[s] += [temp] return temp",
"= p[1] p[0].name = 'TypeLit' return def p_PointerType(p): '''PointerType :",
"p[1].TAC) return def p_ExprSwitchStmt(p): '''ExprSwitchStmt : SWITCH SimpleStmt SEMICOLON LCURLY",
"if len(p) == 3: l1 = gen('label') # l2 =",
"len(p) == 2: p[0] = TreeNode('ReturnStmt', 0, 'None') p[0].TAC.add_line(['return', '',",
"3: p[0].data = p[2].data p[0].TAC = p[2].TAC return def p_ForStmt(p):",
"return def p_BreakStmt(p): '''BreakStmt : BREAK IDENTIFIER ''' parsed.append(p.slice) return",
"= 'Statement' return def p_PrintIntStmt(p): '''PrintIntStmt : PRINTLN LROUND IDENTIFIER",
"p[1].name == 'Expression': if p[1].isLvalue == 0: print_error(\"Lvalue required\") return",
"p[1] = TreeNode('IDENTIFIER',p[1],'INT',1) if p[2].input_type != 'NONE': # array case",
"os if os.path.isfile(input_file) is False: print('Input file ' + input_file",
"| SWITCH LCURLY ScopeStart ExprCaseClauseList ScopeEnd RCURLY | SWITCH Expression",
"TreeNode('IdentifierBotList', 0, 'None', 0, [node]) elif len(p) == 4: node",
"== 1 and symbol_table.search_identifier(p[3].children[i].data) == False and p[3].children[i].data not in",
"input_code = open(input_file, 'r').read() if input_code[len(input_code)-1] != '\\n': input_code +=",
"if len(p) == 4: l1 = gen('label') p[0] = TreeNode('IfStmt',",
"p[0].TAC.add_line(['ifgotoneq', p[1].children, p[1].children, l1]) p[0].TAC.append_TAC(p[3].TAC) p[0].children = [[p[1].data,l1]] p[0].data =",
"filemode = \"w\", format = \"%(filename)10s:%(lineno)4d:%(message)s\" ) log = logging.getLogger()",
"len(p) == 3: p[0] = TreeNode('Parameters', 0, 'None') else: p[0]",
"required\") return else: if symbol_table.add_identifier(p[1].children[i]) == False: print_error(\"Unable to add",
"decimal_lit | octal_lit | hex_lit ''' parsed.append(p.slice) p[0] = p[1]",
"= logging.getLogger() yacc.yacc(debug=True, debuglog=log) input_file = sys.argv[1] import os if",
"= p[2] p[0].name = 'VarDecl' return def p_VarSpecTopList(p): '''VarSpecTopList :",
"BasicLit | FunctionLit ''' parsed.append(p.slice) p[0] = p[1] p[0].name =",
"TreeNode('IDENTIFIER', p[1].data, 'INT', 1, p[2].data) elif p[2].name == 'Arguments': p[0]",
"p_hex_lit(p): '''hex_lit : HEX_LIT ''' parsed.append(p.slice) p[0] = TreeNode('hex_lit', p[1],",
"= p[2] return def p_Result(p): '''Result : Parameters | Type",
"= TreeNode('ExprCaseClauseList', TAC1, 'INT') return def p_ExprCaseClause(p): '''ExprCaseClause : ExprSwitchCase",
"ScopeStart ExprCaseClauseList ScopeEnd RCURLY ''' parsed.append(p.slice) if len(p) == 8:",
"p[0].TAC.add_line(['label', l1, '', '']) p[0].TAC.append_TAC(p[2].TAC) p[0].TAC.add_line(['goto', l1, '', '']) #",
"Expression | Expression GT_EQ Expression | Expression PLUS Expression |",
"symbol_table.add_scope(gen('scope')) p[0] = TreeNode('ScopeStart', symbol_table.current_scope, 'None') return def p_ScopeEnd(p): '''ScopeEnd",
"parsed.append(p.slice) # symbol_table.print_symbol_table() p[0] = TreeNode('FunctionDecl', 0, 'INT') # print",
"p_Assignment(p): '''Assignment : ExpressionList assign_op ExpressionList | Expression assign_op Expression",
"= p[2] p[0].name = 'Operand' return def p_Literal(p): '''Literal :",
"else: # print_error(\"Variable Declaration mismatch: \" + str(l1) + \"",
"for now return def p_ImportSpecList(p): '''ImportSpecList : ImportSpec SEMICOLON ImportSpecList",
"ConstDecl | TypeDecl | VarDecl ''' parsed.append(p.slice) p[0] = p[1]",
"p[1].children[i].isLvalue == 0: print_error(\"Lvalue required\") return else: if symbol_table.add_identifier(p[1].children[i]) ==",
"TODO: Ignoring Imports for now return def p_Block(p): '''Block :",
"Expression EQ_EQ Expression | Expression NOT_EQ Expression | Expression LT",
"FunctionBody ''' parsed.append(p.slice) # Anonymous Function # Not implemented yet",
"return def p_Statement(p): '''Statement : Declaration | SimpleStmt | ReturnStmt",
"== 'IdentifierList': zero_val = TreeNode('decimal_lit', 0, 'INT') # l1 =",
"'_' + gen('str_list') parametersNode = SymbolTableNode(p[3].data, p[3].input_type) newNode = SymbolTableNode(name,",
"('left','COLON'), ('left','SINGLE_QUOTES'), ('left','DOUBLE_QUOTES'), ('left','DECIMAL_LIT'), ('left','OCTAL_LIT'), ('left','HEX_LIT'), ('left','FLOAT_LIT'), ('left','STRING_LIT'), ('left','NEWLINE'), ('left','BREAK'),",
"\"parselog.txt\", filemode = \"w\", format = \"%(filename)10s:%(lineno)4d:%(message)s\" ) log =",
"def p_FunctionName(p): '''FunctionName : IDENTIFIER ''' parsed.append(p.slice) p[0] = TreeNode('FunctionName',",
"'''ImportSpecList : ImportSpec SEMICOLON ImportSpecList | empty ''' parsed.append(p.slice) #",
"1) p[0] = TreeNode('IdentifierBotList', 0, 'None', 0, [node] + p[3].children,",
"def print_error(err): print \"*** Error: \" + err + \"!",
"= p[1].TAC return def p_ExprSwitchCase(p): '''ExprSwitchCase : CASE ExpressionList |",
"else: TreeNode.print_node() return TreeNode.data precedence = ( ('left','IDENTIFIER'), ('right','ASSIGN_OP'), ('left','COMMA'),",
"\" value(s)\") else: p[1] = TreeNode('IDENTIFIER',p[1],'INT',1) if p[2].input_type != 'NONE':",
"('left','FLOAT_LIT'), ('left','STRING_LIT'), ('left','NEWLINE'), ('left','BREAK'), ('left','CONTINUE'), ('left','RETURN'), ('left','RROUND'), ('left','LROUND'), ('left', 'OR_OR'),",
"if temp != p[2].data: print_error('Function ' + funcName + '",
"def p_octal_lit(p): '''octal_lit : OCTAL_LIT ''' parsed.append(p.slice) p[0] = TreeNode('octal_lit',",
"2: p[0] = TreeNode('ExpressionBotList', 0, 'INT', 0, [p[1]], p[1].TAC) elif",
"len(p) == 3: if p[2].name == 'Expression': p[0] = p[2]",
": IMPORT LROUND ImportSpecList RROUND | IMPORT ImportSpec ''' parsed.append(p.slice)",
":: You missed something at the end\" else: print str(sys.argv[1])",
"== False and p[1].data not in generated['temp']: print_error(\"Variable \" +",
"('left', 'AMP_AMP'), ('left', 'EQ_EQ', 'NOT_EQ','LT','LT_EQ','GT','GT_EQ'), ('left', 'PLUS', 'MINUS','OR','CARET'), ('left', 'STAR',",
": Parameters | Type ''' parsed.append(p.slice) if p[1].name == 'Type':",
"0, 'None') if len(p) == 4: if p[2].name == 'Expression':",
"| LROUND Expression RROUND ''' parsed.append(p.slice) if len(p) == 2:",
"return def p_ExpressionBotList(p): '''ExpressionBotList : Expression COMMA ExpressionBotList | Expression",
"if hasattr(p[1], 'name') and p[1].name == 'IdentifierList': for node in",
"TreeNode('ParameterDecl', 0, 'None') if len(p) == 3: if hasattr(p[1], 'name')",
"| OR_EQ | CARET_EQ | STAR_EQ | DIVIDE_EQ | MODULO_EQ",
"def p_FunctionType(p): '''FunctionType : FUNC Signature ''' parsed.append(p.slice) return def",
"temp = len(f.parameters) # p[2].print_node() for child in p[2].children: p[0].TAC.add_line(['putparam',",
"ExprCaseClause ''' parsed.append(p.slice) TAC1 = ThreeAddressCode() TAC2 = ThreeAddressCode() if",
"p[2].name == 'Expression': p[0] = p[2] p[0].name = 'ReturnStmt' p[0].TAC.add_line(['return',",
"= p[2] p[0].name = 'Arguments' p[0].data = len(p[2].children) return def",
"def p_error(p): print p if p == None: print str(sys.argv[1])",
"p[3] # p[0].TAC.append_TAC(p[3].TAC) # p[0].TAC.add_line(['=', check_variable(p[1]), check_variable(expr), '']) # elif",
"p_ArrayType(p): '''ArrayType : LSQUARE ArrayLength RSQUARE Type ''' parsed.append(p.slice) p[0]",
"SEMICOLON ''' parsed.append(p.slice) return def p_FieldDecl(p): '''FieldDecl : IdentifierList Type",
"print_error(\"Variable \" + TreeNode.data + \" is undefined\") return TreeNode.data",
"'None', 0, [node] + p[3].children, p[3].TAC) return def p_IdentifierBotList(p): '''IdentifierBotList",
"'None', 0, [p[1]]) else: p[0] = p[1] p[0].name = 'Result'",
"p[0].children += [node] else: p[0].data += 1 p[0].children += [p[1]]",
"p[0].name = 'ArrayLength' return def p_StructType(p): '''StructType : STRUCT LCURLY",
"\"! ***\" sys.exit(1) def check_variable(TreeNode): # return 2 values. first",
"LCURLY ScopeStart ExprCaseClauseList ScopeEnd RCURLY | SWITCH SimpleStmt SEMICOLON Expression",
"TreeNode('Expr', 0, 'NONE') # if len(p) == 4: # expr",
"# three_addr_code.print_code() assembly_code.print_code() # symbol_table.print_symbol_table() return def p_ImportDeclList(p): '''ImportDeclList :",
"''' parsed.append(p.slice) node = TreeNode('IDENTIFIER', p[1], 'INT', 1) p[0] =",
"len(p) == 3: p[0] = TreeNode('IDENTIFIER', gen('temp'), 'INT', 1) p[0].TAC.add_line([check_variable(p[1]),",
"TreeNode('IDENTIFIER', p[1], p[2].data, 1) p[0].data += 1 p[0].children += [node]",
"check_variable(t1) , check_variable(p[2]), '']) p[0].TAC.append_TAC(p[5].data) for i in range(len(p[5].children)): p[0].TAC.add_line(['ifgotoeq',",
"requires ' + str(temp) + ' parameters but ' +",
"node = TreeNode('IDENTIFIER', p[1], 'INT', 1) p[0] = TreeNode('IdentifierList', 0,",
"= open(input_file, 'r').read() if input_code[len(input_code)-1] != '\\n': input_code += '\\n'",
"('left', 'PLUS', 'MINUS','OR','CARET'), ('left', 'STAR', 'DIVIDE','MODULO','AMP','AND_OR','LS','RS'), ) def p_SourceFile(p): '''SourceFile",
"f.name == p[2].data: noOfParams = len(f.parameters) p[0].TAC.add_line(['func', check_variable(p[2]), str(noOfParams), ''])",
"p == None: print str(sys.argv[1]) + \" :: You missed",
": Expression COMMA ExpressionBotList | Expression ''' parsed.append(p.slice) if len(p)",
"p[2] p[0].name = 'ReturnStmt' p[0].TAC.add_line(['return', check_variable(p[2]), '', '']) return def",
") log = logging.getLogger() yacc.yacc(debug=True, debuglog=log) input_file = sys.argv[1] import",
"'', '']) p[0].TAC.append_TAC(p[2].TAC) p[0].TAC.add_line(['ifgotoeq',check_variable(p[2]), '0', l2]) p[0].TAC.append_TAC(p[3].TAC) p[0].TAC.add_line(['goto', l1, '',",
"= len(p[3].children) p[0].TAC.append_TAC(p[3].TAC) p[0].TAC.append_TAC(p[1].TAC) if l1 == l2: for i",
"'++': p[0].TAC.add_line(['+', check_variable(p[1]), check_variable(p[1]), one_val.data]) else: p[0].TAC.add_line(['-', check_variable(p[1]), check_variable(p[1]), one_val.data])",
"if name == False: name = symbol_table.search_function(TreeNode.data) if name ==",
"something at the end\" else: print str(sys.argv[1]) + \" ::",
"TreeNode('ForStmt', 0, 'INT') if len(p) == 4: l1 = gen('label')",
"[], 'scope': ['scope_0'], 'label': [], 'str_list': []} def gen(s): if",
"= 'IncDecStmt' return def p_ShortVarDecl(p): '''ShortVarDecl : ExpressionList ASSIGN_OP ExpressionList",
"' + input_file + ' does not exist') sys.exit(1) input_code",
"parsed.append(p.slice) return def p_Tag(p): '''Tag : string_lit ''' parsed.append(p.slice) return",
"l2 = gen('label') p[0] = TreeNode('ExprSwitchStmt', 0, 'INT') p[0].TAC.append_TAC(p[2].TAC) t1",
"FieldDecl SEMICOLON ''' parsed.append(p.slice) return def p_FieldDecl(p): '''FieldDecl : IdentifierList",
"TypeDef ''' parsed.append(p.slice) return def p_AliasDecl(p): '''AliasDecl : IDENTIFIER EQ",
"Expression ''' parsed.append(p.slice) p[0] = p[1] p[0].name = 'ArrayLength' return",
"2: p[0] = TreeNode('ReturnStmt', 0, 'None') p[0].TAC.add_line(['return', '', '', ''])",
"p[0].TAC.add_line(['-', check_variable(p[1]), check_variable(p[1]), one_val.data]) else: print_error(\"Lvalue required\") p[0].name = 'IncDecStmt'",
"else: node = TreeNode('IDENTIFIER', p[1], p[2].data, 1) p[0].data += 1",
"3: # expr_list = TreeNode('Expr_List', 0, 'NONE', 0, [zero_val] *",
"generated['temp']: print_error(\"Variable \" + p[1].data + \" is undefined\") return",
"Ignoring Imports for now return def p_ImportSpec(p): '''ImportSpec : DOT",
"def p_assign_op(p): '''assign_op : EQ | PLUS_EQ | MINUS_EQ |",
"| Expression RS Expression | Expression AMP Expression | Expression",
"'''VarDecl : VAR VarSpecTopList ''' parsed.append(p.slice) p[0] = p[2] p[0].name",
"p_TypeSpecTopList(p): '''TypeSpecTopList : TypeSpec | LROUND TypeSpecList RROUND ''' parsed.append(p.slice)",
"if p[1].isLvalue == 0: print_error(\"Lvalue required\") return else: if symbol_table.search_identifier(p[1].data)",
"''' parsed.append(p.slice) one_val = TreeNode('IncDecStmt', '1', 'INT') p[0] = p[1]",
"= p[1].data TAC2 = p[2].data p[0] = TreeNode('ExprCaseClauseList', TAC1, 'INT',",
"| Expression MODULO Expression | Expression LS Expression | Expression",
"'BasicLit' return def p_int_lit(p): '''int_lit : decimal_lit | octal_lit |",
"'INT') p[0] = p[1] if p[1].isLvalue == 1: if p[2]",
"0, 'None') else: p[0] = p[2] p[0].name = 'Parameters' return",
"Expression | Expression DIVIDE Expression | Expression MODULO Expression |",
"p[0] = TreeNode('ScopeStart', symbol_table.current_scope, 'None') return def p_ScopeEnd(p): '''ScopeEnd :",
"if len(p) == 2: p[0] = TreeNode('ExpressionBotList', 0, 'INT', 0,",
"0, 'INT') # l1 = len(p[1].children) # if len(p) ==",
"''' parsed.append(p.slice) # Anonymous Function # Not implemented yet return",
"| CASE Expression ''' parsed.append(p.slice) p[0] = TreeNode('ExprSwitchCase', 0, 'INT')",
"l1, '', '']) p[0].TAC.add_line(['label', l2, '', '']) if len(p) ==",
"= SymbolTableNode(p[3].data, p[3].input_type) newNode = SymbolTableNode(name, p[3].input_type, parameters = [parametersNode])",
"== 3: # expr_list = TreeNode('Expr_List', 0, 'NONE', 0, [zero_val]",
"elif len(p) == 3: if p[2].name == 'Index': p[0] =",
"Ignoring Imports for now return def p_Block(p): '''Block : LCURLY",
"p[3] != None: p[0] = TreeNode('TopLevelDeclList', 0, 'INT', 0, [p[1]]",
"return temp def print_error(err): print \"*** Error: \" + err",
"= 'PrintIntStmt' return def p_PrintStrStmt(p): '''PrintStrStmt : PRINTLN LROUND string_lit",
"p_rune_lit(p): '''rune_lit : RUNE_LIT ''' parsed.append(p.slice) p[0] = TreeNode('rune_lit', p[1],",
"'']) p[0].TAC.add_line(p[5].TAC.code[i]) p[0].TAC.add_line(['label', l2, '', '']) return def p_ExprCaseClauseList(p): '''ExprCaseClauseList",
"= TreeNode('IDENTIFIER', p[1], 'INT', 1) elif p[1].name == 'Operand': p[0]",
"'''StructType : STRUCT LCURLY FieldDeclList RCURLY ''' parsed.append(p.slice) return def",
"= TreeNode('TopLevelDeclList', 0, 'INT', 0, [p[1]], p[1].TAC) return def p_TopLevelDecl(p):",
"= TreeNode('assign_op', p[1], 'OPERATOR') return def p_IfStmt(p): '''IfStmt : IF",
"p[0].TAC.append_TAC(p[3].TAC) else: p[0] = TreeNode('StatementList', 0, 'INT') return def p_Statement(p):",
"p[4].TAC.print_code() symbol_table.add_function(p[2].data, p[3].input_type, p[3].children) if len(p) == 5: noOfParams =",
"l1 == l2: for i in range(l1): if p[1].children[i].isLvalue ==",
"p[1].children[i], expr_list.children[i].data, '']) # else: # print_error(\"Variable Declaration mismatch: \"",
"''' parsed.append(p.slice) return def p_TypeSpecTopList(p): '''TypeSpecTopList : TypeSpec | LROUND",
": TYPE TypeSpecTopList ''' parsed.append(p.slice) return def p_TypeSpecTopList(p): '''TypeSpecTopList :",
"| Block | IfStmt | SwitchStmt | ForStmt | BreakStmt",
"TreeNode('hex_lit', p[1], 'HEX') return def p_float_lit(p): '''float_lit : FLOAT_LIT '''",
"p_StandardTypes(p): '''StandardTypes : PREDEFINED_TYPES ''' parsed.append(p.slice) p[0] = TreeNode('StandardTypes', p[1],",
"\" identifier(s) but \" + str(l2) + \" value(s)\") elif",
"Expression ''' parsed.append(p.slice) p[0] = TreeNode('Assignment', 0, 'INT') if p[1].name",
"l1 = gen('label') l2 = gen('label') p[0] = TreeNode('IfStmt', 0,",
"def p_ParameterList(p): '''ParameterList : ParameterDecl | ParameterList COMMA ParameterDecl '''",
"len(p) == 4: l1 = gen('label') p[0] = TreeNode('IfStmt', 0,",
"3: if p[2].name == 'Index': p[0] = TreeNode('IDENTIFIER', p[1].data, 'INT',",
"TreeNode('IDENTIFIER', gen('temp'), 'INT', 1) p[0].TAC.add_line(['=', check_variable(t1) , check_variable(p[2]), '']) p[0].TAC.append_TAC(p[5].data)",
"+ input_file + ' does not exist') sys.exit(1) input_code =",
"symbol_table.search_function(TreeNode.data) if name == False: print_error(\"Variable \" + TreeNode.data +",
"\" + str(p.lineno) # Standard Logger logging.basicConfig( level = logging.DEBUG,",
"+ err + \"! ***\" sys.exit(1) def check_variable(TreeNode): # return",
"gen('label') l2 = gen('label') p[0] = TreeNode('ExprSwitchStmt', 0, 'INT') p[0].TAC.append_TAC(p[2].TAC)",
"| Expression GT_EQ Expression | Expression PLUS Expression | Expression",
"= TreeNode('VarSpec',p[1].data,'INT') # expr = TreeNode('Expr', 0, 'NONE') # if",
"ScopeStart ExprCaseClauseList ScopeEnd RCURLY | SWITCH Expression LCURLY ScopeStart ExprCaseClauseList",
"| DEFAULT | CASE Expression ''' parsed.append(p.slice) p[0] = TreeNode('ExprSwitchCase',",
"missed something at the end\" else: print str(sys.argv[1]) + \"",
"'scope': ['scope_0'], 'label': [], 'str_list': []} def gen(s): if s",
"| AND_OR_EQ ''' parsed.append(p.slice) p[0] = TreeNode('assign_op', p[1], 'OPERATOR') return",
"for i in range(l1): # p[0].TAC.add_line(['=', p[1].children[i], expr_list.children[i].data, '']) #",
"Expression RROUND ''' # print p.slice parsed.append(p.slice) if len(p) ==",
"== 3: p[0] = TreeNode('Arguments', 0, 'None') if len(p) ==",
"0, [p[1].data] + p[3].children, p[1].TAC) p[0].TAC.append_TAC(p[3].TAC) else: p[0] = TreeNode('StatementList',",
"= gen('label') p[0].TAC.add_line(['label', l1, '', '']) p[0].TAC.append_TAC(p[2].TAC) p[0].TAC.add_line(['ifgotoeq',check_variable(p[2]), '0', l2])",
"RROUND | LROUND Expression RROUND | LROUND Type RROUND |",
"= TreeNode('VarSpec', 0, 'NONE') if hasattr(p[1], 'name') and p[1].name ==",
"'''ArrayLength : Expression ''' parsed.append(p.slice) p[0] = p[1] p[0].name =",
"p[0] = TreeNode('IdentifierBotList', 0, 'None', 0, [node]) elif len(p) ==",
"p[0].name = 'SimpleStmt' return def p_IncDecStmt(p): '''IncDecStmt : Expression PLUS_PLUS",
"p[0] = TreeNode('ExprCaseClause', 0, 'INT') # p[0].TAC.append_TAC(p[1].TAC) p[0].TAC.add_line(['label', l1, '',",
": UnaryExpr | Expression OR_OR Expression | Expression AMP_AMP Expression",
"'INT') p[0].TAC.append_TAC(p[2].TAC) p[0].TAC.add_line(['ifgotoeq', check_variable(p[2]), '0', l1]) p[0].TAC.append_TAC(p[3].TAC) p[0].TAC.add_line(['label', l1, '',",
"tokens from random import * from symbol_table import SymbolTable from",
"parsed.append(p.slice) return def p_GotoStmt(p): '''GotoStmt : GOTO IDENTIFIER ''' parsed.append(p.slice)",
"EQ Type ''' parsed.append(p.slice) return def p_TypeDef(p): '''TypeDef : IDENTIFIER",
"def p_VarDecl(p): '''VarDecl : VAR VarSpecTopList ''' parsed.append(p.slice) p[0] =",
"range(len(p[5].children)): p[0].TAC.add_line(['ifgotoeq', check_variable(t1), p[5].children[i][0], p[5].children[i][1]]) p[0].TAC.add_line(['goto', l2, '', '']) for",
"print str(sys.argv[1]) + \" :: Syntax error in line no",
"p[2].name == 'Index': p[0] = TreeNode('IDENTIFIER', p[1].data, 'INT', 1, p[2].data)",
"''' parsed.append(p.slice) if len(p) == 3: p[0] = TreeNode('Parameters', 0,",
"def p_ImportDeclList(p): '''ImportDeclList : ImportDecl SEMICOLON ImportDeclList | empty '''",
"p_TopLevelDeclList(p): '''TopLevelDeclList : TopLevelDecl SEMICOLON TopLevelDeclList | empty ''' parsed.append(p.slice)",
"print p if p == None: print str(sys.argv[1]) + \"",
"p[0] = p[1] p[0].name = 'Result' return def p_Parameters(p): '''Parameters",
"t1 = TreeNode('IDENTIFIER', gen('temp'), 'INT', 1) p[0].TAC.add_line(['=', check_variable(t1) , check_variable(p[2]),",
"str(l2) + \" value(s)\") else: p[1] = TreeNode('IDENTIFIER',p[1],'INT',1) if p[2].input_type",
"Expression | Expression AMP Expression | Expression AND_OR Expression '''",
"from lexer import tokens from random import * from symbol_table",
"if name == False: print_error(\"Variable \" + TreeNode.data + \"",
"def p_Declaration(p): '''Declaration : ConstDecl | TypeDecl | VarDecl '''",
"# l2 = len(expr_list.children) # p[0].TAC.append_TAC(expr_list.TAC) # p[0].TAC.append_TAC(p[1].TAC) # if",
"IDENTIFIER ''' parsed.append(p.slice) return def p_GotoStmt(p): '''GotoStmt : GOTO IDENTIFIER",
"p[0].TAC.append_TAC(expr_list.TAC) # p[0].TAC.append_TAC(p[1].TAC) # if l1 == l2: # for",
"hasattr(p[1], 'name') and p[1].name == 'IdentifierList': for node in p[1].children:",
"return p[0].TAC.add_line([p[2], check_variable(p[1].children[i]), check_variable(p[3].children[i]), '']) else: print_error(\"Variable Declaration mismatch: \"",
"'ArrayLength' return def p_StructType(p): '''StructType : STRUCT LCURLY FieldDeclList RCURLY",
"= p[1] p[0].name = 'int_lit' return def p_decimal_lit(p): '''decimal_lit :",
"print symbol_table.current_scope # p[4].TAC.print_code() symbol_table.add_function(p[2].data, p[3].input_type, p[3].children) if len(p) ==",
"if len(p) == 2: p[0] = p[1] p[0].name = 'ParameterList'",
"p_Index(p): '''Index : LSQUARE Expression RSQUARE ''' parsed.append(p.slice) p[0] =",
"p[1].data not in generated['temp']: print_error(\"Variable \" + p[1].data + \"",
"IfStmt | SwitchStmt | ForStmt | BreakStmt | ContinueStmt |",
"if p[3] != None: p[0] = TreeNode('TopLevelDeclList', 0, 'INT', 0,",
"[p[1].data] + p[3].children, p[1].TAC) p[0].TAC.append_TAC(p[3].TAC) else: p[0] = TreeNode('StatementList', 0,",
"== '++': p[0].TAC.add_line(['+', check_variable(p[1]), check_variable(p[1]), one_val.data]) else: p[0].TAC.add_line(['-', check_variable(p[1]), check_variable(p[1]),",
"return def p_ParameterDecl(p): '''ParameterDecl : IdentifierList Type | IDENTIFIER Type",
"if len(p) == 8: l1 = gen('label') l2 = gen('label')",
"parsed.append(p.slice) # TODO: Ignoring Imports for now return def p_TopLevelDeclList(p):",
"rune_lit ''' parsed.append(p.slice) p[0] = p[1] p[0].name = 'BasicLit' return",
"STRING_LIT ''' parsed.append(p.slice) p[0] = TreeNode('string_lit', p[1], 'STRING') return def",
"1 p[0].children += [node] else: p[0].data += 1 p[0].children +=",
"'']) # else: # print_error(\"Variable Declaration mismatch: \" + str(l1)",
"False: print_error(\"Unable to add to SymbolTable\") return p[0].TAC.append_TAC(p[3].TAC) p[0].TAC.append_TAC(p[1].TAC) p[0].TAC.add_line([p[2],",
"if len(p) == 4: l1 = gen('label') l2 = gen('label')",
": PrimaryExpr | unary_op UnaryExpr ''' parsed.append(p.slice) if len(p) ==",
"ThreeAddressCode() TAC2 = ThreeAddressCode() if len(p) == 3: TAC1 =",
"= TreeNode('ExpressionBotList', 0, 'INT', 0, [p[1]] + p[3].children, p[1].TAC) p[0].TAC.append_TAC(p[3].TAC)",
"ConstSpec SEMICOLON ''' parsed.append(p.slice) return def p_ConstSpec(p): '''ConstSpec : IDENTIFIER",
"= TreeNode('ReturnStmt', 0, 'None') p[0].TAC.add_line(['return', '', '', '']) if len(p)",
": ExprSwitchStmt ''' parsed.append(p.slice) p[0] = TreeNode('SwitchStmt', 0, 'INT', 0,",
"l1 = gen('label') l2 = gen('label') p[0] = TreeNode('ExprSwitchStmt', 0,",
"LROUND Type COMMA ExpressionList RROUND | LROUND Type COMMA Expression",
": VAR VarSpecTopList ''' parsed.append(p.slice) p[0] = p[2] p[0].name =",
"p[0] = p[1] if p[1].isLvalue == 1: if p[2] ==",
"ExpressionList | IdentifierList Type EQ ExpressionList ''' # Insert into",
"TreeNode.input_type != 'STRING': return TreeNode.data else: TreeNode.print_node() return TreeNode.data precedence",
"def p_Parameters(p): '''Parameters : LROUND RROUND | LROUND ParameterList RROUND",
"== 2: p[0] = p[1] else: p[0] = p[2] p[0].name",
"p_FunctionBody(p): '''FunctionBody : Block ''' parsed.append(p.slice) p[0] = p[1] p[0].name",
"IdentifierList EQ ExpressionList | IdentifierList Type EQ ExpressionList ''' #",
"IdentifierList Type | IDENTIFIER Type | Type ''' parsed.append(p.slice) p[0]",
"# symbol_table.print_symbol_table() if TreeNode.isLvalue == 1: if TreeNode.data not in",
"check_variable(p[1]), str(p[2].data), '']) p[0].TAC.add_line(['return_value', check_variable(p[0]), '', '']) p[0].name = 'PrimaryExpr'",
"p[0] = p[2] p[0].name = 'VarSpecTopList' return def p_VarSpecList(p): '''VarSpecList",
"p[1].children: p[0].data += 1 node.input_type = p[2].data p[0].children += [node]",
"str(l1) + \" identifier(s) but \" + str(l2) + \"",
"TYPE TypeSpecTopList ''' parsed.append(p.slice) return def p_TypeSpecTopList(p): '''TypeSpecTopList : TypeSpec",
": IDENTIFIER | IdentifierList | IDENTIFIER EQ Expression | IdentifierList",
"| TypeDef ''' parsed.append(p.slice) return def p_AliasDecl(p): '''AliasDecl : IDENTIFIER",
"= p[4] # p[0].TAC.append_TAC(p[4].TAC) # p[0].TAC.add_line(['=', check_variable(p[1]), check_variable(expr), '']) return",
"assign_op ExpressionList | Expression assign_op Expression ''' parsed.append(p.slice) p[0] =",
"l1 = len(p[1].children) l2 = len(p[3].children) p[0].TAC.append_TAC(p[3].TAC) p[0].TAC.append_TAC(p[1].TAC) if l1",
"SymbolTable() var_list = [] generated = {'temp': [], 'scope': ['scope_0'],",
"5: # expr_list = p[4] # l2 = len(expr_list.children) #",
"p[0].TAC.add_line(['label', l2, '', '']) if len(p) == 3: l1 =",
"' + str(temp) + ' parameters but ' + str(p[2].data)",
"p_Arguments(p): '''Arguments : LROUND RROUND | LROUND ExpressionList RROUND |",
"== 3: p[0].data = p[2].data p[0].TAC = p[2].TAC return def",
"p.slice[1].type == 'IDENTIFIER': p[0] = TreeNode('IDENTIFIER', p[1], 'INT', 1) elif",
"print_error(\"Unable to add to SymbolTable\") return p[0].TAC.add_line([p[2], check_variable(p[1].children[i]), check_variable(p[3].children[i]), ''])",
"RCURLY | SWITCH SimpleStmt SEMICOLON Expression LCURLY ScopeStart ExprCaseClauseList ScopeEnd",
"p[1] else: p[0] = p[2] p[0].name = 'Type' return def",
"[p[1]], p[1].TAC) return def p_TopLevelDecl(p): '''TopLevelDecl : Declaration | FunctionDecl",
"[zero_val] * l1) # elif len(p) == 4: # expr_list",
"def p_ConstDecl(p): '''ConstDecl : CONST LROUND ConstSpecList RROUND | CONST",
"Signature | FUNC FunctionName Signature FunctionBody ''' parsed.append(p.slice) # symbol_table.print_symbol_table()",
"symbol_table import SymbolTableNode import logging import ply.lex as lex import",
"DEFAULT | CASE Expression ''' parsed.append(p.slice) p[0] = TreeNode('ExprSwitchCase', 0,",
"p[0].TAC.add_line(['ifgotoeq', check_variable(t1), p[5].children[i][0], p[5].children[i][1]]) p[0].TAC.add_line(['goto', l2, '', '']) for i",
"len(p) == 2: p[0] = p[1] p[0].name = 'ParameterList' elif",
"'INT') return def p_octal_lit(p): '''octal_lit : OCTAL_LIT ''' parsed.append(p.slice) p[0]",
"# p[0].TAC.append_TAC(p[1].TAC) # if l1 == l2: # for i",
"p[0].TAC.add_line(['return', '', '', '']) if len(p) == 3: if p[2].name",
"p_UnaryExpr(p): '''UnaryExpr : PrimaryExpr | unary_op UnaryExpr ''' parsed.append(p.slice) if",
"return def p_VarSpec(p): '''VarSpec : IDENTIFIER Type | IDENTIFIER EQ",
"l1, '', '']) # p[0].TAC.add_line(['ifgotoneq', p[1].children, p[1].children, l1]) p[0].TAC.append_TAC(p[3].TAC) p[0].children",
"| LROUND ExpressionList RROUND | LROUND Expression RROUND | LROUND",
"RROUND | LROUND Type RROUND | LROUND Type COMMA ExpressionList",
"IDENTIFIER | IdentifierList | IDENTIFIER EQ Expression | IdentifierList EQ",
"LCURLY ScopeStart ExprCaseClauseList ScopeEnd RCURLY ''' parsed.append(p.slice) if len(p) ==",
"def p_ReturnStmt(p): '''ReturnStmt : RETURN | RETURN Expression | RETURN",
"| LROUND Type COMMA ExpressionList RROUND | LROUND Type COMMA",
"import os if os.path.isfile(input_file) is False: print('Input file ' +",
"print_error(\"Variable \" + p[1].data + \" is undefined\") return if",
"' + str(p[2].data) + ' supplied') p[0].TAC.add_line(['call', check_variable(p[1]), str(p[2].data), ''])",
"'NONE') # if len(p) == 4: # expr = p[3]",
"and Imports for now p[0] = p[5] var_list = symbol_table.make_var_list()",
"p[1] p[0].name = 'Signature' s = 'scope_' + str(len(generated['scope'])) symbol_table.new_scope(s)",
"p[0].name = 'elseTail' return def p_SwitchStmt(p): '''SwitchStmt : ExprSwitchStmt '''",
"LROUND int_lit RROUND ''' if hasattr(p[3], 'name') and p[3].name ==",
"= 'SimpleStmt' return def p_IncDecStmt(p): '''IncDecStmt : Expression PLUS_PLUS |",
"def p_float_lit(p): '''float_lit : FLOAT_LIT ''' parsed.append(p.slice) p[0] = TreeNode('float_lit',",
"in generated['temp']: name = symbol_table.search_identifier(TreeNode.data) if name == False: name",
"return if p[3].isLvalue == 1 and symbol_table.search_identifier(p[3].data) == False and",
"LROUND Expression RROUND | LROUND Type RROUND | LROUND Type",
"IDENTIFIER COMMA IdentifierBotList | IDENTIFIER ''' parsed.append(p.slice) if len(p) ==",
"= TreeNode('IncDecStmt', '1', 'INT') p[0] = p[1] if p[1].isLvalue ==",
"| Expression ASSIGN_OP Expression ''' parsed.append(p.slice) # TODO: Add in",
"p[0] = TreeNode('IDENTIFIER', gen('temp'), 'INT', 1) p[0].TAC.append_TAC(p[1].TAC) p[0].TAC.append_TAC(p[2].TAC) # p[1].print_node()",
"else: p[0] = p[2] p[0].name = 'Operand' return def p_Literal(p):",
"assembly_code = Code() parsed = [] symbol_table = SymbolTable() var_list",
"def p_FieldDeclList(p): '''FieldDeclList : empty | FieldDeclList FieldDecl SEMICOLON '''",
"[p[1]] + p[3].children, p[1].TAC) p[0].TAC.append_TAC(p[3].TAC) else: p[0] = TreeNode('TopLevelDeclList', 0,",
": FUNC Signature ''' parsed.append(p.slice) return def p_Signature(p): '''Signature :",
"[node] else: node = TreeNode('IDENTIFIER', p[1], p[2].data, 1) p[0].data +=",
"Expression LCURLY ScopeStart ExprCaseClauseList ScopeEnd RCURLY ''' parsed.append(p.slice) if len(p)",
"IDENTIFIER Type TagTop ''' parsed.append(p.slice) return def p_TagTop(p): '''TagTop :",
"= TreeNode('StatementList', 0, 'INT', 0, [p[1].data] + p[3].children, p[1].TAC) p[0].TAC.append_TAC(p[3].TAC)",
": Operand | IDENTIFIER | PrimaryExpr Selector | PrimaryExpr Index",
"SEMICOLON LCURLY ScopeStart ExprCaseClauseList ScopeEnd RCURLY | SWITCH SimpleStmt SEMICOLON",
"the end\" else: print str(sys.argv[1]) + \" :: Syntax error",
"p[0].data = p[2].data p[0].TAC = p[2].TAC return def p_ForStmt(p): '''ForStmt",
"RETURN ExpressionList ''' parsed.append(p.slice) if len(p) == 2: p[0] =",
"len(p) == 2: node = TreeNode('IDENTIFIER', p[1], 'INT', 1) p[0]",
"parsed.append(p.slice) if len(p) == 3: p[0] = TreeNode('Parameters', 0, 'None')",
"SEMICOLON ImportDeclList | empty ''' parsed.append(p.slice) # TODO: Ignoring Imports",
"if i in p[5].TAC.leaders[1:]: p[0].TAC.add_line(['goto', l2, '', '']) p[0].TAC.add_line(p[5].TAC.code[i]) p[0].TAC.add_line(['label',",
"Expression Block | FOR Block ''' parsed.append(p.slice) p[0] = TreeNode('ForStmt',",
"p[0].TAC.add_line(['goto', l2, '', '']) p[0].TAC.add_line(p[5].TAC.code[i]) p[0].TAC.add_line(['label', l2, '', '']) return",
": STRING_LIT ''' parsed.append(p.slice) p[0] = TreeNode('string_lit', p[1], 'STRING') return",
"parsed.append(p.slice) return def p_FieldDeclList(p): '''FieldDeclList : empty | FieldDeclList FieldDecl",
"'''StandardTypes : PREDEFINED_TYPES ''' parsed.append(p.slice) p[0] = TreeNode('StandardTypes', p[1], 'NONE')",
"p_Literal(p): '''Literal : BasicLit | FunctionLit ''' parsed.append(p.slice) p[0] =",
"# elif len(p) == 5: # expr = p[4] #",
"= {'temp': [], 'scope': ['scope_0'], 'label': [], 'str_list': []} def",
"return if p[3].children[i].isLvalue == 1 and symbol_table.search_identifier(p[3].children[i].data) == False and",
"p[0].TAC.add_line(['label', l1, '', '']) # p[0].TAC.add_line(['ifgotoneq', p[1].children, p[1].children, l1]) p[0].TAC.append_TAC(p[3].TAC)",
"len(p) == 4: if p[2].name == 'Expression': p[0] = TreeNode('Arguments',",
"| CARET_EQ | STAR_EQ | DIVIDE_EQ | MODULO_EQ | LS_EQ",
"'''ScopeEnd : empty ''' parsed.append(p.slice) symbol_table.end_scope() return def p_StatementList(p): '''StatementList",
"if len(p) == 3: if p[2].name == 'Expression': p[0] =",
"ExpressionList | DEFAULT | CASE Expression ''' parsed.append(p.slice) p[0] =",
"| unary_op UnaryExpr ''' parsed.append(p.slice) if len(p) == 2: p[0]",
"p[2] p[0].name = 'Operand' return def p_Literal(p): '''Literal : BasicLit",
"'''VarSpec : IDENTIFIER Type | IDENTIFIER EQ Expression | IDENTIFIER",
"+ p[1].data + \" is undefined\") return if p[3].isLvalue ==",
"= TreeNode('IDENTIFIER', p[1], p[2].data, 1) p[0].data += 1 p[0].children +=",
"ExprCaseClauseList ScopeEnd RCURLY | SWITCH Expression LCURLY ScopeStart ExprCaseClauseList ScopeEnd",
"('left','COMMA'), ('left','LSQUARE'), ('left','RSQUARE'), ('left','LCURLY'), ('left','RCURLY'), ('left','DDD'), ('left','DOT'), ('left','SEMICOLON'), ('left','COLON'), ('left','SINGLE_QUOTES'),",
"'name') and p[3].name == 'int_lit': p[0] = p[3] # p[0].isLvalue",
"'''ExprSwitchStmt : SWITCH SimpleStmt SEMICOLON LCURLY ScopeStart ExprCaseClauseList ScopeEnd RCURLY",
"''' parsed.append(p.slice) if len(p) == 8: l1 = gen('label') l2",
"= [] generated = {'temp': [], 'scope': ['scope_0'], 'label': [],",
": DOT IDENTIFIER ''' parsed.append(p.slice) return def p_Index(p): '''Index :",
"'PrintStrStmt' return def p_Declaration(p): '''Declaration : ConstDecl | TypeDecl |",
"| ConstSpecList ConstSpec SEMICOLON ''' parsed.append(p.slice) return def p_ConstSpec(p): '''ConstSpec",
"= p[2] p[0].name = 'VarSpecTopList' return def p_VarSpecList(p): '''VarSpecList :",
"generate_assembly(three_addr_code,var_list,symbol_table) # p[0].TAC.print_code() # three_addr_code.print_code() assembly_code.print_code() # symbol_table.print_symbol_table() return def",
"p[0].data = p[2].data p[0].name = 'Block' return def p_ScopeStart(p): '''ScopeStart",
"TypeSpecList RROUND ''' parsed.append(p.slice) return def p_TypeSpecList(p): '''TypeSpecList : empty",
"| IdentifierList | IDENTIFIER EQ Expression | IdentifierList EQ ExpressionList",
"| IMPORT ImportSpec ''' parsed.append(p.slice) # TODO: Ignoring Imports for",
"RUNE_LIT ''' parsed.append(p.slice) p[0] = TreeNode('rune_lit', p[1], 'RUNE') return def",
"'']) return def p_Assignment(p): '''Assignment : ExpressionList assign_op ExpressionList |",
"| Expression AMP Expression | Expression AND_OR Expression ''' parsed.append(p.slice)",
"TreeNode.data else: return name else: newNode = SymbolTableNode(name, TreeNode.input_type) symbol_table.add_var(newNode)",
"# expr_list = p[4] # l2 = len(expr_list.children) # p[0].TAC.append_TAC(expr_list.TAC)",
"print_error(\"Lvalue required\") return else: if symbol_table.add_identifier(p[1].children[i]) == False: print_error(\"Unable to",
"0, 'INT', 0, [p[1].data] + p[3].children, p[1].TAC) p[0].TAC.append_TAC(p[3].TAC) else: p[0]",
"at the end\" else: print str(sys.argv[1]) + \" :: Syntax",
"= TreeNode('rune_lit', p[1], 'RUNE') return def p_empty(p): 'empty :' pass",
"p[3].data not in generated['temp']: print_error(\"Variable \" + p[3].data + \"",
"= p[2].data p[0] = TreeNode('ExprCaseClauseList', TAC1, 'INT', 0, p[1].children +",
"return def p_TopLevelDecl(p): '''TopLevelDecl : Declaration | FunctionDecl ''' parsed.append(p.slice)",
"def p_ExpressionList(p): '''ExpressionList : Expression COMMA ExpressionBotList ''' parsed.append(p.slice) p[0]",
"= TreeNode('IdentifierBotList', 0, 'None', 0, [node]) elif len(p) == 4:",
"PrintIntStmt | PrintStrStmt ''' parsed.append(p.slice) p[0] = p[1] p[0].name =",
"'''FunctionBody : Block ''' parsed.append(p.slice) p[0] = p[1] p[0].name =",
"OR Expression | Expression CARET Expression | Expression STAR Expression",
"TreeNode('unary_op', p[1], 'OPERATOR') return def p_PrimaryExpr(p): '''PrimaryExpr : Operand |",
"p[0] = TreeNode('ExprSwitchStmt', 0, 'INT') p[0].TAC.append_TAC(p[2].TAC) t1 = TreeNode('IDENTIFIER', gen('temp'),",
"open(input_file, 'r').read() if input_code[len(input_code)-1] != '\\n': input_code += '\\n' yacc.parse(input_code,",
"SEMICOLON ''' return def p_VarSpec(p): '''VarSpec : IDENTIFIER Type |",
"import logging import ply.lex as lex import ply.yacc as yacc",
"| Expression LT_EQ Expression | Expression GT Expression | Expression",
"('left','SINGLE_QUOTES'), ('left','DOUBLE_QUOTES'), ('left','DECIMAL_LIT'), ('left','OCTAL_LIT'), ('left','HEX_LIT'), ('left','FLOAT_LIT'), ('left','STRING_LIT'), ('left','NEWLINE'), ('left','BREAK'), ('left','CONTINUE'),",
"Imports for now return def p_ImportSpec(p): '''ImportSpec : DOT string_lit",
"''' parsed.append(p.slice) # TODO: Ignoring Imports for now return def",
"= 'Type' return def p_StandardTypes(p): '''StandardTypes : PREDEFINED_TYPES ''' parsed.append(p.slice)",
"SymbolTable\") return name = symbol_table.search_identifier(p[1].data) newNode = SymbolTableNode(name, p[1].input_type,size =",
"[p[1]]) else: p[0] = p[1] p[0].name = 'Result' return def",
"'']) return def p_ExprCaseClauseList(p): '''ExprCaseClauseList : empty | ExprCaseClauseList ExprCaseClause",
"'', '', '']) if len(p) == 3: if p[2].name ==",
"undefined\") return # print symbol_table.current_scope p[0].TAC.append_TAC(p[3].TAC) p[0].TAC.append_TAC(p[1].TAC) p[0].TAC.add_line([p[2].data, check_variable(p[1]), check_variable(p[3]),",
"+ \" identifier(s) but \" + str(l2) + \" value(s)\")",
"Assignment | ShortVarDecl | IncDecStmt ''' parsed.append(p.slice) p[0] = p[1]",
"p[0].isLvalue = 0 else: p[0] = TreeNode('IDENTIFIER', p[3], 'INT', 1,",
"Result ''' parsed.append(p.slice) p[0] = p[1] p[0].name = 'Signature' s",
"''' parsed.append(p.slice) p[0] = TreeNode('assign_op', p[1], 'OPERATOR') return def p_IfStmt(p):",
"Expression | Assignment | ShortVarDecl | IncDecStmt ''' parsed.append(p.slice) p[0]",
"os.path.isfile(input_file) is False: print('Input file ' + input_file + '",
"SEMICOLON ImportSpecList | empty ''' parsed.append(p.slice) # TODO: Ignoring Imports",
"return def p_elseTail(p): '''elseTail : IfStmt | Block ''' parsed.append(p.slice)",
"parsed.append(p.slice) p[0] = TreeNode('octal_lit', p[1], 'OCT') return def p_hex_lit(p): '''hex_lit",
"p[0].name = 'Arguments' p[0].data = len(p[2].children) return def p_string_lit(p): '''string_lit",
"== 5: # expr_list = p[4] # l2 = len(expr_list.children)",
"= TreeNode('IDENTIFIER', p[1], 'INT', 1) p[0] = TreeNode('IdentifierList', 0, 'None',",
"TypeSpec SEMICOLON ''' parsed.append(p.slice) return def p_TypeSpec(p): '''TypeSpec : AliasDecl",
"ArrayLength RSQUARE Type ''' parsed.append(p.slice) p[0] = TreeNode('ArrayType', p[2].data, p[4].data)",
"return def p_rune_lit(p): '''rune_lit : RUNE_LIT ''' parsed.append(p.slice) p[0] =",
"parsed.append(p.slice) return def p_FunctionType(p): '''FunctionType : FUNC Signature ''' parsed.append(p.slice)",
"= 'Expression' return def p_UnaryExpr(p): '''UnaryExpr : PrimaryExpr | unary_op",
"p[5].children[i][1]]) p[0].TAC.add_line(['goto', l2, '', '']) for i in range(p[5].TAC.length()): if",
"# Standard Logger logging.basicConfig( level = logging.DEBUG, filename = \"parselog.txt\",",
"l2 = len(expr_list.children) # p[0].TAC.append_TAC(expr_list.TAC) # p[0].TAC.append_TAC(p[1].TAC) # if l1",
"== 3: l1 = gen('label') # l2 = gen('label') p[0].TAC.add_line(['label',",
"p_ContinueStmt(p): '''ContinueStmt : CONTINUE IDENTIFIER ''' parsed.append(p.slice) return def p_GotoStmt(p):",
"('left','SEMICOLON'), ('left','COLON'), ('left','SINGLE_QUOTES'), ('left','DOUBLE_QUOTES'), ('left','DECIMAL_LIT'), ('left','OCTAL_LIT'), ('left','HEX_LIT'), ('left','FLOAT_LIT'), ('left','STRING_LIT'), ('left','NEWLINE'),",
"\" + p[3].data + \" is undefined\") return # print",
"''' parsed.append(p.slice) p[0] = p[2] p[0].name = 'Index' return def",
": VarSpec | LROUND VarSpecList RROUND ''' parsed.append(p.slice) if len(p)",
"= gen('label') l2 = gen('label') p[0] = TreeNode('ExprSwitchStmt', 0, 'INT')",
"empty string_lit ''' parsed.append(p.slice) # TODO: Ignoring Imports for now",
"0, 'None', 0, [node] + p[3].children, p[3].TAC) return def p_IdentifierBotList(p):",
"ScopeEnd RCURLY | SWITCH Expression LCURLY ScopeStart ExprCaseClauseList ScopeEnd RCURLY",
"Expression STAR Expression | Expression DIVIDE Expression | Expression MODULO",
"gen('temp'), 'INT', 1) p[0].TAC.add_line(['=', check_variable(t1) , check_variable(p[2]), '']) p[0].TAC.append_TAC(p[5].data) for",
"p[3].input_type) newNode = SymbolTableNode(name, p[3].input_type, parameters = [parametersNode]) symbol_table.add_var(newNode) p[0].TAC.add_line(['print_str',",
"Imports for now p[0] = p[5] var_list = symbol_table.make_var_list() three_addr_code",
"3: l1 = gen('label') # l2 = gen('label') p[0].TAC.add_line(['label', l1,",
"p_TypeDef(p): '''TypeDef : IDENTIFIER Type ''' parsed.append(p.slice) return def p_Type(p):",
"return def p_FieldDecl(p): '''FieldDecl : IdentifierList Type TagTop | IDENTIFIER",
"''' parsed.append(p.slice) TAC1 = ThreeAddressCode() TAC2 = ThreeAddressCode() if len(p)",
"return def p_ScopeEnd(p): '''ScopeEnd : empty ''' parsed.append(p.slice) symbol_table.end_scope() return",
"'''PrimaryExpr : Operand | IDENTIFIER | PrimaryExpr Selector | PrimaryExpr",
"IDENTIFIER ''' parsed.append(p.slice) return def p_ContinueStmt(p): '''ContinueStmt : CONTINUE IDENTIFIER",
"Imports for now return def p_Block(p): '''Block : LCURLY ScopeStart",
"now return def p_Block(p): '''Block : LCURLY ScopeStart StatementList ScopeEnd",
"if variable not found # TreeNode.print_node() # symbol_table.print_symbol_table() if TreeNode.isLvalue",
"p[1], 'INT', 1) p[0] = TreeNode('IdentifierBotList', 0, 'None', 0, [node])",
"== 4: p[0] = TreeNode('StatementList', 0, 'INT', 0, [p[1].data] +",
"= TreeNode('IDENTIFIER', p[3], 'INT', 1, []) p[0].TAC.add_line(['print_int', check_variable(p[0]), '', ''])",
"is 0 if variable not found # TreeNode.print_node() # symbol_table.print_symbol_table()",
"= p[1] p[0].name = 'Signature' s = 'scope_' + str(len(generated['scope']))",
"p[0].TAC.add_line(['=', check_variable(p[1]), check_variable(expr), '']) return def p_FunctionDecl(p): '''FunctionDecl : FUNC",
"Expression | Expression LT_EQ Expression | Expression GT Expression |",
"p[1] p[0].name = 'Declaration' return def p_ConstDecl(p): '''ConstDecl : CONST",
"def p_TypeSpecTopList(p): '''TypeSpecTopList : TypeSpec | LROUND TypeSpecList RROUND '''",
"AMP Expression | Expression AND_OR Expression ''' parsed.append(p.slice) if len(p)",
"TypeSpecTopList ''' parsed.append(p.slice) return def p_TypeSpecTopList(p): '''TypeSpecTopList : TypeSpec |",
"= p[2] p[0].name = 'Type' return def p_StandardTypes(p): '''StandardTypes :",
"len(p) == 3: # expr_list = TreeNode('Expr_List', 0, 'NONE', 0,",
"'NONE', 0, [zero_val] * l1) # elif len(p) == 4:",
"Block ''' parsed.append(p.slice) p[0] = p[1] p[0].name = 'FunctionBody' return",
"''' parsed.append(p.slice) if len(p) == 2: p[0] = TreeNode('ReturnStmt', 0,",
"elif len(p) == 4: p[0] = TreeNode('ExpressionBotList', 0, 'INT', 0,",
"= TreeNode('StandardTypes', p[1], 'NONE') return def p_TypeLit(p): '''TypeLit : ArrayType",
"return def p_PointerType(p): '''PointerType : STAR Type ''' parsed.append(p.slice) return",
"generated[s] = [] temp = s + '_' + str(len(generated[s]))",
"0, 'INT', 0, [p[1]], p[1].TAC) return def p_TopLevelDecl(p): '''TopLevelDecl :",
"| BreakStmt | ContinueStmt | GotoStmt | PrintIntStmt | PrintStrStmt",
"parsed.append(p.slice) return def p_AliasDecl(p): '''AliasDecl : IDENTIFIER EQ Type '''",
"p[0] = TreeNode('ParameterDecl', 0, 'None') if len(p) == 3: if",
"p[0] = TreeNode('string_lit', p[1], 'STRING') return def p_rune_lit(p): '''rune_lit :",
"COMMA ExpressionBotList | Expression ''' parsed.append(p.slice) if len(p) == 2:",
"TreeNode('decimal_lit', 0, 'INT') # l1 = len(p[1].children) # if len(p)",
"\" + p[1].children[i].data + \" is undefined\") return if p[3].children[i].isLvalue",
"import generate_assembly three_addr_code = ThreeAddressCode() assembly_code = Code() parsed =",
"'_' + str(len(generated[s])) generated[s] += [temp] return temp def print_error(err):",
"== 0: print_error(\"Lvalue required\") return else: if symbol_table.search_identifier(p[1].data) == False",
"Block ELSE elseTail ''' parsed.append(p.slice) if len(p) == 4: l1",
"len(p) == 3: l1 = gen('label') # l2 = gen('label')",
"def p_PointerType(p): '''PointerType : STAR Type ''' parsed.append(p.slice) return def",
"return def p_ConstDecl(p): '''ConstDecl : CONST LROUND ConstSpecList RROUND |",
"return def p_ConstSpecList(p): '''ConstSpecList : empty | ConstSpecList ConstSpec SEMICOLON",
"p_IfStmt(p): '''IfStmt : IF Expression Block | IF Expression Block",
"if len(p) == 5: noOfParams = 0 for f in",
"p_FunctionLit(p): '''FunctionLit : FUNC Signature FunctionBody ''' parsed.append(p.slice) # Anonymous",
"TAC2 = ThreeAddressCode() if len(p) == 3: TAC1 = p[1].data",
"Expression LT_EQ Expression | Expression GT Expression | Expression GT_EQ",
"# TreeNode.print_node() # symbol_table.print_symbol_table() if TreeNode.isLvalue == 1: if TreeNode.data",
": Expression | Assignment | ShortVarDecl | IncDecStmt ''' parsed.append(p.slice)",
"= len(f.parameters) p[0].TAC.add_line(['func', check_variable(p[2]), str(noOfParams), '']) for child in reversed(p[3].children):",
"p_FunctionName(p): '''FunctionName : IDENTIFIER ''' parsed.append(p.slice) p[0] = TreeNode('FunctionName', p[1],",
"1 and symbol_table.search_identifier(p[3].children[i].data) == False and p[3].children[i].data not in generated['temp']:",
"= check_variable(p[1]).split(\"_\") scope, funcName = \"_\".join(func[:2]), \"_\".join(func[2:]) temp = 0",
"[node] else: p[0].data += 1 p[0].children += [p[1]] return def",
"= symbol_table.make_var_list() three_addr_code = convert_tac(p[0].TAC) symbol_table.fill_next_use(three_addr_code) assembly_code = generate_assembly(three_addr_code,var_list,symbol_table) #",
": empty | Tag ''' parsed.append(p.slice) return def p_Tag(p): '''Tag",
"p_ImportDeclList(p): '''ImportDeclList : ImportDecl SEMICOLON ImportDeclList | empty ''' parsed.append(p.slice)",
"| MINUS_EQ | OR_EQ | CARET_EQ | STAR_EQ | DIVIDE_EQ",
"p[0].name = 'Type' return def p_StandardTypes(p): '''StandardTypes : PREDEFINED_TYPES '''",
"node = TreeNode('IDENTIFIER', p[1], p[2].data, 1) p[0].data += 1 p[0].children",
"| Expression OR_OR Expression | Expression AMP_AMP Expression | Expression",
"'''TypeSpecList : empty | TypeSpecList TypeSpec SEMICOLON ''' parsed.append(p.slice) return",
"undefined\") return TreeNode.data else: return name else: newNode = SymbolTableNode(name,",
"p[0].name = 'Index' return def p_Arguments(p): '''Arguments : LROUND RROUND",
", check_variable(p[2]), '']) p[0].TAC.append_TAC(p[5].data) for i in range(len(p[5].children)): p[0].TAC.add_line(['ifgotoeq', check_variable(t1),",
"for child in p[2].children: p[0].TAC.add_line(['putparam', check_variable(child), '', '']) if temp",
"Syntax error in line no \" + str(p.lineno) # Standard",
"funcName: temp = len(f.parameters) # p[2].print_node() for child in p[2].children:",
"p[0] = TreeNode('Arguments', 1, 'None', 0, [p[2]], p[2].TAC) if p[2].name",
"'''Declaration : ConstDecl | TypeDecl | VarDecl ''' parsed.append(p.slice) p[0]",
"\" is undefined\") return # print symbol_table.current_scope p[0].TAC.append_TAC(p[3].TAC) p[0].TAC.append_TAC(p[1].TAC) p[0].TAC.add_line([p[2].data,",
"l2 = gen('label') p[0].TAC.add_line(['label', l1, '', '']) p[0].TAC.append_TAC(p[2].TAC) p[0].TAC.add_line(['goto', l1,",
"p[2].name == 'Arguments': p[0] = TreeNode('IDENTIFIER', gen('temp'), 'INT', 1) p[0].TAC.append_TAC(p[1].TAC)",
": ConstDecl | TypeDecl | VarDecl ''' parsed.append(p.slice) p[0] =",
": BasicLit | FunctionLit ''' parsed.append(p.slice) p[0] = p[1] p[0].name",
"Type RROUND | LROUND Type COMMA ExpressionList RROUND | LROUND",
"p[1].name == 'Type': p[0] = TreeNode('Result', 1, 'None', 0, [p[1]])",
"LROUND ImportSpecList RROUND | IMPORT ImportSpec ''' parsed.append(p.slice) # TODO:",
"AMP_EQ | AND_OR_EQ ''' parsed.append(p.slice) p[0] = TreeNode('assign_op', p[1], 'OPERATOR')",
"| empty ''' parsed.append(p.slice) # TODO: Ignoring Imports for now",
"ScopeEnd RCURLY ''' parsed.append(p.slice) p[0] = p[3] p[0].data = p[2].data",
"len(p) == 4: # expr_list = p[3] # elif len(p)",
"noOfParams = 0 for f in symbol_table.symbol_table[symbol_table.current_scope]['functions']: if f.name ==",
"Expression ASSIGN_OP Expression ''' parsed.append(p.slice) # TODO: Add in symbol",
"p[2].data: print_error('Function ' + funcName + ' requires ' +",
"RETURN | RETURN Expression | RETURN ExpressionList ''' parsed.append(p.slice) if",
"name else: newNode = SymbolTableNode(name, TreeNode.input_type) symbol_table.add_var(newNode) if TreeNode.children ==",
"'Expression' return def p_UnaryExpr(p): '''UnaryExpr : PrimaryExpr | unary_op UnaryExpr",
"generate_assembly three_addr_code = ThreeAddressCode() assembly_code = Code() parsed = []",
"# array case # p[2].print_node() if symbol_table.add_identifier(p[1], size = p[2].data)",
"'', '']) if len(p) == 3: l1 = gen('label') #",
"\" is undefined\") return p[0].TAC.add_line([p[2].data, check_variable(p[1].children[i]), check_variable(p[3].children[i]), '']) else: print_error(\"Variable",
"TreeNode.data else: TreeNode.print_node() return TreeNode.data precedence = ( ('left','IDENTIFIER'), ('right','ASSIGN_OP'),",
"Expression LCURLY ScopeStart ExprCaseClauseList ScopeEnd RCURLY | SWITCH LCURLY ScopeStart",
"('left', 'STAR', 'DIVIDE','MODULO','AMP','AND_OR','LS','RS'), ) def p_SourceFile(p): '''SourceFile : PACKAGE IDENTIFIER",
"p[0] = TreeNode('float_lit', p[1], 'FLOAT') return def p_FunctionLit(p): '''FunctionLit :",
"def p_Signature(p): '''Signature : Parameters | Parameters Result ''' parsed.append(p.slice)",
"if p[1].isLvalue == 1: if p[2] == '++': p[0].TAC.add_line(['+', check_variable(p[1]),",
"= 'VarSpecTopList' return def p_VarSpecList(p): '''VarSpecList : empty | VarSpecList",
"ImportSpecList | empty ''' parsed.append(p.slice) # TODO: Ignoring Imports for",
"''' parsed.append(p.slice) if len(p) == 4: p[0] = TreeNode('StatementList', 0,",
"l1]) p[0].TAC.append_TAC(p[3].TAC) p[0].TAC.add_line(['goto', l2, '', '']) p[0].TAC.add_line(['label', l1, '', ''])",
"p[3].children[i].data + \" is undefined\") return p[0].TAC.add_line([p[2].data, check_variable(p[1].children[i]), check_variable(p[3].children[i]), ''])",
"return name else: newNode = SymbolTableNode(name, TreeNode.input_type) symbol_table.add_var(newNode) if TreeNode.children",
"| LROUND Type RROUND | LROUND Type COMMA ExpressionList RROUND",
"yet return def p_Selector(p): '''Selector : DOT IDENTIFIER ''' parsed.append(p.slice)",
"= SymbolTableNode(TreeNode.data, TreeNode.input_type) symbol_table.add_var(newNode) return TreeNode.data else: if TreeNode.input_type !=",
"str(sys.argv[1]) + \" :: You missed something at the end\"",
"else: p[0] = p[2] p[0].name = 'Type' return def p_StandardTypes(p):",
"= generate_assembly(three_addr_code,var_list,symbol_table) # p[0].TAC.print_code() # three_addr_code.print_code() assembly_code.print_code() # symbol_table.print_symbol_table() return",
"string_lit | rune_lit ''' parsed.append(p.slice) p[0] = p[1] p[0].name =",
"4: # expr = p[3] # p[0].TAC.append_TAC(p[3].TAC) # p[0].TAC.add_line(['=', check_variable(p[1]),",
": FOR Expression Block | FOR Block ''' parsed.append(p.slice) p[0]",
"OR_OR Expression | Expression AMP_AMP Expression | Expression EQ_EQ Expression",
"empty | VarSpecList VarSpec SEMICOLON ''' return def p_VarSpec(p): '''VarSpec",
"p_IdentifierList(p): '''IdentifierList : IDENTIFIER COMMA IdentifierBotList ''' parsed.append(p.slice) node =",
"l2, '', '']) if len(p) == 3: l1 = gen('label')",
"in generated['temp']: print_error(\"Variable \" + p[3].children[i].data + \" is undefined\")",
"p_VarSpec(p): '''VarSpec : IDENTIFIER Type | IDENTIFIER EQ Expression |",
"log = logging.getLogger() yacc.yacc(debug=True, debuglog=log) input_file = sys.argv[1] import os",
"import tokens from random import * from symbol_table import SymbolTable",
"p_ExpressionList(p): '''ExpressionList : Expression COMMA ExpressionBotList ''' parsed.append(p.slice) p[0] =",
": empty ''' parsed.append(p.slice) symbol_table.end_scope() return def p_StatementList(p): '''StatementList :",
"FUNC Signature ''' parsed.append(p.slice) return def p_Signature(p): '''Signature : Parameters",
"== 2: p[0] = p[1] p[0].name = 'ParameterList' elif len(p)",
"p[0] = p[3] # p[0].isLvalue = 0 else: p[0] =",
"''' parsed.append(p.slice) return def p_ConstSpec(p): '''ConstSpec : IDENTIFIER | IdentifierList",
"return name = symbol_table.search_identifier(p[1].data) newNode = SymbolTableNode(name, p[1].input_type,size = p[2].data)",
"TreeNode.data + \" is undefined\") return TreeNode.data else: return name",
"''' parsed.append(p.slice) p[0] = TreeNode('decimal_lit', p[1], 'INT') return def p_octal_lit(p):",
"if hasattr(p[3], 'name') and p[3].name == 'int_lit': p[0] = p[3]",
"= 'ArrayLength' return def p_StructType(p): '''StructType : STRUCT LCURLY FieldDeclList",
"TAC1, 'INT') return def p_ExprCaseClause(p): '''ExprCaseClause : ExprSwitchCase COLON StatementList",
"else: print str(sys.argv[1]) + \" :: Syntax error in line",
"| SWITCH SimpleStmt SEMICOLON Expression LCURLY ScopeStart ExprCaseClauseList ScopeEnd RCURLY",
"and p[3].children[i].data not in generated['temp']: print_error(\"Variable \" + p[3].children[i].data +",
"'PLUS', 'MINUS','OR','CARET'), ('left', 'STAR', 'DIVIDE','MODULO','AMP','AND_OR','LS','RS'), ) def p_SourceFile(p): '''SourceFile :",
"+ p[3].children, p[1].TAC) p[0].TAC.append_TAC(p[3].TAC) else: p[0] = TreeNode('StatementList', 0, 'INT')",
"'''FunctionName : IDENTIFIER ''' parsed.append(p.slice) p[0] = TreeNode('FunctionName', p[1], 'INT',",
"if TreeNode.input_type != 'STRING': return TreeNode.data else: TreeNode.print_node() return TreeNode.data",
"# TODO: Ignoring Imports for now return def p_ImportSpec(p): '''ImportSpec",
"p[0].TAC.append_TAC(p[1].TAC) if l1 == l2: for i in range(l1): if",
"# p[0].TAC.print_code() # three_addr_code.print_code() assembly_code.print_code() # symbol_table.print_symbol_table() return def p_ImportDeclList(p):",
"p[0] = p[2] p[0].name = 'ReturnStmt' p[0].TAC.add_line(['return', check_variable(p[2]), '', ''])",
"p[0] = p[1] p[0].name = 'Literal' return def p_BasicLit(p): '''BasicLit",
"[temp] return temp def print_error(err): print \"*** Error: \" +",
"p_ImportSpec(p): '''ImportSpec : DOT string_lit | IDENTIFIER string_lit | empty",
"'None') else: p[0].input_type = p[2] return def p_Result(p): '''Result :",
") def p_SourceFile(p): '''SourceFile : PACKAGE IDENTIFIER SEMICOLON ImportDeclList TopLevelDeclList",
"ExpressionList ''' parsed.append(p.slice) return def p_IdentifierList(p): '''IdentifierList : IDENTIFIER COMMA",
"= len(p[1].children) # if len(p) == 3: # expr_list =",
"0, 'INT') if len(p) == 4: l1 = gen('label') l2",
"p[0].input_type = p[2] return def p_Result(p): '''Result : Parameters |",
"TreeNode.children == []: return name else: return name + '['",
"Type | IDENTIFIER EQ Expression | IDENTIFIER Type EQ Expression",
"len(p) == 3: p[0].data = p[2].data p[0].TAC = p[2].TAC return",
"PLUS_EQ | MINUS_EQ | OR_EQ | CARET_EQ | STAR_EQ |",
"8: l1 = gen('label') l2 = gen('label') p[0] = TreeNode('ExprSwitchStmt',",
"if os.path.isfile(input_file) is False: print('Input file ' + input_file +",
"''' parsed.append(p.slice) return def p_Index(p): '''Index : LSQUARE Expression RSQUARE",
"TAC1 = ThreeAddressCode() TAC2 = ThreeAddressCode() if len(p) == 3:",
"== False: print_error(\"Unable to add to SymbolTable\") return p[0].TAC.add_line([p[2], check_variable(p[1].children[i]),",
"Expression | IdentifierList Type EQ ExpressionList ''' parsed.append(p.slice) return def",
"| PrimaryExpr Arguments ''' parsed.append(p.slice) if len(p) == 2: if",
"return def p_StructType(p): '''StructType : STRUCT LCURLY FieldDeclList RCURLY '''",
"no \" + str(p.lineno) # Standard Logger logging.basicConfig( level =",
"| ShortVarDecl | IncDecStmt ''' parsed.append(p.slice) p[0] = p[1] p[0].name",
"def p_ConstSpec(p): '''ConstSpec : IDENTIFIER | IdentifierList | IDENTIFIER EQ",
"TreeNode('ExprSwitchCase', 0, 'INT') if len(p) == 3: p[0].data = p[2].data",
"p[1].print_node() func = check_variable(p[1]).split(\"_\") scope, funcName = \"_\".join(func[:2]), \"_\".join(func[2:]) temp",
"''' parsed.append(p.slice) p[0] = TreeNode('unary_op', p[1], 'OPERATOR') return def p_PrimaryExpr(p):",
"| FunctionLit ''' parsed.append(p.slice) p[0] = p[1] p[0].name = 'Literal'",
": LROUND RROUND | LROUND ExpressionList RROUND | LROUND Expression",
"sys from codegen import convert_tac from code import Code from",
"'']) p[0].name = 'PrintStrStmt' return def p_Declaration(p): '''Declaration : ConstDecl",
"newNode = SymbolTableNode(TreeNode.data, TreeNode.input_type) symbol_table.add_var(newNode) return TreeNode.data else: if TreeNode.input_type",
"one_val.data]) else: print_error(\"Lvalue required\") p[0].name = 'IncDecStmt' return def p_ShortVarDecl(p):",
"node = TreeNode('IDENTIFIER', p[1], 'INT', 1) p[0] = TreeNode('IdentifierBotList', 0,",
"'INT', 1) p[0].TAC.add_line([check_variable(p[1]), check_variable(p[0]), check_variable(p[2]), '']) p[0].name = 'UnaryExpr' return",
"Expression | Expression AMP_AMP Expression | Expression EQ_EQ Expression |",
"TreeNode('IDENTIFIER', gen('temp'), 'INT', 1) p[0].TAC.append_TAC(p[1].TAC) p[0].TAC.append_TAC(p[2].TAC) # p[1].print_node() func =",
"return def p_ExprCaseClause(p): '''ExprCaseClause : ExprSwitchCase COLON StatementList ''' parsed.append(p.slice)",
"def p_ArrayType(p): '''ArrayType : LSQUARE ArrayLength RSQUARE Type ''' parsed.append(p.slice)",
"in generated['temp']: print_error(\"Variable \" + p[1].data + \" is undefined\")",
"def p_ForStmt(p): '''ForStmt : FOR Expression Block | FOR Block",
"p_int_lit(p): '''int_lit : decimal_lit | octal_lit | hex_lit ''' parsed.append(p.slice)",
"empty | ExprCaseClauseList ExprCaseClause ''' parsed.append(p.slice) TAC1 = ThreeAddressCode() TAC2",
"'']) p[0].TAC.append_TAC(p[2].TAC) p[0].TAC.add_line(['ifgotoeq',check_variable(p[2]), '0', l2]) p[0].TAC.append_TAC(p[3].TAC) p[0].TAC.add_line(['goto', l1, '', ''])",
"= gen('label') p[0] = TreeNode('ExprSwitchStmt', 0, 'INT') p[0].TAC.append_TAC(p[2].TAC) t1 =",
"LT Expression | Expression LT_EQ Expression | Expression GT Expression",
"if p[2].name == 'ExpressionList': p[0] = p[2] p[0].name = 'Arguments'",
"but \" + str(l2) + \" value(s)\") else: p[1] =",
"== 4: l1 = gen('label') p[0] = TreeNode('IfStmt', 0, 'INT')",
"p[0] = p[1] else: p[0] = p[2] p[0].name = 'VarSpecTopList'",
"'INT', 0, [p[1]] + p[3].children, p[1].TAC) p[0].TAC.append_TAC(p[3].TAC) else: p[0] =",
"LROUND Expression RROUND ''' parsed.append(p.slice) if len(p) == 2: p[0]",
"CARET Expression | Expression STAR Expression | Expression DIVIDE Expression",
"temp = s + '_' + str(len(generated[s])) generated[s] += [temp]",
"p_FieldDeclList(p): '''FieldDeclList : empty | FieldDeclList FieldDecl SEMICOLON ''' parsed.append(p.slice)",
"('left', 'EQ_EQ', 'NOT_EQ','LT','LT_EQ','GT','GT_EQ'), ('left', 'PLUS', 'MINUS','OR','CARET'), ('left', 'STAR', 'DIVIDE','MODULO','AMP','AND_OR','LS','RS'), )",
"TreeNode('Arguments', 1, 'None', 0, [p[2]], p[2].TAC) if p[2].name == 'ExpressionList':",
"''' parsed.append(p.slice) p[0] = p[1] p[0].name = 'FunctionBody' return def",
"Expression Block ELSE elseTail ''' parsed.append(p.slice) if len(p) == 4:",
"node.input_type = p[2].data p[0].children += [node] else: node = TreeNode('IDENTIFIER',",
"+= [temp] return temp def print_error(err): print \"*** Error: \"",
"IDENTIFIER | PrimaryExpr Selector | PrimaryExpr Index | PrimaryExpr Arguments",
"'''BasicLit : int_lit | float_lit | string_lit | rune_lit '''",
"'FLOAT') return def p_FunctionLit(p): '''FunctionLit : FUNC Signature FunctionBody '''",
"\" + str(l1) + \" identifier(s) but \" + str(l2)",
"noOfParams = len(f.parameters) p[0].TAC.add_line(['func', check_variable(p[2]), str(noOfParams), '']) for child in",
"l1, '', '']) if len(p) == 6: l1 = gen('label')",
"# symbol_table.print_symbol_table() return def p_ImportDeclList(p): '''ImportDeclList : ImportDecl SEMICOLON ImportDeclList",
"'None', 0, [node] + p[3].children, p[3].TAC) return def p_ExpressionList(p): '''ExpressionList",
"[p[1]], p[1].TAC) elif len(p) == 4: p[0] = TreeNode('ExpressionBotList', 0,",
"else: return name + '[' + TreeNode.children + ']' else:",
"def p_ParameterDecl(p): '''ParameterDecl : IdentifierList Type | IDENTIFIER Type |",
"''' parsed.append(p.slice) if len(p) == 4: if p[3] != None:",
"i in range(l1): # p[0].TAC.add_line(['=', p[1].children[i], expr_list.children[i].data, '']) # else:",
"p[3].data + \" is undefined\") return # print symbol_table.current_scope p[0].TAC.append_TAC(p[3].TAC)",
"sys.exit(1) def check_variable(TreeNode): # return 2 values. first is the",
"= TreeNode('hex_lit', p[1], 'HEX') return def p_float_lit(p): '''float_lit : FLOAT_LIT",
"p[0].name = 'Operand' return def p_Literal(p): '''Literal : BasicLit |",
"5: # expr = p[4] # p[0].TAC.append_TAC(p[4].TAC) # p[0].TAC.add_line(['=', check_variable(p[1]),",
"'']) return def p_elseTail(p): '''elseTail : IfStmt | Block '''",
"p[0] = p[1] p[0].name = 'BasicLit' return def p_int_lit(p): '''int_lit",
"len(p) == 2: p[0].input_type = TreeNode('Result', 0, 'None') else: p[0].input_type",
"'INT', 0, p[1].children + p[2].children, p[1].TAC) p[0].TAC.add_leader(p[0].TAC.length()) p[0].TAC.append_TAC(p[2].TAC) p[0].data.append_TAC(TAC2) else:",
"('left','OCTAL_LIT'), ('left','HEX_LIT'), ('left','FLOAT_LIT'), ('left','STRING_LIT'), ('left','NEWLINE'), ('left','BREAK'), ('left','CONTINUE'), ('left','RETURN'), ('left','RROUND'), ('left','LROUND'),",
"p_TopLevelDecl(p): '''TopLevelDecl : Declaration | FunctionDecl ''' parsed.append(p.slice) p[0] =",
"newNode = SymbolTableNode(name, p[3].input_type, parameters = [parametersNode]) symbol_table.add_var(newNode) p[0].TAC.add_line(['print_str', name,",
"''' parsed.append(p.slice) return def p_GotoStmt(p): '''GotoStmt : GOTO IDENTIFIER '''",
"MINUS Expression | Expression OR Expression | Expression CARET Expression",
"logging.getLogger() yacc.yacc(debug=True, debuglog=log) input_file = sys.argv[1] import os if os.path.isfile(input_file)",
"= ThreeAddressCode() TAC2 = ThreeAddressCode() if len(p) == 3: TAC1",
"FOR Expression Block | FOR Block ''' parsed.append(p.slice) p[0] =",
"int_lit | float_lit | string_lit | rune_lit ''' parsed.append(p.slice) p[0]",
"import ply.yacc as yacc import sys from codegen import convert_tac",
"TreeNode('ExprCaseClause', 0, 'INT') # p[0].TAC.append_TAC(p[1].TAC) p[0].TAC.add_line(['label', l1, '', '']) #",
"p[1] elif len(p) == 4: p[0] = TreeNode('IDENTIFIER', gen('temp'), 'INT',",
"IdentifierList Type | IdentifierList EQ ExpressionList | IdentifierList Type EQ",
"symbol_table.current_scope p[0].TAC.append_TAC(p[3].TAC) p[0].TAC.append_TAC(p[1].TAC) p[0].TAC.add_line([p[2].data, check_variable(p[1]), check_variable(p[3]), '']) return def p_assign_op(p):",
"p[0].TAC.add_line(['=', p[1].children[i], expr_list.children[i].data, '']) # else: # print_error(\"Variable Declaration mismatch:",
"package name and Imports for now p[0] = p[5] var_list",
"is undefined\") return if p[3].children[i].isLvalue == 1 and symbol_table.search_identifier(p[3].children[i].data) ==",
"== 5: # expr = p[4] # p[0].TAC.append_TAC(p[4].TAC) # p[0].TAC.add_line(['=',",
"p[1].children, p[1].children, l1]) p[0].TAC.append_TAC(p[3].TAC) p[0].children = [[p[1].data,l1]] p[0].data = p[1].TAC",
"p_ReturnStmt(p): '''ReturnStmt : RETURN | RETURN Expression | RETURN ExpressionList",
"l1 == l2: # for i in range(l1): # p[0].TAC.add_line(['=',",
"Code from codegen import generate_assembly three_addr_code = ThreeAddressCode() assembly_code =",
"= TreeNode('decimal_lit', p[1], 'INT') return def p_octal_lit(p): '''octal_lit : OCTAL_LIT",
"TreeNode('ExprSwitchStmt', 0, 'INT') p[0].TAC.append_TAC(p[2].TAC) t1 = TreeNode('IDENTIFIER', gen('temp'), 'INT', 1)",
"EQ ExpressionList ''' parsed.append(p.slice) return def p_IdentifierList(p): '''IdentifierList : IDENTIFIER",
"IDENTIFIER Type EQ Expression | IdentifierList Type | IdentifierList EQ",
"UnaryExpr | Expression OR_OR Expression | Expression AMP_AMP Expression |",
"Type | IDENTIFIER Type | Type ''' parsed.append(p.slice) p[0] =",
"TreeNode('VarSpec', 0, 'NONE') if hasattr(p[1], 'name') and p[1].name == 'IdentifierList':",
"ParameterList RROUND ''' parsed.append(p.slice) if len(p) == 3: p[0] =",
"== 'Expression': p[0] = TreeNode('Arguments', 1, 'None', 0, [p[2]], p[2].TAC)",
"Add in symbol table p[0] = TreeNode('ShortVarDecl', 0, 'INT') if",
"'INT', 1, [], p[1].TAC) p[0].TAC.append_TAC(p[3].TAC) p[0].TAC.add_line([p[2],check_variable(p[0]), check_variable(p[1]), check_variable(p[3])]) p[0].name =",
"== 'ExpressionList': p[0] = p[2] p[0].name = 'Arguments' p[0].data =",
"def p_ConstSpecList(p): '''ConstSpecList : empty | ConstSpecList ConstSpec SEMICOLON '''",
"# if l1 == l2: # for i in range(l1):",
"p[0] = p[1] p[0].name = 'FunctionBody' return def p_SimpleStmt(p): '''SimpleStmt",
"[], p[1].TAC) return def p_ExprSwitchStmt(p): '''ExprSwitchStmt : SWITCH SimpleStmt SEMICOLON",
"def p_VarSpecTopList(p): '''VarSpecTopList : VarSpec | LROUND VarSpecList RROUND '''",
"p_Tag(p): '''Tag : string_lit ''' parsed.append(p.slice) return def p_FunctionType(p): '''FunctionType",
"return def p_ShortVarDecl(p): '''ShortVarDecl : ExpressionList ASSIGN_OP ExpressionList | Expression",
"= TreeNode('SwitchStmt', 0, 'INT', 0, [], p[1].TAC) return def p_ExprSwitchStmt(p):",
"parsed.append(p.slice) if len(p) == 2: if p.slice[1].type == 'IDENTIFIER': p[0]",
"'HEX') return def p_float_lit(p): '''float_lit : FLOAT_LIT ''' parsed.append(p.slice) p[0]",
"symbol_table.search_identifier(p[3].data) == False and p[3].data not in generated['temp']: print_error(\"Variable \"",
"p[0].TAC.append_TAC(p[2].TAC) p[0].data.append_TAC(TAC2) else: p[0] = TreeNode('ExprCaseClauseList', TAC1, 'INT') return def",
"'']) p[0].TAC.append_TAC(p[5].data) for i in range(len(p[5].children)): p[0].TAC.add_line(['ifgotoeq', check_variable(t1), p[5].children[i][0], p[5].children[i][1]])",
"[p[1]] + p[3].children, p[1].TAC) p[0].TAC.append_TAC(p[3].TAC) return def p_TypeDecl(p): '''TypeDecl :",
"return def p_Parameters(p): '''Parameters : LROUND RROUND | LROUND ParameterList",
"empty | TypeSpecList TypeSpec SEMICOLON ''' parsed.append(p.slice) return def p_TypeSpec(p):",
"IDENTIFIER ''' parsed.append(p.slice) if len(p) == 2: node = TreeNode('IDENTIFIER',",
"return def p_IncDecStmt(p): '''IncDecStmt : Expression PLUS_PLUS | Expression MINUS_MINUS",
"| Expression AMP_AMP Expression | Expression EQ_EQ Expression | Expression",
"= len(p[2].children) return def p_string_lit(p): '''string_lit : STRING_LIT ''' parsed.append(p.slice)",
"return # print symbol_table.current_scope p[0].TAC.append_TAC(p[3].TAC) p[0].TAC.append_TAC(p[1].TAC) p[0].TAC.add_line([p[2].data, check_variable(p[1]), check_variable(p[3]), ''])",
"l2 = len(p[3].children) p[0].TAC.append_TAC(p[3].TAC) p[0].TAC.append_TAC(p[1].TAC) if l1 == l2: for",
"= p[3] # p[0].isLvalue = 0 else: p[0] = TreeNode('IDENTIFIER',",
"0, [p[1]] + p[3].children, p[1].TAC) p[0].TAC.append_TAC(p[3].TAC) return def p_TypeDecl(p): '''TypeDecl",
"'str_list': []} def gen(s): if s not in generated.keys(): generated[s]",
": HEX_LIT ''' parsed.append(p.slice) p[0] = TreeNode('hex_lit', p[1], 'HEX') return",
"= 0 for f in symbol_table.symbol_table[scope]['functions']: if f.name == funcName:",
"str(noOfParams), '']) for child in reversed(p[3].children): p[0].TAC.add_line(['getparam', p[4].data + '_'",
"p_StatementList(p): '''StatementList : Statement SEMICOLON StatementList | empty ''' parsed.append(p.slice)",
"LROUND ExpressionList RROUND | LROUND Expression RROUND | LROUND Type",
"def p_StructType(p): '''StructType : STRUCT LCURLY FieldDeclList RCURLY ''' parsed.append(p.slice)",
"+ '_' + child.data, child.input_type) symbol_table.add_var(newNode, s) # symbol_table.print_symbol_table() if",
"RROUND | LROUND Type COMMA Expression RROUND ''' # print",
"int_lit RROUND ''' if hasattr(p[3], 'name') and p[3].name == 'int_lit':",
"p[0] = TreeNode('IdentifierBotList', 0, 'None', 0, [node] + p[3].children, p[3].TAC)",
"= sys.argv[1] import os if os.path.isfile(input_file) is False: print('Input file",
"def p_StandardTypes(p): '''StandardTypes : PREDEFINED_TYPES ''' parsed.append(p.slice) p[0] = TreeNode('StandardTypes',",
"parsed.append(p.slice) # TODO: Ignoring Imports for now return def p_ImportSpecList(p):",
"| TypeDecl | VarDecl ''' parsed.append(p.slice) p[0] = p[1] p[0].name",
"+ p[3].children, p[3].TAC) return def p_ExpressionList(p): '''ExpressionList : Expression COMMA",
"TreeNode('Expr_List', 0, 'NONE', 0, [zero_val] * l1) # elif len(p)",
"MODULO_EQ | LS_EQ | RS_EQ | AMP_EQ | AND_OR_EQ '''",
"= symbol_table.current_scope + '_' + gen('str_list') parametersNode = SymbolTableNode(p[3].data, p[3].input_type)",
"p_ExprSwitchCase(p): '''ExprSwitchCase : CASE ExpressionList | DEFAULT | CASE Expression",
"len(p) == 4: p[0] = TreeNode('ParameterList', p[1].data + p[3].data, 'None',",
"0, [p[1]] + p[3].children, p[1].TAC) p[0].TAC.append_TAC(p[3].TAC) else: p[0] = TreeNode('TopLevelDeclList',",
"len(p[3].children) p[0].TAC.append_TAC(p[3].TAC) p[0].TAC.append_TAC(p[1].TAC) if l1 == l2: for i in",
"p[1] p[0].name = 'ArrayLength' return def p_StructType(p): '''StructType : STRUCT",
"+ ' does not exist') sys.exit(1) input_code = open(input_file, 'r').read()",
"'', '', '']) p[0].TAC.append_TAC(p[4].TAC) return def p_FunctionName(p): '''FunctionName : IDENTIFIER",
"LCURLY ScopeStart StatementList ScopeEnd RCURLY ''' parsed.append(p.slice) p[0] = p[3]",
"p[0] = TreeNode('ExpressionBotList', 0, 'INT', 0, [p[1]] + p[3].children, p[1].TAC)",
"4: p[0] = TreeNode('ParameterList', p[1].data + p[3].data, 'None', 0, p[1].children",
"not exist') sys.exit(1) input_code = open(input_file, 'r').read() if input_code[len(input_code)-1] !=",
"Expression | Expression AND_OR Expression ''' parsed.append(p.slice) if len(p) ==",
"= p[2].data p[0].name = 'Block' return def p_ScopeStart(p): '''ScopeStart :",
"symbol_table.current_scope # p[4].TAC.print_code() symbol_table.add_function(p[2].data, p[3].input_type, p[3].children) if len(p) == 5:",
"p[0] = TreeNode('IDENTIFIER', p[1], 'INT', 1) elif p[1].name == 'Operand':",
"symbol_table.make_var_list() three_addr_code = convert_tac(p[0].TAC) symbol_table.fill_next_use(three_addr_code) assembly_code = generate_assembly(three_addr_code,var_list,symbol_table) # p[0].TAC.print_code()",
"''' parsed.append(p.slice) symbol_table.add_scope(gen('scope')) p[0] = TreeNode('ScopeStart', symbol_table.current_scope, 'None') return def",
"'FunctionBody' return def p_SimpleStmt(p): '''SimpleStmt : Expression | Assignment |",
"len(p) == 2: p[0] = TreeNode('ExpressionBotList', 0, 'INT', 0, [p[1]],",
"= [parametersNode]) symbol_table.add_var(newNode) p[0].TAC.add_line(['print_str', name, '', '']) p[0].name = 'PrintStrStmt'",
"GT Expression | Expression GT_EQ Expression | Expression PLUS Expression",
"for i in range(l1): if p[1].children[i].isLvalue == 0: print_error(\"Lvalue required\")",
"temp def print_error(err): print \"*** Error: \" + err +",
"'NOT_EQ','LT','LT_EQ','GT','GT_EQ'), ('left', 'PLUS', 'MINUS','OR','CARET'), ('left', 'STAR', 'DIVIDE','MODULO','AMP','AND_OR','LS','RS'), ) def p_SourceFile(p):",
"+= 1 p[0].children += [p[1]] return def p_VarDecl(p): '''VarDecl :",
"p[3] p[0].data = p[2].data p[0].name = 'Block' return def p_ScopeStart(p):",
"= gen('label') p[0].TAC.add_line(['label', l1, '', '']) p[0].TAC.append_TAC(p[2].TAC) p[0].TAC.add_line(['goto', l1, '',",
"'OCT') return def p_hex_lit(p): '''hex_lit : HEX_LIT ''' parsed.append(p.slice) p[0]",
"# p[0].TAC.append_TAC(p[3].TAC) # p[0].TAC.add_line(['=', check_variable(p[1]), check_variable(expr), '']) # elif len(p)",
"parsed.append(p.slice) if len(p) == 2: p[0] = p[1] elif len(p)",
"child in p[1].children: symbol_table.add_identifier(child, s) newNode = SymbolTableNode(s + '_'",
"p[1] p[0].name = 'SimpleStmt' return def p_IncDecStmt(p): '''IncDecStmt : Expression",
"# p[4].TAC.print_code() symbol_table.add_function(p[2].data, p[3].input_type, p[3].children) if len(p) == 5: noOfParams",
"TagTop ''' parsed.append(p.slice) return def p_TagTop(p): '''TagTop : empty |",
"expr = TreeNode('Expr', 0, 'NONE') # if len(p) == 4:",
"for i in range(p[5].TAC.length()): if i in p[5].TAC.leaders[1:]: p[0].TAC.add_line(['goto', l2,",
"return def p_SwitchStmt(p): '''SwitchStmt : ExprSwitchStmt ''' parsed.append(p.slice) p[0] =",
"RROUND ''' parsed.append(p.slice) if len(p) == 3: p[0] = TreeNode('Parameters',",
"[] generated = {'temp': [], 'scope': ['scope_0'], 'label': [], 'str_list':",
"in generated['temp']: print_error(\"Variable \" + p[1].children[i].data + \" is undefined\")",
"import ThreeAddressCode from lexer import tokens from random import *",
"'PrimaryExpr' return def p_Operand(p): '''Operand : Literal | LROUND Expression",
"= p[1] return def p_ImportDecl(p): '''ImportDecl : IMPORT LROUND ImportSpecList",
"hex_lit ''' parsed.append(p.slice) p[0] = p[1] p[0].name = 'int_lit' return",
"parsed.append(p.slice) p[0] = TreeNode('string_lit', p[1], 'STRING') return def p_rune_lit(p): '''rune_lit",
"BreakStmt | ContinueStmt | GotoStmt | PrintIntStmt | PrintStrStmt '''",
"3: if p[2].name == 'Expression': p[0] = p[2] p[0].name =",
"gen('label') p[0] = TreeNode('IfStmt', 0, 'INT') p[0].TAC.append_TAC(p[2].TAC) p[0].TAC.add_line(['ifgotoeq', check_variable(p[2]), '0',",
"SwitchStmt | ForStmt | BreakStmt | ContinueStmt | GotoStmt |",
": RETURN | RETURN Expression | RETURN ExpressionList ''' parsed.append(p.slice)",
"ScopeStart StatementList ScopeEnd RCURLY ''' parsed.append(p.slice) p[0] = p[3] p[0].data",
"p[0].TAC.append_TAC(p[4].TAC) # p[0].TAC.add_line(['=', check_variable(p[1]), check_variable(expr), '']) return def p_FunctionDecl(p): '''FunctionDecl",
"3: p[0] = TreeNode('IDENTIFIER', gen('temp'), 'INT', 1) p[0].TAC.add_line([check_variable(p[1]), check_variable(p[0]), check_variable(p[2]),",
"return def p_FunctionLit(p): '''FunctionLit : FUNC Signature FunctionBody ''' parsed.append(p.slice)",
"if len(p) == 4: if p[2].name == 'Expression': p[0] =",
"'''ShortVarDecl : ExpressionList ASSIGN_OP ExpressionList | Expression ASSIGN_OP Expression '''",
"elif len(p) == 3: p[0] = TreeNode('IDENTIFIER', gen('temp'), 'INT', 1)",
"'None', 0, [p[2]], p[2].TAC) if p[2].name == 'ExpressionList': p[0] =",
"| Type ''' parsed.append(p.slice) if p[1].name == 'Type': p[0] =",
"gen('label') p[0].TAC.add_line(['label', l1, '', '']) p[0].TAC.append_TAC(p[2].TAC) p[0].TAC.add_line(['goto', l1, '', ''])",
"p[1] if p[1].isLvalue == 1: if p[2] == '++': p[0].TAC.add_line(['+',",
"l1 = gen('label') # l2 = gen('label') p[0].TAC.add_line(['label', l1, '',",
"p[0].TAC.add_line([p[2].data, check_variable(p[1]), check_variable(p[3]), '']) return def p_assign_op(p): '''assign_op : EQ",
"'''IdentifierBotList : IDENTIFIER COMMA IdentifierBotList | IDENTIFIER ''' parsed.append(p.slice) if",
"newNode = SymbolTableNode(name, TreeNode.input_type) symbol_table.add_var(newNode) if TreeNode.children == []: return",
"'PrintIntStmt' return def p_PrintStrStmt(p): '''PrintStrStmt : PRINTLN LROUND string_lit RROUND",
"p[0] = p[1] p[0].name = 'Signature' s = 'scope_' +",
"level = logging.DEBUG, filename = \"parselog.txt\", filemode = \"w\", format",
"LROUND IDENTIFIER RROUND | PRINTLN LROUND int_lit RROUND ''' if",
"IDENTIFIER EQ Type ''' parsed.append(p.slice) return def p_TypeDef(p): '''TypeDef :",
"= 'PrimaryExpr' return def p_Operand(p): '''Operand : Literal | LROUND",
"| Expression DIVIDE Expression | Expression MODULO Expression | Expression",
"TODO: Ignoring package name and Imports for now p[0] =",
"child.data, child.input_type) symbol_table.add_var(newNode, s) # symbol_table.print_symbol_table() if len(p) == 2:",
"'MINUS','OR','CARET'), ('left', 'STAR', 'DIVIDE','MODULO','AMP','AND_OR','LS','RS'), ) def p_SourceFile(p): '''SourceFile : PACKAGE",
"parsed.append(p.slice) p[0] = p[1] p[0].name = 'FunctionBody' return def p_SimpleStmt(p):",
"parsed.append(p.slice) p[0] = p[1] p[0].name = 'elseTail' return def p_SwitchStmt(p):",
": Expression COMMA ExpressionBotList ''' parsed.append(p.slice) p[0] = TreeNode('ExpressionList', 0,",
"FUNC FunctionName Signature | FUNC FunctionName Signature FunctionBody ''' parsed.append(p.slice)",
"symbol_table.add_identifier(p[1], size = p[2].data) == False: print_error(\"Unable to add to",
"Type ''' parsed.append(p.slice) return def p_Type(p): '''Type : TypeLit |",
"VarSpecList RROUND ''' parsed.append(p.slice) if len(p) == 2: p[0] =",
"'DIVIDE','MODULO','AMP','AND_OR','LS','RS'), ) def p_SourceFile(p): '''SourceFile : PACKAGE IDENTIFIER SEMICOLON ImportDeclList",
"IDENTIFIER EQ Expression | IDENTIFIER Type EQ Expression | IdentifierList",
"table p[0] = TreeNode('ShortVarDecl', 0, 'INT') if p[1].name == 'ExpressionList':",
"zero_val = TreeNode('decimal_lit', 0, 'INT') # l1 = len(p[1].children) #",
"DIVIDE Expression | Expression MODULO Expression | Expression LS Expression",
"'None') if len(p) == 3: if hasattr(p[1], 'name') and p[1].name",
"parsed.append(p.slice) return def p_TypeSpecList(p): '''TypeSpecList : empty | TypeSpecList TypeSpec",
"'']) else: print_error(\"Variable Declaration mismatch: \" + str(l1) + \"",
"Index | PrimaryExpr Arguments ''' parsed.append(p.slice) if len(p) == 2:",
"in line no \" + str(p.lineno) # Standard Logger logging.basicConfig(",
"TreeNode('ExpressionList', 0, 'INT', 0, [p[1]] + p[3].children, p[1].TAC) p[0].TAC.append_TAC(p[3].TAC) return",
"def p_TopLevelDeclList(p): '''TopLevelDeclList : TopLevelDecl SEMICOLON TopLevelDeclList | empty '''",
"p[4] # l2 = len(expr_list.children) # p[0].TAC.append_TAC(expr_list.TAC) # p[0].TAC.append_TAC(p[1].TAC) #",
"p[0] = TreeNode('IfStmt', 0, 'INT') p[0].TAC.append_TAC(p[2].TAC) p[0].TAC.add_line(['ifgotoeq', check_variable(p[2]), '0', l1])",
"= TreeNode('IDENTIFIER', gen('temp'), 'INT', 1, [], p[1].TAC) p[0].TAC.append_TAC(p[3].TAC) p[0].TAC.add_line([p[2],check_variable(p[0]), check_variable(p[1]),",
"def p_TypeSpecList(p): '''TypeSpecList : empty | TypeSpecList TypeSpec SEMICOLON '''",
"not in generated['temp']: print_error(\"Variable \" + p[1].data + \" is",
"= \"_\".join(func[:2]), \"_\".join(func[2:]) temp = 0 for f in symbol_table.symbol_table[scope]['functions']:",
"TreeNode('IDENTIFIER', p[1], 'INT', 1) p[0] = TreeNode('IdentifierList', 0, 'None', 0,",
"= 'scope_' + str(len(generated['scope'])) symbol_table.new_scope(s) for child in p[1].children: symbol_table.add_identifier(child,",
"# print_error(\"Variable Declaration mismatch: \" + str(l1) + \" identifier(s)",
"TreeNode('IDENTIFIER', gen('temp'), 'INT', 1, [], p[1].TAC) p[0].TAC.append_TAC(p[3].TAC) p[0].TAC.add_line([p[2],check_variable(p[0]), check_variable(p[1]), check_variable(p[3])])",
"0, [zero_val] * l1) # elif len(p) == 4: #",
"gen('label') l2 = gen('label') p[0] = TreeNode('IfStmt', 0, 'INT') p[0].TAC.append_TAC(p[2].TAC)",
"if len(p) == 3: # expr_list = TreeNode('Expr_List', 0, 'NONE',",
"Expression PLUS_PLUS | Expression MINUS_MINUS ''' parsed.append(p.slice) one_val = TreeNode('IncDecStmt',",
"TODO: Ignoring Imports for now return def p_ImportSpecList(p): '''ImportSpecList :",
"RS Expression | Expression AMP Expression | Expression AND_OR Expression",
"if f.name == p[2].data: noOfParams = len(f.parameters) p[0].TAC.add_line(['func', check_variable(p[2]), str(noOfParams),",
"''' parsed.append(p.slice) # TODO: Add in symbol table p[0] =",
"IdentifierList Type EQ ExpressionList ''' parsed.append(p.slice) return def p_IdentifierList(p): '''IdentifierList",
"return def p_ArrayLength(p): '''ArrayLength : Expression ''' parsed.append(p.slice) p[0] =",
"+ str(temp) + ' parameters but ' + str(p[2].data) +",
"RCURLY ''' parsed.append(p.slice) if len(p) == 8: l1 = gen('label')",
"Type COMMA ExpressionList RROUND | LROUND Type COMMA Expression RROUND",
"'Result' return def p_Parameters(p): '''Parameters : LROUND RROUND | LROUND",
"Block | FOR Block ''' parsed.append(p.slice) p[0] = TreeNode('ForStmt', 0,",
"# return 2 values. first is the name for the",
"str(temp) + ' parameters but ' + str(p[2].data) + '",
"str(len(generated['scope'])) symbol_table.new_scope(s) for child in p[1].children: symbol_table.add_identifier(child, s) newNode =",
"p_Statement(p): '''Statement : Declaration | SimpleStmt | ReturnStmt | Block",
"TreeNode('IDENTIFIER', p[3], 'INT', 1, []) p[0].TAC.add_line(['print_int', check_variable(p[0]), '', '']) p[0].name",
"''' parsed.append(p.slice) if len(p) == 2: node = TreeNode('IDENTIFIER', p[1],",
"StructType | FunctionType | PointerType ''' parsed.append(p.slice) p[0] = p[1]",
": IDENTIFIER COMMA IdentifierBotList ''' parsed.append(p.slice) node = TreeNode('IDENTIFIER', p[1],",
"== 0: print_error(\"Lvalue required\") return else: if symbol_table.add_identifier(p[1]) == False:",
"parsed.append(p.slice) return def p_Type(p): '''Type : TypeLit | StandardTypes |",
"0, p[1].children + p[2].children, p[1].TAC) p[0].TAC.add_leader(p[0].TAC.length()) p[0].TAC.append_TAC(p[2].TAC) p[0].data.append_TAC(TAC2) else: p[0]",
"CASE Expression ''' parsed.append(p.slice) p[0] = TreeNode('ExprSwitchCase', 0, 'INT') if",
"('left','DOUBLE_QUOTES'), ('left','DECIMAL_LIT'), ('left','OCTAL_LIT'), ('left','HEX_LIT'), ('left','FLOAT_LIT'), ('left','STRING_LIT'), ('left','NEWLINE'), ('left','BREAK'), ('left','CONTINUE'), ('left','RETURN'),",
"Block | IF Expression Block ELSE elseTail ''' parsed.append(p.slice) if",
"else: print_error(\"Lvalue required\") p[0].name = 'IncDecStmt' return def p_ShortVarDecl(p): '''ShortVarDecl",
"== False and p[3].children[i].data not in generated['temp']: print_error(\"Variable \" +",
"p[1].name == 'Operand': p[0] = p[1] elif len(p) == 3:",
"\" + p[1].data + \" is undefined\") return if p[3].isLvalue",
"RCURLY | SWITCH Expression LCURLY ScopeStart ExprCaseClauseList ScopeEnd RCURLY '''",
"temp = 0 for f in symbol_table.symbol_table[scope]['functions']: if f.name ==",
"return def p_Operand(p): '''Operand : Literal | LROUND Expression RROUND",
"LROUND ParameterList RROUND ''' parsed.append(p.slice) if len(p) == 3: p[0]",
"def p_TypeSpec(p): '''TypeSpec : AliasDecl | TypeDef ''' parsed.append(p.slice) return",
"Expression | Expression MODULO Expression | Expression LS Expression |",
"not in generated['temp']: print_error(\"Variable \" + p[3].children[i].data + \" is",
"'', '']) # p[0].TAC.add_line([l2]) return def p_ReturnStmt(p): '''ReturnStmt : RETURN",
"+ str(l1) + \" identifier(s) but \" + str(l2) +",
"size = p[2].data) == False: print_error(\"Unable to add to SymbolTable\")",
"def p_hex_lit(p): '''hex_lit : HEX_LIT ''' parsed.append(p.slice) p[0] = TreeNode('hex_lit',",
"ConstSpecList ConstSpec SEMICOLON ''' parsed.append(p.slice) return def p_ConstSpec(p): '''ConstSpec :",
": IF Expression Block | IF Expression Block ELSE elseTail",
"ImportDecl SEMICOLON ImportDeclList | empty ''' parsed.append(p.slice) # TODO: Ignoring",
"('left','DOT'), ('left','SEMICOLON'), ('left','COLON'), ('left','SINGLE_QUOTES'), ('left','DOUBLE_QUOTES'), ('left','DECIMAL_LIT'), ('left','OCTAL_LIT'), ('left','HEX_LIT'), ('left','FLOAT_LIT'), ('left','STRING_LIT'),",
"len(p[1].children) # if len(p) == 3: # expr_list = TreeNode('Expr_List',",
"elif len(p) == 5: # expr = p[4] # p[0].TAC.append_TAC(p[4].TAC)",
"'0', l1]) p[0].TAC.append_TAC(p[3].TAC) p[0].TAC.add_line(['label', l1, '', '']) if len(p) ==",
"codegen import generate_assembly three_addr_code = ThreeAddressCode() assembly_code = Code() parsed",
": empty | ConstSpecList ConstSpec SEMICOLON ''' parsed.append(p.slice) return def",
"Expression Block | IF Expression Block ELSE elseTail ''' parsed.append(p.slice)",
"''' if hasattr(p[3], 'name') and p[3].name == 'int_lit': p[0] =",
"+ \" is undefined\") return p[0].TAC.add_line([p[2].data, check_variable(p[1].children[i]), check_variable(p[3].children[i]), '']) else:",
"else: p[0] = p[1] p[0].name = 'Result' return def p_Parameters(p):",
"ScopeEnd RCURLY | SWITCH LCURLY ScopeStart ExprCaseClauseList ScopeEnd RCURLY |",
"('left','IDENTIFIER'), ('right','ASSIGN_OP'), ('left','COMMA'), ('left','LSQUARE'), ('left','RSQUARE'), ('left','LCURLY'), ('left','RCURLY'), ('left','DDD'), ('left','DOT'), ('left','SEMICOLON'),",
"0, 'None', 0, [node]) elif len(p) == 4: node =",
"p[0].name = 'FunctionBody' return def p_SimpleStmt(p): '''SimpleStmt : Expression |",
"from symbol_table import SymbolTableNode import logging import ply.lex as lex",
"def p_ImportSpec(p): '''ImportSpec : DOT string_lit | IDENTIFIER string_lit |",
"if input_code[len(input_code)-1] != '\\n': input_code += '\\n' yacc.parse(input_code, debug=log, tracking=True)",
"'None', 0, p[1].children + p[3].children, p[1].TAC) p[0].TAC.append_TAC(p[3].TAC) return def p_ParameterDecl(p):",
"MODULO Expression | Expression LS Expression | Expression RS Expression",
"== 2: p[0] = p[1] elif len(p) == 4: p[0]",
"| IF Expression Block ELSE elseTail ''' parsed.append(p.slice) if len(p)",
"TreeNode('octal_lit', p[1], 'OCT') return def p_hex_lit(p): '''hex_lit : HEX_LIT '''",
"parsed.append(p.slice) p[0] = TreeNode('Assignment', 0, 'INT') if p[1].name == 'ExpressionList':",
"parsed.append(p.slice) if len(p) == 4: l1 = gen('label') p[0] =",
"p[0].name = 'int_lit' return def p_decimal_lit(p): '''decimal_lit : DECIMAL_LIT '''",
"'[' + TreeNode.children + ']' else: newNode = SymbolTableNode(TreeNode.data, TreeNode.input_type)",
"string_lit | empty string_lit ''' parsed.append(p.slice) # TODO: Ignoring Imports",
"# p[0].TAC.add_line(['ifgotoneq', p[1].children, p[1].children, l1]) p[0].TAC.append_TAC(p[3].TAC) p[0].children = [[p[1].data,l1]] p[0].data",
"'''ArrayType : LSQUARE ArrayLength RSQUARE Type ''' parsed.append(p.slice) p[0] =",
"STAR Expression | Expression DIVIDE Expression | Expression MODULO Expression",
"Arguments ''' parsed.append(p.slice) if len(p) == 2: if p.slice[1].type ==",
"p[2] p[0].name = 'VarSpecTopList' return def p_VarSpecList(p): '''VarSpecList : empty",
"return def p_TypeLit(p): '''TypeLit : ArrayType | StructType | FunctionType",
"else: newNode = SymbolTableNode(name, TreeNode.input_type) symbol_table.add_var(newNode) if TreeNode.children == []:",
"return def p_ImportDeclList(p): '''ImportDeclList : ImportDecl SEMICOLON ImportDeclList | empty",
"p[2].TAC return def p_ForStmt(p): '''ForStmt : FOR Expression Block |",
"def p_ExprCaseClause(p): '''ExprCaseClause : ExprSwitchCase COLON StatementList ''' parsed.append(p.slice) l1",
"p[0].TAC.add_line([p[2],check_variable(p[0]), check_variable(p[1]), check_variable(p[3])]) p[0].name = 'Expression' return def p_UnaryExpr(p): '''UnaryExpr",
"''' parsed.append(p.slice) p[0] = TreeNode('float_lit', p[1], 'FLOAT') return def p_FunctionLit(p):",
"p[2].data p[0].name = 'Block' return def p_ScopeStart(p): '''ScopeStart : empty",
"parsed.append(p.slice) p[0] = TreeNode('ArrayType', p[2].data, p[4].data) return def p_ArrayLength(p): '''ArrayLength",
"def p_TypeDef(p): '''TypeDef : IDENTIFIER Type ''' parsed.append(p.slice) return def",
"Expression PLUS Expression | Expression MINUS Expression | Expression OR",
"Expression OR Expression | Expression CARET Expression | Expression STAR",
"= TreeNode('decimal_lit', 0, 'INT') # l1 = len(p[1].children) # if",
"name == False: print_error(\"Variable \" + TreeNode.data + \" is",
"1) p[0].TAC.add_line(['=', check_variable(t1) , check_variable(p[2]), '']) p[0].TAC.append_TAC(p[5].data) for i in",
"s not in generated.keys(): generated[s] = [] temp = s",
"'Block' return def p_ScopeStart(p): '''ScopeStart : empty ''' parsed.append(p.slice) symbol_table.add_scope(gen('scope'))",
"TreeNode('Parameters', 0, 'None') else: p[0] = p[2] p[0].name = 'Parameters'",
"+= [node] else: node = TreeNode('IDENTIFIER', p[1], p[2].data, 1) p[0].data",
"== l2: for i in range(l1): if p[1].children[i].isLvalue == 0:",
"check_variable(p[2]), '0', l1]) p[0].TAC.append_TAC(p[3].TAC) p[0].TAC.add_line(['label', l1, '', '']) if len(p)",
"| PrimaryExpr Index | PrimaryExpr Arguments ''' parsed.append(p.slice) if len(p)",
"EQ Expression | IdentifierList EQ ExpressionList | IDENTIFIER Type EQ",
"return def p_ContinueStmt(p): '''ContinueStmt : CONTINUE IDENTIFIER ''' parsed.append(p.slice) return",
"1) p[0].TAC.add_line([check_variable(p[1]), check_variable(p[0]), check_variable(p[2]), '']) p[0].name = 'UnaryExpr' return def",
"| hex_lit ''' parsed.append(p.slice) p[0] = p[1] p[0].name = 'int_lit'",
"== False and p[1].children[i].data not in generated['temp']: print_error(\"Variable \" +",
"symbol_table.fill_next_use(three_addr_code) assembly_code = generate_assembly(three_addr_code,var_list,symbol_table) # p[0].TAC.print_code() # three_addr_code.print_code() assembly_code.print_code() #",
"FunctionName Signature | FUNC FunctionName Signature FunctionBody ''' parsed.append(p.slice) #",
"in p[2].children: p[0].TAC.add_line(['putparam', check_variable(child), '', '']) if temp != p[2].data:",
"= 'TypeLit' return def p_PointerType(p): '''PointerType : STAR Type '''",
"IMPORT LROUND ImportSpecList RROUND | IMPORT ImportSpec ''' parsed.append(p.slice) #",
"newNode = SymbolTableNode(s + '_' + child.data, child.input_type) symbol_table.add_var(newNode, s)",
"ForStmt | BreakStmt | ContinueStmt | GotoStmt | PrintIntStmt |",
"'''Arguments : LROUND RROUND | LROUND ExpressionList RROUND | LROUND",
"'', '']) if len(p) == 3: if p[2].name == 'Expression':",
"IDENTIFIER ''' parsed.append(p.slice) p[0] = TreeNode('FunctionName', p[1], 'INT', 1) return",
"\" :: Syntax error in line no \" + str(p.lineno)",
"= p[2] p[0].name = 'Parameters' return def p_ParameterList(p): '''ParameterList :",
"p[0] = TreeNode('Result', 1, 'None', 0, [p[1]]) else: p[0] =",
"yacc.yacc(debug=True, debuglog=log) input_file = sys.argv[1] import os if os.path.isfile(input_file) is",
"TreeNode('StatementList', 0, 'INT', 0, [p[1].data] + p[3].children, p[1].TAC) p[0].TAC.append_TAC(p[3].TAC) else:",
"IdentifierList | IDENTIFIER EQ Expression | IdentifierList EQ ExpressionList |",
"+ p[3].children, p[1].TAC) p[0].TAC.append_TAC(p[3].TAC) else: p[0] = TreeNode('TopLevelDeclList', 0, 'INT',",
"end\" else: print str(sys.argv[1]) + \" :: Syntax error in",
"print('Input file ' + input_file + ' does not exist')",
"ExpressionList assign_op ExpressionList | Expression assign_op Expression ''' parsed.append(p.slice) p[0]",
"'Parameters' return def p_ParameterList(p): '''ParameterList : ParameterDecl | ParameterList COMMA",
"return def p_FunctionName(p): '''FunctionName : IDENTIFIER ''' parsed.append(p.slice) p[0] =",
"len(p) == 3: TAC1 = p[1].data TAC2 = p[2].data p[0]",
"| LROUND ParameterList RROUND ''' parsed.append(p.slice) if len(p) == 3:",
"LROUND string_lit RROUND ''' p[0] = p[3] name = symbol_table.current_scope",
"return def p_Expression(p): '''Expression : UnaryExpr | Expression OR_OR Expression",
": DECIMAL_LIT ''' parsed.append(p.slice) p[0] = TreeNode('decimal_lit', p[1], 'INT') return",
"ThreeAddressCode from lexer import tokens from random import * from",
"check_variable(p[0]), '', '']) p[0].name = 'PrintIntStmt' return def p_PrintStrStmt(p): '''PrintStrStmt",
"None: p[0] = TreeNode('TopLevelDeclList', 0, 'INT', 0, [p[1]] + p[3].children,",
"[p[1]] + p[3].children, p[1].TAC) p[0].TAC.append_TAC(p[3].TAC) return def p_ExpressionBotList(p): '''ExpressionBotList :",
"range(l1): # p[0].TAC.add_line(['=', p[1].children[i], expr_list.children[i].data, '']) # else: # print_error(\"Variable",
"ExpressionBotList | Expression ''' parsed.append(p.slice) if len(p) == 2: p[0]",
"= 'ParameterList' elif len(p) == 4: p[0] = TreeNode('ParameterList', p[1].data",
"p_PrimaryExpr(p): '''PrimaryExpr : Operand | IDENTIFIER | PrimaryExpr Selector |",
"'''VarSpecTopList : VarSpec | LROUND VarSpecList RROUND ''' parsed.append(p.slice) if",
"'']) p[0].TAC.append_TAC(p[5].TAC) p[0].TAC.add_line(['label', l2, '', '']) return def p_elseTail(p): '''elseTail",
"= p[2].data) symbol_table.add_var(newNode) p[0] = TreeNode('VarSpec',p[1].data,'INT') # expr = TreeNode('Expr',",
"('left','DECIMAL_LIT'), ('left','OCTAL_LIT'), ('left','HEX_LIT'), ('left','FLOAT_LIT'), ('left','STRING_LIT'), ('left','NEWLINE'), ('left','BREAK'), ('left','CONTINUE'), ('left','RETURN'), ('left','RROUND'),",
"variable, second is 0 if variable not found # TreeNode.print_node()",
"if len(p) == 2: node = TreeNode('IDENTIFIER', p[1], 'INT', 1)",
"p[1].data, 'INT', 1, p[2].data) elif p[2].name == 'Arguments': p[0] =",
"4: l1 = gen('label') l2 = gen('label') p[0].TAC.add_line(['label', l1, '',",
"Signature ''' parsed.append(p.slice) return def p_Signature(p): '''Signature : Parameters |",
"required\") return else: if symbol_table.search_identifier(p[1].children[i].data) == False and p[1].children[i].data not",
"= SymbolTableNode(s + '_' + child.data, child.input_type) symbol_table.add_var(newNode, s) #",
"from code import Code from codegen import generate_assembly three_addr_code =",
"p[0].TAC.add_line(['func', check_variable(p[2]), str(noOfParams), '']) for child in reversed(p[3].children): p[0].TAC.add_line(['getparam', p[4].data",
"TreeNode('IDENTIFIER', p[1], 'INT', 1) p[0] = TreeNode('IdentifierBotList', 0, 'None', 0,",
"Expression RS Expression | Expression AMP Expression | Expression AND_OR",
"s) newNode = SymbolTableNode(s + '_' + child.data, child.input_type) symbol_table.add_var(newNode,",
"== 1 and symbol_table.search_identifier(p[3].data) == False and p[3].data not in",
"TreeNode('rune_lit', p[1], 'RUNE') return def p_empty(p): 'empty :' pass def",
"'''VarSpecList : empty | VarSpecList VarSpec SEMICOLON ''' return def",
"p_error(p): print p if p == None: print str(sys.argv[1]) +",
"SEMICOLON StatementList | empty ''' parsed.append(p.slice) if len(p) == 4:",
"p[0] = TreeNode('IDENTIFIER', gen('temp'), 'INT', 1) p[0].TAC.add_line([check_variable(p[1]), check_variable(p[0]), check_variable(p[2]), ''])",
"''' parsed.append(p.slice) # TODO: Ignoring package name and Imports for",
"parsed.append(p.slice) if len(p) == 3: p[0] = TreeNode('Arguments', 0, 'None')",
"else: p[0] = TreeNode('IDENTIFIER', p[3], 'INT', 1, []) p[0].TAC.add_line(['print_int', check_variable(p[0]),",
"FUNC FunctionName Signature FunctionBody ''' parsed.append(p.slice) # symbol_table.print_symbol_table() p[0] =",
"4: l1 = gen('label') p[0] = TreeNode('IfStmt', 0, 'INT') p[0].TAC.append_TAC(p[2].TAC)",
"+ '[' + TreeNode.children + ']' else: newNode = SymbolTableNode(TreeNode.data,",
"def p_ShortVarDecl(p): '''ShortVarDecl : ExpressionList ASSIGN_OP ExpressionList | Expression ASSIGN_OP",
"import SymbolTableNode import logging import ply.lex as lex import ply.yacc",
"Expression CARET Expression | Expression STAR Expression | Expression DIVIDE",
"'''ImportDeclList : ImportDecl SEMICOLON ImportDeclList | empty ''' parsed.append(p.slice) #",
"= TreeNode('StatementList', 0, 'INT') return def p_Statement(p): '''Statement : Declaration",
"| ExprCaseClauseList ExprCaseClause ''' parsed.append(p.slice) TAC1 = ThreeAddressCode() TAC2 =",
"check_variable(expr), '']) # elif len(p) == 5: # expr =",
"parsed.append(p.slice) if len(p) == 4: if p[3] != None: p[0]",
"== 'Type': p[0] = TreeNode('Result', 1, 'None', 0, [p[1]]) else:",
"p[0] = p[1] elif len(p) == 3: p[0] = TreeNode('IDENTIFIER',",
"def p_PrimaryExpr(p): '''PrimaryExpr : Operand | IDENTIFIER | PrimaryExpr Selector",
"+ str(p[2].data) + ' supplied') p[0].TAC.add_line(['call', check_variable(p[1]), str(p[2].data), '']) p[0].TAC.add_line(['return_value',",
"\" identifier(s) but \" + str(l2) + \" value(s)\") else:",
"# TODO: Ignoring package name and Imports for now p[0]",
"if symbol_table.add_identifier(p[1], size = p[2].data) == False: print_error(\"Unable to add",
"'EQ_EQ', 'NOT_EQ','LT','LT_EQ','GT','GT_EQ'), ('left', 'PLUS', 'MINUS','OR','CARET'), ('left', 'STAR', 'DIVIDE','MODULO','AMP','AND_OR','LS','RS'), ) def",
"lex import ply.yacc as yacc import sys from codegen import",
"if p[1].name == 'Type': p[0] = TreeNode('Result', 1, 'None', 0,",
"''' parsed.append(p.slice) p[0] = p[2] p[0].name = 'VarDecl' return def",
"first is the name for the variable, second is 0",
"RCURLY | SWITCH LCURLY ScopeStart ExprCaseClauseList ScopeEnd RCURLY | SWITCH",
"return def p_float_lit(p): '''float_lit : FLOAT_LIT ''' parsed.append(p.slice) p[0] =",
"for now return def p_Block(p): '''Block : LCURLY ScopeStart StatementList",
"return else: if symbol_table.search_identifier(p[1].data) == False and p[1].data not in",
"'IdentifierList': zero_val = TreeNode('decimal_lit', 0, 'INT') # l1 = len(p[1].children)",
"'''Selector : DOT IDENTIFIER ''' parsed.append(p.slice) return def p_Index(p): '''Index",
"expr = p[3] # p[0].TAC.append_TAC(p[3].TAC) # p[0].TAC.add_line(['=', check_variable(p[1]), check_variable(expr), ''])",
"check_variable(p[0]), '', '']) p[0].name = 'PrimaryExpr' return def p_Operand(p): '''Operand",
"TopLevelDecl SEMICOLON TopLevelDeclList | empty ''' parsed.append(p.slice) if len(p) ==",
"'0', l2]) p[0].TAC.append_TAC(p[3].TAC) p[0].TAC.add_line(['goto', l1, '', '']) p[0].TAC.add_line(['label', l2, '',",
"implemented yet return def p_Selector(p): '''Selector : DOT IDENTIFIER '''",
"2: if p.slice[1].type == 'IDENTIFIER': p[0] = TreeNode('IDENTIFIER', p[1], 'INT',",
"p[0] = TreeNode('StatementList', 0, 'INT', 0, [p[1].data] + p[3].children, p[1].TAC)",
"False and p[1].data not in generated['temp']: print_error(\"Variable \" + p[1].data",
"p[0] = TreeNode('IDENTIFIER', p[1].data, 'INT', 1, p[2].data) elif p[2].name ==",
"'''IfStmt : IF Expression Block | IF Expression Block ELSE",
"| LROUND VarSpecList RROUND ''' parsed.append(p.slice) if len(p) == 2:",
"# expr_list = p[3] # elif len(p) == 5: #",
"TypeLit | StandardTypes | LROUND Type RROUND ''' parsed.append(p.slice) if",
"1, []) p[0].TAC.add_line(['print_int', check_variable(p[0]), '', '']) p[0].name = 'PrintIntStmt' return",
"0, [node] + p[3].children, p[3].TAC) return def p_ExpressionList(p): '''ExpressionList :",
"+ child.data, '', '']) p[0].TAC.add_line(['stack_push', '', '', '']) p[0].TAC.append_TAC(p[4].TAC) return",
"1 and symbol_table.search_identifier(p[3].data) == False and p[3].data not in generated['temp']:",
"parsed.append(p.slice) p[0] = TreeNode('ForStmt', 0, 'INT') if len(p) == 4:",
"= SymbolTableNode(name, TreeNode.input_type) symbol_table.add_var(newNode) if TreeNode.children == []: return name",
": IDENTIFIER EQ Type ''' parsed.append(p.slice) return def p_TypeDef(p): '''TypeDef",
"('left','LROUND'), ('left', 'OR_OR'), ('left', 'AMP_AMP'), ('left', 'EQ_EQ', 'NOT_EQ','LT','LT_EQ','GT','GT_EQ'), ('left', 'PLUS',",
"'''PointerType : STAR Type ''' parsed.append(p.slice) return def p_ArrayType(p): '''ArrayType",
"if len(p) == 2: if p.slice[1].type == 'IDENTIFIER': p[0] =",
": IfStmt | Block ''' parsed.append(p.slice) p[0] = p[1] p[0].name",
"p[0] = TreeNode('FunctionName', p[1], 'INT', 1) return def p_FunctionBody(p): '''FunctionBody",
"== 4: p[0] = TreeNode('ExpressionBotList', 0, 'INT', 0, [p[1]] +",
"'name') and p[1].name == 'IdentifierList': zero_val = TreeNode('decimal_lit', 0, 'INT')",
"#!/usr/bin/python from code import TreeNode from code import ThreeAddressCode from",
"'INT') # print symbol_table.current_scope # p[4].TAC.print_code() symbol_table.add_function(p[2].data, p[3].input_type, p[3].children) if",
"p[0] = p[2] p[0].name = 'VarDecl' return def p_VarSpecTopList(p): '''VarSpecTopList",
"p_ScopeEnd(p): '''ScopeEnd : empty ''' parsed.append(p.slice) symbol_table.end_scope() return def p_StatementList(p):",
"p[1], 'INT', 1) p[0] = TreeNode('IdentifierList', 0, 'None', 0, [node]",
"1) p[0] = TreeNode('IdentifierList', 0, 'None', 0, [node] + p[3].children,",
"check_variable(p[0]), check_variable(p[2]), '']) p[0].name = 'UnaryExpr' return def p_unary_op(p): '''unary_op",
"return def p_TopLevelDeclList(p): '''TopLevelDeclList : TopLevelDecl SEMICOLON TopLevelDeclList | empty",
"AliasDecl | TypeDef ''' parsed.append(p.slice) return def p_AliasDecl(p): '''AliasDecl :",
"p[0].TAC.add_line(['ifgotoeq',check_variable(p[2]), '0', l2]) p[0].TAC.append_TAC(p[3].TAC) p[0].TAC.add_line(['goto', l1, '', '']) p[0].TAC.add_line(['label', l2,",
"= TreeNode('ExprSwitchCase', 0, 'INT') if len(p) == 3: p[0].data =",
"'''ExprSwitchCase : CASE ExpressionList | DEFAULT | CASE Expression '''",
"('left','LSQUARE'), ('left','RSQUARE'), ('left','LCURLY'), ('left','RCURLY'), ('left','DDD'), ('left','DOT'), ('left','SEMICOLON'), ('left','COLON'), ('left','SINGLE_QUOTES'), ('left','DOUBLE_QUOTES'),",
"[], 'str_list': []} def gen(s): if s not in generated.keys():",
"p[1].children, l1]) p[0].TAC.append_TAC(p[3].TAC) p[0].children = [[p[1].data,l1]] p[0].data = p[1].TAC return",
"''' parsed.append(p.slice) return def p_IdentifierList(p): '''IdentifierList : IDENTIFIER COMMA IdentifierBotList",
"COMMA ParameterDecl ''' parsed.append(p.slice) if len(p) == 2: p[0] =",
"| IdentifierList Type | IdentifierList EQ ExpressionList | IdentifierList Type",
"def p_Arguments(p): '''Arguments : LROUND RROUND | LROUND ExpressionList RROUND",
"p[0].name = 'Statement' return def p_PrintIntStmt(p): '''PrintIntStmt : PRINTLN LROUND",
"not in generated['temp']: name = symbol_table.search_identifier(TreeNode.data) if name == False:",
"ASSIGN_OP Expression ''' parsed.append(p.slice) # TODO: Add in symbol table",
"return def p_ConstSpec(p): '''ConstSpec : IDENTIFIER | IdentifierList | IDENTIFIER",
": Declaration | FunctionDecl ''' parsed.append(p.slice) p[0] = p[1] return",
"'''Expression : UnaryExpr | Expression OR_OR Expression | Expression AMP_AMP",
"'Declaration' return def p_ConstDecl(p): '''ConstDecl : CONST LROUND ConstSpecList RROUND",
"= TreeNode('IdentifierBotList', 0, 'None', 0, [node] + p[3].children, p[3].TAC) return",
"+ p[3].children, p[1].TAC) p[0].TAC.append_TAC(p[3].TAC) return def p_TypeDecl(p): '''TypeDecl : TYPE",
"l2]) p[0].TAC.append_TAC(p[3].TAC) p[0].TAC.add_line(['goto', l1, '', '']) p[0].TAC.add_line(['label', l2, '', ''])",
"def p_UnaryExpr(p): '''UnaryExpr : PrimaryExpr | unary_op UnaryExpr ''' parsed.append(p.slice)",
"= p[3] # p[0].TAC.append_TAC(p[3].TAC) # p[0].TAC.add_line(['=', check_variable(p[1]), check_variable(expr), '']) #",
"TreeNode.isLvalue == 1: if TreeNode.data not in generated['temp']: name =",
"p[1], 'OCT') return def p_hex_lit(p): '''hex_lit : HEX_LIT ''' parsed.append(p.slice)",
"p_ExprSwitchStmt(p): '''ExprSwitchStmt : SWITCH SimpleStmt SEMICOLON LCURLY ScopeStart ExprCaseClauseList ScopeEnd",
"generated['temp']: name = symbol_table.search_identifier(TreeNode.data) if name == False: name =",
"'''Type : TypeLit | StandardTypes | LROUND Type RROUND '''",
"add to SymbolTable\") return p[0].TAC.add_line([p[2], check_variable(p[1].children[i]), check_variable(p[3].children[i]), '']) else: print_error(\"Variable",
"FunctionLit ''' parsed.append(p.slice) p[0] = p[1] p[0].name = 'Literal' return",
"p_PointerType(p): '''PointerType : STAR Type ''' parsed.append(p.slice) return def p_ArrayType(p):",
"IDENTIFIER ''' parsed.append(p.slice) return def p_Index(p): '''Index : LSQUARE Expression",
"5: noOfParams = 0 for f in symbol_table.symbol_table[symbol_table.current_scope]['functions']: if f.name",
"TreeNode('StandardTypes', p[1], 'NONE') return def p_TypeLit(p): '''TypeLit : ArrayType |",
"RROUND ''' parsed.append(p.slice) return def p_TypeSpecList(p): '''TypeSpecList : empty |",
"print_error(\"Lvalue required\") p[0].name = 'IncDecStmt' return def p_ShortVarDecl(p): '''ShortVarDecl :",
"ExpressionList ''' # Insert into symbol table p[0] = TreeNode('VarSpec',",
"DIVIDE_EQ | MODULO_EQ | LS_EQ | RS_EQ | AMP_EQ |",
"IdentifierList Type EQ ExpressionList ''' # Insert into symbol table",
"= gen('label') p[0] = TreeNode('ExprCaseClause', 0, 'INT') # p[0].TAC.append_TAC(p[1].TAC) p[0].TAC.add_line(['label',",
"'ExpressionList': l1 = len(p[1].children) l2 = len(p[3].children) p[0].TAC.append_TAC(p[3].TAC) p[0].TAC.append_TAC(p[1].TAC) if",
"p[0] = TreeNode('IDENTIFIER', p[3], 'INT', 1, []) p[0].TAC.add_line(['print_int', check_variable(p[0]), '',",
"('left','NEWLINE'), ('left','BREAK'), ('left','CONTINUE'), ('left','RETURN'), ('left','RROUND'), ('left','LROUND'), ('left', 'OR_OR'), ('left', 'AMP_AMP'),",
"IDENTIFIER RROUND | PRINTLN LROUND int_lit RROUND ''' if hasattr(p[3],",
"''' p[0] = p[3] name = symbol_table.current_scope + '_' +",
"# l2 = gen('label') p[0].TAC.add_line(['label', l1, '', '']) p[0].TAC.append_TAC(p[2].TAC) p[0].TAC.add_line(['goto',",
": IDENTIFIER COMMA IdentifierBotList | IDENTIFIER ''' parsed.append(p.slice) if len(p)",
"def p_AliasDecl(p): '''AliasDecl : IDENTIFIER EQ Type ''' parsed.append(p.slice) return",
"p[0].input_type = TreeNode('Result', 0, 'None') else: p[0].input_type = p[2] return",
"ExpressionBotList ''' parsed.append(p.slice) p[0] = TreeNode('ExpressionList', 0, 'INT', 0, [p[1]]",
"parsed.append(p.slice) symbol_table.add_scope(gen('scope')) p[0] = TreeNode('ScopeStart', symbol_table.current_scope, 'None') return def p_ScopeEnd(p):",
"symbol_table = SymbolTable() var_list = [] generated = {'temp': [],",
": int_lit | float_lit | string_lit | rune_lit ''' parsed.append(p.slice)",
"False: print_error(\"Unable to add to SymbolTable\") return p[0].TAC.add_line([p[2], check_variable(p[1].children[i]), check_variable(p[3].children[i]),",
"p[1], 'INT', 1) p[0] = TreeNode('IdentifierBotList', 0, 'None', 0, [node]",
"p[2].TAC) if p[2].name == 'ExpressionList': p[0] = p[2] p[0].name =",
"# p[2].print_node() for child in p[2].children: p[0].TAC.add_line(['putparam', check_variable(child), '', ''])",
"''' parsed.append(p.slice) return def p_ConstSpecList(p): '''ConstSpecList : empty | ConstSpecList",
"| ReturnStmt | Block | IfStmt | SwitchStmt | ForStmt",
"p[1], 'OPERATOR') return def p_PrimaryExpr(p): '''PrimaryExpr : Operand | IDENTIFIER",
"FunctionType | PointerType ''' parsed.append(p.slice) p[0] = p[1] p[0].name =",
"p[0] = TreeNode('ExpressionBotList', 0, 'INT', 0, [p[1]], p[1].TAC) elif len(p)",
"= symbol_table.search_function(TreeNode.data) if name == False: print_error(\"Variable \" + TreeNode.data",
"+ \" value(s)\") else: p[1] = TreeNode('IDENTIFIER',p[1],'INT',1) if p[2].input_type !=",
"if len(p) == 4: p[0] = TreeNode('StatementList', 0, 'INT', 0,",
"'''Signature : Parameters | Parameters Result ''' parsed.append(p.slice) p[0] =",
"p[0] = p[1] else: p[0] = p[2] p[0].name = 'Operand'",
": FLOAT_LIT ''' parsed.append(p.slice) p[0] = TreeNode('float_lit', p[1], 'FLOAT') return",
"CARET_EQ | STAR_EQ | DIVIDE_EQ | MODULO_EQ | LS_EQ |",
"p[0] = p[2] p[0].name = 'Arguments' p[0].data = len(p[2].children) return",
"parsed.append(p.slice) p[0] = TreeNode('decimal_lit', p[1], 'INT') return def p_octal_lit(p): '''octal_lit",
"p[2].data, 1) p[0].data += 1 p[0].children += [node] else: p[0].data",
": IdentifierList Type | IDENTIFIER Type | Type ''' parsed.append(p.slice)",
"p[0] = TreeNode('IdentifierList', 0, 'None', 0, [node] + p[3].children, p[3].TAC)",
"'INT', 1, []) p[0].TAC.add_line(['print_int', check_variable(p[0]), '', '']) p[0].name = 'PrintIntStmt'",
"# TODO: Add in symbol table p[0] = TreeNode('ShortVarDecl', 0,",
"= 'FunctionBody' return def p_SimpleStmt(p): '''SimpleStmt : Expression | Assignment",
"p[2].print_node() for child in p[2].children: p[0].TAC.add_line(['putparam', check_variable(child), '', '']) if",
"and p[1].name == 'IdentifierList': for node in p[1].children: p[0].data +=",
"+ p[1].children[i].data + \" is undefined\") return if p[3].children[i].isLvalue ==",
"IdentifierBotList | IDENTIFIER ''' parsed.append(p.slice) if len(p) == 2: node",
"return def p_ForStmt(p): '''ForStmt : FOR Expression Block | FOR",
"| PLUS_EQ | MINUS_EQ | OR_EQ | CARET_EQ | STAR_EQ",
"else: p[0] = p[2] p[0].name = 'VarSpecTopList' return def p_VarSpecList(p):",
"return def p_Tag(p): '''Tag : string_lit ''' parsed.append(p.slice) return def",
"0, 'None', 0, [node] + p[3].children, p[3].TAC) return def p_ExpressionList(p):",
"p[0] = p[3] name = symbol_table.current_scope + '_' + gen('str_list')",
"name + '[' + TreeNode.children + ']' else: newNode =",
"RROUND ''' parsed.append(p.slice) if len(p) == 2: p[0] = p[1]",
"# p[0].TAC.add_line(['=', check_variable(p[1]), check_variable(expr), '']) # elif len(p) == 5:",
"f in symbol_table.symbol_table[symbol_table.current_scope]['functions']: if f.name == p[2].data: noOfParams = len(f.parameters)",
"= p[2].data p[0].children += [node] else: node = TreeNode('IDENTIFIER', p[1],",
"ExprCaseClauseList ScopeEnd RCURLY | SWITCH LCURLY ScopeStart ExprCaseClauseList ScopeEnd RCURLY",
"Type ''' parsed.append(p.slice) p[0] = TreeNode('ParameterDecl', 0, 'None') if len(p)",
"LROUND Type COMMA Expression RROUND ''' # print p.slice parsed.append(p.slice)",
"string_lit ''' parsed.append(p.slice) # TODO: Ignoring Imports for now return",
"range(l1): if p[1].children[i].isLvalue == 0: print_error(\"Lvalue required\") return else: if",
"elif p[1].name == 'Expression': if p[1].isLvalue == 0: print_error(\"Lvalue required\")",
"''' parsed.append(p.slice) return def p_Expression(p): '''Expression : UnaryExpr | Expression",
"TypeSpecList TypeSpec SEMICOLON ''' parsed.append(p.slice) return def p_TypeSpec(p): '''TypeSpec :",
"check_variable(p[1]), check_variable(expr), '']) # elif len(p) == 5: # expr",
"Expression | Expression STAR Expression | Expression DIVIDE Expression |",
"= 'elseTail' return def p_SwitchStmt(p): '''SwitchStmt : ExprSwitchStmt ''' parsed.append(p.slice)",
"'INT', 0, [p[1].data] + p[3].children, p[1].TAC) p[0].TAC.append_TAC(p[3].TAC) else: p[0] =",
"FUNC Signature FunctionBody ''' parsed.append(p.slice) # Anonymous Function # Not",
"check_variable(p[2]), str(noOfParams), '']) for child in reversed(p[3].children): p[0].TAC.add_line(['getparam', p[4].data +",
"else: p[1] = TreeNode('IDENTIFIER',p[1],'INT',1) if p[2].input_type != 'NONE': # array",
"= 'Literal' return def p_BasicLit(p): '''BasicLit : int_lit | float_lit",
": ExpressionList ASSIGN_OP ExpressionList | Expression ASSIGN_OP Expression ''' parsed.append(p.slice)",
"Signature FunctionBody ''' parsed.append(p.slice) # Anonymous Function # Not implemented",
"symbol_table.add_identifier(p[1].children[i]) == False: print_error(\"Unable to add to SymbolTable\") return p[0].TAC.add_line([p[2],",
"scope, funcName = \"_\".join(func[:2]), \"_\".join(func[2:]) temp = 0 for f",
"p_SwitchStmt(p): '''SwitchStmt : ExprSwitchStmt ''' parsed.append(p.slice) p[0] = TreeNode('SwitchStmt', 0,",
"FunctionBody ''' parsed.append(p.slice) # symbol_table.print_symbol_table() p[0] = TreeNode('FunctionDecl', 0, 'INT')",
"p[0].data = len(p[2].children) return def p_string_lit(p): '''string_lit : STRING_LIT '''",
"= symbol_table.search_identifier(TreeNode.data) if name == False: name = symbol_table.search_function(TreeNode.data) if",
"PACKAGE IDENTIFIER SEMICOLON ImportDeclList TopLevelDeclList ''' parsed.append(p.slice) # TODO: Ignoring",
"'''ImportSpec : DOT string_lit | IDENTIFIER string_lit | empty string_lit",
"2: p[0] = p[1] else: p[0] = p[2] p[0].name =",
"def p_ExprSwitchStmt(p): '''ExprSwitchStmt : SWITCH SimpleStmt SEMICOLON LCURLY ScopeStart ExprCaseClauseList",
"the variable, second is 0 if variable not found #",
"'0', l1]) p[0].TAC.append_TAC(p[3].TAC) p[0].TAC.add_line(['goto', l2, '', '']) p[0].TAC.add_line(['label', l1, '',",
"'INT', 1) p[0] = TreeNode('IdentifierBotList', 0, 'None', 0, [node]) elif",
"parsed.append(p.slice) return def p_TypeSpec(p): '''TypeSpec : AliasDecl | TypeDef '''",
"'''TopLevelDecl : Declaration | FunctionDecl ''' parsed.append(p.slice) p[0] = p[1]",
"return def p_assign_op(p): '''assign_op : EQ | PLUS_EQ | MINUS_EQ",
"'', '']) p[0].name = 'PrintIntStmt' return def p_PrintStrStmt(p): '''PrintStrStmt :",
"'1', 'INT') p[0] = p[1] if p[1].isLvalue == 1: if",
"p[2] p[0].name = 'Type' return def p_StandardTypes(p): '''StandardTypes : PREDEFINED_TYPES",
"\" is undefined\") return if p[3].isLvalue == 1 and symbol_table.search_identifier(p[3].data)",
"len(f.parameters) # p[2].print_node() for child in p[2].children: p[0].TAC.add_line(['putparam', check_variable(child), '',",
"def p_FieldDecl(p): '''FieldDecl : IdentifierList Type TagTop | IDENTIFIER Type",
"'Arguments': p[0] = TreeNode('IDENTIFIER', gen('temp'), 'INT', 1) p[0].TAC.append_TAC(p[1].TAC) p[0].TAC.append_TAC(p[2].TAC) #",
"MINUS_MINUS ''' parsed.append(p.slice) one_val = TreeNode('IncDecStmt', '1', 'INT') p[0] =",
"''' parsed.append(p.slice) p[0] = p[3] p[0].data = p[2].data p[0].name =",
"p[1] else: p[0] = p[2] p[0].name = 'VarSpecTopList' return def",
"TreeNode('IDENTIFIER',p[1],'INT',1) if p[2].input_type != 'NONE': # array case # p[2].print_node()",
"TODO: Ignoring Imports for now return def p_ImportSpec(p): '''ImportSpec :",
"COLON StatementList ''' parsed.append(p.slice) l1 = gen('label') p[0] = TreeNode('ExprCaseClause',",
"| Expression AND_OR Expression ''' parsed.append(p.slice) if len(p) == 2:",
"SymbolTableNode(name, p[3].input_type, parameters = [parametersNode]) symbol_table.add_var(newNode) p[0].TAC.add_line(['print_str', name, '', ''])",
"p[0].name = 'Result' return def p_Parameters(p): '''Parameters : LROUND RROUND",
"if p[1].isLvalue == 0: print_error(\"Lvalue required\") return else: if symbol_table.add_identifier(p[1])",
": IDENTIFIER ''' parsed.append(p.slice) p[0] = TreeNode('FunctionName', p[1], 'INT', 1)",
"| IDENTIFIER EQ Expression | IdentifierList EQ ExpressionList | IDENTIFIER",
"child in p[2].children: p[0].TAC.add_line(['putparam', check_variable(child), '', '']) if temp !=",
"'''TopLevelDeclList : TopLevelDecl SEMICOLON TopLevelDeclList | empty ''' parsed.append(p.slice) if",
"gen('temp'), 'INT', 1) p[0].TAC.append_TAC(p[1].TAC) p[0].TAC.append_TAC(p[2].TAC) # p[1].print_node() func = check_variable(p[1]).split(\"_\")",
"[]} def gen(s): if s not in generated.keys(): generated[s] =",
"Error: \" + err + \"! ***\" sys.exit(1) def check_variable(TreeNode):",
"def p_GotoStmt(p): '''GotoStmt : GOTO IDENTIFIER ''' parsed.append(p.slice) return def",
"TreeNode('IdentifierList', 0, 'None', 0, [node] + p[3].children, p[3].TAC) return def",
"len(expr_list.children) # p[0].TAC.append_TAC(expr_list.TAC) # p[0].TAC.append_TAC(p[1].TAC) # if l1 == l2:",
"if len(p) == 2: p[0].input_type = TreeNode('Result', 0, 'None') else:",
"= p[1] p[0].name = 'elseTail' return def p_SwitchStmt(p): '''SwitchStmt :",
"p[0].TAC.append_TAC(p[2].TAC) p[0].TAC.add_line(['ifgotoeq', check_variable(p[2]), '0', l1]) p[0].TAC.append_TAC(p[3].TAC) p[0].TAC.add_line(['label', l1, '', ''])",
"parametersNode = SymbolTableNode(p[3].data, p[3].input_type) newNode = SymbolTableNode(name, p[3].input_type, parameters =",
"SEMICOLON ''' parsed.append(p.slice) return def p_TypeSpec(p): '''TypeSpec : AliasDecl |",
"p_VarDecl(p): '''VarDecl : VAR VarSpecTopList ''' parsed.append(p.slice) p[0] = p[2]",
"symbol_table.add_var(newNode) p[0] = TreeNode('VarSpec',p[1].data,'INT') # expr = TreeNode('Expr', 0, 'NONE')",
"= p[1] else: p[0] = p[2] p[0].name = 'Operand' return",
"s) # symbol_table.print_symbol_table() if len(p) == 2: p[0].input_type = TreeNode('Result',",
"p_ParameterList(p): '''ParameterList : ParameterDecl | ParameterList COMMA ParameterDecl ''' parsed.append(p.slice)",
"ScopeEnd RCURLY ''' parsed.append(p.slice) if len(p) == 8: l1 =",
"+ str(l2) + \" value(s)\") else: p[1] = TreeNode('IDENTIFIER',p[1],'INT',1) if",
"len(p) == 4: p[0] = TreeNode('IDENTIFIER', gen('temp'), 'INT', 1, [],",
"p[1] p[0].name = 'int_lit' return def p_decimal_lit(p): '''decimal_lit : DECIMAL_LIT",
"\"*** Error: \" + err + \"! ***\" sys.exit(1) def",
"temp != p[2].data: print_error('Function ' + funcName + ' requires",
"for now return def p_ImportSpec(p): '''ImportSpec : DOT string_lit |",
"'''TagTop : empty | Tag ''' parsed.append(p.slice) return def p_Tag(p):",
"parsed.append(p.slice) p[0] = p[3] p[0].data = p[2].data p[0].name = 'Block'",
"[]) p[0].TAC.add_line(['print_int', check_variable(p[0]), '', '']) p[0].name = 'PrintIntStmt' return def",
"p[1], 'NONE') return def p_TypeLit(p): '''TypeLit : ArrayType | StructType",
"def p_TagTop(p): '''TagTop : empty | Tag ''' parsed.append(p.slice) return",
": PLUS | MINUS | NOT | CARET | STAR",
"p_AliasDecl(p): '''AliasDecl : IDENTIFIER EQ Type ''' parsed.append(p.slice) return def",
"| FieldDeclList FieldDecl SEMICOLON ''' parsed.append(p.slice) return def p_FieldDecl(p): '''FieldDecl",
"'Expression': p[0] = TreeNode('Arguments', 1, 'None', 0, [p[2]], p[2].TAC) if",
"RROUND | CONST ConstSpec ''' parsed.append(p.slice) return def p_ConstSpecList(p): '''ConstSpecList",
":' pass def p_error(p): print p if p == None:",
"l1 = gen('label') p[0] = TreeNode('ExprCaseClause', 0, 'INT') # p[0].TAC.append_TAC(p[1].TAC)",
"elif len(p) == 5: # expr_list = p[4] # l2",
"0, [node] + p[3].children, p[3].TAC) return def p_IdentifierBotList(p): '''IdentifierBotList :",
"p[2].print_node() if symbol_table.add_identifier(p[1], size = p[2].data) == False: print_error(\"Unable to",
"RSQUARE ''' parsed.append(p.slice) p[0] = p[2] p[0].name = 'Index' return",
"def p_ExprCaseClauseList(p): '''ExprCaseClauseList : empty | ExprCaseClauseList ExprCaseClause ''' parsed.append(p.slice)",
"def p_TypeDecl(p): '''TypeDecl : TYPE TypeSpecTopList ''' parsed.append(p.slice) return def",
"IF Expression Block | IF Expression Block ELSE elseTail '''",
"'''octal_lit : OCTAL_LIT ''' parsed.append(p.slice) p[0] = TreeNode('octal_lit', p[1], 'OCT')",
"CONTINUE IDENTIFIER ''' parsed.append(p.slice) return def p_GotoStmt(p): '''GotoStmt : GOTO",
"= TreeNode('IdentifierList', 0, 'None', 0, [node] + p[3].children, p[3].TAC) return",
"print_error(\"Variable \" + p[1].children[i].data + \" is undefined\") return if",
"return def p_ExpressionList(p): '''ExpressionList : Expression COMMA ExpressionBotList ''' parsed.append(p.slice)",
"False: print_error(\"Variable \" + TreeNode.data + \" is undefined\") return",
"p[0] = p[1] return def p_ImportDecl(p): '''ImportDecl : IMPORT LROUND",
"range(p[5].TAC.length()): if i in p[5].TAC.leaders[1:]: p[0].TAC.add_line(['goto', l2, '', '']) p[0].TAC.add_line(p[5].TAC.code[i])",
"def p_PrintStrStmt(p): '''PrintStrStmt : PRINTLN LROUND string_lit RROUND ''' p[0]",
"len(f.parameters) p[0].TAC.add_line(['func', check_variable(p[2]), str(noOfParams), '']) for child in reversed(p[3].children): p[0].TAC.add_line(['getparam',",
"= SymbolTableNode(name, p[3].input_type, parameters = [parametersNode]) symbol_table.add_var(newNode) p[0].TAC.add_line(['print_str', name, '',",
"return def p_Declaration(p): '''Declaration : ConstDecl | TypeDecl | VarDecl",
"''' # Insert into symbol table p[0] = TreeNode('VarSpec', 0,",
"= TreeNode('float_lit', p[1], 'FLOAT') return def p_FunctionLit(p): '''FunctionLit : FUNC",
"table p[0] = TreeNode('VarSpec', 0, 'NONE') if hasattr(p[1], 'name') and",
"in symbol_table.symbol_table[symbol_table.current_scope]['functions']: if f.name == p[2].data: noOfParams = len(f.parameters) p[0].TAC.add_line(['func',",
"p[1] p[0].name = 'ParameterList' elif len(p) == 4: p[0] =",
"name = symbol_table.current_scope + '_' + gen('str_list') parametersNode = SymbolTableNode(p[3].data,",
"p[0] = p[2] p[0].name = 'Parameters' return def p_ParameterList(p): '''ParameterList",
"StatementList ''' parsed.append(p.slice) l1 = gen('label') p[0] = TreeNode('ExprCaseClause', 0,",
"RROUND | IMPORT ImportSpec ''' parsed.append(p.slice) # TODO: Ignoring Imports",
"for now p[0] = p[5] var_list = symbol_table.make_var_list() three_addr_code =",
"FieldDeclList RCURLY ''' parsed.append(p.slice) return def p_FieldDeclList(p): '''FieldDeclList : empty",
"| Expression EQ_EQ Expression | Expression NOT_EQ Expression | Expression",
"\" + err + \"! ***\" sys.exit(1) def check_variable(TreeNode): #",
"TreeNode('IDENTIFIER', p[1], 'INT', 1) elif p[1].name == 'Operand': p[0] =",
"''' parsed.append(p.slice) p[0] = p[1] p[0].name = 'Literal' return def",
"expr = p[4] # p[0].TAC.append_TAC(p[4].TAC) # p[0].TAC.add_line(['=', check_variable(p[1]), check_variable(expr), ''])",
"'UnaryExpr' return def p_unary_op(p): '''unary_op : PLUS | MINUS |",
"if p[1].children[i].isLvalue == 0: print_error(\"Lvalue required\") return else: if symbol_table.search_identifier(p[1].children[i].data)",
"VarSpec | LROUND VarSpecList RROUND ''' parsed.append(p.slice) if len(p) ==",
"p[3].data, 'None', 0, p[1].children + p[3].children, p[1].TAC) p[0].TAC.append_TAC(p[3].TAC) return def",
"| MINUS | NOT | CARET | STAR | AMP",
"l2, '', '']) p[0].TAC.add_line(p[5].TAC.code[i]) p[0].TAC.add_line(['label', l2, '', '']) return def",
"convert_tac from code import Code from codegen import generate_assembly three_addr_code",
"' does not exist') sys.exit(1) input_code = open(input_file, 'r').read() if",
"= TreeNode('ArrayType', p[2].data, p[4].data) return def p_ArrayLength(p): '''ArrayLength : Expression",
"p[3].TAC) return def p_ExpressionList(p): '''ExpressionList : Expression COMMA ExpressionBotList '''",
"Type | IdentifierList EQ ExpressionList | IdentifierList Type EQ ExpressionList",
"parsed.append(p.slice) # TODO: Add in symbol table p[0] = TreeNode('ShortVarDecl',",
"0: print_error(\"Lvalue required\") return else: if symbol_table.add_identifier(p[1].children[i]) == False: print_error(\"Unable",
"ExprCaseClauseList ExprCaseClause ''' parsed.append(p.slice) TAC1 = ThreeAddressCode() TAC2 = ThreeAddressCode()",
"| ForStmt | BreakStmt | ContinueStmt | GotoStmt | PrintIntStmt",
"'Arguments' p[0].data = len(p[2].children) return def p_string_lit(p): '''string_lit : STRING_LIT",
"for f in symbol_table.symbol_table[scope]['functions']: if f.name == funcName: temp =",
"len(p[1].children) l2 = len(p[3].children) p[0].TAC.append_TAC(p[3].TAC) p[0].TAC.append_TAC(p[1].TAC) if l1 == l2:",
"return def p_VarSpecList(p): '''VarSpecList : empty | VarSpecList VarSpec SEMICOLON",
"''' parsed.append(p.slice) if len(p) == 2: p[0] = p[1] elif",
"return def p_Arguments(p): '''Arguments : LROUND RROUND | LROUND ExpressionList",
"elif p[2].name == 'Arguments': p[0] = TreeNode('IDENTIFIER', gen('temp'), 'INT', 1)",
"IfStmt | Block ''' parsed.append(p.slice) p[0] = p[1] p[0].name =",
"('left','CONTINUE'), ('left','RETURN'), ('left','RROUND'), ('left','LROUND'), ('left', 'OR_OR'), ('left', 'AMP_AMP'), ('left', 'EQ_EQ',",
"+ p[3].data + \" is undefined\") return # print symbol_table.current_scope",
"parsed.append(p.slice) p[0] = p[1] p[0].name = 'TypeLit' return def p_PointerType(p):",
"ImportSpec ''' parsed.append(p.slice) # TODO: Ignoring Imports for now return",
": ExpressionList assign_op ExpressionList | Expression assign_op Expression ''' parsed.append(p.slice)",
"== None: print str(sys.argv[1]) + \" :: You missed something",
"'']) # elif len(p) == 5: # expr = p[4]",
"len(p) == 2: if p.slice[1].type == 'IDENTIFIER': p[0] = TreeNode('IDENTIFIER',",
"'scope_' + str(len(generated['scope'])) symbol_table.new_scope(s) for child in p[1].children: symbol_table.add_identifier(child, s)",
"to SymbolTable\") return p[0].TAC.add_line([p[2], check_variable(p[1].children[i]), check_variable(p[3].children[i]), '']) else: print_error(\"Variable Declaration",
"+ \" value(s)\") elif p[1].name == 'Expression': if p[1].isLvalue ==",
"if hasattr(p[1], 'name') and p[1].name == 'IdentifierList': zero_val = TreeNode('decimal_lit',",
"return def p_PrintStrStmt(p): '''PrintStrStmt : PRINTLN LROUND string_lit RROUND '''",
"| IdentifierList Type EQ ExpressionList ''' # Insert into symbol",
"print_error(err): print \"*** Error: \" + err + \"! ***\"",
"!= 'NONE': # array case # p[2].print_node() if symbol_table.add_identifier(p[1], size",
"p_octal_lit(p): '''octal_lit : OCTAL_LIT ''' parsed.append(p.slice) p[0] = TreeNode('octal_lit', p[1],",
"# print p.slice parsed.append(p.slice) if len(p) == 3: p[0] =",
"p.slice parsed.append(p.slice) if len(p) == 3: p[0] = TreeNode('Arguments', 0,",
"TreeNode('ExpressionBotList', 0, 'INT', 0, [p[1]], p[1].TAC) elif len(p) == 4:",
"as yacc import sys from codegen import convert_tac from code",
"| Expression OR Expression | Expression CARET Expression | Expression",
"'''TypeSpecTopList : TypeSpec | LROUND TypeSpecList RROUND ''' parsed.append(p.slice) return",
"str(p[2].data), '']) p[0].TAC.add_line(['return_value', check_variable(p[0]), '', '']) p[0].name = 'PrimaryExpr' return",
"''' parsed.append(p.slice) p[0] = TreeNode('ArrayType', p[2].data, p[4].data) return def p_ArrayLength(p):",
"Block ''' parsed.append(p.slice) p[0] = TreeNode('ForStmt', 0, 'INT') if len(p)",
"def p_FunctionDecl(p): '''FunctionDecl : FUNC FunctionName Signature | FUNC FunctionName",
"1) p[0].TAC.append_TAC(p[1].TAC) p[0].TAC.append_TAC(p[2].TAC) # p[1].print_node() func = check_variable(p[1]).split(\"_\") scope, funcName",
"| IDENTIFIER Type EQ Expression | IdentifierList Type EQ ExpressionList",
"= p[1] if p[1].isLvalue == 1: if p[2] == '++':",
"and p[3].name == 'int_lit': p[0] = p[3] # p[0].isLvalue =",
"IDENTIFIER SEMICOLON ImportDeclList TopLevelDeclList ''' parsed.append(p.slice) # TODO: Ignoring package",
"= TreeNode('Parameters', 0, 'None') else: p[0] = p[2] p[0].name =",
"== 4: node = TreeNode('IDENTIFIER', p[1], 'INT', 1) p[0] =",
"p_Operand(p): '''Operand : Literal | LROUND Expression RROUND ''' parsed.append(p.slice)",
"p[0] = TreeNode('ExpressionList', 0, 'INT', 0, [p[1]] + p[3].children, p[1].TAC)",
"4: if p[2].name == 'Expression': p[0] = TreeNode('Arguments', 1, 'None',",
"VarSpec SEMICOLON ''' return def p_VarSpec(p): '''VarSpec : IDENTIFIER Type",
"p_SimpleStmt(p): '''SimpleStmt : Expression | Assignment | ShortVarDecl | IncDecStmt",
"p[1] elif len(p) == 3: if p[2].name == 'Index': p[0]",
"'''UnaryExpr : PrimaryExpr | unary_op UnaryExpr ''' parsed.append(p.slice) if len(p)",
"['scope_0'], 'label': [], 'str_list': []} def gen(s): if s not",
"s = 'scope_' + str(len(generated['scope'])) symbol_table.new_scope(s) for child in p[1].children:",
"'''Result : Parameters | Type ''' parsed.append(p.slice) if p[1].name ==",
"in symbol table p[0] = TreeNode('ShortVarDecl', 0, 'INT') if p[1].name",
"'''ScopeStart : empty ''' parsed.append(p.slice) symbol_table.add_scope(gen('scope')) p[0] = TreeNode('ScopeStart', symbol_table.current_scope,",
"ExpressionList | IDENTIFIER Type EQ Expression | IdentifierList Type EQ",
"return def p_empty(p): 'empty :' pass def p_error(p): print p",
"return def p_GotoStmt(p): '''GotoStmt : GOTO IDENTIFIER ''' parsed.append(p.slice) return",
"| NOT | CARET | STAR | AMP | LT_MINUS",
"\"w\", format = \"%(filename)10s:%(lineno)4d:%(message)s\" ) log = logging.getLogger() yacc.yacc(debug=True, debuglog=log)",
"# TODO: Ignoring Imports for now return def p_Block(p): '''Block",
"| empty string_lit ''' parsed.append(p.slice) # TODO: Ignoring Imports for",
"| IDENTIFIER ''' parsed.append(p.slice) if len(p) == 2: node =",
"TreeNode('Arguments', 0, 'None') if len(p) == 4: if p[2].name ==",
"'''assign_op : EQ | PLUS_EQ | MINUS_EQ | OR_EQ |",
"'']) p[0].TAC.add_line(['return_value', check_variable(p[0]), '', '']) p[0].name = 'PrimaryExpr' return def",
"+ str(p.lineno) # Standard Logger logging.basicConfig( level = logging.DEBUG, filename",
"add to SymbolTable\") return p[0].TAC.append_TAC(p[3].TAC) p[0].TAC.append_TAC(p[1].TAC) p[0].TAC.add_line([p[2], check_variable(p[1]), check_variable(p[3]), ''])",
"ImportSpec SEMICOLON ImportSpecList | empty ''' parsed.append(p.slice) # TODO: Ignoring",
"+ \" is undefined\") return TreeNode.data else: return name else:",
"p[0].name = 'PrimaryExpr' return def p_Operand(p): '''Operand : Literal |",
"| PrintIntStmt | PrintStrStmt ''' parsed.append(p.slice) p[0] = p[1] p[0].name",
"p[0].TAC.append_TAC(p[3].TAC) else: p[0] = TreeNode('TopLevelDeclList', 0, 'INT', 0, [p[1]], p[1].TAC)",
"RROUND | LROUND ParameterList RROUND ''' parsed.append(p.slice) if len(p) ==",
"'''elseTail : IfStmt | Block ''' parsed.append(p.slice) p[0] = p[1]",
"'OPERATOR') return def p_IfStmt(p): '''IfStmt : IF Expression Block |",
"SWITCH LCURLY ScopeStart ExprCaseClauseList ScopeEnd RCURLY | SWITCH Expression LCURLY",
"and symbol_table.search_identifier(p[3].children[i].data) == False and p[3].children[i].data not in generated['temp']: print_error(\"Variable",
"* l1) # elif len(p) == 4: # expr_list =",
"parsed.append(p.slice) TAC1 = ThreeAddressCode() TAC2 = ThreeAddressCode() if len(p) ==",
": GOTO IDENTIFIER ''' parsed.append(p.slice) return def p_Expression(p): '''Expression :",
"return def p_StatementList(p): '''StatementList : Statement SEMICOLON StatementList | empty",
"def p_ImportDecl(p): '''ImportDecl : IMPORT LROUND ImportSpecList RROUND | IMPORT",
"ExpressionList ASSIGN_OP ExpressionList | Expression ASSIGN_OP Expression ''' parsed.append(p.slice) #",
"p[1].name == 'IdentifierList': for node in p[1].children: p[0].data += 1",
"return def p_FieldDeclList(p): '''FieldDeclList : empty | FieldDeclList FieldDecl SEMICOLON",
"= p[3] name = symbol_table.current_scope + '_' + gen('str_list') parametersNode",
"= [] symbol_table = SymbolTable() var_list = [] generated =",
"= TreeNode('ExprCaseClauseList', TAC1, 'INT', 0, p[1].children + p[2].children, p[1].TAC) p[0].TAC.add_leader(p[0].TAC.length())",
"PRINTLN LROUND string_lit RROUND ''' p[0] = p[3] name =",
"now p[0] = p[5] var_list = symbol_table.make_var_list() three_addr_code = convert_tac(p[0].TAC)",
"| AMP_EQ | AND_OR_EQ ''' parsed.append(p.slice) p[0] = TreeNode('assign_op', p[1],",
"''' parsed.append(p.slice) p[0] = TreeNode('FunctionName', p[1], 'INT', 1) return def",
"Expression AMP Expression | Expression AND_OR Expression ''' parsed.append(p.slice) if",
": Block ''' parsed.append(p.slice) p[0] = p[1] p[0].name = 'FunctionBody'",
"Expression | Expression PLUS Expression | Expression MINUS Expression |",
"# p[1].print_node() func = check_variable(p[1]).split(\"_\") scope, funcName = \"_\".join(func[:2]), \"_\".join(func[2:])",
"p[3].children) if len(p) == 5: noOfParams = 0 for f",
"return def p_ExprSwitchStmt(p): '''ExprSwitchStmt : SWITCH SimpleStmt SEMICOLON LCURLY ScopeStart",
"'''TypeDef : IDENTIFIER Type ''' parsed.append(p.slice) return def p_Type(p): '''Type",
"VarSpecList VarSpec SEMICOLON ''' return def p_VarSpec(p): '''VarSpec : IDENTIFIER",
"4: p[0] = TreeNode('IDENTIFIER', gen('temp'), 'INT', 1, [], p[1].TAC) p[0].TAC.append_TAC(p[3].TAC)",
"= p[2] p[0].name = 'Index' return def p_Arguments(p): '''Arguments :",
"1, p[2].data) elif p[2].name == 'Arguments': p[0] = TreeNode('IDENTIFIER', gen('temp'),",
"[node] + p[3].children, p[3].TAC) return def p_IdentifierBotList(p): '''IdentifierBotList : IDENTIFIER",
"empty ''' parsed.append(p.slice) symbol_table.add_scope(gen('scope')) p[0] = TreeNode('ScopeStart', symbol_table.current_scope, 'None') return",
"parsed.append(p.slice) one_val = TreeNode('IncDecStmt', '1', 'INT') p[0] = p[1] if",
"''' parsed.append(p.slice) if len(p) == 2: p[0] = TreeNode('ExpressionBotList', 0,",
"= ( ('left','IDENTIFIER'), ('right','ASSIGN_OP'), ('left','COMMA'), ('left','LSQUARE'), ('left','RSQUARE'), ('left','LCURLY'), ('left','RCURLY'), ('left','DDD'),",
"== []: return name else: return name + '[' +",
"name = symbol_table.search_identifier(TreeNode.data) if name == False: name = symbol_table.search_function(TreeNode.data)",
"else: newNode = SymbolTableNode(TreeNode.data, TreeNode.input_type) symbol_table.add_var(newNode) return TreeNode.data else: if",
"p_ForStmt(p): '''ForStmt : FOR Expression Block | FOR Block '''",
"'''PrintIntStmt : PRINTLN LROUND IDENTIFIER RROUND | PRINTLN LROUND int_lit",
": ImportSpec SEMICOLON ImportSpecList | empty ''' parsed.append(p.slice) # TODO:",
"| Expression ''' parsed.append(p.slice) if len(p) == 2: p[0] =",
"gen('label') p[0] = TreeNode('ExprCaseClause', 0, 'INT') # p[0].TAC.append_TAC(p[1].TAC) p[0].TAC.add_line(['label', l1,",
"return def p_IdentifierBotList(p): '''IdentifierBotList : IDENTIFIER COMMA IdentifierBotList | IDENTIFIER",
"FunctionName Signature FunctionBody ''' parsed.append(p.slice) # symbol_table.print_symbol_table() p[0] = TreeNode('FunctionDecl',",
"return else: if symbol_table.search_identifier(p[1].children[i].data) == False and p[1].children[i].data not in",
"parsed.append(p.slice) p[0] = TreeNode('FunctionName', p[1], 'INT', 1) return def p_FunctionBody(p):",
"0: print_error(\"Lvalue required\") return else: if symbol_table.search_identifier(p[1].data) == False and",
"def p_IdentifierList(p): '''IdentifierList : IDENTIFIER COMMA IdentifierBotList ''' parsed.append(p.slice) node",
"'']) # p[0].TAC.add_line(['ifgotoneq', p[1].children, p[1].children, l1]) p[0].TAC.append_TAC(p[3].TAC) p[0].children = [[p[1].data,l1]]",
"def p_ContinueStmt(p): '''ContinueStmt : CONTINUE IDENTIFIER ''' parsed.append(p.slice) return def",
"'INT', 1) elif p[1].name == 'Operand': p[0] = p[1] elif",
"| rune_lit ''' parsed.append(p.slice) p[0] = p[1] p[0].name = 'BasicLit'",
"''' parsed.append(p.slice) return def p_Tag(p): '''Tag : string_lit ''' parsed.append(p.slice)",
"p[0] = p[1] p[0].name = 'elseTail' return def p_SwitchStmt(p): '''SwitchStmt",
"RS_EQ | AMP_EQ | AND_OR_EQ ''' parsed.append(p.slice) p[0] = TreeNode('assign_op',",
"| empty ''' parsed.append(p.slice) if len(p) == 4: p[0] =",
"does not exist') sys.exit(1) input_code = open(input_file, 'r').read() if input_code[len(input_code)-1]",
"Type ''' parsed.append(p.slice) if p[1].name == 'Type': p[0] = TreeNode('Result',",
"Expression AMP_AMP Expression | Expression EQ_EQ Expression | Expression NOT_EQ",
"| IDENTIFIER Type EQ Expression | IdentifierList Type | IdentifierList",
"if TreeNode.isLvalue == 1: if TreeNode.data not in generated['temp']: name",
": PRINTLN LROUND string_lit RROUND ''' p[0] = p[3] name",
"= TreeNode('IDENTIFIER',p[1],'INT',1) if p[2].input_type != 'NONE': # array case #",
"'OR_OR'), ('left', 'AMP_AMP'), ('left', 'EQ_EQ', 'NOT_EQ','LT','LT_EQ','GT','GT_EQ'), ('left', 'PLUS', 'MINUS','OR','CARET'), ('left',",
"check_variable(p[2]), '0', l1]) p[0].TAC.append_TAC(p[3].TAC) p[0].TAC.add_line(['goto', l2, '', '']) p[0].TAC.add_line(['label', l1,",
": SWITCH SimpleStmt SEMICOLON LCURLY ScopeStart ExprCaseClauseList ScopeEnd RCURLY |",
"| Expression PLUS Expression | Expression MINUS Expression | Expression",
"IDENTIFIER Type ''' parsed.append(p.slice) return def p_Type(p): '''Type : TypeLit",
"return p[0].TAC.append_TAC(p[3].TAC) p[0].TAC.append_TAC(p[1].TAC) p[0].TAC.add_line([p[2], check_variable(p[1]), check_variable(p[3]), '']) return def p_Assignment(p):",
"parsed.append(p.slice) return def p_Signature(p): '''Signature : Parameters | Parameters Result",
"input_file = sys.argv[1] import os if os.path.isfile(input_file) is False: print('Input",
"empty ''' parsed.append(p.slice) if len(p) == 4: if p[3] !=",
"''' parsed.append(p.slice) p[0] = p[1] return def p_ImportDecl(p): '''ImportDecl :",
"***\" sys.exit(1) def check_variable(TreeNode): # return 2 values. first is",
"p[0].TAC.add_line(['label', l2, '', '']) return def p_elseTail(p): '''elseTail : IfStmt",
"\"%(filename)10s:%(lineno)4d:%(message)s\" ) log = logging.getLogger() yacc.yacc(debug=True, debuglog=log) input_file = sys.argv[1]",
"p[5] var_list = symbol_table.make_var_list() three_addr_code = convert_tac(p[0].TAC) symbol_table.fill_next_use(three_addr_code) assembly_code =",
"return def p_int_lit(p): '''int_lit : decimal_lit | octal_lit | hex_lit",
"name, '', '']) p[0].name = 'PrintStrStmt' return def p_Declaration(p): '''Declaration",
"ParameterDecl | ParameterList COMMA ParameterDecl ''' parsed.append(p.slice) if len(p) ==",
"p[0].children = [[p[1].data,l1]] p[0].data = p[1].TAC return def p_ExprSwitchCase(p): '''ExprSwitchCase",
"= logging.DEBUG, filename = \"parselog.txt\", filemode = \"w\", format =",
"p[0] = TreeNode('unary_op', p[1], 'OPERATOR') return def p_PrimaryExpr(p): '''PrimaryExpr :",
"'''Block : LCURLY ScopeStart StatementList ScopeEnd RCURLY ''' parsed.append(p.slice) p[0]",
"def p_Selector(p): '''Selector : DOT IDENTIFIER ''' parsed.append(p.slice) return def",
"identifier(s) but \" + str(l2) + \" value(s)\") else: p[1]",
"if len(p) == 3: TAC1 = p[1].data TAC2 = p[2].data",
"'IdentifierList': for node in p[1].children: p[0].data += 1 node.input_type =",
"in symbol_table.symbol_table[scope]['functions']: if f.name == funcName: temp = len(f.parameters) #",
"RROUND ''' # print p.slice parsed.append(p.slice) if len(p) == 3:",
"unary_op UnaryExpr ''' parsed.append(p.slice) if len(p) == 2: p[0] =",
"for child in p[1].children: symbol_table.add_identifier(child, s) newNode = SymbolTableNode(s +",
"return def p_Block(p): '''Block : LCURLY ScopeStart StatementList ScopeEnd RCURLY",
"NOT_EQ Expression | Expression LT Expression | Expression LT_EQ Expression",
"6: l1 = gen('label') l2 = gen('label') p[0] = TreeNode('IfStmt',",
"def p_decimal_lit(p): '''decimal_lit : DECIMAL_LIT ''' parsed.append(p.slice) p[0] = TreeNode('decimal_lit',",
"Expression assign_op Expression ''' parsed.append(p.slice) p[0] = TreeNode('Assignment', 0, 'INT')",
"p[1].TAC) p[0].TAC.append_TAC(p[3].TAC) p[0].TAC.add_line([p[2],check_variable(p[0]), check_variable(p[1]), check_variable(p[3])]) p[0].name = 'Expression' return def",
"'STAR', 'DIVIDE','MODULO','AMP','AND_OR','LS','RS'), ) def p_SourceFile(p): '''SourceFile : PACKAGE IDENTIFIER SEMICOLON",
"def p_Assignment(p): '''Assignment : ExpressionList assign_op ExpressionList | Expression assign_op",
"PrimaryExpr Selector | PrimaryExpr Index | PrimaryExpr Arguments ''' parsed.append(p.slice)",
"== 2: node = TreeNode('IDENTIFIER', p[1], 'INT', 1) p[0] =",
"= 'Block' return def p_ScopeStart(p): '''ScopeStart : empty ''' parsed.append(p.slice)",
"return def p_Assignment(p): '''Assignment : ExpressionList assign_op ExpressionList | Expression",
": LROUND RROUND | LROUND ParameterList RROUND ''' parsed.append(p.slice) if",
"undefined\") return if p[3].children[i].isLvalue == 1 and symbol_table.search_identifier(p[3].children[i].data) == False",
"p[0] = TreeNode('Assignment', 0, 'INT') if p[1].name == 'ExpressionList': l1",
"= TreeNode('Result', 1, 'None', 0, [p[1]]) else: p[0] = p[1]",
"p[0].TAC.print_code() # three_addr_code.print_code() assembly_code.print_code() # symbol_table.print_symbol_table() return def p_ImportDeclList(p): '''ImportDeclList",
"TreeNode('Assignment', 0, 'INT') if p[1].name == 'ExpressionList': l1 = len(p[1].children)",
"parsed.append(p.slice) p[0] = p[1] p[0].name = 'ArrayLength' return def p_StructType(p):",
"'']) if temp != p[2].data: print_error('Function ' + funcName +",
"| string_lit | rune_lit ''' parsed.append(p.slice) p[0] = p[1] p[0].name",
"lexer import tokens from random import * from symbol_table import",
"# p[0].TAC.add_line([l2]) return def p_ReturnStmt(p): '''ReturnStmt : RETURN | RETURN",
"TreeNode.data precedence = ( ('left','IDENTIFIER'), ('right','ASSIGN_OP'), ('left','COMMA'), ('left','LSQUARE'), ('left','RSQUARE'), ('left','LCURLY'),",
"funcName + ' requires ' + str(temp) + ' parameters",
"4: if p[3] != None: p[0] = TreeNode('TopLevelDeclList', 0, 'INT',",
"p_FunctionDecl(p): '''FunctionDecl : FUNC FunctionName Signature | FUNC FunctionName Signature",
"p[0].TAC.append_TAC(p[1].TAC) p[0].TAC.add_line([p[2], check_variable(p[1]), check_variable(p[3]), '']) return def p_Assignment(p): '''Assignment :",
"p[1], 'OPERATOR') return def p_IfStmt(p): '''IfStmt : IF Expression Block",
"TreeNode('ExprCaseClauseList', TAC1, 'INT', 0, p[1].children + p[2].children, p[1].TAC) p[0].TAC.add_leader(p[0].TAC.length()) p[0].TAC.append_TAC(p[2].TAC)",
"len(p) == 4: p[0] = TreeNode('StatementList', 0, 'INT', 0, [p[1].data]",
"p[0].name = 'VarSpecTopList' return def p_VarSpecList(p): '''VarSpecList : empty |",
": IDENTIFIER Type | IDENTIFIER EQ Expression | IDENTIFIER Type",
"p[1] p[0].name = 'BasicLit' return def p_int_lit(p): '''int_lit : decimal_lit",
"def p_Expression(p): '''Expression : UnaryExpr | Expression OR_OR Expression |",
"print_error(\"Lvalue required\") return else: if symbol_table.search_identifier(p[1].data) == False and p[1].data",
"4: # expr_list = p[3] # elif len(p) == 5:",
"PointerType ''' parsed.append(p.slice) p[0] = p[1] p[0].name = 'TypeLit' return",
"parsed.append(p.slice) p[0] = p[2] p[0].name = 'VarDecl' return def p_VarSpecTopList(p):",
"== 2: p[0] = TreeNode('ReturnStmt', 0, 'None') p[0].TAC.add_line(['return', '', '',",
"DOT string_lit | IDENTIFIER string_lit | empty string_lit ''' parsed.append(p.slice)",
"for the variable, second is 0 if variable not found",
"= p[1] p[0].name = 'ArrayLength' return def p_StructType(p): '''StructType :",
"0, 'None') if len(p) == 3: if hasattr(p[1], 'name') and",
"# print symbol_table.current_scope p[0].TAC.append_TAC(p[3].TAC) p[0].TAC.append_TAC(p[1].TAC) p[0].TAC.add_line([p[2].data, check_variable(p[1]), check_variable(p[3]), '']) return",
"p_FieldDecl(p): '''FieldDecl : IdentifierList Type TagTop | IDENTIFIER Type TagTop",
"PREDEFINED_TYPES ''' parsed.append(p.slice) p[0] = TreeNode('StandardTypes', p[1], 'NONE') return def",
"in p[1].children: p[0].data += 1 node.input_type = p[2].data p[0].children +=",
"'None') p[0].TAC.add_line(['return', '', '', '']) if len(p) == 3: if",
"+ ']' else: newNode = SymbolTableNode(TreeNode.data, TreeNode.input_type) symbol_table.add_var(newNode) return TreeNode.data",
"l2: # for i in range(l1): # p[0].TAC.add_line(['=', p[1].children[i], expr_list.children[i].data,",
"gen('label') l2 = gen('label') p[0].TAC.add_line(['label', l1, '', '']) p[0].TAC.append_TAC(p[2].TAC) p[0].TAC.add_line(['ifgotoeq',check_variable(p[2]),",
"\"_\".join(func[:2]), \"_\".join(func[2:]) temp = 0 for f in symbol_table.symbol_table[scope]['functions']: if",
"p[0] = TreeNode('ExprCaseClauseList', TAC1, 'INT') return def p_ExprCaseClause(p): '''ExprCaseClause :",
"p[0].TAC.append_TAC(p[5].TAC) p[0].TAC.add_line(['label', l2, '', '']) return def p_elseTail(p): '''elseTail :",
"p[3].isLvalue == 1 and symbol_table.search_identifier(p[3].data) == False and p[3].data not",
"| LS_EQ | RS_EQ | AMP_EQ | AND_OR_EQ ''' parsed.append(p.slice)",
"''' parsed.append(p.slice) symbol_table.end_scope() return def p_StatementList(p): '''StatementList : Statement SEMICOLON",
"p[0].TAC.append_TAC(p[3].TAC) p[0].TAC.add_line([p[2],check_variable(p[0]), check_variable(p[1]), check_variable(p[3])]) p[0].name = 'Expression' return def p_UnaryExpr(p):",
"p[1] p[0].name = 'TypeLit' return def p_PointerType(p): '''PointerType : STAR",
"'''ConstDecl : CONST LROUND ConstSpecList RROUND | CONST ConstSpec '''",
"if len(p) == 4: # expr = p[3] # p[0].TAC.append_TAC(p[3].TAC)",
"p[0].TAC.append_TAC(p[3].TAC) p[0].TAC.append_TAC(p[1].TAC) p[0].TAC.add_line([p[2].data, check_variable(p[1]), check_variable(p[3]), '']) return def p_assign_op(p): '''assign_op",
"0, 'INT') if p[1].name == 'ExpressionList': l1 = len(p[1].children) l2",
"False and p[3].children[i].data not in generated['temp']: print_error(\"Variable \" + p[3].children[i].data",
": Parameters | Parameters Result ''' parsed.append(p.slice) p[0] = p[1]",
"''' parsed.append(p.slice) if p[1].name == 'Type': p[0] = TreeNode('Result', 1,",
": LCURLY ScopeStart StatementList ScopeEnd RCURLY ''' parsed.append(p.slice) p[0] =",
"symbol_table.search_identifier(p[3].children[i].data) == False and p[3].children[i].data not in generated['temp']: print_error(\"Variable \"",
"p[1].isLvalue == 1: if p[2] == '++': p[0].TAC.add_line(['+', check_variable(p[1]), check_variable(p[1]),",
"from code import TreeNode from code import ThreeAddressCode from lexer",
"p_GotoStmt(p): '''GotoStmt : GOTO IDENTIFIER ''' parsed.append(p.slice) return def p_Expression(p):",
"return def p_VarSpecTopList(p): '''VarSpecTopList : VarSpec | LROUND VarSpecList RROUND",
"| IncDecStmt ''' parsed.append(p.slice) p[0] = p[1] p[0].name = 'SimpleStmt'",
"else: p[0] = TreeNode('StatementList', 0, 'INT') return def p_Statement(p): '''Statement",
"| SwitchStmt | ForStmt | BreakStmt | ContinueStmt | GotoStmt",
"= 'Index' return def p_Arguments(p): '''Arguments : LROUND RROUND |",
"ExprCaseClauseList ScopeEnd RCURLY | SWITCH SimpleStmt SEMICOLON Expression LCURLY ScopeStart",
"string_lit ''' parsed.append(p.slice) return def p_FunctionType(p): '''FunctionType : FUNC Signature",
"p[1].name == 'ExpressionList': l1 = len(p[1].children) l2 = len(p[3].children) p[0].TAC.append_TAC(p[3].TAC)",
"TreeNode('ExprCaseClauseList', TAC1, 'INT') return def p_ExprCaseClause(p): '''ExprCaseClause : ExprSwitchCase COLON",
"Type EQ Expression | IdentifierList Type EQ ExpressionList ''' parsed.append(p.slice)",
"p[0].TAC.append_TAC(p[2].TAC) p[0].TAC.add_line(['ifgotoeq', check_variable(p[2]), '0', l1]) p[0].TAC.append_TAC(p[3].TAC) p[0].TAC.add_line(['goto', l2, '', ''])",
"if len(p) == 4: if p[3] != None: p[0] =",
"def p_ImportSpecList(p): '''ImportSpecList : ImportSpec SEMICOLON ImportSpecList | empty '''",
"p[0].name = 'TypeLit' return def p_PointerType(p): '''PointerType : STAR Type",
"= p[1] p[0].name = 'Declaration' return def p_ConstDecl(p): '''ConstDecl :",
"= TreeNode('Assignment', 0, 'INT') if p[1].name == 'ExpressionList': l1 =",
"0, [p[1]], p[1].TAC) elif len(p) == 4: p[0] = TreeNode('ExpressionBotList',",
"p_TypeSpecList(p): '''TypeSpecList : empty | TypeSpecList TypeSpec SEMICOLON ''' parsed.append(p.slice)",
"return def p_VarDecl(p): '''VarDecl : VAR VarSpecTopList ''' parsed.append(p.slice) p[0]",
"== 4: l1 = gen('label') l2 = gen('label') p[0].TAC.add_line(['label', l1,",
"elif len(p) == 4: node = TreeNode('IDENTIFIER', p[1], 'INT', 1)",
"len(p) == 8: l1 = gen('label') l2 = gen('label') p[0]",
"''' parsed.append(p.slice) p[0] = p[1] p[0].name = 'Signature' s =",
"p[1], 'INT') return def p_octal_lit(p): '''octal_lit : OCTAL_LIT ''' parsed.append(p.slice)",
"= TreeNode('ScopeStart', symbol_table.current_scope, 'None') return def p_ScopeEnd(p): '''ScopeEnd : empty",
"p[0].TAC.append_TAC(p[4].TAC) return def p_FunctionName(p): '''FunctionName : IDENTIFIER ''' parsed.append(p.slice) p[0]",
"print \"*** Error: \" + err + \"! ***\" sys.exit(1)",
"is the name for the variable, second is 0 if",
"p_TypeSpec(p): '''TypeSpec : AliasDecl | TypeDef ''' parsed.append(p.slice) return def",
"parsed.append(p.slice) node = TreeNode('IDENTIFIER', p[1], 'INT', 1) p[0] = TreeNode('IdentifierList',",
"def p_int_lit(p): '''int_lit : decimal_lit | octal_lit | hex_lit '''",
"l1, '', '']) p[0].TAC.append_TAC(p[2].TAC) p[0].TAC.add_line(['goto', l1, '', '']) # p[0].TAC.add_line([l2])",
"else: p[0].data += 1 p[0].children += [p[1]] return def p_VarDecl(p):",
"p_BasicLit(p): '''BasicLit : int_lit | float_lit | string_lit | rune_lit",
"ThreeAddressCode() assembly_code = Code() parsed = [] symbol_table = SymbolTable()",
"p[1].isLvalue == 0: print_error(\"Lvalue required\") return else: if symbol_table.add_identifier(p[1]) ==",
"expr_list = p[4] # l2 = len(expr_list.children) # p[0].TAC.append_TAC(expr_list.TAC) #",
"''' parsed.append(p.slice) p[0] = p[1] p[0].name = 'ArrayLength' return def",
"'', '']) p[0].TAC.add_line(['label', l2, '', '']) if len(p) == 3:",
"| StructType | FunctionType | PointerType ''' parsed.append(p.slice) p[0] =",
"'', '']) p[0].TAC.add_line(['stack_push', '', '', '']) p[0].TAC.append_TAC(p[4].TAC) return def p_FunctionName(p):",
"elif p[1].name == 'Operand': p[0] = p[1] elif len(p) ==",
": ImportDecl SEMICOLON ImportDeclList | empty ''' parsed.append(p.slice) # TODO:",
"'''Parameters : LROUND RROUND | LROUND ParameterList RROUND ''' parsed.append(p.slice)",
"p[0].TAC.append_TAC(p[2].TAC) p[0].TAC.add_line(['goto', l1, '', '']) # p[0].TAC.add_line([l2]) return def p_ReturnStmt(p):",
": Expression PLUS_PLUS | Expression MINUS_MINUS ''' parsed.append(p.slice) one_val =",
"| IDENTIFIER EQ Expression | IDENTIFIER Type EQ Expression |",
"p[0] = TreeNode('SwitchStmt', 0, 'INT', 0, [], p[1].TAC) return def",
"p[0] = TreeNode('ArrayType', p[2].data, p[4].data) return def p_ArrayLength(p): '''ArrayLength :",
"\" + str(l2) + \" value(s)\") elif p[1].name == 'Expression':",
"TreeNode.input_type) symbol_table.add_var(newNode) return TreeNode.data else: if TreeNode.input_type != 'STRING': return",
"| IDENTIFIER string_lit | empty string_lit ''' parsed.append(p.slice) # TODO:",
"p[3].name == 'int_lit': p[0] = p[3] # p[0].isLvalue = 0",
"p[0] = p[2] p[0].name = 'Type' return def p_StandardTypes(p): '''StandardTypes",
"''' parsed.append(p.slice) # symbol_table.print_symbol_table() p[0] = TreeNode('FunctionDecl', 0, 'INT') #",
"| Block ''' parsed.append(p.slice) p[0] = p[1] p[0].name = 'elseTail'",
"'', '']) return def p_BreakStmt(p): '''BreakStmt : BREAK IDENTIFIER '''",
"'''Statement : Declaration | SimpleStmt | ReturnStmt | Block |",
"generated['temp']: print_error(\"Variable \" + p[3].children[i].data + \" is undefined\") return",
"| PrintStrStmt ''' parsed.append(p.slice) p[0] = p[1] p[0].name = 'Statement'",
"| VarSpecList VarSpec SEMICOLON ''' return def p_VarSpec(p): '''VarSpec :",
"RROUND ''' if hasattr(p[3], 'name') and p[3].name == 'int_lit': p[0]",
"'', '']) for i in range(p[5].TAC.length()): if i in p[5].TAC.leaders[1:]:",
"return TreeNode.data else: if TreeNode.input_type != 'STRING': return TreeNode.data else:",
"'''ParameterDecl : IdentifierList Type | IDENTIFIER Type | Type '''",
"'', '']) p[0].name = 'PrimaryExpr' return def p_Operand(p): '''Operand :",
"STRUCT LCURLY FieldDeclList RCURLY ''' parsed.append(p.slice) return def p_FieldDeclList(p): '''FieldDeclList",
"= 'int_lit' return def p_decimal_lit(p): '''decimal_lit : DECIMAL_LIT ''' parsed.append(p.slice)",
"p[1].children[i].isLvalue == 0: print_error(\"Lvalue required\") return else: if symbol_table.search_identifier(p[1].children[i].data) ==",
"p_Expression(p): '''Expression : UnaryExpr | Expression OR_OR Expression | Expression",
"def check_variable(TreeNode): # return 2 values. first is the name",
"''' return def p_VarSpec(p): '''VarSpec : IDENTIFIER Type | IDENTIFIER",
"now return def p_ImportSpecList(p): '''ImportSpecList : ImportSpec SEMICOLON ImportSpecList |",
"check_variable(p[1]), check_variable(p[1]), one_val.data]) else: print_error(\"Lvalue required\") p[0].name = 'IncDecStmt' return",
"p[2].data p[0].children += [node] else: node = TreeNode('IDENTIFIER', p[1], p[2].data,",
"TODO: Add in symbol table p[0] = TreeNode('ShortVarDecl', 0, 'INT')",
"'''ConstSpec : IDENTIFIER | IdentifierList | IDENTIFIER EQ Expression |",
"VarDecl ''' parsed.append(p.slice) p[0] = p[1] p[0].name = 'Declaration' return",
"MINUS | NOT | CARET | STAR | AMP |",
"check_variable(p[1]).split(\"_\") scope, funcName = \"_\".join(func[:2]), \"_\".join(func[2:]) temp = 0 for",
"Expression | Expression LT Expression | Expression LT_EQ Expression |",
"TreeNode('float_lit', p[1], 'FLOAT') return def p_FunctionLit(p): '''FunctionLit : FUNC Signature",
"p[0].data += 1 node.input_type = p[2].data p[0].children += [node] else:",
"1 p[0].children += [p[1]] return def p_VarDecl(p): '''VarDecl : VAR",
"MINUS_EQ | OR_EQ | CARET_EQ | STAR_EQ | DIVIDE_EQ |",
"''' parsed.append(p.slice) p[0] = p[1] p[0].name = 'TypeLit' return def",
"p[4].data + '_' + child.data, '', '']) p[0].TAC.add_line(['stack_push', '', '',",
"{'temp': [], 'scope': ['scope_0'], 'label': [], 'str_list': []} def gen(s):",
"| Parameters Result ''' parsed.append(p.slice) p[0] = p[1] p[0].name =",
"len(p) == 2: p[0] = p[1] elif len(p) == 4:",
"print_error(\"Lvalue required\") return else: if symbol_table.add_identifier(p[1]) == False: print_error(\"Unable to",
"def p_BasicLit(p): '''BasicLit : int_lit | float_lit | string_lit |",
"p[0] = p[1] p[0].name = 'SimpleStmt' return def p_IncDecStmt(p): '''IncDecStmt",
"parsed.append(p.slice) return def p_IdentifierList(p): '''IdentifierList : IDENTIFIER COMMA IdentifierBotList '''",
": PACKAGE IDENTIFIER SEMICOLON ImportDeclList TopLevelDeclList ''' parsed.append(p.slice) # TODO:",
"'''AliasDecl : IDENTIFIER EQ Type ''' parsed.append(p.slice) return def p_TypeDef(p):",
"p[2].name == 'Expression': p[0] = TreeNode('Arguments', 1, 'None', 0, [p[2]],",
"TypeDecl | VarDecl ''' parsed.append(p.slice) p[0] = p[1] p[0].name =",
"COMMA IdentifierBotList | IDENTIFIER ''' parsed.append(p.slice) if len(p) == 2:",
"4: p[0] = TreeNode('ExpressionBotList', 0, 'INT', 0, [p[1]] + p[3].children,",
"p[3].children, p[1].TAC) p[0].TAC.append_TAC(p[3].TAC) else: p[0] = TreeNode('StatementList', 0, 'INT') return",
"the name for the variable, second is 0 if variable",
"| RETURN ExpressionList ''' parsed.append(p.slice) if len(p) == 2: p[0]",
"2: p[0] = p[1] elif len(p) == 4: p[0] =",
": CONTINUE IDENTIFIER ''' parsed.append(p.slice) return def p_GotoStmt(p): '''GotoStmt :",
"Declaration | SimpleStmt | ReturnStmt | Block | IfStmt |",
"= ThreeAddressCode() if len(p) == 3: TAC1 = p[1].data TAC2",
"= TreeNode('octal_lit', p[1], 'OCT') return def p_hex_lit(p): '''hex_lit : HEX_LIT",
"p_Block(p): '''Block : LCURLY ScopeStart StatementList ScopeEnd RCURLY ''' parsed.append(p.slice)",
"PrimaryExpr | unary_op UnaryExpr ''' parsed.append(p.slice) if len(p) == 2:",
"TreeNode('ParameterList', p[1].data + p[3].data, 'None', 0, p[1].children + p[3].children, p[1].TAC)",
"IF Expression Block ELSE elseTail ''' parsed.append(p.slice) if len(p) ==",
"import sys from codegen import convert_tac from code import Code",
"# expr = TreeNode('Expr', 0, 'NONE') # if len(p) ==",
"SymbolTable from symbol_table import SymbolTableNode import logging import ply.lex as",
"== 3: if p[2].name == 'Index': p[0] = TreeNode('IDENTIFIER', p[1].data,",
"l2, '', '']) for i in range(p[5].TAC.length()): if i in",
"= [] temp = s + '_' + str(len(generated[s])) generated[s]",
"def p_VarSpec(p): '''VarSpec : IDENTIFIER Type | IDENTIFIER EQ Expression",
": STRUCT LCURLY FieldDeclList RCURLY ''' parsed.append(p.slice) return def p_FieldDeclList(p):",
"= p[1] elif len(p) == 3: if p[2].name == 'Index':",
"parsed.append(p.slice) # TODO: Ignoring package name and Imports for now",
"sys.argv[1] import os if os.path.isfile(input_file) is False: print('Input file '",
"'INT', 0, [p[1]], p[1].TAC) return def p_TopLevelDecl(p): '''TopLevelDecl : Declaration",
"= TreeNode('Expr', 0, 'NONE') # if len(p) == 4: #",
"p[3].children, p[3].TAC) return def p_IdentifierBotList(p): '''IdentifierBotList : IDENTIFIER COMMA IdentifierBotList",
"p[0] = p[3] p[0].data = p[2].data p[0].name = 'Block' return",
"if symbol_table.add_identifier(p[1]) == False: print_error(\"Unable to add to SymbolTable\") return",
"p[1].data TAC2 = p[2].data p[0] = TreeNode('ExprCaseClauseList', TAC1, 'INT', 0,",
"'''Operand : Literal | LROUND Expression RROUND ''' parsed.append(p.slice) if",
"0, 'None') else: p[0].input_type = p[2] return def p_Result(p): '''Result",
"Expression | IdentifierList EQ ExpressionList | IDENTIFIER Type EQ Expression",
"| LROUND TypeSpecList RROUND ''' parsed.append(p.slice) return def p_TypeSpecList(p): '''TypeSpecList",
"parsed.append(p.slice) l1 = gen('label') p[0] = TreeNode('ExprCaseClause', 0, 'INT') #",
"'ReturnStmt' p[0].TAC.add_line(['return', check_variable(p[2]), '', '']) return def p_BreakStmt(p): '''BreakStmt :",
"exist') sys.exit(1) input_code = open(input_file, 'r').read() if input_code[len(input_code)-1] != '\\n':",
"check_variable(p[3]), '']) return def p_assign_op(p): '''assign_op : EQ | PLUS_EQ",
"+ str(len(generated[s])) generated[s] += [temp] return temp def print_error(err): print",
"parsed.append(p.slice) # TODO: Ignoring Imports for now return def p_Block(p):",
"# symbol_table.print_symbol_table() p[0] = TreeNode('FunctionDecl', 0, 'INT') # print symbol_table.current_scope",
"p[0].TAC.add_line(['=', check_variable(t1) , check_variable(p[2]), '']) p[0].TAC.append_TAC(p[5].data) for i in range(len(p[5].children)):",
"'''unary_op : PLUS | MINUS | NOT | CARET |",
"RROUND | LROUND Type COMMA ExpressionList RROUND | LROUND Type",
"\" :: You missed something at the end\" else: print",
"TreeNode('FunctionName', p[1], 'INT', 1) return def p_FunctionBody(p): '''FunctionBody : Block",
"Declaration | FunctionDecl ''' parsed.append(p.slice) p[0] = p[1] return def",
"p[0].TAC.add_line([p[2].data, check_variable(p[1].children[i]), check_variable(p[3].children[i]), '']) else: print_error(\"Variable Declaration mismatch: \" +",
"# Not implemented yet return def p_Selector(p): '''Selector : DOT",
"LCURLY FieldDeclList RCURLY ''' parsed.append(p.slice) return def p_FieldDeclList(p): '''FieldDeclList :",
"if p == None: print str(sys.argv[1]) + \" :: You",
"parsed.append(p.slice) p[0] = TreeNode('SwitchStmt', 0, 'INT', 0, [], p[1].TAC) return",
"p[1].children: symbol_table.add_identifier(child, s) newNode = SymbolTableNode(s + '_' + child.data,",
"def p_TopLevelDecl(p): '''TopLevelDecl : Declaration | FunctionDecl ''' parsed.append(p.slice) p[0]",
"'''SourceFile : PACKAGE IDENTIFIER SEMICOLON ImportDeclList TopLevelDeclList ''' parsed.append(p.slice) #",
"'''TypeLit : ArrayType | StructType | FunctionType | PointerType '''",
"LROUND VarSpecList RROUND ''' parsed.append(p.slice) if len(p) == 2: p[0]",
"parsed.append(p.slice) p[0] = p[1] p[0].name = 'BasicLit' return def p_int_lit(p):",
"p_Declaration(p): '''Declaration : ConstDecl | TypeDecl | VarDecl ''' parsed.append(p.slice)",
"'''Index : LSQUARE Expression RSQUARE ''' parsed.append(p.slice) p[0] = p[2]",
"parsed.append(p.slice) p[0] = p[1] p[0].name = 'int_lit' return def p_decimal_lit(p):",
"Expression MINUS_MINUS ''' parsed.append(p.slice) one_val = TreeNode('IncDecStmt', '1', 'INT') p[0]",
"Expression COMMA ExpressionBotList ''' parsed.append(p.slice) p[0] = TreeNode('ExpressionList', 0, 'INT',",
"''' parsed.append(p.slice) return def p_FieldDecl(p): '''FieldDecl : IdentifierList Type TagTop",
"ExpressionList | Expression ASSIGN_OP Expression ''' parsed.append(p.slice) # TODO: Add",
"def p_Operand(p): '''Operand : Literal | LROUND Expression RROUND '''",
"= p[1] else: p[0] = p[2] p[0].name = 'VarSpecTopList' return",
"# else: # print_error(\"Variable Declaration mismatch: \" + str(l1) +",
"'']) p[0].TAC.append_TAC(p[4].TAC) return def p_FunctionName(p): '''FunctionName : IDENTIFIER ''' parsed.append(p.slice)",
"p[0] = TreeNode('hex_lit', p[1], 'HEX') return def p_float_lit(p): '''float_lit :",
"ply.lex as lex import ply.yacc as yacc import sys from",
"check_variable(p[1]), check_variable(p[3]), '']) return def p_Assignment(p): '''Assignment : ExpressionList assign_op",
"parsed.append(p.slice) p[0] = p[2] p[0].name = 'Index' return def p_Arguments(p):",
"= ThreeAddressCode() assembly_code = Code() parsed = [] symbol_table =",
"''' parsed.append(p.slice) p[0] = TreeNode('octal_lit', p[1], 'OCT') return def p_hex_lit(p):",
"| ParameterList COMMA ParameterDecl ''' parsed.append(p.slice) if len(p) == 2:",
"'''ExpressionList : Expression COMMA ExpressionBotList ''' parsed.append(p.slice) p[0] = TreeNode('ExpressionList',",
"p_PrintStrStmt(p): '''PrintStrStmt : PRINTLN LROUND string_lit RROUND ''' p[0] =",
"if len(p) == 2: p[0] = p[1] else: p[0] =",
"from codegen import generate_assembly three_addr_code = ThreeAddressCode() assembly_code = Code()",
"# if len(p) == 3: # expr_list = TreeNode('Expr_List', 0,",
"SEMICOLON Expression LCURLY ScopeStart ExprCaseClauseList ScopeEnd RCURLY | SWITCH LCURLY",
"TreeNode('Result', 0, 'None') else: p[0].input_type = p[2] return def p_Result(p):",
"return def p_ExprCaseClauseList(p): '''ExprCaseClauseList : empty | ExprCaseClauseList ExprCaseClause '''",
"# p[0].TAC.append_TAC(p[1].TAC) p[0].TAC.add_line(['label', l1, '', '']) # p[0].TAC.add_line(['ifgotoneq', p[1].children, p[1].children,",
": FUNC Signature FunctionBody ''' parsed.append(p.slice) # Anonymous Function #",
"Expression | Expression MINUS Expression | Expression OR Expression |",
"generated[s] += [temp] return temp def print_error(err): print \"*** Error:",
"import * from symbol_table import SymbolTable from symbol_table import SymbolTableNode",
"TreeNode('ExpressionBotList', 0, 'INT', 0, [p[1]] + p[3].children, p[1].TAC) p[0].TAC.append_TAC(p[3].TAC) return",
"1: if p[2] == '++': p[0].TAC.add_line(['+', check_variable(p[1]), check_variable(p[1]), one_val.data]) else:",
"gen('label') p[0] = TreeNode('ExprSwitchStmt', 0, 'INT') p[0].TAC.append_TAC(p[2].TAC) t1 = TreeNode('IDENTIFIER',",
"= p[2].data p[0].TAC = p[2].TAC return def p_ForStmt(p): '''ForStmt :",
"else: p[0].input_type = p[2] return def p_Result(p): '''Result : Parameters",
"TreeNode('IDENTIFIER', gen('temp'), 'INT', 1) p[0].TAC.add_line([check_variable(p[1]), check_variable(p[0]), check_variable(p[2]), '']) p[0].name =",
"LROUND Type RROUND | LROUND Type COMMA ExpressionList RROUND |",
"[[p[1].data,l1]] p[0].data = p[1].TAC return def p_ExprSwitchCase(p): '''ExprSwitchCase : CASE",
": empty ''' parsed.append(p.slice) symbol_table.add_scope(gen('scope')) p[0] = TreeNode('ScopeStart', symbol_table.current_scope, 'None')",
"p[0].name = 'Parameters' return def p_ParameterList(p): '''ParameterList : ParameterDecl |",
"AMP_AMP Expression | Expression EQ_EQ Expression | Expression NOT_EQ Expression",
"LCURLY ScopeStart ExprCaseClauseList ScopeEnd RCURLY | SWITCH Expression LCURLY ScopeStart",
"return def p_FunctionType(p): '''FunctionType : FUNC Signature ''' parsed.append(p.slice) return",
"check_variable(t1), p[5].children[i][0], p[5].children[i][1]]) p[0].TAC.add_line(['goto', l2, '', '']) for i in",
"octal_lit | hex_lit ''' parsed.append(p.slice) p[0] = p[1] p[0].name =",
"| STAR_EQ | DIVIDE_EQ | MODULO_EQ | LS_EQ | RS_EQ",
"ASSIGN_OP ExpressionList | Expression ASSIGN_OP Expression ''' parsed.append(p.slice) # TODO:",
"p[0].TAC.add_line(['ifgotoeq', check_variable(p[2]), '0', l1]) p[0].TAC.append_TAC(p[3].TAC) p[0].TAC.add_line(['label', l1, '', '']) if",
"as lex import ply.yacc as yacc import sys from codegen",
"p[0].TAC.add_line(['getparam', p[4].data + '_' + child.data, '', '']) p[0].TAC.add_line(['stack_push', '',",
"'', '']) # p[0].TAC.add_line(['ifgotoneq', p[1].children, p[1].children, l1]) p[0].TAC.append_TAC(p[3].TAC) p[0].children =",
"parsed.append(p.slice) if p[1].name == 'Type': p[0] = TreeNode('Result', 1, 'None',",
"'ExpressionList': p[0] = p[2] p[0].name = 'Arguments' p[0].data = len(p[2].children)",
"= p[1] p[0].name = 'Statement' return def p_PrintIntStmt(p): '''PrintIntStmt :",
"CONST LROUND ConstSpecList RROUND | CONST ConstSpec ''' parsed.append(p.slice) return",
": AliasDecl | TypeDef ''' parsed.append(p.slice) return def p_AliasDecl(p): '''AliasDecl"
] |
[
"in progressbar.progressbar(range(args.num_frames)): tg = n / (args.num_frames - 1) t",
"red = im green = 1 - im blue =",
"* args.height) cut_buf = ffi.new(\"double[]\", max_iter) fixed_seed = Random(1) for",
"video duration\") args.aspect = args.width / args.height args.num_frames = int(args.video_duration",
"255).astype('uint8') def do_render(args, writer): max_iter = 32 im_buf = ffi.new(\"double[]\",",
"random(channel.shape)*dither for channel in rgb] if indexing == 'ij': rgb",
"args.video_quality: args.video_quality = 10 writer = imageio.get_writer(args.outfile, fps=args.framerate, quality=args.video_quality, macro_block_size=1)",
"indexing == 'ij': rgb = [channel.T for channel in rgb]",
"if not args.video_duration: raise ValueError(\"Missing video duration\") args.aspect = args.width",
"= 1 - bg red = im green = 1",
"args.framerate = 24 if not args.video_quality: args.video_quality = 10 writer",
"parser = argparse.ArgumentParser(description='Render audio samples') parser.add_argument('outfile', type=str, help='Output file name')",
"blue + 0.2*green red = 0.1 + 0.8*red + green**3",
"\"40p\": (71, 40), } def make_video_frame(rgb, indexing='ij', dither=1.0/256.0): if dither:",
"ValueError(\"Missing video duration\") args.aspect = args.width / args.height args.num_frames =",
"type=int, help='Video quality factor') parser.add_argument('--video-duration', type=float, help='Duration of video to",
"if not args.framerate: args.framerate = 24 if not args.video_quality: args.video_quality",
"parser.parse_args() if not args.framerate: args.framerate = 24 if not args.video_quality:",
"'__main__': parser = argparse.ArgumentParser(description='Render audio samples') parser.add_argument('outfile', type=str, help='Output file",
"green**3 green = 0.2 + 0.21*green frame = make_video_frame([red*fg +",
"(142, 80), \"40p\": (71, 40), } def make_video_frame(rgb, indexing='ij', dither=1.0/256.0):",
"parser.add_argument('--framerate', type=int, help='Video frame rate') parser.add_argument('--video-quality', type=int, help='Video quality factor')",
"ValueError(\"Invalid or missing resolution\") if not args.video_duration: raise ValueError(\"Missing video",
"= n / (args.num_frames - 1) t = tg lib.mandelbrot(im_buf,",
"frame rate') parser.add_argument('--video-quality', type=int, help='Video quality factor') parser.add_argument('--video-duration', type=float, help='Duration",
"missing resolution\") if not args.video_duration: raise ValueError(\"Missing video duration\") args.aspect",
"file name') parser.add_argument('--params', type=str, help='Parameter YAML file name') parser.add_argument('--resolution', choices=RESOLUTIONS.keys(),",
"tg lib.mandelbrot(im_buf, args.width, args.height, 0.7, 0.8, 3.5, t-20, cut_buf, max_iter)",
"0.2 + 0.21*green frame = make_video_frame([red*fg + 0.15*bg, green*fg +",
"height if (not args.width) or (not args.height): raise ValueError(\"Invalid or",
"of video to render in seconds') args = parser.parse_args() if",
"im /= im.max() fg = 1 - bg red =",
"Random(1) for i in range(max_iter): cut_buf[i] = i*fixed_seed.random() for n",
"+ 0.1*bg], indexing=None) writer.append_data(frame) if __name__ == '__main__': parser =",
"ffi, lib from pylab import * from random import Random",
"simulation grid width', metavar='W') parser.add_argument('--height', type=int, help='Video and simulation grid",
"RESOLUTIONS[args.resolution] if not args.width: args.width = width if not args.height:",
"i in range(max_iter): cut_buf[i] = i*fixed_seed.random() for n in progressbar.progressbar(range(args.num_frames)):",
"not args.framerate: args.framerate = 24 if not args.video_quality: args.video_quality =",
"+ green**3 green = 0.2 + 0.21*green frame = make_video_frame([red*fg",
"- bg red = im green = 1 - im",
"name') parser.add_argument('--params', type=str, help='Parameter YAML file name') parser.add_argument('--resolution', choices=RESOLUTIONS.keys(), help='Video",
"ffi.new(\"double[]\", args.width * args.height) cut_buf = ffi.new(\"double[]\", max_iter) fixed_seed =",
"help='Video quality factor') parser.add_argument('--video-duration', type=float, help='Duration of video to render",
"import progressbar from _routines import ffi, lib from pylab import",
"\"160p\": (284, 160), \"80p\": (142, 80), \"40p\": (71, 40), }",
"parser.add_argument('--params', type=str, help='Parameter YAML file name') parser.add_argument('--resolution', choices=RESOLUTIONS.keys(), help='Video and",
"(426, 240), \"160p\": (284, 160), \"80p\": (142, 80), \"40p\": (71,",
"= stack(rgb, axis=-1) frame = clip(frame, 0.0, 1.0) return (frame",
"type=str, help='Output file name') parser.add_argument('--params', type=str, help='Parameter YAML file name')",
"type=float, help='Duration of video to render in seconds') args =",
"metavar='H') parser.add_argument('--framerate', type=int, help='Video frame rate') parser.add_argument('--video-quality', type=int, help='Video quality",
"file name') parser.add_argument('--resolution', choices=RESOLUTIONS.keys(), help='Video and simulation grid resolution') parser.add_argument('--width',",
"/= im.max() fg = 1 - bg red = im",
"= 4*im*(1-im) blue = blue + 0.2*green red = 0.1",
"not args.width: args.width = width if not args.height: args.height =",
"= 0.1 + 0.8*red + green**3 green = 0.2 +",
"type=int, help='Video and simulation grid width', metavar='W') parser.add_argument('--height', type=int, help='Video",
"args.height = height if (not args.width) or (not args.height): raise",
"- im blue = 4*im*(1-im) blue = blue + 0.2*green",
"\"80p\": (142, 80), \"40p\": (71, 40), } def make_video_frame(rgb, indexing='ij',",
"max_iter) im = array(list(im_buf)).reshape(args.height, args.width) # for i in range(max_iter):",
"simulation grid height', metavar='H') parser.add_argument('--framerate', type=int, help='Video frame rate') parser.add_argument('--video-quality',",
"writer.append_data(frame) if __name__ == '__main__': parser = argparse.ArgumentParser(description='Render audio samples')",
"= width if not args.height: args.height = height if (not",
"raise ValueError(\"Invalid or missing resolution\") if not args.video_duration: raise ValueError(\"Missing",
"*= 0.05**args.dt bg = (im < 0) im /= im.max()",
"0.8*red + green**3 green = 0.2 + 0.21*green frame =",
"range(max_iter): cut_buf[i] = i*fixed_seed.random() for n in progressbar.progressbar(range(args.num_frames)): tg =",
"pylab import * from random import Random RESOLUTIONS = {",
"3.5, t-20, cut_buf, max_iter) im = array(list(im_buf)).reshape(args.height, args.width) # for",
"or (not args.height): raise ValueError(\"Invalid or missing resolution\") if not",
"writer): max_iter = 32 im_buf = ffi.new(\"double[]\", args.width * args.height)",
"1.0) return (frame * 255).astype('uint8') def do_render(args, writer): max_iter =",
"make_video_frame(rgb, indexing='ij', dither=1.0/256.0): if dither: rgb = [channel + random(channel.shape)*dither",
"name') parser.add_argument('--resolution', choices=RESOLUTIONS.keys(), help='Video and simulation grid resolution') parser.add_argument('--width', type=int,",
"type=int, help='Video and simulation grid height', metavar='H') parser.add_argument('--framerate', type=int, help='Video",
"= clip(frame, 0.0, 1.0) return (frame * 255).astype('uint8') def do_render(args,",
"resolution') parser.add_argument('--width', type=int, help='Video and simulation grid width', metavar='W') parser.add_argument('--height',",
"video to render in seconds') args = parser.parse_args() if not",
"= ffi.new(\"double[]\", args.width * args.height) cut_buf = ffi.new(\"double[]\", max_iter) fixed_seed",
"+ 0.2*green red = 0.1 + 0.8*red + green**3 green",
"im = array(list(im_buf)).reshape(args.height, args.width) # for i in range(max_iter): #",
"\"480p\": (854, 480), \"360p\": (640, 360), \"240p\": (426, 240), \"160p\":",
"(2560, 1440), \"1080p\": (1920, 1080), \"720p\": (1280, 720), \"480p\": (854,",
"max_iter = 32 im_buf = ffi.new(\"double[]\", args.width * args.height) cut_buf",
"im.max() fg = 1 - bg red = im green",
"0) im /= im.max() fg = 1 - bg red",
"= im green = 1 - im blue = 4*im*(1-im)",
"t-20, cut_buf, max_iter) im = array(list(im_buf)).reshape(args.height, args.width) # for i",
"blue*fg + 0.1*bg], indexing=None) writer.append_data(frame) if __name__ == '__main__': parser",
"if dither: rgb = [channel + random(channel.shape)*dither for channel in",
"24 if not args.video_quality: args.video_quality = 10 writer = imageio.get_writer(args.outfile,",
"= 32 im_buf = ffi.new(\"double[]\", args.width * args.height) cut_buf =",
"rgb = [channel + random(channel.shape)*dither for channel in rgb] if",
"to render in seconds') args = parser.parse_args() if not args.framerate:",
"= ffi.new(\"double[]\", max_iter) fixed_seed = Random(1) for i in range(max_iter):",
"and simulation grid height', metavar='H') parser.add_argument('--framerate', type=int, help='Video frame rate')",
"(frame * 255).astype('uint8') def do_render(args, writer): max_iter = 32 im_buf",
"writer = imageio.get_writer(args.outfile, fps=args.framerate, quality=args.video_quality, macro_block_size=1) # Compute derived parameters",
"args.width, args.height, 0.7, 0.8, 3.5, t-20, cut_buf, max_iter) im =",
"parser.add_argument('--video-duration', type=float, help='Duration of video to render in seconds') args",
"help='Duration of video to render in seconds') args = parser.parse_args()",
"indexing='ij', dither=1.0/256.0): if dither: rgb = [channel + random(channel.shape)*dither for",
"args.width: args.width = width if not args.height: args.height = height",
"help='Video and simulation grid height', metavar='H') parser.add_argument('--framerate', type=int, help='Video frame",
"argparse.ArgumentParser(description='Render audio samples') parser.add_argument('outfile', type=str, help='Output file name') parser.add_argument('--params', type=str,",
"stack(rgb, axis=-1) frame = clip(frame, 0.0, 1.0) return (frame *",
"random import Random RESOLUTIONS = { \"2160p\": (3840, 2160), \"1440p\":",
"(284, 160), \"80p\": (142, 80), \"40p\": (71, 40), } def",
"(1920, 1080), \"720p\": (1280, 720), \"480p\": (854, 480), \"360p\": (640,",
"simulation grid resolution') parser.add_argument('--width', type=int, help='Video and simulation grid width',",
"resolution\") if not args.video_duration: raise ValueError(\"Missing video duration\") args.aspect =",
"quality=args.video_quality, macro_block_size=1) # Compute derived parameters if args.resolution: width, height",
"dither=1.0/256.0): if dither: rgb = [channel + random(channel.shape)*dither for channel",
"in rgb] if indexing == 'ij': rgb = [channel.T for",
"1080), \"720p\": (1280, 720), \"480p\": (854, 480), \"360p\": (640, 360),",
"from _routines import ffi, lib from pylab import * from",
"[channel.T for channel in rgb] frame = stack(rgb, axis=-1) frame",
"/ (args.num_frames - 1) t = tg lib.mandelbrot(im_buf, args.width, args.height,",
"if not args.video_quality: args.video_quality = 10 writer = imageio.get_writer(args.outfile, fps=args.framerate,",
"args.height): raise ValueError(\"Invalid or missing resolution\") if not args.video_duration: raise",
"in rgb] frame = stack(rgb, axis=-1) frame = clip(frame, 0.0,",
"480), \"360p\": (640, 360), \"240p\": (426, 240), \"160p\": (284, 160),",
"lib.mandelbrot(im_buf, args.width, args.height, 0.7, 0.8, 3.5, t-20, cut_buf, max_iter) im",
"t = tg lib.mandelbrot(im_buf, args.width, args.height, 0.7, 0.8, 3.5, t-20,",
"== 'ij': rgb = [channel.T for channel in rgb] frame",
"audio samples') parser.add_argument('outfile', type=str, help='Output file name') parser.add_argument('--params', type=str, help='Parameter",
"argparse import imageio import progressbar from _routines import ffi, lib",
"40), } def make_video_frame(rgb, indexing='ij', dither=1.0/256.0): if dither: rgb =",
"(args.num_frames - 1) t = tg lib.mandelbrot(im_buf, args.width, args.height, 0.7,",
"indexing=None) writer.append_data(frame) if __name__ == '__main__': parser = argparse.ArgumentParser(description='Render audio",
"(1280, 720), \"480p\": (854, 480), \"360p\": (640, 360), \"240p\": (426,",
"type=int, help='Video frame rate') parser.add_argument('--video-quality', type=int, help='Video quality factor') parser.add_argument('--video-duration',",
"\"240p\": (426, 240), \"160p\": (284, 160), \"80p\": (142, 80), \"40p\":",
"import argparse import imageio import progressbar from _routines import ffi,",
"10 writer = imageio.get_writer(args.outfile, fps=args.framerate, quality=args.video_quality, macro_block_size=1) # Compute derived",
"cut_buf = ffi.new(\"double[]\", max_iter) fixed_seed = Random(1) for i in",
"args.num_frames = int(args.video_duration * args.framerate) args.dt = 1.0 / args.num_frames",
"width if not args.height: args.height = height if (not args.width)",
"derived parameters if args.resolution: width, height = RESOLUTIONS[args.resolution] if not",
"green = 0.2 + 0.21*green frame = make_video_frame([red*fg + 0.15*bg,",
"fg = 1 - bg red = im green =",
"240), \"160p\": (284, 160), \"80p\": (142, 80), \"40p\": (71, 40),",
"parser.add_argument('--video-quality', type=int, help='Video quality factor') parser.add_argument('--video-duration', type=float, help='Duration of video",
"if not args.width: args.width = width if not args.height: args.height",
"lib from pylab import * from random import Random RESOLUTIONS",
"parser.add_argument('--width', type=int, help='Video and simulation grid width', metavar='W') parser.add_argument('--height', type=int,",
"type=str, help='Parameter YAML file name') parser.add_argument('--resolution', choices=RESOLUTIONS.keys(), help='Video and simulation",
"720), \"480p\": (854, 480), \"360p\": (640, 360), \"240p\": (426, 240),",
"= make_video_frame([red*fg + 0.15*bg, green*fg + 0.08*bg, blue*fg + 0.1*bg],",
"seconds') args = parser.parse_args() if not args.framerate: args.framerate = 24",
"RESOLUTIONS = { \"2160p\": (3840, 2160), \"1440p\": (2560, 1440), \"1080p\":",
"parser.add_argument('--height', type=int, help='Video and simulation grid height', metavar='H') parser.add_argument('--framerate', type=int,",
"YAML file name') parser.add_argument('--resolution', choices=RESOLUTIONS.keys(), help='Video and simulation grid resolution')",
"not args.height: args.height = height if (not args.width) or (not",
"im_buf = ffi.new(\"double[]\", args.width * args.height) cut_buf = ffi.new(\"double[]\", max_iter)",
"= array(list(im_buf)).reshape(args.height, args.width) # for i in range(max_iter): # cut_buf[i]",
"2160), \"1440p\": (2560, 1440), \"1080p\": (1920, 1080), \"720p\": (1280, 720),",
"n / (args.num_frames - 1) t = tg lib.mandelbrot(im_buf, args.width,",
"n in progressbar.progressbar(range(args.num_frames)): tg = n / (args.num_frames - 1)",
"array(list(im_buf)).reshape(args.height, args.width) # for i in range(max_iter): # cut_buf[i] *=",
"fps=args.framerate, quality=args.video_quality, macro_block_size=1) # Compute derived parameters if args.resolution: width,",
"args.framerate: args.framerate = 24 if not args.video_quality: args.video_quality = 10",
"parser.add_argument('outfile', type=str, help='Output file name') parser.add_argument('--params', type=str, help='Parameter YAML file",
"def make_video_frame(rgb, indexing='ij', dither=1.0/256.0): if dither: rgb = [channel +",
"channel in rgb] frame = stack(rgb, axis=-1) frame = clip(frame,",
"0.05**args.dt bg = (im < 0) im /= im.max() fg",
"Compute derived parameters if args.resolution: width, height = RESOLUTIONS[args.resolution] if",
"progressbar from _routines import ffi, lib from pylab import *",
"0.15*bg, green*fg + 0.08*bg, blue*fg + 0.1*bg], indexing=None) writer.append_data(frame) if",
"in range(max_iter): cut_buf[i] = i*fixed_seed.random() for n in progressbar.progressbar(range(args.num_frames)): tg",
"grid resolution') parser.add_argument('--width', type=int, help='Video and simulation grid width', metavar='W')",
"args.aspect = args.width / args.height args.num_frames = int(args.video_duration * args.framerate)",
"\"1440p\": (2560, 1440), \"1080p\": (1920, 1080), \"720p\": (1280, 720), \"480p\":",
"args.width / args.height args.num_frames = int(args.video_duration * args.framerate) args.dt =",
"= [channel.T for channel in rgb] frame = stack(rgb, axis=-1)",
"\"2160p\": (3840, 2160), \"1440p\": (2560, 1440), \"1080p\": (1920, 1080), \"720p\":",
"rgb] if indexing == 'ij': rgb = [channel.T for channel",
"1 - bg red = im green = 1 -",
"imageio.get_writer(args.outfile, fps=args.framerate, quality=args.video_quality, macro_block_size=1) # Compute derived parameters if args.resolution:",
"do_render(args, writer): max_iter = 32 im_buf = ffi.new(\"double[]\", args.width *",
"import imageio import progressbar from _routines import ffi, lib from",
"for channel in rgb] frame = stack(rgb, axis=-1) frame =",
"max_iter) fixed_seed = Random(1) for i in range(max_iter): cut_buf[i] =",
"frame = make_video_frame([red*fg + 0.15*bg, green*fg + 0.08*bg, blue*fg +",
"args.video_quality = 10 writer = imageio.get_writer(args.outfile, fps=args.framerate, quality=args.video_quality, macro_block_size=1) #",
"and simulation grid width', metavar='W') parser.add_argument('--height', type=int, help='Video and simulation",
"0.1 + 0.8*red + green**3 green = 0.2 + 0.21*green",
"int(args.video_duration * args.framerate) args.dt = 1.0 / args.num_frames do_render(args, writer)",
"32 im_buf = ffi.new(\"double[]\", args.width * args.height) cut_buf = ffi.new(\"double[]\",",
"grid width', metavar='W') parser.add_argument('--height', type=int, help='Video and simulation grid height',",
"make_video_frame([red*fg + 0.15*bg, green*fg + 0.08*bg, blue*fg + 0.1*bg], indexing=None)",
"metavar='W') parser.add_argument('--height', type=int, help='Video and simulation grid height', metavar='H') parser.add_argument('--framerate',",
"if indexing == 'ij': rgb = [channel.T for channel in",
"not args.video_quality: args.video_quality = 10 writer = imageio.get_writer(args.outfile, fps=args.framerate, quality=args.video_quality,",
"and simulation grid resolution') parser.add_argument('--width', type=int, help='Video and simulation grid",
"+ 0.21*green frame = make_video_frame([red*fg + 0.15*bg, green*fg + 0.08*bg,",
"(not args.width) or (not args.height): raise ValueError(\"Invalid or missing resolution\")",
"(im < 0) im /= im.max() fg = 1 -",
"4*im*(1-im) blue = blue + 0.2*green red = 0.1 +",
"green*fg + 0.08*bg, blue*fg + 0.1*bg], indexing=None) writer.append_data(frame) if __name__",
"args.height: args.height = height if (not args.width) or (not args.height):",
"rgb = [channel.T for channel in rgb] frame = stack(rgb,",
"<gh_stars>0 import argparse import imageio import progressbar from _routines import",
"< 0) im /= im.max() fg = 1 - bg",
"= parser.parse_args() if not args.framerate: args.framerate = 24 if not",
"- 1) t = tg lib.mandelbrot(im_buf, args.width, args.height, 0.7, 0.8,",
"= { \"2160p\": (3840, 2160), \"1440p\": (2560, 1440), \"1080p\": (1920,",
"0.21*green frame = make_video_frame([red*fg + 0.15*bg, green*fg + 0.08*bg, blue*fg",
"# cut_buf[i] *= 0.05**args.dt bg = (im < 0) im",
"or missing resolution\") if not args.video_duration: raise ValueError(\"Missing video duration\")",
"i in range(max_iter): # cut_buf[i] *= 0.05**args.dt bg = (im",
"for i in range(max_iter): # cut_buf[i] *= 0.05**args.dt bg =",
"160), \"80p\": (142, 80), \"40p\": (71, 40), } def make_video_frame(rgb,",
"= [channel + random(channel.shape)*dither for channel in rgb] if indexing",
"ffi.new(\"double[]\", max_iter) fixed_seed = Random(1) for i in range(max_iter): cut_buf[i]",
"for n in progressbar.progressbar(range(args.num_frames)): tg = n / (args.num_frames -",
"__name__ == '__main__': parser = argparse.ArgumentParser(description='Render audio samples') parser.add_argument('outfile', type=str,",
"height = RESOLUTIONS[args.resolution] if not args.width: args.width = width if",
"i*fixed_seed.random() for n in progressbar.progressbar(range(args.num_frames)): tg = n / (args.num_frames",
"# Compute derived parameters if args.resolution: width, height = RESOLUTIONS[args.resolution]",
"import ffi, lib from pylab import * from random import",
"'ij': rgb = [channel.T for channel in rgb] frame =",
"+ 0.15*bg, green*fg + 0.08*bg, blue*fg + 0.1*bg], indexing=None) writer.append_data(frame)",
"= (im < 0) im /= im.max() fg = 1",
"parser.add_argument('--resolution', choices=RESOLUTIONS.keys(), help='Video and simulation grid resolution') parser.add_argument('--width', type=int, help='Video",
"= 10 writer = imageio.get_writer(args.outfile, fps=args.framerate, quality=args.video_quality, macro_block_size=1) # Compute",
"return (frame * 255).astype('uint8') def do_render(args, writer): max_iter = 32",
"green = 1 - im blue = 4*im*(1-im) blue =",
"clip(frame, 0.0, 1.0) return (frame * 255).astype('uint8') def do_render(args, writer):",
"\"1080p\": (1920, 1080), \"720p\": (1280, 720), \"480p\": (854, 480), \"360p\":",
"rate') parser.add_argument('--video-quality', type=int, help='Video quality factor') parser.add_argument('--video-duration', type=float, help='Duration of",
"Random RESOLUTIONS = { \"2160p\": (3840, 2160), \"1440p\": (2560, 1440),",
"bg red = im green = 1 - im blue",
"cut_buf[i] *= 0.05**args.dt bg = (im < 0) im /=",
"= height if (not args.width) or (not args.height): raise ValueError(\"Invalid",
"args.resolution: width, height = RESOLUTIONS[args.resolution] if not args.width: args.width =",
"== '__main__': parser = argparse.ArgumentParser(description='Render audio samples') parser.add_argument('outfile', type=str, help='Output",
"_routines import ffi, lib from pylab import * from random",
"args.width) # for i in range(max_iter): # cut_buf[i] *= 0.05**args.dt",
"args.width) or (not args.height): raise ValueError(\"Invalid or missing resolution\") if",
"im green = 1 - im blue = 4*im*(1-im) blue",
"duration\") args.aspect = args.width / args.height args.num_frames = int(args.video_duration *",
"raise ValueError(\"Missing video duration\") args.aspect = args.width / args.height args.num_frames",
"{ \"2160p\": (3840, 2160), \"1440p\": (2560, 1440), \"1080p\": (1920, 1080),",
"axis=-1) frame = clip(frame, 0.0, 1.0) return (frame * 255).astype('uint8')",
"range(max_iter): # cut_buf[i] *= 0.05**args.dt bg = (im < 0)",
"0.2*green red = 0.1 + 0.8*red + green**3 green =",
"red = 0.1 + 0.8*red + green**3 green = 0.2",
"+ 0.8*red + green**3 green = 0.2 + 0.21*green frame",
"width', metavar='W') parser.add_argument('--height', type=int, help='Video and simulation grid height', metavar='H')",
"imageio import progressbar from _routines import ffi, lib from pylab",
"= RESOLUTIONS[args.resolution] if not args.width: args.width = width if not",
"args.video_duration: raise ValueError(\"Missing video duration\") args.aspect = args.width / args.height",
"+ random(channel.shape)*dither for channel in rgb] if indexing == 'ij':",
"not args.video_duration: raise ValueError(\"Missing video duration\") args.aspect = args.width /",
"help='Parameter YAML file name') parser.add_argument('--resolution', choices=RESOLUTIONS.keys(), help='Video and simulation grid",
"factor') parser.add_argument('--video-duration', type=float, help='Duration of video to render in seconds')",
"(71, 40), } def make_video_frame(rgb, indexing='ij', dither=1.0/256.0): if dither: rgb",
"args.height, 0.7, 0.8, 3.5, t-20, cut_buf, max_iter) im = array(list(im_buf)).reshape(args.height,",
"= argparse.ArgumentParser(description='Render audio samples') parser.add_argument('outfile', type=str, help='Output file name') parser.add_argument('--params',",
"/ args.height args.num_frames = int(args.video_duration * args.framerate) args.dt = 1.0",
"= Random(1) for i in range(max_iter): cut_buf[i] = i*fixed_seed.random() for",
"macro_block_size=1) # Compute derived parameters if args.resolution: width, height =",
"in seconds') args = parser.parse_args() if not args.framerate: args.framerate =",
"if (not args.width) or (not args.height): raise ValueError(\"Invalid or missing",
"help='Video and simulation grid width', metavar='W') parser.add_argument('--height', type=int, help='Video and",
"0.1*bg], indexing=None) writer.append_data(frame) if __name__ == '__main__': parser = argparse.ArgumentParser(description='Render",
"* 255).astype('uint8') def do_render(args, writer): max_iter = 32 im_buf =",
"= 0.2 + 0.21*green frame = make_video_frame([red*fg + 0.15*bg, green*fg",
"frame = clip(frame, 0.0, 1.0) return (frame * 255).astype('uint8') def",
"if not args.height: args.height = height if (not args.width) or",
"0.0, 1.0) return (frame * 255).astype('uint8') def do_render(args, writer): max_iter",
"args.height args.num_frames = int(args.video_duration * args.framerate) args.dt = 1.0 /",
"from pylab import * from random import Random RESOLUTIONS =",
"dither: rgb = [channel + random(channel.shape)*dither for channel in rgb]",
"1440), \"1080p\": (1920, 1080), \"720p\": (1280, 720), \"480p\": (854, 480),",
"bg = (im < 0) im /= im.max() fg =",
"0.08*bg, blue*fg + 0.1*bg], indexing=None) writer.append_data(frame) if __name__ == '__main__':",
"channel in rgb] if indexing == 'ij': rgb = [channel.T",
"+ 0.08*bg, blue*fg + 0.1*bg], indexing=None) writer.append_data(frame) if __name__ ==",
"blue = blue + 0.2*green red = 0.1 + 0.8*red",
"args.height) cut_buf = ffi.new(\"double[]\", max_iter) fixed_seed = Random(1) for i",
"height', metavar='H') parser.add_argument('--framerate', type=int, help='Video frame rate') parser.add_argument('--video-quality', type=int, help='Video",
"= blue + 0.2*green red = 0.1 + 0.8*red +",
"rgb] frame = stack(rgb, axis=-1) frame = clip(frame, 0.0, 1.0)",
"} def make_video_frame(rgb, indexing='ij', dither=1.0/256.0): if dither: rgb = [channel",
"grid height', metavar='H') parser.add_argument('--framerate', type=int, help='Video frame rate') parser.add_argument('--video-quality', type=int,",
"(not args.height): raise ValueError(\"Invalid or missing resolution\") if not args.video_duration:",
"render in seconds') args = parser.parse_args() if not args.framerate: args.framerate",
"* args.framerate) args.dt = 1.0 / args.num_frames do_render(args, writer) writer.close()",
"(854, 480), \"360p\": (640, 360), \"240p\": (426, 240), \"160p\": (284,",
"= tg lib.mandelbrot(im_buf, args.width, args.height, 0.7, 0.8, 3.5, t-20, cut_buf,",
"tg = n / (args.num_frames - 1) t = tg",
"width, height = RESOLUTIONS[args.resolution] if not args.width: args.width = width",
"samples') parser.add_argument('outfile', type=str, help='Output file name') parser.add_argument('--params', type=str, help='Parameter YAML",
"(640, 360), \"240p\": (426, 240), \"160p\": (284, 160), \"80p\": (142,",
"for i in range(max_iter): cut_buf[i] = i*fixed_seed.random() for n in",
"= 1 - im blue = 4*im*(1-im) blue = blue",
"[channel + random(channel.shape)*dither for channel in rgb] if indexing ==",
"import Random RESOLUTIONS = { \"2160p\": (3840, 2160), \"1440p\": (2560,",
"= imageio.get_writer(args.outfile, fps=args.framerate, quality=args.video_quality, macro_block_size=1) # Compute derived parameters if",
"* from random import Random RESOLUTIONS = { \"2160p\": (3840,",
"\"360p\": (640, 360), \"240p\": (426, 240), \"160p\": (284, 160), \"80p\":",
"fixed_seed = Random(1) for i in range(max_iter): cut_buf[i] = i*fixed_seed.random()",
"360), \"240p\": (426, 240), \"160p\": (284, 160), \"80p\": (142, 80),",
"if args.resolution: width, height = RESOLUTIONS[args.resolution] if not args.width: args.width",
"if __name__ == '__main__': parser = argparse.ArgumentParser(description='Render audio samples') parser.add_argument('outfile',",
"cut_buf[i] = i*fixed_seed.random() for n in progressbar.progressbar(range(args.num_frames)): tg = n",
"args.width = width if not args.height: args.height = height if",
"(3840, 2160), \"1440p\": (2560, 1440), \"1080p\": (1920, 1080), \"720p\": (1280,",
"help='Output file name') parser.add_argument('--params', type=str, help='Parameter YAML file name') parser.add_argument('--resolution',",
"# for i in range(max_iter): # cut_buf[i] *= 0.05**args.dt bg",
"quality factor') parser.add_argument('--video-duration', type=float, help='Duration of video to render in",
"args = parser.parse_args() if not args.framerate: args.framerate = 24 if",
"= args.width / args.height args.num_frames = int(args.video_duration * args.framerate) args.dt",
"cut_buf, max_iter) im = array(list(im_buf)).reshape(args.height, args.width) # for i in",
"for channel in rgb] if indexing == 'ij': rgb =",
"args.width * args.height) cut_buf = ffi.new(\"double[]\", max_iter) fixed_seed = Random(1)",
"progressbar.progressbar(range(args.num_frames)): tg = n / (args.num_frames - 1) t =",
"in range(max_iter): # cut_buf[i] *= 0.05**args.dt bg = (im <",
"1) t = tg lib.mandelbrot(im_buf, args.width, args.height, 0.7, 0.8, 3.5,",
"def do_render(args, writer): max_iter = 32 im_buf = ffi.new(\"double[]\", args.width",
"import * from random import Random RESOLUTIONS = { \"2160p\":",
"help='Video frame rate') parser.add_argument('--video-quality', type=int, help='Video quality factor') parser.add_argument('--video-duration', type=float,",
"im blue = 4*im*(1-im) blue = blue + 0.2*green red",
"= i*fixed_seed.random() for n in progressbar.progressbar(range(args.num_frames)): tg = n /",
"\"720p\": (1280, 720), \"480p\": (854, 480), \"360p\": (640, 360), \"240p\":",
"help='Video and simulation grid resolution') parser.add_argument('--width', type=int, help='Video and simulation",
"0.8, 3.5, t-20, cut_buf, max_iter) im = array(list(im_buf)).reshape(args.height, args.width) #",
"from random import Random RESOLUTIONS = { \"2160p\": (3840, 2160),",
"1 - im blue = 4*im*(1-im) blue = blue +",
"= 24 if not args.video_quality: args.video_quality = 10 writer =",
"= int(args.video_duration * args.framerate) args.dt = 1.0 / args.num_frames do_render(args,",
"80), \"40p\": (71, 40), } def make_video_frame(rgb, indexing='ij', dither=1.0/256.0): if",
"blue = 4*im*(1-im) blue = blue + 0.2*green red =",
"parameters if args.resolution: width, height = RESOLUTIONS[args.resolution] if not args.width:",
"0.7, 0.8, 3.5, t-20, cut_buf, max_iter) im = array(list(im_buf)).reshape(args.height, args.width)",
"choices=RESOLUTIONS.keys(), help='Video and simulation grid resolution') parser.add_argument('--width', type=int, help='Video and",
"frame = stack(rgb, axis=-1) frame = clip(frame, 0.0, 1.0) return"
] |
[
"QOS_1, QOS_2 from hbmqtt.adapters import BufferAdapter class SubscribePacketTest(unittest.TestCase): def test_from_stream(self):",
"data = b'\\x80\\x0e\\x00\\x0a\\x00\\x03a/b\\x01\\x00\\x03c/d\\x02' stream = BufferAdapter(data) message = anyio.run(SubscribePacket.from_stream, stream)",
"(topic, qos) = message.payload.topics[0] self.assertEqual(topic, 'a/b') self.assertEqual(qos, QOS_1) (topic, qos)",
"def test_from_stream(self): data = b'\\x80\\x0e\\x00\\x0a\\x00\\x03a/b\\x01\\x00\\x03c/d\\x02' stream = BufferAdapter(data) message =",
"'a/b') self.assertEqual(qos, QOS_1) (topic, qos) = message.payload.topics[1] self.assertEqual(topic, 'c/d') self.assertEqual(qos,",
"self.assertEqual(topic, 'c/d') self.assertEqual(qos, QOS_2) def test_to_stream(self): variable_header = PacketIdVariableHeader(10) payload",
"= b'\\x80\\x0e\\x00\\x0a\\x00\\x03a/b\\x01\\x00\\x03c/d\\x02' stream = BufferAdapter(data) message = anyio.run(SubscribePacket.from_stream, stream) (topic,",
"self.assertEqual(qos, QOS_2) def test_to_stream(self): variable_header = PacketIdVariableHeader(10) payload = SubscribePayload(",
"[ ('a/b', QOS_1), ('c/d', QOS_2) ]) publish = SubscribePacket(variable_header=variable_header, payload=payload)",
"stream) (topic, qos) = message.payload.topics[0] self.assertEqual(topic, 'a/b') self.assertEqual(qos, QOS_1) (topic,",
"variable_header = PacketIdVariableHeader(10) payload = SubscribePayload( [ ('a/b', QOS_1), ('c/d',",
"def test_to_stream(self): variable_header = PacketIdVariableHeader(10) payload = SubscribePayload( [ ('a/b',",
"b'\\x80\\x0e\\x00\\x0a\\x00\\x03a/b\\x01\\x00\\x03c/d\\x02' stream = BufferAdapter(data) message = anyio.run(SubscribePacket.from_stream, stream) (topic, qos)",
"from hbmqtt.adapters import BufferAdapter class SubscribePacketTest(unittest.TestCase): def test_from_stream(self): data =",
"hbmqtt.adapters import BufferAdapter class SubscribePacketTest(unittest.TestCase): def test_from_stream(self): data = b'\\x80\\x0e\\x00\\x0a\\x00\\x03a/b\\x01\\x00\\x03c/d\\x02'",
"SubscribePayload( [ ('a/b', QOS_1), ('c/d', QOS_2) ]) publish = SubscribePacket(variable_header=variable_header,",
"import unittest from hbmqtt.mqtt.subscribe import SubscribePacket, SubscribePayload from hbmqtt.mqtt.packet import",
"SubscribePacket, SubscribePayload from hbmqtt.mqtt.packet import PacketIdVariableHeader from hbmqtt.mqtt.constants import QOS_1,",
"anyio import unittest from hbmqtt.mqtt.subscribe import SubscribePacket, SubscribePayload from hbmqtt.mqtt.packet",
"('c/d', QOS_2) ]) publish = SubscribePacket(variable_header=variable_header, payload=payload) out = publish.to_bytes()",
"# # See the file license.txt for copying permission. import",
"permission. import anyio import unittest from hbmqtt.mqtt.subscribe import SubscribePacket, SubscribePayload",
"payload = SubscribePayload( [ ('a/b', QOS_1), ('c/d', QOS_2) ]) publish",
"file license.txt for copying permission. import anyio import unittest from",
"PacketIdVariableHeader from hbmqtt.mqtt.constants import QOS_1, QOS_2 from hbmqtt.adapters import BufferAdapter",
"test_to_stream(self): variable_header = PacketIdVariableHeader(10) payload = SubscribePayload( [ ('a/b', QOS_1),",
"import QOS_1, QOS_2 from hbmqtt.adapters import BufferAdapter class SubscribePacketTest(unittest.TestCase): def",
"import SubscribePacket, SubscribePayload from hbmqtt.mqtt.packet import PacketIdVariableHeader from hbmqtt.mqtt.constants import",
"'c/d') self.assertEqual(qos, QOS_2) def test_to_stream(self): variable_header = PacketIdVariableHeader(10) payload =",
"Copyright (c) 2015 <NAME> # # See the file license.txt",
"unittest from hbmqtt.mqtt.subscribe import SubscribePacket, SubscribePayload from hbmqtt.mqtt.packet import PacketIdVariableHeader",
"QOS_1), ('c/d', QOS_2) ]) publish = SubscribePacket(variable_header=variable_header, payload=payload) out =",
"QOS_2) ]) publish = SubscribePacket(variable_header=variable_header, payload=payload) out = publish.to_bytes() self.assertEqual(out,",
"= BufferAdapter(data) message = anyio.run(SubscribePacket.from_stream, stream) (topic, qos) = message.payload.topics[0]",
"hbmqtt.mqtt.constants import QOS_1, QOS_2 from hbmqtt.adapters import BufferAdapter class SubscribePacketTest(unittest.TestCase):",
"license.txt for copying permission. import anyio import unittest from hbmqtt.mqtt.subscribe",
"import BufferAdapter class SubscribePacketTest(unittest.TestCase): def test_from_stream(self): data = b'\\x80\\x0e\\x00\\x0a\\x00\\x03a/b\\x01\\x00\\x03c/d\\x02' stream",
"QOS_2) def test_to_stream(self): variable_header = PacketIdVariableHeader(10) payload = SubscribePayload( [",
"hbmqtt.mqtt.subscribe import SubscribePacket, SubscribePayload from hbmqtt.mqtt.packet import PacketIdVariableHeader from hbmqtt.mqtt.constants",
"qos) = message.payload.topics[0] self.assertEqual(topic, 'a/b') self.assertEqual(qos, QOS_1) (topic, qos) =",
"<filename>tests/mqtt/test_subscribe.py # Copyright (c) 2015 <NAME> # # See the",
"anyio.run(SubscribePacket.from_stream, stream) (topic, qos) = message.payload.topics[0] self.assertEqual(topic, 'a/b') self.assertEqual(qos, QOS_1)",
"BufferAdapter(data) message = anyio.run(SubscribePacket.from_stream, stream) (topic, qos) = message.payload.topics[0] self.assertEqual(topic,",
"the file license.txt for copying permission. import anyio import unittest",
"message.payload.topics[0] self.assertEqual(topic, 'a/b') self.assertEqual(qos, QOS_1) (topic, qos) = message.payload.topics[1] self.assertEqual(topic,",
"<NAME> # # See the file license.txt for copying permission.",
"stream = BufferAdapter(data) message = anyio.run(SubscribePacket.from_stream, stream) (topic, qos) =",
"SubscribePacketTest(unittest.TestCase): def test_from_stream(self): data = b'\\x80\\x0e\\x00\\x0a\\x00\\x03a/b\\x01\\x00\\x03c/d\\x02' stream = BufferAdapter(data) message",
"qos) = message.payload.topics[1] self.assertEqual(topic, 'c/d') self.assertEqual(qos, QOS_2) def test_to_stream(self): variable_header",
"self.assertEqual(qos, QOS_1) (topic, qos) = message.payload.topics[1] self.assertEqual(topic, 'c/d') self.assertEqual(qos, QOS_2)",
"test_from_stream(self): data = b'\\x80\\x0e\\x00\\x0a\\x00\\x03a/b\\x01\\x00\\x03c/d\\x02' stream = BufferAdapter(data) message = anyio.run(SubscribePacket.from_stream,",
"]) publish = SubscribePacket(variable_header=variable_header, payload=payload) out = publish.to_bytes() self.assertEqual(out, b'\\x82\\x0e\\x00\\x0a\\x00\\x03a/b\\x01\\x00\\x03c/d\\x02')",
"= message.payload.topics[0] self.assertEqual(topic, 'a/b') self.assertEqual(qos, QOS_1) (topic, qos) = message.payload.topics[1]",
"SubscribePayload from hbmqtt.mqtt.packet import PacketIdVariableHeader from hbmqtt.mqtt.constants import QOS_1, QOS_2",
"= anyio.run(SubscribePacket.from_stream, stream) (topic, qos) = message.payload.topics[0] self.assertEqual(topic, 'a/b') self.assertEqual(qos,",
"hbmqtt.mqtt.packet import PacketIdVariableHeader from hbmqtt.mqtt.constants import QOS_1, QOS_2 from hbmqtt.adapters",
"class SubscribePacketTest(unittest.TestCase): def test_from_stream(self): data = b'\\x80\\x0e\\x00\\x0a\\x00\\x03a/b\\x01\\x00\\x03c/d\\x02' stream = BufferAdapter(data)",
"message.payload.topics[1] self.assertEqual(topic, 'c/d') self.assertEqual(qos, QOS_2) def test_to_stream(self): variable_header = PacketIdVariableHeader(10)",
"= SubscribePayload( [ ('a/b', QOS_1), ('c/d', QOS_2) ]) publish =",
"(topic, qos) = message.payload.topics[1] self.assertEqual(topic, 'c/d') self.assertEqual(qos, QOS_2) def test_to_stream(self):",
"# See the file license.txt for copying permission. import anyio",
"from hbmqtt.mqtt.subscribe import SubscribePacket, SubscribePayload from hbmqtt.mqtt.packet import PacketIdVariableHeader from",
"import PacketIdVariableHeader from hbmqtt.mqtt.constants import QOS_1, QOS_2 from hbmqtt.adapters import",
"QOS_2 from hbmqtt.adapters import BufferAdapter class SubscribePacketTest(unittest.TestCase): def test_from_stream(self): data",
"from hbmqtt.mqtt.packet import PacketIdVariableHeader from hbmqtt.mqtt.constants import QOS_1, QOS_2 from",
"= message.payload.topics[1] self.assertEqual(topic, 'c/d') self.assertEqual(qos, QOS_2) def test_to_stream(self): variable_header =",
"# Copyright (c) 2015 <NAME> # # See the file",
"from hbmqtt.mqtt.constants import QOS_1, QOS_2 from hbmqtt.adapters import BufferAdapter class",
"BufferAdapter class SubscribePacketTest(unittest.TestCase): def test_from_stream(self): data = b'\\x80\\x0e\\x00\\x0a\\x00\\x03a/b\\x01\\x00\\x03c/d\\x02' stream =",
"for copying permission. import anyio import unittest from hbmqtt.mqtt.subscribe import",
"message = anyio.run(SubscribePacket.from_stream, stream) (topic, qos) = message.payload.topics[0] self.assertEqual(topic, 'a/b')",
"See the file license.txt for copying permission. import anyio import",
"PacketIdVariableHeader(10) payload = SubscribePayload( [ ('a/b', QOS_1), ('c/d', QOS_2) ])",
"self.assertEqual(topic, 'a/b') self.assertEqual(qos, QOS_1) (topic, qos) = message.payload.topics[1] self.assertEqual(topic, 'c/d')",
"('a/b', QOS_1), ('c/d', QOS_2) ]) publish = SubscribePacket(variable_header=variable_header, payload=payload) out",
"copying permission. import anyio import unittest from hbmqtt.mqtt.subscribe import SubscribePacket,",
"import anyio import unittest from hbmqtt.mqtt.subscribe import SubscribePacket, SubscribePayload from",
"2015 <NAME> # # See the file license.txt for copying",
"QOS_1) (topic, qos) = message.payload.topics[1] self.assertEqual(topic, 'c/d') self.assertEqual(qos, QOS_2) def",
"= PacketIdVariableHeader(10) payload = SubscribePayload( [ ('a/b', QOS_1), ('c/d', QOS_2)",
"(c) 2015 <NAME> # # See the file license.txt for"
] |
[
"None state_dict_S = torch.load(args.init_checkpoint_S, map_location='cpu') state_weight = {k[5:]:v for k,v",
"= None tokenizer = ChineseFullTokenizer(vocab_file=args.vocab_file, do_lower_case=args.do_lower_case) convert_fn = partial(convert_examples_to_features, tokenizer=tokenizer,",
"#parameters params = list(model_S.named_parameters()) all_trainable_params = divide_parameters(params, lr=args.learning_rate) logger.info(\"Length of",
"read_and_convert(args.fake_file_1,is_training=True, do_lower_case=args.do_lower_case, read_fn=read_squad_examples,convert_fn=convert_fn) train_examples += fake_examples1 train_features += fake_features1 if",
"is not None state_dict_S = torch.load(args.init_checkpoint_S, map_location='cpu') state_weight = {k[5:]:v",
"= partial(convert_examples_to_features, tokenizer=tokenizer, max_seq_length=args.max_seq_length, doc_stride=args.doc_stride, max_query_length=args.max_query_length) if args.do_train: train_examples,train_features =",
"logger.info(\" Num split examples = %d\", len(train_features)) logger.info(\" Forward batch",
"n_gpu = args_check(args) os.makedirs(args.output_dir, exist_ok=True) forward_batch_size = int(args.train_batch_size / args.gradient_accumulation_steps)",
"DataLoader(train_dataset, sampler=train_sampler, batch_size=args.forward_batch_size,drop_last=True) callback_func = partial(predict, eval_examples=eval_examples, eval_features=eval_features, args=args) with",
"data train_examples = None train_features = None eval_examples = None",
"NotImplementedError train_dataloader = DataLoader(train_dataset, sampler=train_sampler, batch_size=args.forward_batch_size,drop_last=True) callback_func = partial(predict, eval_examples=eval_examples,",
"checkpoint model_S = BertForQASimple(bert_config_S,args) #Load student if args.load_model_type=='bert': assert args.init_checkpoint_S",
"in train_features], dtype=torch.float) all_segment_ids = torch.tensor([f.segment_ids for f in train_features],",
"student if args.load_model_type=='bert': assert args.init_checkpoint_S is not None state_dict_S =",
"not empty.\") if args.gradient_accumulation_steps < 1: raise ValueError(\"Invalid gradient_accumulation_steps parameter:",
"args.local_rank == -1 or args.no_cuda: device = torch.device(\"cuda\" if torch.cuda.is_available()",
"def main(): #parse arguments config.parse() args = config.args for k,v",
"n_gpu def main(): #parse arguments config.parse() args = config.args for",
"if args.local_rank != -1: raise NotImplementedError elif n_gpu > 1:",
"torch.cuda.manual_seed_all(args.random_seed) np.random.seed(args.random_seed) random.seed(args.random_seed) #arguments check device, n_gpu = args_check(args) os.makedirs(args.output_dir,",
"partial(convert_examples_to_features, tokenizer=tokenizer, max_seq_length=args.max_seq_length, doc_stride=args.doc_stride, max_query_length=args.max_query_length) if args.do_train: train_examples,train_features = read_and_convert(args.train_file,is_training=True,",
"logger.info(\"device %s n_gpu %d distributed training %r\", device, n_gpu, bool(args.local_rank",
"callback=callback_func) if not args.do_train and args.do_predict: res = predict(model_S,eval_examples,eval_features,step=0,args=args) print",
"size = %d\", forward_batch_size) logger.info(\" Num backward steps = %d\",",
"f in train_features], dtype=torch.long) all_start_positions = torch.tensor([f.start_position for f in",
"torch.device(\"cuda\", args.local_rank) n_gpu = 1 torch.distributed.init_process_group(backend='nccl') logger.info(\"device %s n_gpu %d",
"read_fn=read_squad_examples,convert_fn=convert_fn) train_examples += fake_examples2 train_features += fake_features2 num_train_steps = int(len(train_features)/args.train_batch_size)",
"eval_examples,eval_features = read_and_convert(args.predict_file,is_training=False, do_lower_case=args.do_lower_case, read_fn=read_squad_examples,convert_fn=convert_fn) #Build Model and load checkpoint",
"import BertForQASimple, BertForQASimpleAdaptorTraining from textbrewer import DistillationConfig, TrainingConfig, BasicTrainer from",
"do_lower_case=args.do_lower_case, read_fn=read_squad_examples,convert_fn=convert_fn) train_examples += fake_examples2 train_features += fake_features2 num_train_steps =",
"args.do_train and not args.do_predict: raise ValueError(\"At least one of `do_train`",
"!= -1: raise NotImplementedError elif n_gpu > 1: model_S =",
"convert_examples_to_features, read_squad_examples from processing import ChineseFullTokenizer from pytorch_pretrained_bert.my_modeling import BertConfig",
"else: raise NotImplementedError train_dataloader = DataLoader(train_dataset, sampler=train_sampler, batch_size=args.forward_batch_size,drop_last=True) callback_func =",
"in train_features], dtype=torch.long) all_input_mask = torch.tensor([f.input_mask for f in train_features],",
"args.output_dir, device = args.device) distiller = BasicTrainer(train_config = train_config, model",
"n_gpu = torch.cuda.device_count() if not args.no_cuda else 0 else: device",
"%(name)s - %(message)s', datefmt='%Y/%m/%d %H:%M:%S', level=logging.INFO, ) logger = logging.getLogger(\"Main\")",
"lr=args.learning_rate) logger.info(\"Length of all_trainable_params: %d\", len(all_trainable_params)) optimizer = BERTAdam(all_trainable_params,lr=args.learning_rate, warmup=args.warmup_proportion,t_total=num_train_steps,schedule=args.schedule,",
"logger.warning(\"Output directory () already exists and is not empty.\") if",
"= 1 torch.distributed.init_process_group(backend='nccl') logger.info(\"device %s n_gpu %d distributed training %r\",",
"#set seeds torch.manual_seed(args.random_seed) torch.cuda.manual_seed_all(args.random_seed) np.random.seed(args.random_seed) random.seed(args.random_seed) #arguments check device, n_gpu",
"and not args.no_cuda else \"cpu\") n_gpu = torch.cuda.device_count() if not",
"in state_dict_S.items() if k.startswith('bert.')} missing_keys,_ = model_S.bert.load_state_dict(state_weight,strict=False) assert len(missing_keys)==0 elif",
"logging.basicConfig( format='%(asctime)s - %(levelname)s - %(name)s - %(message)s', datefmt='%Y/%m/%d %H:%M:%S',",
"in train_features], dtype=torch.long) all_end_positions = torch.tensor([f.end_position for f in train_features],",
"state_dict_S.items() if k.startswith('bert.')} missing_keys,_ = model_S.bert.load_state_dict(state_weight,strict=False) assert len(missing_keys)==0 elif args.load_model_type=='all':",
"not args.no_cuda else \"cpu\") n_gpu = torch.cuda.device_count() if not args.no_cuda",
"args.do_train: train_examples,train_features = read_and_convert(args.train_file,is_training=True, do_lower_case=args.do_lower_case, read_fn=read_squad_examples,convert_fn=convert_fn) if args.fake_file_1: fake_examples1,fake_features1 =",
"args=args) with distiller: distiller.train(optimizer, scheduler=None, dataloader=train_dataloader, num_epochs=args.num_train_epochs, callback=callback_func) if not",
"list(model_S.named_parameters()) all_trainable_params = divide_parameters(params, lr=args.learning_rate) logger.info(\"Length of all_trainable_params: %d\", len(all_trainable_params))",
"None num_train_steps = None tokenizer = ChineseFullTokenizer(vocab_file=args.vocab_file, do_lower_case=args.do_lower_case) convert_fn =",
"logger.info(\" Num orig examples = %d\", len(train_examples)) logger.info(\" Num split",
"if torch.cuda.is_available() and not args.no_cuda else \"cpu\") n_gpu = torch.cuda.device_count()",
"pytorch_pretrained_bert.my_modeling import BertConfig from optimization import BERTAdam import config from",
"DISTILLATION ########### train_config = TrainingConfig( gradient_accumulation_steps = args.gradient_accumulation_steps, ckpt_frequency =",
"= read_and_convert(args.predict_file,is_training=False, do_lower_case=args.do_lower_case, read_fn=read_squad_examples,convert_fn=convert_fn) #Build Model and load checkpoint model_S",
"import torch from processing import convert_examples_to_features, read_squad_examples from processing import",
"train_features += fake_features1 if args.fake_file_2: fake_examples2, fake_features2 = read_and_convert(args.fake_file_2,is_training=True, do_lower_case=args.do_lower_case,",
"+= fake_examples2 train_features += fake_features2 num_train_steps = int(len(train_features)/args.train_batch_size) * args.num_train_epochs",
"if args.do_train: #parameters params = list(model_S.named_parameters()) all_trainable_params = divide_parameters(params, lr=args.learning_rate)",
"tokenizer=tokenizer, max_seq_length=args.max_seq_length, doc_stride=args.doc_stride, max_query_length=args.max_query_length) if args.do_train: train_examples,train_features = read_and_convert(args.train_file,is_training=True, do_lower_case=args.do_lower_case,",
"= partial(predict, eval_examples=eval_examples, eval_features=eval_features, args=args) with distiller: distiller.train(optimizer, scheduler=None, dataloader=train_dataloader,",
"all_start_positions, all_end_positions) if args.local_rank == -1: train_sampler = RandomSampler(train_dataset) else:",
"model_S, adaptor = BertForQASimpleAdaptorTraining) all_input_ids = torch.tensor([f.input_ids for f in",
"device, n_gpu = args_check(args) os.makedirs(args.output_dir, exist_ok=True) forward_batch_size = int(args.train_batch_size /",
"divide_parameters from modeling import BertForQASimple, BertForQASimpleAdaptorTraining from textbrewer import DistillationConfig,",
"k.startswith('bert.')} missing_keys,_ = model_S.bert.load_state_dict(state_weight,strict=False) assert len(missing_keys)==0 elif args.load_model_type=='all': assert args.tuned_checkpoint_S",
"fake_examples1,fake_features1 = read_and_convert(args.fake_file_1,is_training=True, do_lower_case=args.do_lower_case, read_fn=read_squad_examples,convert_fn=convert_fn) train_examples += fake_examples1 train_features +=",
"not None state_dict_S = torch.load(args.tuned_checkpoint_S,map_location='cpu') model_S.load_state_dict(state_dict_S) else: logger.info(\"Model is randomly",
"directory () already exists and is not empty.\") if args.gradient_accumulation_steps",
"training %r\", device, n_gpu, bool(args.local_rank != -1)) args.n_gpu = n_gpu",
"args.do_predict: raise ValueError(\"At least one of `do_train` or `do_predict` must",
"of `do_train` or `do_predict` must be True.\") if args.local_rank ==",
"= {k[5:]:v for k,v in state_dict_S.items() if k.startswith('bert.')} missing_keys,_ =",
"torch.tensor([f.input_ids for f in train_features], dtype=torch.long) all_input_mask = torch.tensor([f.input_mask for",
"########### DISTILLATION ########### train_config = TrainingConfig( gradient_accumulation_steps = args.gradient_accumulation_steps, ckpt_frequency",
"examples = %d\", len(train_examples)) logger.info(\" Num split examples = %d\",",
"def args_check(args): if os.path.exists(args.output_dir) and os.listdir(args.output_dir): logger.warning(\"Output directory () already",
"+= fake_examples1 train_features += fake_features1 if args.fake_file_2: fake_examples2, fake_features2 =",
"ChineseFullTokenizer(vocab_file=args.vocab_file, do_lower_case=args.do_lower_case) convert_fn = partial(convert_examples_to_features, tokenizer=tokenizer, max_seq_length=args.max_seq_length, doc_stride=args.doc_stride, max_query_length=args.max_query_length) if",
"= config.args for k,v in vars(args).items(): logger.info(f\"{k}:{v}\") #set seeds torch.manual_seed(args.random_seed)",
"> 1: model_S = torch.nn.DataParallel(model_S) #,output_device=n_gpu-1) if args.do_train: #parameters params",
"eval_features = None num_train_steps = None tokenizer = ChineseFullTokenizer(vocab_file=args.vocab_file, do_lower_case=args.do_lower_case)",
"-1)) args.n_gpu = n_gpu args.device = device return device, n_gpu",
"distributed training %r\", device, n_gpu, bool(args.local_rank != -1)) args.n_gpu =",
"args.load_model_type=='all': assert args.tuned_checkpoint_S is not None state_dict_S = torch.load(args.tuned_checkpoint_S,map_location='cpu') model_S.load_state_dict(state_dict_S)",
"max_seq_length=args.max_seq_length, doc_stride=args.doc_stride, max_query_length=args.max_query_length) if args.do_train: train_examples,train_features = read_and_convert(args.train_file,is_training=True, do_lower_case=args.do_lower_case, read_fn=read_squad_examples,convert_fn=convert_fn)",
"if not args.do_train and args.do_predict: res = predict(model_S,eval_examples,eval_features,step=0,args=args) print (res)",
"= TrainingConfig( gradient_accumulation_steps = args.gradient_accumulation_steps, ckpt_frequency = args.ckpt_frequency, log_dir =",
"batch size = %d\", forward_batch_size) logger.info(\" Num backward steps =",
"- %(levelname)s - %(name)s - %(message)s', datefmt='%Y/%m/%d %H:%M:%S', level=logging.INFO, )",
"`do_train` or `do_predict` must be True.\") if args.local_rank == -1",
"= RandomSampler(train_dataset) else: raise NotImplementedError train_dataloader = DataLoader(train_dataset, sampler=train_sampler, batch_size=args.forward_batch_size,drop_last=True)",
"TensorDataset, DataLoader, RandomSampler from functools import partial from train_eval import",
"torch.cuda.is_available() and not args.no_cuda else \"cpu\") n_gpu = torch.cuda.device_count() if",
"in train_features], dtype=torch.long) train_dataset = TensorDataset(all_input_ids, all_segment_ids, all_input_mask, all_doc_mask, all_start_positions,",
"= BERTAdam(all_trainable_params,lr=args.learning_rate, warmup=args.warmup_proportion,t_total=num_train_steps,schedule=args.schedule, s_opt1=args.s_opt1, s_opt2=args.s_opt2, s_opt3=args.s_opt3) logger.info(\"***** Running training *****\")",
"> 1: if args.local_rank != -1: raise NotImplementedError elif n_gpu",
"= %d\", num_train_steps) ########### DISTILLATION ########### train_config = TrainingConfig( gradient_accumulation_steps",
"read_and_convert, divide_parameters from modeling import BertForQASimple, BertForQASimpleAdaptorTraining from textbrewer import",
"num_train_steps = int(len(train_features)/args.train_batch_size) * args.num_train_epochs if args.do_predict: eval_examples,eval_features = read_and_convert(args.predict_file,is_training=False,",
"= DataLoader(train_dataset, sampler=train_sampler, batch_size=args.forward_batch_size,drop_last=True) callback_func = partial(predict, eval_examples=eval_examples, eval_features=eval_features, args=args)",
"torch.tensor([f.doc_mask for f in train_features], dtype=torch.float) all_segment_ids = torch.tensor([f.segment_ids for",
"%(levelname)s - %(name)s - %(message)s', datefmt='%Y/%m/%d %H:%M:%S', level=logging.INFO, ) logger",
"for f in train_features], dtype=torch.float) all_segment_ids = torch.tensor([f.segment_ids for f",
"assert args.init_checkpoint_S is not None state_dict_S = torch.load(args.init_checkpoint_S, map_location='cpu') state_weight",
"k,v in vars(args).items(): logger.info(f\"{k}:{v}\") #set seeds torch.manual_seed(args.random_seed) torch.cuda.manual_seed_all(args.random_seed) np.random.seed(args.random_seed) random.seed(args.random_seed)",
"warmup=args.warmup_proportion,t_total=num_train_steps,schedule=args.schedule, s_opt1=args.s_opt1, s_opt2=args.s_opt2, s_opt3=args.s_opt3) logger.info(\"***** Running training *****\") logger.info(\" Num",
"output_dir = args.output_dir, device = args.device) distiller = BasicTrainer(train_config =",
"torch from processing import convert_examples_to_features, read_squad_examples from processing import ChineseFullTokenizer",
"args.fake_file_1: fake_examples1,fake_features1 = read_and_convert(args.fake_file_1,is_training=True, do_lower_case=args.do_lower_case, read_fn=read_squad_examples,convert_fn=convert_fn) train_examples += fake_examples1 train_features",
"s_opt3=args.s_opt3) logger.info(\"***** Running training *****\") logger.info(\" Num orig examples =",
"if args.local_rank == -1 or args.no_cuda: device = torch.device(\"cuda\" if",
"randomly initialized.\") model_S.to(device) if args.local_rank != -1 or n_gpu >",
"and os.listdir(args.output_dir): logger.warning(\"Output directory () already exists and is not",
"ValueError(\"At least one of `do_train` or `do_predict` must be True.\")",
"args.fake_file_2: fake_examples2, fake_features2 = read_and_convert(args.fake_file_2,is_training=True, do_lower_case=args.do_lower_case, read_fn=read_squad_examples,convert_fn=convert_fn) train_examples += fake_examples2",
"#read data train_examples = None train_features = None eval_examples =",
"processing import convert_examples_to_features, read_squad_examples from processing import ChineseFullTokenizer from pytorch_pretrained_bert.my_modeling",
"True.\") if args.local_rank == -1 or args.no_cuda: device = torch.device(\"cuda\"",
"else 0 else: device = torch.device(\"cuda\", args.local_rank) n_gpu = 1",
"torch.manual_seed(args.random_seed) torch.cuda.manual_seed_all(args.random_seed) np.random.seed(args.random_seed) random.seed(args.random_seed) #arguments check device, n_gpu = args_check(args)",
"read_and_convert(args.predict_file,is_training=False, do_lower_case=args.do_lower_case, read_fn=read_squad_examples,convert_fn=convert_fn) #Build Model and load checkpoint model_S =",
"Num split examples = %d\", len(train_features)) logger.info(\" Forward batch size",
"None state_dict_S = torch.load(args.tuned_checkpoint_S,map_location='cpu') model_S.load_state_dict(state_dict_S) else: logger.info(\"Model is randomly initialized.\")",
"all_trainable_params: %d\", len(all_trainable_params)) optimizer = BERTAdam(all_trainable_params,lr=args.learning_rate, warmup=args.warmup_proportion,t_total=num_train_steps,schedule=args.schedule, s_opt1=args.s_opt1, s_opt2=args.s_opt2, s_opt3=args.s_opt3)",
"fake_examples2, fake_features2 = read_and_convert(args.fake_file_2,is_training=True, do_lower_case=args.do_lower_case, read_fn=read_squad_examples,convert_fn=convert_fn) train_examples += fake_examples2 train_features",
"check device, n_gpu = args_check(args) os.makedirs(args.output_dir, exist_ok=True) forward_batch_size = int(args.train_batch_size",
"eval_examples=eval_examples, eval_features=eval_features, args=args) with distiller: distiller.train(optimizer, scheduler=None, dataloader=train_dataloader, num_epochs=args.num_train_epochs, callback=callback_func)",
"{}, should be >= 1\".format( args.gradient_accumulation_steps)) if not args.do_train and",
"!= -1)) args.n_gpu = n_gpu args.device = device return device,",
"1: if args.local_rank != -1: raise NotImplementedError elif n_gpu >",
"BertForQASimple, BertForQASimpleAdaptorTraining from textbrewer import DistillationConfig, TrainingConfig, BasicTrainer from torch.utils.data",
"torch.load(args.tuned_checkpoint_S,map_location='cpu') model_S.load_state_dict(state_dict_S) else: logger.info(\"Model is randomly initialized.\") model_S.to(device) if args.local_rank",
"state_weight = {k[5:]:v for k,v in state_dict_S.items() if k.startswith('bert.')} missing_keys,_",
"steps = %d\", num_train_steps) ########### DISTILLATION ########### train_config = TrainingConfig(",
"train_examples,train_features = read_and_convert(args.train_file,is_training=True, do_lower_case=args.do_lower_case, read_fn=read_squad_examples,convert_fn=convert_fn) if args.fake_file_1: fake_examples1,fake_features1 = read_and_convert(args.fake_file_1,is_training=True,",
"assert len(missing_keys)==0 elif args.load_model_type=='all': assert args.tuned_checkpoint_S is not None state_dict_S",
"if args.gradient_accumulation_steps < 1: raise ValueError(\"Invalid gradient_accumulation_steps parameter: {}, should",
"res = predict(model_S,eval_examples,eval_features,step=0,args=args) print (res) if __name__ == \"__main__\": main()",
"BertForQASimpleAdaptorTraining from textbrewer import DistillationConfig, TrainingConfig, BasicTrainer from torch.utils.data import",
"max_query_length=args.max_query_length) if args.do_train: train_examples,train_features = read_and_convert(args.train_file,is_training=True, do_lower_case=args.do_lower_case, read_fn=read_squad_examples,convert_fn=convert_fn) if args.fake_file_1:",
"import ChineseFullTokenizer from pytorch_pretrained_bert.my_modeling import BertConfig from optimization import BERTAdam",
"train_examples += fake_examples2 train_features += fake_features2 num_train_steps = int(len(train_features)/args.train_batch_size) *",
"from processing import ChineseFullTokenizer from pytorch_pretrained_bert.my_modeling import BertConfig from optimization",
"utils import read_and_convert, divide_parameters from modeling import BertForQASimple, BertForQASimpleAdaptorTraining from",
"train_examples += fake_examples1 train_features += fake_features1 if args.fake_file_2: fake_examples2, fake_features2",
"format='%(asctime)s - %(levelname)s - %(name)s - %(message)s', datefmt='%Y/%m/%d %H:%M:%S', level=logging.INFO,",
"TrainingConfig, BasicTrainer from torch.utils.data import TensorDataset, DataLoader, RandomSampler from functools",
"do_lower_case=args.do_lower_case) convert_fn = partial(convert_examples_to_features, tokenizer=tokenizer, max_seq_length=args.max_seq_length, doc_stride=args.doc_stride, max_query_length=args.max_query_length) if args.do_train:",
"logging logging.basicConfig( format='%(asctime)s - %(levelname)s - %(name)s - %(message)s', datefmt='%Y/%m/%d",
"import DistillationConfig, TrainingConfig, BasicTrainer from torch.utils.data import TensorDataset, DataLoader, RandomSampler",
"else \"cpu\") n_gpu = torch.cuda.device_count() if not args.no_cuda else 0",
"assert args.max_seq_length <= bert_config_S.max_position_embeddings #read data train_examples = None train_features",
"of all_trainable_params: %d\", len(all_trainable_params)) optimizer = BERTAdam(all_trainable_params,lr=args.learning_rate, warmup=args.warmup_proportion,t_total=num_train_steps,schedule=args.schedule, s_opt1=args.s_opt1, s_opt2=args.s_opt2,",
"train_dataloader = DataLoader(train_dataset, sampler=train_sampler, batch_size=args.forward_batch_size,drop_last=True) callback_func = partial(predict, eval_examples=eval_examples, eval_features=eval_features,",
"fake_features2 = read_and_convert(args.fake_file_2,is_training=True, do_lower_case=args.do_lower_case, read_fn=read_squad_examples,convert_fn=convert_fn) train_examples += fake_examples2 train_features +=",
"args.no_cuda else 0 else: device = torch.device(\"cuda\", args.local_rank) n_gpu =",
"train_examples = None train_features = None eval_examples = None eval_features",
"= logging.getLogger(\"Main\") import os,random import numpy as np import torch",
"load checkpoint model_S = BertForQASimple(bert_config_S,args) #Load student if args.load_model_type=='bert': assert",
"import logging logging.basicConfig( format='%(asctime)s - %(levelname)s - %(name)s - %(message)s',",
"= torch.load(args.tuned_checkpoint_S,map_location='cpu') model_S.load_state_dict(state_dict_S) else: logger.info(\"Model is randomly initialized.\") model_S.to(device) if",
"s_opt1=args.s_opt1, s_opt2=args.s_opt2, s_opt3=args.s_opt3) logger.info(\"***** Running training *****\") logger.info(\" Num orig",
"+= fake_features1 if args.fake_file_2: fake_examples2, fake_features2 = read_and_convert(args.fake_file_2,is_training=True, do_lower_case=args.do_lower_case, read_fn=read_squad_examples,convert_fn=convert_fn)",
"for f in train_features], dtype=torch.long) train_dataset = TensorDataset(all_input_ids, all_segment_ids, all_input_mask,",
"from pytorch_pretrained_bert.my_modeling import BertConfig from optimization import BERTAdam import config",
"not args.no_cuda else 0 else: device = torch.device(\"cuda\", args.local_rank) n_gpu",
"device, n_gpu, bool(args.local_rank != -1)) args.n_gpu = n_gpu args.device =",
"all_doc_mask, all_start_positions, all_end_positions) if args.local_rank == -1: train_sampler = RandomSampler(train_dataset)",
"#load bert config bert_config_S = BertConfig.from_json_file(args.bert_config_file_S) assert args.max_seq_length <= bert_config_S.max_position_embeddings",
"num_train_steps = None tokenizer = ChineseFullTokenizer(vocab_file=args.vocab_file, do_lower_case=args.do_lower_case) convert_fn = partial(convert_examples_to_features,",
"n_gpu = 1 torch.distributed.init_process_group(backend='nccl') logger.info(\"device %s n_gpu %d distributed training",
"in train_features], dtype=torch.long) all_start_positions = torch.tensor([f.start_position for f in train_features],",
"tokenizer = ChineseFullTokenizer(vocab_file=args.vocab_file, do_lower_case=args.do_lower_case) convert_fn = partial(convert_examples_to_features, tokenizer=tokenizer, max_seq_length=args.max_seq_length, doc_stride=args.doc_stride,",
"and load checkpoint model_S = BertForQASimple(bert_config_S,args) #Load student if args.load_model_type=='bert':",
"args.max_seq_length <= bert_config_S.max_position_embeddings #read data train_examples = None train_features =",
"is randomly initialized.\") model_S.to(device) if args.local_rank != -1 or n_gpu",
"dataloader=train_dataloader, num_epochs=args.num_train_epochs, callback=callback_func) if not args.do_train and args.do_predict: res =",
"empty.\") if args.gradient_accumulation_steps < 1: raise ValueError(\"Invalid gradient_accumulation_steps parameter: {},",
"BertConfig from optimization import BERTAdam import config from utils import",
"seeds torch.manual_seed(args.random_seed) torch.cuda.manual_seed_all(args.random_seed) np.random.seed(args.random_seed) random.seed(args.random_seed) #arguments check device, n_gpu =",
"args.device = device return device, n_gpu def main(): #parse arguments",
"if not args.do_train and not args.do_predict: raise ValueError(\"At least one",
"read_and_convert(args.train_file,is_training=True, do_lower_case=args.do_lower_case, read_fn=read_squad_examples,convert_fn=convert_fn) if args.fake_file_1: fake_examples1,fake_features1 = read_and_convert(args.fake_file_1,is_training=True, do_lower_case=args.do_lower_case, read_fn=read_squad_examples,convert_fn=convert_fn)",
"predict def args_check(args): if os.path.exists(args.output_dir) and os.listdir(args.output_dir): logger.warning(\"Output directory ()",
"state_dict_S = torch.load(args.tuned_checkpoint_S,map_location='cpu') model_S.load_state_dict(state_dict_S) else: logger.info(\"Model is randomly initialized.\") model_S.to(device)",
"processing import ChineseFullTokenizer from pytorch_pretrained_bert.my_modeling import BertConfig from optimization import",
"= args.device) distiller = BasicTrainer(train_config = train_config, model = model_S,",
"already exists and is not empty.\") if args.gradient_accumulation_steps < 1:",
"exist_ok=True) forward_batch_size = int(args.train_batch_size / args.gradient_accumulation_steps) args.forward_batch_size = forward_batch_size #load",
"examples = %d\", len(train_features)) logger.info(\" Forward batch size = %d\",",
"n_gpu > 1: if args.local_rank != -1: raise NotImplementedError elif",
"DataLoader, RandomSampler from functools import partial from train_eval import predict",
"map_location='cpu') state_weight = {k[5:]:v for k,v in state_dict_S.items() if k.startswith('bert.')}",
"train_sampler = RandomSampler(train_dataset) else: raise NotImplementedError train_dataloader = DataLoader(train_dataset, sampler=train_sampler,",
"= torch.device(\"cuda\", args.local_rank) n_gpu = 1 torch.distributed.init_process_group(backend='nccl') logger.info(\"device %s n_gpu",
"args.local_rank != -1 or n_gpu > 1: if args.local_rank !=",
"numpy as np import torch from processing import convert_examples_to_features, read_squad_examples",
"all_input_mask, all_doc_mask, all_start_positions, all_end_positions) if args.local_rank == -1: train_sampler =",
"train_features], dtype=torch.long) train_dataset = TensorDataset(all_input_ids, all_segment_ids, all_input_mask, all_doc_mask, all_start_positions, all_end_positions)",
"from utils import read_and_convert, divide_parameters from modeling import BertForQASimple, BertForQASimpleAdaptorTraining",
"= model_S.bert.load_state_dict(state_weight,strict=False) assert len(missing_keys)==0 elif args.load_model_type=='all': assert args.tuned_checkpoint_S is not",
"args.local_rank != -1: raise NotImplementedError elif n_gpu > 1: model_S",
"import read_and_convert, divide_parameters from modeling import BertForQASimple, BertForQASimpleAdaptorTraining from textbrewer",
"-1: raise NotImplementedError elif n_gpu > 1: model_S = torch.nn.DataParallel(model_S)",
"forward_batch_size = int(args.train_batch_size / args.gradient_accumulation_steps) args.forward_batch_size = forward_batch_size #load bert",
"`do_predict` must be True.\") if args.local_rank == -1 or args.no_cuda:",
"args_check(args) os.makedirs(args.output_dir, exist_ok=True) forward_batch_size = int(args.train_batch_size / args.gradient_accumulation_steps) args.forward_batch_size =",
"= torch.nn.DataParallel(model_S) #,output_device=n_gpu-1) if args.do_train: #parameters params = list(model_S.named_parameters()) all_trainable_params",
"torch.tensor([f.start_position for f in train_features], dtype=torch.long) all_end_positions = torch.tensor([f.end_position for",
"np import torch from processing import convert_examples_to_features, read_squad_examples from processing",
"= TensorDataset(all_input_ids, all_segment_ids, all_input_mask, all_doc_mask, all_start_positions, all_end_positions) if args.local_rank ==",
"= None eval_features = None num_train_steps = None tokenizer =",
"Num orig examples = %d\", len(train_examples)) logger.info(\" Num split examples",
"for k,v in vars(args).items(): logger.info(f\"{k}:{v}\") #set seeds torch.manual_seed(args.random_seed) torch.cuda.manual_seed_all(args.random_seed) np.random.seed(args.random_seed)",
"model = model_S, adaptor = BertForQASimpleAdaptorTraining) all_input_ids = torch.tensor([f.input_ids for",
"train_features], dtype=torch.long) all_input_mask = torch.tensor([f.input_mask for f in train_features], dtype=torch.long)",
"1 torch.distributed.init_process_group(backend='nccl') logger.info(\"device %s n_gpu %d distributed training %r\", device,",
"bert_config_S = BertConfig.from_json_file(args.bert_config_file_S) assert args.max_seq_length <= bert_config_S.max_position_embeddings #read data train_examples",
"args.no_cuda else \"cpu\") n_gpu = torch.cuda.device_count() if not args.no_cuda else",
"= torch.tensor([f.segment_ids for f in train_features], dtype=torch.long) all_start_positions = torch.tensor([f.start_position",
"torch.tensor([f.input_mask for f in train_features], dtype=torch.long) all_doc_mask = torch.tensor([f.doc_mask for",
"= divide_parameters(params, lr=args.learning_rate) logger.info(\"Length of all_trainable_params: %d\", len(all_trainable_params)) optimizer =",
"missing_keys,_ = model_S.bert.load_state_dict(state_weight,strict=False) assert len(missing_keys)==0 elif args.load_model_type=='all': assert args.tuned_checkpoint_S is",
"#,output_device=n_gpu-1) if args.do_train: #parameters params = list(model_S.named_parameters()) all_trainable_params = divide_parameters(params,",
"= torch.tensor([f.start_position for f in train_features], dtype=torch.long) all_end_positions = torch.tensor([f.end_position",
"args.ckpt_frequency, log_dir = args.output_dir, output_dir = args.output_dir, device = args.device)",
"<= bert_config_S.max_position_embeddings #read data train_examples = None train_features = None",
"*****\") logger.info(\" Num orig examples = %d\", len(train_examples)) logger.info(\" Num",
"os.makedirs(args.output_dir, exist_ok=True) forward_batch_size = int(args.train_batch_size / args.gradient_accumulation_steps) args.forward_batch_size = forward_batch_size",
"if args.local_rank == -1: train_sampler = RandomSampler(train_dataset) else: raise NotImplementedError",
"from textbrewer import DistillationConfig, TrainingConfig, BasicTrainer from torch.utils.data import TensorDataset,",
">= 1\".format( args.gradient_accumulation_steps)) if not args.do_train and not args.do_predict: raise",
"must be True.\") if args.local_rank == -1 or args.no_cuda: device",
"orig examples = %d\", len(train_examples)) logger.info(\" Num split examples =",
"== -1: train_sampler = RandomSampler(train_dataset) else: raise NotImplementedError train_dataloader =",
"train_config = TrainingConfig( gradient_accumulation_steps = args.gradient_accumulation_steps, ckpt_frequency = args.ckpt_frequency, log_dir",
"%r\", device, n_gpu, bool(args.local_rank != -1)) args.n_gpu = n_gpu args.device",
"from processing import convert_examples_to_features, read_squad_examples from processing import ChineseFullTokenizer from",
"logger.info(\"Length of all_trainable_params: %d\", len(all_trainable_params)) optimizer = BERTAdam(all_trainable_params,lr=args.learning_rate, warmup=args.warmup_proportion,t_total=num_train_steps,schedule=args.schedule, s_opt1=args.s_opt1,",
"args.n_gpu = n_gpu args.device = device return device, n_gpu def",
"split examples = %d\", len(train_features)) logger.info(\" Forward batch size =",
"== -1 or args.no_cuda: device = torch.device(\"cuda\" if torch.cuda.is_available() and",
"raise NotImplementedError train_dataloader = DataLoader(train_dataset, sampler=train_sampler, batch_size=args.forward_batch_size,drop_last=True) callback_func = partial(predict,",
"logger.info(\"Model is randomly initialized.\") model_S.to(device) if args.local_rank != -1 or",
"np.random.seed(args.random_seed) random.seed(args.random_seed) #arguments check device, n_gpu = args_check(args) os.makedirs(args.output_dir, exist_ok=True)",
"optimization import BERTAdam import config from utils import read_and_convert, divide_parameters",
"not args.do_train and not args.do_predict: raise ValueError(\"At least one of",
"train_features += fake_features2 num_train_steps = int(len(train_features)/args.train_batch_size) * args.num_train_epochs if args.do_predict:",
"f in train_features], dtype=torch.long) all_doc_mask = torch.tensor([f.doc_mask for f in",
"train_dataset = TensorDataset(all_input_ids, all_segment_ids, all_input_mask, all_doc_mask, all_start_positions, all_end_positions) if args.local_rank",
"log_dir = args.output_dir, output_dir = args.output_dir, device = args.device) distiller",
"torch.tensor([f.end_position for f in train_features], dtype=torch.long) train_dataset = TensorDataset(all_input_ids, all_segment_ids,",
"all_doc_mask = torch.tensor([f.doc_mask for f in train_features], dtype=torch.float) all_segment_ids =",
"if args.local_rank != -1 or n_gpu > 1: if args.local_rank",
"%d\", len(all_trainable_params)) optimizer = BERTAdam(all_trainable_params,lr=args.learning_rate, warmup=args.warmup_proportion,t_total=num_train_steps,schedule=args.schedule, s_opt1=args.s_opt1, s_opt2=args.s_opt2, s_opt3=args.s_opt3) logger.info(\"*****",
"if args.fake_file_2: fake_examples2, fake_features2 = read_and_convert(args.fake_file_2,is_training=True, do_lower_case=args.do_lower_case, read_fn=read_squad_examples,convert_fn=convert_fn) train_examples +=",
"raise NotImplementedError elif n_gpu > 1: model_S = torch.nn.DataParallel(model_S) #,output_device=n_gpu-1)",
"vars(args).items(): logger.info(f\"{k}:{v}\") #set seeds torch.manual_seed(args.random_seed) torch.cuda.manual_seed_all(args.random_seed) np.random.seed(args.random_seed) random.seed(args.random_seed) #arguments check",
"scheduler=None, dataloader=train_dataloader, num_epochs=args.num_train_epochs, callback=callback_func) if not args.do_train and args.do_predict: res",
"all_start_positions = torch.tensor([f.start_position for f in train_features], dtype=torch.long) all_end_positions =",
"= args_check(args) os.makedirs(args.output_dir, exist_ok=True) forward_batch_size = int(args.train_batch_size / args.gradient_accumulation_steps) args.forward_batch_size",
"dtype=torch.long) train_dataset = TensorDataset(all_input_ids, all_segment_ids, all_input_mask, all_doc_mask, all_start_positions, all_end_positions) if",
"Model and load checkpoint model_S = BertForQASimple(bert_config_S,args) #Load student if",
"sampler=train_sampler, batch_size=args.forward_batch_size,drop_last=True) callback_func = partial(predict, eval_examples=eval_examples, eval_features=eval_features, args=args) with distiller:",
"or `do_predict` must be True.\") if args.local_rank == -1 or",
"= train_config, model = model_S, adaptor = BertForQASimpleAdaptorTraining) all_input_ids =",
"k,v in state_dict_S.items() if k.startswith('bert.')} missing_keys,_ = model_S.bert.load_state_dict(state_weight,strict=False) assert len(missing_keys)==0",
"for f in train_features], dtype=torch.long) all_input_mask = torch.tensor([f.input_mask for f",
"1: model_S = torch.nn.DataParallel(model_S) #,output_device=n_gpu-1) if args.do_train: #parameters params =",
"- %(message)s', datefmt='%Y/%m/%d %H:%M:%S', level=logging.INFO, ) logger = logging.getLogger(\"Main\") import",
"0 else: device = torch.device(\"cuda\", args.local_rank) n_gpu = 1 torch.distributed.init_process_group(backend='nccl')",
"os.path.exists(args.output_dir) and os.listdir(args.output_dir): logger.warning(\"Output directory () already exists and is",
"config bert_config_S = BertConfig.from_json_file(args.bert_config_file_S) assert args.max_seq_length <= bert_config_S.max_position_embeddings #read data",
"dtype=torch.long) all_input_mask = torch.tensor([f.input_mask for f in train_features], dtype=torch.long) all_doc_mask",
"BERTAdam import config from utils import read_and_convert, divide_parameters from modeling",
"%d distributed training %r\", device, n_gpu, bool(args.local_rank != -1)) args.n_gpu",
"if args.do_predict: eval_examples,eval_features = read_and_convert(args.predict_file,is_training=False, do_lower_case=args.do_lower_case, read_fn=read_squad_examples,convert_fn=convert_fn) #Build Model and",
"all_segment_ids = torch.tensor([f.segment_ids for f in train_features], dtype=torch.long) all_start_positions =",
"bool(args.local_rank != -1)) args.n_gpu = n_gpu args.device = device return",
"dtype=torch.long) all_end_positions = torch.tensor([f.end_position for f in train_features], dtype=torch.long) train_dataset",
"device = torch.device(\"cuda\", args.local_rank) n_gpu = 1 torch.distributed.init_process_group(backend='nccl') logger.info(\"device %s",
"%H:%M:%S', level=logging.INFO, ) logger = logging.getLogger(\"Main\") import os,random import numpy",
"n_gpu, bool(args.local_rank != -1)) args.n_gpu = n_gpu args.device = device",
"bert config bert_config_S = BertConfig.from_json_file(args.bert_config_file_S) assert args.max_seq_length <= bert_config_S.max_position_embeddings #read",
"or n_gpu > 1: if args.local_rank != -1: raise NotImplementedError",
"elif args.load_model_type=='all': assert args.tuned_checkpoint_S is not None state_dict_S = torch.load(args.tuned_checkpoint_S,map_location='cpu')",
"num_epochs=args.num_train_epochs, callback=callback_func) if not args.do_train and args.do_predict: res = predict(model_S,eval_examples,eval_features,step=0,args=args)",
"- %(name)s - %(message)s', datefmt='%Y/%m/%d %H:%M:%S', level=logging.INFO, ) logger =",
"= torch.tensor([f.end_position for f in train_features], dtype=torch.long) train_dataset = TensorDataset(all_input_ids,",
"if args.fake_file_1: fake_examples1,fake_features1 = read_and_convert(args.fake_file_1,is_training=True, do_lower_case=args.do_lower_case, read_fn=read_squad_examples,convert_fn=convert_fn) train_examples += fake_examples1",
"#Build Model and load checkpoint model_S = BertForQASimple(bert_config_S,args) #Load student",
"from train_eval import predict def args_check(args): if os.path.exists(args.output_dir) and os.listdir(args.output_dir):",
"NotImplementedError elif n_gpu > 1: model_S = torch.nn.DataParallel(model_S) #,output_device=n_gpu-1) if",
"logger.info(\"***** Running training *****\") logger.info(\" Num orig examples = %d\",",
"= ChineseFullTokenizer(vocab_file=args.vocab_file, do_lower_case=args.do_lower_case) convert_fn = partial(convert_examples_to_features, tokenizer=tokenizer, max_seq_length=args.max_seq_length, doc_stride=args.doc_stride, max_query_length=args.max_query_length)",
"train_features = None eval_examples = None eval_features = None num_train_steps",
"None eval_features = None num_train_steps = None tokenizer = ChineseFullTokenizer(vocab_file=args.vocab_file,",
"read_fn=read_squad_examples,convert_fn=convert_fn) train_examples += fake_examples1 train_features += fake_features1 if args.fake_file_2: fake_examples2,",
"= torch.load(args.init_checkpoint_S, map_location='cpu') state_weight = {k[5:]:v for k,v in state_dict_S.items()",
"from torch.utils.data import TensorDataset, DataLoader, RandomSampler from functools import partial",
"len(all_trainable_params)) optimizer = BERTAdam(all_trainable_params,lr=args.learning_rate, warmup=args.warmup_proportion,t_total=num_train_steps,schedule=args.schedule, s_opt1=args.s_opt1, s_opt2=args.s_opt2, s_opt3=args.s_opt3) logger.info(\"***** Running",
"BertForQASimpleAdaptorTraining) all_input_ids = torch.tensor([f.input_ids for f in train_features], dtype=torch.long) all_input_mask",
"dtype=torch.float) all_segment_ids = torch.tensor([f.segment_ids for f in train_features], dtype=torch.long) all_start_positions",
"f in train_features], dtype=torch.long) all_end_positions = torch.tensor([f.end_position for f in",
"forward_batch_size #load bert config bert_config_S = BertConfig.from_json_file(args.bert_config_file_S) assert args.max_seq_length <=",
"= n_gpu args.device = device return device, n_gpu def main():",
"raise ValueError(\"Invalid gradient_accumulation_steps parameter: {}, should be >= 1\".format( args.gradient_accumulation_steps))",
"and not args.do_predict: raise ValueError(\"At least one of `do_train` or",
"= BertForQASimple(bert_config_S,args) #Load student if args.load_model_type=='bert': assert args.init_checkpoint_S is not",
"len(missing_keys)==0 elif args.load_model_type=='all': assert args.tuned_checkpoint_S is not None state_dict_S =",
"= int(args.train_batch_size / args.gradient_accumulation_steps) args.forward_batch_size = forward_batch_size #load bert config",
"optimizer = BERTAdam(all_trainable_params,lr=args.learning_rate, warmup=args.warmup_proportion,t_total=num_train_steps,schedule=args.schedule, s_opt1=args.s_opt1, s_opt2=args.s_opt2, s_opt3=args.s_opt3) logger.info(\"***** Running training",
"for f in train_features], dtype=torch.long) all_end_positions = torch.tensor([f.end_position for f",
"%d\", forward_batch_size) logger.info(\" Num backward steps = %d\", num_train_steps) ###########",
"len(train_examples)) logger.info(\" Num split examples = %d\", len(train_features)) logger.info(\" Forward",
"= read_and_convert(args.train_file,is_training=True, do_lower_case=args.do_lower_case, read_fn=read_squad_examples,convert_fn=convert_fn) if args.fake_file_1: fake_examples1,fake_features1 = read_and_convert(args.fake_file_1,is_training=True, do_lower_case=args.do_lower_case,",
"ValueError(\"Invalid gradient_accumulation_steps parameter: {}, should be >= 1\".format( args.gradient_accumulation_steps)) if",
"read_fn=read_squad_examples,convert_fn=convert_fn) if args.fake_file_1: fake_examples1,fake_features1 = read_and_convert(args.fake_file_1,is_training=True, do_lower_case=args.do_lower_case, read_fn=read_squad_examples,convert_fn=convert_fn) train_examples +=",
"RandomSampler(train_dataset) else: raise NotImplementedError train_dataloader = DataLoader(train_dataset, sampler=train_sampler, batch_size=args.forward_batch_size,drop_last=True) callback_func",
"for f in train_features], dtype=torch.long) all_doc_mask = torch.tensor([f.doc_mask for f",
"import os,random import numpy as np import torch from processing",
"or args.no_cuda: device = torch.device(\"cuda\" if torch.cuda.is_available() and not args.no_cuda",
") logger = logging.getLogger(\"Main\") import os,random import numpy as np",
"adaptor = BertForQASimpleAdaptorTraining) all_input_ids = torch.tensor([f.input_ids for f in train_features],",
"= torch.tensor([f.doc_mask for f in train_features], dtype=torch.float) all_segment_ids = torch.tensor([f.segment_ids",
"dtype=torch.long) all_doc_mask = torch.tensor([f.doc_mask for f in train_features], dtype=torch.float) all_segment_ids",
"= torch.tensor([f.input_mask for f in train_features], dtype=torch.long) all_doc_mask = torch.tensor([f.doc_mask",
"import convert_examples_to_features, read_squad_examples from processing import ChineseFullTokenizer from pytorch_pretrained_bert.my_modeling import",
"int(len(train_features)/args.train_batch_size) * args.num_train_epochs if args.do_predict: eval_examples,eval_features = read_and_convert(args.predict_file,is_training=False, do_lower_case=args.do_lower_case, read_fn=read_squad_examples,convert_fn=convert_fn)",
"batch_size=args.forward_batch_size,drop_last=True) callback_func = partial(predict, eval_examples=eval_examples, eval_features=eval_features, args=args) with distiller: distiller.train(optimizer,",
"model_S.to(device) if args.local_rank != -1 or n_gpu > 1: if",
"training *****\") logger.info(\" Num orig examples = %d\", len(train_examples)) logger.info(\"",
"distiller.train(optimizer, scheduler=None, dataloader=train_dataloader, num_epochs=args.num_train_epochs, callback=callback_func) if not args.do_train and args.do_predict:",
"args.no_cuda: device = torch.device(\"cuda\" if torch.cuda.is_available() and not args.no_cuda else",
"import partial from train_eval import predict def args_check(args): if os.path.exists(args.output_dir)",
"is not empty.\") if args.gradient_accumulation_steps < 1: raise ValueError(\"Invalid gradient_accumulation_steps",
"BasicTrainer from torch.utils.data import TensorDataset, DataLoader, RandomSampler from functools import",
"<filename>examples/cmrc2018_example/main.trainer.py<gh_stars>1000+ import logging logging.basicConfig( format='%(asctime)s - %(levelname)s - %(name)s -",
"be >= 1\".format( args.gradient_accumulation_steps)) if not args.do_train and not args.do_predict:",
"all_input_mask = torch.tensor([f.input_mask for f in train_features], dtype=torch.long) all_doc_mask =",
"partial(predict, eval_examples=eval_examples, eval_features=eval_features, args=args) with distiller: distiller.train(optimizer, scheduler=None, dataloader=train_dataloader, num_epochs=args.num_train_epochs,",
"+= fake_features2 num_train_steps = int(len(train_features)/args.train_batch_size) * args.num_train_epochs if args.do_predict: eval_examples,eval_features",
"torch.load(args.init_checkpoint_S, map_location='cpu') state_weight = {k[5:]:v for k,v in state_dict_S.items() if",
"args.load_model_type=='bert': assert args.init_checkpoint_S is not None state_dict_S = torch.load(args.init_checkpoint_S, map_location='cpu')",
"= args.gradient_accumulation_steps, ckpt_frequency = args.ckpt_frequency, log_dir = args.output_dir, output_dir =",
"not args.do_train and args.do_predict: res = predict(model_S,eval_examples,eval_features,step=0,args=args) print (res) if",
"torch.cuda.device_count() if not args.no_cuda else 0 else: device = torch.device(\"cuda\",",
"params = list(model_S.named_parameters()) all_trainable_params = divide_parameters(params, lr=args.learning_rate) logger.info(\"Length of all_trainable_params:",
"gradient_accumulation_steps = args.gradient_accumulation_steps, ckpt_frequency = args.ckpt_frequency, log_dir = args.output_dir, output_dir",
"= BertConfig.from_json_file(args.bert_config_file_S) assert args.max_seq_length <= bert_config_S.max_position_embeddings #read data train_examples =",
"torch.nn.DataParallel(model_S) #,output_device=n_gpu-1) if args.do_train: #parameters params = list(model_S.named_parameters()) all_trainable_params =",
"level=logging.INFO, ) logger = logging.getLogger(\"Main\") import os,random import numpy as",
"as np import torch from processing import convert_examples_to_features, read_squad_examples from",
"random.seed(args.random_seed) #arguments check device, n_gpu = args_check(args) os.makedirs(args.output_dir, exist_ok=True) forward_batch_size",
"parameter: {}, should be >= 1\".format( args.gradient_accumulation_steps)) if not args.do_train",
"fake_features1 if args.fake_file_2: fake_examples2, fake_features2 = read_and_convert(args.fake_file_2,is_training=True, do_lower_case=args.do_lower_case, read_fn=read_squad_examples,convert_fn=convert_fn) train_examples",
"is not None state_dict_S = torch.load(args.tuned_checkpoint_S,map_location='cpu') model_S.load_state_dict(state_dict_S) else: logger.info(\"Model is",
"ChineseFullTokenizer from pytorch_pretrained_bert.my_modeling import BertConfig from optimization import BERTAdam import",
"config.parse() args = config.args for k,v in vars(args).items(): logger.info(f\"{k}:{v}\") #set",
"args.local_rank == -1: train_sampler = RandomSampler(train_dataset) else: raise NotImplementedError train_dataloader",
"all_segment_ids, all_input_mask, all_doc_mask, all_start_positions, all_end_positions) if args.local_rank == -1: train_sampler",
"None tokenizer = ChineseFullTokenizer(vocab_file=args.vocab_file, do_lower_case=args.do_lower_case) convert_fn = partial(convert_examples_to_features, tokenizer=tokenizer, max_seq_length=args.max_seq_length,",
"logger.info(\" Num backward steps = %d\", num_train_steps) ########### DISTILLATION ###########",
"n_gpu > 1: model_S = torch.nn.DataParallel(model_S) #,output_device=n_gpu-1) if args.do_train: #parameters",
"read_fn=read_squad_examples,convert_fn=convert_fn) #Build Model and load checkpoint model_S = BertForQASimple(bert_config_S,args) #Load",
"= read_and_convert(args.fake_file_2,is_training=True, do_lower_case=args.do_lower_case, read_fn=read_squad_examples,convert_fn=convert_fn) train_examples += fake_examples2 train_features += fake_features2",
"= args.output_dir, output_dir = args.output_dir, device = args.device) distiller =",
"= BasicTrainer(train_config = train_config, model = model_S, adaptor = BertForQASimpleAdaptorTraining)",
"ckpt_frequency = args.ckpt_frequency, log_dir = args.output_dir, output_dir = args.output_dir, device",
"all_end_positions) if args.local_rank == -1: train_sampler = RandomSampler(train_dataset) else: raise",
"logger.info(\" Forward batch size = %d\", forward_batch_size) logger.info(\" Num backward",
"args.gradient_accumulation_steps, ckpt_frequency = args.ckpt_frequency, log_dir = args.output_dir, output_dir = args.output_dir,",
"/ args.gradient_accumulation_steps) args.forward_batch_size = forward_batch_size #load bert config bert_config_S =",
"args_check(args): if os.path.exists(args.output_dir) and os.listdir(args.output_dir): logger.warning(\"Output directory () already exists",
"args.do_train: #parameters params = list(model_S.named_parameters()) all_trainable_params = divide_parameters(params, lr=args.learning_rate) logger.info(\"Length",
"= torch.cuda.device_count() if not args.no_cuda else 0 else: device =",
"read_and_convert(args.fake_file_2,is_training=True, do_lower_case=args.do_lower_case, read_fn=read_squad_examples,convert_fn=convert_fn) train_examples += fake_examples2 train_features += fake_features2 num_train_steps",
"BertConfig.from_json_file(args.bert_config_file_S) assert args.max_seq_length <= bert_config_S.max_position_embeddings #read data train_examples = None",
"modeling import BertForQASimple, BertForQASimpleAdaptorTraining from textbrewer import DistillationConfig, TrainingConfig, BasicTrainer",
"import BERTAdam import config from utils import read_and_convert, divide_parameters from",
"device, n_gpu def main(): #parse arguments config.parse() args = config.args",
"1\".format( args.gradient_accumulation_steps)) if not args.do_train and not args.do_predict: raise ValueError(\"At",
"BertForQASimple(bert_config_S,args) #Load student if args.load_model_type=='bert': assert args.init_checkpoint_S is not None",
"all_input_ids = torch.tensor([f.input_ids for f in train_features], dtype=torch.long) all_input_mask =",
"-1 or n_gpu > 1: if args.local_rank != -1: raise",
"BERTAdam(all_trainable_params,lr=args.learning_rate, warmup=args.warmup_proportion,t_total=num_train_steps,schedule=args.schedule, s_opt1=args.s_opt1, s_opt2=args.s_opt2, s_opt3=args.s_opt3) logger.info(\"***** Running training *****\") logger.info(\"",
"None train_features = None eval_examples = None eval_features = None",
"########### train_config = TrainingConfig( gradient_accumulation_steps = args.gradient_accumulation_steps, ckpt_frequency = args.ckpt_frequency,",
"logger.info(f\"{k}:{v}\") #set seeds torch.manual_seed(args.random_seed) torch.cuda.manual_seed_all(args.random_seed) np.random.seed(args.random_seed) random.seed(args.random_seed) #arguments check device,",
"int(args.train_batch_size / args.gradient_accumulation_steps) args.forward_batch_size = forward_batch_size #load bert config bert_config_S",
"#parse arguments config.parse() args = config.args for k,v in vars(args).items():",
"os,random import numpy as np import torch from processing import",
"args.local_rank) n_gpu = 1 torch.distributed.init_process_group(backend='nccl') logger.info(\"device %s n_gpu %d distributed",
"model_S.bert.load_state_dict(state_weight,strict=False) assert len(missing_keys)==0 elif args.load_model_type=='all': assert args.tuned_checkpoint_S is not None",
"train_eval import predict def args_check(args): if os.path.exists(args.output_dir) and os.listdir(args.output_dir): logger.warning(\"Output",
"= list(model_S.named_parameters()) all_trainable_params = divide_parameters(params, lr=args.learning_rate) logger.info(\"Length of all_trainable_params: %d\",",
"exists and is not empty.\") if args.gradient_accumulation_steps < 1: raise",
"config from utils import read_and_convert, divide_parameters from modeling import BertForQASimple,",
"arguments config.parse() args = config.args for k,v in vars(args).items(): logger.info(f\"{k}:{v}\")",
"Num backward steps = %d\", num_train_steps) ########### DISTILLATION ########### train_config",
"import numpy as np import torch from processing import convert_examples_to_features,",
"from optimization import BERTAdam import config from utils import read_and_convert,",
"torch.distributed.init_process_group(backend='nccl') logger.info(\"device %s n_gpu %d distributed training %r\", device, n_gpu,",
"train_config, model = model_S, adaptor = BertForQASimpleAdaptorTraining) all_input_ids = torch.tensor([f.input_ids",
"if args.load_model_type=='bert': assert args.init_checkpoint_S is not None state_dict_S = torch.load(args.init_checkpoint_S,",
"and is not empty.\") if args.gradient_accumulation_steps < 1: raise ValueError(\"Invalid",
"not None state_dict_S = torch.load(args.init_checkpoint_S, map_location='cpu') state_weight = {k[5:]:v for",
"return device, n_gpu def main(): #parse arguments config.parse() args =",
"= None eval_examples = None eval_features = None num_train_steps =",
"* args.num_train_epochs if args.do_predict: eval_examples,eval_features = read_and_convert(args.predict_file,is_training=False, do_lower_case=args.do_lower_case, read_fn=read_squad_examples,convert_fn=convert_fn) #Build",
"= args.output_dir, device = args.device) distiller = BasicTrainer(train_config = train_config,",
"doc_stride=args.doc_stride, max_query_length=args.max_query_length) if args.do_train: train_examples,train_features = read_and_convert(args.train_file,is_training=True, do_lower_case=args.do_lower_case, read_fn=read_squad_examples,convert_fn=convert_fn) if",
"in vars(args).items(): logger.info(f\"{k}:{v}\") #set seeds torch.manual_seed(args.random_seed) torch.cuda.manual_seed_all(args.random_seed) np.random.seed(args.random_seed) random.seed(args.random_seed) #arguments",
"args.do_predict: res = predict(model_S,eval_examples,eval_features,step=0,args=args) print (res) if __name__ == \"__main__\":",
"read_squad_examples from processing import ChineseFullTokenizer from pytorch_pretrained_bert.my_modeling import BertConfig from",
"config.args for k,v in vars(args).items(): logger.info(f\"{k}:{v}\") #set seeds torch.manual_seed(args.random_seed) torch.cuda.manual_seed_all(args.random_seed)",
"distiller = BasicTrainer(train_config = train_config, model = model_S, adaptor =",
"= %d\", forward_batch_size) logger.info(\" Num backward steps = %d\", num_train_steps)",
"#arguments check device, n_gpu = args_check(args) os.makedirs(args.output_dir, exist_ok=True) forward_batch_size =",
"model_S.load_state_dict(state_dict_S) else: logger.info(\"Model is randomly initialized.\") model_S.to(device) if args.local_rank !=",
"convert_fn = partial(convert_examples_to_features, tokenizer=tokenizer, max_seq_length=args.max_seq_length, doc_stride=args.doc_stride, max_query_length=args.max_query_length) if args.do_train: train_examples,train_features",
"else: logger.info(\"Model is randomly initialized.\") model_S.to(device) if args.local_rank != -1",
"TensorDataset(all_input_ids, all_segment_ids, all_input_mask, all_doc_mask, all_start_positions, all_end_positions) if args.local_rank == -1:",
"all_trainable_params = divide_parameters(params, lr=args.learning_rate) logger.info(\"Length of all_trainable_params: %d\", len(all_trainable_params)) optimizer",
"n_gpu args.device = device return device, n_gpu def main(): #parse",
"%(message)s', datefmt='%Y/%m/%d %H:%M:%S', level=logging.INFO, ) logger = logging.getLogger(\"Main\") import os,random",
"not args.do_predict: raise ValueError(\"At least one of `do_train` or `do_predict`",
"Running training *****\") logger.info(\" Num orig examples = %d\", len(train_examples))",
"if k.startswith('bert.')} missing_keys,_ = model_S.bert.load_state_dict(state_weight,strict=False) assert len(missing_keys)==0 elif args.load_model_type=='all': assert",
"= torch.device(\"cuda\" if torch.cuda.is_available() and not args.no_cuda else \"cpu\") n_gpu",
"in train_features], dtype=torch.long) all_doc_mask = torch.tensor([f.doc_mask for f in train_features],",
"state_dict_S = torch.load(args.init_checkpoint_S, map_location='cpu') state_weight = {k[5:]:v for k,v in",
"forward_batch_size) logger.info(\" Num backward steps = %d\", num_train_steps) ########### DISTILLATION",
"if args.do_train: train_examples,train_features = read_and_convert(args.train_file,is_training=True, do_lower_case=args.do_lower_case, read_fn=read_squad_examples,convert_fn=convert_fn) if args.fake_file_1: fake_examples1,fake_features1",
"#Load student if args.load_model_type=='bert': assert args.init_checkpoint_S is not None state_dict_S",
"do_lower_case=args.do_lower_case, read_fn=read_squad_examples,convert_fn=convert_fn) if args.fake_file_1: fake_examples1,fake_features1 = read_and_convert(args.fake_file_1,is_training=True, do_lower_case=args.do_lower_case, read_fn=read_squad_examples,convert_fn=convert_fn) train_examples",
"args.gradient_accumulation_steps < 1: raise ValueError(\"Invalid gradient_accumulation_steps parameter: {}, should be",
"= BertForQASimpleAdaptorTraining) all_input_ids = torch.tensor([f.input_ids for f in train_features], dtype=torch.long)",
"if os.path.exists(args.output_dir) and os.listdir(args.output_dir): logger.warning(\"Output directory () already exists and",
"n_gpu %d distributed training %r\", device, n_gpu, bool(args.local_rank != -1))",
"logger = logging.getLogger(\"Main\") import os,random import numpy as np import",
"device return device, n_gpu def main(): #parse arguments config.parse() args",
"do_lower_case=args.do_lower_case, read_fn=read_squad_examples,convert_fn=convert_fn) #Build Model and load checkpoint model_S = BertForQASimple(bert_config_S,args)",
"model_S = BertForQASimple(bert_config_S,args) #Load student if args.load_model_type=='bert': assert args.init_checkpoint_S is",
"one of `do_train` or `do_predict` must be True.\") if args.local_rank",
"initialized.\") model_S.to(device) if args.local_rank != -1 or n_gpu > 1:",
"-1: train_sampler = RandomSampler(train_dataset) else: raise NotImplementedError train_dataloader = DataLoader(train_dataset,",
"RandomSampler from functools import partial from train_eval import predict def",
"else: device = torch.device(\"cuda\", args.local_rank) n_gpu = 1 torch.distributed.init_process_group(backend='nccl') logger.info(\"device",
"partial from train_eval import predict def args_check(args): if os.path.exists(args.output_dir) and",
"args.num_train_epochs if args.do_predict: eval_examples,eval_features = read_and_convert(args.predict_file,is_training=False, do_lower_case=args.do_lower_case, read_fn=read_squad_examples,convert_fn=convert_fn) #Build Model",
"%d\", len(train_examples)) logger.info(\" Num split examples = %d\", len(train_features)) logger.info(\"",
"be True.\") if args.local_rank == -1 or args.no_cuda: device =",
"{k[5:]:v for k,v in state_dict_S.items() if k.startswith('bert.')} missing_keys,_ = model_S.bert.load_state_dict(state_weight,strict=False)",
"divide_parameters(params, lr=args.learning_rate) logger.info(\"Length of all_trainable_params: %d\", len(all_trainable_params)) optimizer = BERTAdam(all_trainable_params,lr=args.learning_rate,",
"f in train_features], dtype=torch.long) train_dataset = TensorDataset(all_input_ids, all_segment_ids, all_input_mask, all_doc_mask,",
"!= -1 or n_gpu > 1: if args.local_rank != -1:",
"distiller: distiller.train(optimizer, scheduler=None, dataloader=train_dataloader, num_epochs=args.num_train_epochs, callback=callback_func) if not args.do_train and",
"DistillationConfig, TrainingConfig, BasicTrainer from torch.utils.data import TensorDataset, DataLoader, RandomSampler from",
"backward steps = %d\", num_train_steps) ########### DISTILLATION ########### train_config =",
"all_end_positions = torch.tensor([f.end_position for f in train_features], dtype=torch.long) train_dataset =",
"f in train_features], dtype=torch.long) all_input_mask = torch.tensor([f.input_mask for f in",
"= read_and_convert(args.fake_file_1,is_training=True, do_lower_case=args.do_lower_case, read_fn=read_squad_examples,convert_fn=convert_fn) train_examples += fake_examples1 train_features += fake_features1",
"import predict def args_check(args): if os.path.exists(args.output_dir) and os.listdir(args.output_dir): logger.warning(\"Output directory",
"train_features], dtype=torch.long) all_doc_mask = torch.tensor([f.doc_mask for f in train_features], dtype=torch.float)",
"for f in train_features], dtype=torch.long) all_start_positions = torch.tensor([f.start_position for f",
"datefmt='%Y/%m/%d %H:%M:%S', level=logging.INFO, ) logger = logging.getLogger(\"Main\") import os,random import",
"args.gradient_accumulation_steps) args.forward_batch_size = forward_batch_size #load bert config bert_config_S = BertConfig.from_json_file(args.bert_config_file_S)",
"from functools import partial from train_eval import predict def args_check(args):",
"for k,v in state_dict_S.items() if k.startswith('bert.')} missing_keys,_ = model_S.bert.load_state_dict(state_weight,strict=False) assert",
"fake_features2 num_train_steps = int(len(train_features)/args.train_batch_size) * args.num_train_epochs if args.do_predict: eval_examples,eval_features =",
"Forward batch size = %d\", forward_batch_size) logger.info(\" Num backward steps",
"fake_examples1 train_features += fake_features1 if args.fake_file_2: fake_examples2, fake_features2 = read_and_convert(args.fake_file_2,is_training=True,",
"from modeling import BertForQASimple, BertForQASimpleAdaptorTraining from textbrewer import DistillationConfig, TrainingConfig,",
"callback_func = partial(predict, eval_examples=eval_examples, eval_features=eval_features, args=args) with distiller: distiller.train(optimizer, scheduler=None,",
"s_opt2=args.s_opt2, s_opt3=args.s_opt3) logger.info(\"***** Running training *****\") logger.info(\" Num orig examples",
"train_features], dtype=torch.long) all_start_positions = torch.tensor([f.start_position for f in train_features], dtype=torch.long)",
"TrainingConfig( gradient_accumulation_steps = args.gradient_accumulation_steps, ckpt_frequency = args.ckpt_frequency, log_dir = args.output_dir,",
"eval_examples = None eval_features = None num_train_steps = None tokenizer",
"() already exists and is not empty.\") if args.gradient_accumulation_steps <",
"= None train_features = None eval_examples = None eval_features =",
"textbrewer import DistillationConfig, TrainingConfig, BasicTrainer from torch.utils.data import TensorDataset, DataLoader,",
"None eval_examples = None eval_features = None num_train_steps = None",
"import TensorDataset, DataLoader, RandomSampler from functools import partial from train_eval",
"functools import partial from train_eval import predict def args_check(args): if",
"%d\", len(train_features)) logger.info(\" Forward batch size = %d\", forward_batch_size) logger.info(\"",
"torch.utils.data import TensorDataset, DataLoader, RandomSampler from functools import partial from",
"= None num_train_steps = None tokenizer = ChineseFullTokenizer(vocab_file=args.vocab_file, do_lower_case=args.do_lower_case) convert_fn",
"BasicTrainer(train_config = train_config, model = model_S, adaptor = BertForQASimpleAdaptorTraining) all_input_ids",
"args.tuned_checkpoint_S is not None state_dict_S = torch.load(args.tuned_checkpoint_S,map_location='cpu') model_S.load_state_dict(state_dict_S) else: logger.info(\"Model",
"fake_examples2 train_features += fake_features2 num_train_steps = int(len(train_features)/args.train_batch_size) * args.num_train_epochs if",
"len(train_features)) logger.info(\" Forward batch size = %d\", forward_batch_size) logger.info(\" Num",
"device = args.device) distiller = BasicTrainer(train_config = train_config, model =",
"with distiller: distiller.train(optimizer, scheduler=None, dataloader=train_dataloader, num_epochs=args.num_train_epochs, callback=callback_func) if not args.do_train",
"1: raise ValueError(\"Invalid gradient_accumulation_steps parameter: {}, should be >= 1\".format(",
"\"cpu\") n_gpu = torch.cuda.device_count() if not args.no_cuda else 0 else:",
"device = torch.device(\"cuda\" if torch.cuda.is_available() and not args.no_cuda else \"cpu\")",
"args.forward_batch_size = forward_batch_size #load bert config bert_config_S = BertConfig.from_json_file(args.bert_config_file_S) assert",
"= torch.tensor([f.input_ids for f in train_features], dtype=torch.long) all_input_mask = torch.tensor([f.input_mask",
"= device return device, n_gpu def main(): #parse arguments config.parse()",
"elif n_gpu > 1: model_S = torch.nn.DataParallel(model_S) #,output_device=n_gpu-1) if args.do_train:",
"raise ValueError(\"At least one of `do_train` or `do_predict` must be",
"eval_features=eval_features, args=args) with distiller: distiller.train(optimizer, scheduler=None, dataloader=train_dataloader, num_epochs=args.num_train_epochs, callback=callback_func) if",
"args.do_predict: eval_examples,eval_features = read_and_convert(args.predict_file,is_training=False, do_lower_case=args.do_lower_case, read_fn=read_squad_examples,convert_fn=convert_fn) #Build Model and load",
"bert_config_S.max_position_embeddings #read data train_examples = None train_features = None eval_examples",
"main(): #parse arguments config.parse() args = config.args for k,v in",
"< 1: raise ValueError(\"Invalid gradient_accumulation_steps parameter: {}, should be >=",
"%s n_gpu %d distributed training %r\", device, n_gpu, bool(args.local_rank !=",
"train_features], dtype=torch.long) all_end_positions = torch.tensor([f.end_position for f in train_features], dtype=torch.long)",
"args.do_train and args.do_predict: res = predict(model_S,eval_examples,eval_features,step=0,args=args) print (res) if __name__",
"torch.tensor([f.segment_ids for f in train_features], dtype=torch.long) all_start_positions = torch.tensor([f.start_position for",
"model_S = torch.nn.DataParallel(model_S) #,output_device=n_gpu-1) if args.do_train: #parameters params = list(model_S.named_parameters())",
"num_train_steps) ########### DISTILLATION ########### train_config = TrainingConfig( gradient_accumulation_steps = args.gradient_accumulation_steps,",
"logging.getLogger(\"Main\") import os,random import numpy as np import torch from",
"os.listdir(args.output_dir): logger.warning(\"Output directory () already exists and is not empty.\")",
"= %d\", len(train_features)) logger.info(\" Forward batch size = %d\", forward_batch_size)",
"gradient_accumulation_steps parameter: {}, should be >= 1\".format( args.gradient_accumulation_steps)) if not",
"= %d\", len(train_examples)) logger.info(\" Num split examples = %d\", len(train_features))",
"args.device) distiller = BasicTrainer(train_config = train_config, model = model_S, adaptor",
"import config from utils import read_and_convert, divide_parameters from modeling import",
"least one of `do_train` or `do_predict` must be True.\") if",
"= int(len(train_features)/args.train_batch_size) * args.num_train_epochs if args.do_predict: eval_examples,eval_features = read_and_convert(args.predict_file,is_training=False, do_lower_case=args.do_lower_case,",
"assert args.tuned_checkpoint_S is not None state_dict_S = torch.load(args.tuned_checkpoint_S,map_location='cpu') model_S.load_state_dict(state_dict_S) else:",
"= forward_batch_size #load bert config bert_config_S = BertConfig.from_json_file(args.bert_config_file_S) assert args.max_seq_length",
"if not args.no_cuda else 0 else: device = torch.device(\"cuda\", args.local_rank)",
"f in train_features], dtype=torch.float) all_segment_ids = torch.tensor([f.segment_ids for f in",
"and args.do_predict: res = predict(model_S,eval_examples,eval_features,step=0,args=args) print (res) if __name__ ==",
"import BertConfig from optimization import BERTAdam import config from utils",
"dtype=torch.long) all_start_positions = torch.tensor([f.start_position for f in train_features], dtype=torch.long) all_end_positions",
"should be >= 1\".format( args.gradient_accumulation_steps)) if not args.do_train and not",
"= model_S, adaptor = BertForQASimpleAdaptorTraining) all_input_ids = torch.tensor([f.input_ids for f",
"= args.ckpt_frequency, log_dir = args.output_dir, output_dir = args.output_dir, device =",
"train_features], dtype=torch.float) all_segment_ids = torch.tensor([f.segment_ids for f in train_features], dtype=torch.long)",
"args.gradient_accumulation_steps)) if not args.do_train and not args.do_predict: raise ValueError(\"At least",
"args = config.args for k,v in vars(args).items(): logger.info(f\"{k}:{v}\") #set seeds",
"%d\", num_train_steps) ########### DISTILLATION ########### train_config = TrainingConfig( gradient_accumulation_steps =",
"-1 or args.no_cuda: device = torch.device(\"cuda\" if torch.cuda.is_available() and not",
"args.output_dir, output_dir = args.output_dir, device = args.device) distiller = BasicTrainer(train_config",
"args.init_checkpoint_S is not None state_dict_S = torch.load(args.init_checkpoint_S, map_location='cpu') state_weight =",
"do_lower_case=args.do_lower_case, read_fn=read_squad_examples,convert_fn=convert_fn) train_examples += fake_examples1 train_features += fake_features1 if args.fake_file_2:",
"torch.device(\"cuda\" if torch.cuda.is_available() and not args.no_cuda else \"cpu\") n_gpu ="
] |
[
"'trials': 2, 'max_timesteps': int(2e8), 'reward_floor': 0.0, 'reward_ceiling': 5000.0, }, {",
"}, {'env_id': 'InvertedPendulum-v1', 'trials': 3, 'max_timesteps': 1000000, 'reward_floor': 5.6, 'reward_ceiling':",
"163.9, 'reward_ceiling': 40000.0, }, { 'env_id': 'SeaquestNoFrameskip-v4', 'trials': 2, 'max_timesteps':",
"'reward_floor': -10000.0, 'reward_ceiling': 16280.0, }, {'env_id': 'MinecraftHard-v0', 'trials': 2, 'max_timesteps':",
"'Walker2d-v1', 'trials': 1, 'max_timesteps': 1000000, } ]) register_benchmark( id='Mujoco1M-v0', name='Mujoco1M',",
"100, 500]: bandit_tasks.append({ 'env_id': 'BernoulliBandit-{k}.arms-{n}.episodes-v0'.format(k=n_arms, n=n_episodes), 'trials': 1, 'max_timesteps': 10",
"25.0, 'reward_ceiling': 10000.0, }, { 'env_id': 'PitfallNoFrameskip-v4', 'trials': 2, 'max_timesteps':",
"600000, 'reward_floor': -1000.0, 'reward_ceiling': 1000.0, }, ]) register_benchmark( id='MinecraftVeryHard-v0', name='MinecraftVeryHard',",
"} ]) register_benchmark( id='Mujoco1M-v0', name='Mujoco1M', view_group=\"Control\", description='Mujoco benchmark with 1M",
"tasks=[ {'env_id': 'MinecraftDefaultWorld1-v0', 'trials': 2, 'max_timesteps': 6000000, 'reward_floor': -1000.0, 'reward_ceiling':",
"'trials': 3, 'max_timesteps': 1000000, 'reward_floor': -280.0, 'reward_ceiling': 4000.0, }, {'env_id':",
"register_benchmark( id='AtariExploration40M', scorer=scoring.TotalReward(), name='AtariExploration40M', view_group=\"Atari\", description='7 Atari games, with pixel",
"2, 'max_timesteps': int(4e7), 'reward_floor': 363.9, 'reward_ceiling': 60000.0, }, { 'env_id':",
"n_episodes, }) register_benchmark( id='BernoulliBandit-v0', name='BernoulliBandit', description='Multi-armed Bernoulli bandits', scorer=scoring.ClipTo01ThenAverage(num_episodes=1000), tasks=bandit_tasks",
"int(2e8), 'reward_floor': 163.9, 'reward_ceiling': 40000.0, }, { 'env_id': 'SeaquestNoFrameskip-v4', 'trials':",
"n_episodes in [10, 100, 500]: bandit_tasks.append({ 'env_id': 'BernoulliBandit-{k}.arms-{n}.episodes-v0'.format(k=n_arms, n=n_episodes), 'trials':",
"'trials': 2, 'max_timesteps': int(4e7), 'reward_floor': 0.0, 'reward_ceiling': 5000.0, }, {",
"'trials': 2, 'max_timesteps': int(2e8), 'reward_floor': 363.9, 'reward_ceiling': 60000.0, }, {",
"'MountainCar-v0', 'trials': 3, 'max_timesteps': 100000, 'reward_floor': -200.0, 'reward_ceiling': -100.0, },",
"'reward_ceiling': 4000.0, }, {'env_id': 'InvertedDoublePendulum-v1', 'trials': 3, 'max_timesteps': 1000000, 'reward_floor':",
"'MinecraftMaze1-v0', 'trials': 2, 'max_timesteps': 600000, 'reward_floor': -1000.0, 'reward_ceiling': 1000.0, },",
"1.7, 'reward_ceiling': 800.0, }, { 'env_id': 'EnduroNoFrameskip-v4', 'trials': 2, 'max_timesteps':",
"'trials': 1, 'max_timesteps': 1000000, }, {'env_id': 'Humanoid-v1', 'trials': 1, 'max_timesteps':",
"1000.0, }, {'env_id': 'Reacher-v1', 'trials': 3, 'max_timesteps': 1000000, 'reward_floor': -43.0,",
"'env_id': 'VentureNoFrameskip-v4', 'trials': 2, 'max_timesteps': int(4e7), 'reward_floor': 18.0, 'reward_ceiling': 100.0,",
"observations', tasks=[ { 'env_id': 'BeamRiderNoFrameskip-v4', 'trials': 2, 'max_timesteps': int(2e8), 'reward_floor':",
"'max_timesteps': int(4e7), 'reward_floor': -348.8, 'reward_ceiling': 1000.0, }, { 'env_id': 'PrivateEyeNoFrameskip-v4',",
"{'env_id': 'MinecraftMaze1-v0', 'trials': 2, 'max_timesteps': 600000, 'reward_floor': -1000.0, 'reward_ceiling': 1000.0,",
"2, 'max_timesteps': int(2e8), 'reward_floor': 163.9, 'reward_ceiling': 40000.0, }, { 'env_id':",
"}, { 'env_id': 'PongNoFrameskip-v4', 'trials': 2, 'max_timesteps': int(4e7), 'reward_floor': -20.7,",
"'env_id': 'SpaceInvadersNoFrameskip-v4', 'trials': 2, 'max_timesteps': int(2e8), 'reward_floor': 148.0, 'reward_ceiling': 30000.0,",
"0.1, 'reward_ceiling': 31.0, }, { 'env_id': 'GravitarNoFrameskip-v4', 'trials': 2, 'max_timesteps':",
"2, 'max_timesteps': int(4e7), 'reward_floor': 245.5, 'reward_ceiling': 1000.0, }, { 'env_id':",
"register_benchmark( id='MinecraftImpossible-v0', name='MinecraftImpossible', view_group=\"Minecraft\", description='Minecraft impossible benchmark', scorer=scoring.ClipTo01ThenAverage(), tasks=[ {'env_id':",
"'trials': 2, 'max_timesteps': int(2e8), 'reward_floor': 148.0, 'reward_ceiling': 30000.0, }, ])",
"]) bandit_tasks = [] for n_arms in [5, 10, 50]:",
"'reward_floor': 25.0, 'reward_ceiling': 10000.0, }, { 'env_id': 'PitfallNoFrameskip-v4', 'trials': 2,",
"n_states in [10]: for n_actions in [5]: for episode_length in",
"scorer=scoring.TotalReward(), name='Atari200M', view_group=\"Atari\", description='7 Atari games, with pixel observations', tasks=[",
"60000.0, }, { 'env_id': 'BreakoutNoFrameskip-v4', 'trials': 2, 'max_timesteps': int(2e8), 'reward_floor':",
"'max_timesteps': int(4e7), 'reward_floor': 245.5, 'reward_ceiling': 1000.0, }, { 'env_id': 'MontezumaRevengeNoFrameskip-v4',",
"1000000, 'reward_floor': 0.23, 'reward_ceiling': 500.0, }, {'env_id': 'Walker2d-v1', 'trials': 3,",
"scorer=scoring.TotalReward(), name='AtariExploration40M', view_group=\"Atari\", description='7 Atari games, with pixel observations', tasks=[",
"1, 'max_timesteps': 1000000, }, {'env_id': 'Humanoid-v1', 'trials': 1, 'max_timesteps': 1000000,",
"hard benchmark', scorer=scoring.ClipTo01ThenAverage(), tasks=[ {'env_id': 'MinecraftObstacles-v0', 'trials': 1, 'max_timesteps': 900000,",
"'reward_floor': -1000.0, 'reward_ceiling': 4160.0, }, {'env_id': 'MinecraftAttic-v0', 'trials': 1, 'max_timesteps':",
"'max_timesteps': int(2e8), 'reward_floor': -20.7, 'reward_ceiling': 21.0, }, { 'env_id': 'QbertNoFrameskip-v4',",
"'reward_ceiling': 8040.0, }, {'env_id': 'MinecraftMaze1-v0', 'trials': 2, 'max_timesteps': 600000, 'reward_floor':",
"[] for n_arms in [5, 10, 50]: for n_episodes in",
"'CartPole-v0', 'trials': 1, 'max_timesteps': 2000, }, {'env_id': 'Pendulum-v0', 'trials': 1,",
"1000000, 'reward_floor': 1.6, 'reward_ceiling': 5500.0, } ]) register_benchmark( id='MinecraftEasy-v0', name='MinecraftEasy',",
"0.0, 'reward_ceiling': 5000.0, }, { 'env_id': 'PongNoFrameskip-v4', 'trials': 2, 'max_timesteps':",
"'max_timesteps': 600000, 'reward_floor': -1000.0, 'reward_ceiling': 1000.0, }, {'env_id': 'MinecraftMaze2-v0', 'trials':",
"register_benchmark( id='Atari200M', scorer=scoring.TotalReward(), name='Atari200M', view_group=\"Atari\", description='7 Atari games, with pixel",
"description='Mujoco benchmark with 10M steps', scorer=scoring.ClipTo01ThenAverage(), tasks=[ {'env_id': 'Ant-v1', 'trials':",
"'reward_floor': 0, 'reward_ceiling': episode_length * n_episodes * 2, }) register_benchmark(",
"with pixel observations', tasks=[ { 'env_id': 'BeamRiderNoFrameskip-v4', 'trials': 2, 'max_timesteps':",
"'max_timesteps': 1000000, }, {'env_id': 'Hopper-v1', 'trials': 1, 'max_timesteps': 1000000, },",
"name='MinecraftEasy', view_group=\"Minecraft\", description='Minecraft easy benchmark', scorer=scoring.ClipTo01ThenAverage(), tasks=[ {'env_id': 'MinecraftBasic-v0', 'trials':",
"-1000.0, 'reward_ceiling': 1000.0, }, ]) register_benchmark( id='MinecraftVeryHard-v0', name='MinecraftVeryHard', view_group=\"Minecraft\", description='Minecraft",
"'reward_ceiling': 21.0, }, { 'env_id': 'QbertNoFrameskip-v4', 'trials': 2, 'max_timesteps': int(2e8),",
"]) register_benchmark( id='AtariExploration40M', scorer=scoring.TotalReward(), name='AtariExploration40M', view_group=\"Atari\", description='7 Atari games, with",
"30000.0, } ]) register_benchmark( id='AtariExploration40M', scorer=scoring.TotalReward(), name='AtariExploration40M', view_group=\"Atari\", description='7 Atari",
"bandits', scorer=scoring.ClipTo01ThenAverage(num_episodes=1000), tasks=bandit_tasks ) tabular_mdp_tasks = [] for n_states in",
"'MinecraftDefaultWorld1-v0', 'trials': 2, 'max_timesteps': 6000000, 'reward_floor': -1000.0, 'reward_ceiling': 1000.0, },",
"'reward_floor': -1000.0, 'reward_ceiling': 1040.0, }, {'env_id': 'MinecraftComplexityUsage-v0', 'trials': 1, 'max_timesteps':",
"2047.2, 'reward_ceiling': 5000.0, }, { 'env_id': 'VentureNoFrameskip-v4', 'trials': 2, 'max_timesteps':",
"scorer=scoring.ClipTo01ThenAverage(), tasks=[ {'env_id': 'MinecraftBasic-v0', 'trials': 2, 'max_timesteps': 600000, 'reward_floor': -2200.0,",
"-1000.0, 'reward_ceiling': 1040.0, }, {'env_id': 'MinecraftComplexityUsage-v0', 'trials': 1, 'max_timesteps': 600000,",
"'reward_floor': 0.0, 'reward_ceiling': 500.0, }, {'env_id': 'Acrobot-v1', 'trials': 3, 'max_timesteps':",
"'reward_floor': -43.0, 'reward_ceiling': -0.5, }, {'env_id': 'Swimmer-v1', 'trials': 3, 'max_timesteps':",
"2, 'max_timesteps': 300000, 'reward_floor': -1000.0, 'reward_ceiling': 2800.0, }, {'env_id': 'MinecraftEating1-v0',",
"1000.0, }, ]) register_benchmark( id='MinecraftVeryHard-v0', name='MinecraftVeryHard', view_group=\"Minecraft\", description='Minecraft very hard",
"2, 'max_timesteps': int(2e8), 'reward_floor': 148.0, 'reward_ceiling': 30000.0, }, ]) register_benchmark(",
"benchmark with 10M steps', scorer=scoring.ClipTo01ThenAverage(), tasks=[ {'env_id': 'Ant-v1', 'trials': 1,",
"}, { 'env_id': 'PongNoFrameskip-v4', 'trials': 2, 'max_timesteps': int(2e8), 'reward_floor': -20.7,",
"'max_timesteps': int(4e7), 'reward_floor': 18.0, 'reward_ceiling': 100.0, } ]) register_benchmark( id='ClassicControl2-v0',",
"'env_id': 'EnduroNoFrameskip-v4', 'trials': 2, 'max_timesteps': int(2e8), 'reward_floor': 0.0, 'reward_ceiling': 5000.0,",
"'max_timesteps': int(4e7), 'reward_floor': 662.8, 'reward_ceiling': 100.0, }, { 'env_id': 'SolarisNoFrameskip-v4',",
"}, {'env_id': 'Walker2d-v1', 'trials': 3, 'max_timesteps': 1000000, 'reward_floor': 1.6, 'reward_ceiling':",
"68.4, 'reward_ceiling': 100000.0, }, { 'env_id': 'SpaceInvadersNoFrameskip-v4', 'trials': 2, 'max_timesteps':",
"'env_id': 'PrivateEyeNoFrameskip-v4', 'trials': 2, 'max_timesteps': int(4e7), 'reward_floor': 662.8, 'reward_ceiling': 100.0,",
"]) ### Autogenerated by tinkerbell.benchmark.convert_benchmark.py register_benchmark( id='Mujoco10M-v0', name='Mujoco10M', view_group=\"Control\", description='Mujoco",
"'reward_ceiling': 21.0, }, { 'env_id': 'QbertNoFrameskip-v4', 'trials': 2, 'max_timesteps': int(4e7),",
"hard benchmark', scorer=scoring.ClipTo01ThenAverage(), tasks=[ {'env_id': 'MinecraftMedium-v0', 'trials': 2, 'max_timesteps': 1800000,",
"'reward_floor': 2047.2, 'reward_ceiling': 5000.0, }, { 'env_id': 'VentureNoFrameskip-v4', 'trials': 2,",
"n_actions in [5]: for episode_length in [10]: for n_episodes in",
"{'env_id': 'MinecraftDefaultWorld1-v0', 'trials': 2, 'max_timesteps': 6000000, 'reward_floor': -1000.0, 'reward_ceiling': 1000.0,",
"'reward_ceiling': 1000.0, }, {'env_id': 'Reacher-v1', 'trials': 3, 'max_timesteps': 1000000, 'reward_floor':",
"scorer=scoring.ClipTo01ThenAverage(), tasks=[ {'env_id': 'MinecraftDefaultWorld1-v0', 'trials': 2, 'max_timesteps': 6000000, 'reward_floor': -1000.0,",
"'PitfallNoFrameskip-v4', 'trials': 2, 'max_timesteps': int(4e7), 'reward_floor': -348.8, 'reward_ceiling': 1000.0, },",
"3, 'max_timesteps': 1000000, 'reward_floor': 1.6, 'reward_ceiling': 5500.0, } ]) register_benchmark(",
"= [] for n_states in [10]: for n_actions in [5]:",
"'reward_floor': 53.0, 'reward_ceiling': 10000.0, }, {'env_id': 'InvertedPendulum-v1', 'trials': 3, 'max_timesteps':",
"int(2e8), 'reward_floor': 68.4, 'reward_ceiling': 100000.0, }, { 'env_id': 'SpaceInvadersNoFrameskip-v4', 'trials':",
"tasks=[ {'env_id': 'HalfCheetah-v1', 'trials': 3, 'max_timesteps': 1000000, 'reward_floor': -280.0, 'reward_ceiling':",
"'trials': 3, 'max_timesteps': 1000000, 'reward_floor': 5.6, 'reward_ceiling': 1000.0, }, {'env_id':",
"50]: for n_episodes in [10, 100, 500]: bandit_tasks.append({ 'env_id': 'BernoulliBandit-{k}.arms-{n}.episodes-v0'.format(k=n_arms,",
"'reward_ceiling': 1000.0, }, ]) bandit_tasks = [] for n_arms in",
"for n_arms in [5, 10, 50]: for n_episodes in [10,",
"'max_timesteps': 10 ** 9, 'reward_floor': 0, 'reward_ceiling': episode_length * n_episodes",
"register_benchmark( id='ClassicControl2-v0', name='ClassicControl2', view_group=\"Control\", description='Simple classic control benchmark', scorer=scoring.ClipTo01ThenAverage(), tasks=[",
"2, 'max_timesteps': int(2e8), 'reward_floor': 1.7, 'reward_ceiling': 800.0, }, { 'env_id':",
"id='ClassicControl-v0', name='ClassicControl', view_group=\"Control\", description='Simple classic control benchmark', scorer=scoring.ClipTo01ThenAverage(), tasks=[ {'env_id':",
"'BernoulliBandit-{k}.arms-{n}.episodes-v0'.format(k=n_arms, n=n_episodes), 'trials': 1, 'max_timesteps': 10 ** 9, 'reward_floor': 0,",
"}, {'env_id': 'MinecraftMaze2-v0', 'trials': 2, 'max_timesteps': 2000000, 'reward_floor': -1000.0, 'reward_ceiling':",
"for n_episodes in [10, 25, 50, 75, 100]: tabular_mdp_tasks.append({ 'env_id':",
"'SpaceInvadersNoFrameskip-v4', 'trials': 2, 'max_timesteps': int(2e8), 'reward_floor': 148.0, 'reward_ceiling': 30000.0, },",
"in [10]: for n_episodes in [10, 25, 50, 75, 100]:",
"int(4e7), 'reward_floor': -348.8, 'reward_ceiling': 1000.0, }, { 'env_id': 'PrivateEyeNoFrameskip-v4', 'trials':",
"500.0, }, {'env_id': 'Walker2d-v1', 'trials': 3, 'max_timesteps': 1000000, 'reward_floor': 1.6,",
"2, 'max_timesteps': int(4e7), 'reward_floor': 0.0, 'reward_ceiling': 5000.0, }, { 'env_id':",
"'trials': 1, 'max_timesteps': 1000000, }, {'env_id': 'Walker2d-v1', 'trials': 1, 'max_timesteps':",
"'env_id': 'BeamRiderNoFrameskip-v4', 'trials': 2, 'max_timesteps': int(4e7), 'reward_floor': 363.9, 'reward_ceiling': 60000.0,",
"3, 'max_timesteps': 1000000, 'reward_floor': 0.23, 'reward_ceiling': 500.0, }, {'env_id': 'Walker2d-v1',",
"description='7 Atari games, with pixel observations', tasks=[ { 'env_id': 'FreewayNoFrameskip-v4',",
"30000.0, }, ]) register_benchmark( id='Atari40M', scorer=scoring.TotalReward(), name='Atari40M', view_group=\"Atari\", description='7 Atari",
"description='Simple classic control benchmark', scorer=scoring.ClipTo01ThenAverage(), tasks=[ {'env_id': 'CartPole-v1', 'trials': 3,",
"'env_id': 'SeaquestNoFrameskip-v4', 'trials': 2, 'max_timesteps': int(2e8), 'reward_floor': 68.4, 'reward_ceiling': 100000.0,",
"2, 'max_timesteps': 400000, 'reward_floor': -100.0, 'reward_ceiling': 100.0, }, {'env_id': 'MinecraftVertical-v0',",
"2, 'max_timesteps': int(4e7), 'reward_floor': 68.4, 'reward_ceiling': 100000.0, }, { 'env_id':",
"1, 'max_timesteps': 1000000, }, {'env_id': 'Walker2d-v1', 'trials': 1, 'max_timesteps': 1000000,",
"'reward_ceiling': 1000.0, }, { 'env_id': 'MontezumaRevengeNoFrameskip-v4', 'trials': 2, 'max_timesteps': int(4e7),",
"'InvertedPendulum-v1', 'trials': 3, 'max_timesteps': 1000000, 'reward_floor': 5.6, 'reward_ceiling': 1000.0, },",
"}, {'env_id': 'MinecraftDefaultFlat1-v0', 'trials': 2, 'max_timesteps': 2000000, 'reward_floor': -500.0, 'reward_ceiling':",
"-1000.0, 'reward_ceiling': 8040.0, }, {'env_id': 'MinecraftMaze1-v0', 'trials': 2, 'max_timesteps': 600000,",
"6000000, 'reward_floor': -1000.0, 'reward_ceiling': 1000.0, }, ]) bandit_tasks = []",
"id='Atari40M', scorer=scoring.TotalReward(), name='Atari40M', view_group=\"Atari\", description='7 Atari games, with pixel observations',",
"register_benchmark( id='MinecraftHard-v0', name='MinecraftHard', view_group=\"Minecraft\", description='Minecraft hard benchmark', scorer=scoring.ClipTo01ThenAverage(), tasks=[ {'env_id':",
"tasks=bandit_tasks ) tabular_mdp_tasks = [] for n_states in [10]: for",
"{'env_id': 'Pendulum-v0', 'trials': 1, 'max_timesteps': 1000, }, ]) register_benchmark( id='ClassicControl-v0',",
"games, with pixel observations', tasks=[ { 'env_id': 'FreewayNoFrameskip-v4', 'trials': 2,",
"'reward_floor': -348.8, 'reward_ceiling': 1000.0, }, { 'env_id': 'PrivateEyeNoFrameskip-v4', 'trials': 2,",
"'trials': 2, 'max_timesteps': int(4e7), 'reward_floor': 18.0, 'reward_ceiling': 100.0, } ])",
"[10, 25, 50, 75, 100]: tabular_mdp_tasks.append({ 'env_id': 'RandomTabularMDP-{s}.states-{a}.actions-{t}.timesteps-{n}.episodes-v0'.format( s=n_states, a=n_actions,",
"-200.0, 'reward_ceiling': -100.0, }, {'env_id': 'Pendulum-v0', 'trials': 3, 'max_timesteps': 200000,",
"'max_timesteps': int(4e7), 'reward_floor': 25.0, 'reward_ceiling': 10000.0, }, { 'env_id': 'PitfallNoFrameskip-v4',",
"'reward_ceiling': 60000.0, }, { 'env_id': 'BreakoutNoFrameskip-v4', 'trials': 2, 'max_timesteps': int(4e7),",
"}, {'env_id': 'Swimmer-v1', 'trials': 3, 'max_timesteps': 1000000, 'reward_floor': 0.23, 'reward_ceiling':",
"'trials': 2, 'max_timesteps': int(4e7), 'reward_floor': 1.7, 'reward_ceiling': 800.0, }, {",
"'max_timesteps': int(2e8), 'reward_floor': 0.0, 'reward_ceiling': 5000.0, }, { 'env_id': 'PongNoFrameskip-v4',",
"1, 'max_timesteps': 1000, }, ]) register_benchmark( id='ClassicControl-v0', name='ClassicControl', view_group=\"Control\", description='Simple",
"-1000.0, 'reward_ceiling': 1000.0, }, ]) bandit_tasks = [] for n_arms",
"[5]: for episode_length in [10]: for n_episodes in [10, 25,",
"2, 'max_timesteps': int(4e7), 'reward_floor': -348.8, 'reward_ceiling': 1000.0, }, { 'env_id':",
"{ 'env_id': 'QbertNoFrameskip-v4', 'trials': 2, 'max_timesteps': int(4e7), 'reward_floor': 163.9, 'reward_ceiling':",
"[] for n_states in [10]: for n_actions in [5]: for",
"'reward_floor': 1.7, 'reward_ceiling': 800.0, }, { 'env_id': 'EnduroNoFrameskip-v4', 'trials': 2,",
"'env_id': 'PitfallNoFrameskip-v4', 'trials': 2, 'max_timesteps': int(4e7), 'reward_floor': -348.8, 'reward_ceiling': 1000.0,",
"{'env_id': 'Hopper-v1', 'trials': 1, 'max_timesteps': 1000000, }, {'env_id': 'Humanoid-v1', 'trials':",
"}, {'env_id': 'Hopper-v1', 'trials': 3, 'max_timesteps': 1000000, 'reward_floor': 16.0, 'reward_ceiling':",
"245.5, 'reward_ceiling': 1000.0, }, { 'env_id': 'MontezumaRevengeNoFrameskip-v4', 'trials': 2, 'max_timesteps':",
"}, { 'env_id': 'EnduroNoFrameskip-v4', 'trials': 2, 'max_timesteps': int(2e8), 'reward_floor': 0.0,",
"1, 'max_timesteps': 10 ** 9, 'reward_floor': 0, 'reward_ceiling': episode_length *",
"register_benchmark( id='Mujoco10M-v0', name='Mujoco10M', view_group=\"Control\", description='Mujoco benchmark with 10M steps', scorer=scoring.ClipTo01ThenAverage(),",
"'max_timesteps': 100000, 'reward_floor': 0.0, 'reward_ceiling': 500.0, }, {'env_id': 'Acrobot-v1', 'trials':",
"'HumanoidStandup-v1', 'trials': 1, 'max_timesteps': 1000000, }, {'env_id': 'Walker2d-v1', 'trials': 1,",
"'reward_floor': -1000.0, 'reward_ceiling': 1000.0, }, ]) bandit_tasks = [] for",
"in [10, 100, 500]: bandit_tasks.append({ 'env_id': 'BernoulliBandit-{k}.arms-{n}.episodes-v0'.format(k=n_arms, n=n_episodes), 'trials': 1,",
"2080.0, }, {'env_id': 'MinecraftSimpleRoomMaze-v0', 'trials': 1, 'max_timesteps': 900000, 'reward_floor': -1000.0,",
"'reward_ceiling': 5000.0, }, { 'env_id': 'VentureNoFrameskip-v4', 'trials': 2, 'max_timesteps': int(4e7),",
"for n_episodes in [10, 100, 500]: bandit_tasks.append({ 'env_id': 'BernoulliBandit-{k}.arms-{n}.episodes-v0'.format(k=n_arms, n=n_episodes),",
") tabular_mdp_tasks = [] for n_states in [10]: for n_actions",
"'reward_ceiling': 0.0, }, {'env_id': 'MountainCar-v0', 'trials': 3, 'max_timesteps': 100000, 'reward_floor':",
"3, 'max_timesteps': 100000, 'reward_floor': -500.0, 'reward_ceiling': 0.0, }, {'env_id': 'MountainCar-v0',",
"148.0, 'reward_ceiling': 30000.0, }, ]) register_benchmark( id='Atari40M', scorer=scoring.TotalReward(), name='Atari40M', view_group=\"Atari\",",
"'trials': 1, 'max_timesteps': 1000000, }, {'env_id': 'HumanoidStandup-v1', 'trials': 1, 'max_timesteps':",
"view_group=\"Minecraft\", description='Minecraft easy benchmark', scorer=scoring.ClipTo01ThenAverage(), tasks=[ {'env_id': 'MinecraftBasic-v0', 'trials': 2,",
"'MinecraftObstacles-v0', 'trials': 1, 'max_timesteps': 900000, 'reward_floor': -1000.0, 'reward_ceiling': 2080.0, },",
"'trials': 2, 'max_timesteps': 1800000, 'reward_floor': -10000.0, 'reward_ceiling': 16280.0, }, {'env_id':",
"episode_length in [10]: for n_episodes in [10, 25, 50, 75,",
"### Autogenerated by tinkerbell.benchmark.convert_benchmark.py register_benchmark( id='Mujoco10M-v0', name='Mujoco10M', view_group=\"Control\", description='Mujoco benchmark",
"'SeaquestNoFrameskip-v4', 'trials': 2, 'max_timesteps': int(2e8), 'reward_floor': 68.4, 'reward_ceiling': 100000.0, },",
"'env_id': 'QbertNoFrameskip-v4', 'trials': 2, 'max_timesteps': int(4e7), 'reward_floor': 163.9, 'reward_ceiling': 40000.0,",
"tasks=[ {'env_id': 'Ant-v1', 'trials': 1, 'max_timesteps': 1000000, }, {'env_id': 'Hopper-v1',",
"scorer=scoring.ClipTo01ThenAverage(), tasks=[ {'env_id': 'MinecraftObstacles-v0', 'trials': 1, 'max_timesteps': 900000, 'reward_floor': -1000.0,",
"with 10M steps', scorer=scoring.ClipTo01ThenAverage(), tasks=[ {'env_id': 'Ant-v1', 'trials': 1, 'max_timesteps':",
"'max_timesteps': 400000, 'reward_floor': -100.0, 'reward_ceiling': 100.0, }, {'env_id': 'MinecraftVertical-v0', 'trials':",
"}, {'env_id': 'HumanoidStandup-v1', 'trials': 1, 'max_timesteps': 1000000, }, {'env_id': 'Walker2d-v1',",
"'trials': 3, 'max_timesteps': 100000, 'reward_floor': -200.0, 'reward_ceiling': -100.0, }, {'env_id':",
"for episode_length in [10]: for n_episodes in [10, 25, 50,",
"2, 'max_timesteps': int(2e8), 'reward_floor': 68.4, 'reward_ceiling': 100000.0, }, { 'env_id':",
"tasks=[ {'env_id': 'CartPole-v0', 'trials': 1, 'max_timesteps': 2000, }, {'env_id': 'Pendulum-v0',",
"{'env_id': 'Pendulum-v0', 'trials': 3, 'max_timesteps': 200000, 'reward_floor': -1400.0, 'reward_ceiling': 0.0,",
"-10000.0, 'reward_ceiling': 32640.0, }, ]) register_benchmark( id='MinecraftImpossible-v0', name='MinecraftImpossible', view_group=\"Minecraft\", description='Minecraft",
"'reward_floor': 662.8, 'reward_ceiling': 100.0, }, { 'env_id': 'SolarisNoFrameskip-v4', 'trials': 2,",
"[10]: for n_episodes in [10, 25, 50, 75, 100]: tabular_mdp_tasks.append({",
"10000.0, }, {'env_id': 'InvertedPendulum-v1', 'trials': 3, 'max_timesteps': 1000000, 'reward_floor': 5.6,",
"'max_timesteps': int(4e7), 'reward_floor': 0.1, 'reward_ceiling': 31.0, }, { 'env_id': 'GravitarNoFrameskip-v4',",
"int(4e7), 'reward_floor': 662.8, 'reward_ceiling': 100.0, }, { 'env_id': 'SolarisNoFrameskip-v4', 'trials':",
"register_benchmark( id='ClassicControl-v0', name='ClassicControl', view_group=\"Control\", description='Simple classic control benchmark', scorer=scoring.ClipTo01ThenAverage(), tasks=[",
"'MinecraftSimpleRoomMaze-v0', 'trials': 1, 'max_timesteps': 900000, 'reward_floor': -1000.0, 'reward_ceiling': 4160.0, },",
"{ 'env_id': 'PongNoFrameskip-v4', 'trials': 2, 'max_timesteps': int(2e8), 'reward_floor': -20.7, 'reward_ceiling':",
"-20.7, 'reward_ceiling': 21.0, }, { 'env_id': 'QbertNoFrameskip-v4', 'trials': 2, 'max_timesteps':",
"description='Minecraft hard benchmark', scorer=scoring.ClipTo01ThenAverage(), tasks=[ {'env_id': 'MinecraftObstacles-v0', 'trials': 1, 'max_timesteps':",
"int(2e8), 'reward_floor': 0.0, 'reward_ceiling': 5000.0, }, { 'env_id': 'PongNoFrameskip-v4', 'trials':",
"'MinecraftTrickyArena1-v0', 'trials': 2, 'max_timesteps': 300000, 'reward_floor': -1000.0, 'reward_ceiling': 2800.0, },",
"games, with pixel observations', tasks=[ { 'env_id': 'BeamRiderNoFrameskip-v4', 'trials': 2,",
"200000, 'reward_floor': -1400.0, 'reward_ceiling': 0.0, }, ]) ### Autogenerated by",
"int(4e7), 'reward_floor': 0.0, 'reward_ceiling': 5000.0, }, { 'env_id': 'PongNoFrameskip-v4', 'trials':",
"25, 50, 75, 100]: tabular_mdp_tasks.append({ 'env_id': 'RandomTabularMDP-{s}.states-{a}.actions-{t}.timesteps-{n}.episodes-v0'.format( s=n_states, a=n_actions, t=episode_length,",
"'trials': 1, 'max_timesteps': 2000, }, {'env_id': 'Pendulum-v0', 'trials': 1, 'max_timesteps':",
"'max_timesteps': int(2e8), 'reward_floor': 68.4, 'reward_ceiling': 100000.0, }, { 'env_id': 'SpaceInvadersNoFrameskip-v4',",
"}, ]) register_benchmark( id='MinecraftImpossible-v0', name='MinecraftImpossible', view_group=\"Minecraft\", description='Minecraft impossible benchmark', scorer=scoring.ClipTo01ThenAverage(),",
"0, 'reward_ceiling': n_episodes, }) register_benchmark( id='BernoulliBandit-v0', name='BernoulliBandit', description='Multi-armed Bernoulli bandits',",
"'reward_ceiling': n_episodes, }) register_benchmark( id='BernoulliBandit-v0', name='BernoulliBandit', description='Multi-armed Bernoulli bandits', scorer=scoring.ClipTo01ThenAverage(num_episodes=1000),",
"100.0, } ]) register_benchmark( id='ClassicControl2-v0', name='ClassicControl2', view_group=\"Control\", description='Simple classic control",
"'reward_ceiling': 31.0, }, { 'env_id': 'GravitarNoFrameskip-v4', 'trials': 2, 'max_timesteps': int(4e7),",
"'trials': 2, 'max_timesteps': 2000000, 'reward_floor': -500.0, 'reward_ceiling': 0.0, }, {'env_id':",
"'Hopper-v1', 'trials': 1, 'max_timesteps': 1000000, }, {'env_id': 'Humanoid-v1', 'trials': 1,",
"'trials': 2, 'max_timesteps': int(2e8), 'reward_floor': -20.7, 'reward_ceiling': 21.0, }, {",
"tasks=[ { 'env_id': 'BeamRiderNoFrameskip-v4', 'trials': 2, 'max_timesteps': int(4e7), 'reward_floor': 363.9,",
"40000.0, }, { 'env_id': 'SeaquestNoFrameskip-v4', 'trials': 2, 'max_timesteps': int(4e7), 'reward_floor':",
"tasks=[ {'env_id': 'MinecraftBasic-v0', 'trials': 2, 'max_timesteps': 600000, 'reward_floor': -2200.0, 'reward_ceiling':",
"int(4e7), 'reward_floor': 245.5, 'reward_ceiling': 1000.0, }, { 'env_id': 'MontezumaRevengeNoFrameskip-v4', 'trials':",
"600000, 'reward_floor': -1000.0, 'reward_ceiling': 1040.0, }, {'env_id': 'MinecraftComplexityUsage-v0', 'trials': 1,",
"'reward_ceiling': 5000.0, }, { 'env_id': 'PongNoFrameskip-v4', 'trials': 2, 'max_timesteps': int(4e7),",
"int(4e7), 'reward_floor': -20.7, 'reward_ceiling': 21.0, }, { 'env_id': 'QbertNoFrameskip-v4', 'trials':",
"'reward_floor': 0.1, 'reward_ceiling': 31.0, }, { 'env_id': 'GravitarNoFrameskip-v4', 'trials': 2,",
"'GravitarNoFrameskip-v4', 'trials': 2, 'max_timesteps': int(4e7), 'reward_floor': 245.5, 'reward_ceiling': 1000.0, },",
"n=n_episodes, ), 'trials': 1, 'max_timesteps': 10 ** 9, 'reward_floor': 0,",
"2, 'max_timesteps': 900000, 'reward_floor': -1000.0, 'reward_ceiling': 8040.0, }, {'env_id': 'MinecraftMaze1-v0',",
"int(4e7), 'reward_floor': 148.0, 'reward_ceiling': 30000.0, } ]) register_benchmark( id='AtariExploration40M', scorer=scoring.TotalReward(),",
"{'env_id': 'MinecraftCliffWalking1-v0', 'trials': 2, 'max_timesteps': 400000, 'reward_floor': -100.0, 'reward_ceiling': 100.0,",
"int(2e8), 'reward_floor': 1.7, 'reward_ceiling': 800.0, }, { 'env_id': 'EnduroNoFrameskip-v4', 'trials':",
"}, {'env_id': 'Pendulum-v0', 'trials': 3, 'max_timesteps': 200000, 'reward_floor': -1400.0, 'reward_ceiling':",
"1.6, 'reward_ceiling': 5500.0, } ]) register_benchmark( id='MinecraftEasy-v0', name='MinecraftEasy', view_group=\"Minecraft\", description='Minecraft",
"]) register_benchmark( id='MinecraftHard-v0', name='MinecraftHard', view_group=\"Minecraft\", description='Minecraft hard benchmark', scorer=scoring.ClipTo01ThenAverage(), tasks=[",
"]) register_benchmark( id='MinecraftVeryHard-v0', name='MinecraftVeryHard', view_group=\"Minecraft\", description='Minecraft very hard benchmark', scorer=scoring.ClipTo01ThenAverage(),",
"]) register_benchmark( id='MinecraftImpossible-v0', name='MinecraftImpossible', view_group=\"Minecraft\", description='Minecraft impossible benchmark', scorer=scoring.ClipTo01ThenAverage(), tasks=[",
"bandit_tasks.append({ 'env_id': 'BernoulliBandit-{k}.arms-{n}.episodes-v0'.format(k=n_arms, n=n_episodes), 'trials': 1, 'max_timesteps': 10 ** 9,",
"}, {'env_id': 'Walker2d-v1', 'trials': 1, 'max_timesteps': 1000000, } ]) register_benchmark(",
"'trials': 2, 'max_timesteps': 400000, 'reward_floor': -100.0, 'reward_ceiling': 100.0, }, {'env_id':",
"9, 'reward_floor': 0, 'reward_ceiling': n_episodes, }) register_benchmark( id='BernoulliBandit-v0', name='BernoulliBandit', description='Multi-armed",
"2, 'max_timesteps': int(2e8), 'reward_floor': -20.7, 'reward_ceiling': 21.0, }, { 'env_id':",
"{ 'env_id': 'BeamRiderNoFrameskip-v4', 'trials': 2, 'max_timesteps': int(4e7), 'reward_floor': 363.9, 'reward_ceiling':",
"tasks=[ {'env_id': 'CartPole-v1', 'trials': 3, 'max_timesteps': 100000, 'reward_floor': 0.0, 'reward_ceiling':",
"description='7 Atari games, with pixel observations', tasks=[ { 'env_id': 'BeamRiderNoFrameskip-v4',",
"-1000.0, 'reward_ceiling': 4160.0, }, {'env_id': 'MinecraftAttic-v0', 'trials': 1, 'max_timesteps': 600000,",
"'reward_floor': 163.9, 'reward_ceiling': 40000.0, }, { 'env_id': 'SeaquestNoFrameskip-v4', 'trials': 2,",
"21.0, }, { 'env_id': 'QbertNoFrameskip-v4', 'trials': 2, 'max_timesteps': int(2e8), 'reward_floor':",
"1000000, 'reward_floor': -43.0, 'reward_ceiling': -0.5, }, {'env_id': 'Swimmer-v1', 'trials': 3,",
"'reward_ceiling': 1000.0, }, { 'env_id': 'PrivateEyeNoFrameskip-v4', 'trials': 2, 'max_timesteps': int(4e7),",
"'reward_ceiling': 500.0, }, {'env_id': 'Walker2d-v1', 'trials': 3, 'max_timesteps': 1000000, 'reward_floor':",
"'env_id': 'BeamRiderNoFrameskip-v4', 'trials': 2, 'max_timesteps': int(2e8), 'reward_floor': 363.9, 'reward_ceiling': 60000.0,",
"'reward_ceiling': -100.0, }, {'env_id': 'Pendulum-v0', 'trials': 3, 'max_timesteps': 200000, 'reward_floor':",
"}) register_benchmark( id='RandomTabularMDP-v0', name='RandomTabularMDP', description='Random tabular MDPs', scorer=scoring.ClipTo01ThenAverage(num_episodes=1000), tasks=tabular_mdp_tasks )",
"'max_timesteps': 600000, 'reward_floor': -1000.0, 'reward_ceiling': 1040.0, }, {'env_id': 'MinecraftComplexityUsage-v0', 'trials':",
"10, 50]: for n_episodes in [10, 100, 500]: bandit_tasks.append({ 'env_id':",
"view_group=\"Minecraft\", description='Minecraft very hard benchmark', scorer=scoring.ClipTo01ThenAverage(), tasks=[ {'env_id': 'MinecraftMedium-v0', 'trials':",
"}, {'env_id': 'MinecraftSimpleRoomMaze-v0', 'trials': 1, 'max_timesteps': 900000, 'reward_floor': -1000.0, 'reward_ceiling':",
"id='MinecraftImpossible-v0', name='MinecraftImpossible', view_group=\"Minecraft\", description='Minecraft impossible benchmark', scorer=scoring.ClipTo01ThenAverage(), tasks=[ {'env_id': 'MinecraftDefaultWorld1-v0',",
"'max_timesteps': int(2e8), 'reward_floor': 363.9, 'reward_ceiling': 60000.0, }, { 'env_id': 'BreakoutNoFrameskip-v4',",
"'reward_ceiling': 100.0, }, {'env_id': 'MinecraftVertical-v0', 'trials': 2, 'max_timesteps': 900000, 'reward_floor':",
"{'env_id': 'HalfCheetah-v1', 'trials': 3, 'max_timesteps': 1000000, 'reward_floor': -280.0, 'reward_ceiling': 4000.0,",
"Atari games, with pixel observations', tasks=[ { 'env_id': 'BeamRiderNoFrameskip-v4', 'trials':",
"int(4e7), 'reward_floor': 1.7, 'reward_ceiling': 800.0, }, { 'env_id': 'EnduroNoFrameskip-v4', 'trials':",
"'reward_floor': 0.0, 'reward_ceiling': 5000.0, }, { 'env_id': 'PongNoFrameskip-v4', 'trials': 2,",
"}, { 'env_id': 'SeaquestNoFrameskip-v4', 'trials': 2, 'max_timesteps': int(4e7), 'reward_floor': 68.4,",
"<reponame>youngwoon/DnC-RL-Tensorflow<gh_stars>1-10 # EXPERIMENTAL: all may be removed soon from gym.benchmarks",
"'trials': 1, 'max_timesteps': 1000000, }, {'env_id': 'Hopper-v1', 'trials': 1, 'max_timesteps':",
"'EnduroNoFrameskip-v4', 'trials': 2, 'max_timesteps': int(2e8), 'reward_floor': 0.0, 'reward_ceiling': 5000.0, },",
"scorer=scoring.ClipTo01ThenAverage(), tasks=[ {'env_id': 'MinecraftCliffWalking1-v0', 'trials': 2, 'max_timesteps': 400000, 'reward_floor': -100.0,",
"} ]) register_benchmark( id='AtariExploration40M', scorer=scoring.TotalReward(), name='AtariExploration40M', view_group=\"Atari\", description='7 Atari games,",
"register_benchmark, registry, register_benchmark_view # imports used elsewhere register_benchmark( id='Atari200M', scorer=scoring.TotalReward(),",
"}, {'env_id': 'MinecraftAttic-v0', 'trials': 1, 'max_timesteps': 600000, 'reward_floor': -1000.0, 'reward_ceiling':",
"2400000, 'reward_floor': -10000.0, 'reward_ceiling': 32640.0, }, ]) register_benchmark( id='MinecraftImpossible-v0', name='MinecraftImpossible',",
"'BreakoutNoFrameskip-v4', 'trials': 2, 'max_timesteps': int(2e8), 'reward_floor': 1.7, 'reward_ceiling': 800.0, },",
"1000.0, }, { 'env_id': 'MontezumaRevengeNoFrameskip-v4', 'trials': 2, 'max_timesteps': int(4e7), 'reward_floor':",
"'MinecraftComplexityUsage-v0', 'trials': 1, 'max_timesteps': 600000, 'reward_floor': -1000.0, 'reward_ceiling': 1000.0, },",
"'reward_ceiling': 10000.0, }, {'env_id': 'InvertedPendulum-v1', 'trials': 3, 'max_timesteps': 1000000, 'reward_floor':",
"'reward_floor': 68.4, 'reward_ceiling': 100000.0, }, { 'env_id': 'SpaceInvadersNoFrameskip-v4', 'trials': 2,",
"'max_timesteps': 1000000, }, {'env_id': 'Walker2d-v1', 'trials': 1, 'max_timesteps': 1000000, }",
"'max_timesteps': 2400000, 'reward_floor': -10000.0, 'reward_ceiling': 32640.0, }, ]) register_benchmark( id='MinecraftImpossible-v0',",
"'EnduroNoFrameskip-v4', 'trials': 2, 'max_timesteps': int(4e7), 'reward_floor': 0.0, 'reward_ceiling': 5000.0, },",
"2, 'max_timesteps': int(4e7), 'reward_floor': 148.0, 'reward_ceiling': 30000.0, } ]) register_benchmark(",
"observations', tasks=[ { 'env_id': 'FreewayNoFrameskip-v4', 'trials': 2, 'max_timesteps': int(4e7), 'reward_floor':",
"}, {'env_id': 'MountainCar-v0', 'trials': 3, 'max_timesteps': 100000, 'reward_floor': -200.0, 'reward_ceiling':",
"gym.benchmarks import scoring from gym.benchmarks.registration import benchmark_spec, register_benchmark, registry, register_benchmark_view",
"'max_timesteps': 1000000, 'reward_floor': 1.6, 'reward_ceiling': 5500.0, } ]) register_benchmark( id='MinecraftEasy-v0',",
"'reward_ceiling': 1000.0, }, {'env_id': 'MinecraftMaze2-v0', 'trials': 2, 'max_timesteps': 2000000, 'reward_floor':",
"register_benchmark( id='MinecraftVeryHard-v0', name='MinecraftVeryHard', view_group=\"Minecraft\", description='Minecraft very hard benchmark', scorer=scoring.ClipTo01ThenAverage(), tasks=[",
"2, 'max_timesteps': int(4e7), 'reward_floor': 1.7, 'reward_ceiling': 800.0, }, { 'env_id':",
"100000, 'reward_floor': 0.0, 'reward_ceiling': 500.0, }, {'env_id': 'Acrobot-v1', 'trials': 3,",
"}, {'env_id': 'Pendulum-v0', 'trials': 1, 'max_timesteps': 1000, }, ]) register_benchmark(",
"pixel observations', tasks=[ { 'env_id': 'FreewayNoFrameskip-v4', 'trials': 2, 'max_timesteps': int(4e7),",
"'max_timesteps': 2000, }, {'env_id': 'Pendulum-v0', 'trials': 1, 'max_timesteps': 1000, },",
"with 1M steps', scorer=scoring.ClipTo01ThenAverage(), tasks=[ {'env_id': 'HalfCheetah-v1', 'trials': 3, 'max_timesteps':",
"description='Minecraft very hard benchmark', scorer=scoring.ClipTo01ThenAverage(), tasks=[ {'env_id': 'MinecraftMedium-v0', 'trials': 2,",
"2, 'max_timesteps': 2400000, 'reward_floor': -10000.0, 'reward_ceiling': 32640.0, }, ]) register_benchmark(",
"3, 'max_timesteps': 100000, 'reward_floor': 0.0, 'reward_ceiling': 500.0, }, {'env_id': 'Acrobot-v1',",
"'reward_floor': -10000.0, 'reward_ceiling': 32640.0, }, ]) register_benchmark( id='MinecraftImpossible-v0', name='MinecraftImpossible', view_group=\"Minecraft\",",
"1000.0, }, { 'env_id': 'PrivateEyeNoFrameskip-v4', 'trials': 2, 'max_timesteps': int(4e7), 'reward_floor':",
"{'env_id': 'MinecraftSimpleRoomMaze-v0', 'trials': 1, 'max_timesteps': 900000, 'reward_floor': -1000.0, 'reward_ceiling': 4160.0,",
"100000, 'reward_floor': -500.0, 'reward_ceiling': 0.0, }, {'env_id': 'MountainCar-v0', 'trials': 3,",
"1000000, 'reward_floor': 53.0, 'reward_ceiling': 10000.0, }, {'env_id': 'InvertedPendulum-v1', 'trials': 3,",
"5000.0, }, { 'env_id': 'PongNoFrameskip-v4', 'trials': 2, 'max_timesteps': int(4e7), 'reward_floor':",
"60000.0, }, { 'env_id': 'BreakoutNoFrameskip-v4', 'trials': 2, 'max_timesteps': int(4e7), 'reward_floor':",
"'max_timesteps': int(2e8), 'reward_floor': 148.0, 'reward_ceiling': 30000.0, }, ]) register_benchmark( id='Atari40M',",
"registry, register_benchmark_view # imports used elsewhere register_benchmark( id='Atari200M', scorer=scoring.TotalReward(), name='Atari200M',",
"}, { 'env_id': 'BreakoutNoFrameskip-v4', 'trials': 2, 'max_timesteps': int(4e7), 'reward_floor': 1.7,",
"{ 'env_id': 'BeamRiderNoFrameskip-v4', 'trials': 2, 'max_timesteps': int(2e8), 'reward_floor': 363.9, 'reward_ceiling':",
"int(2e8), 'reward_floor': 363.9, 'reward_ceiling': 60000.0, }, { 'env_id': 'BreakoutNoFrameskip-v4', 'trials':",
"'QbertNoFrameskip-v4', 'trials': 2, 'max_timesteps': int(2e8), 'reward_floor': 163.9, 'reward_ceiling': 40000.0, },",
"}, { 'env_id': 'EnduroNoFrameskip-v4', 'trials': 2, 'max_timesteps': int(4e7), 'reward_floor': 0.0,",
"{'env_id': 'HumanoidStandup-v1', 'trials': 1, 'max_timesteps': 1000000, }, {'env_id': 'Walker2d-v1', 'trials':",
"{ 'env_id': 'BreakoutNoFrameskip-v4', 'trials': 2, 'max_timesteps': int(2e8), 'reward_floor': 1.7, 'reward_ceiling':",
"impossible benchmark', scorer=scoring.ClipTo01ThenAverage(), tasks=[ {'env_id': 'MinecraftDefaultWorld1-v0', 'trials': 2, 'max_timesteps': 6000000,",
"1000000, }, {'env_id': 'Humanoid-v1', 'trials': 1, 'max_timesteps': 1000000, }, {'env_id':",
"1, 'max_timesteps': 10 ** 9, 'reward_floor': 0, 'reward_ceiling': n_episodes, })",
"}, { 'env_id': 'PrivateEyeNoFrameskip-v4', 'trials': 2, 'max_timesteps': int(4e7), 'reward_floor': 662.8,",
"50, 75, 100]: tabular_mdp_tasks.append({ 'env_id': 'RandomTabularMDP-{s}.states-{a}.actions-{t}.timesteps-{n}.episodes-v0'.format( s=n_states, a=n_actions, t=episode_length, n=n_episodes,",
"'max_timesteps': 1800000, 'reward_floor': -10000.0, 'reward_ceiling': 16280.0, }, {'env_id': 'MinecraftHard-v0', 'trials':",
"'env_id': 'QbertNoFrameskip-v4', 'trials': 2, 'max_timesteps': int(2e8), 'reward_floor': 163.9, 'reward_ceiling': 40000.0,",
"{ 'env_id': 'BreakoutNoFrameskip-v4', 'trials': 2, 'max_timesteps': int(4e7), 'reward_floor': 1.7, 'reward_ceiling':",
"'trials': 3, 'max_timesteps': 200000, 'reward_floor': -1400.0, 'reward_ceiling': 0.0, }, ])",
"'FreewayNoFrameskip-v4', 'trials': 2, 'max_timesteps': int(4e7), 'reward_floor': 0.1, 'reward_ceiling': 31.0, },",
"id='MinecraftHard-v0', name='MinecraftHard', view_group=\"Minecraft\", description='Minecraft hard benchmark', scorer=scoring.ClipTo01ThenAverage(), tasks=[ {'env_id': 'MinecraftObstacles-v0',",
"2, 'max_timesteps': int(2e8), 'reward_floor': 363.9, 'reward_ceiling': 60000.0, }, { 'env_id':",
"-10000.0, 'reward_ceiling': 16280.0, }, {'env_id': 'MinecraftHard-v0', 'trials': 2, 'max_timesteps': 2400000,",
"register_benchmark_view # imports used elsewhere register_benchmark( id='Atari200M', scorer=scoring.TotalReward(), name='Atari200M', view_group=\"Atari\",",
"300000, 'reward_floor': -1000.0, 'reward_ceiling': 2800.0, }, {'env_id': 'MinecraftEating1-v0', 'trials': 2,",
"removed soon from gym.benchmarks import scoring from gym.benchmarks.registration import benchmark_spec,",
"description='Minecraft medium benchmark', scorer=scoring.ClipTo01ThenAverage(), tasks=[ {'env_id': 'MinecraftCliffWalking1-v0', 'trials': 2, 'max_timesteps':",
"[10]: for n_actions in [5]: for episode_length in [10]: for",
"'trials': 1, 'max_timesteps': 1000, }, ]) register_benchmark( id='ClassicControl-v0', name='ClassicControl', view_group=\"Control\",",
"view_group=\"Control\", description='Mujoco benchmark with 1M steps', scorer=scoring.ClipTo01ThenAverage(), tasks=[ {'env_id': 'HalfCheetah-v1',",
"2, 'max_timesteps': 600000, 'reward_floor': -2200.0, 'reward_ceiling': 1000.0, }, {'env_id': 'MinecraftDefaultFlat1-v0',",
"'reward_floor': -1000.0, 'reward_ceiling': 2080.0, }, {'env_id': 'MinecraftSimpleRoomMaze-v0', 'trials': 1, 'max_timesteps':",
"2000000, 'reward_floor': -500.0, 'reward_ceiling': 0.0, }, {'env_id': 'MinecraftTrickyArena1-v0', 'trials': 2,",
"n_episodes * 2, }) register_benchmark( id='RandomTabularMDP-v0', name='RandomTabularMDP', description='Random tabular MDPs',",
"-100.0, }, {'env_id': 'Pendulum-v0', 'trials': 3, 'max_timesteps': 200000, 'reward_floor': -1400.0,",
"scorer=scoring.TotalReward(), name='Atari40M', view_group=\"Atari\", description='7 Atari games, with pixel observations', tasks=[",
"'reward_floor': 0, 'reward_ceiling': n_episodes, }) register_benchmark( id='BernoulliBandit-v0', name='BernoulliBandit', description='Multi-armed Bernoulli",
"2, 'max_timesteps': 2000000, 'reward_floor': -1000.0, 'reward_ceiling': 1000.0, }, ]) register_benchmark(",
"'MinecraftDefaultFlat1-v0', 'trials': 2, 'max_timesteps': 2000000, 'reward_floor': -500.0, 'reward_ceiling': 0.0, },",
"import scoring from gym.benchmarks.registration import benchmark_spec, register_benchmark, registry, register_benchmark_view #",
"1800000, 'reward_floor': -10000.0, 'reward_ceiling': 16280.0, }, {'env_id': 'MinecraftHard-v0', 'trials': 2,",
"}, {'env_id': 'Acrobot-v1', 'trials': 3, 'max_timesteps': 100000, 'reward_floor': -500.0, 'reward_ceiling':",
"}, ]) bandit_tasks = [] for n_arms in [5, 10,",
"'reward_ceiling': 32640.0, }, ]) register_benchmark( id='MinecraftImpossible-v0', name='MinecraftImpossible', view_group=\"Minecraft\", description='Minecraft impossible",
"}, {'env_id': 'MinecraftHard-v0', 'trials': 2, 'max_timesteps': 2400000, 'reward_floor': -10000.0, 'reward_ceiling':",
"'max_timesteps': int(4e7), 'reward_floor': 163.9, 'reward_ceiling': 40000.0, }, { 'env_id': 'SeaquestNoFrameskip-v4',",
"int(2e8), 'reward_floor': 148.0, 'reward_ceiling': 30000.0, }, ]) register_benchmark( id='Atari40M', scorer=scoring.TotalReward(),",
"}, { 'env_id': 'SpaceInvadersNoFrameskip-v4', 'trials': 2, 'max_timesteps': int(4e7), 'reward_floor': 148.0,",
"{'env_id': 'InvertedPendulum-v1', 'trials': 3, 'max_timesteps': 1000000, 'reward_floor': 5.6, 'reward_ceiling': 1000.0,",
"-2200.0, 'reward_ceiling': 1000.0, }, {'env_id': 'MinecraftDefaultFlat1-v0', 'trials': 2, 'max_timesteps': 2000000,",
"'Reacher-v1', 'trials': 3, 'max_timesteps': 1000000, 'reward_floor': -43.0, 'reward_ceiling': -0.5, },",
"'reward_floor': -20.7, 'reward_ceiling': 21.0, }, { 'env_id': 'QbertNoFrameskip-v4', 'trials': 2,",
"{'env_id': 'MountainCar-v0', 'trials': 3, 'max_timesteps': 100000, 'reward_floor': -200.0, 'reward_ceiling': -100.0,",
"'BeamRiderNoFrameskip-v4', 'trials': 2, 'max_timesteps': int(2e8), 'reward_floor': 363.9, 'reward_ceiling': 60000.0, },",
"'reward_floor': -100.0, 'reward_ceiling': 100.0, }, {'env_id': 'MinecraftVertical-v0', 'trials': 2, 'max_timesteps':",
"'MontezumaRevengeNoFrameskip-v4', 'trials': 2, 'max_timesteps': int(4e7), 'reward_floor': 25.0, 'reward_ceiling': 10000.0, },",
"'max_timesteps': 1000, }, ]) register_benchmark( id='ClassicControl-v0', name='ClassicControl', view_group=\"Control\", description='Simple classic",
"Autogenerated by tinkerbell.benchmark.convert_benchmark.py register_benchmark( id='Mujoco10M-v0', name='Mujoco10M', view_group=\"Control\", description='Mujoco benchmark with",
"'reward_ceiling': 60000.0, }, { 'env_id': 'BreakoutNoFrameskip-v4', 'trials': 2, 'max_timesteps': int(2e8),",
"name='MinecraftHard', view_group=\"Minecraft\", description='Minecraft hard benchmark', scorer=scoring.ClipTo01ThenAverage(), tasks=[ {'env_id': 'MinecraftObstacles-v0', 'trials':",
"scorer=scoring.ClipTo01ThenAverage(), tasks=[ {'env_id': 'MinecraftMedium-v0', 'trials': 2, 'max_timesteps': 1800000, 'reward_floor': -10000.0,",
"steps', scorer=scoring.ClipTo01ThenAverage(), tasks=[ {'env_id': 'HalfCheetah-v1', 'trials': 3, 'max_timesteps': 1000000, 'reward_floor':",
"-300.0, 'reward_ceiling': 300.0, }, ]) register_benchmark( id='MinecraftMedium-v0', name='MinecraftMedium', view_group=\"Minecraft\", description='Minecraft",
"]) register_benchmark( id='ClassicControl2-v0', name='ClassicControl2', view_group=\"Control\", description='Simple classic control benchmark', scorer=scoring.ClipTo01ThenAverage(),",
"16280.0, }, {'env_id': 'MinecraftHard-v0', 'trials': 2, 'max_timesteps': 2400000, 'reward_floor': -10000.0,",
"'reward_ceiling': 0.0, }, {'env_id': 'MinecraftTrickyArena1-v0', 'trials': 2, 'max_timesteps': 300000, 'reward_floor':",
"3, 'max_timesteps': 100000, 'reward_floor': -200.0, 'reward_ceiling': -100.0, }, {'env_id': 'Pendulum-v0',",
"'max_timesteps': 1000000, }, {'env_id': 'HumanoidStandup-v1', 'trials': 1, 'max_timesteps': 1000000, },",
"'trials': 2, 'max_timesteps': int(2e8), 'reward_floor': 163.9, 'reward_ceiling': 40000.0, }, {",
"800.0, }, { 'env_id': 'EnduroNoFrameskip-v4', 'trials': 2, 'max_timesteps': int(4e7), 'reward_floor':",
"tasks=[ { 'env_id': 'BeamRiderNoFrameskip-v4', 'trials': 2, 'max_timesteps': int(2e8), 'reward_floor': 363.9,",
"'max_timesteps': 300000, 'reward_floor': -300.0, 'reward_ceiling': 300.0, }, ]) register_benchmark( id='MinecraftMedium-v0',",
"}) register_benchmark( id='BernoulliBandit-v0', name='BernoulliBandit', description='Multi-armed Bernoulli bandits', scorer=scoring.ClipTo01ThenAverage(num_episodes=1000), tasks=bandit_tasks )",
"}, ]) register_benchmark( id='Atari40M', scorer=scoring.TotalReward(), name='Atari40M', view_group=\"Atari\", description='7 Atari games,",
"'max_timesteps': 300000, 'reward_floor': -1000.0, 'reward_ceiling': 2800.0, }, {'env_id': 'MinecraftEating1-v0', 'trials':",
"view_group=\"Control\", description='Simple classic control benchmark', scorer=scoring.ClipTo01ThenAverage(), tasks=[ {'env_id': 'CartPole-v1', 'trials':",
"1000000, 'reward_floor': 16.0, 'reward_ceiling': 4000.0, }, {'env_id': 'InvertedDoublePendulum-v1', 'trials': 3,",
"10 ** 9, 'reward_floor': 0, 'reward_ceiling': n_episodes, }) register_benchmark( id='BernoulliBandit-v0',",
"}, { 'env_id': 'BreakoutNoFrameskip-v4', 'trials': 2, 'max_timesteps': int(2e8), 'reward_floor': 1.7,",
"2, 'max_timesteps': int(4e7), 'reward_floor': 0.1, 'reward_ceiling': 31.0, }, { 'env_id':",
"1000000, }, {'env_id': 'Walker2d-v1', 'trials': 1, 'max_timesteps': 1000000, } ])",
"-280.0, 'reward_ceiling': 4000.0, }, {'env_id': 'Hopper-v1', 'trials': 3, 'max_timesteps': 1000000,",
"-500.0, 'reward_ceiling': 0.0, }, {'env_id': 'MountainCar-v0', 'trials': 3, 'max_timesteps': 100000,",
"view_group=\"Control\", description='Simple classic control benchmark', scorer=scoring.ClipTo01ThenAverage(), tasks=[ {'env_id': 'CartPole-v0', 'trials':",
"), 'trials': 1, 'max_timesteps': 10 ** 9, 'reward_floor': 0, 'reward_ceiling':",
"900000, 'reward_floor': -1000.0, 'reward_ceiling': 2080.0, }, {'env_id': 'MinecraftSimpleRoomMaze-v0', 'trials': 1,",
"'Pendulum-v0', 'trials': 1, 'max_timesteps': 1000, }, ]) register_benchmark( id='ClassicControl-v0', name='ClassicControl',",
"easy benchmark', scorer=scoring.ClipTo01ThenAverage(), tasks=[ {'env_id': 'MinecraftBasic-v0', 'trials': 2, 'max_timesteps': 600000,",
"'QbertNoFrameskip-v4', 'trials': 2, 'max_timesteps': int(4e7), 'reward_floor': 163.9, 'reward_ceiling': 40000.0, },",
"3, 'max_timesteps': 1000000, 'reward_floor': 5.6, 'reward_ceiling': 1000.0, }, {'env_id': 'Reacher-v1',",
"900000, 'reward_floor': -1000.0, 'reward_ceiling': 4160.0, }, {'env_id': 'MinecraftAttic-v0', 'trials': 1,",
"'max_timesteps': 10 ** 9, 'reward_floor': 0, 'reward_ceiling': n_episodes, }) register_benchmark(",
"2800.0, }, {'env_id': 'MinecraftEating1-v0', 'trials': 2, 'max_timesteps': 300000, 'reward_floor': -300.0,",
"'max_timesteps': int(4e7), 'reward_floor': 68.4, 'reward_ceiling': 100000.0, }, { 'env_id': 'SpaceInvadersNoFrameskip-v4',",
"} ]) register_benchmark( id='ClassicControl2-v0', name='ClassicControl2', view_group=\"Control\", description='Simple classic control benchmark',",
"]) register_benchmark( id='Atari40M', scorer=scoring.TotalReward(), name='Atari40M', view_group=\"Atari\", description='7 Atari games, with",
"all may be removed soon from gym.benchmarks import scoring from",
"'trials': 2, 'max_timesteps': 6000000, 'reward_floor': -1000.0, 'reward_ceiling': 1000.0, }, ])",
"# imports used elsewhere register_benchmark( id='Atari200M', scorer=scoring.TotalReward(), name='Atari200M', view_group=\"Atari\", description='7",
"'InvertedDoublePendulum-v1', 'trials': 3, 'max_timesteps': 1000000, 'reward_floor': 53.0, 'reward_ceiling': 10000.0, },",
"'reward_ceiling': 0.0, }, ]) ### Autogenerated by tinkerbell.benchmark.convert_benchmark.py register_benchmark( id='Mujoco10M-v0',",
"'reward_ceiling': 10000.0, }, { 'env_id': 'PitfallNoFrameskip-v4', 'trials': 2, 'max_timesteps': int(4e7),",
"'env_id': 'FreewayNoFrameskip-v4', 'trials': 2, 'max_timesteps': int(4e7), 'reward_floor': 0.1, 'reward_ceiling': 31.0,",
"3, 'max_timesteps': 200000, 'reward_floor': -1400.0, 'reward_ceiling': 0.0, }, ]) ###",
"description='Minecraft easy benchmark', scorer=scoring.ClipTo01ThenAverage(), tasks=[ {'env_id': 'MinecraftBasic-v0', 'trials': 2, 'max_timesteps':",
"'VentureNoFrameskip-v4', 'trials': 2, 'max_timesteps': int(4e7), 'reward_floor': 18.0, 'reward_ceiling': 100.0, }",
"18.0, 'reward_ceiling': 100.0, } ]) register_benchmark( id='ClassicControl2-v0', name='ClassicControl2', view_group=\"Control\", description='Simple",
"'trials': 3, 'max_timesteps': 100000, 'reward_floor': 0.0, 'reward_ceiling': 500.0, }, {'env_id':",
"n_arms in [5, 10, 50]: for n_episodes in [10, 100,",
"}, {'env_id': 'MinecraftMaze1-v0', 'trials': 2, 'max_timesteps': 600000, 'reward_floor': -1000.0, 'reward_ceiling':",
"Bernoulli bandits', scorer=scoring.ClipTo01ThenAverage(num_episodes=1000), tasks=bandit_tasks ) tabular_mdp_tasks = [] for n_states",
"'RandomTabularMDP-{s}.states-{a}.actions-{t}.timesteps-{n}.episodes-v0'.format( s=n_states, a=n_actions, t=episode_length, n=n_episodes, ), 'trials': 1, 'max_timesteps': 10",
"'max_timesteps': 1000000, 'reward_floor': -280.0, 'reward_ceiling': 4000.0, }, {'env_id': 'Hopper-v1', 'trials':",
"1, 'max_timesteps': 600000, 'reward_floor': -1000.0, 'reward_ceiling': 1040.0, }, {'env_id': 'MinecraftComplexityUsage-v0',",
"pixel observations', tasks=[ { 'env_id': 'BeamRiderNoFrameskip-v4', 'trials': 2, 'max_timesteps': int(4e7),",
"-348.8, 'reward_ceiling': 1000.0, }, { 'env_id': 'PrivateEyeNoFrameskip-v4', 'trials': 2, 'max_timesteps':",
"{'env_id': 'MinecraftBasic-v0', 'trials': 2, 'max_timesteps': 600000, 'reward_floor': -2200.0, 'reward_ceiling': 1000.0,",
"classic control benchmark', scorer=scoring.ClipTo01ThenAverage(), tasks=[ {'env_id': 'CartPole-v1', 'trials': 3, 'max_timesteps':",
"'max_timesteps': int(4e7), 'reward_floor': 2047.2, 'reward_ceiling': 5000.0, }, { 'env_id': 'VentureNoFrameskip-v4',",
"}, {'env_id': 'Reacher-v1', 'trials': 3, 'max_timesteps': 1000000, 'reward_floor': -43.0, 'reward_ceiling':",
"= [] for n_arms in [5, 10, 50]: for n_episodes",
"register_benchmark( id='BernoulliBandit-v0', name='BernoulliBandit', description='Multi-armed Bernoulli bandits', scorer=scoring.ClipTo01ThenAverage(num_episodes=1000), tasks=bandit_tasks ) tabular_mdp_tasks",
"in [5, 10, 50]: for n_episodes in [10, 100, 500]:",
"'trials': 2, 'max_timesteps': int(4e7), 'reward_floor': 68.4, 'reward_ceiling': 100000.0, }, {",
"'reward_floor': 148.0, 'reward_ceiling': 30000.0, } ]) register_benchmark( id='AtariExploration40M', scorer=scoring.TotalReward(), name='AtariExploration40M',",
"benchmark', scorer=scoring.ClipTo01ThenAverage(), tasks=[ {'env_id': 'CartPole-v0', 'trials': 1, 'max_timesteps': 2000, },",
"{'env_id': 'Walker2d-v1', 'trials': 1, 'max_timesteps': 1000000, } ]) register_benchmark( id='Mujoco1M-v0',",
"'reward_floor': -300.0, 'reward_ceiling': 300.0, }, ]) register_benchmark( id='MinecraftMedium-v0', name='MinecraftMedium', view_group=\"Minecraft\",",
"benchmark', scorer=scoring.ClipTo01ThenAverage(), tasks=[ {'env_id': 'MinecraftObstacles-v0', 'trials': 1, 'max_timesteps': 900000, 'reward_floor':",
"{ 'env_id': 'SpaceInvadersNoFrameskip-v4', 'trials': 2, 'max_timesteps': int(4e7), 'reward_floor': 148.0, 'reward_ceiling':",
"{'env_id': 'MinecraftAttic-v0', 'trials': 1, 'max_timesteps': 600000, 'reward_floor': -1000.0, 'reward_ceiling': 1040.0,",
"'env_id': 'PongNoFrameskip-v4', 'trials': 2, 'max_timesteps': int(4e7), 'reward_floor': -20.7, 'reward_ceiling': 21.0,",
"}, {'env_id': 'Humanoid-v1', 'trials': 1, 'max_timesteps': 1000000, }, {'env_id': 'HumanoidStandup-v1',",
"1, 'max_timesteps': 900000, 'reward_floor': -1000.0, 'reward_ceiling': 2080.0, }, {'env_id': 'MinecraftSimpleRoomMaze-v0',",
"'reward_ceiling': 2080.0, }, {'env_id': 'MinecraftSimpleRoomMaze-v0', 'trials': 1, 'max_timesteps': 900000, 'reward_floor':",
"int(4e7), 'reward_floor': 25.0, 'reward_ceiling': 10000.0, }, { 'env_id': 'PitfallNoFrameskip-v4', 'trials':",
"'MinecraftAttic-v0', 'trials': 1, 'max_timesteps': 600000, 'reward_floor': -1000.0, 'reward_ceiling': 1040.0, },",
"{'env_id': 'MinecraftMedium-v0', 'trials': 2, 'max_timesteps': 1800000, 'reward_floor': -10000.0, 'reward_ceiling': 16280.0,",
"'max_timesteps': 600000, 'reward_floor': -1000.0, 'reward_ceiling': 1000.0, }, ]) register_benchmark( id='MinecraftVeryHard-v0',",
"'reward_ceiling': 500.0, }, {'env_id': 'Acrobot-v1', 'trials': 3, 'max_timesteps': 100000, 'reward_floor':",
"'reward_floor': -500.0, 'reward_ceiling': 0.0, }, {'env_id': 'MountainCar-v0', 'trials': 3, 'max_timesteps':",
"scorer=scoring.ClipTo01ThenAverage(num_episodes=1000), tasks=bandit_tasks ) tabular_mdp_tasks = [] for n_states in [10]:",
"'reward_floor': -1000.0, 'reward_ceiling': 8040.0, }, {'env_id': 'MinecraftMaze1-v0', 'trials': 2, 'max_timesteps':",
"2, 'max_timesteps': int(4e7), 'reward_floor': 2047.2, 'reward_ceiling': 5000.0, }, { 'env_id':",
"'reward_ceiling': 5500.0, } ]) register_benchmark( id='MinecraftEasy-v0', name='MinecraftEasy', view_group=\"Minecraft\", description='Minecraft easy",
"{'env_id': 'MinecraftVertical-v0', 'trials': 2, 'max_timesteps': 900000, 'reward_floor': -1000.0, 'reward_ceiling': 8040.0,",
"{'env_id': 'MinecraftEating1-v0', 'trials': 2, 'max_timesteps': 300000, 'reward_floor': -300.0, 'reward_ceiling': 300.0,",
"4000.0, }, {'env_id': 'InvertedDoublePendulum-v1', 'trials': 3, 'max_timesteps': 1000000, 'reward_floor': 53.0,",
"{ 'env_id': 'EnduroNoFrameskip-v4', 'trials': 2, 'max_timesteps': int(2e8), 'reward_floor': 0.0, 'reward_ceiling':",
"name='Atari40M', view_group=\"Atari\", description='7 Atari games, with pixel observations', tasks=[ {",
"0.0, }, {'env_id': 'MountainCar-v0', 'trials': 3, 'max_timesteps': 100000, 'reward_floor': -200.0,",
"'SeaquestNoFrameskip-v4', 'trials': 2, 'max_timesteps': int(4e7), 'reward_floor': 68.4, 'reward_ceiling': 100000.0, },",
"100.0, }, {'env_id': 'MinecraftVertical-v0', 'trials': 2, 'max_timesteps': 900000, 'reward_floor': -1000.0,",
"1000000, } ]) register_benchmark( id='Mujoco1M-v0', name='Mujoco1M', view_group=\"Control\", description='Mujoco benchmark with",
"21.0, }, { 'env_id': 'QbertNoFrameskip-v4', 'trials': 2, 'max_timesteps': int(4e7), 'reward_floor':",
"scorer=scoring.ClipTo01ThenAverage(), tasks=[ {'env_id': 'Ant-v1', 'trials': 1, 'max_timesteps': 1000000, }, {'env_id':",
"'SolarisNoFrameskip-v4', 'trials': 2, 'max_timesteps': int(4e7), 'reward_floor': 2047.2, 'reward_ceiling': 5000.0, },",
"elsewhere register_benchmark( id='Atari200M', scorer=scoring.TotalReward(), name='Atari200M', view_group=\"Atari\", description='7 Atari games, with",
"* n_episodes * 2, }) register_benchmark( id='RandomTabularMDP-v0', name='RandomTabularMDP', description='Random tabular",
"'reward_ceiling': 100000.0, }, { 'env_id': 'SpaceInvadersNoFrameskip-v4', 'trials': 2, 'max_timesteps': int(4e7),",
"'reward_floor': -1000.0, 'reward_ceiling': 1000.0, }, ]) register_benchmark( id='MinecraftHard-v0', name='MinecraftHard', view_group=\"Minecraft\",",
"'reward_floor': 18.0, 'reward_ceiling': 100.0, } ]) register_benchmark( id='ClassicControl2-v0', name='ClassicControl2', view_group=\"Control\",",
"}, {'env_id': 'MinecraftEating1-v0', 'trials': 2, 'max_timesteps': 300000, 'reward_floor': -300.0, 'reward_ceiling':",
"{ 'env_id': 'MontezumaRevengeNoFrameskip-v4', 'trials': 2, 'max_timesteps': int(4e7), 'reward_floor': 25.0, 'reward_ceiling':",
"'reward_ceiling': 1000.0, }, {'env_id': 'MinecraftDefaultFlat1-v0', 'trials': 2, 'max_timesteps': 2000000, 'reward_floor':",
"'trials': 2, 'max_timesteps': int(4e7), 'reward_floor': 148.0, 'reward_ceiling': 30000.0, } ])",
"'max_timesteps': 100000, 'reward_floor': -500.0, 'reward_ceiling': 0.0, }, {'env_id': 'MountainCar-v0', 'trials':",
"1000.0, }, ]) bandit_tasks = [] for n_arms in [5,",
"n=n_episodes), 'trials': 1, 'max_timesteps': 10 ** 9, 'reward_floor': 0, 'reward_ceiling':",
"'env_id': 'BreakoutNoFrameskip-v4', 'trials': 2, 'max_timesteps': int(4e7), 'reward_floor': 1.7, 'reward_ceiling': 800.0,",
"{'env_id': 'MinecraftObstacles-v0', 'trials': 1, 'max_timesteps': 900000, 'reward_floor': -1000.0, 'reward_ceiling': 2080.0,",
"'max_timesteps': 1000000, }, {'env_id': 'Humanoid-v1', 'trials': 1, 'max_timesteps': 1000000, },",
"'reward_ceiling': 30000.0, } ]) register_benchmark( id='AtariExploration40M', scorer=scoring.TotalReward(), name='AtariExploration40M', view_group=\"Atari\", description='7",
"1000, }, ]) register_benchmark( id='ClassicControl-v0', name='ClassicControl', view_group=\"Control\", description='Simple classic control",
"very hard benchmark', scorer=scoring.ClipTo01ThenAverage(), tasks=[ {'env_id': 'MinecraftMedium-v0', 'trials': 2, 'max_timesteps':",
"'Humanoid-v1', 'trials': 1, 'max_timesteps': 1000000, }, {'env_id': 'HumanoidStandup-v1', 'trials': 1,",
"EXPERIMENTAL: all may be removed soon from gym.benchmarks import scoring",
"100000, 'reward_floor': -200.0, 'reward_ceiling': -100.0, }, {'env_id': 'Pendulum-v0', 'trials': 3,",
"148.0, 'reward_ceiling': 30000.0, } ]) register_benchmark( id='AtariExploration40M', scorer=scoring.TotalReward(), name='AtariExploration40M', view_group=\"Atari\",",
"}, { 'env_id': 'SolarisNoFrameskip-v4', 'trials': 2, 'max_timesteps': int(4e7), 'reward_floor': 2047.2,",
"300000, 'reward_floor': -300.0, 'reward_ceiling': 300.0, }, ]) register_benchmark( id='MinecraftMedium-v0', name='MinecraftMedium',",
"view_group=\"Minecraft\", description='Minecraft hard benchmark', scorer=scoring.ClipTo01ThenAverage(), tasks=[ {'env_id': 'MinecraftObstacles-v0', 'trials': 1,",
"'reward_floor': 1.6, 'reward_ceiling': 5500.0, } ]) register_benchmark( id='MinecraftEasy-v0', name='MinecraftEasy', view_group=\"Minecraft\",",
"'HalfCheetah-v1', 'trials': 3, 'max_timesteps': 1000000, 'reward_floor': -280.0, 'reward_ceiling': 4000.0, },",
"3, 'max_timesteps': 1000000, 'reward_floor': 53.0, 'reward_ceiling': 10000.0, }, {'env_id': 'InvertedPendulum-v1',",
"int(2e8), 'reward_floor': -20.7, 'reward_ceiling': 21.0, }, { 'env_id': 'QbertNoFrameskip-v4', 'trials':",
"name='AtariExploration40M', view_group=\"Atari\", description='7 Atari games, with pixel observations', tasks=[ {",
"1000000, }, {'env_id': 'Hopper-v1', 'trials': 1, 'max_timesteps': 1000000, }, {'env_id':",
"'trials': 2, 'max_timesteps': 600000, 'reward_floor': -2200.0, 'reward_ceiling': 1000.0, }, {'env_id':",
"0, 'reward_ceiling': episode_length * n_episodes * 2, }) register_benchmark( id='RandomTabularMDP-v0',",
"'trials': 2, 'max_timesteps': int(4e7), 'reward_floor': 245.5, 'reward_ceiling': 1000.0, }, {",
"'reward_ceiling': -0.5, }, {'env_id': 'Swimmer-v1', 'trials': 3, 'max_timesteps': 1000000, 'reward_floor':",
"'BreakoutNoFrameskip-v4', 'trials': 2, 'max_timesteps': int(4e7), 'reward_floor': 1.7, 'reward_ceiling': 800.0, },",
"pixel observations', tasks=[ { 'env_id': 'BeamRiderNoFrameskip-v4', 'trials': 2, 'max_timesteps': int(2e8),",
"'max_timesteps': 200000, 'reward_floor': -1400.0, 'reward_ceiling': 0.0, }, ]) ### Autogenerated",
"{ 'env_id': 'PongNoFrameskip-v4', 'trials': 2, 'max_timesteps': int(4e7), 'reward_floor': -20.7, 'reward_ceiling':",
"id='MinecraftVeryHard-v0', name='MinecraftVeryHard', view_group=\"Minecraft\", description='Minecraft very hard benchmark', scorer=scoring.ClipTo01ThenAverage(), tasks=[ {'env_id':",
"{'env_id': 'MinecraftMaze2-v0', 'trials': 2, 'max_timesteps': 2000000, 'reward_floor': -1000.0, 'reward_ceiling': 1000.0,",
"# EXPERIMENTAL: all may be removed soon from gym.benchmarks import",
"'env_id': 'GravitarNoFrameskip-v4', 'trials': 2, 'max_timesteps': int(4e7), 'reward_floor': 245.5, 'reward_ceiling': 1000.0,",
"'reward_floor': -1000.0, 'reward_ceiling': 2800.0, }, {'env_id': 'MinecraftEating1-v0', 'trials': 2, 'max_timesteps':",
"benchmark with 1M steps', scorer=scoring.ClipTo01ThenAverage(), tasks=[ {'env_id': 'HalfCheetah-v1', 'trials': 3,",
"-1000.0, 'reward_ceiling': 1000.0, }, {'env_id': 'MinecraftMaze2-v0', 'trials': 2, 'max_timesteps': 2000000,",
"'max_timesteps': 900000, 'reward_floor': -1000.0, 'reward_ceiling': 2080.0, }, {'env_id': 'MinecraftSimpleRoomMaze-v0', 'trials':",
"'trials': 2, 'max_timesteps': int(4e7), 'reward_floor': 163.9, 'reward_ceiling': 40000.0, }, {",
"'max_timesteps': 100000, 'reward_floor': -200.0, 'reward_ceiling': -100.0, }, {'env_id': 'Pendulum-v0', 'trials':",
"view_group=\"Minecraft\", description='Minecraft impossible benchmark', scorer=scoring.ClipTo01ThenAverage(), tasks=[ {'env_id': 'MinecraftDefaultWorld1-v0', 'trials': 2,",
"'MinecraftCliffWalking1-v0', 'trials': 2, 'max_timesteps': 400000, 'reward_floor': -100.0, 'reward_ceiling': 100.0, },",
"'trials': 2, 'max_timesteps': int(4e7), 'reward_floor': 0.1, 'reward_ceiling': 31.0, }, {",
"'reward_floor': -200.0, 'reward_ceiling': -100.0, }, {'env_id': 'Pendulum-v0', 'trials': 3, 'max_timesteps':",
"{'env_id': 'Reacher-v1', 'trials': 3, 'max_timesteps': 1000000, 'reward_floor': -43.0, 'reward_ceiling': -0.5,",
"{'env_id': 'Hopper-v1', 'trials': 3, 'max_timesteps': 1000000, 'reward_floor': 16.0, 'reward_ceiling': 4000.0,",
"5500.0, } ]) register_benchmark( id='MinecraftEasy-v0', name='MinecraftEasy', view_group=\"Minecraft\", description='Minecraft easy benchmark',",
"steps', scorer=scoring.ClipTo01ThenAverage(), tasks=[ {'env_id': 'Ant-v1', 'trials': 1, 'max_timesteps': 1000000, },",
"'trials': 2, 'max_timesteps': int(2e8), 'reward_floor': 1.7, 'reward_ceiling': 800.0, }, {",
"]) register_benchmark( id='MinecraftMedium-v0', name='MinecraftMedium', view_group=\"Minecraft\", description='Minecraft medium benchmark', scorer=scoring.ClipTo01ThenAverage(), tasks=[",
"31.0, }, { 'env_id': 'GravitarNoFrameskip-v4', 'trials': 2, 'max_timesteps': int(4e7), 'reward_floor':",
"}, { 'env_id': 'QbertNoFrameskip-v4', 'trials': 2, 'max_timesteps': int(2e8), 'reward_floor': 163.9,",
"100.0, }, { 'env_id': 'SolarisNoFrameskip-v4', 'trials': 2, 'max_timesteps': int(4e7), 'reward_floor':",
"5.6, 'reward_ceiling': 1000.0, }, {'env_id': 'Reacher-v1', 'trials': 3, 'max_timesteps': 1000000,",
"episode_length * n_episodes * 2, }) register_benchmark( id='RandomTabularMDP-v0', name='RandomTabularMDP', description='Random",
"0.23, 'reward_ceiling': 500.0, }, {'env_id': 'Walker2d-v1', 'trials': 3, 'max_timesteps': 1000000,",
"10M steps', scorer=scoring.ClipTo01ThenAverage(), tasks=[ {'env_id': 'Ant-v1', 'trials': 1, 'max_timesteps': 1000000,",
"'max_timesteps': 1000000, 'reward_floor': 5.6, 'reward_ceiling': 1000.0, }, {'env_id': 'Reacher-v1', 'trials':",
"'max_timesteps': 900000, 'reward_floor': -1000.0, 'reward_ceiling': 8040.0, }, {'env_id': 'MinecraftMaze1-v0', 'trials':",
"int(4e7), 'reward_floor': 0.1, 'reward_ceiling': 31.0, }, { 'env_id': 'GravitarNoFrameskip-v4', 'trials':",
"{'env_id': 'MinecraftDefaultFlat1-v0', 'trials': 2, 'max_timesteps': 2000000, 'reward_floor': -500.0, 'reward_ceiling': 0.0,",
"}, ]) register_benchmark( id='MinecraftVeryHard-v0', name='MinecraftVeryHard', view_group=\"Minecraft\", description='Minecraft very hard benchmark',",
"scorer=scoring.ClipTo01ThenAverage(), tasks=[ {'env_id': 'CartPole-v1', 'trials': 3, 'max_timesteps': 100000, 'reward_floor': 0.0,",
"'trials': 1, 'max_timesteps': 900000, 'reward_floor': -1000.0, 'reward_ceiling': 2080.0, }, {'env_id':",
"scorer=scoring.ClipTo01ThenAverage(), tasks=[ {'env_id': 'HalfCheetah-v1', 'trials': 3, 'max_timesteps': 1000000, 'reward_floor': -280.0,",
"}, {'env_id': 'Hopper-v1', 'trials': 1, 'max_timesteps': 1000000, }, {'env_id': 'Humanoid-v1',",
"register_benchmark( id='Mujoco1M-v0', name='Mujoco1M', view_group=\"Control\", description='Mujoco benchmark with 1M steps', scorer=scoring.ClipTo01ThenAverage(),",
"{ 'env_id': 'SeaquestNoFrameskip-v4', 'trials': 2, 'max_timesteps': int(4e7), 'reward_floor': 68.4, 'reward_ceiling':",
"scorer=scoring.ClipTo01ThenAverage(), tasks=[ {'env_id': 'CartPole-v0', 'trials': 1, 'max_timesteps': 2000, }, {'env_id':",
"-100.0, 'reward_ceiling': 100.0, }, {'env_id': 'MinecraftVertical-v0', 'trials': 2, 'max_timesteps': 900000,",
"'trials': 2, 'max_timesteps': int(2e8), 'reward_floor': 68.4, 'reward_ceiling': 100000.0, }, {",
"'env_id': 'EnduroNoFrameskip-v4', 'trials': 2, 'max_timesteps': int(4e7), 'reward_floor': 0.0, 'reward_ceiling': 5000.0,",
"be removed soon from gym.benchmarks import scoring from gym.benchmarks.registration import",
"10 ** 9, 'reward_floor': 0, 'reward_ceiling': episode_length * n_episodes *",
"'reward_ceiling': 4160.0, }, {'env_id': 'MinecraftAttic-v0', 'trials': 1, 'max_timesteps': 600000, 'reward_floor':",
"'reward_ceiling': 800.0, }, { 'env_id': 'EnduroNoFrameskip-v4', 'trials': 2, 'max_timesteps': int(2e8),",
"}, {'env_id': 'MinecraftComplexityUsage-v0', 'trials': 1, 'max_timesteps': 600000, 'reward_floor': -1000.0, 'reward_ceiling':",
"view_group=\"Atari\", description='7 Atari games, with pixel observations', tasks=[ { 'env_id':",
"name='MinecraftMedium', view_group=\"Minecraft\", description='Minecraft medium benchmark', scorer=scoring.ClipTo01ThenAverage(), tasks=[ {'env_id': 'MinecraftCliffWalking1-v0', 'trials':",
"'env_id': 'PongNoFrameskip-v4', 'trials': 2, 'max_timesteps': int(2e8), 'reward_floor': -20.7, 'reward_ceiling': 21.0,",
"'trials': 2, 'max_timesteps': 900000, 'reward_floor': -1000.0, 'reward_ceiling': 8040.0, }, {'env_id':",
"bandit_tasks = [] for n_arms in [5, 10, 50]: for",
"{'env_id': 'CartPole-v0', 'trials': 1, 'max_timesteps': 2000, }, {'env_id': 'Pendulum-v0', 'trials':",
"benchmark', scorer=scoring.ClipTo01ThenAverage(), tasks=[ {'env_id': 'MinecraftDefaultWorld1-v0', 'trials': 2, 'max_timesteps': 6000000, 'reward_floor':",
"'reward_ceiling': episode_length * n_episodes * 2, }) register_benchmark( id='RandomTabularMDP-v0', name='RandomTabularMDP',",
"tasks=[ {'env_id': 'MinecraftObstacles-v0', 'trials': 1, 'max_timesteps': 900000, 'reward_floor': -1000.0, 'reward_ceiling':",
"with pixel observations', tasks=[ { 'env_id': 'FreewayNoFrameskip-v4', 'trials': 2, 'max_timesteps':",
"used elsewhere register_benchmark( id='Atari200M', scorer=scoring.TotalReward(), name='Atari200M', view_group=\"Atari\", description='7 Atari games,",
"s=n_states, a=n_actions, t=episode_length, n=n_episodes, ), 'trials': 1, 'max_timesteps': 10 **",
"'max_timesteps': 600000, 'reward_floor': -2200.0, 'reward_ceiling': 1000.0, }, {'env_id': 'MinecraftDefaultFlat1-v0', 'trials':",
"'PongNoFrameskip-v4', 'trials': 2, 'max_timesteps': int(2e8), 'reward_floor': -20.7, 'reward_ceiling': 21.0, },",
"}, { 'env_id': 'VentureNoFrameskip-v4', 'trials': 2, 'max_timesteps': int(4e7), 'reward_floor': 18.0,",
"'trials': 3, 'max_timesteps': 1000000, 'reward_floor': -43.0, 'reward_ceiling': -0.5, }, {'env_id':",
"'max_timesteps': 6000000, 'reward_floor': -1000.0, 'reward_ceiling': 1000.0, }, ]) bandit_tasks =",
"} ]) register_benchmark( id='MinecraftEasy-v0', name='MinecraftEasy', view_group=\"Minecraft\", description='Minecraft easy benchmark', scorer=scoring.ClipTo01ThenAverage(),",
"'trials': 2, 'max_timesteps': 2400000, 'reward_floor': -10000.0, 'reward_ceiling': 32640.0, }, ])",
"}, { 'env_id': 'QbertNoFrameskip-v4', 'trials': 2, 'max_timesteps': int(4e7), 'reward_floor': 163.9,",
"}, { 'env_id': 'SpaceInvadersNoFrameskip-v4', 'trials': 2, 'max_timesteps': int(2e8), 'reward_floor': 148.0,",
"2000, }, {'env_id': 'Pendulum-v0', 'trials': 1, 'max_timesteps': 1000, }, ])",
"'reward_floor': -280.0, 'reward_ceiling': 4000.0, }, {'env_id': 'Hopper-v1', 'trials': 3, 'max_timesteps':",
"1040.0, }, {'env_id': 'MinecraftComplexityUsage-v0', 'trials': 1, 'max_timesteps': 600000, 'reward_floor': -1000.0,",
"'reward_ceiling': 16280.0, }, {'env_id': 'MinecraftHard-v0', 'trials': 2, 'max_timesteps': 2400000, 'reward_floor':",
"name='MinecraftImpossible', view_group=\"Minecraft\", description='Minecraft impossible benchmark', scorer=scoring.ClipTo01ThenAverage(), tasks=[ {'env_id': 'MinecraftDefaultWorld1-v0', 'trials':",
"view_group=\"Control\", description='Mujoco benchmark with 10M steps', scorer=scoring.ClipTo01ThenAverage(), tasks=[ {'env_id': 'Ant-v1',",
"* 2, }) register_benchmark( id='RandomTabularMDP-v0', name='RandomTabularMDP', description='Random tabular MDPs', scorer=scoring.ClipTo01ThenAverage(num_episodes=1000),",
"'Walker2d-v1', 'trials': 3, 'max_timesteps': 1000000, 'reward_floor': 1.6, 'reward_ceiling': 5500.0, }",
"10000.0, }, { 'env_id': 'PitfallNoFrameskip-v4', 'trials': 2, 'max_timesteps': int(4e7), 'reward_floor':",
"Atari games, with pixel observations', tasks=[ { 'env_id': 'FreewayNoFrameskip-v4', 'trials':",
"}, ]) register_benchmark( id='MinecraftHard-v0', name='MinecraftHard', view_group=\"Minecraft\", description='Minecraft hard benchmark', scorer=scoring.ClipTo01ThenAverage(),",
"'MinecraftHard-v0', 'trials': 2, 'max_timesteps': 2400000, 'reward_floor': -10000.0, 'reward_ceiling': 32640.0, },",
"9, 'reward_floor': 0, 'reward_ceiling': episode_length * n_episodes * 2, })",
"}, { 'env_id': 'GravitarNoFrameskip-v4', 'trials': 2, 'max_timesteps': int(4e7), 'reward_floor': 245.5,",
"1M steps', scorer=scoring.ClipTo01ThenAverage(), tasks=[ {'env_id': 'HalfCheetah-v1', 'trials': 3, 'max_timesteps': 1000000,",
"'max_timesteps': 1000000, 'reward_floor': -43.0, 'reward_ceiling': -0.5, }, {'env_id': 'Swimmer-v1', 'trials':",
"classic control benchmark', scorer=scoring.ClipTo01ThenAverage(), tasks=[ {'env_id': 'CartPole-v0', 'trials': 1, 'max_timesteps':",
"2, 'max_timesteps': 300000, 'reward_floor': -300.0, 'reward_ceiling': 300.0, }, ]) register_benchmark(",
"0.0, }, {'env_id': 'MinecraftTrickyArena1-v0', 'trials': 2, 'max_timesteps': 300000, 'reward_floor': -1000.0,",
"'PongNoFrameskip-v4', 'trials': 2, 'max_timesteps': int(4e7), 'reward_floor': -20.7, 'reward_ceiling': 21.0, },",
"{'env_id': 'Walker2d-v1', 'trials': 3, 'max_timesteps': 1000000, 'reward_floor': 1.6, 'reward_ceiling': 5500.0,",
"'trials': 2, 'max_timesteps': 600000, 'reward_floor': -1000.0, 'reward_ceiling': 1000.0, }, {'env_id':",
"2, 'max_timesteps': int(4e7), 'reward_floor': 18.0, 'reward_ceiling': 100.0, } ]) register_benchmark(",
"5000.0, }, { 'env_id': 'VentureNoFrameskip-v4', 'trials': 2, 'max_timesteps': int(4e7), 'reward_floor':",
"}, ]) register_benchmark( id='ClassicControl-v0', name='ClassicControl', view_group=\"Control\", description='Simple classic control benchmark',",
"32640.0, }, ]) register_benchmark( id='MinecraftImpossible-v0', name='MinecraftImpossible', view_group=\"Minecraft\", description='Minecraft impossible benchmark',",
"{ 'env_id': 'PitfallNoFrameskip-v4', 'trials': 2, 'max_timesteps': int(4e7), 'reward_floor': -348.8, 'reward_ceiling':",
"'reward_ceiling': 100.0, } ]) register_benchmark( id='ClassicControl2-v0', name='ClassicControl2', view_group=\"Control\", description='Simple classic",
"'reward_floor': 0.23, 'reward_ceiling': 500.0, }, {'env_id': 'Walker2d-v1', 'trials': 3, 'max_timesteps':",
"int(4e7), 'reward_floor': 363.9, 'reward_ceiling': 60000.0, }, { 'env_id': 'BreakoutNoFrameskip-v4', 'trials':",
"[5, 10, 50]: for n_episodes in [10, 100, 500]: bandit_tasks.append({",
"'env_id': 'RandomTabularMDP-{s}.states-{a}.actions-{t}.timesteps-{n}.episodes-v0'.format( s=n_states, a=n_actions, t=episode_length, n=n_episodes, ), 'trials': 1, 'max_timesteps':",
"tasks=[ { 'env_id': 'FreewayNoFrameskip-v4', 'trials': 2, 'max_timesteps': int(4e7), 'reward_floor': 0.1,",
"import benchmark_spec, register_benchmark, registry, register_benchmark_view # imports used elsewhere register_benchmark(",
"662.8, 'reward_ceiling': 100.0, }, { 'env_id': 'SolarisNoFrameskip-v4', 'trials': 2, 'max_timesteps':",
"{'env_id': 'Swimmer-v1', 'trials': 3, 'max_timesteps': 1000000, 'reward_floor': 0.23, 'reward_ceiling': 500.0,",
"{'env_id': 'Humanoid-v1', 'trials': 1, 'max_timesteps': 1000000, }, {'env_id': 'HumanoidStandup-v1', 'trials':",
"id='BernoulliBandit-v0', name='BernoulliBandit', description='Multi-armed Bernoulli bandits', scorer=scoring.ClipTo01ThenAverage(num_episodes=1000), tasks=bandit_tasks ) tabular_mdp_tasks =",
"1000.0, }, {'env_id': 'MinecraftDefaultFlat1-v0', 'trials': 2, 'max_timesteps': 2000000, 'reward_floor': -500.0,",
"'max_timesteps': 2000000, 'reward_floor': -1000.0, 'reward_ceiling': 1000.0, }, ]) register_benchmark( id='MinecraftHard-v0',",
"'trials': 1, 'max_timesteps': 600000, 'reward_floor': -1000.0, 'reward_ceiling': 1000.0, }, ])",
"600000, 'reward_floor': -2200.0, 'reward_ceiling': 1000.0, }, {'env_id': 'MinecraftDefaultFlat1-v0', 'trials': 2,",
"from gym.benchmarks import scoring from gym.benchmarks.registration import benchmark_spec, register_benchmark, registry,",
"[10, 100, 500]: bandit_tasks.append({ 'env_id': 'BernoulliBandit-{k}.arms-{n}.episodes-v0'.format(k=n_arms, n=n_episodes), 'trials': 1, 'max_timesteps':",
"from gym.benchmarks.registration import benchmark_spec, register_benchmark, registry, register_benchmark_view # imports used",
"3, 'max_timesteps': 1000000, 'reward_floor': -43.0, 'reward_ceiling': -0.5, }, {'env_id': 'Swimmer-v1',",
"'trials': 3, 'max_timesteps': 1000000, 'reward_floor': 1.6, 'reward_ceiling': 5500.0, } ])",
"{ 'env_id': 'PrivateEyeNoFrameskip-v4', 'trials': 2, 'max_timesteps': int(4e7), 'reward_floor': 662.8, 'reward_ceiling':",
"'reward_ceiling': 100.0, }, { 'env_id': 'SolarisNoFrameskip-v4', 'trials': 2, 'max_timesteps': int(4e7),",
"3, 'max_timesteps': 1000000, 'reward_floor': 16.0, 'reward_ceiling': 4000.0, }, {'env_id': 'InvertedDoublePendulum-v1',",
"'Ant-v1', 'trials': 1, 'max_timesteps': 1000000, }, {'env_id': 'Hopper-v1', 'trials': 1,",
"name='Mujoco1M', view_group=\"Control\", description='Mujoco benchmark with 1M steps', scorer=scoring.ClipTo01ThenAverage(), tasks=[ {'env_id':",
"8040.0, }, {'env_id': 'MinecraftMaze1-v0', 'trials': 2, 'max_timesteps': 600000, 'reward_floor': -1000.0,",
"-43.0, 'reward_ceiling': -0.5, }, {'env_id': 'Swimmer-v1', 'trials': 3, 'max_timesteps': 1000000,",
"medium benchmark', scorer=scoring.ClipTo01ThenAverage(), tasks=[ {'env_id': 'MinecraftCliffWalking1-v0', 'trials': 2, 'max_timesteps': 400000,",
"int(4e7), 'reward_floor': 18.0, 'reward_ceiling': 100.0, } ]) register_benchmark( id='ClassicControl2-v0', name='ClassicControl2',",
"by tinkerbell.benchmark.convert_benchmark.py register_benchmark( id='Mujoco10M-v0', name='Mujoco10M', view_group=\"Control\", description='Mujoco benchmark with 10M",
"'BeamRiderNoFrameskip-v4', 'trials': 2, 'max_timesteps': int(4e7), 'reward_floor': 363.9, 'reward_ceiling': 60000.0, },",
"}, { 'env_id': 'PitfallNoFrameskip-v4', 'trials': 2, 'max_timesteps': int(4e7), 'reward_floor': -348.8,",
"2, 'max_timesteps': 600000, 'reward_floor': -1000.0, 'reward_ceiling': 1000.0, }, {'env_id': 'MinecraftMaze2-v0',",
"'Pendulum-v0', 'trials': 3, 'max_timesteps': 200000, 'reward_floor': -1400.0, 'reward_ceiling': 0.0, },",
"'trials': 1, 'max_timesteps': 900000, 'reward_floor': -1000.0, 'reward_ceiling': 4160.0, }, {'env_id':",
"500.0, }, {'env_id': 'Acrobot-v1', 'trials': 3, 'max_timesteps': 100000, 'reward_floor': -500.0,",
"'reward_ceiling': 5000.0, }, { 'env_id': 'PongNoFrameskip-v4', 'trials': 2, 'max_timesteps': int(2e8),",
"register_benchmark( id='Atari40M', scorer=scoring.TotalReward(), name='Atari40M', view_group=\"Atari\", description='7 Atari games, with pixel",
"'max_timesteps': 900000, 'reward_floor': -1000.0, 'reward_ceiling': 4160.0, }, {'env_id': 'MinecraftAttic-v0', 'trials':",
"2, 'max_timesteps': 6000000, 'reward_floor': -1000.0, 'reward_ceiling': 1000.0, }, ]) bandit_tasks",
"a=n_actions, t=episode_length, n=n_episodes, ), 'trials': 1, 'max_timesteps': 10 ** 9,",
"]) register_benchmark( id='Mujoco1M-v0', name='Mujoco1M', view_group=\"Control\", description='Mujoco benchmark with 1M steps',",
"-0.5, }, {'env_id': 'Swimmer-v1', 'trials': 3, 'max_timesteps': 1000000, 'reward_floor': 0.23,",
"400000, 'reward_floor': -100.0, 'reward_ceiling': 100.0, }, {'env_id': 'MinecraftVertical-v0', 'trials': 2,",
"'reward_floor': 16.0, 'reward_ceiling': 4000.0, }, {'env_id': 'InvertedDoublePendulum-v1', 'trials': 3, 'max_timesteps':",
"{'env_id': 'MinecraftComplexityUsage-v0', 'trials': 1, 'max_timesteps': 600000, 'reward_floor': -1000.0, 'reward_ceiling': 1000.0,",
"id='ClassicControl2-v0', name='ClassicControl2', view_group=\"Control\", description='Simple classic control benchmark', scorer=scoring.ClipTo01ThenAverage(), tasks=[ {'env_id':",
"{ 'env_id': 'SpaceInvadersNoFrameskip-v4', 'trials': 2, 'max_timesteps': int(2e8), 'reward_floor': 148.0, 'reward_ceiling':",
"'trials': 1, 'max_timesteps': 10 ** 9, 'reward_floor': 0, 'reward_ceiling': n_episodes,",
"}, { 'env_id': 'MontezumaRevengeNoFrameskip-v4', 'trials': 2, 'max_timesteps': int(4e7), 'reward_floor': 25.0,",
"scoring from gym.benchmarks.registration import benchmark_spec, register_benchmark, registry, register_benchmark_view # imports",
"name='ClassicControl', view_group=\"Control\", description='Simple classic control benchmark', scorer=scoring.ClipTo01ThenAverage(), tasks=[ {'env_id': 'CartPole-v1',",
"'trials': 2, 'max_timesteps': 300000, 'reward_floor': -300.0, 'reward_ceiling': 300.0, }, ])",
"1000.0, }, {'env_id': 'MinecraftMaze2-v0', 'trials': 2, 'max_timesteps': 2000000, 'reward_floor': -1000.0,",
"benchmark', scorer=scoring.ClipTo01ThenAverage(), tasks=[ {'env_id': 'CartPole-v1', 'trials': 3, 'max_timesteps': 100000, 'reward_floor':",
"{'env_id': 'InvertedDoublePendulum-v1', 'trials': 3, 'max_timesteps': 1000000, 'reward_floor': 53.0, 'reward_ceiling': 10000.0,",
"gym.benchmarks.registration import benchmark_spec, register_benchmark, registry, register_benchmark_view # imports used elsewhere",
"'reward_floor': 245.5, 'reward_ceiling': 1000.0, }, { 'env_id': 'MontezumaRevengeNoFrameskip-v4', 'trials': 2,",
"int(4e7), 'reward_floor': 163.9, 'reward_ceiling': 40000.0, }, { 'env_id': 'SeaquestNoFrameskip-v4', 'trials':",
"'reward_floor': -2200.0, 'reward_ceiling': 1000.0, }, {'env_id': 'MinecraftDefaultFlat1-v0', 'trials': 2, 'max_timesteps':",
"'max_timesteps': int(4e7), 'reward_floor': 0.0, 'reward_ceiling': 5000.0, }, { 'env_id': 'PongNoFrameskip-v4',",
"'Swimmer-v1', 'trials': 3, 'max_timesteps': 1000000, 'reward_floor': 0.23, 'reward_ceiling': 500.0, },",
"view_group=\"Minecraft\", description='Minecraft medium benchmark', scorer=scoring.ClipTo01ThenAverage(), tasks=[ {'env_id': 'MinecraftCliffWalking1-v0', 'trials': 2,",
"'reward_ceiling': 1040.0, }, {'env_id': 'MinecraftComplexityUsage-v0', 'trials': 1, 'max_timesteps': 600000, 'reward_floor':",
"'reward_ceiling': 1000.0, }, ]) register_benchmark( id='MinecraftVeryHard-v0', name='MinecraftVeryHard', view_group=\"Minecraft\", description='Minecraft very",
"0.0, }, ]) ### Autogenerated by tinkerbell.benchmark.convert_benchmark.py register_benchmark( id='Mujoco10M-v0', name='Mujoco10M',",
"5000.0, }, { 'env_id': 'PongNoFrameskip-v4', 'trials': 2, 'max_timesteps': int(2e8), 'reward_floor':",
"{ 'env_id': 'QbertNoFrameskip-v4', 'trials': 2, 'max_timesteps': int(2e8), 'reward_floor': 163.9, 'reward_ceiling':",
"'SpaceInvadersNoFrameskip-v4', 'trials': 2, 'max_timesteps': int(4e7), 'reward_floor': 148.0, 'reward_ceiling': 30000.0, }",
"-1000.0, 'reward_ceiling': 2080.0, }, {'env_id': 'MinecraftSimpleRoomMaze-v0', 'trials': 1, 'max_timesteps': 900000,",
"name='Mujoco10M', view_group=\"Control\", description='Mujoco benchmark with 10M steps', scorer=scoring.ClipTo01ThenAverage(), tasks=[ {'env_id':",
"}, ]) ### Autogenerated by tinkerbell.benchmark.convert_benchmark.py register_benchmark( id='Mujoco10M-v0', name='Mujoco10M', view_group=\"Control\",",
"'reward_ceiling': 800.0, }, { 'env_id': 'EnduroNoFrameskip-v4', 'trials': 2, 'max_timesteps': int(4e7),",
"1, 'max_timesteps': 600000, 'reward_floor': -1000.0, 'reward_ceiling': 1000.0, }, ]) register_benchmark(",
"'env_id': 'SpaceInvadersNoFrameskip-v4', 'trials': 2, 'max_timesteps': int(4e7), 'reward_floor': 148.0, 'reward_ceiling': 30000.0,",
"'max_timesteps': int(2e8), 'reward_floor': 1.7, 'reward_ceiling': 800.0, }, { 'env_id': 'EnduroNoFrameskip-v4',",
"'reward_ceiling': 40000.0, }, { 'env_id': 'SeaquestNoFrameskip-v4', 'trials': 2, 'max_timesteps': int(4e7),",
"'Hopper-v1', 'trials': 3, 'max_timesteps': 1000000, 'reward_floor': 16.0, 'reward_ceiling': 4000.0, },",
"}, {'env_id': 'MinecraftVertical-v0', 'trials': 2, 'max_timesteps': 900000, 'reward_floor': -1000.0, 'reward_ceiling':",
"control benchmark', scorer=scoring.ClipTo01ThenAverage(), tasks=[ {'env_id': 'CartPole-v1', 'trials': 3, 'max_timesteps': 100000,",
"'trials': 3, 'max_timesteps': 100000, 'reward_floor': -500.0, 'reward_ceiling': 0.0, }, {'env_id':",
"register_benchmark( id='MinecraftEasy-v0', name='MinecraftEasy', view_group=\"Minecraft\", description='Minecraft easy benchmark', scorer=scoring.ClipTo01ThenAverage(), tasks=[ {'env_id':",
"100]: tabular_mdp_tasks.append({ 'env_id': 'RandomTabularMDP-{s}.states-{a}.actions-{t}.timesteps-{n}.episodes-v0'.format( s=n_states, a=n_actions, t=episode_length, n=n_episodes, ), 'trials':",
"id='MinecraftEasy-v0', name='MinecraftEasy', view_group=\"Minecraft\", description='Minecraft easy benchmark', scorer=scoring.ClipTo01ThenAverage(), tasks=[ {'env_id': 'MinecraftBasic-v0',",
"900000, 'reward_floor': -1000.0, 'reward_ceiling': 8040.0, }, {'env_id': 'MinecraftMaze1-v0', 'trials': 2,",
"'max_timesteps': 2000000, 'reward_floor': -500.0, 'reward_ceiling': 0.0, }, {'env_id': 'MinecraftTrickyArena1-v0', 'trials':",
"{'env_id': 'CartPole-v1', 'trials': 3, 'max_timesteps': 100000, 'reward_floor': 0.0, 'reward_ceiling': 500.0,",
"1, 'max_timesteps': 1000000, }, {'env_id': 'HumanoidStandup-v1', 'trials': 1, 'max_timesteps': 1000000,",
"id='AtariExploration40M', scorer=scoring.TotalReward(), name='AtariExploration40M', view_group=\"Atari\", description='7 Atari games, with pixel observations',",
"'reward_ceiling': 2800.0, }, {'env_id': 'MinecraftEating1-v0', 'trials': 2, 'max_timesteps': 300000, 'reward_floor':",
"soon from gym.benchmarks import scoring from gym.benchmarks.registration import benchmark_spec, register_benchmark,",
"1000000, 'reward_floor': 5.6, 'reward_ceiling': 1000.0, }, {'env_id': 'Reacher-v1', 'trials': 3,",
"4160.0, }, {'env_id': 'MinecraftAttic-v0', 'trials': 1, 'max_timesteps': 600000, 'reward_floor': -1000.0,",
"tabular_mdp_tasks.append({ 'env_id': 'RandomTabularMDP-{s}.states-{a}.actions-{t}.timesteps-{n}.episodes-v0'.format( s=n_states, a=n_actions, t=episode_length, n=n_episodes, ), 'trials': 1,",
"{ 'env_id': 'SeaquestNoFrameskip-v4', 'trials': 2, 'max_timesteps': int(2e8), 'reward_floor': 68.4, 'reward_ceiling':",
"'trials': 2, 'max_timesteps': int(4e7), 'reward_floor': 363.9, 'reward_ceiling': 60000.0, }, {",
"'reward_floor': -1400.0, 'reward_ceiling': 0.0, }, ]) ### Autogenerated by tinkerbell.benchmark.convert_benchmark.py",
"tasks=[ {'env_id': 'MinecraftMedium-v0', 'trials': 2, 'max_timesteps': 1800000, 'reward_floor': -10000.0, 'reward_ceiling':",
"0.0, 'reward_ceiling': 500.0, }, {'env_id': 'Acrobot-v1', 'trials': 3, 'max_timesteps': 100000,",
"int(4e7), 'reward_floor': 68.4, 'reward_ceiling': 100000.0, }, { 'env_id': 'SpaceInvadersNoFrameskip-v4', 'trials':",
"'trials': 1, 'max_timesteps': 1000000, } ]) register_benchmark( id='Mujoco1M-v0', name='Mujoco1M', view_group=\"Control\",",
"tinkerbell.benchmark.convert_benchmark.py register_benchmark( id='Mujoco10M-v0', name='Mujoco10M', view_group=\"Control\", description='Mujoco benchmark with 10M steps',",
"description='Simple classic control benchmark', scorer=scoring.ClipTo01ThenAverage(), tasks=[ {'env_id': 'CartPole-v0', 'trials': 1,",
"800.0, }, { 'env_id': 'EnduroNoFrameskip-v4', 'trials': 2, 'max_timesteps': int(2e8), 'reward_floor':",
"description='Mujoco benchmark with 1M steps', scorer=scoring.ClipTo01ThenAverage(), tasks=[ {'env_id': 'HalfCheetah-v1', 'trials':",
"'reward_ceiling': 40000.0, }, { 'env_id': 'SeaquestNoFrameskip-v4', 'trials': 2, 'max_timesteps': int(2e8),",
"{ 'env_id': 'SolarisNoFrameskip-v4', 'trials': 2, 'max_timesteps': int(4e7), 'reward_floor': 2047.2, 'reward_ceiling':",
"tasks=[ {'env_id': 'MinecraftCliffWalking1-v0', 'trials': 2, 'max_timesteps': 400000, 'reward_floor': -100.0, 'reward_ceiling':",
"name='MinecraftVeryHard', view_group=\"Minecraft\", description='Minecraft very hard benchmark', scorer=scoring.ClipTo01ThenAverage(), tasks=[ {'env_id': 'MinecraftMedium-v0',",
"in [5]: for episode_length in [10]: for n_episodes in [10,",
"'reward_ceiling': 4000.0, }, {'env_id': 'Hopper-v1', 'trials': 3, 'max_timesteps': 1000000, 'reward_floor':",
"'reward_floor': -1000.0, 'reward_ceiling': 1000.0, }, {'env_id': 'MinecraftMaze2-v0', 'trials': 2, 'max_timesteps':",
"2, 'max_timesteps': 2000000, 'reward_floor': -500.0, 'reward_ceiling': 0.0, }, {'env_id': 'MinecraftTrickyArena1-v0',",
"-1000.0, 'reward_ceiling': 1000.0, }, ]) register_benchmark( id='MinecraftHard-v0', name='MinecraftHard', view_group=\"Minecraft\", description='Minecraft",
"600000, 'reward_floor': -1000.0, 'reward_ceiling': 1000.0, }, {'env_id': 'MinecraftMaze2-v0', 'trials': 2,",
"'env_id': 'BreakoutNoFrameskip-v4', 'trials': 2, 'max_timesteps': int(2e8), 'reward_floor': 1.7, 'reward_ceiling': 800.0,",
"2, 'max_timesteps': int(2e8), 'reward_floor': 0.0, 'reward_ceiling': 5000.0, }, { 'env_id':",
"'reward_floor': -1000.0, 'reward_ceiling': 1000.0, }, ]) register_benchmark( id='MinecraftVeryHard-v0', name='MinecraftVeryHard', view_group=\"Minecraft\",",
"'reward_floor': 363.9, 'reward_ceiling': 60000.0, }, { 'env_id': 'BreakoutNoFrameskip-v4', 'trials': 2,",
"1, 'max_timesteps': 2000, }, {'env_id': 'Pendulum-v0', 'trials': 1, 'max_timesteps': 1000,",
"]) register_benchmark( id='ClassicControl-v0', name='ClassicControl', view_group=\"Control\", description='Simple classic control benchmark', scorer=scoring.ClipTo01ThenAverage(),",
"}, ]) register_benchmark( id='MinecraftMedium-v0', name='MinecraftMedium', view_group=\"Minecraft\", description='Minecraft medium benchmark', scorer=scoring.ClipTo01ThenAverage(),",
"benchmark', scorer=scoring.ClipTo01ThenAverage(), tasks=[ {'env_id': 'MinecraftMedium-v0', 'trials': 2, 'max_timesteps': 1800000, 'reward_floor':",
"2000000, 'reward_floor': -1000.0, 'reward_ceiling': 1000.0, }, ]) register_benchmark( id='MinecraftHard-v0', name='MinecraftHard',",
"'Acrobot-v1', 'trials': 3, 'max_timesteps': 100000, 'reward_floor': -500.0, 'reward_ceiling': 0.0, },",
"'MinecraftEating1-v0', 'trials': 2, 'max_timesteps': 300000, 'reward_floor': -300.0, 'reward_ceiling': 300.0, },",
"'trials': 2, 'max_timesteps': int(4e7), 'reward_floor': -20.7, 'reward_ceiling': 21.0, }, {",
"500]: bandit_tasks.append({ 'env_id': 'BernoulliBandit-{k}.arms-{n}.episodes-v0'.format(k=n_arms, n=n_episodes), 'trials': 1, 'max_timesteps': 10 **",
"363.9, 'reward_ceiling': 60000.0, }, { 'env_id': 'BreakoutNoFrameskip-v4', 'trials': 2, 'max_timesteps':",
"id='Mujoco1M-v0', name='Mujoco1M', view_group=\"Control\", description='Mujoco benchmark with 1M steps', scorer=scoring.ClipTo01ThenAverage(), tasks=[",
"}, {'env_id': 'InvertedDoublePendulum-v1', 'trials': 3, 'max_timesteps': 1000000, 'reward_floor': 53.0, 'reward_ceiling':",
"{'env_id': 'MinecraftHard-v0', 'trials': 2, 'max_timesteps': 2400000, 'reward_floor': -10000.0, 'reward_ceiling': 32640.0,",
"16.0, 'reward_ceiling': 4000.0, }, {'env_id': 'InvertedDoublePendulum-v1', 'trials': 3, 'max_timesteps': 1000000,",
"3, 'max_timesteps': 1000000, 'reward_floor': -280.0, 'reward_ceiling': 4000.0, }, {'env_id': 'Hopper-v1',",
"{ 'env_id': 'EnduroNoFrameskip-v4', 'trials': 2, 'max_timesteps': int(4e7), 'reward_floor': 0.0, 'reward_ceiling':",
"'trials': 3, 'max_timesteps': 1000000, 'reward_floor': 16.0, 'reward_ceiling': 4000.0, }, {'env_id':",
"'max_timesteps': 1000000, 'reward_floor': 0.23, 'reward_ceiling': 500.0, }, {'env_id': 'Walker2d-v1', 'trials':",
"'reward_ceiling': 300.0, }, ]) register_benchmark( id='MinecraftMedium-v0', name='MinecraftMedium', view_group=\"Minecraft\", description='Minecraft medium",
"1, 'max_timesteps': 1000000, }, {'env_id': 'Hopper-v1', 'trials': 1, 'max_timesteps': 1000000,",
"n_episodes in [10, 25, 50, 75, 100]: tabular_mdp_tasks.append({ 'env_id': 'RandomTabularMDP-{s}.states-{a}.actions-{t}.timesteps-{n}.episodes-v0'.format(",
"75, 100]: tabular_mdp_tasks.append({ 'env_id': 'RandomTabularMDP-{s}.states-{a}.actions-{t}.timesteps-{n}.episodes-v0'.format( s=n_states, a=n_actions, t=episode_length, n=n_episodes, ),",
"{ 'env_id': 'GravitarNoFrameskip-v4', 'trials': 2, 'max_timesteps': int(4e7), 'reward_floor': 245.5, 'reward_ceiling':",
"2, 'max_timesteps': int(4e7), 'reward_floor': -20.7, 'reward_ceiling': 21.0, }, { 'env_id':",
"'reward_ceiling': 1000.0, }, ]) register_benchmark( id='MinecraftHard-v0', name='MinecraftHard', view_group=\"Minecraft\", description='Minecraft hard",
"description='Multi-armed Bernoulli bandits', scorer=scoring.ClipTo01ThenAverage(num_episodes=1000), tasks=bandit_tasks ) tabular_mdp_tasks = [] for",
"in [10]: for n_actions in [5]: for episode_length in [10]:",
"{ 'env_id': 'VentureNoFrameskip-v4', 'trials': 2, 'max_timesteps': int(4e7), 'reward_floor': 18.0, 'reward_ceiling':",
"id='MinecraftMedium-v0', name='MinecraftMedium', view_group=\"Minecraft\", description='Minecraft medium benchmark', scorer=scoring.ClipTo01ThenAverage(), tasks=[ {'env_id': 'MinecraftCliffWalking1-v0',",
"4000.0, }, {'env_id': 'Hopper-v1', 'trials': 3, 'max_timesteps': 1000000, 'reward_floor': 16.0,",
"** 9, 'reward_floor': 0, 'reward_ceiling': episode_length * n_episodes * 2,",
"2, 'max_timesteps': int(4e7), 'reward_floor': 662.8, 'reward_ceiling': 100.0, }, { 'env_id':",
"'trials': 2, 'max_timesteps': 300000, 'reward_floor': -1000.0, 'reward_ceiling': 2800.0, }, {'env_id':",
"}, { 'env_id': 'SeaquestNoFrameskip-v4', 'trials': 2, 'max_timesteps': int(2e8), 'reward_floor': 68.4,",
"'MinecraftVertical-v0', 'trials': 2, 'max_timesteps': 900000, 'reward_floor': -1000.0, 'reward_ceiling': 8040.0, },",
"'env_id': 'SeaquestNoFrameskip-v4', 'trials': 2, 'max_timesteps': int(4e7), 'reward_floor': 68.4, 'reward_ceiling': 100000.0,",
"may be removed soon from gym.benchmarks import scoring from gym.benchmarks.registration",
"'trials': 1, 'max_timesteps': 600000, 'reward_floor': -1000.0, 'reward_ceiling': 1040.0, }, {'env_id':",
"name='BernoulliBandit', description='Multi-armed Bernoulli bandits', scorer=scoring.ClipTo01ThenAverage(num_episodes=1000), tasks=bandit_tasks ) tabular_mdp_tasks = []",
"300.0, }, ]) register_benchmark( id='MinecraftMedium-v0', name='MinecraftMedium', view_group=\"Minecraft\", description='Minecraft medium benchmark',",
"1, 'max_timesteps': 1000000, } ]) register_benchmark( id='Mujoco1M-v0', name='Mujoco1M', view_group=\"Control\", description='Mujoco",
"{ 'env_id': 'FreewayNoFrameskip-v4', 'trials': 2, 'max_timesteps': int(4e7), 'reward_floor': 0.1, 'reward_ceiling':",
"1, 'max_timesteps': 900000, 'reward_floor': -1000.0, 'reward_ceiling': 4160.0, }, {'env_id': 'MinecraftAttic-v0',",
"'MinecraftMedium-v0', 'trials': 2, 'max_timesteps': 1800000, 'reward_floor': -10000.0, 'reward_ceiling': 16280.0, },",
"'trials': 1, 'max_timesteps': 10 ** 9, 'reward_floor': 0, 'reward_ceiling': episode_length",
"2, 'max_timesteps': 1800000, 'reward_floor': -10000.0, 'reward_ceiling': 16280.0, }, {'env_id': 'MinecraftHard-v0',",
"'max_timesteps': 1000000, 'reward_floor': 16.0, 'reward_ceiling': 4000.0, }, {'env_id': 'InvertedDoublePendulum-v1', 'trials':",
"id='Mujoco10M-v0', name='Mujoco10M', view_group=\"Control\", description='Mujoco benchmark with 10M steps', scorer=scoring.ClipTo01ThenAverage(), tasks=[",
"'MinecraftBasic-v0', 'trials': 2, 'max_timesteps': 600000, 'reward_floor': -2200.0, 'reward_ceiling': 1000.0, },",
"1000.0, }, ]) register_benchmark( id='MinecraftHard-v0', name='MinecraftHard', view_group=\"Minecraft\", description='Minecraft hard benchmark',",
"'env_id': 'BernoulliBandit-{k}.arms-{n}.episodes-v0'.format(k=n_arms, n=n_episodes), 'trials': 1, 'max_timesteps': 10 ** 9, 'reward_floor':",
"1000000, }, {'env_id': 'HumanoidStandup-v1', 'trials': 1, 'max_timesteps': 1000000, }, {'env_id':",
"-1400.0, 'reward_ceiling': 0.0, }, ]) ### Autogenerated by tinkerbell.benchmark.convert_benchmark.py register_benchmark(",
"'trials': 2, 'max_timesteps': int(4e7), 'reward_floor': -348.8, 'reward_ceiling': 1000.0, }, {",
"'max_timesteps': int(4e7), 'reward_floor': 363.9, 'reward_ceiling': 60000.0, }, { 'env_id': 'BreakoutNoFrameskip-v4',",
"benchmark', scorer=scoring.ClipTo01ThenAverage(), tasks=[ {'env_id': 'MinecraftBasic-v0', 'trials': 2, 'max_timesteps': 600000, 'reward_floor':",
"'reward_ceiling': 30000.0, }, ]) register_benchmark( id='Atari40M', scorer=scoring.TotalReward(), name='Atari40M', view_group=\"Atari\", description='7",
"'max_timesteps': int(4e7), 'reward_floor': -20.7, 'reward_ceiling': 21.0, }, { 'env_id': 'QbertNoFrameskip-v4',",
"benchmark', scorer=scoring.ClipTo01ThenAverage(), tasks=[ {'env_id': 'MinecraftCliffWalking1-v0', 'trials': 2, 'max_timesteps': 400000, 'reward_floor':",
"'trials': 2, 'max_timesteps': int(4e7), 'reward_floor': 2047.2, 'reward_ceiling': 5000.0, }, {",
"-1000.0, 'reward_ceiling': 2800.0, }, {'env_id': 'MinecraftEating1-v0', 'trials': 2, 'max_timesteps': 300000,",
"'env_id': 'MontezumaRevengeNoFrameskip-v4', 'trials': 2, 'max_timesteps': int(4e7), 'reward_floor': 25.0, 'reward_ceiling': 10000.0,",
"}, {'env_id': 'MinecraftTrickyArena1-v0', 'trials': 2, 'max_timesteps': 300000, 'reward_floor': -1000.0, 'reward_ceiling':",
"-500.0, 'reward_ceiling': 0.0, }, {'env_id': 'MinecraftTrickyArena1-v0', 'trials': 2, 'max_timesteps': 300000,",
"'trials': 3, 'max_timesteps': 1000000, 'reward_floor': 53.0, 'reward_ceiling': 10000.0, }, {'env_id':",
"control benchmark', scorer=scoring.ClipTo01ThenAverage(), tasks=[ {'env_id': 'CartPole-v0', 'trials': 1, 'max_timesteps': 2000,",
"t=episode_length, n=n_episodes, ), 'trials': 1, 'max_timesteps': 10 ** 9, 'reward_floor':",
"53.0, 'reward_ceiling': 10000.0, }, {'env_id': 'InvertedPendulum-v1', 'trials': 3, 'max_timesteps': 1000000,",
"'PrivateEyeNoFrameskip-v4', 'trials': 2, 'max_timesteps': int(4e7), 'reward_floor': 662.8, 'reward_ceiling': 100.0, },",
"2, }) register_benchmark( id='RandomTabularMDP-v0', name='RandomTabularMDP', description='Random tabular MDPs', scorer=scoring.ClipTo01ThenAverage(num_episodes=1000), tasks=tabular_mdp_tasks",
"'CartPole-v1', 'trials': 3, 'max_timesteps': 100000, 'reward_floor': 0.0, 'reward_ceiling': 500.0, },",
"{'env_id': 'MinecraftTrickyArena1-v0', 'trials': 2, 'max_timesteps': 300000, 'reward_floor': -1000.0, 'reward_ceiling': 2800.0,",
"'reward_ceiling': 100000.0, }, { 'env_id': 'SpaceInvadersNoFrameskip-v4', 'trials': 2, 'max_timesteps': int(2e8),",
"tabular_mdp_tasks = [] for n_states in [10]: for n_actions in",
"'MinecraftMaze2-v0', 'trials': 2, 'max_timesteps': 2000000, 'reward_floor': -1000.0, 'reward_ceiling': 1000.0, },",
"in [10, 25, 50, 75, 100]: tabular_mdp_tasks.append({ 'env_id': 'RandomTabularMDP-{s}.states-{a}.actions-{t}.timesteps-{n}.episodes-v0'.format( s=n_states,",
"for n_states in [10]: for n_actions in [5]: for episode_length",
"1000000, 'reward_floor': -280.0, 'reward_ceiling': 4000.0, }, {'env_id': 'Hopper-v1', 'trials': 3,",
"name='Atari200M', view_group=\"Atari\", description='7 Atari games, with pixel observations', tasks=[ {",
"100000.0, }, { 'env_id': 'SpaceInvadersNoFrameskip-v4', 'trials': 2, 'max_timesteps': int(4e7), 'reward_floor':",
"'max_timesteps': 1000000, } ]) register_benchmark( id='Mujoco1M-v0', name='Mujoco1M', view_group=\"Control\", description='Mujoco benchmark",
"name='ClassicControl2', view_group=\"Control\", description='Simple classic control benchmark', scorer=scoring.ClipTo01ThenAverage(), tasks=[ {'env_id': 'CartPole-v0',",
"register_benchmark( id='MinecraftMedium-v0', name='MinecraftMedium', view_group=\"Minecraft\", description='Minecraft medium benchmark', scorer=scoring.ClipTo01ThenAverage(), tasks=[ {'env_id':",
"{'env_id': 'Acrobot-v1', 'trials': 3, 'max_timesteps': 100000, 'reward_floor': -500.0, 'reward_ceiling': 0.0,",
"2, 'max_timesteps': int(4e7), 'reward_floor': 163.9, 'reward_ceiling': 40000.0, }, { 'env_id':",
"'trials': 3, 'max_timesteps': 1000000, 'reward_floor': 0.23, 'reward_ceiling': 500.0, }, {'env_id':",
"id='Atari200M', scorer=scoring.TotalReward(), name='Atari200M', view_group=\"Atari\", description='7 Atari games, with pixel observations',",
"'trials': 2, 'max_timesteps': int(4e7), 'reward_floor': 662.8, 'reward_ceiling': 100.0, }, {",
"100000.0, }, { 'env_id': 'SpaceInvadersNoFrameskip-v4', 'trials': 2, 'max_timesteps': int(2e8), 'reward_floor':",
"for n_actions in [5]: for episode_length in [10]: for n_episodes",
"'max_timesteps': int(4e7), 'reward_floor': 148.0, 'reward_ceiling': 30000.0, } ]) register_benchmark( id='AtariExploration40M',",
"observations', tasks=[ { 'env_id': 'BeamRiderNoFrameskip-v4', 'trials': 2, 'max_timesteps': int(4e7), 'reward_floor':",
"** 9, 'reward_floor': 0, 'reward_ceiling': n_episodes, }) register_benchmark( id='BernoulliBandit-v0', name='BernoulliBandit',",
"benchmark_spec, register_benchmark, registry, register_benchmark_view # imports used elsewhere register_benchmark( id='Atari200M',",
"'reward_floor': 148.0, 'reward_ceiling': 30000.0, }, ]) register_benchmark( id='Atari40M', scorer=scoring.TotalReward(), name='Atari40M',",
"40000.0, }, { 'env_id': 'SeaquestNoFrameskip-v4', 'trials': 2, 'max_timesteps': int(2e8), 'reward_floor':",
"{'env_id': 'Ant-v1', 'trials': 1, 'max_timesteps': 1000000, }, {'env_id': 'Hopper-v1', 'trials':",
"'reward_floor': 5.6, 'reward_ceiling': 1000.0, }, {'env_id': 'Reacher-v1', 'trials': 3, 'max_timesteps':",
"'trials': 2, 'max_timesteps': int(4e7), 'reward_floor': 25.0, 'reward_ceiling': 10000.0, }, {",
"'trials': 2, 'max_timesteps': 2000000, 'reward_floor': -1000.0, 'reward_ceiling': 1000.0, }, ])",
"2, 'max_timesteps': int(4e7), 'reward_floor': 25.0, 'reward_ceiling': 10000.0, }, { 'env_id':",
"]) register_benchmark( id='MinecraftEasy-v0', name='MinecraftEasy', view_group=\"Minecraft\", description='Minecraft easy benchmark', scorer=scoring.ClipTo01ThenAverage(), tasks=[",
"'reward_floor': -500.0, 'reward_ceiling': 0.0, }, {'env_id': 'MinecraftTrickyArena1-v0', 'trials': 2, 'max_timesteps':",
"'max_timesteps': int(4e7), 'reward_floor': 1.7, 'reward_ceiling': 800.0, }, { 'env_id': 'EnduroNoFrameskip-v4',",
"int(4e7), 'reward_floor': 2047.2, 'reward_ceiling': 5000.0, }, { 'env_id': 'VentureNoFrameskip-v4', 'trials':",
"'max_timesteps': int(2e8), 'reward_floor': 163.9, 'reward_ceiling': 40000.0, }, { 'env_id': 'SeaquestNoFrameskip-v4',",
"description='Minecraft impossible benchmark', scorer=scoring.ClipTo01ThenAverage(), tasks=[ {'env_id': 'MinecraftDefaultWorld1-v0', 'trials': 2, 'max_timesteps':",
"'max_timesteps': 1000000, 'reward_floor': 53.0, 'reward_ceiling': 10000.0, }, {'env_id': 'InvertedPendulum-v1', 'trials':",
"imports used elsewhere register_benchmark( id='Atari200M', scorer=scoring.TotalReward(), name='Atari200M', view_group=\"Atari\", description='7 Atari",
"'env_id': 'SolarisNoFrameskip-v4', 'trials': 2, 'max_timesteps': int(4e7), 'reward_floor': 2047.2, 'reward_ceiling': 5000.0,"
] |
[
"script was created for one time usage and has to",
"use the same criteria as Kemker et al. Classes and",
"tf import os import json from warnings import warn warn('The",
"we only use samples which only belong to one of",
"valid_idx] x_data = np.stack(x_data) ### Split into test and train",
"1)[0] # Find samples that are shorter than 10 seconds",
"2.0 (the \"License\"); # you may not use this file",
"'ontology.json') target_path = os.path.join(data_dir, 'audioset_data_balanced.pickle') n_classes = 100 n_sample =",
"dataset, which can then be used via :class:`data.timeseries.audioset_data.AudiosetData`. The result",
"file (parsed from ontology.json) - no parent / child relationship",
"warn warn('The script was created for one time usage and",
"np.random.seed(42) n_train = int(n_sample * (1-test_frac)) n_test = int(n_sample *",
"Count number of valid samples for potential classes y_single =",
"x_data = np.stack(x_data) ### Split into test and train and",
"!= [], 'has_child' : j['child_ids'] != [], 'conf' : conf_data[j['name']],",
"+ 'reusing it. All paths specified here are absolute.') #",
">= n_sample_cutoff)[0] our_classes = [classes[i] for i in class_idx] ###",
"length of 10 seconds The chosen classes and samples are",
":3.7 \"\"\" Script to structure the audioset dataset, which can",
"range(len(y)): y_fil.append( np.intersect1d(y[i],classes)) # Find samples with one label n_labels",
"original dataset provides three subsets with different compositions of samples",
"+= 1 continue tokens = line.split('\"') n = tokens[1] csv_data.update({n:l})",
"context_features = { 'start_time_seconds': tf.FixedLenFeature([], tf.float32), 'labels': tf.VarLenFeature(dtype=tf.int64), } context_parsed,",
"version :1.0 # python_version :3.7 \"\"\" Script to structure the",
"The dataset is stored in tensorflow files. Since we work",
"the audioset dataset, which can then be used via :class:`data.timeseries.audioset_data.AudiosetData`.",
"fpath_conf_data = os.path.join(data_dir, 'confidence_data.csv') fpath_label_inds = os.path.join(data_dir, 'class_labels_indices.csv') fpath_ontology =",
"class_idx = np.where(np.asarray(num_samples) >= n_sample_cutoff)[0] our_classes = [classes[i] for i",
"**audio** (numpy.ndarray): Array of shape (10,128) representing one sample with",
"of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless",
"open(fpath_label_inds) as f: for line in f: if l ==",
"potential classes y_single = np.asarray([y_fil[i][0] for i in valid_idx]) num_samples",
"np.intersect1d(y[i],our_classes)) # Find samples that belong to only one of",
"data are preprocessed to fit our continual learning experiments. The",
"classes. Since we only work with a subset of classes",
"open(fpath_conf_data) as f: for line in f: tokens = line.split()",
"for d in dataset: x.append(d[0].numpy()) y.append(tf.sparse.to_dense(tf.sparse.reorder(d[1])).numpy()) ### Filter classes as",
"= '../../datasets/sequential/audioset/' download_dir = os.path.join(data_dir,'audioset_download') fpath_conf_data = os.path.join(data_dir, 'confidence_data.csv') fpath_label_inds",
"= {} with open(fpath_label_inds) as f: for line in f:",
"\"\"\" import numpy as np import pickle import tensorflow as",
"use - we exclude samples that don't have the full",
"Subsequently executing this script will create a pickle file containing",
"restricted in the following way: Classes: - no restriction according",
"following folder: ``datasets/sequential/audioset/audioset_download``. Subsequently executing this script will create a",
"we work with pytorch and there is no utility to",
"all_data = [] for j in json_data: if j['name'] in",
"as described above. # Parse confidence values conf_data = {}",
"saved to a pickle file. \"\"\" import numpy as np",
"via :class:`data.timeseries.audioset_data.AudiosetData`. The result of this script is available at",
"only one of the potential classes. # We also exclude",
"too_short = np.where(np.asarray([x.shape[0] for x in x]) != 10)[0] #",
"{ 'start_time_seconds': tf.FixedLenFeature([], tf.float32), 'labels': tf.VarLenFeature(dtype=tf.int64), } context_parsed, sequence_parsed =",
"[] for d in dataset: x.append(d[0].numpy()) y.append(tf.sparse.to_dense(tf.sparse.reorder(d[1])).numpy()) ### Filter classes",
"the data again according the the chosen classes y_fil =",
"== 1)[0] # Find samples that dont are shorter than",
"of samples per class np.random.seed(42) n_train = int(n_sample * (1-test_frac))",
"numbers from label csv file l = -1 csv_data =",
"and relabel the classes to be between 0 and n_classes",
"np.arange(len(train_ind),len(train_ind)+len(test_ind)) ### Save data with open(target_path, 'wb') as f: pickle.dump([x_data_sub,",
"np import pickle import tensorflow as tf import os import",
"filter and structure them according to our criteria. We use",
"of 10 seconds The chosen classes and samples are then",
"[] for path, subdirs, files in os.walk(download_dir): for name in",
"then split into train and test data and saved to",
"# We also exclude some samples that don't have data",
"[], 'has_child' : j['child_ids'] != [], 'conf' : conf_data[j['name']], 'id'",
"valid_idx] y_data = [np.where(np.asarray(our_classes) == i)[0][0] for i in y_data]",
"# Parse ontology info from json file with open(fpath_ontology, 'r')",
"train_ind = np.arange(0,len(train_ind)) test_ind = np.arange(len(train_ind),len(train_ind)+len(test_ind)) ### Save data with",
"name in files: if 'tfrecord' in name: fpaths.append(os.path.join(path, name)) #",
"some samples that don't have data for the full 10",
"tf.cast(context_parsed['labels'], tf.int64) return audio, label # Apply decode function to",
"use this file except in compliance with the License. #",
"be adapted when ' + 'reusing it. All paths specified",
"j['name'], 'restricted' : j['restrictions'] != [], 'has_child' : j['child_ids'] !=",
": j['restrictions'] != [], 'has_child' : j['child_ids'] != [], 'conf'",
"warn('The script was created for one time usage and has",
"for y in y_fil]) single_label_idx = np.where(n_labels == 1)[0] #",
"be excluded) too_short = np.where(np.asarray([x.shape[0] for x in x]) !=",
"# Find samples that are shorter than 10 seconds (to",
"and samples, we load all available data and then filter",
"samples, we load all available data and then filter and",
"shorter than 10 seconds too_short = np.where(np.asarray([x.shape[0] for x in",
"for i in valid_idx] x_data = np.stack(x_data) ### Split into",
"which can then be used via :class:`data.timeseries.audioset_data.AudiosetData`. The result of",
"confidence values conf_data = {} with open(fpath_conf_data) as f: for",
"ontology file (parsed from ontology.json) - no parent / child",
"shape (1,) containing the class of the corresponding sample \"\"\"",
"tf.VarLenFeature(dtype=tf.int64), } context_parsed, sequence_parsed = tf.parse_single_sequence_example( serialized_example, sequence_features=sequence_features, context_features=context_features )",
"the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required",
"of shape (1,) containing the class of the corresponding sample",
"full 10 seconds. # First discard labels that are not",
"== 1)[0] # Find samples that are shorter than 10",
"n_labels = np.asarray([len(y) for y in y_fil]) single_label_idx = np.where(n_labels",
"License. # You may obtain a copy of the License",
"n_test = int(n_sample * test_frac) train_ind = [] test_ind =",
"classes. # We also exclude some samples that don't have",
"more samples than a certain threshold Samples: - since samples",
"= { 'name' : j['name'], 'restricted' : j['restrictions'] != [],",
"i in class_idx] ### Filter the data again according the",
"in valid_idx] y_data = [np.where(np.asarray(our_classes) == i)[0][0] for i in",
"mapping to work! tf.enable_eager_execution() # Set paths and parameters data_dir",
"per class np.random.seed(42) n_train = int(n_sample * (1-test_frac)) n_test =",
"number of samples per class np.random.seed(42) n_train = int(n_sample *",
"under the License is distributed on an \"AS IS\" BASIS,",
"= os.path.join(data_dir, 'ontology.json') target_path = os.path.join(data_dir, 'audioset_data_balanced.pickle') n_classes = 100",
"files: if 'tfrecord' in name: fpaths.append(os.path.join(path, name)) # Create dataset",
"else: n = n+' '+t else: break conf_data.update({n:c}) # Parse",
"[] for j in json_data: if j['name'] in conf_data.keys(): class_info",
"= 0 for t in tokens: if t.find('%') is not",
"License for the specific language governing permissions and # limitations",
"chosen classes y_fil = [] for i in range(len(y)): y_fil.append(",
"(parsed from ontology.json) - no parent / child relationship (parsed",
"Kemker et al. Classes and samples are restricted in the",
"# Count number of valid samples for potential classes y_single",
"and structure them according to our criteria. We use the",
"as np import pickle import tensorflow as tf import os",
"shorter than 10 seconds (to be excluded) too_short = np.where(np.asarray([x.shape[0]",
"n == '': n = t else: n = n+'",
"potential classes. # We also exclude some samples that don't",
"Find samples that dont are shorter than 10 seconds too_short",
"for i in y_data] y_data = np.asarray(y_data) x_data = [x[i]",
"to ontology file (parsed from ontology.json) - no parent /",
"json_data = json.load(f) # Put all data into a single",
"classes y_fil = [] for i in range(len(y)): y_fil.append( np.intersect1d(y[i],our_classes))",
"in this study. The dataset is stored in tensorflow files.",
"for i in range(len(y)): y_fil.append( np.intersect1d(y[i],our_classes)) # Find samples that",
"valid_idx]) num_samples = [len(np.where(y_single == i)[0]) for i in classes]",
"only one of the potential classes n_labels = np.asarray([len(y) for",
"in range(len(y)): y_fil.append( np.intersect1d(y[i],our_classes)) # Find samples that belong to",
"# Tensorflow eager mode needs to be enabled for dataset",
"tar.gz into the following folder: ``datasets/sequential/audioset/audioset_download``. Subsequently executing this script",
"in range(len(y)): y_fil.append( np.intersect1d(y[i],classes)) # Find samples with one label",
"range(len(y)): y_fil.append( np.intersect1d(y[i],our_classes)) # Find samples that belong to only",
"\"\"\" Script to structure the audioset dataset, which can then",
"stored in tensorflow files. Since we work with pytorch and",
"sequence_features = { 'audio_embedding': tf.FixedLenSequenceFeature([], tf.string), } context_features = {",
"be enabled for dataset mapping to work! tf.enable_eager_execution() # Set",
"the chosen classes y_fil = [] for i in range(len(y)):",
"no parent / child relationship (parsed from ontology.json) - confidence",
"= line.split('\"') n = tokens[1] csv_data.update({n:l}) l +=1 # Parse",
"one of the potential classes. # We also exclude some",
"single_label_idx = np.where(n_labels == 1)[0] # Find samples that dont",
"with a subset of classes and samples, we load all",
"to our criteria. We use the same criteria as Kemker",
"dataset and decode dataset = tf.data.TFRecordDataset(fpaths) dataset = dataset.map(decode) #",
"and t != '-': if n == '': n =",
"j['name'] in conf_data.keys(): class_info = { 'name' : j['name'], 'restricted'",
"to one of the classes we use - we exclude",
"= -1 csv_data = {} with open(fpath_label_inds) as f: for",
"parse confidence c = 0 for t in tokens: if",
"was copied from website into txt file) - number of",
"into test and train and restrict the number of samples",
"with pytorch and there is no utility to read tensorflow",
"them as numpy arrays in a pickle file. Furthermore the",
"0.20 ### Load data by serializing files and applying decode",
"applying decode function. def decode(serialized_example): \"\"\"Decode data from TFRecord files.",
"os.walk(download_dir): for name in files: if 'tfrecord' in name: fpaths.append(os.path.join(path,",
"that belong to only one of the potential classes. #",
"fit our continual learning experiments. The original dataset provides three",
"samples: we only take classes that have more samples than",
"in compliance with the License. # You may obtain a",
"and # limitations under the License. # # title :data/timeseries/preprocess_audioset.py",
"tf.parse_single_sequence_example( serialized_example, sequence_features=sequence_features, context_features=context_features ) audio = tf.decode_raw(sequence_parsed['audio_embedding'], tf.uint8) label",
"the set of valid samples valid_idx = np.setdiff1d(single_label_idx,too_short) # Count",
"under the License. # # title :data/timeseries/preprocess_audioset.py # author :be",
"again according the the chosen classes y_fil = [] for",
"train_ind = np.asarray(train_ind) test_ind = np.asarray(test_ind) sub_sample_idx = np.hstack((train_ind,test_ind)) x_data_sub",
"path, subdirs, files in os.walk(download_dir): for name in files: if",
"software # distributed under the License is distributed on an",
"np.where(np.asarray(num_samples) >= n_sample_cutoff)[0] our_classes = [classes[i] for i in class_idx]",
"file. \"\"\" import numpy as np import pickle import tensorflow",
"from warnings import warn warn('The script was created for one",
"= [] for c in all_data: if not c['restricted'] and",
"classes y_fil = [] for i in range(len(y)): y_fil.append( np.intersect1d(y[i],classes))",
"test_ind = np.asarray(test_ind) sub_sample_idx = np.hstack((train_ind,test_ind)) x_data_sub = x_data[sub_sample_idx,:,:] y_data_sub",
"x_data_sub = x_data[sub_sample_idx,:,:] y_data_sub = y_data[sub_sample_idx] train_ind = np.arange(0,len(train_ind)) test_ind",
"data with open(target_path, 'wb') as f: pickle.dump([x_data_sub, y_data_sub, train_ind, test_ind],",
"to be adapted when ' + 'reusing it. All paths",
"= tf.decode_raw(sequence_parsed['audio_embedding'], tf.uint8) label = tf.cast(context_parsed['labels'], tf.int64) return audio, label",
"- no restriction according to ontology file (parsed from ontology.json)",
": j['name'], 'restricted' : j['restrictions'] != [], 'has_child' : j['child_ids']",
"= [] test_ind = [] for i in range(n_classes): sample_idx",
"created :31/03/2020 # version :1.0 # python_version :3.7 \"\"\" Script",
"is no utility to read tensorflow files, we extract the",
"serialized_example as created by tf.data.TFRecordDataset Returns: (tuple): Tuple containing: -",
"== i)[0][0] for i in y_data] y_data = np.asarray(y_data) x_data",
"Take the n classes with the highest number of samples",
"certain threshold Samples: - since samples can have multiple labels,",
"All paths specified here are absolute.') # Tensorflow eager mode",
"fpaths = [] for path, subdirs, files in os.walk(download_dir): for",
"data from TFRecord files. Args: serialized_example: serialized_example as created by",
"from ontology.json) - confidence level > 70% (data was copied",
"features - **label** (numpy.ndarray): Array of shape (1,) containing the",
"in class_idx] ### Filter the data again according the the",
"== i)[0] n_sample_class = len(sample_idx) rand_idx = np.arange(n_sample_class) np.random.shuffle(rand_idx) train_ind.extend(sample_idx[rand_idx[0:n_train]])",
"for c in all_data: if not c['restricted'] and not c['has_child']",
"in name: fpaths.append(os.path.join(path, name)) # Create dataset and decode dataset",
"t.find('%') == -1 and t != '-': if n ==",
"import tensorflow as tf import os import json from warnings",
"we load all available data and then filter and structure",
"needs to be enabled for dataset mapping to work! tf.enable_eager_execution()",
"The original dataset provides three subsets with different compositions of",
"no utility to read tensorflow files, we extract the data",
"from TFRecord files. Args: serialized_example: serialized_example as created by tf.data.TFRecordDataset",
"line.split('\"') n = tokens[1] csv_data.update({n:l}) l +=1 # Parse ontology",
"since samples can have multiple labels, we only use samples",
"from https://research.google.com/audioset/download.html and extract the tar.gz into the following folder:",
"Array of shape (1,) containing the class of the corresponding",
"study. The dataset is stored in tensorflow files. Since we",
"int(t[:-1]) # parse class name n = '' for t",
"class of the corresponding sample \"\"\" sequence_features = { 'audio_embedding':",
"are restricted in the following way: Classes: - no restriction",
"seconds The chosen classes and samples are then split into",
"t in tokens: if t.find('%') == -1 and t !=",
"not in the set of potential classes y_fil = []",
"number of samples: we only take classes that have more",
"to work! tf.enable_eager_execution() # Set paths and parameters data_dir =",
"anyway. fpaths = [] for path, subdirs, files in os.walk(download_dir):",
"learning experiments. The original dataset provides three subsets with different",
"into train and test data and saved to a pickle",
"permissions and # limitations under the License. # # title",
"function to all dataset entries using map function. # Take",
"sequence_features=sequence_features, context_features=context_features ) audio = tf.decode_raw(sequence_parsed['audio_embedding'], tf.uint8) label = tf.cast(context_parsed['labels'],",
"eager mode needs to be enabled for dataset mapping to",
"Create dataset and decode dataset = tf.data.TFRecordDataset(fpaths) dataset = dataset.map(decode)",
"in the following way: Classes: - no restriction according to",
"classes and samples, we load all available data and then",
"data and saved to a pickle file. \"\"\" import numpy",
"'+t else: break conf_data.update({n:c}) # Parse class numbers from label",
"### Filter classes as described above. # Parse confidence values",
"= np.asarray([len(y) for y in y_fil]) single_label_idx = np.where(n_labels ==",
": csv_data[j['name']] } all_data.append(class_info) # Filter classes classes = []",
"# Put all data into a single list. all_data =",
"in all_data: if not c['restricted'] and not c['has_child'] and c['conf']",
"OF ANY KIND, either express or implied. # See the",
"Classes: - no restriction according to ontology file (parsed from",
"WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.",
"tensorflow as tf import os import json from warnings import",
"warnings import warn warn('The script was created for one time",
"discard labels that are not in the set of potential",
"ANY KIND, either express or implied. # See the License",
"See the License for the specific language governing permissions and",
"= line.split() # parse confidence c = 0 for t",
"10 seconds (to be excluded) too_short = np.where(np.asarray([x.shape[0] for x",
"n_sample_cutoff = np.sort(num_samples)[-n_classes] class_idx = np.where(np.asarray(num_samples) >= n_sample_cutoff)[0] our_classes =",
"as tf import os import json from warnings import warn",
"containing the class of the corresponding sample \"\"\" sequence_features =",
"y_data = np.asarray(y_data) x_data = [x[i] for i in valid_idx]",
"import warn warn('The script was created for one time usage",
"potential classes y_fil = [] for i in range(len(y)): y_fil.append(",
"the License. # You may obtain a copy of the",
"at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable",
"for the specific language governing permissions and # limitations under",
"and test data and saved to a pickle file. \"\"\"",
"dataset entries using map function. # Take files from all",
"[x[i] for i in valid_idx] x_data = np.stack(x_data) ### Split",
"to in writing, software # distributed under the License is",
"f: if l == -1: l += 1 continue tokens",
"# Find samples with one label n_labels = np.asarray([len(y) for",
"work with pytorch and there is no utility to read",
"# See the License for the specific language governing permissions",
"the following folder: ``datasets/sequential/audioset/audioset_download``. Subsequently executing this script will create",
"et al. Classes and samples are restricted in the following",
"# Extract data to lists x = [] y =",
"y_fil = [] for i in range(len(y)): y_fil.append( np.intersect1d(y[i],our_classes)) #",
"Restructure data and relabel the classes to be between 0",
"set of valid samples valid_idx = np.setdiff1d(single_label_idx,too_short) # Count number",
"i)[0] n_sample_class = len(sample_idx) rand_idx = np.arange(n_sample_class) np.random.shuffle(rand_idx) train_ind.extend(sample_idx[rand_idx[0:n_train]]) test_ind.extend(sample_idx[rand_idx[n_train:n_sample]])",
"and train and restrict the number of samples per class",
"= [classes[i] for i in class_idx] ### Filter the data",
"= np.asarray(train_ind) test_ind = np.asarray(test_ind) sub_sample_idx = np.hstack((train_ind,test_ind)) x_data_sub =",
"language governing permissions and # limitations under the License. #",
"``datasets/sequential/audioset/audioset_download``. Subsequently executing this script will create a pickle file",
"or agreed to in writing, software # distributed under the",
"decode function to all dataset entries using map function. #",
"we use - we exclude samples that don't have the",
"than 10 seconds (to be excluded) too_short = np.where(np.asarray([x.shape[0] for",
"np.where(np.asarray([x.shape[0] for x in x]) != 10)[0] # Construct the",
"# Find samples that dont are shorter than 10 seconds",
"required by applicable law or agreed to in writing, software",
"x = [] y = [] for d in dataset:",
"(10,128) representing one sample with 10 timesteps and 128 features",
"### Filter the samples. # Find samples that belong to",
"BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either",
"Load data by serializing files and applying decode function. def",
"break conf_data.update({n:c}) # Parse class numbers from label csv file",
"with the License. # You may obtain a copy of",
"be used via :class:`data.timeseries.audioset_data.AudiosetData`. The result of this script is",
"potential classes n_labels = np.asarray([len(y) for y in y_fil]) single_label_idx",
"name: fpaths.append(os.path.join(path, name)) # Create dataset and decode dataset =",
"j['child_ids'] != [], 'conf' : conf_data[j['name']], 'id' : csv_data[j['name']] }",
"t in tokens: if t.find('%') is not -1: c =",
"open(fpath_ontology, 'r') as f: json_data = json.load(f) # Put all",
"and saved to a pickle file. \"\"\" import numpy as",
"according to ontology file (parsed from ontology.json) - no parent",
"# contact :<EMAIL> # created :31/03/2020 # version :1.0 #",
"time usage and has to be adapted when ' +",
"parameters data_dir = '../../datasets/sequential/audioset/' download_dir = os.path.join(data_dir,'audioset_download') fpath_conf_data = os.path.join(data_dir,",
"that don't have the full length of 10 seconds The",
"data to lists x = [] y = [] for",
"pickle import tensorflow as tf import os import json from",
"to be enabled for dataset mapping to work! tf.enable_eager_execution() #",
"dataset: x.append(d[0].numpy()) y.append(tf.sparse.to_dense(tf.sparse.reorder(d[1])).numpy()) ### Filter classes as described above. #",
"since we repartition anyway. fpaths = [] for path, subdirs,",
"compliance with the License. # You may obtain a copy",
"load all available data and then filter and structure them",
"Since we work with pytorch and there is no utility",
"agreed to in writing, software # distributed under the License",
"samples that don't have the full length of 10 seconds",
"The chosen classes and samples are then split into train",
"for path, subdirs, files in os.walk(download_dir): for name in files:",
"pickle file. \"\"\" import numpy as np import pickle import",
"y in y_fil]) single_label_idx = np.where(n_labels == 1)[0] # Find",
"= [x[i] for i in valid_idx] x_data = np.stack(x_data) ###",
"= np.where(np.asarray(num_samples) >= n_sample_cutoff)[0] our_classes = [classes[i] for i in",
"distributed under the License is distributed on an \"AS IS\"",
"[] y = [] for d in dataset: x.append(d[0].numpy()) y.append(tf.sparse.to_dense(tf.sparse.reorder(d[1])).numpy())",
"If you want to recreate or modify this dataset, download",
"= [] for i in range(len(y)): y_fil.append( np.intersect1d(y[i],classes)) # Find",
"available at https://www.dropbox.com/s/07dfeeuf5aq4w1h/audioset_data_balanced?dl=0 If you want to recreate or modify",
"to fit our continual learning experiments. The original dataset provides",
"i in valid_idx]) num_samples = [len(np.where(y_single == i)[0]) for i",
"# Construct the set of valid samples valid_idx = np.setdiff1d(single_label_idx,too_short)",
"Extract data to lists x = [] y = []",
"classes.append(c['id']) ### Filter the samples. # Find samples that belong",
"express or implied. # See the License for the specific",
"data for the full 10 seconds. # First discard labels",
"Find samples with one label n_labels = np.asarray([len(y) for y",
"= np.arange(len(train_ind),len(train_ind)+len(test_ind)) ### Save data with open(target_path, 'wb') as f:",
"except in compliance with the License. # You may obtain",
"Tensorflow eager mode needs to be enabled for dataset mapping",
"in f: if l == -1: l += 1 continue",
"repartition anyway. fpaths = [] for path, subdirs, files in",
"Samples: - since samples can have multiple labels, we only",
"is not -1: c = int(t[:-1]) # parse class name",
"pickle file containing the 100 class subset of audioset used",
"script is available at https://www.dropbox.com/s/07dfeeuf5aq4w1h/audioset_data_balanced?dl=0 If you want to recreate",
"Licensed under the Apache License, Version 2.0 (the \"License\"); #",
"in y_fil]) single_label_idx = np.where(n_labels == 1)[0] # Find samples",
"don't have data for the full 10 seconds. # First",
"np.asarray([len(y) for y in y_fil]) single_label_idx = np.where(n_labels == 1)[0]",
"not use this file except in compliance with the License.",
"We use the same criteria as Kemker et al. Classes",
"data and then filter and structure them according to our",
"a pickle file. \"\"\" import numpy as np import pickle",
"if not c['restricted'] and not c['has_child'] and c['conf'] >= 70:",
"writing, software # distributed under the License is distributed on",
"of the potential classes. # We also exclude some samples",
"data sets since we repartition anyway. fpaths = [] for",
"np.arange(n_sample_class) np.random.shuffle(rand_idx) train_ind.extend(sample_idx[rand_idx[0:n_train]]) test_ind.extend(sample_idx[rand_idx[n_train:n_sample]]) train_ind = np.asarray(train_ind) test_ind = np.asarray(test_ind)",
"you may not use this file except in compliance with",
"Args: serialized_example: serialized_example as created by tf.data.TFRecordDataset Returns: (tuple): Tuple",
"them according to our criteria. We use the same criteria",
"[] for i in range(len(y)): y_fil.append( np.intersect1d(y[i],classes)) # Find samples",
"train_ind.extend(sample_idx[rand_idx[0:n_train]]) test_ind.extend(sample_idx[rand_idx[n_train:n_sample]]) train_ind = np.asarray(train_ind) test_ind = np.asarray(test_ind) sub_sample_idx =",
"samples which only belong to one of the classes we",
"# Licensed under the Apache License, Version 2.0 (the \"License\");",
"the classes we use - we exclude samples that don't",
"will create a pickle file containing the 100 class subset",
"in dataset: x.append(d[0].numpy()) y.append(tf.sparse.to_dense(tf.sparse.reorder(d[1])).numpy()) ### Filter classes as described above.",
"with one label n_labels = np.asarray([len(y) for y in y_fil])",
"experiments. The original dataset provides three subsets with different compositions",
"https://www.dropbox.com/s/07dfeeuf5aq4w1h/audioset_data_balanced?dl=0 If you want to recreate or modify this dataset,",
"= np.arange(n_sample_class) np.random.shuffle(rand_idx) train_ind.extend(sample_idx[rand_idx[0:n_train]]) test_ind.extend(sample_idx[rand_idx[n_train:n_sample]]) train_ind = np.asarray(train_ind) test_ind =",
"as f: for line in f: tokens = line.split() #",
"this study. The dataset is stored in tensorflow files. Since",
"json.load(f) # Put all data into a single list. all_data",
"f: for line in f: if l == -1: l",
"test_ind = np.arange(len(train_ind),len(train_ind)+len(test_ind)) ### Save data with open(target_path, 'wb') as",
"tf.string), } context_features = { 'start_time_seconds': tf.FixedLenFeature([], tf.float32), 'labels': tf.VarLenFeature(dtype=tf.int64),",
"\"\"\" sequence_features = { 'audio_embedding': tf.FixedLenSequenceFeature([], tf.string), } context_features =",
"Filter classes classes = [] for c in all_data: if",
"- confidence level > 70% (data was copied from website",
"mode needs to be enabled for dataset mapping to work!",
"for name in files: if 'tfrecord' in name: fpaths.append(os.path.join(path, name))",
"'-': if n == '': n = t else: n",
"[len(np.where(y_single == i)[0]) for i in classes] # Take the",
"[] for i in range(len(y)): y_fil.append( np.intersect1d(y[i],our_classes)) # Find samples",
"label # Apply decode function to all dataset entries using",
"the full length of 10 seconds The chosen classes and",
"al. Classes and samples are restricted in the following way:",
"CONDITIONS OF ANY KIND, either express or implied. # See",
"representing one sample with 10 timesteps and 128 features -",
"json_data: if j['name'] in conf_data.keys(): class_info = { 'name' :",
"python3 # Copyright 2020 <NAME> # # Licensed under the",
"to recreate or modify this dataset, download the audioset data",
"for line in f: tokens = line.split() # parse confidence",
"samples for potential classes y_single = np.asarray([y_fil[i][0] for i in",
"is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES",
"'labels': tf.VarLenFeature(dtype=tf.int64), } context_parsed, sequence_parsed = tf.parse_single_sequence_example( serialized_example, sequence_features=sequence_features, context_features=context_features",
"sample_idx = np.where(y_data == i)[0] n_sample_class = len(sample_idx) rand_idx =",
"train and test data and saved to a pickle file.",
"all dataset entries using map function. # Take files from",
"containing the 100 class subset of audioset used in this",
"numpy as np import pickle import tensorflow as tf import",
"#!/usr/bin/env python3 # Copyright 2020 <NAME> # # Licensed under",
"== i)[0]) for i in classes] # Take the n",
"have the full length of 10 seconds The chosen classes",
"100 class subset of audioset used in this study. The",
"tf.data.TFRecordDataset(fpaths) dataset = dataset.map(decode) # Extract data to lists x",
"chosen classes and samples are then split into train and",
"(tuple): Tuple containing: - **audio** (numpy.ndarray): Array of shape (10,128)",
"when ' + 'reusing it. All paths specified here are",
"of shape (10,128) representing one sample with 10 timesteps and",
"(numpy.ndarray): Array of shape (1,) containing the class of the",
"all_data: if not c['restricted'] and not c['has_child'] and c['conf'] >=",
"and samples are then split into train and test data",
"'start_time_seconds': tf.FixedLenFeature([], tf.float32), 'labels': tf.VarLenFeature(dtype=tf.int64), } context_parsed, sequence_parsed = tf.parse_single_sequence_example(",
"class_info = { 'name' : j['name'], 'restricted' : j['restrictions'] !=",
"Parse ontology info from json file with open(fpath_ontology, 'r') as",
"labels, we only use samples which only belong to one",
"Put all data into a single list. all_data = []",
"from json file with open(fpath_ontology, 'r') as f: json_data =",
"* test_frac) train_ind = [] test_ind = [] for i",
"tokens = line.split('\"') n = tokens[1] csv_data.update({n:l}) l +=1 #",
"and samples are restricted in the following way: Classes: -",
"website into txt file) - number of samples: we only",
"that are shorter than 10 seconds (to be excluded) too_short",
"which only belong to one of the classes we use",
"not -1: c = int(t[:-1]) # parse class name n",
"subsets with different compositions of samples and classes. Since we",
"only belong to one of the classes we use -",
"**label** (numpy.ndarray): Array of shape (1,) containing the class of",
"(parsed from ontology.json) - confidence level > 70% (data was",
"if t.find('%') == -1 and t != '-': if n",
"} context_features = { 'start_time_seconds': tf.FixedLenFeature([], tf.float32), 'labels': tf.VarLenFeature(dtype=tf.int64), }",
"a certain threshold Samples: - since samples can have multiple",
"used via :class:`data.timeseries.audioset_data.AudiosetData`. The result of this script is available",
"our_classes = [classes[i] for i in class_idx] ### Filter the",
"csv file l = -1 csv_data = {} with open(fpath_label_inds)",
"multiple labels, we only use samples which only belong to",
"our criteria. We use the same criteria as Kemker et",
"in json_data: if j['name'] in conf_data.keys(): class_info = { 'name'",
"if l == -1: l += 1 continue tokens =",
"files and applying decode function. def decode(serialized_example): \"\"\"Decode data from",
"dataset mapping to work! tf.enable_eager_execution() # Set paths and parameters",
"[] for c in all_data: if not c['restricted'] and not",
"class numbers from label csv file l = -1 csv_data",
"### Load data by serializing files and applying decode function.",
"as f: for line in f: if l == -1:",
"and c['conf'] >= 70: classes.append(c['id']) ### Filter the samples. #",
"set of potential classes y_fil = [] for i in",
"OR CONDITIONS OF ANY KIND, either express or implied. #",
"Furthermore the data are preprocessed to fit our continual learning",
"with open(target_path, 'wb') as f: pickle.dump([x_data_sub, y_data_sub, train_ind, test_ind], f)",
"samples can have multiple labels, we only use samples which",
"tf.decode_raw(sequence_parsed['audio_embedding'], tf.uint8) label = tf.cast(context_parsed['labels'], tf.int64) return audio, label #",
"the License is distributed on an \"AS IS\" BASIS, #",
"in x]) != 10)[0] # Construct the set of valid",
"valid samples valid_idx = np.setdiff1d(single_label_idx,too_short) # Count number of valid",
"one of the classes we use - we exclude samples",
"def decode(serialized_example): \"\"\"Decode data from TFRecord files. Args: serialized_example: serialized_example",
"n = n+' '+t else: break conf_data.update({n:c}) # Parse class",
"restriction according to ontology file (parsed from ontology.json) - no",
"dont are shorter than 10 seconds too_short = np.where(np.asarray([x.shape[0] for",
"dataset = dataset.map(decode) # Extract data to lists x =",
"data and relabel the classes to be between 0 and",
"Copyright 2020 <NAME> # # Licensed under the Apache License,",
"of this script is available at https://www.dropbox.com/s/07dfeeuf5aq4w1h/audioset_data_balanced?dl=0 If you want",
"line in f: if l == -1: l += 1",
"to all dataset entries using map function. # Take files",
"of classes and samples, we load all available data and",
"decode function. def decode(serialized_example): \"\"\"Decode data from TFRecord files. Args:",
"[classes[i] for i in class_idx] ### Filter the data again",
"have more samples than a certain threshold Samples: - since",
"[np.where(np.asarray(our_classes) == i)[0][0] for i in y_data] y_data = np.asarray(y_data)",
"n_classes = 100 n_sample = 1000 test_frac = 0.20 ###",
"split into train and test data and saved to a",
"c['conf'] >= 70: classes.append(c['id']) ### Filter the samples. # Find",
"-1: c = int(t[:-1]) # parse class name n =",
"Array of shape (10,128) representing one sample with 10 timesteps",
"== '': n = t else: n = n+' '+t",
"'audioset_data_balanced.pickle') n_classes = 100 n_sample = 1000 test_frac = 0.20",
"seconds. # First discard labels that are not in the",
"!= 10)[0] # Construct the set of valid samples valid_idx",
"in classes] # Take the n classes with the highest",
"one of the potential classes n_labels = np.asarray([len(y) for y",
"that don't have data for the full 10 seconds. #",
"test_ind = [] for i in range(n_classes): sample_idx = np.where(y_data",
"author :be # contact :<EMAIL> # created :31/03/2020 # version",
"Find samples that belong to only one of the potential",
"samples that don't have data for the full 10 seconds.",
"recreate or modify this dataset, download the audioset data from",
"created for one time usage and has to be adapted",
":31/03/2020 # version :1.0 # python_version :3.7 \"\"\" Script to",
"for t in tokens: if t.find('%') == -1 and t",
"# Restructure data and relabel the classes to be between",
"(data was copied from website into txt file) - number",
"classes with the highest number of samples n_sample_cutoff = np.sort(num_samples)[-n_classes]",
"law or agreed to in writing, software # distributed under",
"Split into test and train and restrict the number of",
"this script is available at https://www.dropbox.com/s/07dfeeuf5aq4w1h/audioset_data_balanced?dl=0 If you want to",
"return audio, label # Apply decode function to all dataset",
"j in json_data: if j['name'] in conf_data.keys(): class_info = {",
"are preprocessed to fit our continual learning experiments. The original",
"j['restrictions'] != [], 'has_child' : j['child_ids'] != [], 'conf' :",
"of the corresponding sample \"\"\" sequence_features = { 'audio_embedding': tf.FixedLenSequenceFeature([],",
"safe them as numpy arrays in a pickle file. Furthermore",
"\"\"\"Decode data from TFRecord files. Args: serialized_example: serialized_example as created",
"dataset, download the audioset data from https://research.google.com/audioset/download.html and extract the",
"and then filter and structure them according to our criteria.",
"confidence c = 0 for t in tokens: if t.find('%')",
"for dataset mapping to work! tf.enable_eager_execution() # Set paths and",
"csv_data = {} with open(fpath_label_inds) as f: for line in",
"1 continue tokens = line.split('\"') n = tokens[1] csv_data.update({n:l}) l",
"valid_idx = np.setdiff1d(single_label_idx,too_short) # Restructure data and relabel the classes",
"f: for line in f: tokens = line.split() # parse",
"= np.where(n_labels == 1)[0] # Find samples that dont are",
"Classes and samples are restricted in the following way: Classes:",
"provides three subsets with different compositions of samples and classes.",
"if j['name'] in conf_data.keys(): class_info = { 'name' : j['name'],",
"paths specified here are absolute.') # Tensorflow eager mode needs",
"if 'tfrecord' in name: fpaths.append(os.path.join(path, name)) # Create dataset and",
"in files: if 'tfrecord' in name: fpaths.append(os.path.join(path, name)) # Create",
"files. Since we work with pytorch and there is no",
"= dataset.map(decode) # Extract data to lists x = []",
"samples that dont are shorter than 10 seconds too_short =",
"adapted when ' + 'reusing it. All paths specified here",
"-1 and t != '-': if n == '': n",
"classes and samples are then split into train and test",
"Since we only work with a subset of classes and",
"# Create dataset and decode dataset = tf.data.TFRecordDataset(fpaths) dataset =",
":data/timeseries/preprocess_audioset.py # author :be # contact :<EMAIL> # created :31/03/2020",
"may obtain a copy of the License at # #",
"json from warnings import warn warn('The script was created for",
"executing this script will create a pickle file containing the",
"Filter the samples. # Find samples that belong to only",
"the set of potential classes y_fil = [] for i",
"for line in f: if l == -1: l +=",
"conf_data[j['name']], 'id' : csv_data[j['name']] } all_data.append(class_info) # Filter classes classes",
"c['has_child'] and c['conf'] >= 70: classes.append(c['id']) ### Filter the samples.",
"== -1: l += 1 continue tokens = line.split('\"') n",
"x_data = [x[i] for i in valid_idx] x_data = np.stack(x_data)",
"dataset is stored in tensorflow files. Since we work with",
"and has to be adapted when ' + 'reusing it.",
"IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,",
"tf.enable_eager_execution() # Set paths and parameters data_dir = '../../datasets/sequential/audioset/' download_dir",
"with open(fpath_label_inds) as f: for line in f: if l",
"0 and n_classes y_data = [y_fil[i][0] for i in valid_idx]",
"* (1-test_frac)) n_test = int(n_sample * test_frac) train_ind = []",
"Script to structure the audioset dataset, which can then be",
"n_sample_cutoff)[0] our_classes = [classes[i] for i in class_idx] ### Filter",
"= [] for path, subdirs, files in os.walk(download_dir): for name",
"with different compositions of samples and classes. Since we only",
"may not use this file except in compliance with the",
"available data and then filter and structure them according to",
"'class_labels_indices.csv') fpath_ontology = os.path.join(data_dir, 'ontology.json') target_path = os.path.join(data_dir, 'audioset_data_balanced.pickle') n_classes",
"classes we use - we exclude samples that don't have",
"test_frac = 0.20 ### Load data by serializing files and",
"= np.where(n_labels == 1)[0] # Find samples that are shorter",
"classes = [] for c in all_data: if not c['restricted']",
"WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or",
"samples. # Find samples that belong to only one of",
"pickle file. Furthermore the data are preprocessed to fit our",
":1.0 # python_version :3.7 \"\"\" Script to structure the audioset",
"test data and saved to a pickle file. \"\"\" import",
"this file except in compliance with the License. # You",
"os.path.join(data_dir, 'audioset_data_balanced.pickle') n_classes = 100 n_sample = 1000 test_frac =",
"f: tokens = line.split() # parse confidence c = 0",
"License. # # title :data/timeseries/preprocess_audioset.py # author :be # contact",
"= tf.parse_single_sequence_example( serialized_example, sequence_features=sequence_features, context_features=context_features ) audio = tf.decode_raw(sequence_parsed['audio_embedding'], tf.uint8)",
"tokens: if t.find('%') == -1 and t != '-': if",
"samples with one label n_labels = np.asarray([len(y) for y in",
"# Take files from all three data sets since we",
"parent / child relationship (parsed from ontology.json) - confidence level",
"the full 10 seconds. # First discard labels that are",
"n_classes y_data = [y_fil[i][0] for i in valid_idx] y_data =",
"and there is no utility to read tensorflow files, we",
">= 70: classes.append(c['id']) ### Filter the samples. # Find samples",
"<NAME> # # Licensed under the Apache License, Version 2.0",
"for i in classes] # Take the n classes with",
"in tensorflow files. Since we work with pytorch and there",
"c['restricted'] and not c['has_child'] and c['conf'] >= 70: classes.append(c['id']) ###",
"np.sort(num_samples)[-n_classes] class_idx = np.where(np.asarray(num_samples) >= n_sample_cutoff)[0] our_classes = [classes[i] for",
"[] test_ind = [] for i in range(n_classes): sample_idx =",
"i in range(n_classes): sample_idx = np.where(y_data == i)[0] n_sample_class =",
"the the chosen classes y_fil = [] for i in",
"os.path.join(data_dir, 'confidence_data.csv') fpath_label_inds = os.path.join(data_dir, 'class_labels_indices.csv') fpath_ontology = os.path.join(data_dir, 'ontology.json')",
"# # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law",
"to a pickle file. \"\"\" import numpy as np import",
"same criteria as Kemker et al. Classes and samples are",
"of the classes we use - we exclude samples that",
"are absolute.') # Tensorflow eager mode needs to be enabled",
"and not c['has_child'] and c['conf'] >= 70: classes.append(c['id']) ### Filter",
"y_data_sub = y_data[sub_sample_idx] train_ind = np.arange(0,len(train_ind)) test_ind = np.arange(len(train_ind),len(train_ind)+len(test_ind)) ###",
"# # Licensed under the Apache License, Version 2.0 (the",
"{ 'audio_embedding': tf.FixedLenSequenceFeature([], tf.string), } context_features = { 'start_time_seconds': tf.FixedLenFeature([],",
"file except in compliance with the License. # You may",
"on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS",
"title :data/timeseries/preprocess_audioset.py # author :be # contact :<EMAIL> # created",
"for i in valid_idx] y_data = [np.where(np.asarray(our_classes) == i)[0][0] for",
"70% (data was copied from website into txt file) -",
"that have more samples than a certain threshold Samples: -",
"file. Furthermore the data are preprocessed to fit our continual",
"in range(n_classes): sample_idx = np.where(y_data == i)[0] n_sample_class = len(sample_idx)",
"of samples and classes. Since we only work with a",
"map function. # Take files from all three data sets",
"all data into a single list. all_data = [] for",
"of valid samples valid_idx = np.setdiff1d(single_label_idx,too_short) # Count number of",
"in a pickle file. Furthermore the data are preprocessed to",
"to structure the audioset dataset, which can then be used",
"ontology info from json file with open(fpath_ontology, 'r') as f:",
"of valid samples for potential classes y_single = np.asarray([y_fil[i][0] for",
"belong to only one of the potential classes. # We",
"subset of audioset used in this study. The dataset is",
"np.asarray(test_ind) sub_sample_idx = np.hstack((train_ind,test_ind)) x_data_sub = x_data[sub_sample_idx,:,:] y_data_sub = y_data[sub_sample_idx]",
"take classes that have more samples than a certain threshold",
"'conf' : conf_data[j['name']], 'id' : csv_data[j['name']] } all_data.append(class_info) # Filter",
"# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express",
"serialized_example: serialized_example as created by tf.data.TFRecordDataset Returns: (tuple): Tuple containing:",
"the License. # # title :data/timeseries/preprocess_audioset.py # author :be #",
"= os.path.join(data_dir, 'confidence_data.csv') fpath_label_inds = os.path.join(data_dir, 'class_labels_indices.csv') fpath_ontology = os.path.join(data_dir,",
"samples and classes. Since we only work with a subset",
"valid samples valid_idx = np.setdiff1d(single_label_idx,too_short) # Restructure data and relabel",
"= tokens[1] csv_data.update({n:l}) l +=1 # Parse ontology info from",
"# Copyright 2020 <NAME> # # Licensed under the Apache",
"conf_data = {} with open(fpath_conf_data) as f: for line in",
"decode dataset = tf.data.TFRecordDataset(fpaths) dataset = dataset.map(decode) # Extract data",
"= np.hstack((train_ind,test_ind)) x_data_sub = x_data[sub_sample_idx,:,:] y_data_sub = y_data[sub_sample_idx] train_ind =",
"os.path.join(data_dir, 'class_labels_indices.csv') fpath_ontology = os.path.join(data_dir, 'ontology.json') target_path = os.path.join(data_dir, 'audioset_data_balanced.pickle')",
"the audioset data from https://research.google.com/audioset/download.html and extract the tar.gz into",
"sample \"\"\" sequence_features = { 'audio_embedding': tf.FixedLenSequenceFeature([], tf.string), } context_features",
") audio = tf.decode_raw(sequence_parsed['audio_embedding'], tf.uint8) label = tf.cast(context_parsed['labels'], tf.int64) return",
"samples that belong to only one of the potential classes",
"= x_data[sub_sample_idx,:,:] y_data_sub = y_data[sub_sample_idx] train_ind = np.arange(0,len(train_ind)) test_ind =",
"Find samples that are shorter than 10 seconds (to be",
"'r') as f: json_data = json.load(f) # Put all data",
"in the set of potential classes y_fil = [] for",
"a pickle file. Furthermore the data are preprocessed to fit",
"excluded) too_short = np.where(np.asarray([x.shape[0] for x in x]) != 10)[0]",
"data and safe them as numpy arrays in a pickle",
"one sample with 10 timesteps and 128 features - **label**",
"= int(t[:-1]) # parse class name n = '' for",
"the class of the corresponding sample \"\"\" sequence_features = {",
"np.asarray(train_ind) test_ind = np.asarray(test_ind) sub_sample_idx = np.hstack((train_ind,test_ind)) x_data_sub = x_data[sub_sample_idx,:,:]",
"as f: json_data = json.load(f) # Put all data into",
"dataset = tf.data.TFRecordDataset(fpaths) dataset = dataset.map(decode) # Extract data to",
"dataset.map(decode) # Extract data to lists x = [] y",
"confidence level > 70% (data was copied from website into",
"np.intersect1d(y[i],classes)) # Find samples with one label n_labels = np.asarray([len(y)",
"conf_data.keys(): class_info = { 'name' : j['name'], 'restricted' : j['restrictions']",
"x in x]) != 10)[0] # Construct the set of",
"we only take classes that have more samples than a",
"!= '-': if n == '': n = t else:",
"labels that are not in the set of potential classes",
"# Parse confidence values conf_data = {} with open(fpath_conf_data) as",
"= y_data[sub_sample_idx] train_ind = np.arange(0,len(train_ind)) test_ind = np.arange(len(train_ind),len(train_ind)+len(test_ind)) ### Save",
"sets since we repartition anyway. fpaths = [] for path,",
"d in dataset: x.append(d[0].numpy()) y.append(tf.sparse.to_dense(tf.sparse.reorder(d[1])).numpy()) ### Filter classes as described",
"http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed",
"= '' for t in tokens: if t.find('%') == -1",
"for x in x]) != 10)[0] # Construct the set",
"= np.stack(x_data) ### Split into test and train and restrict",
"python_version :3.7 \"\"\" Script to structure the audioset dataset, which",
"threshold Samples: - since samples can have multiple labels, we",
"in tokens: if t.find('%') == -1 and t != '-':",
"i)[0]) for i in classes] # Take the n classes",
"decode(serialized_example): \"\"\"Decode data from TFRecord files. Args: serialized_example: serialized_example as",
"tf.data.TFRecordDataset Returns: (tuple): Tuple containing: - **audio** (numpy.ndarray): Array of",
"'tfrecord' in name: fpaths.append(os.path.join(path, name)) # Create dataset and decode",
"y_data = [y_fil[i][0] for i in valid_idx] y_data = [np.where(np.asarray(our_classes)",
"and parameters data_dir = '../../datasets/sequential/audioset/' download_dir = os.path.join(data_dir,'audioset_download') fpath_conf_data =",
"= int(n_sample * (1-test_frac)) n_test = int(n_sample * test_frac) train_ind",
"we extract the data and safe them as numpy arrays",
"10 seconds The chosen classes and samples are then split",
"download the audioset data from https://research.google.com/audioset/download.html and extract the tar.gz",
"subset of classes and samples, we load all available data",
"here are absolute.') # Tensorflow eager mode needs to be",
"by tf.data.TFRecordDataset Returns: (tuple): Tuple containing: - **audio** (numpy.ndarray): Array",
"'name' : j['name'], 'restricted' : j['restrictions'] != [], 'has_child' :",
"or implied. # See the License for the specific language",
"= os.path.join(data_dir, 'class_labels_indices.csv') fpath_ontology = os.path.join(data_dir, 'ontology.json') target_path = os.path.join(data_dir,",
"'../../datasets/sequential/audioset/' download_dir = os.path.join(data_dir,'audioset_download') fpath_conf_data = os.path.join(data_dir, 'confidence_data.csv') fpath_label_inds =",
"from all three data sets since we repartition anyway. fpaths",
"have data for the full 10 seconds. # First discard",
"we repartition anyway. fpaths = [] for path, subdirs, files",
"[] for i in range(n_classes): sample_idx = np.where(y_data == i)[0]",
"KIND, either express or implied. # See the License for",
"specific language governing permissions and # limitations under the License.",
"i)[0][0] for i in y_data] y_data = np.asarray(y_data) x_data =",
"### Filter the data again according the the chosen classes",
"contact :<EMAIL> # created :31/03/2020 # version :1.0 # python_version",
"audioset data from https://research.google.com/audioset/download.html and extract the tar.gz into the",
"# author :be # contact :<EMAIL> # created :31/03/2020 #",
"= json.load(f) # Put all data into a single list.",
"serializing files and applying decode function. def decode(serialized_example): \"\"\"Decode data",
"the potential classes. # We also exclude some samples that",
"according the the chosen classes y_fil = [] for i",
"Filter the data again according the the chosen classes y_fil",
"work with a subset of classes and samples, we load",
"context_features=context_features ) audio = tf.decode_raw(sequence_parsed['audio_embedding'], tf.uint8) label = tf.cast(context_parsed['labels'], tf.int64)",
"download_dir = os.path.join(data_dir,'audioset_download') fpath_conf_data = os.path.join(data_dir, 'confidence_data.csv') fpath_label_inds = os.path.join(data_dir,",
"# Take the n classes with the highest number of",
"License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by",
"as Kemker et al. Classes and samples are restricted in",
"t.find('%') is not -1: c = int(t[:-1]) # parse class",
"exclude some samples that don't have data for the full",
":class:`data.timeseries.audioset_data.AudiosetData`. The result of this script is available at https://www.dropbox.com/s/07dfeeuf5aq4w1h/audioset_data_balanced?dl=0",
"by serializing files and applying decode function. def decode(serialized_example): \"\"\"Decode",
"int(n_sample * test_frac) train_ind = [] test_ind = [] for",
"the 100 class subset of audioset used in this study.",
"We also exclude some samples that don't have data for",
"with the highest number of samples n_sample_cutoff = np.sort(num_samples)[-n_classes] class_idx",
"of valid samples valid_idx = np.setdiff1d(single_label_idx,too_short) # Restructure data and",
"= [] for i in range(len(y)): y_fil.append( np.intersect1d(y[i],our_classes)) # Find",
"all available data and then filter and structure them according",
"was created for one time usage and has to be",
"is available at https://www.dropbox.com/s/07dfeeuf5aq4w1h/audioset_data_balanced?dl=0 If you want to recreate or",
"'reusing it. All paths specified here are absolute.') # Tensorflow",
"class name n = '' for t in tokens: if",
"(the \"License\"); # you may not use this file except",
"'restricted' : j['restrictions'] != [], 'has_child' : j['child_ids'] != [],",
"specified here are absolute.') # Tensorflow eager mode needs to",
"[], 'conf' : conf_data[j['name']], 'id' : csv_data[j['name']] } all_data.append(class_info) #",
"y_fil.append( np.intersect1d(y[i],classes)) # Find samples with one label n_labels =",
"data_dir = '../../datasets/sequential/audioset/' download_dir = os.path.join(data_dir,'audioset_download') fpath_conf_data = os.path.join(data_dir, 'confidence_data.csv')",
"# you may not use this file except in compliance",
"a single list. all_data = [] for j in json_data:",
"np.random.shuffle(rand_idx) train_ind.extend(sample_idx[rand_idx[0:n_train]]) test_ind.extend(sample_idx[rand_idx[n_train:n_sample]]) train_ind = np.asarray(train_ind) test_ind = np.asarray(test_ind) sub_sample_idx",
"highest number of samples n_sample_cutoff = np.sort(num_samples)[-n_classes] class_idx = np.where(np.asarray(num_samples)",
"= t else: n = n+' '+t else: break conf_data.update({n:c})",
"can have multiple labels, we only use samples which only",
"classes n_labels = np.asarray([len(y) for y in y_fil]) single_label_idx =",
"np.where(n_labels == 1)[0] # Find samples that dont are shorter",
"of samples: we only take classes that have more samples",
"samples than a certain threshold Samples: - since samples can",
"structure them according to our criteria. We use the same",
"samples are then split into train and test data and",
"c = int(t[:-1]) # parse class name n = ''",
"are shorter than 10 seconds (to be excluded) too_short =",
"samples valid_idx = np.setdiff1d(single_label_idx,too_short) # Restructure data and relabel the",
"of the potential classes n_labels = np.asarray([len(y) for y in",
"the data are preprocessed to fit our continual learning experiments.",
"in valid_idx]) num_samples = [len(np.where(y_single == i)[0]) for i in",
"= np.sort(num_samples)[-n_classes] class_idx = np.where(np.asarray(num_samples) >= n_sample_cutoff)[0] our_classes = [classes[i]",
"np.where(n_labels == 1)[0] # Find samples that are shorter than",
"tf.int64) return audio, label # Apply decode function to all",
"First discard labels that are not in the set of",
"# # Unless required by applicable law or agreed to",
"The result of this script is available at https://www.dropbox.com/s/07dfeeuf5aq4w1h/audioset_data_balanced?dl=0 If",
"using map function. # Take files from all three data",
"for j in json_data: if j['name'] in conf_data.keys(): class_info =",
"at https://www.dropbox.com/s/07dfeeuf5aq4w1h/audioset_data_balanced?dl=0 If you want to recreate or modify this",
"single_label_idx = np.where(n_labels == 1)[0] # Find samples that are",
"'': n = t else: n = n+' '+t else:",
"the set of valid samples valid_idx = np.setdiff1d(single_label_idx,too_short) # Restructure",
"this dataset, download the audioset data from https://research.google.com/audioset/download.html and extract",
"# title :data/timeseries/preprocess_audioset.py # author :be # contact :<EMAIL> #",
"seconds too_short = np.where(np.asarray([x.shape[0] for x in x]) != 10)[0]",
"between 0 and n_classes y_data = [y_fil[i][0] for i in",
"(1-test_frac)) n_test = int(n_sample * test_frac) train_ind = [] test_ind",
"} all_data.append(class_info) # Filter classes classes = [] for c",
"test_frac) train_ind = [] test_ind = [] for i in",
"obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0",
"extract the data and safe them as numpy arrays in",
"and n_classes y_data = [y_fil[i][0] for i in valid_idx] y_data",
"this script will create a pickle file containing the 100",
"Set paths and parameters data_dir = '../../datasets/sequential/audioset/' download_dir = os.path.join(data_dir,'audioset_download')",
"samples valid_idx = np.setdiff1d(single_label_idx,too_short) # Count number of valid samples",
"from label csv file l = -1 csv_data = {}",
"Version 2.0 (the \"License\"); # you may not use this",
"y.append(tf.sparse.to_dense(tf.sparse.reorder(d[1])).numpy()) ### Filter classes as described above. # Parse confidence",
"continue tokens = line.split('\"') n = tokens[1] csv_data.update({n:l}) l +=1",
"10 timesteps and 128 features - **label** (numpy.ndarray): Array of",
"data into a single list. all_data = [] for j",
"i in valid_idx] y_data = [np.where(np.asarray(our_classes) == i)[0][0] for i",
"= [np.where(np.asarray(our_classes) == i)[0][0] for i in y_data] y_data =",
"in os.walk(download_dir): for name in files: if 'tfrecord' in name:",
"the tar.gz into the following folder: ``datasets/sequential/audioset/audioset_download``. Subsequently executing this",
"np.asarray(y_data) x_data = [x[i] for i in valid_idx] x_data =",
"according to our criteria. We use the same criteria as",
"- number of samples: we only take classes that have",
"= 1000 test_frac = 0.20 ### Load data by serializing",
"tf.FixedLenSequenceFeature([], tf.string), } context_features = { 'start_time_seconds': tf.FixedLenFeature([], tf.float32), 'labels':",
"n = tokens[1] csv_data.update({n:l}) l +=1 # Parse ontology info",
"valid_idx = np.setdiff1d(single_label_idx,too_short) # Count number of valid samples for",
"# parse confidence c = 0 for t in tokens:",
"i in range(len(y)): y_fil.append( np.intersect1d(y[i],our_classes)) # Find samples that belong",
"# python_version :3.7 \"\"\" Script to structure the audioset dataset,",
"and decode dataset = tf.data.TFRecordDataset(fpaths) dataset = dataset.map(decode) # Extract",
"belong to only one of the potential classes n_labels =",
"in f: tokens = line.split() # parse confidence c =",
"implied. # See the License for the specific language governing",
"100 n_sample = 1000 test_frac = 0.20 ### Load data",
"l == -1: l += 1 continue tokens = line.split('\"')",
"than 10 seconds too_short = np.where(np.asarray([x.shape[0] for x in x])",
"for i in range(n_classes): sample_idx = np.where(y_data == i)[0] n_sample_class",
"that are not in the set of potential classes y_fil",
"10)[0] # Construct the set of valid samples valid_idx =",
"under the Apache License, Version 2.0 (the \"License\"); # you",
"os.path.join(data_dir,'audioset_download') fpath_conf_data = os.path.join(data_dir, 'confidence_data.csv') fpath_label_inds = os.path.join(data_dir, 'class_labels_indices.csv') fpath_ontology",
"three data sets since we repartition anyway. fpaths = []",
"= n+' '+t else: break conf_data.update({n:c}) # Parse class numbers",
"np.setdiff1d(single_label_idx,too_short) # Count number of valid samples for potential classes",
"info from json file with open(fpath_ontology, 'r') as f: json_data",
"= [len(np.where(y_single == i)[0]) for i in classes] # Take",
"classes y_single = np.asarray([y_fil[i][0] for i in valid_idx]) num_samples =",
"json file with open(fpath_ontology, 'r') as f: json_data = json.load(f)",
"samples that are shorter than 10 seconds (to be excluded)",
"i in y_data] y_data = np.asarray(y_data) x_data = [x[i] for",
"y_fil]) single_label_idx = np.where(n_labels == 1)[0] # Find samples that",
"ontology.json) - no parent / child relationship (parsed from ontology.json)",
"{} with open(fpath_conf_data) as f: for line in f: tokens",
"and applying decode function. def decode(serialized_example): \"\"\"Decode data from TFRecord",
"y_data = [np.where(np.asarray(our_classes) == i)[0][0] for i in y_data] y_data",
"way: Classes: - no restriction according to ontology file (parsed",
"= [y_fil[i][0] for i in valid_idx] y_data = [np.where(np.asarray(our_classes) ==",
"belong to one of the classes we use - we",
"restrict the number of samples per class np.random.seed(42) n_train =",
"# version :1.0 # python_version :3.7 \"\"\" Script to structure",
"parse class name n = '' for t in tokens:",
"relabel the classes to be between 0 and n_classes y_data",
"by applicable law or agreed to in writing, software #",
"ontology.json) - confidence level > 70% (data was copied from",
"data from https://research.google.com/audioset/download.html and extract the tar.gz into the following",
"'audio_embedding': tf.FixedLenSequenceFeature([], tf.string), } context_features = { 'start_time_seconds': tf.FixedLenFeature([], tf.float32),",
"utility to read tensorflow files, we extract the data and",
"a pickle file containing the 100 class subset of audioset",
"the following way: Classes: - no restriction according to ontology",
"we exclude samples that don't have the full length of",
"= { 'start_time_seconds': tf.FixedLenFeature([], tf.float32), 'labels': tf.VarLenFeature(dtype=tf.int64), } context_parsed, sequence_parsed",
"audio = tf.decode_raw(sequence_parsed['audio_embedding'], tf.uint8) label = tf.cast(context_parsed['labels'], tf.int64) return audio,",
"label = tf.cast(context_parsed['labels'], tf.int64) return audio, label # Apply decode",
"= tf.cast(context_parsed['labels'], tf.int64) return audio, label # Apply decode function",
"if n == '': n = t else: n =",
"of potential classes y_fil = [] for i in range(len(y)):",
"for i in range(len(y)): y_fil.append( np.intersect1d(y[i],classes)) # Find samples with",
"class_idx] ### Filter the data again according the the chosen",
"then filter and structure them according to our criteria. We",
"you want to recreate or modify this dataset, download the",
"classes as described above. # Parse confidence values conf_data =",
"sub_sample_idx = np.hstack((train_ind,test_ind)) x_data_sub = x_data[sub_sample_idx,:,:] y_data_sub = y_data[sub_sample_idx] train_ind",
"files from all three data sets since we repartition anyway.",
"to only one of the potential classes. # We also",
"len(sample_idx) rand_idx = np.arange(n_sample_class) np.random.shuffle(rand_idx) train_ind.extend(sample_idx[rand_idx[0:n_train]]) test_ind.extend(sample_idx[rand_idx[n_train:n_sample]]) train_ind = np.asarray(train_ind)",
"timesteps and 128 features - **label** (numpy.ndarray): Array of shape",
"= [] for d in dataset: x.append(d[0].numpy()) y.append(tf.sparse.to_dense(tf.sparse.reorder(d[1])).numpy()) ### Filter",
"tensorflow files. Since we work with pytorch and there is",
"compositions of samples and classes. Since we only work with",
"shape (10,128) representing one sample with 10 timesteps and 128",
"= os.path.join(data_dir, 'audioset_data_balanced.pickle') n_classes = 100 n_sample = 1000 test_frac",
"np.setdiff1d(single_label_idx,too_short) # Restructure data and relabel the classes to be",
"subdirs, files in os.walk(download_dir): for name in files: if 'tfrecord'",
"it. All paths specified here are absolute.') # Tensorflow eager",
"target_path = os.path.join(data_dir, 'audioset_data_balanced.pickle') n_classes = 100 n_sample = 1000",
"tokens[1] csv_data.update({n:l}) l +=1 # Parse ontology info from json",
"-1: l += 1 continue tokens = line.split('\"') n =",
"tokens: if t.find('%') is not -1: c = int(t[:-1]) #",
"fpath_ontology = os.path.join(data_dir, 'ontology.json') target_path = os.path.join(data_dir, 'audioset_data_balanced.pickle') n_classes =",
"create a pickle file containing the 100 class subset of",
"y = [] for d in dataset: x.append(d[0].numpy()) y.append(tf.sparse.to_dense(tf.sparse.reorder(d[1])).numpy()) ###",
"line in f: tokens = line.split() # parse confidence c",
"classes] # Take the n classes with the highest number",
"test_ind.extend(sample_idx[rand_idx[n_train:n_sample]]) train_ind = np.asarray(train_ind) test_ind = np.asarray(test_ind) sub_sample_idx = np.hstack((train_ind,test_ind))",
"y_fil = [] for i in range(len(y)): y_fil.append( np.intersect1d(y[i],classes)) #",
"from website into txt file) - number of samples: we",
"/ child relationship (parsed from ontology.json) - confidence level >",
"t else: n = n+' '+t else: break conf_data.update({n:c}) #",
"= os.path.join(data_dir,'audioset_download') fpath_conf_data = os.path.join(data_dir, 'confidence_data.csv') fpath_label_inds = os.path.join(data_dir, 'class_labels_indices.csv')",
"int(n_sample * (1-test_frac)) n_test = int(n_sample * test_frac) train_ind =",
"= np.asarray(test_ind) sub_sample_idx = np.hstack((train_ind,test_ind)) x_data_sub = x_data[sub_sample_idx,:,:] y_data_sub =",
"into a single list. all_data = [] for j in",
"c in all_data: if not c['restricted'] and not c['has_child'] and",
"= [] for i in range(n_classes): sample_idx = np.where(y_data ==",
"a subset of classes and samples, we load all available",
"tensorflow files, we extract the data and safe them as",
"> 70% (data was copied from website into txt file)",
"- **label** (numpy.ndarray): Array of shape (1,) containing the class",
"in valid_idx] x_data = np.stack(x_data) ### Split into test and",
"name n = '' for t in tokens: if t.find('%')",
"n classes with the highest number of samples n_sample_cutoff =",
"os import json from warnings import warn warn('The script was",
"<filename>hypnettorch/data/timeseries/preprocess_audioset.py #!/usr/bin/env python3 # Copyright 2020 <NAME> # # Licensed",
"all three data sets since we repartition anyway. fpaths =",
"== -1 and t != '-': if n == '':",
"that belong to only one of the potential classes n_labels",
"l = -1 csv_data = {} with open(fpath_label_inds) as f:",
"csv_data[j['name']] } all_data.append(class_info) # Filter classes classes = [] for",
"train and restrict the number of samples per class np.random.seed(42)",
"label n_labels = np.asarray([len(y) for y in y_fil]) single_label_idx =",
"Construct the set of valid samples valid_idx = np.setdiff1d(single_label_idx,too_short) #",
"and classes. Since we only work with a subset of",
"an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF",
"full length of 10 seconds The chosen classes and samples",
"enabled for dataset mapping to work! tf.enable_eager_execution() # Set paths",
"the data and safe them as numpy arrays in a",
"classes that have more samples than a certain threshold Samples:",
"tf.FixedLenFeature([], tf.float32), 'labels': tf.VarLenFeature(dtype=tf.int64), } context_parsed, sequence_parsed = tf.parse_single_sequence_example( serialized_example,",
"Unless required by applicable law or agreed to in writing,",
"can then be used via :class:`data.timeseries.audioset_data.AudiosetData`. The result of this",
"paths and parameters data_dir = '../../datasets/sequential/audioset/' download_dir = os.path.join(data_dir,'audioset_download') fpath_conf_data",
"'has_child' : j['child_ids'] != [], 'conf' : conf_data[j['name']], 'id' :",
"- since samples can have multiple labels, we only use",
"= tf.data.TFRecordDataset(fpaths) dataset = dataset.map(decode) # Extract data to lists",
"criteria as Kemker et al. Classes and samples are restricted",
"and extract the tar.gz into the following folder: ``datasets/sequential/audioset/audioset_download``. Subsequently",
"samples that belong to only one of the potential classes.",
"import json from warnings import warn warn('The script was created",
"{ 'name' : j['name'], 'restricted' : j['restrictions'] != [], 'has_child'",
"sample with 10 timesteps and 128 features - **label** (numpy.ndarray):",
"= int(n_sample * test_frac) train_ind = [] test_ind = []",
"# Filter classes classes = [] for c in all_data:",
"files. Args: serialized_example: serialized_example as created by tf.data.TFRecordDataset Returns: (tuple):",
"Apply decode function to all dataset entries using map function.",
"modify this dataset, download the audioset data from https://research.google.com/audioset/download.html and",
"'id' : csv_data[j['name']] } all_data.append(class_info) # Filter classes classes =",
"number of valid samples for potential classes y_single = np.asarray([y_fil[i][0]",
"dataset provides three subsets with different compositions of samples and",
"the specific language governing permissions and # limitations under the",
"work! tf.enable_eager_execution() # Set paths and parameters data_dir = '../../datasets/sequential/audioset/'",
"as created by tf.data.TFRecordDataset Returns: (tuple): Tuple containing: - **audio**",
"- no parent / child relationship (parsed from ontology.json) -",
"= np.asarray([y_fil[i][0] for i in valid_idx]) num_samples = [len(np.where(y_single ==",
"classes to be between 0 and n_classes y_data = [y_fil[i][0]",
"(to be excluded) too_short = np.where(np.asarray([x.shape[0] for x in x])",
"and safe them as numpy arrays in a pickle file.",
"applicable law or agreed to in writing, software # distributed",
"for one time usage and has to be adapted when",
"i in range(len(y)): y_fil.append( np.intersect1d(y[i],classes)) # Find samples with one",
"valid samples for potential classes y_single = np.asarray([y_fil[i][0] for i",
"serialized_example, sequence_features=sequence_features, context_features=context_features ) audio = tf.decode_raw(sequence_parsed['audio_embedding'], tf.uint8) label =",
"following way: Classes: - no restriction according to ontology file",
"criteria. We use the same criteria as Kemker et al.",
"described above. # Parse confidence values conf_data = {} with",
"has to be adapted when ' + 'reusing it. All",
"to lists x = [] y = [] for d",
"Filter classes as described above. # Parse confidence values conf_data",
"relationship (parsed from ontology.json) - confidence level > 70% (data",
"classes classes = [] for c in all_data: if not",
"not c['has_child'] and c['conf'] >= 70: classes.append(c['id']) ### Filter the",
"= [] for j in json_data: if j['name'] in conf_data.keys():",
"in writing, software # distributed under the License is distributed",
"governing permissions and # limitations under the License. # #",
"10 seconds. # First discard labels that are not in",
"i in classes] # Take the n classes with the",
"label csv file l = -1 csv_data = {} with",
"with open(fpath_ontology, 'r') as f: json_data = json.load(f) # Put",
"to read tensorflow files, we extract the data and safe",
"only take classes that have more samples than a certain",
"import os import json from warnings import warn warn('The script",
"Take files from all three data sets since we repartition",
"no restriction according to ontology file (parsed from ontology.json) -",
"conf_data.update({n:c}) # Parse class numbers from label csv file l",
"audioset dataset, which can then be used via :class:`data.timeseries.audioset_data.AudiosetData`. The",
"as numpy arrays in a pickle file. Furthermore the data",
"# limitations under the License. # # title :data/timeseries/preprocess_audioset.py #",
"with 10 timesteps and 128 features - **label** (numpy.ndarray): Array",
"https://research.google.com/audioset/download.html and extract the tar.gz into the following folder: ``datasets/sequential/audioset/audioset_download``.",
"= np.where(np.asarray([x.shape[0] for x in x]) != 10)[0] # Construct",
"the number of samples per class np.random.seed(42) n_train = int(n_sample",
"audio, label # Apply decode function to all dataset entries",
"script will create a pickle file containing the 100 class",
"# created :31/03/2020 # version :1.0 # python_version :3.7 \"\"\"",
"audioset used in this study. The dataset is stored in",
"is stored in tensorflow files. Since we work with pytorch",
"from ontology.json) - no parent / child relationship (parsed from",
"y_data] y_data = np.asarray(y_data) x_data = [x[i] for i in",
"context_parsed, sequence_parsed = tf.parse_single_sequence_example( serialized_example, sequence_features=sequence_features, context_features=context_features ) audio =",
"### Split into test and train and restrict the number",
"x.append(d[0].numpy()) y.append(tf.sparse.to_dense(tf.sparse.reorder(d[1])).numpy()) ### Filter classes as described above. # Parse",
"i in valid_idx] x_data = np.stack(x_data) ### Split into test",
"created by tf.data.TFRecordDataset Returns: (tuple): Tuple containing: - **audio** (numpy.ndarray):",
": conf_data[j['name']], 'id' : csv_data[j['name']] } all_data.append(class_info) # Filter classes",
"np.asarray([y_fil[i][0] for i in valid_idx]) num_samples = [len(np.where(y_single == i)[0])",
"name)) # Create dataset and decode dataset = tf.data.TFRecordDataset(fpaths) dataset",
"continual learning experiments. The original dataset provides three subsets with",
"np.where(y_data == i)[0] n_sample_class = len(sample_idx) rand_idx = np.arange(n_sample_class) np.random.shuffle(rand_idx)",
"only work with a subset of classes and samples, we",
"into the following folder: ``datasets/sequential/audioset/audioset_download``. Subsequently executing this script will",
"seconds (to be excluded) too_short = np.where(np.asarray([x.shape[0] for x in",
"tf.uint8) label = tf.cast(context_parsed['labels'], tf.int64) return audio, label # Apply",
"License is distributed on an \"AS IS\" BASIS, # WITHOUT",
"number of samples n_sample_cutoff = np.sort(num_samples)[-n_classes] class_idx = np.where(np.asarray(num_samples) >=",
"entries using map function. # Take files from all three",
"# # title :data/timeseries/preprocess_audioset.py # author :be # contact :<EMAIL>",
"License, Version 2.0 (the \"License\"); # you may not use",
"to only one of the potential classes n_labels = np.asarray([len(y)",
"samples per class np.random.seed(42) n_train = int(n_sample * (1-test_frac)) n_test",
"x_data[sub_sample_idx,:,:] y_data_sub = y_data[sub_sample_idx] train_ind = np.arange(0,len(train_ind)) test_ind = np.arange(len(train_ind),len(train_ind)+len(test_ind))",
"# You may obtain a copy of the License at",
"fpaths.append(os.path.join(path, name)) # Create dataset and decode dataset = tf.data.TFRecordDataset(fpaths)",
"values conf_data = {} with open(fpath_conf_data) as f: for line",
"are shorter than 10 seconds too_short = np.where(np.asarray([x.shape[0] for x",
"Returns: (tuple): Tuple containing: - **audio** (numpy.ndarray): Array of shape",
"csv_data.update({n:l}) l +=1 # Parse ontology info from json file",
"{} with open(fpath_label_inds) as f: for line in f: if",
"Save data with open(target_path, 'wb') as f: pickle.dump([x_data_sub, y_data_sub, train_ind,",
"not c['restricted'] and not c['has_child'] and c['conf'] >= 70: classes.append(c['id'])",
"train_ind = [] test_ind = [] for i in range(n_classes):",
"copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # #",
"file with open(fpath_ontology, 'r') as f: json_data = json.load(f) #",
"70: classes.append(c['id']) ### Filter the samples. # Find samples that",
"also exclude some samples that don't have data for the",
"the n classes with the highest number of samples n_sample_cutoff",
"of samples n_sample_cutoff = np.sort(num_samples)[-n_classes] class_idx = np.where(np.asarray(num_samples) >= n_sample_cutoff)[0]",
"different compositions of samples and classes. Since we only work",
"of audioset used in this study. The dataset is stored",
"use samples which only belong to one of the classes",
"exclude samples that don't have the full length of 10",
"sequence_parsed = tf.parse_single_sequence_example( serialized_example, sequence_features=sequence_features, context_features=context_features ) audio = tf.decode_raw(sequence_parsed['audio_embedding'],",
"n = t else: n = n+' '+t else: break",
"+=1 # Parse ontology info from json file with open(fpath_ontology,",
"that dont are shorter than 10 seconds too_short = np.where(np.asarray([x.shape[0]",
"pytorch and there is no utility to read tensorflow files,",
"structure the audioset dataset, which can then be used via",
"don't have the full length of 10 seconds The chosen",
"for the full 10 seconds. # First discard labels that",
"data again according the the chosen classes y_fil = []",
"have multiple labels, we only use samples which only belong",
"= 100 n_sample = 1000 test_frac = 0.20 ### Load",
"the License for the specific language governing permissions and #",
"Apache License, Version 2.0 (the \"License\"); # you may not",
"# First discard labels that are not in the set",
"1)[0] # Find samples that dont are shorter than 10",
"} context_parsed, sequence_parsed = tf.parse_single_sequence_example( serialized_example, sequence_features=sequence_features, context_features=context_features ) audio",
"either express or implied. # See the License for the",
"the samples. # Find samples that belong to only one",
"files in os.walk(download_dir): for name in files: if 'tfrecord' in",
"we only work with a subset of classes and samples,",
"Parse confidence values conf_data = {} with open(fpath_conf_data) as f:",
"lists x = [] y = [] for d in",
"= {} with open(fpath_conf_data) as f: for line in f:",
"# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or",
"file l = -1 csv_data = {} with open(fpath_label_inds) as",
"n_sample = 1000 test_frac = 0.20 ### Load data by",
"one label n_labels = np.asarray([len(y) for y in y_fil]) single_label_idx",
"function. # Take files from all three data sets since",
"x]) != 10)[0] # Construct the set of valid samples",
"the potential classes n_labels = np.asarray([len(y) for y in y_fil])",
"= np.asarray(y_data) x_data = [x[i] for i in valid_idx] x_data",
"128 features - **label** (numpy.ndarray): Array of shape (1,) containing",
"numpy arrays in a pickle file. Furthermore the data are",
"file containing the 100 class subset of audioset used in",
"list. all_data = [] for j in json_data: if j['name']",
"our continual learning experiments. The original dataset provides three subsets",
"fpath_label_inds = os.path.join(data_dir, 'class_labels_indices.csv') fpath_ontology = os.path.join(data_dir, 'ontology.json') target_path =",
"[y_fil[i][0] for i in valid_idx] y_data = [np.where(np.asarray(our_classes) == i)[0][0]",
"than a certain threshold Samples: - since samples can have",
"0 for t in tokens: if t.find('%') is not -1:",
"the highest number of samples n_sample_cutoff = np.sort(num_samples)[-n_classes] class_idx =",
"range(n_classes): sample_idx = np.where(y_data == i)[0] n_sample_class = len(sample_idx) rand_idx",
"y_data[sub_sample_idx] train_ind = np.arange(0,len(train_ind)) test_ind = np.arange(len(train_ind),len(train_ind)+len(test_ind)) ### Save data",
"with open(fpath_conf_data) as f: for line in f: tokens =",
"y_single = np.asarray([y_fil[i][0] for i in valid_idx]) num_samples = [len(np.where(y_single",
"all_data.append(class_info) # Filter classes classes = [] for c in",
"# Parse class numbers from label csv file l =",
"= len(sample_idx) rand_idx = np.arange(n_sample_class) np.random.shuffle(rand_idx) train_ind.extend(sample_idx[rand_idx[0:n_train]]) test_ind.extend(sample_idx[rand_idx[n_train:n_sample]]) train_ind =",
"one time usage and has to be adapted when '",
"samples are restricted in the following way: Classes: - no",
"-1 csv_data = {} with open(fpath_label_inds) as f: for line",
"= np.setdiff1d(single_label_idx,too_short) # Count number of valid samples for potential",
"= np.where(y_data == i)[0] n_sample_class = len(sample_idx) rand_idx = np.arange(n_sample_class)",
"l +=1 # Parse ontology info from json file with",
":be # contact :<EMAIL> # created :31/03/2020 # version :1.0",
"containing: - **audio** (numpy.ndarray): Array of shape (10,128) representing one",
"a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 #",
"want to recreate or modify this dataset, download the audioset",
"n = '' for t in tokens: if t.find('%') ==",
"usage and has to be adapted when ' + 'reusing",
"for i in class_idx] ### Filter the data again according",
"= 0.20 ### Load data by serializing files and applying",
"copied from website into txt file) - number of samples:",
"import numpy as np import pickle import tensorflow as tf",
"into txt file) - number of samples: we only take",
"l += 1 continue tokens = line.split('\"') n = tokens[1]",
"preprocessed to fit our continual learning experiments. The original dataset",
"files, we extract the data and safe them as numpy",
"- we exclude samples that don't have the full length",
"t != '-': if n == '': n = t",
"for i in valid_idx]) num_samples = [len(np.where(y_single == i)[0]) for",
"set of valid samples valid_idx = np.setdiff1d(single_label_idx,too_short) # Restructure data",
"n_sample_class = len(sample_idx) rand_idx = np.arange(n_sample_class) np.random.shuffle(rand_idx) train_ind.extend(sample_idx[rand_idx[0:n_train]]) test_ind.extend(sample_idx[rand_idx[n_train:n_sample]]) train_ind",
"rand_idx = np.arange(n_sample_class) np.random.shuffle(rand_idx) train_ind.extend(sample_idx[rand_idx[0:n_train]]) test_ind.extend(sample_idx[rand_idx[n_train:n_sample]]) train_ind = np.asarray(train_ind) test_ind",
"arrays in a pickle file. Furthermore the data are preprocessed",
"are then split into train and test data and saved",
"\"License\"); # you may not use this file except in",
"folder: ``datasets/sequential/audioset/audioset_download``. Subsequently executing this script will create a pickle",
"n+' '+t else: break conf_data.update({n:c}) # Parse class numbers from",
"np.hstack((train_ind,test_ind)) x_data_sub = x_data[sub_sample_idx,:,:] y_data_sub = y_data[sub_sample_idx] train_ind = np.arange(0,len(train_ind))",
"above. # Parse confidence values conf_data = {} with open(fpath_conf_data)",
"= { 'audio_embedding': tf.FixedLenSequenceFeature([], tf.string), } context_features = { 'start_time_seconds':",
"2020 <NAME> # # Licensed under the Apache License, Version",
"distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR",
"' + 'reusing it. All paths specified here are absolute.')",
"for t in tokens: if t.find('%') is not -1: c",
"if t.find('%') is not -1: c = int(t[:-1]) # parse",
"the classes to be between 0 and n_classes y_data =",
"or modify this dataset, download the audioset data from https://research.google.com/audioset/download.html",
"read tensorflow files, we extract the data and safe them",
"function. def decode(serialized_example): \"\"\"Decode data from TFRecord files. Args: serialized_example:",
"(numpy.ndarray): Array of shape (10,128) representing one sample with 10",
"corresponding sample \"\"\" sequence_features = { 'audio_embedding': tf.FixedLenSequenceFeature([], tf.string), }",
"# Apply decode function to all dataset entries using map",
"10 seconds too_short = np.where(np.asarray([x.shape[0] for x in x]) !=",
"### Save data with open(target_path, 'wb') as f: pickle.dump([x_data_sub, y_data_sub,",
"# distributed under the License is distributed on an \"AS",
"absolute.') # Tensorflow eager mode needs to be enabled for",
"class subset of audioset used in this study. The dataset",
"samples n_sample_cutoff = np.sort(num_samples)[-n_classes] class_idx = np.where(np.asarray(num_samples) >= n_sample_cutoff)[0] our_classes",
"# Set paths and parameters data_dir = '../../datasets/sequential/audioset/' download_dir =",
"# Unless required by applicable law or agreed to in",
"extract the tar.gz into the following folder: ``datasets/sequential/audioset/audioset_download``. Subsequently executing",
"TFRecord files. Args: serialized_example: serialized_example as created by tf.data.TFRecordDataset Returns:",
"Tuple containing: - **audio** (numpy.ndarray): Array of shape (10,128) representing",
"y_fil.append( np.intersect1d(y[i],our_classes)) # Find samples that belong to only one",
"to be between 0 and n_classes y_data = [y_fil[i][0] for",
"test and train and restrict the number of samples per",
"line.split() # parse confidence c = 0 for t in",
"tf.float32), 'labels': tf.VarLenFeature(dtype=tf.int64), } context_parsed, sequence_parsed = tf.parse_single_sequence_example( serialized_example, sequence_features=sequence_features,",
"'confidence_data.csv') fpath_label_inds = os.path.join(data_dir, 'class_labels_indices.csv') fpath_ontology = os.path.join(data_dir, 'ontology.json') target_path",
"used in this study. The dataset is stored in tensorflow",
"\"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY",
"result of this script is available at https://www.dropbox.com/s/07dfeeuf5aq4w1h/audioset_data_balanced?dl=0 If you",
"num_samples = [len(np.where(y_single == i)[0]) for i in classes] #",
"Parse class numbers from label csv file l = -1",
"# Find samples that belong to only one of the",
"- **audio** (numpy.ndarray): Array of shape (10,128) representing one sample",
"child relationship (parsed from ontology.json) - confidence level > 70%",
"c = 0 for t in tokens: if t.find('%') is",
"limitations under the License. # # title :data/timeseries/preprocess_audioset.py # author",
"data by serializing files and applying decode function. def decode(serialized_example):",
"only use samples which only belong to one of the",
"level > 70% (data was copied from website into txt",
"!= [], 'conf' : conf_data[j['name']], 'id' : csv_data[j['name']] } all_data.append(class_info)",
"You may obtain a copy of the License at #",
"the same criteria as Kemker et al. Classes and samples",
"three subsets with different compositions of samples and classes. Since",
"'' for t in tokens: if t.find('%') == -1 and",
"in conf_data.keys(): class_info = { 'name' : j['name'], 'restricted' :",
"np.stack(x_data) ### Split into test and train and restrict the",
": j['child_ids'] != [], 'conf' : conf_data[j['name']], 'id' : csv_data[j['name']]",
":<EMAIL> # created :31/03/2020 # version :1.0 # python_version :3.7",
"1000 test_frac = 0.20 ### Load data by serializing files",
"else: break conf_data.update({n:c}) # Parse class numbers from label csv",
"single list. all_data = [] for j in json_data: if",
"and 128 features - **label** (numpy.ndarray): Array of shape (1,)",
"txt file) - number of samples: we only take classes",
"file) - number of samples: we only take classes that",
"then be used via :class:`data.timeseries.audioset_data.AudiosetData`. The result of this script",
"(1,) containing the class of the corresponding sample \"\"\" sequence_features",
"f: json_data = json.load(f) # Put all data into a",
"the corresponding sample \"\"\" sequence_features = { 'audio_embedding': tf.FixedLenSequenceFeature([], tf.string),",
"in y_data] y_data = np.asarray(y_data) x_data = [x[i] for i",
"= np.arange(0,len(train_ind)) test_ind = np.arange(len(train_ind),len(train_ind)+len(test_ind)) ### Save data with open(target_path,",
"there is no utility to read tensorflow files, we extract",
"= np.setdiff1d(single_label_idx,too_short) # Restructure data and relabel the classes to",
"are not in the set of potential classes y_fil =",
"be between 0 and n_classes y_data = [y_fil[i][0] for i",
"the Apache License, Version 2.0 (the \"License\"); # you may",
"= [] y = [] for d in dataset: x.append(d[0].numpy())",
"in tokens: if t.find('%') is not -1: c = int(t[:-1])",
"os.path.join(data_dir, 'ontology.json') target_path = os.path.join(data_dir, 'audioset_data_balanced.pickle') n_classes = 100 n_sample",
"np.arange(0,len(train_ind)) test_ind = np.arange(len(train_ind),len(train_ind)+len(test_ind)) ### Save data with open(target_path, 'wb')",
"import pickle import tensorflow as tf import os import json",
"tokens = line.split() # parse confidence c = 0 for",
"n_train = int(n_sample * (1-test_frac)) n_test = int(n_sample * test_frac)",
"# parse class name n = '' for t in",
"class np.random.seed(42) n_train = int(n_sample * (1-test_frac)) n_test = int(n_sample",
"and restrict the number of samples per class np.random.seed(42) n_train",
"for potential classes y_single = np.asarray([y_fil[i][0] for i in valid_idx])"
] |
[
"'POST': try: code = status.HTTP_200_OK post = Post.objects.get(post_pk=post_pk) if 'title'",
"paginator.get_page(page_number) serializer = PostSerializer(page_obj.object_list, many=True) return Response(serializer.data, code) @api_view(['GET', 'POST',",
"comment.save() serializer = CommentSerializer(comment) except Exception as e: print(e) code",
"request.method == 'POST': if add_Comment(request, post_pk=request.data['Post_pk'], auth_pk=request.data['auth_pk']): code = status.HTTP_202_ACCEPTED",
"paginator = Paginator(posts, page_size) page_obj = paginator.get_page(page_number) data = PostSerializer(page_obj.object_list,",
"paginator = Paginator(comment, page_size) page_obj = paginator.get_page(page_number) serializer = CommentSerializer(page_obj.object_list,",
"request.method == 'POST': try: code = status.HTTP_200_OK post = Post.objects.get(post_pk=post_pk)",
"'size' in request.GET: page_size = request.GET.get('size') else: page_size = 5",
"if post.contentType == \"application/app\": post.content = request.FILES['file'].read() #Inputfile elif post.contentType",
"'POST': try: code = status.HTTP_200_OK comment = Comments.objects.get(pk=comment_pk) if 'contentType'",
"status.HTTP_400_BAD_REQUEST else: code = status.HTTP_200_OK posts = Post.objects.filter(id__icontains = \"linkedspace\")",
"elif contentType in [\"image/png\", \"image/jpeg\",]: content = base64.b64encode(request.FILES['file'].read()) #Inputfile else:",
"else: print(request.data) print(form.errors) print(form.data) return False def add_Comment(request, post_pk, auth_pk,",
"post.content = request.FILES['file'].read() #Inputfile elif post.contentType in [\"image/png\", \"image/jpeg\",]: post.content",
"import django.core from permissions import CustomAuthentication, AccessPermission from django.core.paginator import",
"[\"image/png\", \"image/jpeg\",]: post.content = base64.b64encode(request.FILES['file'].read()) #Inputfile else: post.content = request.data[\"text\"]",
"auth=('socialdistribution_t03','c404t03')) if team3.status_code == 200: data.append(team3.json()) team15 = get('https://unhindled.herokuapp.com/service/allposts/', auth=('connectionsuperuser','404connection'))",
"= Author.objects.get(pk = auth_pk) likeObjs = Like.objects.filter(~Q(auth_pk = author), object",
"updateForeignAuthors() published = timezone.now() contentType = form.cleaned_data['contentType'] if contentType ==",
"timezone.now() posts = Post(pk=uid, id=id, author_id=author_id, author=author, title=title, source=source, origin=origin,",
"@authentication_classes([CustomAuthentication]) @permission_classes([AccessPermission]) def PostsList(request, auth_pk=None): page_number = request.GET.get('page') if 'size'",
"\"items\": likes } return Response(response_dict) @api_view(['GET', 'POST',]) @authentication_classes([CustomAuthentication]) @permission_classes([AccessPermission]) def",
"page_size) page_obj = paginator.get_page(page_number) serializer = PostSerializer(page_obj.object_list, many=True) return Response(serializer.data,",
"Exception as e: print(e) code = status.HTTP_400_BAD_REQUEST comment = Comments.objects.all()",
"= {} return Response(data, code) @api_view(['GET', 'POST', 'PUT', 'DELETE', ])",
"page_size) page_obj = paginator.get_page(page_number) data = PostSerializer(page_obj.object_list, many=True).data except Exception",
"import Like from Author.views import updateForeignAuthors, GetForeignAuthors from .models import",
"title=title, source=source, origin=origin, description=descirption, contentType=contentType, count=0, size=10, categories=categories,visibility=visibility, unlisted=unlisted, published=published,",
"id = author_id.url author = json.loads(serializers.serialize('json', Author.objects.filter(pk=auth_pk), fields=('type', 'id', 'host',",
"= request.data['visibility'] if 'unlisted' in request.data.keys(): post.unlisted = request.data['unlisted'] if",
"author = Author.objects.get(pk = auth_pk) likeObjs = Like.objects.filter(~Q(auth_pk = author),",
"= l[key] like[\"@context\"] = l[\"context\"] like[\"author\"] = json.loads(django.core.serializers.serialize('json', Author.objects.filter(id=l[\"author\"]), fields=('type',",
".models import Post, Author from .form import PostForm from Posts.commentForm",
"code = status.HTTP_400_BAD_REQUEST comment = Comments.objects.all() paginator = Paginator(comment, page_size)",
"= status.HTTP_200_OK post = Post.objects.get(post_pk=post_pk) if 'title' in request.data.keys(): post.title",
"author_id = Author.objects.get(pk=auth_pk) id = author_id.url author = json.loads(serializers.serialize('json', Author.objects.filter(pk=auth_pk),",
"Paginator(comment, page_size) page_obj = paginator.get_page(page_number) serializer = CommentSerializer(page_obj.object_list, many=True) elif",
"page_obj = paginator.get_page(page_number) serializer = PostSerializer(page_obj.object_list, many=True) elif request.method ==",
"AccessPermission from django.core.paginator import Paginator import traceback def newPost(request, uid=None,",
"]) @authentication_classes([CustomAuthentication]) @permission_classes([AccessPermission]) def commentDetail(request, post_pk, comment_pk, auth_pk=None): page_number =",
"settings from django.core import serializers from django.utils import timezone import",
"form.is_valid(): title = form.cleaned_data['title'] descirption = form.cleaned_data['description'] categories = form.cleaned_data['categories'].split('",
"page_size = 5 if request.method == 'GET': comments = Comments.objects.filter(Post_pk_str=post_pk)",
"Q import django.core from permissions import CustomAuthentication, AccessPermission from django.core.paginator",
"Author.serializers import LikeSerializer from Author.models import Like from Author.views import",
"Post.objects.get(pk=post_pk) post_id = getattr(post, 'id') comment_id = getattr(post, 'comments') paginator",
"@permission_classes([AccessPermission]) def commentDetail(request, post_pk, comment_pk, auth_pk=None): page_number = request.GET.get('page') if",
"import LikeSerializer from Author.models import Like from Author.views import updateForeignAuthors,",
"'url', 'github',)))[0]['fields'] likes.append(like) response_dict = { \"type\": \"likes\", \"items\": likes",
"if 'text' in request.data.keys(): comment.content = request.data['text'] comment.save() serializer =",
"else: print(request.data) return False @api_view(['GET',]) @authentication_classes([CustomAuthentication]) @permission_classes([AccessPermission]) def PostLikesView(request, post_pk,",
"= Like.objects.filter(~Q(auth_pk = author), object = post.id) Likes = LikeSerializer(likeObjs,",
"{ \"type\": \"comments\", \"page\": page_number, \"size\": page_size, \"post\": post_id, \"id\":",
"= request.FILES['file'].read() #Inputfile elif post.contentType in [\"image/png\", \"image/jpeg\",]: post.content =",
"def newPost(request, uid=None, auth_pk=None): form = PostForm(request.POST, request.FILES) if form.is_valid():",
"page_size = 5 if request.method == 'GET': try: code =",
"+ \"/\" author_id = Author.objects.get(pk=auth_pk) id = author_id.url author =",
"= PostSerializer(page_obj.object_list, many=True) return Response(serializer.data, code) @api_view(['GET', 'POST', ]) @authentication_classes([CustomAuthentication])",
"= request.data['text'] comment.save() serializer = CommentSerializer(comment) except Exception as e:",
"auth_pk=request.data['auth_pk']): code = status.HTTP_201_CREATED post = Post.objects.latest(\"published\") data = PostSerializer(post).data",
"'POST',]) @authentication_classes([CustomAuthentication]) @permission_classes([AccessPermission]) def commentListView(request, post_pk, auth_pk=None): page_number = request.GET.get('page')",
"in request.data.keys(): post.categories = request.data['categories'].split(' ') if 'visibility' in request.data.keys():",
"page_number, \"size\": page_size, \"post\": post_id, \"id\": comment_id, \"comments\": serializer.data, }",
"\"/\" author_id = Author.objects.get(pk=auth_pk) id = author_id.url author = json.loads(serializers.serialize('json',",
"try: code = status.HTTP_200_OK post = Post.objects.get(post_pk=post_pk) serializer = PostSerializer(post)",
"auth=('connectionsuperuser','404connection')) if team15.status_code == 200: data.append(team15.json()) team17 = get('https://cmput404f21t17.herokuapp.com/service/connect/public/', auth=('4cbe2def-feaa-4bb7-bce5-<PASSWORD>','123456'))",
"= request.data['categories'].split(' ') if 'visibility' in request.data.keys(): post.visibility = request.data['visibility']",
"import Post, Author from .form import PostForm from Posts.commentForm import",
"auth_id=None): data = [] team3 = get('https://social-dis.herokuapp.com/posts', auth=('socialdistribution_t03','c404t03')) if team3.status_code",
"from rest_framework.decorators import api_view, authentication_classes, permission_classes from rest_framework.response import Response",
"False def add_Comment(request, post_pk, auth_pk, uid=None): form = CommentForm(request.POST, request.FILES)",
"import get from .serializers import CommentSerializer, PostSerializer from Author.serializers import",
"'github',)))[0]['fields'] likes.append(like) response_dict = { \"type\": \"likes\", \"items\": likes }",
"response_dict = { \"type\": \"comments\", \"page\": page_number, \"size\": page_size, \"post\":",
"= Post.objects.filter(id__icontains = \"linkedspace\") paginator = Paginator(posts, page_size) page_obj =",
"== 'POST': try: code = status.HTTP_200_OK comment = Comments.objects.get(pk=comment_pk) if",
"'visibility' in request.data.keys(): post.visibility = request.data['visibility'] if 'unlisted' in request.data.keys():",
"request.data.keys(): post.unlisted = request.data['unlisted'] if 'contentType' in request.data.keys(): post.contentType =",
"'description' in request.data.keys(): post.description = request.data['description'] if 'categories' in request.data.keys():",
"\"/\" origin = settings.SERVER_URL + \"/\" author_id = Author.objects.get(pk=auth_pk) id",
"re import base64 from django.db.models import Q import django.core from",
"in Likes.data: like = {} for key in l: if(key",
"try: code = status.HTTP_200_OK post = Post.objects.get(post_pk=post_pk) if 'title' in",
"'displayName', 'url', 'github',)))[0]['fields'] if uid == None: r_uid = uuid.uuid4().hex",
"None: r_uid = uuid.uuid4().hex uid = re.sub('-', '', r_uid) comment_id",
"== 200: data.append(team3.json()) team15 = get('https://unhindled.herokuapp.com/service/allposts/', auth=('connectionsuperuser','404connection')) if team15.status_code ==",
"request.GET.get('size') else: page_size = 5 if request.method == 'GET': comments",
"[] team3 = get('https://social-dis.herokuapp.com/posts', auth=('socialdistribution_t03','c404t03')) if team3.status_code == 200: data.append(team3.json())",
"in [\"image/png\", \"image/jpeg\",]: content = base64.b64encode(request.FILES['file'].read()) #Inputfile else: content =",
"'POST': if newPost(request, auth_pk=request.data['auth_pk']): code = status.HTTP_201_CREATED post = Post.objects.latest(\"published\")",
"') visibility = form.cleaned_data['visibility'] unlisted = form.cleaned_data['unlisted'] contentType = form.cleaned_data['contentType']",
"'host', 'url', 'github',)))[0]['fields'] likes.append(like) response_dict = { \"type\": \"likes\", \"items\":",
"= timezone.now() posts = Post(pk=uid, id=id, author_id=author_id, author=author, title=title, source=source,",
"read_only=True, many=True) likes = [] for l in Likes.data: like",
"= status.HTTP_200_OK posts = Post.objects.filter(id__icontains = \"linkedspace\") paginator = Paginator(posts,",
"many=True) return Response(serializer.data, code) @api_view(['GET', 'POST', ]) @authentication_classes([CustomAuthentication]) @permission_classes([AccessPermission]) def",
"status.HTTP_404_NOT_FOUND comment = Comments.objects.all() paginator = Paginator(comment, page_size) page_obj =",
"return True else: print(request.data) return False @api_view(['GET',]) @authentication_classes([CustomAuthentication]) @permission_classes([AccessPermission]) def",
"= { \"type\": \"comments\", \"page\": page_number, \"size\": page_size, \"post\": post_id,",
"post_id, \"id\": comment_id, \"comments\": serializer.data, } return Response(response_dict) elif request.method",
"uid + \"/\" comments_id = id + \"comments/\" published =",
"Likes = LikeSerializer(likeObjs, read_only=True, many=True) likes = [] for l",
"PostSerializer(page_obj.object_list, many=True) elif request.method == 'POST': try: code = status.HTTP_200_OK",
"auth_pk=request.data['auth_pk']): code = status.HTTP_202_ACCEPTED comment = Comments.objects.latest(\"published\") data = CommentSerializer(comment).data",
"json.loads(django.core.serializers.serialize('json', Author.objects.filter(id=l[\"author\"]), fields=('type', 'id', 'displayName', 'host', 'url', 'github',)))[0]['fields'] likes.append(like) response_dict",
"data.append(team3.json()) team15 = get('https://unhindled.herokuapp.com/service/allposts/', auth=('connectionsuperuser','404connection')) if team15.status_code == 200: data.append(team15.json())",
"page_obj = paginator.get_page(page_number) data = PostSerializer(page_obj.object_list, many=True).data except Exception as",
"@api_view(['GET', 'POST',]) @authentication_classes([CustomAuthentication]) @permission_classes([AccessPermission]) def PostsList(request, auth_pk=None): page_number = request.GET.get('page')",
"= PostSerializer(page_obj.object_list, many=True).data except Exception as e: print(e) data =",
"Author.views import updateForeignAuthors, GetForeignAuthors from .models import Post, Author from",
"e: print(e) data = {} code = status.HTTP_400_BAD_REQUEST else: code",
"paginator.get_page(page_number) serializer = PostSerializer(page_obj.object_list, many=True) elif request.method == 'PUT': try:",
"permissions import CustomAuthentication, AccessPermission from django.core.paginator import Paginator import traceback",
"return False @api_view(['GET',]) @authentication_classes([CustomAuthentication]) @permission_classes([AccessPermission]) def PostLikesView(request, post_pk, auth_pk): post",
"post_pk=request.data['Post_pk'], auth_pk=request.data['auth_pk']): code = status.HTTP_202_ACCEPTED comment = Comments.objects.latest(\"published\") data =",
"return Response(data, code) @api_view(['GET', 'POST',]) @authentication_classes([CustomAuthentication]) @permission_classes([AccessPermission]) def commentListView(request, post_pk,",
"[\"image/png\", \"image/jpeg\",]: content = base64.b64encode(request.FILES['file'].read()) #Inputfile else: content = form.cleaned_data[\"text\"]",
"post_pk if uid == None: r_uid = uuid.uuid4().hex uid =",
"return Response(response_dict) elif request.method == 'POST': if add_Comment(request, post_pk=request.data['Post_pk'], auth_pk=request.data['auth_pk']):",
"code = status.HTTP_200_OK except Exception as e: print(e) code =",
"if 'contentType' in request.data.keys(): comment.contentType = request.data['contentType'] if 'text' in",
"= Post(pk=uid, id=id, author_id=author_id, author=author, title=title, source=source, origin=origin, description=descirption, contentType=contentType,",
"many=True) elif request.method == 'PUT': try: code = status.HTTP_201_CREATED assert",
"page_size = request.GET.get('size') else: page_size = 5 if request.method ==",
"= request.GET.get('size') else: page_size = 5 if request.method == 'GET':",
"author_id = json.loads(serializers.serialize('json', Author.objects.filter(email=auth_pk), fields=('type', 'id', 'host', 'displayName', 'url', 'github',)))[0]['fields']",
"= Comments.objects.get(pk=comment_pk) serializer = CommentSerializer(comment) except Exception as e: print(e)",
"author=author_id, size=10, published=published, contentType=contentType, content=content) comments.save() return True else: print(request.data)",
"Post.objects.filter(id__icontains = \"linkedspace\") paginator = Paginator(posts, page_size) page_obj = paginator.get_page(page_number)",
"post.content = base64.b64encode(request.FILES['file'].read()) #Inputfile else: post.content = request.data[\"text\"] post.save() serializer",
"= re.sub('-', '', r_uid) id = id + '/posts/' +",
"many=True) response_dict = { \"type\": \"comments\", \"page\": page_number, \"size\": page_size,",
"auth_pk) likeObjs = Like.objects.filter(~Q(auth_pk = author), object = post.id) Likes",
"as e: print(e) code = status.HTTP_404_NOT_FOUND post = Post.objects.all() paginator",
"paginator.get_page(page_number) serializer = PostSerializer(page_obj.object_list, many=True) elif request.method == 'DELETE': try:",
"for key in l: if(key != \"context\"): like[key] = l[key]",
"status.HTTP_200_OK post = Post.objects.get(post_pk=post_pk) serializer = PostSerializer(post) except Exception as",
"Post, Author from .form import PostForm from Posts.commentForm import CommentForm",
"'displayName', 'url', 'github',)))[0]['fields'] post = Post.objects.get(pk = post_pk) post_pk_str =",
"= { \"type\": \"likes\", \"items\": likes } return Response(response_dict) @api_view(['GET',",
"'displayName', 'host', 'url', 'github',)))[0]['fields'] likes.append(like) response_dict = { \"type\": \"likes\",",
"rest_framework.response import Response from django.shortcuts import HttpResponse, render from requests",
"post.description = request.data['description'] if 'categories' in request.data.keys(): post.categories = request.data['categories'].split('",
"{} for key in l: if(key != \"context\"): like[key] =",
"comment.content = request.data['text'] comment.save() serializer = CommentSerializer(comment) except Exception as",
"in l: if(key != \"context\"): like[key] = l[key] like[\"@context\"] =",
"json.loads(serializers.serialize('json', Author.objects.filter(email=auth_pk), fields=('type', 'id', 'host', 'displayName', 'url', 'github',)))[0]['fields'] post =",
"else: content = form.cleaned_data[\"text\"] author_id = json.loads(serializers.serialize('json', Author.objects.filter(email=auth_pk), fields=('type', 'id',",
"try: author = Author.objects.get(auth_pk=auth_pk) posts = Post.objects.filter(author_id=author, id__icontains = \"linkedspace\")",
"'id', 'host', 'displayName', 'url', 'github',)))[0]['fields'] if uid == None: r_uid",
"CommentSerializer, PostSerializer from Author.serializers import LikeSerializer from Author.models import Like",
"Comments(pk=uid, id=comment_id, Post_pk=post, Post_pk_str = post_pk_str, auth_pk_str = auth_pk, author=author_id,",
"status.HTTP_201_CREATED post = Post.objects.latest(\"published\") data = PostSerializer(post).data else: code =",
"import HttpResponse, render from requests import get from .serializers import",
"if 'title' in request.data.keys(): post.title = request.data['title'] if 'description' in",
"'/posts/' + uid + \"/\" comments_id = id + \"comments/\"",
"Like.objects.filter(~Q(auth_pk = author), object = post.id) Likes = LikeSerializer(likeObjs, read_only=True,",
"@api_view(['GET', 'POST', 'PUT', 'DELETE', ]) @authentication_classes([CustomAuthentication]) @permission_classes([AccessPermission]) def PostDetail(request, post_pk,",
"'url', 'github',)))[0]['fields'] if uid == None: r_uid = uuid.uuid4().hex uid",
"post = Post.objects.get(post_pk=post_pk) serializer = PostSerializer(post) except Exception as e:",
"@api_view(['GET',]) @authentication_classes([CustomAuthentication]) @permission_classes([AccessPermission]) def PostLikesView(request, post_pk, auth_pk): post = Post.objects.get(post_pk",
"many=True) elif request.method == 'POST': try: code = status.HTTP_200_OK comment",
"author = Author.objects.get(auth_pk=auth_pk) posts = Post.objects.filter(author_id=author, id__icontains = \"linkedspace\") code",
"if contentType == \"application/app\": content = request.FILES['file'].read() #Inputfile elif contentType",
"200: data.append(team15.json()) team17 = get('https://cmput404f21t17.herokuapp.com/service/connect/public/', auth=('4cbe2def-feaa-4bb7-bce5-<PASSWORD>','123456')) if team17.status_code == 200:",
"from rest_framework.response import Response from django.shortcuts import HttpResponse, render from",
"\"comments\", \"page\": page_number, \"size\": page_size, \"post\": post_id, \"id\": comment_id, \"comments\":",
"getattr(post, 'id') comment_id = getattr(post, 'comments') paginator = Paginator(comments, page_size)",
"= paginator.get_page(page_number) serializer = CommentSerializer(page_obj.object_list, many=True) response_dict = { \"type\":",
"contentType=contentType, content=content) comments.save() return True else: print(request.data) return False @api_view(['GET',])",
"Response(response_dict) @api_view(['GET', 'POST',]) @authentication_classes([CustomAuthentication]) @permission_classes([AccessPermission]) def PostsList(request, auth_pk=None): page_number =",
"serializer = PostSerializer(page_obj.object_list, many=True) return Response(serializer.data, code) @api_view(['GET', 'POST', ])",
"Exception as e: print(e) code = status.HTTP_404_NOT_FOUND comment = Comments.objects.all()",
"post_pk, auth_pk, uid=None): form = CommentForm(request.POST, request.FILES) if form.is_valid(): updateForeignAuthors()",
"uid == None: r_uid = uuid.uuid4().hex uid = re.sub('-', '',",
"CommentSerializer(comment) except Exception as e: print(e) code = status.HTTP_404_NOT_FOUND comment",
"Response(data, code) @api_view(['GET', 'POST', 'PUT', 'DELETE', ]) @authentication_classes([CustomAuthentication]) @permission_classes([AccessPermission]) def",
"form.cleaned_data['categories'].split(' ') visibility = form.cleaned_data['visibility'] unlisted = form.cleaned_data['unlisted'] contentType =",
"comment_pk, auth_pk=None): page_number = request.GET.get('page') if 'size' in request.GET: page_size",
"form.cleaned_data['visibility'] unlisted = form.cleaned_data['unlisted'] contentType = form.cleaned_data['contentType'] if contentType ==",
"post = Post.objects.get(post_pk = post_pk) author = Author.objects.get(pk = auth_pk)",
"auth_pk): post = Post.objects.get(post_pk = post_pk) author = Author.objects.get(pk =",
"'POST', ]) @authentication_classes([CustomAuthentication]) @permission_classes([AccessPermission]) def commentDetail(request, post_pk, comment_pk, auth_pk=None): page_number",
"comment = Comments.objects.all() paginator = Paginator(comment, page_size) page_obj = paginator.get_page(page_number)",
"Author.objects.filter(email=auth_pk), fields=('type', 'id', 'host', 'displayName', 'url', 'github',)))[0]['fields'] post = Post.objects.get(pk",
"'', r_uid) id = id + '/posts/' + uid +",
"= uuid.uuid4().hex uid = re.sub('-', '', r_uid) comment_id = getattr(post,",
"code = status.HTTP_400_BAD_REQUEST post = Post.objects.all() paginator = Paginator(post, page_size)",
"r_uid = uuid.uuid4().hex uid = re.sub('-', '', r_uid) id =",
"page_obj = paginator.get_page(page_number) serializer = CommentSerializer(page_obj.object_list, many=True) response_dict = {",
"= author), object = post.id) Likes = LikeSerializer(likeObjs, read_only=True, many=True)",
"\"comments/\" published = timezone.now() posts = Post(pk=uid, id=id, author_id=author_id, author=author,",
"serializer = PostSerializer(page_obj.object_list, many=True) elif request.method == 'DELETE': try: post",
"post_pk) author = Author.objects.get(pk = auth_pk) likeObjs = Like.objects.filter(~Q(auth_pk =",
"response_dict = { \"type\": \"likes\", \"items\": likes } return Response(response_dict)",
"status.HTTP_404_NOT_FOUND post = Post.objects.all() paginator = Paginator(post, page_size) page_obj =",
"import updateForeignAuthors, GetForeignAuthors from .models import Post, Author from .form",
"serializer = PostSerializer(page_obj.object_list, many=True) elif request.method == 'PUT': try: code",
"= Paginator(post, page_size) page_obj = paginator.get_page(page_number) serializer = PostSerializer(page_obj.object_list, many=True)",
"in [\"image/png\", \"image/jpeg\",]: post.content = base64.b64encode(request.FILES['file'].read()) #Inputfile else: post.content =",
"'POST',]) @authentication_classes([CustomAuthentication]) @permission_classes([AccessPermission]) def PostsList(request, auth_pk=None): page_number = request.GET.get('page') if",
"request.data.keys(): comment.content = request.data['text'] comment.save() serializer = CommentSerializer(comment) except Exception",
"= id + '/posts/' + uid + \"/\" comments_id =",
"add_Comment(request, post_pk=request.data['Post_pk'], auth_pk=request.data['auth_pk']): code = status.HTTP_202_ACCEPTED comment = Comments.objects.latest(\"published\") data",
".form import PostForm from Posts.commentForm import CommentForm import json import",
"else: post.content = request.data[\"text\"] post.save() serializer = PostSerializer(post) except Exception",
"form.cleaned_data['description'] categories = form.cleaned_data['categories'].split(' ') visibility = form.cleaned_data['visibility'] unlisted =",
"form = CommentForm(request.POST, request.FILES) if form.is_valid(): updateForeignAuthors() published = timezone.now()",
"print(e) data = {} code = status.HTTP_400_BAD_REQUEST else: code =",
"'contentType' in request.data.keys(): post.contentType = request.data['contentType'] if post.contentType == \"application/app\":",
"+ '/posts/' + uid + \"/\" comments_id = id +",
"status.HTTP_201_CREATED assert newPost(request, post_pk, request.data['auth_pk'])==True post = Post.objects.get(post_pk=post_pk) serializer =",
"code) @api_view(['GET',]) def connection(request, auth_id=None): data = [] team3 =",
"Exception as e: print(e) code = status.HTTP_400_BAD_REQUEST post = Post.objects.all()",
"e: print(e) code = status.HTTP_404_NOT_FOUND comment = Comments.objects.all() paginator =",
"from Author.serializers import LikeSerializer from Author.models import Like from Author.views",
"request.data['text'] comment.save() serializer = CommentSerializer(comment) except Exception as e: print(e)",
"team15 = get('https://unhindled.herokuapp.com/service/allposts/', auth=('connectionsuperuser','404connection')) if team15.status_code == 200: data.append(team15.json()) team17",
"CommentForm(request.POST, request.FILES) if form.is_valid(): updateForeignAuthors() published = timezone.now() contentType =",
"many=True) elif request.method == 'DELETE': try: post = Post.objects.get(post_pk=post_pk) post.delete()",
"auth_pk, uid=None): form = CommentForm(request.POST, request.FILES) if form.is_valid(): updateForeignAuthors() published",
"Response(response_dict) elif request.method == 'POST': if add_Comment(request, post_pk=request.data['Post_pk'], auth_pk=request.data['auth_pk']): code",
"return Response(serializer.data, code) @api_view(['GET', 'POST', ]) @authentication_classes([CustomAuthentication]) @permission_classes([AccessPermission]) def commentDetail(request,",
"request.data['visibility'] if 'unlisted' in request.data.keys(): post.unlisted = request.data['unlisted'] if 'contentType'",
"PostSerializer from Author.serializers import LikeSerializer from Author.models import Like from",
"Exception as e: print(e) data = {} code = status.HTTP_400_BAD_REQUEST",
"uuid.uuid4().hex uid = re.sub('-', '', r_uid) id = id +",
"from .models import Post, Author from .form import PostForm from",
"posts.save() return True else: print(request.data) print(form.errors) print(form.data) return False def",
"page_obj = paginator.get_page(page_number) data = PostSerializer(page_obj.object_list, many=True).data elif request.method ==",
"= form.cleaned_data['categories'].split(' ') visibility = form.cleaned_data['visibility'] unlisted = form.cleaned_data['unlisted'] contentType",
"= author_id.url author = json.loads(serializers.serialize('json', Author.objects.filter(pk=auth_pk), fields=('type', 'id', 'host', 'displayName',",
"{ \"type\": \"likes\", \"items\": likes } return Response(response_dict) @api_view(['GET', 'POST',])",
"comment = Comments.objects.get(pk=comment_pk) serializer = CommentSerializer(comment) except Exception as e:",
"return Response(response_dict) @api_view(['GET', 'POST',]) @authentication_classes([CustomAuthentication]) @permission_classes([AccessPermission]) def PostsList(request, auth_pk=None): page_number",
"\"image/jpeg\",]: post.content = base64.b64encode(request.FILES['file'].read()) #Inputfile else: post.content = request.data[\"text\"] post.save()",
"many=True) likes = [] for l in Likes.data: like =",
"code = status.HTTP_200_OK posts = Post.objects.filter(id__icontains = \"linkedspace\") paginator =",
"'comments') paginator = Paginator(comments, page_size) page_obj = paginator.get_page(page_number) serializer =",
"form.cleaned_data[\"text\"] author_id = json.loads(serializers.serialize('json', Author.objects.filter(email=auth_pk), fields=('type', 'id', 'host', 'displayName', 'url',",
"'contentType' in request.data.keys(): comment.contentType = request.data['contentType'] if 'text' in request.data.keys():",
"import CommentSerializer, PostSerializer from Author.serializers import LikeSerializer from Author.models import",
"likes.append(like) response_dict = { \"type\": \"likes\", \"items\": likes } return",
"comments=comments_id) posts.save() return True else: print(request.data) print(form.errors) print(form.data) return False",
"except Exception as e: print(e) code = status.HTTP_400_BAD_REQUEST post =",
"post.contentType = request.data['contentType'] if post.contentType == \"application/app\": post.content = request.FILES['file'].read()",
"e: print(e) code = status.HTTP_400_BAD_REQUEST post = Post.objects.all() paginator =",
"True else: print(request.data) return False @api_view(['GET',]) @authentication_classes([CustomAuthentication]) @permission_classes([AccessPermission]) def PostLikesView(request,",
"comment_id = getattr(post, 'comments') paginator = Paginator(comments, page_size) page_obj =",
"try: post = Post.objects.get(post_pk=post_pk) post.delete() code = status.HTTP_200_OK except Exception",
"= Post.objects.get(post_pk=post_pk) serializer = PostSerializer(post) except Exception as e: print(e)",
"settings.SERVER_URL + \"/\" author_id = Author.objects.get(pk=auth_pk) id = author_id.url author",
"published=published, content=content, comments=comments_id) posts.save() return True else: print(request.data) print(form.errors) print(form.data)",
"= Comments.objects.all() paginator = Paginator(comment, page_size) page_obj = paginator.get_page(page_number) serializer",
"uuid import re import base64 from django.db.models import Q import",
"import timezone import requests from Posts.commentModel import Comments #from Posts.commentView",
"post.save() serializer = PostSerializer(post) except Exception as e: print(e) code",
"PostSerializer(page_obj.object_list, many=True).data elif request.method == 'POST': if newPost(request, auth_pk=request.data['auth_pk']): code",
"visibility = form.cleaned_data['visibility'] unlisted = form.cleaned_data['unlisted'] contentType = form.cleaned_data['contentType'] if",
"= status.HTTP_201_CREATED post = Post.objects.latest(\"published\") data = PostSerializer(post).data else: code",
"data = PostSerializer(post).data else: code = status.HTTP_400_BAD_REQUEST data = {}",
"id + '/posts/' + uid + \"/\" comments_id = id",
"newPost(request, post_pk, request.data['auth_pk'])==True post = Post.objects.get(post_pk=post_pk) serializer = PostSerializer(post) except",
"!= \"context\"): like[key] = l[key] like[\"@context\"] = l[\"context\"] like[\"author\"] =",
"code = status.HTTP_201_CREATED assert newPost(request, post_pk, request.data['auth_pk'])==True post = Post.objects.get(post_pk=post_pk)",
"json.loads(serializers.serialize('json', Author.objects.filter(pk=auth_pk), fields=('type', 'id', 'host', 'displayName', 'url', 'github',)))[0]['fields'] if uid",
"contentType = form.cleaned_data['contentType'] if contentType == \"application/app\": content = request.FILES['file'].read()",
"newPost(request, auth_pk=request.data['auth_pk']): code = status.HTTP_201_CREATED post = Post.objects.latest(\"published\") data =",
"post = Post.objects.all() paginator = Paginator(post, page_size) page_obj = paginator.get_page(page_number)",
"= Post.objects.get(post_pk=post_pk) post.delete() code = status.HTTP_200_OK except Exception as e:",
"from Posts.commentForm import CommentForm import json import uuid import re",
"django.core.paginator import Paginator import traceback def newPost(request, uid=None, auth_pk=None): form",
"code = status.HTTP_200_OK paginator = Paginator(posts, page_size) page_obj = paginator.get_page(page_number)",
"page_obj = paginator.get_page(page_number) serializer = CommentSerializer(page_obj.object_list, many=True) elif request.method ==",
"from django.db.models import Q import django.core from permissions import CustomAuthentication,",
"serializer = PostSerializer(page_obj.object_list, many=True) elif request.method == 'POST': try: code",
"== 'GET': if auth_pk: try: author = Author.objects.get(auth_pk=auth_pk) posts =",
"e: print(e) code = status.HTTP_404_NOT_FOUND post = Post.objects.all() paginator =",
"content = request.FILES['file'].read() #Inputfile elif contentType in [\"image/png\", \"image/jpeg\",]: content",
"add_Comment(request, post_pk, auth_pk, uid=None): form = CommentForm(request.POST, request.FILES) if form.is_valid():",
"= request.data[\"text\"] post.save() serializer = PostSerializer(post) except Exception as e:",
"r_uid) id = id + '/posts/' + uid + \"/\"",
"\"linkedspace\") paginator = Paginator(posts, page_size) page_obj = paginator.get_page(page_number) data =",
"#Inputfile elif contentType in [\"image/png\", \"image/jpeg\",]: content = base64.b64encode(request.FILES['file'].read()) #Inputfile",
"Likes.data: like = {} for key in l: if(key !=",
"code = status.HTTP_404_NOT_FOUND post = Post.objects.all() paginator = Paginator(post, page_size)",
"request.data.keys(): post.title = request.data['title'] if 'description' in request.data.keys(): post.description =",
"django.utils import timezone import requests from Posts.commentModel import Comments #from",
"descirption = form.cleaned_data['description'] categories = form.cleaned_data['categories'].split(' ') visibility = form.cleaned_data['visibility']",
"code = status.HTTP_200_OK post = Post.objects.get(post_pk=post_pk) serializer = PostSerializer(post) except",
"\"post\": post_id, \"id\": comment_id, \"comments\": serializer.data, } return Response(response_dict) elif",
"from rest_framework import status from rest_framework.decorators import api_view, authentication_classes, permission_classes",
"import api_view, authentication_classes, permission_classes from rest_framework.response import Response from django.shortcuts",
"Response(data, code) @api_view(['GET', 'POST',]) @authentication_classes([CustomAuthentication]) @permission_classes([AccessPermission]) def commentListView(request, post_pk, auth_pk=None):",
"= base64.b64encode(request.FILES['file'].read()) #Inputfile else: post.content = request.data[\"text\"] post.save() serializer =",
"Author.objects.filter(pk=auth_pk), fields=('type', 'id', 'host', 'displayName', 'url', 'github',)))[0]['fields'] if uid ==",
"post_pk, auth_pk): post = Post.objects.get(post_pk = post_pk) author = Author.objects.get(pk",
"contentType=contentType, count=0, size=10, categories=categories,visibility=visibility, unlisted=unlisted, published=published, content=content, comments=comments_id) posts.save() return",
"= post_pk_str, auth_pk_str = auth_pk, author=author_id, size=10, published=published, contentType=contentType, content=content)",
"l[key] like[\"@context\"] = l[\"context\"] like[\"author\"] = json.loads(django.core.serializers.serialize('json', Author.objects.filter(id=l[\"author\"]), fields=('type', 'id',",
"serializer = CommentSerializer(page_obj.object_list, many=True) response_dict = { \"type\": \"comments\", \"page\":",
"serializer = PostSerializer(post) except Exception as e: print(e) code =",
"as e: print(e) code = status.HTTP_404_NOT_FOUND comment = Comments.objects.all() paginator",
"= get('https://social-dis.herokuapp.com/posts', auth=('socialdistribution_t03','c404t03')) if team3.status_code == 200: data.append(team3.json()) team15 =",
"django.shortcuts import HttpResponse, render from requests import get from .serializers",
"request.GET: page_size = request.GET.get('size') else: page_size = 5 if request.method",
"Paginator(comments, page_size) page_obj = paginator.get_page(page_number) serializer = CommentSerializer(page_obj.object_list, many=True) response_dict",
"== \"application/app\": post.content = request.FILES['file'].read() #Inputfile elif post.contentType in [\"image/png\",",
"permission_classes from rest_framework.response import Response from django.shortcuts import HttpResponse, render",
"settings.SERVER_URL + \"/\" origin = settings.SERVER_URL + \"/\" author_id =",
"= paginator.get_page(page_number) serializer = CommentSerializer(page_obj.object_list, many=True) elif request.method == 'POST':",
"import add_Comment from rest_framework import status from rest_framework.decorators import api_view,",
"from permissions import CustomAuthentication, AccessPermission from django.core.paginator import Paginator import",
"newPost(request, uid=None, auth_pk=None): form = PostForm(request.POST, request.FILES) if form.is_valid(): title",
"def add_Comment(request, post_pk, auth_pk, uid=None): form = CommentForm(request.POST, request.FILES) if",
"content=content, comments=comments_id) posts.save() return True else: print(request.data) print(form.errors) print(form.data) return",
"'', r_uid) comment_id = getattr(post, 'comments') + uid comments =",
"= base64.b64encode(request.FILES['file'].read()) #Inputfile else: content = form.cleaned_data[\"text\"] author_id = json.loads(serializers.serialize('json',",
"content = form.cleaned_data[\"text\"] author_id = json.loads(serializers.serialize('json', Author.objects.filter(email=auth_pk), fields=('type', 'id', 'host',",
"print(request.data) return False @api_view(['GET',]) @authentication_classes([CustomAuthentication]) @permission_classes([AccessPermission]) def PostLikesView(request, post_pk, auth_pk):",
"CommentForm import json import uuid import re import base64 from",
"= \"linkedspace\") code = status.HTTP_200_OK paginator = Paginator(posts, page_size) page_obj",
"return Response(data, code) @api_view(['GET', 'POST', 'PUT', 'DELETE', ]) @authentication_classes([CustomAuthentication]) @permission_classes([AccessPermission])",
"= status.HTTP_200_OK post = Post.objects.get(post_pk=post_pk) serializer = PostSerializer(post) except Exception",
"comment.contentType = request.data['contentType'] if 'text' in request.data.keys(): comment.content = request.data['text']",
"import PostForm from Posts.commentForm import CommentForm import json import uuid",
"if newPost(request, auth_pk=request.data['auth_pk']): code = status.HTTP_201_CREATED post = Post.objects.latest(\"published\") data",
"paginator.get_page(page_number) serializer = PostSerializer(page_obj.object_list, many=True) elif request.method == 'POST': try:",
"5 if request.method == 'GET': comments = Comments.objects.filter(Post_pk_str=post_pk) post =",
"import status from rest_framework.decorators import api_view, authentication_classes, permission_classes from rest_framework.response",
"= form.cleaned_data['description'] categories = form.cleaned_data['categories'].split(' ') visibility = form.cleaned_data['visibility'] unlisted",
"object = post.id) Likes = LikeSerializer(likeObjs, read_only=True, many=True) likes =",
"#from Posts.commentView import add_Comment from rest_framework import status from rest_framework.decorators",
"posts = Post.objects.filter(author_id=author, id__icontains = \"linkedspace\") code = status.HTTP_200_OK paginator",
"Post.objects.all() paginator = Paginator(post, page_size) page_obj = paginator.get_page(page_number) serializer =",
"post.categories = request.data['categories'].split(' ') if 'visibility' in request.data.keys(): post.visibility =",
"page_size) page_obj = paginator.get_page(page_number) serializer = CommentSerializer(page_obj.object_list, many=True) return Response(serializer.data,",
"code) @api_view(['GET', 'POST', ]) @authentication_classes([CustomAuthentication]) @permission_classes([AccessPermission]) def commentDetail(request, post_pk, comment_pk,",
"[] for l in Likes.data: like = {} for key",
"Comments.objects.get(pk=comment_pk) serializer = CommentSerializer(comment) except Exception as e: print(e) code",
"page_size) page_obj = paginator.get_page(page_number) data = PostSerializer(page_obj.object_list, many=True).data elif request.method",
"page_size = 5 if request.method == 'GET': if auth_pk: try:",
"'GET': try: code = status.HTTP_200_OK comment = Comments.objects.get(pk=comment_pk) serializer =",
"import Q import django.core from permissions import CustomAuthentication, AccessPermission from",
"re.sub('-', '', r_uid) id = id + '/posts/' + uid",
"except Exception as e: print(e) code = status.HTTP_404_NOT_FOUND comment =",
"== 200: data.append(team15.json()) team17 = get('https://cmput404f21t17.herokuapp.com/service/connect/public/', auth=('4cbe2def-feaa-4bb7-bce5-<PASSWORD>','123456')) if team17.status_code ==",
"= form.cleaned_data['contentType'] if contentType == \"application/app\": content = request.FILES['file'].read() #Inputfile",
"count=0, size=10, categories=categories,visibility=visibility, unlisted=unlisted, published=published, content=content, comments=comments_id) posts.save() return True",
"if form.is_valid(): title = form.cleaned_data['title'] descirption = form.cleaned_data['description'] categories =",
"elif request.method == 'PUT': try: code = status.HTTP_201_CREATED assert newPost(request,",
"from requests import get from .serializers import CommentSerializer, PostSerializer from",
"'GET': comments = Comments.objects.filter(Post_pk_str=post_pk) post = Post.objects.get(pk=post_pk) post_id = getattr(post,",
"= l[\"context\"] like[\"author\"] = json.loads(django.core.serializers.serialize('json', Author.objects.filter(id=l[\"author\"]), fields=('type', 'id', 'displayName', 'host',",
"+ \"/\" origin = settings.SERVER_URL + \"/\" author_id = Author.objects.get(pk=auth_pk)",
"django.core from permissions import CustomAuthentication, AccessPermission from django.core.paginator import Paginator",
"= get('https://unhindled.herokuapp.com/service/allposts/', auth=('connectionsuperuser','404connection')) if team15.status_code == 200: data.append(team15.json()) team17 =",
"= status.HTTP_201_CREATED assert newPost(request, post_pk, request.data['auth_pk'])==True post = Post.objects.get(post_pk=post_pk) serializer",
"rest_framework import status from rest_framework.decorators import api_view, authentication_classes, permission_classes from",
"timezone.now() contentType = form.cleaned_data['contentType'] if contentType == \"application/app\": content =",
"= base64.b64encode(request.FILES['file'].read()) #Inputfile else: content = form.cleaned_data[\"text\"] source = settings.SERVER_URL",
"content = base64.b64encode(request.FILES['file'].read()) #Inputfile else: content = form.cleaned_data[\"text\"] source =",
"= status.HTTP_400_BAD_REQUEST comment = Comments.objects.all() paginator = Paginator(comment, page_size) page_obj",
"= 5 if request.method == 'GET': try: code = status.HTTP_200_OK",
"'title' in request.data.keys(): post.title = request.data['title'] if 'description' in request.data.keys():",
"== 'GET': comments = Comments.objects.filter(Post_pk_str=post_pk) post = Post.objects.get(pk=post_pk) post_id =",
"'github',)))[0]['fields'] post = Post.objects.get(pk = post_pk) post_pk_str = post_pk if",
"= form.cleaned_data['unlisted'] contentType = form.cleaned_data['contentType'] if contentType == \"application/app\": content",
"= id + \"comments/\" published = timezone.now() posts = Post(pk=uid,",
"= PostSerializer(page_obj.object_list, many=True) elif request.method == 'POST': try: code =",
"elif request.method == 'POST': try: code = status.HTTP_200_OK comment =",
"request.data['description'] if 'categories' in request.data.keys(): post.categories = request.data['categories'].split(' ') if",
"except Exception as e: print(e) code = status.HTTP_400_BAD_REQUEST comment =",
"= settings.SERVER_URL + \"/\" origin = settings.SERVER_URL + \"/\" author_id",
"Post.objects.get(post_pk=post_pk) if 'title' in request.data.keys(): post.title = request.data['title'] if 'description'",
"updateForeignAuthors, GetForeignAuthors from .models import Post, Author from .form import",
"CommentSerializer(page_obj.object_list, many=True) elif request.method == 'POST': try: code = status.HTTP_200_OK",
"'PUT': try: code = status.HTTP_201_CREATED assert newPost(request, post_pk, request.data['auth_pk'])==True post",
"post.content = request.data[\"text\"] post.save() serializer = PostSerializer(post) except Exception as",
"id=id, author_id=author_id, author=author, title=title, source=source, origin=origin, description=descirption, contentType=contentType, count=0, size=10,",
"= request.data['contentType'] if 'text' in request.data.keys(): comment.content = request.data['text'] comment.save()",
"= Post.objects.get(post_pk=post_pk) if 'title' in request.data.keys(): post.title = request.data['title'] if",
"if form.is_valid(): updateForeignAuthors() published = timezone.now() contentType = form.cleaned_data['contentType'] if",
"in request.data.keys(): comment.contentType = request.data['contentType'] if 'text' in request.data.keys(): comment.content",
"Paginator(posts, page_size) page_obj = paginator.get_page(page_number) data = PostSerializer(page_obj.object_list, many=True).data except",
"request.FILES['file'].read() #Inputfile elif contentType in [\"image/png\", \"image/jpeg\",]: content = base64.b64encode(request.FILES['file'].read())",
"= Paginator(comments, page_size) page_obj = paginator.get_page(page_number) serializer = CommentSerializer(page_obj.object_list, many=True)",
"size=10, published=published, contentType=contentType, content=content) comments.save() return True else: print(request.data) return",
"code = status.HTTP_202_ACCEPTED comment = Comments.objects.latest(\"published\") data = CommentSerializer(comment).data else:",
"Author.objects.get(pk = auth_pk) likeObjs = Like.objects.filter(~Q(auth_pk = author), object =",
"= timezone.now() contentType = form.cleaned_data['contentType'] if contentType == \"application/app\": content",
"'comments') + uid comments = Comments(pk=uid, id=comment_id, Post_pk=post, Post_pk_str =",
"PostDetail(request, post_pk, auth_pk=None): page_number = request.GET.get('page') if 'size' in request.GET:",
"data = {} return Response(data, code) @api_view(['GET', 'POST', 'PUT', 'DELETE',",
"request.method == 'GET': try: code = status.HTTP_200_OK comment = Comments.objects.get(pk=comment_pk)",
"\"application/app\": content = request.FILES['file'].read() #Inputfile elif contentType in [\"image/png\", \"image/jpeg\",]:",
"= getattr(post, 'id') comment_id = getattr(post, 'comments') paginator = Paginator(comments,",
"serializer = CommentSerializer(page_obj.object_list, many=True) elif request.method == 'POST': try: code",
"= auth_pk) likeObjs = Like.objects.filter(~Q(auth_pk = author), object = post.id)",
"= Paginator(posts, page_size) page_obj = paginator.get_page(page_number) data = PostSerializer(page_obj.object_list, many=True).data",
"post_pk) post_pk_str = post_pk if uid == None: r_uid =",
"id=comment_id, Post_pk=post, Post_pk_str = post_pk_str, auth_pk_str = auth_pk, author=author_id, size=10,",
"== 'GET': try: code = status.HTTP_200_OK post = Post.objects.get(post_pk=post_pk) serializer",
"== 'POST': try: code = status.HTTP_200_OK post = Post.objects.get(post_pk=post_pk) if",
"code = status.HTTP_200_OK post = Post.objects.get(post_pk=post_pk) if 'title' in request.data.keys():",
"@permission_classes([AccessPermission]) def PostsList(request, auth_pk=None): page_number = request.GET.get('page') if 'size' in",
"author), object = post.id) Likes = LikeSerializer(likeObjs, read_only=True, many=True) likes",
"code = status.HTTP_400_BAD_REQUEST else: code = status.HTTP_200_OK posts = Post.objects.filter(id__icontains",
"== None: r_uid = uuid.uuid4().hex uid = re.sub('-', '', r_uid)",
"status.HTTP_400_BAD_REQUEST data = {} return Response(data, code) @api_view(['GET', 'POST',]) @authentication_classes([CustomAuthentication])",
"if request.method == 'GET': comments = Comments.objects.filter(Post_pk_str=post_pk) post = Post.objects.get(pk=post_pk)",
"serializers from django.utils import timezone import requests from Posts.commentModel import",
"Post.objects.filter(author_id=author, id__icontains = \"linkedspace\") code = status.HTTP_200_OK paginator = Paginator(posts,",
"LikeSerializer from Author.models import Like from Author.views import updateForeignAuthors, GetForeignAuthors",
"= status.HTTP_200_OK comment = Comments.objects.get(pk=comment_pk) if 'contentType' in request.data.keys(): comment.contentType",
"= status.HTTP_400_BAD_REQUEST data = {} return Response(data, code) @api_view(['GET', 'POST',",
"many=True) elif request.method == 'POST': try: code = status.HTTP_200_OK post",
"= 5 if request.method == 'GET': if auth_pk: try: author",
"= json.loads(serializers.serialize('json', Author.objects.filter(pk=auth_pk), fields=('type', 'id', 'host', 'displayName', 'url', 'github',)))[0]['fields'] if",
"in request.data.keys(): post.contentType = request.data['contentType'] if post.contentType == \"application/app\": post.content",
"elif request.method == 'POST': try: code = status.HTTP_200_OK post =",
"Post.objects.get(post_pk=post_pk) serializer = PostSerializer(post) except Exception as e: print(e) code",
"import uuid import re import base64 from django.db.models import Q",
"Exception as e: print(e) code = status.HTTP_404_NOT_FOUND post = Post.objects.all()",
"= CommentSerializer(page_obj.object_list, many=True) elif request.method == 'POST': try: code =",
"= getattr(post, 'comments') paginator = Paginator(comments, page_size) page_obj = paginator.get_page(page_number)",
"print(request.data) print(form.errors) print(form.data) return False def add_Comment(request, post_pk, auth_pk, uid=None):",
"if request.method == 'GET': try: code = status.HTTP_200_OK post =",
"= request.data['unlisted'] if 'contentType' in request.data.keys(): post.contentType = request.data['contentType'] if",
"@api_view(['GET', 'POST', ]) @authentication_classes([CustomAuthentication]) @permission_classes([AccessPermission]) def commentDetail(request, post_pk, comment_pk, auth_pk=None):",
"contentType == \"application/app\": content = request.FILES['file'].read() #Inputfile elif contentType in",
"+ uid + \"/\" comments_id = id + \"comments/\" published",
"PostSerializer(post) except Exception as e: print(e) code = status.HTTP_400_BAD_REQUEST post",
"post_id = getattr(post, 'id') comment_id = getattr(post, 'comments') paginator =",
"Author.models import Like from Author.views import updateForeignAuthors, GetForeignAuthors from .models",
"get('https://unhindled.herokuapp.com/service/allposts/', auth=('connectionsuperuser','404connection')) if team15.status_code == 200: data.append(team15.json()) team17 = get('https://cmput404f21t17.herokuapp.com/service/connect/public/',",
"import base64 from django.db.models import Q import django.core from permissions",
"data = PostSerializer(page_obj.object_list, many=True).data except Exception as e: print(e) data",
"elif request.method == 'POST': if newPost(request, auth_pk=request.data['auth_pk']): code = status.HTTP_201_CREATED",
"'host', 'displayName', 'url', 'github',)))[0]['fields'] if uid == None: r_uid =",
"post_pk_str = post_pk if uid == None: r_uid = uuid.uuid4().hex",
"page_size, \"post\": post_id, \"id\": comment_id, \"comments\": serializer.data, } return Response(response_dict)",
"print(form.errors) print(form.data) return False def add_Comment(request, post_pk, auth_pk, uid=None): form",
"request.method == 'GET': try: code = status.HTTP_200_OK post = Post.objects.get(post_pk=post_pk)",
"request.data['contentType'] if 'text' in request.data.keys(): comment.content = request.data['text'] comment.save() serializer",
"form.cleaned_data['title'] descirption = form.cleaned_data['description'] categories = form.cleaned_data['categories'].split(' ') visibility =",
"paginator.get_page(page_number) data = PostSerializer(page_obj.object_list, many=True).data elif request.method == 'POST': if",
"likes = [] for l in Likes.data: like = {}",
"request.method == 'GET': if auth_pk: try: author = Author.objects.get(auth_pk=auth_pk) posts",
"print(e) code = status.HTTP_404_NOT_FOUND post = Post.objects.all() paginator = Paginator(post,",
"from Posts.commentModel import Comments #from Posts.commentView import add_Comment from rest_framework",
"re.sub('-', '', r_uid) comment_id = getattr(post, 'comments') + uid comments",
"request.method == 'GET': comments = Comments.objects.filter(Post_pk_str=post_pk) post = Post.objects.get(pk=post_pk) post_id",
"Author.objects.get(auth_pk=auth_pk) posts = Post.objects.filter(author_id=author, id__icontains = \"linkedspace\") code = status.HTTP_200_OK",
"many=True).data elif request.method == 'POST': if newPost(request, auth_pk=request.data['auth_pk']): code =",
"unlisted=unlisted, published=published, content=content, comments=comments_id) posts.save() return True else: print(request.data) print(form.errors)",
"= Post.objects.get(pk=post_pk) post_id = getattr(post, 'id') comment_id = getattr(post, 'comments')",
"'id', 'displayName', 'host', 'url', 'github',)))[0]['fields'] likes.append(like) response_dict = { \"type\":",
"many=True).data except Exception as e: print(e) data = {} code",
"django.db.models import Q import django.core from permissions import CustomAuthentication, AccessPermission",
"Author.objects.get(pk=auth_pk) id = author_id.url author = json.loads(serializers.serialize('json', Author.objects.filter(pk=auth_pk), fields=('type', 'id',",
"@permission_classes([AccessPermission]) def PostDetail(request, post_pk, auth_pk=None): page_number = request.GET.get('page') if 'size'",
"= post_pk) post_pk_str = post_pk if uid == None: r_uid",
"from .serializers import CommentSerializer, PostSerializer from Author.serializers import LikeSerializer from",
"code = status.HTTP_201_CREATED post = Post.objects.latest(\"published\") data = PostSerializer(post).data else:",
"Posts.commentModel import Comments #from Posts.commentView import add_Comment from rest_framework import",
"PostSerializer(post) except Exception as e: print(e) code = status.HTTP_404_NOT_FOUND post",
"as e: print(e) code = status.HTTP_400_BAD_REQUEST comment = Comments.objects.all() paginator",
"team17 = get('https://cmput404f21t17.herokuapp.com/service/connect/public/', auth=('4cbe2def-feaa-4bb7-bce5-<PASSWORD>','123456')) if team17.status_code == 200: data.append(team17.json()) return",
"post = Post.objects.get(pk=post_pk) post_id = getattr(post, 'id') comment_id = getattr(post,",
"else: page_size = 5 if request.method == 'GET': comments =",
"form = PostForm(request.POST, request.FILES) if form.is_valid(): title = form.cleaned_data['title'] descirption",
"True else: print(request.data) print(form.errors) print(form.data) return False def add_Comment(request, post_pk,",
"= PostSerializer(page_obj.object_list, many=True).data elif request.method == 'POST': if newPost(request, auth_pk=request.data['auth_pk']):",
"= CommentSerializer(comment).data else: code = status.HTTP_400_BAD_REQUEST data = {} return",
"l[\"context\"] like[\"author\"] = json.loads(django.core.serializers.serialize('json', Author.objects.filter(id=l[\"author\"]), fields=('type', 'id', 'displayName', 'host', 'url',",
"= CommentSerializer(page_obj.object_list, many=True) response_dict = { \"type\": \"comments\", \"page\": page_number,",
"base64 from django.db.models import Q import django.core from permissions import",
"if 'description' in request.data.keys(): post.description = request.data['description'] if 'categories' in",
"render from requests import get from .serializers import CommentSerializer, PostSerializer",
"= Post.objects.all() paginator = Paginator(post, page_size) page_obj = paginator.get_page(page_number) serializer",
"paginator.get_page(page_number) data = PostSerializer(page_obj.object_list, many=True).data except Exception as e: print(e)",
"post = Post.objects.get(post_pk=post_pk) post.delete() code = status.HTTP_200_OK except Exception as",
"add_Comment from rest_framework import status from rest_framework.decorators import api_view, authentication_classes,",
"import re import base64 from django.db.models import Q import django.core",
"import CommentForm import json import uuid import re import base64",
"+ uid comments = Comments(pk=uid, id=comment_id, Post_pk=post, Post_pk_str = post_pk_str,",
"} return Response(response_dict) @api_view(['GET', 'POST',]) @authentication_classes([CustomAuthentication]) @permission_classes([AccessPermission]) def PostsList(request, auth_pk=None):",
"= request.data['title'] if 'description' in request.data.keys(): post.description = request.data['description'] if",
"comments_id = id + \"comments/\" published = timezone.now() posts =",
"base64.b64encode(request.FILES['file'].read()) #Inputfile else: post.content = request.data[\"text\"] post.save() serializer = PostSerializer(post)",
"authentication_classes, permission_classes from rest_framework.response import Response from django.shortcuts import HttpResponse,",
"request.FILES) if form.is_valid(): updateForeignAuthors() published = timezone.now() contentType = form.cleaned_data['contentType']",
"requests from Posts.commentModel import Comments #from Posts.commentView import add_Comment from",
"for l in Likes.data: like = {} for key in",
"@permission_classes([AccessPermission]) def PostLikesView(request, post_pk, auth_pk): post = Post.objects.get(post_pk = post_pk)",
"print(e) code = status.HTTP_404_NOT_FOUND comment = Comments.objects.all() paginator = Paginator(comment,",
"like[\"@context\"] = l[\"context\"] like[\"author\"] = json.loads(django.core.serializers.serialize('json', Author.objects.filter(id=l[\"author\"]), fields=('type', 'id', 'displayName',",
"get('https://social-dis.herokuapp.com/posts', auth=('socialdistribution_t03','c404t03')) if team3.status_code == 200: data.append(team3.json()) team15 = get('https://unhindled.herokuapp.com/service/allposts/',",
"Paginator(comment, page_size) page_obj = paginator.get_page(page_number) serializer = CommentSerializer(page_obj.object_list, many=True) return",
"id__icontains = \"linkedspace\") code = status.HTTP_200_OK paginator = Paginator(posts, page_size)",
"def commentDetail(request, post_pk, comment_pk, auth_pk=None): page_number = request.GET.get('page') if 'size'",
"request.data['unlisted'] if 'contentType' in request.data.keys(): post.contentType = request.data['contentType'] if post.contentType",
".serializers import CommentSerializer, PostSerializer from Author.serializers import LikeSerializer from Author.models",
"@authentication_classes([CustomAuthentication]) @permission_classes([AccessPermission]) def commentDetail(request, post_pk, comment_pk, auth_pk=None): page_number = request.GET.get('page')",
"= get('https://cmput404f21t17.herokuapp.com/service/connect/public/', auth=('4cbe2def-feaa-4bb7-bce5-<PASSWORD>','123456')) if team17.status_code == 200: data.append(team17.json()) return Response({'connection':",
"Post.objects.latest(\"published\") data = PostSerializer(post).data else: code = status.HTTP_400_BAD_REQUEST data =",
"@authentication_classes([CustomAuthentication]) @permission_classes([AccessPermission]) def PostLikesView(request, post_pk, auth_pk): post = Post.objects.get(post_pk =",
"from Author.models import Like from Author.views import updateForeignAuthors, GetForeignAuthors from",
"{} return Response(data, code) @api_view(['GET', 'POST', 'PUT', 'DELETE', ]) @authentication_classes([CustomAuthentication])",
"auth_pk_str = auth_pk, author=author_id, size=10, published=published, contentType=contentType, content=content) comments.save() return",
"request.method == 'PUT': try: code = status.HTTP_201_CREATED assert newPost(request, post_pk,",
"else: page_size = 5 if request.method == 'GET': try: code",
"try: code = status.HTTP_200_OK comment = Comments.objects.get(pk=comment_pk) if 'contentType' in",
"= Comments.objects.filter(Post_pk_str=post_pk) post = Post.objects.get(pk=post_pk) post_id = getattr(post, 'id') comment_id",
"Post_pk=post, Post_pk_str = post_pk_str, auth_pk_str = auth_pk, author=author_id, size=10, published=published,",
"= PostSerializer(post) except Exception as e: print(e) code = status.HTTP_404_NOT_FOUND",
"l in Likes.data: like = {} for key in l:",
"Like from Author.views import updateForeignAuthors, GetForeignAuthors from .models import Post,",
"'GET': try: code = status.HTTP_200_OK post = Post.objects.get(post_pk=post_pk) serializer =",
"fields=('type', 'id', 'host', 'displayName', 'url', 'github',)))[0]['fields'] if uid == None:",
"PostLikesView(request, post_pk, auth_pk): post = Post.objects.get(post_pk = post_pk) author =",
"= status.HTTP_200_OK comment = Comments.objects.get(pk=comment_pk) serializer = CommentSerializer(comment) except Exception",
"= PostSerializer(post) except Exception as e: print(e) code = status.HTTP_400_BAD_REQUEST",
"status.HTTP_200_OK comment = Comments.objects.get(pk=comment_pk) serializer = CommentSerializer(comment) except Exception as",
"CommentSerializer(comment) except Exception as e: print(e) code = status.HTTP_400_BAD_REQUEST comment",
"many=True) return Response(serializer.data, code) @api_view(['GET',]) def connection(request, auth_id=None): data =",
"= {} for key in l: if(key != \"context\"): like[key]",
"CustomAuthentication, AccessPermission from django.core.paginator import Paginator import traceback def newPost(request,",
"Author from .form import PostForm from Posts.commentForm import CommentForm import",
"title = form.cleaned_data['title'] descirption = form.cleaned_data['description'] categories = form.cleaned_data['categories'].split(' ')",
"request.GET.get('size') else: page_size = 5 if request.method == 'GET': if",
"PostForm from Posts.commentForm import CommentForm import json import uuid import",
"Comments.objects.latest(\"published\") data = CommentSerializer(comment).data else: code = status.HTTP_400_BAD_REQUEST data =",
"\"id\": comment_id, \"comments\": serializer.data, } return Response(response_dict) elif request.method ==",
"PostForm(request.POST, request.FILES) if form.is_valid(): title = form.cleaned_data['title'] descirption = form.cleaned_data['description']",
"if uid == None: r_uid = uuid.uuid4().hex uid = re.sub('-',",
"from django.core import serializers from django.utils import timezone import requests",
"description=descirption, contentType=contentType, count=0, size=10, categories=categories,visibility=visibility, unlisted=unlisted, published=published, content=content, comments=comments_id) posts.save()",
"if request.method == 'GET': if auth_pk: try: author = Author.objects.get(auth_pk=auth_pk)",
"code) @api_view(['GET', 'POST', 'PUT', 'DELETE', ]) @authentication_classes([CustomAuthentication]) @permission_classes([AccessPermission]) def PostDetail(request,",
"print(e) code = status.HTTP_400_BAD_REQUEST post = Post.objects.all() paginator = Paginator(post,",
"200: data.append(team3.json()) team15 = get('https://unhindled.herokuapp.com/service/allposts/', auth=('connectionsuperuser','404connection')) if team15.status_code == 200:",
"== 'PUT': try: code = status.HTTP_201_CREATED assert newPost(request, post_pk, request.data['auth_pk'])==True",
"request.data[\"text\"] post.save() serializer = PostSerializer(post) except Exception as e: print(e)",
"= paginator.get_page(page_number) serializer = PostSerializer(page_obj.object_list, many=True) return Response(serializer.data, code) @api_view(['GET',",
"likes } return Response(response_dict) @api_view(['GET', 'POST',]) @authentication_classes([CustomAuthentication]) @permission_classes([AccessPermission]) def PostsList(request,",
"= CommentSerializer(comment) except Exception as e: print(e) code = status.HTTP_404_NOT_FOUND",
"= 5 if request.method == 'GET': comments = Comments.objects.filter(Post_pk_str=post_pk) post",
"GetForeignAuthors from .models import Post, Author from .form import PostForm",
"in request.data.keys(): comment.content = request.data['text'] comment.save() serializer = CommentSerializer(comment) except",
"status.HTTP_200_OK comment = Comments.objects.get(pk=comment_pk) if 'contentType' in request.data.keys(): comment.contentType =",
"team3 = get('https://social-dis.herokuapp.com/posts', auth=('socialdistribution_t03','c404t03')) if team3.status_code == 200: data.append(team3.json()) team15",
"Paginator(post, page_size) page_obj = paginator.get_page(page_number) serializer = PostSerializer(page_obj.object_list, many=True) elif",
"'id', 'host', 'displayName', 'url', 'github',)))[0]['fields'] post = Post.objects.get(pk = post_pk)",
"def PostLikesView(request, post_pk, auth_pk): post = Post.objects.get(post_pk = post_pk) author",
"from Author.views import updateForeignAuthors, GetForeignAuthors from .models import Post, Author",
"form.cleaned_data[\"text\"] source = settings.SERVER_URL + \"/\" origin = settings.SERVER_URL +",
"author_id.url author = json.loads(serializers.serialize('json', Author.objects.filter(pk=auth_pk), fields=('type', 'id', 'host', 'displayName', 'url',",
"'github',)))[0]['fields'] if uid == None: r_uid = uuid.uuid4().hex uid =",
"= post.id) Likes = LikeSerializer(likeObjs, read_only=True, many=True) likes = []",
"size=10, categories=categories,visibility=visibility, unlisted=unlisted, published=published, content=content, comments=comments_id) posts.save() return True else:",
"Paginator(posts, page_size) page_obj = paginator.get_page(page_number) data = PostSerializer(page_obj.object_list, many=True).data elif",
"\"size\": page_size, \"post\": post_id, \"id\": comment_id, \"comments\": serializer.data, } return",
"comment_id, \"comments\": serializer.data, } return Response(response_dict) elif request.method == 'POST':",
"\"comments\": serializer.data, } return Response(response_dict) elif request.method == 'POST': if",
"@authentication_classes([CustomAuthentication]) @permission_classes([AccessPermission]) def PostDetail(request, post_pk, auth_pk=None): page_number = request.GET.get('page') if",
"request.data['contentType'] if post.contentType == \"application/app\": post.content = request.FILES['file'].read() #Inputfile elif",
"status.HTTP_200_OK except Exception as e: print(e) code = status.HTTP_404_NOT_FOUND post",
"get('https://cmput404f21t17.herokuapp.com/service/connect/public/', auth=('4cbe2def-feaa-4bb7-bce5-<PASSWORD>','123456')) if team17.status_code == 200: data.append(team17.json()) return Response({'connection': data})",
"code = status.HTTP_404_NOT_FOUND comment = Comments.objects.all() paginator = Paginator(comment, page_size)",
"post_pk, comment_pk, auth_pk=None): page_number = request.GET.get('page') if 'size' in request.GET:",
"django.conf import settings from django.core import serializers from django.utils import",
"#Inputfile elif post.contentType in [\"image/png\", \"image/jpeg\",]: post.content = base64.b64encode(request.FILES['file'].read()) #Inputfile",
"print(e) code = status.HTTP_400_BAD_REQUEST comment = Comments.objects.all() paginator = Paginator(comment,",
"Response(serializer.data, code) @api_view(['GET', 'POST', ]) @authentication_classes([CustomAuthentication]) @permission_classes([AccessPermission]) def commentDetail(request, post_pk,",
"request.data.keys(): post.description = request.data['description'] if 'categories' in request.data.keys(): post.categories =",
"= PostSerializer(post).data else: code = status.HTTP_400_BAD_REQUEST data = {} return",
"\"type\": \"likes\", \"items\": likes } return Response(response_dict) @api_view(['GET', 'POST',]) @authentication_classes([CustomAuthentication])",
"as e: print(e) data = {} code = status.HTTP_400_BAD_REQUEST else:",
"#Inputfile else: post.content = request.data[\"text\"] post.save() serializer = PostSerializer(post) except",
"code = status.HTTP_400_BAD_REQUEST data = {} return Response(data, code) @api_view(['GET',",
"= paginator.get_page(page_number) serializer = PostSerializer(page_obj.object_list, many=True) elif request.method == 'POST':",
"like[key] = l[key] like[\"@context\"] = l[\"context\"] like[\"author\"] = json.loads(django.core.serializers.serialize('json', Author.objects.filter(id=l[\"author\"]),",
"import traceback def newPost(request, uid=None, auth_pk=None): form = PostForm(request.POST, request.FILES)",
"import CustomAuthentication, AccessPermission from django.core.paginator import Paginator import traceback def",
"Posts.commentView import add_Comment from rest_framework import status from rest_framework.decorators import",
"+ \"/\" comments_id = id + \"comments/\" published = timezone.now()",
"r_uid = uuid.uuid4().hex uid = re.sub('-', '', r_uid) comment_id =",
"return False def add_Comment(request, post_pk, auth_pk, uid=None): form = CommentForm(request.POST,",
"post.id) Likes = LikeSerializer(likeObjs, read_only=True, many=True) likes = [] for",
"= CommentSerializer(page_obj.object_list, many=True) return Response(serializer.data, code) @api_view(['GET',]) def connection(request, auth_id=None):",
"= Paginator(comment, page_size) page_obj = paginator.get_page(page_number) serializer = CommentSerializer(page_obj.object_list, many=True)",
"@permission_classes([AccessPermission]) def commentListView(request, post_pk, auth_pk=None): page_number = request.GET.get('page') if 'size'",
"Post.objects.get(pk = post_pk) post_pk_str = post_pk if uid == None:",
"data = CommentSerializer(comment).data else: code = status.HTTP_400_BAD_REQUEST data = {}",
"request.data['auth_pk'])==True post = Post.objects.get(post_pk=post_pk) serializer = PostSerializer(post) except Exception as",
"= Author.objects.get(auth_pk=auth_pk) posts = Post.objects.filter(author_id=author, id__icontains = \"linkedspace\") code =",
"= Author.objects.get(pk=auth_pk) id = author_id.url author = json.loads(serializers.serialize('json', Author.objects.filter(pk=auth_pk), fields=('type',",
"status.HTTP_400_BAD_REQUEST post = Post.objects.all() paginator = Paginator(post, page_size) page_obj =",
"auth_pk, author=author_id, size=10, published=published, contentType=contentType, content=content) comments.save() return True else:",
"paginator.get_page(page_number) serializer = CommentSerializer(page_obj.object_list, many=True) return Response(serializer.data, code) @api_view(['GET',]) def",
"'DELETE': try: post = Post.objects.get(post_pk=post_pk) post.delete() code = status.HTTP_200_OK except",
"post = Post.objects.latest(\"published\") data = PostSerializer(post).data else: code = status.HTTP_400_BAD_REQUEST",
"form.cleaned_data['contentType'] if contentType == \"application/app\": content = request.FILES['file'].read() #Inputfile elif",
"uid = re.sub('-', '', r_uid) comment_id = getattr(post, 'comments') +",
"PostsList(request, auth_pk=None): page_number = request.GET.get('page') if 'size' in request.GET: page_size",
"request.GET.get('size') else: page_size = 5 if request.method == 'GET': try:",
"else: code = status.HTTP_200_OK posts = Post.objects.filter(id__icontains = \"linkedspace\") paginator",
"'host', 'displayName', 'url', 'github',)))[0]['fields'] post = Post.objects.get(pk = post_pk) post_pk_str",
"request.data.keys(): post.visibility = request.data['visibility'] if 'unlisted' in request.data.keys(): post.unlisted =",
"content = base64.b64encode(request.FILES['file'].read()) #Inputfile else: content = form.cleaned_data[\"text\"] author_id =",
"json import uuid import re import base64 from django.db.models import",
"else: page_size = 5 if request.method == 'GET': if auth_pk:",
"auth_pk=None): page_number = request.GET.get('page') if 'size' in request.GET: page_size =",
"= status.HTTP_404_NOT_FOUND post = Post.objects.all() paginator = Paginator(post, page_size) page_obj",
"uid=None): form = CommentForm(request.POST, request.FILES) if form.is_valid(): updateForeignAuthors() published =",
"= request.FILES['file'].read() #Inputfile elif contentType in [\"image/png\", \"image/jpeg\",]: content =",
"paginator = Paginator(post, page_size) page_obj = paginator.get_page(page_number) serializer = PostSerializer(page_obj.object_list,",
"\"context\"): like[key] = l[key] like[\"@context\"] = l[\"context\"] like[\"author\"] = json.loads(django.core.serializers.serialize('json',",
"import serializers from django.utils import timezone import requests from Posts.commentModel",
"\"likes\", \"items\": likes } return Response(response_dict) @api_view(['GET', 'POST',]) @authentication_classes([CustomAuthentication]) @permission_classes([AccessPermission])",
"from .form import PostForm from Posts.commentForm import CommentForm import json",
"request.FILES) if form.is_valid(): title = form.cleaned_data['title'] descirption = form.cleaned_data['description'] categories",
"id = id + '/posts/' + uid + \"/\" comments_id",
"post_pk_str, auth_pk_str = auth_pk, author=author_id, size=10, published=published, contentType=contentType, content=content) comments.save()",
"elif request.method == 'POST': if add_Comment(request, post_pk=request.data['Post_pk'], auth_pk=request.data['auth_pk']): code =",
"= paginator.get_page(page_number) serializer = PostSerializer(page_obj.object_list, many=True) elif request.method == 'DELETE':",
"comments = Comments.objects.filter(Post_pk_str=post_pk) post = Post.objects.get(pk=post_pk) post_id = getattr(post, 'id')",
"status.HTTP_200_OK paginator = Paginator(posts, page_size) page_obj = paginator.get_page(page_number) data =",
"== 'POST': if newPost(request, auth_pk=request.data['auth_pk']): code = status.HTTP_201_CREATED post =",
"'url', 'github',)))[0]['fields'] post = Post.objects.get(pk = post_pk) post_pk_str = post_pk",
"comment = Comments.objects.get(pk=comment_pk) if 'contentType' in request.data.keys(): comment.contentType = request.data['contentType']",
"Response(serializer.data, code) @api_view(['GET',]) def connection(request, auth_id=None): data = [] team3",
"#Inputfile else: content = form.cleaned_data[\"text\"] source = settings.SERVER_URL + \"/\"",
"Post.objects.get(post_pk = post_pk) author = Author.objects.get(pk = auth_pk) likeObjs =",
"if 'unlisted' in request.data.keys(): post.unlisted = request.data['unlisted'] if 'contentType' in",
"= {} code = status.HTTP_400_BAD_REQUEST else: code = status.HTTP_200_OK posts",
"\"type\": \"comments\", \"page\": page_number, \"size\": page_size, \"post\": post_id, \"id\": comment_id,",
"Post.objects.get(post_pk=post_pk) post.delete() code = status.HTTP_200_OK except Exception as e: print(e)",
"@authentication_classes([CustomAuthentication]) @permission_classes([AccessPermission]) def commentListView(request, post_pk, auth_pk=None): page_number = request.GET.get('page') if",
"origin=origin, description=descirption, contentType=contentType, count=0, size=10, categories=categories,visibility=visibility, unlisted=unlisted, published=published, content=content, comments=comments_id)",
"if 'contentType' in request.data.keys(): post.contentType = request.data['contentType'] if post.contentType ==",
"page_obj = paginator.get_page(page_number) serializer = CommentSerializer(page_obj.object_list, many=True) return Response(serializer.data, code)",
"fields=('type', 'id', 'host', 'displayName', 'url', 'github',)))[0]['fields'] post = Post.objects.get(pk =",
"\"page\": page_number, \"size\": page_size, \"post\": post_id, \"id\": comment_id, \"comments\": serializer.data,",
"CommentSerializer(page_obj.object_list, many=True) response_dict = { \"type\": \"comments\", \"page\": page_number, \"size\":",
"unlisted = form.cleaned_data['unlisted'] contentType = form.cleaned_data['contentType'] if contentType == \"application/app\":",
"'text' in request.data.keys(): comment.content = request.data['text'] comment.save() serializer = CommentSerializer(comment)",
"form.cleaned_data['unlisted'] contentType = form.cleaned_data['contentType'] if contentType == \"application/app\": content =",
"auth_pk: try: author = Author.objects.get(auth_pk=auth_pk) posts = Post.objects.filter(author_id=author, id__icontains =",
"= Post.objects.get(post_pk = post_pk) author = Author.objects.get(pk = auth_pk) likeObjs",
"post.unlisted = request.data['unlisted'] if 'contentType' in request.data.keys(): post.contentType = request.data['contentType']",
"'PUT', 'DELETE', ]) @authentication_classes([CustomAuthentication]) @permission_classes([AccessPermission]) def PostDetail(request, post_pk, auth_pk=None): page_number",
"5 if request.method == 'GET': if auth_pk: try: author =",
"\"application/app\": post.content = request.FILES['file'].read() #Inputfile elif post.contentType in [\"image/png\", \"image/jpeg\",]:",
"as e: print(e) code = status.HTTP_400_BAD_REQUEST post = Post.objects.all() paginator",
"likeObjs = Like.objects.filter(~Q(auth_pk = author), object = post.id) Likes =",
"request.method == 'POST': try: code = status.HTTP_200_OK comment = Comments.objects.get(pk=comment_pk)",
"5 if request.method == 'GET': try: code = status.HTTP_200_OK comment",
"+ \"comments/\" published = timezone.now() posts = Post(pk=uid, id=id, author_id=author_id,",
"page_size) page_obj = paginator.get_page(page_number) serializer = PostSerializer(page_obj.object_list, many=True) elif request.method",
"PostSerializer(page_obj.object_list, many=True).data except Exception as e: print(e) data = {}",
"source=source, origin=origin, description=descirption, contentType=contentType, count=0, size=10, categories=categories,visibility=visibility, unlisted=unlisted, published=published, content=content,",
"'id') comment_id = getattr(post, 'comments') paginator = Paginator(comments, page_size) page_obj",
"import requests from Posts.commentModel import Comments #from Posts.commentView import add_Comment",
"elif post.contentType in [\"image/png\", \"image/jpeg\",]: post.content = base64.b64encode(request.FILES['file'].read()) #Inputfile else:",
"id + \"comments/\" published = timezone.now() posts = Post(pk=uid, id=id,",
"fields=('type', 'id', 'displayName', 'host', 'url', 'github',)))[0]['fields'] likes.append(like) response_dict = {",
"uid = re.sub('-', '', r_uid) id = id + '/posts/'",
"= [] team3 = get('https://social-dis.herokuapp.com/posts', auth=('socialdistribution_t03','c404t03')) if team3.status_code == 200:",
"request.FILES['file'].read() #Inputfile elif post.contentType in [\"image/png\", \"image/jpeg\",]: post.content = base64.b64encode(request.FILES['file'].read())",
"= Comments.objects.get(pk=comment_pk) if 'contentType' in request.data.keys(): comment.contentType = request.data['contentType'] if",
"import json import uuid import re import base64 from django.db.models",
"= auth_pk, author=author_id, size=10, published=published, contentType=contentType, content=content) comments.save() return True",
"else: code = status.HTTP_400_BAD_REQUEST data = {} return Response(data, code)",
"if request.method == 'GET': try: code = status.HTTP_200_OK comment =",
"if team3.status_code == 200: data.append(team3.json()) team15 = get('https://unhindled.herokuapp.com/service/allposts/', auth=('connectionsuperuser','404connection')) if",
"= CommentForm(request.POST, request.FILES) if form.is_valid(): updateForeignAuthors() published = timezone.now() contentType",
"= json.loads(django.core.serializers.serialize('json', Author.objects.filter(id=l[\"author\"]), fields=('type', 'id', 'displayName', 'host', 'url', 'github',)))[0]['fields'] likes.append(like)",
"serializer = CommentSerializer(comment) except Exception as e: print(e) code =",
"posts = Post(pk=uid, id=id, author_id=author_id, author=author, title=title, source=source, origin=origin, description=descirption,",
"= status.HTTP_404_NOT_FOUND comment = Comments.objects.all() paginator = Paginator(comment, page_size) page_obj",
"= status.HTTP_200_OK except Exception as e: print(e) code = status.HTTP_404_NOT_FOUND",
"from django.utils import timezone import requests from Posts.commentModel import Comments",
"Post_pk_str = post_pk_str, auth_pk_str = auth_pk, author=author_id, size=10, published=published, contentType=contentType,",
"== 'GET': try: code = status.HTTP_200_OK comment = Comments.objects.get(pk=comment_pk) serializer",
"request.data.keys(): post.categories = request.data['categories'].split(' ') if 'visibility' in request.data.keys(): post.visibility",
"categories = form.cleaned_data['categories'].split(' ') visibility = form.cleaned_data['visibility'] unlisted = form.cleaned_data['unlisted']",
"traceback def newPost(request, uid=None, auth_pk=None): form = PostForm(request.POST, request.FILES) if",
"in request.GET: page_size = request.GET.get('size') else: page_size = 5 if",
"else: content = form.cleaned_data[\"text\"] source = settings.SERVER_URL + \"/\" origin",
"post.title = request.data['title'] if 'description' in request.data.keys(): post.description = request.data['description']",
"post.visibility = request.data['visibility'] if 'unlisted' in request.data.keys(): post.unlisted = request.data['unlisted']",
"key in l: if(key != \"context\"): like[key] = l[key] like[\"@context\"]",
"]) @authentication_classes([CustomAuthentication]) @permission_classes([AccessPermission]) def PostDetail(request, post_pk, auth_pk=None): page_number = request.GET.get('page')",
"like = {} for key in l: if(key != \"context\"):",
"= status.HTTP_400_BAD_REQUEST data = {} return Response(data, code) @api_view(['GET', 'POST',])",
"def PostDetail(request, post_pk, auth_pk=None): page_number = request.GET.get('page') if 'size' in",
"post = Post.objects.get(pk = post_pk) post_pk_str = post_pk if uid",
"Response from django.shortcuts import HttpResponse, render from requests import get",
"commentListView(request, post_pk, auth_pk=None): page_number = request.GET.get('page') if 'size' in request.GET:",
"PostSerializer(page_obj.object_list, many=True) return Response(serializer.data, code) @api_view(['GET', 'POST', ]) @authentication_classes([CustomAuthentication]) @permission_classes([AccessPermission])",
"base64.b64encode(request.FILES['file'].read()) #Inputfile else: content = form.cleaned_data[\"text\"] source = settings.SERVER_URL +",
"data = {} return Response(data, code) @api_view(['GET', 'POST',]) @authentication_classes([CustomAuthentication]) @permission_classes([AccessPermission])",
"= [] for l in Likes.data: like = {} for",
"status.HTTP_400_BAD_REQUEST data = {} return Response(data, code) @api_view(['GET', 'POST', 'PUT',",
"paginator.get_page(page_number) serializer = CommentSerializer(page_obj.object_list, many=True) elif request.method == 'POST': try:",
"status.HTTP_400_BAD_REQUEST comment = Comments.objects.all() paginator = Paginator(comment, page_size) page_obj =",
"Paginator(post, page_size) page_obj = paginator.get_page(page_number) serializer = PostSerializer(page_obj.object_list, many=True) return",
"= paginator.get_page(page_number) serializer = PostSerializer(page_obj.object_list, many=True) elif request.method == 'PUT':",
"try: code = status.HTTP_201_CREATED assert newPost(request, post_pk, request.data['auth_pk'])==True post =",
"print(form.data) return False def add_Comment(request, post_pk, auth_pk, uid=None): form =",
"status from rest_framework.decorators import api_view, authentication_classes, permission_classes from rest_framework.response import",
"code = status.HTTP_200_OK comment = Comments.objects.get(pk=comment_pk) if 'contentType' in request.data.keys():",
"if 'size' in request.GET: page_size = request.GET.get('size') else: page_size =",
"source = settings.SERVER_URL + \"/\" origin = settings.SERVER_URL + \"/\"",
"= status.HTTP_200_OK paginator = Paginator(posts, page_size) page_obj = paginator.get_page(page_number) data",
"= PostSerializer(page_obj.object_list, many=True) elif request.method == 'DELETE': try: post =",
"= CommentSerializer(comment) except Exception as e: print(e) code = status.HTTP_400_BAD_REQUEST",
"= re.sub('-', '', r_uid) comment_id = getattr(post, 'comments') + uid",
"if auth_pk: try: author = Author.objects.get(auth_pk=auth_pk) posts = Post.objects.filter(author_id=author, id__icontains",
"if add_Comment(request, post_pk=request.data['Post_pk'], auth_pk=request.data['auth_pk']): code = status.HTTP_202_ACCEPTED comment = Comments.objects.latest(\"published\")",
"post.contentType == \"application/app\": post.content = request.FILES['file'].read() #Inputfile elif post.contentType in",
"status.HTTP_200_OK post = Post.objects.get(post_pk=post_pk) if 'title' in request.data.keys(): post.title =",
"contentType in [\"image/png\", \"image/jpeg\",]: content = base64.b64encode(request.FILES['file'].read()) #Inputfile else: content",
"Comments.objects.get(pk=comment_pk) if 'contentType' in request.data.keys(): comment.contentType = request.data['contentType'] if 'text'",
"if(key != \"context\"): like[key] = l[key] like[\"@context\"] = l[\"context\"] like[\"author\"]",
"l: if(key != \"context\"): like[key] = l[key] like[\"@context\"] = l[\"context\"]",
"post_pk, auth_pk=None): page_number = request.GET.get('page') if 'size' in request.GET: page_size",
"Comments #from Posts.commentView import add_Comment from rest_framework import status from",
"@api_view(['GET',]) def connection(request, auth_id=None): data = [] team3 = get('https://social-dis.herokuapp.com/posts',",
"= status.HTTP_400_BAD_REQUEST else: code = status.HTTP_200_OK posts = Post.objects.filter(id__icontains =",
"auth_pk=None): form = PostForm(request.POST, request.FILES) if form.is_valid(): title = form.cleaned_data['title']",
"= PostSerializer(page_obj.object_list, many=True) elif request.method == 'PUT': try: code =",
"uuid.uuid4().hex uid = re.sub('-', '', r_uid) comment_id = getattr(post, 'comments')",
"paginator = Paginator(comments, page_size) page_obj = paginator.get_page(page_number) serializer = CommentSerializer(page_obj.object_list,",
"False @api_view(['GET',]) @authentication_classes([CustomAuthentication]) @permission_classes([AccessPermission]) def PostLikesView(request, post_pk, auth_pk): post =",
"django.core import serializers from django.utils import timezone import requests from",
"e: print(e) code = status.HTTP_400_BAD_REQUEST comment = Comments.objects.all() paginator =",
"published=published, contentType=contentType, content=content) comments.save() return True else: print(request.data) return False",
"Comments.objects.filter(Post_pk_str=post_pk) post = Post.objects.get(pk=post_pk) post_id = getattr(post, 'id') comment_id =",
"if 'categories' in request.data.keys(): post.categories = request.data['categories'].split(' ') if 'visibility'",
"CommentSerializer(comment).data else: code = status.HTTP_400_BAD_REQUEST data = {} return Response(data,",
"HttpResponse, render from requests import get from .serializers import CommentSerializer,",
"= Comments.objects.latest(\"published\") data = CommentSerializer(comment).data else: code = status.HTTP_400_BAD_REQUEST data",
"origin = settings.SERVER_URL + \"/\" author_id = Author.objects.get(pk=auth_pk) id =",
"try: code = status.HTTP_200_OK comment = Comments.objects.get(pk=comment_pk) serializer = CommentSerializer(comment)",
"= paginator.get_page(page_number) data = PostSerializer(page_obj.object_list, many=True).data except Exception as e:",
"= Comments(pk=uid, id=comment_id, Post_pk=post, Post_pk_str = post_pk_str, auth_pk_str = auth_pk,",
"\"/\" comments_id = id + \"comments/\" published = timezone.now() posts",
"comments = Comments(pk=uid, id=comment_id, Post_pk=post, Post_pk_str = post_pk_str, auth_pk_str =",
"= \"linkedspace\") paginator = Paginator(posts, page_size) page_obj = paginator.get_page(page_number) data",
"team15.status_code == 200: data.append(team15.json()) team17 = get('https://cmput404f21t17.herokuapp.com/service/connect/public/', auth=('4cbe2def-feaa-4bb7-bce5-<PASSWORD>','123456')) if team17.status_code",
"content=content) comments.save() return True else: print(request.data) return False @api_view(['GET',]) @authentication_classes([CustomAuthentication])",
"in request.data.keys(): post.unlisted = request.data['unlisted'] if 'contentType' in request.data.keys(): post.contentType",
"except Exception as e: print(e) code = status.HTTP_404_NOT_FOUND post =",
"CommentSerializer(page_obj.object_list, many=True) return Response(serializer.data, code) @api_view(['GET',]) def connection(request, auth_id=None): data",
"Post(pk=uid, id=id, author_id=author_id, author=author, title=title, source=source, origin=origin, description=descirption, contentType=contentType, count=0,",
"except Exception as e: print(e) data = {} code =",
"elif request.method == 'DELETE': try: post = Post.objects.get(post_pk=post_pk) post.delete() code",
"= paginator.get_page(page_number) serializer = CommentSerializer(page_obj.object_list, many=True) return Response(serializer.data, code) @api_view(['GET',])",
"post.contentType in [\"image/png\", \"image/jpeg\",]: post.content = base64.b64encode(request.FILES['file'].read()) #Inputfile else: post.content",
"serializer.data, } return Response(response_dict) elif request.method == 'POST': if add_Comment(request,",
"'POST', 'PUT', 'DELETE', ]) @authentication_classes([CustomAuthentication]) @permission_classes([AccessPermission]) def PostDetail(request, post_pk, auth_pk=None):",
"post = Post.objects.get(post_pk=post_pk) if 'title' in request.data.keys(): post.title = request.data['title']",
"= form.cleaned_data['visibility'] unlisted = form.cleaned_data['unlisted'] contentType = form.cleaned_data['contentType'] if contentType",
"= settings.SERVER_URL + \"/\" author_id = Author.objects.get(pk=auth_pk) id = author_id.url",
"team3.status_code == 200: data.append(team3.json()) team15 = get('https://unhindled.herokuapp.com/service/allposts/', auth=('connectionsuperuser','404connection')) if team15.status_code",
"author_id=author_id, author=author, title=title, source=source, origin=origin, description=descirption, contentType=contentType, count=0, size=10, categories=categories,visibility=visibility,",
"from django.conf import settings from django.core import serializers from django.utils",
"= PostForm(request.POST, request.FILES) if form.is_valid(): title = form.cleaned_data['title'] descirption =",
"base64.b64encode(request.FILES['file'].read()) #Inputfile else: content = form.cleaned_data[\"text\"] author_id = json.loads(serializers.serialize('json', Author.objects.filter(email=auth_pk),",
"request.method == 'POST': if newPost(request, auth_pk=request.data['auth_pk']): code = status.HTTP_201_CREATED post",
"PostSerializer(page_obj.object_list, many=True) elif request.method == 'DELETE': try: post = Post.objects.get(post_pk=post_pk)",
"page_obj = paginator.get_page(page_number) serializer = PostSerializer(page_obj.object_list, many=True) return Response(serializer.data, code)",
"in request.data.keys(): post.title = request.data['title'] if 'description' in request.data.keys(): post.description",
"\"linkedspace\") code = status.HTTP_200_OK paginator = Paginator(posts, page_size) page_obj =",
"= Post.objects.filter(author_id=author, id__icontains = \"linkedspace\") code = status.HTTP_200_OK paginator =",
"= post_pk if uid == None: r_uid = uuid.uuid4().hex uid",
"= request.data['description'] if 'categories' in request.data.keys(): post.categories = request.data['categories'].split(' ')",
"data.append(team15.json()) team17 = get('https://cmput404f21t17.herokuapp.com/service/connect/public/', auth=('4cbe2def-feaa-4bb7-bce5-<PASSWORD>','123456')) if team17.status_code == 200: data.append(team17.json())",
"request.data['categories'].split(' ') if 'visibility' in request.data.keys(): post.visibility = request.data['visibility'] if",
"if team15.status_code == 200: data.append(team15.json()) team17 = get('https://cmput404f21t17.herokuapp.com/service/connect/public/', auth=('4cbe2def-feaa-4bb7-bce5-<PASSWORD>','123456')) if",
"5 if request.method == 'GET': try: code = status.HTTP_200_OK post",
"{} return Response(data, code) @api_view(['GET', 'POST',]) @authentication_classes([CustomAuthentication]) @permission_classes([AccessPermission]) def commentListView(request,",
"serializer = CommentSerializer(page_obj.object_list, many=True) return Response(serializer.data, code) @api_view(['GET',]) def connection(request,",
"status.HTTP_202_ACCEPTED comment = Comments.objects.latest(\"published\") data = CommentSerializer(comment).data else: code =",
"comment = Comments.objects.latest(\"published\") data = CommentSerializer(comment).data else: code = status.HTTP_400_BAD_REQUEST",
"= request.GET.get('page') if 'size' in request.GET: page_size = request.GET.get('size') else:",
"posts = Post.objects.filter(id__icontains = \"linkedspace\") paginator = Paginator(posts, page_size) page_obj",
"def PostsList(request, auth_pk=None): page_number = request.GET.get('page') if 'size' in request.GET:",
"commentDetail(request, post_pk, comment_pk, auth_pk=None): page_number = request.GET.get('page') if 'size' in",
"None: r_uid = uuid.uuid4().hex uid = re.sub('-', '', r_uid) id",
"from django.core.paginator import Paginator import traceback def newPost(request, uid=None, auth_pk=None):",
"import Paginator import traceback def newPost(request, uid=None, auth_pk=None): form =",
"page_size) page_obj = paginator.get_page(page_number) serializer = CommentSerializer(page_obj.object_list, many=True) elif request.method",
"connection(request, auth_id=None): data = [] team3 = get('https://social-dis.herokuapp.com/posts', auth=('socialdistribution_t03','c404t03')) if",
"= getattr(post, 'comments') + uid comments = Comments(pk=uid, id=comment_id, Post_pk=post,",
"= form.cleaned_data[\"text\"] source = settings.SERVER_URL + \"/\" origin = settings.SERVER_URL",
"return Response(serializer.data, code) @api_view(['GET',]) def connection(request, auth_id=None): data = []",
"uid=None, auth_pk=None): form = PostForm(request.POST, request.FILES) if form.is_valid(): title =",
"== \"application/app\": content = request.FILES['file'].read() #Inputfile elif contentType in [\"image/png\",",
"in request.data.keys(): post.description = request.data['description'] if 'categories' in request.data.keys(): post.categories",
"page_size) page_obj = paginator.get_page(page_number) serializer = CommentSerializer(page_obj.object_list, many=True) response_dict =",
"= Post.objects.get(pk = post_pk) post_pk_str = post_pk if uid ==",
"from django.shortcuts import HttpResponse, render from requests import get from",
"request.data.keys(): comment.contentType = request.data['contentType'] if 'text' in request.data.keys(): comment.content =",
"code) @api_view(['GET', 'POST',]) @authentication_classes([CustomAuthentication]) @permission_classes([AccessPermission]) def commentListView(request, post_pk, auth_pk=None): page_number",
"assert newPost(request, post_pk, request.data['auth_pk'])==True post = Post.objects.get(post_pk=post_pk) serializer = PostSerializer(post)",
"getattr(post, 'comments') paginator = Paginator(comments, page_size) page_obj = paginator.get_page(page_number) serializer",
"uid comments = Comments(pk=uid, id=comment_id, Post_pk=post, Post_pk_str = post_pk_str, auth_pk_str",
"status.HTTP_200_OK posts = Post.objects.filter(id__icontains = \"linkedspace\") paginator = Paginator(posts, page_size)",
"in request.data.keys(): post.visibility = request.data['visibility'] if 'unlisted' in request.data.keys(): post.unlisted",
"post.delete() code = status.HTTP_200_OK except Exception as e: print(e) code",
"data = PostSerializer(page_obj.object_list, many=True).data elif request.method == 'POST': if newPost(request,",
"= form.cleaned_data['title'] descirption = form.cleaned_data['description'] categories = form.cleaned_data['categories'].split(' ') visibility",
"data = {} code = status.HTTP_400_BAD_REQUEST else: code = status.HTTP_200_OK",
"{} code = status.HTTP_400_BAD_REQUEST else: code = status.HTTP_200_OK posts =",
"= uuid.uuid4().hex uid = re.sub('-', '', r_uid) id = id",
"= paginator.get_page(page_number) data = PostSerializer(page_obj.object_list, many=True).data elif request.method == 'POST':",
"Author.objects.filter(id=l[\"author\"]), fields=('type', 'id', 'displayName', 'host', 'url', 'github',)))[0]['fields'] likes.append(like) response_dict =",
"comments.save() return True else: print(request.data) return False @api_view(['GET',]) @authentication_classes([CustomAuthentication]) @permission_classes([AccessPermission])",
"data = [] team3 = get('https://social-dis.herokuapp.com/posts', auth=('socialdistribution_t03','c404t03')) if team3.status_code ==",
"== 'DELETE': try: post = Post.objects.get(post_pk=post_pk) post.delete() code = status.HTTP_200_OK",
"'categories' in request.data.keys(): post.categories = request.data['categories'].split(' ') if 'visibility' in",
"paginator.get_page(page_number) serializer = CommentSerializer(page_obj.object_list, many=True) response_dict = { \"type\": \"comments\",",
"Comments.objects.all() paginator = Paginator(comment, page_size) page_obj = paginator.get_page(page_number) serializer =",
"published = timezone.now() posts = Post(pk=uid, id=id, author_id=author_id, author=author, title=title,",
"Paginator import traceback def newPost(request, uid=None, auth_pk=None): form = PostForm(request.POST,",
"r_uid) comment_id = getattr(post, 'comments') + uid comments = Comments(pk=uid,",
"PostSerializer(post).data else: code = status.HTTP_400_BAD_REQUEST data = {} return Response(data,",
"Posts.commentForm import CommentForm import json import uuid import re import",
"def commentListView(request, post_pk, auth_pk=None): page_number = request.GET.get('page') if 'size' in",
"= status.HTTP_400_BAD_REQUEST post = Post.objects.all() paginator = Paginator(post, page_size) page_obj",
"= request.data['contentType'] if post.contentType == \"application/app\": post.content = request.FILES['file'].read() #Inputfile",
"PostSerializer(page_obj.object_list, many=True) elif request.method == 'PUT': try: code = status.HTTP_201_CREATED",
"= form.cleaned_data[\"text\"] author_id = json.loads(serializers.serialize('json', Author.objects.filter(email=auth_pk), fields=('type', 'id', 'host', 'displayName',",
"request.GET.get('page') if 'size' in request.GET: page_size = request.GET.get('size') else: page_size",
"@api_view(['GET', 'POST',]) @authentication_classes([CustomAuthentication]) @permission_classes([AccessPermission]) def commentListView(request, post_pk, auth_pk=None): page_number =",
"== 'POST': if add_Comment(request, post_pk=request.data['Post_pk'], auth_pk=request.data['auth_pk']): code = status.HTTP_202_ACCEPTED comment",
"= Post.objects.latest(\"published\") data = PostSerializer(post).data else: code = status.HTTP_400_BAD_REQUEST data",
"import settings from django.core import serializers from django.utils import timezone",
"request.method == 'DELETE': try: post = Post.objects.get(post_pk=post_pk) post.delete() code =",
"like[\"author\"] = json.loads(django.core.serializers.serialize('json', Author.objects.filter(id=l[\"author\"]), fields=('type', 'id', 'displayName', 'host', 'url', 'github',)))[0]['fields']",
"'GET': if auth_pk: try: author = Author.objects.get(auth_pk=auth_pk) posts = Post.objects.filter(author_id=author,",
"= status.HTTP_202_ACCEPTED comment = Comments.objects.latest(\"published\") data = CommentSerializer(comment).data else: code",
"= LikeSerializer(likeObjs, read_only=True, many=True) likes = [] for l in",
"if 'visibility' in request.data.keys(): post.visibility = request.data['visibility'] if 'unlisted' in",
"post_pk, request.data['auth_pk'])==True post = Post.objects.get(post_pk=post_pk) serializer = PostSerializer(post) except Exception",
"#Inputfile else: content = form.cleaned_data[\"text\"] author_id = json.loads(serializers.serialize('json', Author.objects.filter(email=auth_pk), fields=('type',",
"timezone import requests from Posts.commentModel import Comments #from Posts.commentView import",
"import Response from django.shortcuts import HttpResponse, render from requests import",
"= json.loads(serializers.serialize('json', Author.objects.filter(email=auth_pk), fields=('type', 'id', 'host', 'displayName', 'url', 'github',)))[0]['fields'] post",
"getattr(post, 'comments') + uid comments = Comments(pk=uid, id=comment_id, Post_pk=post, Post_pk_str",
"'POST': if add_Comment(request, post_pk=request.data['Post_pk'], auth_pk=request.data['auth_pk']): code = status.HTTP_202_ACCEPTED comment =",
"def connection(request, auth_id=None): data = [] team3 = get('https://social-dis.herokuapp.com/posts', auth=('socialdistribution_t03','c404t03'))",
"') if 'visibility' in request.data.keys(): post.visibility = request.data['visibility'] if 'unlisted'",
"\"image/jpeg\",]: content = base64.b64encode(request.FILES['file'].read()) #Inputfile else: content = form.cleaned_data[\"text\"] source",
"request.data['title'] if 'description' in request.data.keys(): post.description = request.data['description'] if 'categories'",
"request.data.keys(): post.contentType = request.data['contentType'] if post.contentType == \"application/app\": post.content =",
"import Comments #from Posts.commentView import add_Comment from rest_framework import status",
"'DELETE', ]) @authentication_classes([CustomAuthentication]) @permission_classes([AccessPermission]) def PostDetail(request, post_pk, auth_pk=None): page_number =",
"content = form.cleaned_data[\"text\"] source = settings.SERVER_URL + \"/\" origin =",
"return True else: print(request.data) print(form.errors) print(form.data) return False def add_Comment(request,",
"'unlisted' in request.data.keys(): post.unlisted = request.data['unlisted'] if 'contentType' in request.data.keys():",
"code = status.HTTP_200_OK comment = Comments.objects.get(pk=comment_pk) serializer = CommentSerializer(comment) except",
"page_number = request.GET.get('page') if 'size' in request.GET: page_size = request.GET.get('size')",
"form.is_valid(): updateForeignAuthors() published = timezone.now() contentType = form.cleaned_data['contentType'] if contentType",
"} return Response(response_dict) elif request.method == 'POST': if add_Comment(request, post_pk=request.data['Post_pk'],",
"api_view, authentication_classes, permission_classes from rest_framework.response import Response from django.shortcuts import",
"\"image/jpeg\",]: content = base64.b64encode(request.FILES['file'].read()) #Inputfile else: content = form.cleaned_data[\"text\"] author_id",
"= {} return Response(data, code) @api_view(['GET', 'POST',]) @authentication_classes([CustomAuthentication]) @permission_classes([AccessPermission]) def",
"comment_id = getattr(post, 'comments') + uid comments = Comments(pk=uid, id=comment_id,",
"requests import get from .serializers import CommentSerializer, PostSerializer from Author.serializers",
"LikeSerializer(likeObjs, read_only=True, many=True) likes = [] for l in Likes.data:",
"author=author, title=title, source=source, origin=origin, description=descirption, contentType=contentType, count=0, size=10, categories=categories,visibility=visibility, unlisted=unlisted,",
"= post_pk) author = Author.objects.get(pk = auth_pk) likeObjs = Like.objects.filter(~Q(auth_pk",
"rest_framework.decorators import api_view, authentication_classes, permission_classes from rest_framework.response import Response from",
"published = timezone.now() contentType = form.cleaned_data['contentType'] if contentType == \"application/app\":",
"categories=categories,visibility=visibility, unlisted=unlisted, published=published, content=content, comments=comments_id) posts.save() return True else: print(request.data)",
"get from .serializers import CommentSerializer, PostSerializer from Author.serializers import LikeSerializer",
"author = json.loads(serializers.serialize('json', Author.objects.filter(pk=auth_pk), fields=('type', 'id', 'host', 'displayName', 'url', 'github',)))[0]['fields']"
] |
[
"0.2]], [[0.05, 0.1], [-0.9, 0.05]]]], dims = ('t','y','x','band'), reduce_by =",
"return _construct @pytest.fixture def execute_array_element_process(generate_data): def wrapped(data_arguments={}, index=None, return_nodata=None): arguments",
"({}, 5, [[[np.nan, np.nan], [np.nan, np.nan]]], ('t','y','x')), ]) def test_with_xarray_out_bounds_return_nodata(execute_array_element_process,",
"return xrdata return _construct @pytest.fixture def execute_array_element_process(generate_data): def wrapped(data_arguments={}, index=None,",
"dims = ('t','y','x','band'), reduce_by = \"band\", as_list = False ):",
"execute_array_element_process(data_arguments=data_arguments, index=index, return_nodata=return_nodata) assert result == expected_result @pytest.mark.parametrize('data,index,reduce_by,expected_data,expected_dims', [ ([[[[0.1,",
"\"\"\" Test array_element process with xarray.DataArrays \"\"\" expected_result = generate_data(data=expected_data,",
"return_no_data \"\"\" expected_result = generate_data(expected_data, dims=expected_dims) result = execute_array_element_process(data_arguments=data_arguments, index=index,",
"is not None: arguments[\"index\"] = index if return_nodata is not",
"index, reduce_by, expected_data, expected_dims): \"\"\" Test array_element process with xarray.DataArrays",
"= generate_data(expected_data, dims=expected_dims) result = execute_array_element_process(data_arguments=data_arguments, index=index, return_nodata=True) xr.testing.assert_equal(result, expected_result)",
"expected_result): \"\"\" Test array_element process with examples from https://open-eo.github.io/openeo-api/processreference/#array_element \"\"\"",
"'index' in process 'array_element' is invalid: Index out of bounds.\"",
"([[[[0.1, 0.15], [0.15, 0.2]], [[0.05, 0.1], [-0.9, 0.05]]]], 1, \"y\",",
"0.15], [0.15, 0.2]], [[0.05, 0.1], [-0.9, 0.05]]]], 0, \"band\", [[[0.1,",
"False ): if as_list: return data xrdata = xr.DataArray( data,",
"sys, os import xarray as xr import numpy as np",
"('t','y','x')), ]) def test_with_xarray_out_bounds_return_nodata(execute_array_element_process, generate_data, data_arguments, index, expected_data, expected_dims): \"\"\"",
"with xarray.DataArrays with out of bounds index and return_no_data \"\"\"",
"if return_nodata is not None: arguments[\"return_nodata\"] = return_nodata return process.array_element.array_elementEOTask(None,",
"0.1], [-0.9, 0.05]]]], 0, \"band\", [[[0.1, 0.15], [0.05, -0.9]]], ('t','y','x')),",
"Test array_element process with examples from https://open-eo.github.io/openeo-api/processreference/#array_element \"\"\" data_arguments =",
"@pytest.mark.parametrize('data,return_nodata,index,expected_result', [ ([9,8,7,6,5], None, 2, 7), ([\"A\",\"B\",\"C\"], None, 0, \"A\"),",
"index, expected_data, expected_dims): \"\"\" Test array_element process with xarray.DataArrays with",
"index, return_nodata, expected_result): \"\"\" Test array_element process with examples from",
"expected_data, expected_dims): \"\"\" Test array_element process with xarray.DataArrays \"\"\" expected_result",
"= index if return_nodata is not None: arguments[\"return_nodata\"] = return_nodata",
"of bounds.\" @pytest.mark.parametrize('data_arguments,index,expected_data,expected_dims', [ ({}, 5, [[[np.nan, np.nan], [np.nan, np.nan]]],",
"5, [[[np.nan, np.nan], [np.nan, np.nan]]], ('t','y','x')), ]) def test_with_xarray_out_bounds_return_nodata(execute_array_element_process, generate_data,",
"tests: ################################### @pytest.mark.parametrize('data,return_nodata,index,expected_result', [ ([9,8,7,6,5], None, 2, 7), ([\"A\",\"B\",\"C\"], None,",
"= ('t','y','x','band'), reduce_by = \"band\", as_list = False ): if",
"array_element process with xarray.DataArrays \"\"\" expected_result = generate_data(data=expected_data, dims=expected_dims, reduce_by=reduce_by)",
"generate_data(**data_arguments) if index is not None: arguments[\"index\"] = index if",
"\"\"\" Test array_element process with examples from https://open-eo.github.io/openeo-api/processreference/#array_element \"\"\" data_arguments",
"def execute_array_element_process(generate_data): def wrapped(data_arguments={}, index=None, return_nodata=None): arguments = {} if",
"as_list: return data xrdata = xr.DataArray( data, dims=dims, attrs={'reduce_by': [reduce_by]},",
"pytest.raises(ProcessArgumentInvalid) as ex: result = execute_array_element_process(index=5) assert ex.value.args[0] == \"The",
"array_element process with xarray.DataArrays with out of bounds index and",
"xarray.DataArrays \"\"\" expected_result = generate_data(data=expected_data, dims=expected_dims, reduce_by=reduce_by) result = execute_array_element_process(data_arguments={\"data\":",
"'array_element' is invalid: Index out of bounds.\" @pytest.mark.parametrize('data_arguments,index,expected_data,expected_dims', [ ({},",
"################################### # tests: ################################### @pytest.mark.parametrize('data,return_nodata,index,expected_result', [ ([9,8,7,6,5], None, 2, 7),",
"0.15], [0.05, -0.9]]], ('t','y','x')), ([[[[0.1, 0.15], [0.15, 0.2]], [[0.05, 0.1],",
"process 'array_element' is invalid: Index out of bounds.\" @pytest.mark.parametrize('data_arguments,index,expected_data,expected_dims', [",
"xarray as xr import numpy as np sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) import process",
"is invalid: Index out of bounds.\" @pytest.mark.parametrize('data_arguments,index,expected_data,expected_dims', [ ({}, 5,",
"Index out of bounds.\" @pytest.mark.parametrize('data_arguments,index,expected_data,expected_dims', [ ({}, 5, [[[np.nan, np.nan],",
"= \"band\", as_list = False ): if as_list: return data",
"@pytest.mark.parametrize('data_arguments,index,expected_data,expected_dims', [ ({}, 5, [[[np.nan, np.nan], [np.nan, np.nan]]], ('t','y','x')), ])",
"import numpy as np sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) import process from process._common import",
"out of bounds index and return_no_data \"\"\" expected_result = generate_data(expected_data,",
"data, dims=dims, attrs={'reduce_by': [reduce_by]}, ) return xrdata return _construct @pytest.fixture",
"xarray.DataArrays with out of bounds index \"\"\" with pytest.raises(ProcessArgumentInvalid) as",
"import xarray as xr import numpy as np sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) import",
"1, \"y\", [[[0.05, 0.1], [-0.9, 0.05]]], ('t','x','band')), ]) def test_with_xarray(execute_array_element_process,",
"bounds.\" @pytest.mark.parametrize('data_arguments,index,expected_data,expected_dims', [ ({}, 5, [[[np.nan, np.nan], [np.nan, np.nan]]], ('t','y','x')),",
"process from process._common import ProcessArgumentInvalid, ProcessArgumentRequired @pytest.fixture def generate_data(): def",
"[reduce_by]}, ) return xrdata return _construct @pytest.fixture def execute_array_element_process(generate_data): def",
"return process.array_element.array_elementEOTask(None, \"\" , None, {}, \"arrayel1\").process(arguments) return wrapped ###################################",
"process._common import ProcessArgumentInvalid, ProcessArgumentRequired @pytest.fixture def generate_data(): def _construct( data",
"index=index, return_nodata=return_nodata) assert result == expected_result @pytest.mark.parametrize('data,index,reduce_by,expected_data,expected_dims', [ ([[[[0.1, 0.15],",
"[[0.05, 0.1], [-0.9, 0.05]]]], 0, \"band\", [[[0.1, 0.15], [0.05, -0.9]]],",
"0.05]]]], 1, \"y\", [[[0.05, 0.1], [-0.9, 0.05]]], ('t','x','band')), ]) def",
"process with xarray.DataArrays \"\"\" expected_result = generate_data(data=expected_data, dims=expected_dims, reduce_by=reduce_by) result",
"test_examples(execute_array_element_process, data, index, return_nodata, expected_result): \"\"\" Test array_element process with",
"return data xrdata = xr.DataArray( data, dims=dims, attrs={'reduce_by': [reduce_by]}, )",
"None) ]) def test_examples(execute_array_element_process, data, index, return_nodata, expected_result): \"\"\" Test",
"<reponame>Open-EO/openeo-sentinelhub-python-driver import pytest import sys, os import xarray as xr",
"out of bounds.\" @pytest.mark.parametrize('data_arguments,index,expected_data,expected_dims', [ ({}, 5, [[[np.nan, np.nan], [np.nan,",
"\"as_list\": True} result = execute_array_element_process(data_arguments=data_arguments, index=index, return_nodata=return_nodata) assert result ==",
"sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) import process from process._common import ProcessArgumentInvalid, ProcessArgumentRequired @pytest.fixture def",
"('t','y','x')), ([[[[0.1, 0.15], [0.15, 0.2]], [[0.05, 0.1], [-0.9, 0.05]]]], 1,",
"xarray.DataArrays with out of bounds index and return_no_data \"\"\" expected_result",
"0, None) ]) def test_examples(execute_array_element_process, data, index, return_nodata, expected_result): \"\"\"",
"from process._common import ProcessArgumentInvalid, ProcessArgumentRequired @pytest.fixture def generate_data(): def _construct(",
"('t','y','x','band'), reduce_by = \"band\", as_list = False ): if as_list:",
"import sys, os import xarray as xr import numpy as",
"reduce_by=reduce_by) result = execute_array_element_process(data_arguments={\"data\": data, \"reduce_by\": reduce_by}, index=index) xr.testing.assert_allclose(result, expected_result)",
"[-0.9, 0.05]]]], dims = ('t','y','x','band'), reduce_by = \"band\", as_list =",
"== \"The argument 'index' in process 'array_element' is invalid: Index",
"]) def test_with_xarray(execute_array_element_process, generate_data, data, index, reduce_by, expected_data, expected_dims): \"\"\"",
"[0.15, 0.2]], [[0.05, 0.1], [-0.9, 0.05]]]], 0, \"band\", [[[0.1, 0.15],",
"os import xarray as xr import numpy as np sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))",
"= execute_array_element_process(data_arguments={\"data\": data, \"reduce_by\": reduce_by}, index=index) xr.testing.assert_allclose(result, expected_result) def test_with_xarray_out_bounds(execute_array_element_process,",
"= execute_array_element_process(index=5) assert ex.value.args[0] == \"The argument 'index' in process",
"\"\"\" Test array_element process with xarray.DataArrays with out of bounds",
"expected_result) def test_with_xarray_out_bounds(execute_array_element_process, generate_data): \"\"\" Test array_element process with xarray.DataArrays",
"[ ([9,8,7,6,5], None, 2, 7), ([\"A\",\"B\",\"C\"], None, 0, \"A\"), ([],",
"def test_examples(execute_array_element_process, data, index, return_nodata, expected_result): \"\"\" Test array_element process",
"= False ): if as_list: return data xrdata = xr.DataArray(",
"[ ([[[[0.1, 0.15], [0.15, 0.2]], [[0.05, 0.1], [-0.9, 0.05]]]], 0,",
"np sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) import process from process._common import ProcessArgumentInvalid, ProcessArgumentRequired @pytest.fixture",
"execute_array_element_process(data_arguments={\"data\": data, \"reduce_by\": reduce_by}, index=index) xr.testing.assert_allclose(result, expected_result) def test_with_xarray_out_bounds(execute_array_element_process, generate_data):",
"ex: result = execute_array_element_process(index=5) assert ex.value.args[0] == \"The argument 'index'",
"as xr import numpy as np sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) import process from",
"reduce_by, expected_data, expected_dims): \"\"\" Test array_element process with xarray.DataArrays \"\"\"",
"xrdata return _construct @pytest.fixture def execute_array_element_process(generate_data): def wrapped(data_arguments={}, index=None, return_nodata=None):",
"data, index, return_nodata, expected_result): \"\"\" Test array_element process with examples",
"result == expected_result @pytest.mark.parametrize('data,index,reduce_by,expected_data,expected_dims', [ ([[[[0.1, 0.15], [0.15, 0.2]], [[0.05,",
"of bounds index \"\"\" with pytest.raises(ProcessArgumentInvalid) as ex: result =",
"process with xarray.DataArrays with out of bounds index and return_no_data",
"]) def test_examples(execute_array_element_process, data, index, return_nodata, expected_result): \"\"\" Test array_element",
"0.1], [-0.9, 0.05]]]], dims = ('t','y','x','band'), reduce_by = \"band\", as_list",
"ProcessArgumentRequired @pytest.fixture def generate_data(): def _construct( data = [[[[0.1, 0.15],",
"result = execute_array_element_process(index=5) assert ex.value.args[0] == \"The argument 'index' in",
"def _construct( data = [[[[0.1, 0.15], [0.15, 0.2]], [[0.05, 0.1],",
"@pytest.fixture def execute_array_element_process(generate_data): def wrapped(data_arguments={}, index=None, return_nodata=None): arguments = {}",
"index \"\"\" with pytest.raises(ProcessArgumentInvalid) as ex: result = execute_array_element_process(index=5) assert",
"wrapped ################################### # tests: ################################### @pytest.mark.parametrize('data,return_nodata,index,expected_result', [ ([9,8,7,6,5], None, 2,",
"assert ex.value.args[0] == \"The argument 'index' in process 'array_element' is",
"{\"data\": data, \"as_list\": True} result = execute_array_element_process(data_arguments=data_arguments, index=index, return_nodata=return_nodata) assert",
"ex.value.args[0] == \"The argument 'index' in process 'array_element' is invalid:",
"argument 'index' in process 'array_element' is invalid: Index out of",
"https://open-eo.github.io/openeo-api/processreference/#array_element \"\"\" data_arguments = {\"data\": data, \"as_list\": True} result =",
"invalid: Index out of bounds.\" @pytest.mark.parametrize('data_arguments,index,expected_data,expected_dims', [ ({}, 5, [[[np.nan,",
"as np sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) import process from process._common import ProcessArgumentInvalid, ProcessArgumentRequired",
"if data_arguments is not None: arguments[\"data\"] = generate_data(**data_arguments) if index",
"= generate_data(**data_arguments) if index is not None: arguments[\"index\"] = index",
"xrdata = xr.DataArray( data, dims=dims, attrs={'reduce_by': [reduce_by]}, ) return xrdata",
"\"arrayel1\").process(arguments) return wrapped ################################### # tests: ################################### @pytest.mark.parametrize('data,return_nodata,index,expected_result', [ ([9,8,7,6,5],",
"as ex: result = execute_array_element_process(index=5) assert ex.value.args[0] == \"The argument",
"with pytest.raises(ProcessArgumentInvalid) as ex: result = execute_array_element_process(index=5) assert ex.value.args[0] ==",
"generate_data): \"\"\" Test array_element process with xarray.DataArrays with out of",
"[[[0.05, 0.1], [-0.9, 0.05]]], ('t','x','band')), ]) def test_with_xarray(execute_array_element_process, generate_data, data,",
"bounds index \"\"\" with pytest.raises(ProcessArgumentInvalid) as ex: result = execute_array_element_process(index=5)",
"xr.testing.assert_allclose(result, expected_result) def test_with_xarray_out_bounds(execute_array_element_process, generate_data): \"\"\" Test array_element process with",
"return_nodata=return_nodata) assert result == expected_result @pytest.mark.parametrize('data,index,reduce_by,expected_data,expected_dims', [ ([[[[0.1, 0.15], [0.15,",
"np.nan]]], ('t','y','x')), ]) def test_with_xarray_out_bounds_return_nodata(execute_array_element_process, generate_data, data_arguments, index, expected_data, expected_dims):",
"data, \"as_list\": True} result = execute_array_element_process(data_arguments=data_arguments, index=index, return_nodata=return_nodata) assert result",
"\"band\", [[[0.1, 0.15], [0.05, -0.9]]], ('t','y','x')), ([[[[0.1, 0.15], [0.15, 0.2]],",
"0.2]], [[0.05, 0.1], [-0.9, 0.05]]]], 1, \"y\", [[[0.05, 0.1], [-0.9,",
"[[[[0.1, 0.15], [0.15, 0.2]], [[0.05, 0.1], [-0.9, 0.05]]]], dims =",
"0, \"band\", [[[0.1, 0.15], [0.05, -0.9]]], ('t','y','x')), ([[[[0.1, 0.15], [0.15,",
"None: arguments[\"index\"] = index if return_nodata is not None: arguments[\"return_nodata\"]",
"data, index, reduce_by, expected_data, expected_dims): \"\"\" Test array_element process with",
"result = execute_array_element_process(data_arguments={\"data\": data, \"reduce_by\": reduce_by}, index=index) xr.testing.assert_allclose(result, expected_result) def",
"with xarray.DataArrays with out of bounds index \"\"\" with pytest.raises(ProcessArgumentInvalid)",
"]) def test_with_xarray_out_bounds_return_nodata(execute_array_element_process, generate_data, data_arguments, index, expected_data, expected_dims): \"\"\" Test",
"import process from process._common import ProcessArgumentInvalid, ProcessArgumentRequired @pytest.fixture def generate_data():",
"dims=dims, attrs={'reduce_by': [reduce_by]}, ) return xrdata return _construct @pytest.fixture def",
"== expected_result @pytest.mark.parametrize('data,index,reduce_by,expected_data,expected_dims', [ ([[[[0.1, 0.15], [0.15, 0.2]], [[0.05, 0.1],",
"generate_data(data=expected_data, dims=expected_dims, reduce_by=reduce_by) result = execute_array_element_process(data_arguments={\"data\": data, \"reduce_by\": reduce_by}, index=index)",
"with examples from https://open-eo.github.io/openeo-api/processreference/#array_element \"\"\" data_arguments = {\"data\": data, \"as_list\":",
"([[[[0.1, 0.15], [0.15, 0.2]], [[0.05, 0.1], [-0.9, 0.05]]]], 0, \"band\",",
"\"\"\" expected_result = generate_data(data=expected_data, dims=expected_dims, reduce_by=reduce_by) result = execute_array_element_process(data_arguments={\"data\": data,",
"7), ([\"A\",\"B\",\"C\"], None, 0, \"A\"), ([], True, 0, None) ])",
"def test_with_xarray_out_bounds_return_nodata(execute_array_element_process, generate_data, data_arguments, index, expected_data, expected_dims): \"\"\" Test array_element",
"Test array_element process with xarray.DataArrays \"\"\" expected_result = generate_data(data=expected_data, dims=expected_dims,",
"\"\"\" expected_result = generate_data(expected_data, dims=expected_dims) result = execute_array_element_process(data_arguments=data_arguments, index=index, return_nodata=True)",
"in process 'array_element' is invalid: Index out of bounds.\" @pytest.mark.parametrize('data_arguments,index,expected_data,expected_dims',",
"([9,8,7,6,5], None, 2, 7), ([\"A\",\"B\",\"C\"], None, 0, \"A\"), ([], True,",
"execute_array_element_process(index=5) assert ex.value.args[0] == \"The argument 'index' in process 'array_element'",
"0.1], [-0.9, 0.05]]], ('t','x','band')), ]) def test_with_xarray(execute_array_element_process, generate_data, data, index,",
"data xrdata = xr.DataArray( data, dims=dims, attrs={'reduce_by': [reduce_by]}, ) return",
"arguments = {} if data_arguments is not None: arguments[\"data\"] =",
"ProcessArgumentInvalid, ProcessArgumentRequired @pytest.fixture def generate_data(): def _construct( data = [[[[0.1,",
"_construct( data = [[[[0.1, 0.15], [0.15, 0.2]], [[0.05, 0.1], [-0.9,",
"[[0.05, 0.1], [-0.9, 0.05]]]], 1, \"y\", [[[0.05, 0.1], [-0.9, 0.05]]],",
"return_nodata is not None: arguments[\"return_nodata\"] = return_nodata return process.array_element.array_elementEOTask(None, \"\"",
"([\"A\",\"B\",\"C\"], None, 0, \"A\"), ([], True, 0, None) ]) def",
"('t','x','band')), ]) def test_with_xarray(execute_array_element_process, generate_data, data, index, reduce_by, expected_data, expected_dims):",
"dims=expected_dims, reduce_by=reduce_by) result = execute_array_element_process(data_arguments={\"data\": data, \"reduce_by\": reduce_by}, index=index) xr.testing.assert_allclose(result,",
"0.15], [0.15, 0.2]], [[0.05, 0.1], [-0.9, 0.05]]]], dims = ('t','y','x','band'),",
"attrs={'reduce_by': [reduce_by]}, ) return xrdata return _construct @pytest.fixture def execute_array_element_process(generate_data):",
"is not None: arguments[\"return_nodata\"] = return_nodata return process.array_element.array_elementEOTask(None, \"\" ,",
"array_element process with examples from https://open-eo.github.io/openeo-api/processreference/#array_element \"\"\" data_arguments = {\"data\":",
"index is not None: arguments[\"index\"] = index if return_nodata is",
", None, {}, \"arrayel1\").process(arguments) return wrapped ################################### # tests: ###################################",
"data, \"reduce_by\": reduce_by}, index=index) xr.testing.assert_allclose(result, expected_result) def test_with_xarray_out_bounds(execute_array_element_process, generate_data): \"\"\"",
"def test_with_xarray_out_bounds(execute_array_element_process, generate_data): \"\"\" Test array_element process with xarray.DataArrays with",
"test_with_xarray_out_bounds(execute_array_element_process, generate_data): \"\"\" Test array_element process with xarray.DataArrays with out",
"is not None: arguments[\"data\"] = generate_data(**data_arguments) if index is not",
"None: arguments[\"return_nodata\"] = return_nodata return process.array_element.array_elementEOTask(None, \"\" , None, {},",
"data_arguments, index, expected_data, expected_dims): \"\"\" Test array_element process with xarray.DataArrays",
"result = execute_array_element_process(data_arguments=data_arguments, index=index, return_nodata=return_nodata) assert result == expected_result @pytest.mark.parametrize('data,index,reduce_by,expected_data,expected_dims',",
"process.array_element.array_elementEOTask(None, \"\" , None, {}, \"arrayel1\").process(arguments) return wrapped ################################### #",
"True} result = execute_array_element_process(data_arguments=data_arguments, index=index, return_nodata=return_nodata) assert result == expected_result",
"import pytest import sys, os import xarray as xr import",
"0.2]], [[0.05, 0.1], [-0.9, 0.05]]]], 0, \"band\", [[[0.1, 0.15], [0.05,",
"return_nodata, expected_result): \"\"\" Test array_element process with examples from https://open-eo.github.io/openeo-api/processreference/#array_element",
"test_with_xarray(execute_array_element_process, generate_data, data, index, reduce_by, expected_data, expected_dims): \"\"\" Test array_element",
"of bounds index and return_no_data \"\"\" expected_result = generate_data(expected_data, dims=expected_dims)",
"\"band\", as_list = False ): if as_list: return data xrdata",
"arguments[\"index\"] = index if return_nodata is not None: arguments[\"return_nodata\"] =",
"([], True, 0, None) ]) def test_examples(execute_array_element_process, data, index, return_nodata,",
"= [[[[0.1, 0.15], [0.15, 0.2]], [[0.05, 0.1], [-0.9, 0.05]]]], dims",
"from https://open-eo.github.io/openeo-api/processreference/#array_element \"\"\" data_arguments = {\"data\": data, \"as_list\": True} result",
"[-0.9, 0.05]]]], 0, \"band\", [[[0.1, 0.15], [0.05, -0.9]]], ('t','y','x')), ([[[[0.1,",
"reduce_by = \"band\", as_list = False ): if as_list: return",
"): if as_list: return data xrdata = xr.DataArray( data, dims=dims,",
"generate_data, data, index, reduce_by, expected_data, expected_dims): \"\"\" Test array_element process",
"\"reduce_by\": reduce_by}, index=index) xr.testing.assert_allclose(result, expected_result) def test_with_xarray_out_bounds(execute_array_element_process, generate_data): \"\"\" Test",
"-0.9]]], ('t','y','x')), ([[[[0.1, 0.15], [0.15, 0.2]], [[0.05, 0.1], [-0.9, 0.05]]]],",
"execute_array_element_process(generate_data): def wrapped(data_arguments={}, index=None, return_nodata=None): arguments = {} if data_arguments",
"data_arguments is not None: arguments[\"data\"] = generate_data(**data_arguments) if index is",
"wrapped(data_arguments={}, index=None, return_nodata=None): arguments = {} if data_arguments is not",
"test_with_xarray_out_bounds_return_nodata(execute_array_element_process, generate_data, data_arguments, index, expected_data, expected_dims): \"\"\" Test array_element process",
"_construct @pytest.fixture def execute_array_element_process(generate_data): def wrapped(data_arguments={}, index=None, return_nodata=None): arguments =",
"data = [[[[0.1, 0.15], [0.15, 0.2]], [[0.05, 0.1], [-0.9, 0.05]]]],",
"expected_data, expected_dims): \"\"\" Test array_element process with xarray.DataArrays with out",
"xr.DataArray( data, dims=dims, attrs={'reduce_by': [reduce_by]}, ) return xrdata return _construct",
"################################### @pytest.mark.parametrize('data,return_nodata,index,expected_result', [ ([9,8,7,6,5], None, 2, 7), ([\"A\",\"B\",\"C\"], None, 0,",
"index and return_no_data \"\"\" expected_result = generate_data(expected_data, dims=expected_dims) result =",
"None, 0, \"A\"), ([], True, 0, None) ]) def test_examples(execute_array_element_process,",
"if as_list: return data xrdata = xr.DataArray( data, dims=dims, attrs={'reduce_by':",
"@pytest.fixture def generate_data(): def _construct( data = [[[[0.1, 0.15], [0.15,",
"[0.15, 0.2]], [[0.05, 0.1], [-0.9, 0.05]]]], 1, \"y\", [[[0.05, 0.1],",
"None: arguments[\"data\"] = generate_data(**data_arguments) if index is not None: arguments[\"index\"]",
"\"\" , None, {}, \"arrayel1\").process(arguments) return wrapped ################################### # tests:",
"None, 2, 7), ([\"A\",\"B\",\"C\"], None, 0, \"A\"), ([], True, 0,",
"[[0.05, 0.1], [-0.9, 0.05]]]], dims = ('t','y','x','band'), reduce_by = \"band\",",
"2, 7), ([\"A\",\"B\",\"C\"], None, 0, \"A\"), ([], True, 0, None)",
"data_arguments = {\"data\": data, \"as_list\": True} result = execute_array_element_process(data_arguments=data_arguments, index=index,",
"\"\"\" data_arguments = {\"data\": data, \"as_list\": True} result = execute_array_element_process(data_arguments=data_arguments,",
"array_element process with xarray.DataArrays with out of bounds index \"\"\"",
"numpy as np sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) import process from process._common import ProcessArgumentInvalid,",
"index=None, return_nodata=None): arguments = {} if data_arguments is not None:",
"process with xarray.DataArrays with out of bounds index \"\"\" with",
"def wrapped(data_arguments={}, index=None, return_nodata=None): arguments = {} if data_arguments is",
"not None: arguments[\"index\"] = index if return_nodata is not None:",
"return_nodata return process.array_element.array_elementEOTask(None, \"\" , None, {}, \"arrayel1\").process(arguments) return wrapped",
"as_list = False ): if as_list: return data xrdata =",
") return xrdata return _construct @pytest.fixture def execute_array_element_process(generate_data): def wrapped(data_arguments={},",
"# tests: ################################### @pytest.mark.parametrize('data,return_nodata,index,expected_result', [ ([9,8,7,6,5], None, 2, 7), ([\"A\",\"B\",\"C\"],",
"examples from https://open-eo.github.io/openeo-api/processreference/#array_element \"\"\" data_arguments = {\"data\": data, \"as_list\": True}",
"not None: arguments[\"data\"] = generate_data(**data_arguments) if index is not None:",
"0.05]]]], 0, \"band\", [[[0.1, 0.15], [0.05, -0.9]]], ('t','y','x')), ([[[[0.1, 0.15],",
"= execute_array_element_process(data_arguments=data_arguments, index=index, return_nodata=return_nodata) assert result == expected_result @pytest.mark.parametrize('data,index,reduce_by,expected_data,expected_dims', [",
"[[[0.1, 0.15], [0.05, -0.9]]], ('t','y','x')), ([[[[0.1, 0.15], [0.15, 0.2]], [[0.05,",
"0.1], [-0.9, 0.05]]]], 1, \"y\", [[[0.05, 0.1], [-0.9, 0.05]]], ('t','x','band')),",
"reduce_by}, index=index) xr.testing.assert_allclose(result, expected_result) def test_with_xarray_out_bounds(execute_array_element_process, generate_data): \"\"\" Test array_element",
"xr import numpy as np sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) import process from process._common",
"= return_nodata return process.array_element.array_elementEOTask(None, \"\" , None, {}, \"arrayel1\").process(arguments) return",
"0.15], [0.15, 0.2]], [[0.05, 0.1], [-0.9, 0.05]]]], 1, \"y\", [[[0.05,",
"[-0.9, 0.05]]]], 1, \"y\", [[[0.05, 0.1], [-0.9, 0.05]]], ('t','x','band')), ])",
"Test array_element process with xarray.DataArrays with out of bounds index",
"process with examples from https://open-eo.github.io/openeo-api/processreference/#array_element \"\"\" data_arguments = {\"data\": data,",
"out of bounds index \"\"\" with pytest.raises(ProcessArgumentInvalid) as ex: result",
"return_nodata=None): arguments = {} if data_arguments is not None: arguments[\"data\"]",
"\"The argument 'index' in process 'array_element' is invalid: Index out",
"np.nan], [np.nan, np.nan]]], ('t','y','x')), ]) def test_with_xarray_out_bounds_return_nodata(execute_array_element_process, generate_data, data_arguments, index,",
"= generate_data(data=expected_data, dims=expected_dims, reduce_by=reduce_by) result = execute_array_element_process(data_arguments={\"data\": data, \"reduce_by\": reduce_by},",
"generate_data, data_arguments, index, expected_data, expected_dims): \"\"\" Test array_element process with",
"[0.15, 0.2]], [[0.05, 0.1], [-0.9, 0.05]]]], dims = ('t','y','x','band'), reduce_by",
"0.05]]]], dims = ('t','y','x','band'), reduce_by = \"band\", as_list = False",
"expected_result = generate_data(data=expected_data, dims=expected_dims, reduce_by=reduce_by) result = execute_array_element_process(data_arguments={\"data\": data, \"reduce_by\":",
"arguments[\"return_nodata\"] = return_nodata return process.array_element.array_elementEOTask(None, \"\" , None, {}, \"arrayel1\").process(arguments)",
"expected_result = generate_data(expected_data, dims=expected_dims) result = execute_array_element_process(data_arguments=data_arguments, index=index, return_nodata=True) xr.testing.assert_equal(result,",
"expected_dims): \"\"\" Test array_element process with xarray.DataArrays \"\"\" expected_result =",
"def test_with_xarray(execute_array_element_process, generate_data, data, index, reduce_by, expected_data, expected_dims): \"\"\" Test",
"assert result == expected_result @pytest.mark.parametrize('data,index,reduce_by,expected_data,expected_dims', [ ([[[[0.1, 0.15], [0.15, 0.2]],",
"with out of bounds index and return_no_data \"\"\" expected_result =",
"= {} if data_arguments is not None: arguments[\"data\"] = generate_data(**data_arguments)",
"[[[np.nan, np.nan], [np.nan, np.nan]]], ('t','y','x')), ]) def test_with_xarray_out_bounds_return_nodata(execute_array_element_process, generate_data, data_arguments,",
"expected_result @pytest.mark.parametrize('data,index,reduce_by,expected_data,expected_dims', [ ([[[[0.1, 0.15], [0.15, 0.2]], [[0.05, 0.1], [-0.9,",
"\"A\"), ([], True, 0, None) ]) def test_examples(execute_array_element_process, data, index,",
"index if return_nodata is not None: arguments[\"return_nodata\"] = return_nodata return",
"and return_no_data \"\"\" expected_result = generate_data(expected_data, dims=expected_dims) result = execute_array_element_process(data_arguments=data_arguments,",
"\"\"\" with pytest.raises(ProcessArgumentInvalid) as ex: result = execute_array_element_process(index=5) assert ex.value.args[0]",
"= xr.DataArray( data, dims=dims, attrs={'reduce_by': [reduce_by]}, ) return xrdata return",
"{} if data_arguments is not None: arguments[\"data\"] = generate_data(**data_arguments) if",
"= {\"data\": data, \"as_list\": True} result = execute_array_element_process(data_arguments=data_arguments, index=index, return_nodata=return_nodata)",
"def generate_data(): def _construct( data = [[[[0.1, 0.15], [0.15, 0.2]],",
"None, {}, \"arrayel1\").process(arguments) return wrapped ################################### # tests: ################################### @pytest.mark.parametrize('data,return_nodata,index,expected_result',",
"{}, \"arrayel1\").process(arguments) return wrapped ################################### # tests: ################################### @pytest.mark.parametrize('data,return_nodata,index,expected_result', [",
"0, \"A\"), ([], True, 0, None) ]) def test_examples(execute_array_element_process, data,",
"arguments[\"data\"] = generate_data(**data_arguments) if index is not None: arguments[\"index\"] =",
"generate_data(): def _construct( data = [[[[0.1, 0.15], [0.15, 0.2]], [[0.05,",
"[0.05, -0.9]]], ('t','y','x')), ([[[[0.1, 0.15], [0.15, 0.2]], [[0.05, 0.1], [-0.9,",
"with out of bounds index \"\"\" with pytest.raises(ProcessArgumentInvalid) as ex:",
"index=index) xr.testing.assert_allclose(result, expected_result) def test_with_xarray_out_bounds(execute_array_element_process, generate_data): \"\"\" Test array_element process",
"import ProcessArgumentInvalid, ProcessArgumentRequired @pytest.fixture def generate_data(): def _construct( data =",
"[ ({}, 5, [[[np.nan, np.nan], [np.nan, np.nan]]], ('t','y','x')), ]) def",
"with xarray.DataArrays \"\"\" expected_result = generate_data(data=expected_data, dims=expected_dims, reduce_by=reduce_by) result =",
"[np.nan, np.nan]]], ('t','y','x')), ]) def test_with_xarray_out_bounds_return_nodata(execute_array_element_process, generate_data, data_arguments, index, expected_data,",
"return wrapped ################################### # tests: ################################### @pytest.mark.parametrize('data,return_nodata,index,expected_result', [ ([9,8,7,6,5], None,",
"expected_dims): \"\"\" Test array_element process with xarray.DataArrays with out of",
"[-0.9, 0.05]]], ('t','x','band')), ]) def test_with_xarray(execute_array_element_process, generate_data, data, index, reduce_by,",
"if index is not None: arguments[\"index\"] = index if return_nodata",
"bounds index and return_no_data \"\"\" expected_result = generate_data(expected_data, dims=expected_dims) result",
"\"y\", [[[0.05, 0.1], [-0.9, 0.05]]], ('t','x','band')), ]) def test_with_xarray(execute_array_element_process, generate_data,",
"pytest import sys, os import xarray as xr import numpy",
"@pytest.mark.parametrize('data,index,reduce_by,expected_data,expected_dims', [ ([[[[0.1, 0.15], [0.15, 0.2]], [[0.05, 0.1], [-0.9, 0.05]]]],",
"0.05]]], ('t','x','band')), ]) def test_with_xarray(execute_array_element_process, generate_data, data, index, reduce_by, expected_data,",
"not None: arguments[\"return_nodata\"] = return_nodata return process.array_element.array_elementEOTask(None, \"\" , None,",
"True, 0, None) ]) def test_examples(execute_array_element_process, data, index, return_nodata, expected_result):"
] |
[
"], srcs: [ $nanobench_srcs ], data: [ \"resources/*\", ], }''')",
"variable // or set enable_profile_use property to false. cc_defaults {",
"to get the main source lists and include directories for",
"defs['avx' ] + defs['hsw' ]), 'dm_includes' : bpfmt(8, dm_includes), 'dm_srcs'",
"Turn a list of strings into the style bpfmt outputs.",
"mips: { srcs: [ $none_srcs ], }, mips64: { srcs:",
"}, }, defaults: [\"skia_deps\", \"skia_pgo\", ], } // Build libskia",
"and is separate from skia. // To turn it off,",
"{ name: \"skia_tool_deps\", defaults: [ \"skia_deps\", \"skia_pgo_no_profile_use\" ], static_libs: [",
"if not s.endswith('.h')} nanobench_srcs = {s for s in nanobench_srcs",
"we start off with a template for Android.bp, # with",
"lists and include directories for Skia. gn_args = { 'is_official_build':",
"'\"android\"', 'skia_vulkan_header': '\"Skia_Vulkan_Android.h\"', } js = gn_to_bp_utils.GenerateJSONFromGN(gn_args) def strip_slashes(lst): return",
"{ srcs: [ $none_srcs ], }, mips64: { srcs: [",
"have everything to fill in Android.bp... with open('Android.bp', 'w') as",
"], group_static_libs: true, } cc_defaults { name: \"skia_tool_deps\", defaults: [",
"get the main source lists and include directories for Skia.",
"is governed by a BSD-style license that can be #",
"\"skia_pgo\", ], } // Build libskia with PGO by default.",
"not s.endswith('.h')} cflags = gn_to_bp_utils.CleanupCFlags(cflags) cflags_cc = gn_to_bp_utils.CleanupCCFlags(cflags_cc) # We",
"], local_include_dirs: [ $dm_includes ], srcs: [ $dm_srcs ], shared_libs:",
"tempfile import gn_to_bp_utils # First we start off with a",
"strip_slashes(js['targets']['//:dm']['sources']) dm_includes = strip_slashes(js['targets']['//:dm']['include_dirs']) nanobench_target = js['targets']['//:nanobench'] nanobench_srcs = strip_slashes(nanobench_target['sources'])",
"\"skia_pgo\", ], pgo: { enable_profile_use: false, }, } cc_defaults {",
"'local_includes': bpfmt(8, local_includes), 'srcs': bpfmt(8, srcs), 'cflags': bpfmt(8, cflags, False),",
"[ $srcs ], arch: { arm: { srcs: [ $arm_srcs",
"= os.path.dirname(__file__) defs = gn_to_bp_utils.GetArchSources(os.path.join(here, 'opts.gni')) gn_to_bp_utils.WriteUserConfig('include/config/SkUserConfig.h', defines) # Turn",
"{ name: \"libskia\", cflags: [ $cflags ], cppflags:[ $cflags_cc ],",
"is defined in build/soong/cc/pgo.go // and is separate from skia.",
"= gn_to_bp_utils.CleanupCCFlags(cflags_cc) # We need to add the include path",
"information, // and should fail if we're wrong. \"-Wno-over-aligned\" ],",
"\"libz\", \"libcutils\", \"libnativewindow\", ], static_libs: [ \"libarect\", \"libsfntly\", \"libwebp-decode\", \"libwebp-encode\",",
"$local_includes ], srcs: [ $srcs ], arch: { arm: {",
"of PGO profile data is defined in build/soong/cc/pgo.go // and",
"think new/malloc will only be 4-byte aligned // on x86",
"to add the include path to the vulkan defines and",
"cflags_cc = strip_slashes(js['targets']['//:skia']['cflags_cc']) local_includes = strip_slashes(js['targets']['//:skia']['include_dirs']) export_includes = strip_slashes(js['targets']['//:public']['include_dirs']) defines",
"static_libs: [ \"libjsoncpp\", \"libskia\", ], cflags: [ \"-Wno-unused-parameter\", \"-Wno-unused-variable\", ],",
"cflags = strip_slashes(js['targets']['//:skia']['cflags']) cflags_cc = strip_slashes(js['targets']['//:skia']['cflags_cc']) local_includes = strip_slashes(js['targets']['//:skia']['include_dirs']) export_includes",
"found in the LICENSE file. # Generate Android.bp for Skia",
"= strip_slashes(js['targets']['//:dm']['sources']) dm_includes = strip_slashes(js['targets']['//:dm']['include_dirs']) nanobench_target = js['targets']['//:nanobench'] nanobench_srcs =",
"not s.endswith('.h')} dm_srcs = {s for s in dm_srcs if",
"LICENSE file. # Generate Android.bp for Skia from GN configuration.",
"bpfmt(8, dm_srcs), 'nanobench_includes' : bpfmt(8, nanobench_includes), 'nanobench_srcs' : bpfmt(8, nanobench_srcs),",
"path to the vulkan defines and header file set in",
"= string.Template('''// This file is autogenerated by gn_to_bp.py. cc_library_static {",
"'skia_use_vulkan': 'true', 'target_cpu': '\"none\"', 'target_os': '\"android\"', 'skia_vulkan_header': '\"Skia_Vulkan_Android.h\"', } js",
"'x86_srcs': bpfmt(16, defs['sse2'] + defs['ssse3'] + defs['sse41'] + defs['sse42'] +",
"cc_test { name: \"skia_nanobench\", defaults: [ \"skia_tool_deps\" ], local_include_dirs: [",
"code is governed by a BSD-style license that can be",
"'export_includes': bpfmt(8, export_includes), 'local_includes': bpfmt(8, local_includes), 'srcs': bpfmt(8, srcs), 'cflags':",
"+ defs['ssse3'] + defs['sse41'] + defs['sse42'] + defs['avx' ] +",
"4-byte aligned // on x86 Android. We're pretty sure it's",
"8-byte // alignment. tests/OverAlignedTest.cpp has more information, // and should",
"defs['crc32']), 'none_srcs': bpfmt(16, defs['none']), 'x86_srcs': bpfmt(16, defs['sse2'] + defs['ssse3'] +",
"bpfmt(8, export_includes), 'local_includes': bpfmt(8, local_includes), 'srcs': bpfmt(8, srcs), 'cflags': bpfmt(8,",
"defined in build/soong/cc/pgo.go // and is separate from skia. //",
"into the style bpfmt outputs. def bpfmt(indent, lst, sort=True): if",
"lists and include directories. bp = string.Template('''// This file is",
"governed by a BSD-style license that can be # found",
"], local_include_dirs: [ $local_includes ], srcs: [ $srcs ], arch:",
"# then skia_vulkan_header gn arg that is used for framework",
"gn_to_bp_utils.GetArchSources(os.path.join(here, 'opts.gni')) gn_to_bp_utils.WriteUserConfig('include/config/SkUserConfig.h', defines) # Turn a list of strings",
"Use of this source code is governed by a BSD-style",
"used for framework builds. local_includes.add(\"platform_tools/android/vulkan\") export_includes.add(\"platform_tools/android/vulkan\") here = os.path.dirname(__file__) defs",
"<reponame>despairblue/esy-skia #!/usr/bin/env python # # Copyright 2016 Google Inc. #",
"list headers. srcs = {s for s in srcs if",
"# We'll run GN to get the main source lists",
"[ $cflags ], cppflags:[ $cflags_cc ], export_include_dirs: [ $export_includes ],",
"2016 Google Inc. # # Use of this source code",
"pretty sure it's actually 8-byte // alignment. tests/OverAlignedTest.cpp has more",
"'//:dm', 'sources', dm_srcs, 'skia') gn_to_bp_utils.GrabDependentValues(js, '//:nanobench', 'sources', nanobench_srcs, 'skia') #",
"holes for source lists and include directories. bp = string.Template('''//",
"nanobench_includes = strip_slashes(nanobench_target['include_dirs']) gn_to_bp_utils.GrabDependentValues(js, '//:skia', 'sources', srcs, None) gn_to_bp_utils.GrabDependentValues(js, '//:dm',",
"in build/soong/cc/pgo.go // and is separate from skia. // To",
"second-party library. srcs .add(\"third_party/skcms/skcms.c\") local_includes.add(\"third_party/skcms\") dm_includes .add(\"third_party/skcms\") # No need",
"'*indent).join('\"%s\",' % v for v in lst) # OK! We",
": bpfmt(8, dm_srcs), 'nanobench_includes' : bpfmt(8, nanobench_includes), 'nanobench_srcs' : bpfmt(8,",
"sure it's actually 8-byte // alignment. tests/OverAlignedTest.cpp has more information,",
"'skia_use_libheif': 'true', 'skia_use_vulkan': 'true', 'target_cpu': '\"none\"', 'target_os': '\"android\"', 'skia_vulkan_header': '\"Skia_Vulkan_Android.h\"',",
"in js['targets']['//:skia']['defines']] dm_srcs = strip_slashes(js['targets']['//:dm']['sources']) dm_includes = strip_slashes(js['targets']['//:dm']['include_dirs']) nanobench_target =",
"is autogenerated by gn_to_bp.py. cc_library_static { name: \"libskia\", cflags: [",
"srcs: [ $arm_neon_srcs ], }, }, arm64: { srcs: [",
"neon: { srcs: [ $arm_neon_srcs ], }, }, arm64: {",
"for framework builds. local_includes.add(\"platform_tools/android/vulkan\") export_includes.add(\"platform_tools/android/vulkan\") here = os.path.dirname(__file__) defs =",
"more information, // and should fail if we're wrong. \"-Wno-over-aligned\"",
"here = os.path.dirname(__file__) defs = gn_to_bp_utils.GetArchSources(os.path.join(here, 'opts.gni')) gn_to_bp_utils.WriteUserConfig('include/config/SkUserConfig.h', defines) #",
"], }, x86_64: { srcs: [ $x86_srcs ], }, },",
"def strip_slashes(lst): return {str(p.lstrip('/')) for p in lst} srcs =",
"// on x86 Android. We're pretty sure it's actually 8-byte",
"dm_srcs = {s for s in dm_srcs if not s.endswith('.h')}",
"= gn_to_bp_utils.GenerateJSONFromGN(gn_args) def strip_slashes(lst): return {str(p.lstrip('/')) for p in lst}",
"builds. local_includes.add(\"platform_tools/android/vulkan\") export_includes.add(\"platform_tools/android/vulkan\") here = os.path.dirname(__file__) defs = gn_to_bp_utils.GetArchSources(os.path.join(here, 'opts.gni'))",
"the LICENSE file. # Generate Android.bp for Skia from GN",
"headers. srcs = {s for s in srcs if not",
"\"libGLESv2\", \"libdng_sdk\", \"libexpat\", \"libft2\", \"libheif\", \"libicui18n\", \"libicuuc\", \"libjpeg\", \"liblog\", \"libpiex\",",
"that is used for framework builds. local_includes.add(\"platform_tools/android/vulkan\") export_includes.add(\"platform_tools/android/vulkan\") here =",
"[ \"skia_pgo\", ], pgo: { enable_profile_use: false, }, } cc_defaults",
"\"defaults\" property to disable profile use for Skia tools and",
"srcs: [ $none_srcs ], }, x86: { srcs: [ $x86_srcs",
"$arm64_srcs ], }, mips: { srcs: [ $none_srcs ], },",
"srcs .add(\"third_party/skcms/skcms.c\") local_includes.add(\"third_party/skcms\") dm_includes .add(\"third_party/skcms\") # No need to list",
"\"resources/*\", ], }''') # We'll run GN to get the",
"\"skia_tool_deps\" ], local_include_dirs: [ $dm_includes ], srcs: [ $dm_srcs ],",
"file is autogenerated by gn_to_bp.py. cc_library_static { name: \"libskia\", cflags:",
"Generate Android.bp for Skia from GN configuration. import json import",
"\"hwui/hwui.profdata\", benchmarks: [\"hwui\", \"skia\"], enable_profile_use: true, }, } // \"defaults\"",
"], local_include_dirs: [ $nanobench_includes ], srcs: [ $nanobench_srcs ], data:",
"\"-Wno-unused-variable\", ], } cc_test { name: \"skia_dm\", defaults: [ \"skia_tool_deps\"",
"in the LICENSE file. # Generate Android.bp for Skia from",
"profile data is defined in build/soong/cc/pgo.go // and is separate",
"\"libwebp-encode\", ], group_static_libs: true, } cc_defaults { name: \"skia_tool_deps\", defaults:",
"'dm_srcs' : bpfmt(8, dm_srcs), 'nanobench_includes' : bpfmt(8, nanobench_includes), 'nanobench_srcs' :",
"'skia_enable_skottie': 'false', # requires rapidjson third-party 'skia_use_libheif': 'true', 'skia_use_vulkan': 'true',",
"{ instrumentation: true, profile_file: \"hwui/hwui.profdata\", benchmarks: [\"hwui\", \"skia\"], enable_profile_use: true,",
"string.Template('''// This file is autogenerated by gn_to_bp.py. cc_library_static { name:",
"and benchmarks. cc_defaults { name: \"skia_pgo_no_profile_use\", defaults: [ \"skia_pgo\", ],",
"We'll run GN to get the main source lists and",
"{ arm: { srcs: [ $arm_srcs ], neon: { srcs:",
"{ srcs: [ $x86_srcs ], }, }, defaults: [\"skia_deps\", \"skia_pgo\",",
"}, } // \"defaults\" property to disable profile use for",
"= {s for s in dm_srcs if not s.endswith('.h')} nanobench_srcs",
"srcs: [ $srcs ], arch: { arm: { srcs: [",
"a list of strings into the style bpfmt outputs. def",
"'cflags': bpfmt(8, cflags, False), 'cflags_cc': bpfmt(8, cflags_cc), 'arm_srcs': bpfmt(16, defs['armv7']),",
"it off, set ANDROID_PGO_NO_PROFILE_USE environment variable // or set enable_profile_use",
"{ srcs: [ $arm_srcs ], neon: { srcs: [ $arm_neon_srcs",
"json import os import pprint import string import subprocess import",
"gn_to_bp_utils # First we start off with a template for",
"vulkan defines and header file set in # then skia_vulkan_header",
"local_includes.add(\"platform_tools/android/vulkan\") export_includes.add(\"platform_tools/android/vulkan\") here = os.path.dirname(__file__) defs = gn_to_bp_utils.GetArchSources(os.path.join(here, 'opts.gni')) gn_to_bp_utils.WriteUserConfig('include/config/SkUserConfig.h',",
"arg that is used for framework builds. local_includes.add(\"platform_tools/android/vulkan\") export_includes.add(\"platform_tools/android/vulkan\") here",
"source lists and include directories for Skia. gn_args = {",
"defs['ssse3'] + defs['sse41'] + defs['sse42'] + defs['avx' ] + defs['hsw'",
".add(\"third_party/skcms\") # No need to list headers. srcs = {s",
"('\\n' + ' '*indent).join('\"%s\",' % v for v in lst)",
"cc_defaults { name: \"skia_pgo\", pgo: { instrumentation: true, profile_file: \"hwui/hwui.profdata\",",
"s in srcs if not s.endswith('.h')} dm_srcs = {s for",
"kind of a second-party library. srcs .add(\"third_party/skcms/skcms.c\") local_includes.add(\"third_party/skcms\") dm_includes .add(\"third_party/skcms\")",
"= strip_slashes(js['targets']['//:dm']['include_dirs']) nanobench_target = js['targets']['//:nanobench'] nanobench_srcs = strip_slashes(nanobench_target['sources']) nanobench_includes =",
"bpfmt(8, srcs), 'cflags': bpfmt(8, cflags, False), 'cflags_cc': bpfmt(8, cflags_cc), 'arm_srcs':",
"to fill in Android.bp... with open('Android.bp', 'w') as f: print",
"$export_includes ], local_include_dirs: [ $local_includes ], srcs: [ $srcs ],",
"include directories for Skia. gn_args = { 'is_official_build': 'true', 'skia_enable_tools':",
"return {str(p.lstrip('/')) for p in lst} srcs = strip_slashes(js['targets']['//:skia']['sources']) cflags",
"from skia. // To turn it off, set ANDROID_PGO_NO_PROFILE_USE environment",
"gn_to_bp_utils.CleanupCCFlags(cflags_cc) # We need to add the include path to",
"\"skia_pgo_no_profile_use\", defaults: [ \"skia_pgo\", ], pgo: { enable_profile_use: false, },",
"\"skia_deps\", \"skia_pgo_no_profile_use\" ], static_libs: [ \"libjsoncpp\", \"libskia\", ], cflags: [",
"srcs: [ $dm_srcs ], shared_libs: [ \"libbinder\", \"libutils\", ], }",
"file. # Generate Android.bp for Skia from GN configuration. import",
"\"libdng_sdk\", \"libexpat\", \"libft2\", \"libheif\", \"libicui18n\", \"libicuuc\", \"libjpeg\", \"liblog\", \"libpiex\", \"libpng\",",
"[ $nanobench_includes ], srcs: [ $nanobench_srcs ], data: [ \"resources/*\",",
"template for Android.bp, # with holes for source lists and",
"disable profile use for Skia tools and benchmarks. cc_defaults {",
"\"skia_deps\", shared_libs: [ \"libEGL\", \"libGLESv2\", \"libdng_sdk\", \"libexpat\", \"libft2\", \"libheif\", \"libicui18n\",",
"[ $local_includes ], srcs: [ $srcs ], arch: { arm:",
"], cflags: [ \"-Wno-unused-parameter\", \"-Wno-unused-variable\", ], } cc_test { name:",
"skia_vulkan_header gn arg that is used for framework builds. local_includes.add(\"platform_tools/android/vulkan\")",
"{ name: \"skia_pgo_no_profile_use\", defaults: [ \"skia_pgo\", ], pgo: { enable_profile_use:",
"srcs, None) gn_to_bp_utils.GrabDependentValues(js, '//:dm', 'sources', dm_srcs, 'skia') gn_to_bp_utils.GrabDependentValues(js, '//:nanobench', 'sources',",
"], }, }, defaults: [\"skia_deps\", \"skia_pgo\", ], } // Build",
"nanobench_srcs if not s.endswith('.h')} cflags = gn_to_bp_utils.CleanupCFlags(cflags) cflags_cc = gn_to_bp_utils.CleanupCCFlags(cflags_cc)",
"], neon: { srcs: [ $arm_neon_srcs ], }, }, arm64:",
"defs['armv7']), 'arm_neon_srcs': bpfmt(20, defs['neon']), 'arm64_srcs': bpfmt(16, defs['arm64'] + defs['crc32']), 'none_srcs':",
"license that can be # found in the LICENSE file.",
"{s for s in srcs if not s.endswith('.h')} dm_srcs =",
"list of strings into the style bpfmt outputs. def bpfmt(indent,",
"be # found in the LICENSE file. # Generate Android.bp",
"with holes for source lists and include directories. bp =",
"bpfmt(8, dm_includes), 'dm_srcs' : bpfmt(8, dm_srcs), 'nanobench_includes' : bpfmt(8, nanobench_includes),",
"\"skia_tool_deps\" ], local_include_dirs: [ $nanobench_includes ], srcs: [ $nanobench_srcs ],",
"bpfmt(20, defs['neon']), 'arm64_srcs': bpfmt(16, defs['arm64'] + defs['crc32']), 'none_srcs': bpfmt(16, defs['none']),",
"configuration. import json import os import pprint import string import",
"defines and header file set in # then skia_vulkan_header gn",
"\"skia_dm\", defaults: [ \"skia_tool_deps\" ], local_include_dirs: [ $dm_includes ], srcs:",
"cflags_cc = gn_to_bp_utils.CleanupCCFlags(cflags_cc) # We need to add the include",
"a second-party library. srcs .add(\"third_party/skcms/skcms.c\") local_includes.add(\"third_party/skcms\") dm_includes .add(\"third_party/skcms\") # No",
"cflags: [ $cflags ], cppflags:[ $cflags_cc ], export_include_dirs: [ $export_includes",
"arch: { arm: { srcs: [ $arm_srcs ], neon: {",
"BSD-style license that can be # found in the LICENSE",
"} cc_defaults { name: \"skia_deps\", shared_libs: [ \"libEGL\", \"libGLESv2\", \"libdng_sdk\",",
"to list headers. srcs = {s for s in srcs",
"string import subprocess import tempfile import gn_to_bp_utils # First we",
"No need to list headers. srcs = {s for s",
"# We need to add the include path to the",
"# Use of this source code is governed by a",
"], }, mips64: { srcs: [ $none_srcs ], }, x86:",
"need to add the include path to the vulkan defines",
"'sources', srcs, None) gn_to_bp_utils.GrabDependentValues(js, '//:dm', 'sources', dm_srcs, 'skia') gn_to_bp_utils.GrabDependentValues(js, '//:nanobench',",
"\"libpiex\", \"libpng\", \"libvulkan\", \"libz\", \"libcutils\", \"libnativewindow\", ], static_libs: [ \"libarect\",",
"autogenerated by gn_to_bp.py. cc_library_static { name: \"libskia\", cflags: [ $cflags",
"in srcs if not s.endswith('.h')} dm_srcs = {s for s",
"has more information, // and should fail if we're wrong.",
"bpfmt(indent, lst, sort=True): if sort: lst = sorted(lst) return ('\\n'",
"{ name: \"skia_nanobench\", defaults: [ \"skia_tool_deps\" ], local_include_dirs: [ $nanobench_includes",
"of a second-party library. srcs .add(\"third_party/skcms/skcms.c\") local_includes.add(\"third_party/skcms\") dm_includes .add(\"third_party/skcms\") #",
"defaults: [ \"skia_tool_deps\" ], local_include_dirs: [ $nanobench_includes ], srcs: [",
"bpfmt(16, defs['arm64'] + defs['crc32']), 'none_srcs': bpfmt(16, defs['none']), 'x86_srcs': bpfmt(16, defs['sse2']",
"pprint import string import subprocess import tempfile import gn_to_bp_utils #",
"], }''') # We'll run GN to get the main",
"# with holes for source lists and include directories. bp",
"\"libft2\", \"libheif\", \"libicui18n\", \"libicuuc\", \"libjpeg\", \"liblog\", \"libpiex\", \"libpng\", \"libvulkan\", \"libz\",",
"dm_srcs), 'nanobench_includes' : bpfmt(8, nanobench_includes), 'nanobench_srcs' : bpfmt(8, nanobench_srcs), })",
"'sources', dm_srcs, 'skia') gn_to_bp_utils.GrabDependentValues(js, '//:nanobench', 'sources', nanobench_srcs, 'skia') # skcms",
"name: \"skia_pgo_no_profile_use\", defaults: [ \"skia_pgo\", ], pgo: { enable_profile_use: false,",
"export_include_dirs: [ $export_includes ], local_include_dirs: [ $local_includes ], srcs: [",
"], cppflags:[ $cflags_cc ], export_include_dirs: [ $export_includes ], local_include_dirs: [",
"}, defaults: [\"skia_deps\", \"skia_pgo\", ], } // Build libskia with",
"defaults: [ \"skia_pgo\", ], pgo: { enable_profile_use: false, }, }",
"gn_args = { 'is_official_build': 'true', 'skia_enable_tools': 'true', 'skia_enable_skottie': 'false', #",
"strip_slashes(js['targets']['//:skia']['include_dirs']) export_includes = strip_slashes(js['targets']['//:public']['include_dirs']) defines = [str(d) for d in",
"for v in lst) # OK! We have everything to",
"return ('\\n' + ' '*indent).join('\"%s\",' % v for v in",
"None) gn_to_bp_utils.GrabDependentValues(js, '//:dm', 'sources', dm_srcs, 'skia') gn_to_bp_utils.GrabDependentValues(js, '//:nanobench', 'sources', nanobench_srcs,",
"cflags, False), 'cflags_cc': bpfmt(8, cflags_cc), 'arm_srcs': bpfmt(16, defs['armv7']), 'arm_neon_srcs': bpfmt(20,",
"We're pretty sure it's actually 8-byte // alignment. tests/OverAlignedTest.cpp has",
"a BSD-style license that can be # found in the",
"$x86_srcs ], }, }, defaults: [\"skia_deps\", \"skia_pgo\", ], } //",
"for d in js['targets']['//:skia']['defines']] dm_srcs = strip_slashes(js['targets']['//:dm']['sources']) dm_includes = strip_slashes(js['targets']['//:dm']['include_dirs'])",
"'cflags_cc': bpfmt(8, cflags_cc), 'arm_srcs': bpfmt(16, defs['armv7']), 'arm_neon_srcs': bpfmt(20, defs['neon']), 'arm64_srcs':",
"= { 'is_official_build': 'true', 'skia_enable_tools': 'true', 'skia_enable_skottie': 'false', # requires",
"the vulkan defines and header file set in # then",
"os.path.dirname(__file__) defs = gn_to_bp_utils.GetArchSources(os.path.join(here, 'opts.gni')) gn_to_bp_utils.WriteUserConfig('include/config/SkUserConfig.h', defines) # Turn a",
"dm_includes), 'dm_srcs' : bpfmt(8, dm_srcs), 'nanobench_includes' : bpfmt(8, nanobench_includes), 'nanobench_srcs'",
"if sort: lst = sorted(lst) return ('\\n' + ' '*indent).join('\"%s\",'",
"little special, kind of a second-party library. srcs .add(\"third_party/skcms/skcms.c\") local_includes.add(\"third_party/skcms\")",
": bpfmt(8, dm_includes), 'dm_srcs' : bpfmt(8, dm_srcs), 'nanobench_includes' : bpfmt(8,",
"fill in Android.bp... with open('Android.bp', 'w') as f: print >>f,",
"+ defs['hsw' ]), 'dm_includes' : bpfmt(8, dm_includes), 'dm_srcs' : bpfmt(8,",
"\"-Wno-over-aligned\" ], }, x86_64: { srcs: [ $x86_srcs ], },",
"lst = sorted(lst) return ('\\n' + ' '*indent).join('\"%s\",' % v",
"$nanobench_includes ], srcs: [ $nanobench_srcs ], data: [ \"resources/*\", ],",
"= strip_slashes(nanobench_target['include_dirs']) gn_to_bp_utils.GrabDependentValues(js, '//:skia', 'sources', srcs, None) gn_to_bp_utils.GrabDependentValues(js, '//:dm', 'sources',",
"x86_64: { srcs: [ $x86_srcs ], }, }, defaults: [\"skia_deps\",",
"[ $x86_srcs ], }, }, defaults: [\"skia_deps\", \"skia_pgo\", ], }",
"directories. bp = string.Template('''// This file is autogenerated by gn_to_bp.py.",
"defaults: [ \"skia_tool_deps\" ], local_include_dirs: [ $dm_includes ], srcs: [",
"actually 8-byte // alignment. tests/OverAlignedTest.cpp has more information, // and",
"\"libjpeg\", \"liblog\", \"libpiex\", \"libpng\", \"libvulkan\", \"libz\", \"libcutils\", \"libnativewindow\", ], static_libs:",
"with PGO by default. // Location of PGO profile data",
"{ srcs: [ $arm64_srcs ], }, mips: { srcs: [",
"\"libEGL\", \"libGLESv2\", \"libdng_sdk\", \"libexpat\", \"libft2\", \"libheif\", \"libicui18n\", \"libicuuc\", \"libjpeg\", \"liblog\",",
"= strip_slashes(js['targets']['//:skia']['sources']) cflags = strip_slashes(js['targets']['//:skia']['cflags']) cflags_cc = strip_slashes(js['targets']['//:skia']['cflags_cc']) local_includes =",
"in dm_srcs if not s.endswith('.h')} nanobench_srcs = {s for s",
"rapidjson third-party 'skia_use_libheif': 'true', 'skia_use_vulkan': 'true', 'target_cpu': '\"none\"', 'target_os': '\"android\"',",
"{ name: \"skia_deps\", shared_libs: [ \"libEGL\", \"libGLESv2\", \"libdng_sdk\", \"libexpat\", \"libft2\",",
"[ \"libEGL\", \"libGLESv2\", \"libdng_sdk\", \"libexpat\", \"libft2\", \"libheif\", \"libicui18n\", \"libicuuc\", \"libjpeg\",",
"s.endswith('.h')} cflags = gn_to_bp_utils.CleanupCFlags(cflags) cflags_cc = gn_to_bp_utils.CleanupCCFlags(cflags_cc) # We need",
"js['targets']['//:skia']['defines']] dm_srcs = strip_slashes(js['targets']['//:dm']['sources']) dm_includes = strip_slashes(js['targets']['//:dm']['include_dirs']) nanobench_target = js['targets']['//:nanobench']",
"name: \"libskia\", cflags: [ $cflags ], cppflags:[ $cflags_cc ], export_include_dirs:",
"import tempfile import gn_to_bp_utils # First we start off with",
"gn_to_bp_utils.GenerateJSONFromGN(gn_args) def strip_slashes(lst): return {str(p.lstrip('/')) for p in lst} srcs",
"], } cc_test { name: \"skia_nanobench\", defaults: [ \"skia_tool_deps\" ],",
"defs['neon']), 'arm64_srcs': bpfmt(16, defs['arm64'] + defs['crc32']), 'none_srcs': bpfmt(16, defs['none']), 'x86_srcs':",
"srcs: [ $none_srcs ], }, mips64: { srcs: [ $none_srcs",
"cc_library_static { name: \"libskia\", cflags: [ $cflags ], cppflags:[ $cflags_cc",
"d in js['targets']['//:skia']['defines']] dm_srcs = strip_slashes(js['targets']['//:dm']['sources']) dm_includes = strip_slashes(js['targets']['//:dm']['include_dirs']) nanobench_target",
"+ defs['avx' ] + defs['hsw' ]), 'dm_includes' : bpfmt(8, dm_includes),",
"for s in dm_srcs if not s.endswith('.h')} nanobench_srcs = {s",
"[ \"skia_tool_deps\" ], local_include_dirs: [ $nanobench_includes ], srcs: [ $nanobench_srcs",
"\"libexpat\", \"libft2\", \"libheif\", \"libicui18n\", \"libicuuc\", \"libjpeg\", \"liblog\", \"libpiex\", \"libpng\", \"libvulkan\",",
"js['targets']['//:nanobench'] nanobench_srcs = strip_slashes(nanobench_target['sources']) nanobench_includes = strip_slashes(nanobench_target['include_dirs']) gn_to_bp_utils.GrabDependentValues(js, '//:skia', 'sources',",
"for source lists and include directories. bp = string.Template('''// This",
"js = gn_to_bp_utils.GenerateJSONFromGN(gn_args) def strip_slashes(lst): return {str(p.lstrip('/')) for p in",
"property to disable profile use for Skia tools and benchmarks.",
"= sorted(lst) return ('\\n' + ' '*indent).join('\"%s\",' % v for",
"name: \"skia_dm\", defaults: [ \"skia_tool_deps\" ], local_include_dirs: [ $dm_includes ],",
"'\"Skia_Vulkan_Android.h\"', } js = gn_to_bp_utils.GenerateJSONFromGN(gn_args) def strip_slashes(lst): return {str(p.lstrip('/')) for",
"add the include path to the vulkan defines and header",
"[ $arm_neon_srcs ], }, }, arm64: { srcs: [ $arm64_srcs",
"\"libarect\", \"libsfntly\", \"libwebp-decode\", \"libwebp-encode\", ], group_static_libs: true, } cc_defaults {",
"export_includes), 'local_includes': bpfmt(8, local_includes), 'srcs': bpfmt(8, srcs), 'cflags': bpfmt(8, cflags,",
"benchmarks. cc_defaults { name: \"skia_pgo_no_profile_use\", defaults: [ \"skia_pgo\", ], pgo:",
"in lst) # OK! We have everything to fill in",
"PGO by default. // Location of PGO profile data is",
"local_include_dirs: [ $dm_includes ], srcs: [ $dm_srcs ], shared_libs: [",
"Skia tools and benchmarks. cc_defaults { name: \"skia_pgo_no_profile_use\", defaults: [",
"'true', 'skia_enable_skottie': 'false', # requires rapidjson third-party 'skia_use_libheif': 'true', 'skia_use_vulkan':",
"}, x86_64: { srcs: [ $x86_srcs ], }, }, defaults:",
"import gn_to_bp_utils # First we start off with a template",
"bp.substitute({ 'export_includes': bpfmt(8, export_includes), 'local_includes': bpfmt(8, local_includes), 'srcs': bpfmt(8, srcs),",
"gn_to_bp.py. cc_library_static { name: \"libskia\", cflags: [ $cflags ], cppflags:[",
"instrumentation: true, profile_file: \"hwui/hwui.profdata\", benchmarks: [\"hwui\", \"skia\"], enable_profile_use: true, },",
"only be 4-byte aligned // on x86 Android. We're pretty",
"[ \"libjsoncpp\", \"libskia\", ], cflags: [ \"-Wno-unused-parameter\", \"-Wno-unused-variable\", ], }",
"special, kind of a second-party library. srcs .add(\"third_party/skcms/skcms.c\") local_includes.add(\"third_party/skcms\") dm_includes",
"\"-Wno-unused-parameter\", \"-Wno-unused-variable\", ], } cc_test { name: \"skia_dm\", defaults: [",
"on x86 Android. We're pretty sure it's actually 8-byte //",
"with a template for Android.bp, # with holes for source",
"and include directories for Skia. gn_args = { 'is_official_build': 'true',",
"We need to add the include path to the vulkan",
"the main source lists and include directories for Skia. gn_args",
"], }, mips: { srcs: [ $none_srcs ], }, mips64:",
"Copyright 2016 Google Inc. # # Use of this source",
"library. srcs .add(\"third_party/skcms/skcms.c\") local_includes.add(\"third_party/skcms\") dm_includes .add(\"third_party/skcms\") # No need to",
"'w') as f: print >>f, bp.substitute({ 'export_includes': bpfmt(8, export_includes), 'local_includes':",
"off, set ANDROID_PGO_NO_PROFILE_USE environment variable // or set enable_profile_use property",
"environment variable // or set enable_profile_use property to false. cc_defaults",
"# skcms is a little special, kind of a second-party",
"\"skia\"], enable_profile_use: true, }, } // \"defaults\" property to disable",
"False), 'cflags_cc': bpfmt(8, cflags_cc), 'arm_srcs': bpfmt(16, defs['armv7']), 'arm_neon_srcs': bpfmt(20, defs['neon']),",
"\"skia_pgo_no_profile_use\" ], static_libs: [ \"libjsoncpp\", \"libskia\", ], cflags: [ \"-Wno-unused-parameter\",",
"], data: [ \"resources/*\", ], }''') # We'll run GN",
"'//:skia', 'sources', srcs, None) gn_to_bp_utils.GrabDependentValues(js, '//:dm', 'sources', dm_srcs, 'skia') gn_to_bp_utils.GrabDependentValues(js,",
"this source code is governed by a BSD-style license that",
"{ srcs: [ $none_srcs ], }, x86: { srcs: [",
"cc_defaults { name: \"skia_pgo_no_profile_use\", defaults: [ \"skia_pgo\", ], pgo: {",
"+ defs['sse42'] + defs['avx' ] + defs['hsw' ]), 'dm_includes' :",
"\"libnativewindow\", ], static_libs: [ \"libarect\", \"libsfntly\", \"libwebp-decode\", \"libwebp-encode\", ], group_static_libs:",
"= [str(d) for d in js['targets']['//:skia']['defines']] dm_srcs = strip_slashes(js['targets']['//:dm']['sources']) dm_includes",
"{s for s in nanobench_srcs if not s.endswith('.h')} cflags =",
"sorted(lst) return ('\\n' + ' '*indent).join('\"%s\",' % v for v",
"source lists and include directories. bp = string.Template('''// This file",
"lst} srcs = strip_slashes(js['targets']['//:skia']['sources']) cflags = strip_slashes(js['targets']['//:skia']['cflags']) cflags_cc = strip_slashes(js['targets']['//:skia']['cflags_cc'])",
"= gn_to_bp_utils.CleanupCFlags(cflags) cflags_cc = gn_to_bp_utils.CleanupCCFlags(cflags_cc) # We need to add",
"by gn_to_bp.py. cc_library_static { name: \"libskia\", cflags: [ $cflags ],",
"[ $x86_srcs ], cflags: [ // Clang seems to think",
"], }, }, arm64: { srcs: [ $arm64_srcs ], },",
"= strip_slashes(js['targets']['//:skia']['include_dirs']) export_includes = strip_slashes(js['targets']['//:public']['include_dirs']) defines = [str(d) for d",
"pgo: { instrumentation: true, profile_file: \"hwui/hwui.profdata\", benchmarks: [\"hwui\", \"skia\"], enable_profile_use:",
"], srcs: [ $dm_srcs ], shared_libs: [ \"libbinder\", \"libutils\", ],",
"nanobench_srcs, 'skia') # skcms is a little special, kind of",
"srcs: [ $arm64_srcs ], }, mips: { srcs: [ $none_srcs",
"$x86_srcs ], cflags: [ // Clang seems to think new/malloc",
"source code is governed by a BSD-style license that can",
"import pprint import string import subprocess import tempfile import gn_to_bp_utils",
"Build libskia with PGO by default. // Location of PGO",
"gn_to_bp_utils.CleanupCFlags(cflags) cflags_cc = gn_to_bp_utils.CleanupCCFlags(cflags_cc) # We need to add the",
"new/malloc will only be 4-byte aligned // on x86 Android.",
"enable_profile_use: true, }, } // \"defaults\" property to disable profile",
"'dm_includes' : bpfmt(8, dm_includes), 'dm_srcs' : bpfmt(8, dm_srcs), 'nanobench_includes' :",
"// \"defaults\" property to disable profile use for Skia tools",
"strip_slashes(nanobench_target['include_dirs']) gn_to_bp_utils.GrabDependentValues(js, '//:skia', 'sources', srcs, None) gn_to_bp_utils.GrabDependentValues(js, '//:dm', 'sources', dm_srcs,",
"\"libicuuc\", \"libjpeg\", \"liblog\", \"libpiex\", \"libpng\", \"libvulkan\", \"libz\", \"libcutils\", \"libnativewindow\", ],",
"outputs. def bpfmt(indent, lst, sort=True): if sort: lst = sorted(lst)",
"skia. // To turn it off, set ANDROID_PGO_NO_PROFILE_USE environment variable",
"} // \"defaults\" property to disable profile use for Skia",
"[ \"-Wno-unused-parameter\", \"-Wno-unused-variable\", ], } cc_test { name: \"skia_dm\", defaults:",
"wrong. \"-Wno-over-aligned\" ], }, x86_64: { srcs: [ $x86_srcs ],",
"{ enable_profile_use: false, }, } cc_defaults { name: \"skia_deps\", shared_libs:",
"gn_to_bp_utils.GrabDependentValues(js, '//:dm', 'sources', dm_srcs, 'skia') gn_to_bp_utils.GrabDependentValues(js, '//:nanobench', 'sources', nanobench_srcs, 'skia')",
"\"libheif\", \"libicui18n\", \"libicuuc\", \"libjpeg\", \"liblog\", \"libpiex\", \"libpng\", \"libvulkan\", \"libz\", \"libcutils\",",
"'true', 'skia_enable_tools': 'true', 'skia_enable_skottie': 'false', # requires rapidjson third-party 'skia_use_libheif':",
"OK! We have everything to fill in Android.bp... with open('Android.bp',",
"s.endswith('.h')} nanobench_srcs = {s for s in nanobench_srcs if not",
"cc_test { name: \"skia_dm\", defaults: [ \"skia_tool_deps\" ], local_include_dirs: [",
"{ srcs: [ $x86_srcs ], cflags: [ // Clang seems",
"# requires rapidjson third-party 'skia_use_libheif': 'true', 'skia_use_vulkan': 'true', 'target_cpu': '\"none\"',",
"$srcs ], arch: { arm: { srcs: [ $arm_srcs ],",
"cflags = gn_to_bp_utils.CleanupCFlags(cflags) cflags_cc = gn_to_bp_utils.CleanupCCFlags(cflags_cc) # We need to",
"of this source code is governed by a BSD-style license",
"to think new/malloc will only be 4-byte aligned // on",
"can be # found in the LICENSE file. # Generate",
"for s in srcs if not s.endswith('.h')} dm_srcs = {s",
"}, mips: { srcs: [ $none_srcs ], }, mips64: {",
"to the vulkan defines and header file set in #",
"defs['hsw' ]), 'dm_includes' : bpfmt(8, dm_includes), 'dm_srcs' : bpfmt(8, dm_srcs),",
"# First we start off with a template for Android.bp,",
"}''') # We'll run GN to get the main source",
"lst, sort=True): if sort: lst = sorted(lst) return ('\\n' +",
"'//:nanobench', 'sources', nanobench_srcs, 'skia') # skcms is a little special,",
"cc_defaults { name: \"skia_deps\", shared_libs: [ \"libEGL\", \"libGLESv2\", \"libdng_sdk\", \"libexpat\",",
"# # Use of this source code is governed by",
"then skia_vulkan_header gn arg that is used for framework builds.",
"everything to fill in Android.bp... with open('Android.bp', 'w') as f:",
"Location of PGO profile data is defined in build/soong/cc/pgo.go //",
"bpfmt(8, cflags_cc), 'arm_srcs': bpfmt(16, defs['armv7']), 'arm_neon_srcs': bpfmt(20, defs['neon']), 'arm64_srcs': bpfmt(16,",
"[ $none_srcs ], }, mips64: { srcs: [ $none_srcs ],",
"= gn_to_bp_utils.GetArchSources(os.path.join(here, 'opts.gni')) gn_to_bp_utils.WriteUserConfig('include/config/SkUserConfig.h', defines) # Turn a list of",
"not s.endswith('.h')} nanobench_srcs = {s for s in nanobench_srcs if",
"benchmarks: [\"hwui\", \"skia\"], enable_profile_use: true, }, } // \"defaults\" property",
"[ $nanobench_srcs ], data: [ \"resources/*\", ], }''') # We'll",
"seems to think new/malloc will only be 4-byte aligned //",
"'true', 'target_cpu': '\"none\"', 'target_os': '\"android\"', 'skia_vulkan_header': '\"Skia_Vulkan_Android.h\"', } js =",
"start off with a template for Android.bp, # with holes",
"}, }, arm64: { srcs: [ $arm64_srcs ], }, mips:",
"be 4-byte aligned // on x86 Android. We're pretty sure",
"// Build libskia with PGO by default. // Location of",
"GN to get the main source lists and include directories",
"the style bpfmt outputs. def bpfmt(indent, lst, sort=True): if sort:",
"$dm_includes ], srcs: [ $dm_srcs ], shared_libs: [ \"libbinder\", \"libutils\",",
"cflags: [ \"-Wno-unused-parameter\", \"-Wno-unused-variable\", ], } cc_test { name: \"skia_dm\",",
"tests/OverAlignedTest.cpp has more information, // and should fail if we're",
"strip_slashes(js['targets']['//:skia']['sources']) cflags = strip_slashes(js['targets']['//:skia']['cflags']) cflags_cc = strip_slashes(js['targets']['//:skia']['cflags_cc']) local_includes = strip_slashes(js['targets']['//:skia']['include_dirs'])",
"+ defs['crc32']), 'none_srcs': bpfmt(16, defs['none']), 'x86_srcs': bpfmt(16, defs['sse2'] + defs['ssse3']",
"'is_official_build': 'true', 'skia_enable_tools': 'true', 'skia_enable_skottie': 'false', # requires rapidjson third-party",
"skcms is a little special, kind of a second-party library.",
"// To turn it off, set ANDROID_PGO_NO_PROFILE_USE environment variable //",
"], srcs: [ $srcs ], arch: { arm: { srcs:",
"name: \"skia_tool_deps\", defaults: [ \"skia_deps\", \"skia_pgo_no_profile_use\" ], static_libs: [ \"libjsoncpp\",",
"for Skia. gn_args = { 'is_official_build': 'true', 'skia_enable_tools': 'true', 'skia_enable_skottie':",
"v for v in lst) # OK! We have everything",
"srcs), 'cflags': bpfmt(8, cflags, False), 'cflags_cc': bpfmt(8, cflags_cc), 'arm_srcs': bpfmt(16,",
"}, } cc_defaults { name: \"skia_deps\", shared_libs: [ \"libEGL\", \"libGLESv2\",",
"local_includes = strip_slashes(js['targets']['//:skia']['include_dirs']) export_includes = strip_slashes(js['targets']['//:public']['include_dirs']) defines = [str(d) for",
"defaults: [\"skia_deps\", \"skia_pgo\", ], } // Build libskia with PGO",
"'target_cpu': '\"none\"', 'target_os': '\"android\"', 'skia_vulkan_header': '\"Skia_Vulkan_Android.h\"', } js = gn_to_bp_utils.GenerateJSONFromGN(gn_args)",
"the include path to the vulkan defines and header file",
"v in lst) # OK! We have everything to fill",
"for Skia tools and benchmarks. cc_defaults { name: \"skia_pgo_no_profile_use\", defaults:",
"export_includes = strip_slashes(js['targets']['//:public']['include_dirs']) defines = [str(d) for d in js['targets']['//:skia']['defines']]",
"defaults: [ \"skia_deps\", \"skia_pgo_no_profile_use\" ], static_libs: [ \"libjsoncpp\", \"libskia\", ],",
"], shared_libs: [ \"libbinder\", \"libutils\", ], } cc_test { name:",
"name: \"skia_nanobench\", defaults: [ \"skia_tool_deps\" ], local_include_dirs: [ $nanobench_includes ],",
"group_static_libs: true, } cc_defaults { name: \"skia_tool_deps\", defaults: [ \"skia_deps\",",
"is used for framework builds. local_includes.add(\"platform_tools/android/vulkan\") export_includes.add(\"platform_tools/android/vulkan\") here = os.path.dirname(__file__)",
"} cc_test { name: \"skia_dm\", defaults: [ \"skia_tool_deps\" ], local_include_dirs:",
"defs['sse41'] + defs['sse42'] + defs['avx' ] + defs['hsw' ]), 'dm_includes'",
"include path to the vulkan defines and header file set",
"header file set in # then skia_vulkan_header gn arg that",
"for s in nanobench_srcs if not s.endswith('.h')} cflags = gn_to_bp_utils.CleanupCFlags(cflags)",
"is separate from skia. // To turn it off, set",
"print >>f, bp.substitute({ 'export_includes': bpfmt(8, export_includes), 'local_includes': bpfmt(8, local_includes), 'srcs':",
"strings into the style bpfmt outputs. def bpfmt(indent, lst, sort=True):",
"$cflags_cc ], export_include_dirs: [ $export_includes ], local_include_dirs: [ $local_includes ],",
"], static_libs: [ \"libarect\", \"libsfntly\", \"libwebp-decode\", \"libwebp-encode\", ], group_static_libs: true,",
"sort=True): if sort: lst = sorted(lst) return ('\\n' + '",
"\"skia_nanobench\", defaults: [ \"skia_tool_deps\" ], local_include_dirs: [ $nanobench_includes ], srcs:",
"nanobench_srcs = strip_slashes(nanobench_target['sources']) nanobench_includes = strip_slashes(nanobench_target['include_dirs']) gn_to_bp_utils.GrabDependentValues(js, '//:skia', 'sources', srcs,",
"false, }, } cc_defaults { name: \"skia_deps\", shared_libs: [ \"libEGL\",",
"bpfmt(8, local_includes), 'srcs': bpfmt(8, srcs), 'cflags': bpfmt(8, cflags, False), 'cflags_cc':",
"that can be # found in the LICENSE file. #",
">>f, bp.substitute({ 'export_includes': bpfmt(8, export_includes), 'local_includes': bpfmt(8, local_includes), 'srcs': bpfmt(8,",
"include directories. bp = string.Template('''// This file is autogenerated by",
"will only be 4-byte aligned // on x86 Android. We're",
"for Skia from GN configuration. import json import os import",
"srcs: [ $nanobench_srcs ], data: [ \"resources/*\", ], }''') #",
"$nanobench_srcs ], data: [ \"resources/*\", ], }''') # We'll run",
"strip_slashes(js['targets']['//:skia']['cflags']) cflags_cc = strip_slashes(js['targets']['//:skia']['cflags_cc']) local_includes = strip_slashes(js['targets']['//:skia']['include_dirs']) export_includes = strip_slashes(js['targets']['//:public']['include_dirs'])",
"python # # Copyright 2016 Google Inc. # # Use",
"[ $arm_srcs ], neon: { srcs: [ $arm_neon_srcs ], },",
"strip_slashes(lst): return {str(p.lstrip('/')) for p in lst} srcs = strip_slashes(js['targets']['//:skia']['sources'])",
"[ $dm_srcs ], shared_libs: [ \"libbinder\", \"libutils\", ], } cc_test",
"srcs: [ $x86_srcs ], cflags: [ // Clang seems to",
"+ defs['sse41'] + defs['sse42'] + defs['avx' ] + defs['hsw' ]),",
"or set enable_profile_use property to false. cc_defaults { name: \"skia_pgo\",",
"{ srcs: [ $arm_neon_srcs ], }, }, arm64: { srcs:",
"= strip_slashes(js['targets']['//:skia']['cflags_cc']) local_includes = strip_slashes(js['targets']['//:skia']['include_dirs']) export_includes = strip_slashes(js['targets']['//:public']['include_dirs']) defines =",
"' '*indent).join('\"%s\",' % v for v in lst) # OK!",
"os import pprint import string import subprocess import tempfile import",
"data is defined in build/soong/cc/pgo.go // and is separate from",
"profile_file: \"hwui/hwui.profdata\", benchmarks: [\"hwui\", \"skia\"], enable_profile_use: true, }, } //",
"defs['arm64'] + defs['crc32']), 'none_srcs': bpfmt(16, defs['none']), 'x86_srcs': bpfmt(16, defs['sse2'] +",
"# # Copyright 2016 Google Inc. # # Use of",
"#!/usr/bin/env python # # Copyright 2016 Google Inc. # #",
"\"liblog\", \"libpiex\", \"libpng\", \"libvulkan\", \"libz\", \"libcutils\", \"libnativewindow\", ], static_libs: [",
"s in nanobench_srcs if not s.endswith('.h')} cflags = gn_to_bp_utils.CleanupCFlags(cflags) cflags_cc",
"bpfmt outputs. def bpfmt(indent, lst, sort=True): if sort: lst =",
"nanobench_srcs = {s for s in nanobench_srcs if not s.endswith('.h')}",
"[ $export_includes ], local_include_dirs: [ $local_includes ], srcs: [ $srcs",
"x86 Android. We're pretty sure it's actually 8-byte // alignment.",
"srcs = strip_slashes(js['targets']['//:skia']['sources']) cflags = strip_slashes(js['targets']['//:skia']['cflags']) cflags_cc = strip_slashes(js['targets']['//:skia']['cflags_cc']) local_includes",
"property to false. cc_defaults { name: \"skia_pgo\", pgo: { instrumentation:",
"lst) # OK! We have everything to fill in Android.bp...",
"Skia from GN configuration. import json import os import pprint",
"[ \"libbinder\", \"libutils\", ], } cc_test { name: \"skia_nanobench\", defaults:",
"mips64: { srcs: [ $none_srcs ], }, x86: { srcs:",
"], arch: { arm: { srcs: [ $arm_srcs ], neon:",
"alignment. tests/OverAlignedTest.cpp has more information, // and should fail if",
"cc_defaults { name: \"skia_tool_deps\", defaults: [ \"skia_deps\", \"skia_pgo_no_profile_use\" ], static_libs:",
"\"libbinder\", \"libutils\", ], } cc_test { name: \"skia_nanobench\", defaults: [",
"requires rapidjson third-party 'skia_use_libheif': 'true', 'skia_use_vulkan': 'true', 'target_cpu': '\"none\"', 'target_os':",
"off with a template for Android.bp, # with holes for",
"[ $none_srcs ], }, x86: { srcs: [ $x86_srcs ],",
"open('Android.bp', 'w') as f: print >>f, bp.substitute({ 'export_includes': bpfmt(8, export_includes),",
"we're wrong. \"-Wno-over-aligned\" ], }, x86_64: { srcs: [ $x86_srcs",
"p in lst} srcs = strip_slashes(js['targets']['//:skia']['sources']) cflags = strip_slashes(js['targets']['//:skia']['cflags']) cflags_cc",
"// Clang seems to think new/malloc will only be 4-byte",
"strip_slashes(js['targets']['//:dm']['include_dirs']) nanobench_target = js['targets']['//:nanobench'] nanobench_srcs = strip_slashes(nanobench_target['sources']) nanobench_includes = strip_slashes(nanobench_target['include_dirs'])",
"with open('Android.bp', 'w') as f: print >>f, bp.substitute({ 'export_includes': bpfmt(8,",
"framework builds. local_includes.add(\"platform_tools/android/vulkan\") export_includes.add(\"platform_tools/android/vulkan\") here = os.path.dirname(__file__) defs = gn_to_bp_utils.GetArchSources(os.path.join(here,",
"local_include_dirs: [ $local_includes ], srcs: [ $srcs ], arch: {",
"], } // Build libskia with PGO by default. //",
"for p in lst} srcs = strip_slashes(js['targets']['//:skia']['sources']) cflags = strip_slashes(js['targets']['//:skia']['cflags'])",
"{str(p.lstrip('/')) for p in lst} srcs = strip_slashes(js['targets']['//:skia']['sources']) cflags =",
"[ \"skia_deps\", \"skia_pgo_no_profile_use\" ], static_libs: [ \"libjsoncpp\", \"libskia\", ], cflags:",
"\"skia_tool_deps\", defaults: [ \"skia_deps\", \"skia_pgo_no_profile_use\" ], static_libs: [ \"libjsoncpp\", \"libskia\",",
"run GN to get the main source lists and include",
"// or set enable_profile_use property to false. cc_defaults { name:",
"aligned // on x86 Android. We're pretty sure it's actually",
"import json import os import pprint import string import subprocess",
"to false. cc_defaults { name: \"skia_pgo\", pgo: { instrumentation: true,",
"[\"hwui\", \"skia\"], enable_profile_use: true, }, } // \"defaults\" property to",
"should fail if we're wrong. \"-Wno-over-aligned\" ], }, x86_64: {",
"name: \"skia_deps\", shared_libs: [ \"libEGL\", \"libGLESv2\", \"libdng_sdk\", \"libexpat\", \"libft2\", \"libheif\",",
"\"libvulkan\", \"libz\", \"libcutils\", \"libnativewindow\", ], static_libs: [ \"libarect\", \"libsfntly\", \"libwebp-decode\",",
"This file is autogenerated by gn_to_bp.py. cc_library_static { name: \"libskia\",",
"it's actually 8-byte // alignment. tests/OverAlignedTest.cpp has more information, //",
"as f: print >>f, bp.substitute({ 'export_includes': bpfmt(8, export_includes), 'local_includes': bpfmt(8,",
"'skia') gn_to_bp_utils.GrabDependentValues(js, '//:nanobench', 'sources', nanobench_srcs, 'skia') # skcms is a",
"], } cc_test { name: \"skia_dm\", defaults: [ \"skia_tool_deps\" ],",
"$cflags ], cppflags:[ $cflags_cc ], export_include_dirs: [ $export_includes ], local_include_dirs:",
"'\"none\"', 'target_os': '\"android\"', 'skia_vulkan_header': '\"Skia_Vulkan_Android.h\"', } js = gn_to_bp_utils.GenerateJSONFromGN(gn_args) def",
"bpfmt(16, defs['armv7']), 'arm_neon_srcs': bpfmt(20, defs['neon']), 'arm64_srcs': bpfmt(16, defs['arm64'] + defs['crc32']),",
"[\"skia_deps\", \"skia_pgo\", ], } // Build libskia with PGO by",
"}, x86: { srcs: [ $x86_srcs ], cflags: [ //",
"} cc_defaults { name: \"skia_tool_deps\", defaults: [ \"skia_deps\", \"skia_pgo_no_profile_use\" ],",
"defs = gn_to_bp_utils.GetArchSources(os.path.join(here, 'opts.gni')) gn_to_bp_utils.WriteUserConfig('include/config/SkUserConfig.h', defines) # Turn a list",
"sort: lst = sorted(lst) return ('\\n' + ' '*indent).join('\"%s\",' %",
"defs['none']), 'x86_srcs': bpfmt(16, defs['sse2'] + defs['ssse3'] + defs['sse41'] + defs['sse42']",
"$arm_neon_srcs ], }, }, arm64: { srcs: [ $arm64_srcs ],",
"directories for Skia. gn_args = { 'is_official_build': 'true', 'skia_enable_tools': 'true',",
"style bpfmt outputs. def bpfmt(indent, lst, sort=True): if sort: lst",
"// alignment. tests/OverAlignedTest.cpp has more information, // and should fail",
"dm_srcs = strip_slashes(js['targets']['//:dm']['sources']) dm_includes = strip_slashes(js['targets']['//:dm']['include_dirs']) nanobench_target = js['targets']['//:nanobench'] nanobench_srcs",
"srcs if not s.endswith('.h')} dm_srcs = {s for s in",
"if not s.endswith('.h')} cflags = gn_to_bp_utils.CleanupCFlags(cflags) cflags_cc = gn_to_bp_utils.CleanupCCFlags(cflags_cc) #",
"+ ' '*indent).join('\"%s\",' % v for v in lst) #",
"gn_to_bp_utils.GrabDependentValues(js, '//:skia', 'sources', srcs, None) gn_to_bp_utils.GrabDependentValues(js, '//:dm', 'sources', dm_srcs, 'skia')",
".add(\"third_party/skcms/skcms.c\") local_includes.add(\"third_party/skcms\") dm_includes .add(\"third_party/skcms\") # No need to list headers.",
"in # then skia_vulkan_header gn arg that is used for",
"build/soong/cc/pgo.go // and is separate from skia. // To turn",
"# OK! We have everything to fill in Android.bp... with",
"= {s for s in nanobench_srcs if not s.endswith('.h')} cflags",
"\"libskia\", ], cflags: [ \"-Wno-unused-parameter\", \"-Wno-unused-variable\", ], } cc_test {",
"a little special, kind of a second-party library. srcs .add(\"third_party/skcms/skcms.c\")",
"set enable_profile_use property to false. cc_defaults { name: \"skia_pgo\", pgo:",
"} // Build libskia with PGO by default. // Location",
"\"libicui18n\", \"libicuuc\", \"libjpeg\", \"liblog\", \"libpiex\", \"libpng\", \"libvulkan\", \"libz\", \"libcutils\", \"libnativewindow\",",
"'arm_srcs': bpfmt(16, defs['armv7']), 'arm_neon_srcs': bpfmt(20, defs['neon']), 'arm64_srcs': bpfmt(16, defs['arm64'] +",
"Android.bp for Skia from GN configuration. import json import os",
"false. cc_defaults { name: \"skia_pgo\", pgo: { instrumentation: true, profile_file:",
"set in # then skia_vulkan_header gn arg that is used",
"main source lists and include directories for Skia. gn_args =",
"{s for s in dm_srcs if not s.endswith('.h')} nanobench_srcs =",
"'skia') # skcms is a little special, kind of a",
"def bpfmt(indent, lst, sort=True): if sort: lst = sorted(lst) return",
"\"libutils\", ], } cc_test { name: \"skia_nanobench\", defaults: [ \"skia_tool_deps\"",
"= strip_slashes(nanobench_target['sources']) nanobench_includes = strip_slashes(nanobench_target['include_dirs']) gn_to_bp_utils.GrabDependentValues(js, '//:skia', 'sources', srcs, None)",
"# Turn a list of strings into the style bpfmt",
"separate from skia. // To turn it off, set ANDROID_PGO_NO_PROFILE_USE",
"dm_srcs, 'skia') gn_to_bp_utils.GrabDependentValues(js, '//:nanobench', 'sources', nanobench_srcs, 'skia') # skcms is",
"Inc. # # Use of this source code is governed",
"$none_srcs ], }, x86: { srcs: [ $x86_srcs ], cflags:",
"bpfmt(8, cflags, False), 'cflags_cc': bpfmt(8, cflags_cc), 'arm_srcs': bpfmt(16, defs['armv7']), 'arm_neon_srcs':",
"Skia. gn_args = { 'is_official_build': 'true', 'skia_enable_tools': 'true', 'skia_enable_skottie': 'false',",
"by a BSD-style license that can be # found in",
"shared_libs: [ \"libbinder\", \"libutils\", ], } cc_test { name: \"skia_nanobench\",",
"'arm64_srcs': bpfmt(16, defs['arm64'] + defs['crc32']), 'none_srcs': bpfmt(16, defs['none']), 'x86_srcs': bpfmt(16,",
"enable_profile_use: false, }, } cc_defaults { name: \"skia_deps\", shared_libs: [",
"= strip_slashes(js['targets']['//:public']['include_dirs']) defines = [str(d) for d in js['targets']['//:skia']['defines']] dm_srcs",
"dm_includes = strip_slashes(js['targets']['//:dm']['include_dirs']) nanobench_target = js['targets']['//:nanobench'] nanobench_srcs = strip_slashes(nanobench_target['sources']) nanobench_includes",
"{ name: \"skia_pgo\", pgo: { instrumentation: true, profile_file: \"hwui/hwui.profdata\", benchmarks:",
"], cflags: [ // Clang seems to think new/malloc will",
"[str(d) for d in js['targets']['//:skia']['defines']] dm_srcs = strip_slashes(js['targets']['//:dm']['sources']) dm_includes =",
"% v for v in lst) # OK! We have",
"default. // Location of PGO profile data is defined in",
"srcs = {s for s in srcs if not s.endswith('.h')}",
"'true', 'skia_use_vulkan': 'true', 'target_cpu': '\"none\"', 'target_os': '\"android\"', 'skia_vulkan_header': '\"Skia_Vulkan_Android.h\"', }",
"enable_profile_use property to false. cc_defaults { name: \"skia_pgo\", pgo: {",
"], static_libs: [ \"libjsoncpp\", \"libskia\", ], cflags: [ \"-Wno-unused-parameter\", \"-Wno-unused-variable\",",
"bp = string.Template('''// This file is autogenerated by gn_to_bp.py. cc_library_static",
"[ \"skia_tool_deps\" ], local_include_dirs: [ $dm_includes ], srcs: [ $dm_srcs",
"is a little special, kind of a second-party library. srcs",
"third-party 'skia_use_libheif': 'true', 'skia_use_vulkan': 'true', 'target_cpu': '\"none\"', 'target_os': '\"android\"', 'skia_vulkan_header':",
"\"skia_pgo\", pgo: { instrumentation: true, profile_file: \"hwui/hwui.profdata\", benchmarks: [\"hwui\", \"skia\"],",
"f: print >>f, bp.substitute({ 'export_includes': bpfmt(8, export_includes), 'local_includes': bpfmt(8, local_includes),",
"To turn it off, set ANDROID_PGO_NO_PROFILE_USE environment variable // or",
"x86: { srcs: [ $x86_srcs ], cflags: [ // Clang",
"} cc_test { name: \"skia_nanobench\", defaults: [ \"skia_tool_deps\" ], local_include_dirs:",
"defines = [str(d) for d in js['targets']['//:skia']['defines']] dm_srcs = strip_slashes(js['targets']['//:dm']['sources'])",
"[ // Clang seems to think new/malloc will only be",
"cflags_cc), 'arm_srcs': bpfmt(16, defs['armv7']), 'arm_neon_srcs': bpfmt(20, defs['neon']), 'arm64_srcs': bpfmt(16, defs['arm64']",
"Android.bp, # with holes for source lists and include directories.",
"local_includes), 'srcs': bpfmt(8, srcs), 'cflags': bpfmt(8, cflags, False), 'cflags_cc': bpfmt(8,",
"s.endswith('.h')} dm_srcs = {s for s in dm_srcs if not",
"gn_to_bp_utils.GrabDependentValues(js, '//:nanobench', 'sources', nanobench_srcs, 'skia') # skcms is a little",
"ANDROID_PGO_NO_PROFILE_USE environment variable // or set enable_profile_use property to false.",
"cppflags:[ $cflags_cc ], export_include_dirs: [ $export_includes ], local_include_dirs: [ $local_includes",
"file set in # then skia_vulkan_header gn arg that is",
"}, mips64: { srcs: [ $none_srcs ], }, x86: {",
"\"libpng\", \"libvulkan\", \"libz\", \"libcutils\", \"libnativewindow\", ], static_libs: [ \"libarect\", \"libsfntly\",",
"in lst} srcs = strip_slashes(js['targets']['//:skia']['sources']) cflags = strip_slashes(js['targets']['//:skia']['cflags']) cflags_cc =",
"Android. We're pretty sure it's actually 8-byte // alignment. tests/OverAlignedTest.cpp",
"], export_include_dirs: [ $export_includes ], local_include_dirs: [ $local_includes ], srcs:",
"defs['sse42'] + defs['avx' ] + defs['hsw' ]), 'dm_includes' : bpfmt(8,",
"bpfmt(16, defs['none']), 'x86_srcs': bpfmt(16, defs['sse2'] + defs['ssse3'] + defs['sse41'] +",
"'skia_enable_tools': 'true', 'skia_enable_skottie': 'false', # requires rapidjson third-party 'skia_use_libheif': 'true',",
"a template for Android.bp, # with holes for source lists",
"from GN configuration. import json import os import pprint import",
"= {s for s in srcs if not s.endswith('.h')} dm_srcs",
"[ \"libarect\", \"libsfntly\", \"libwebp-decode\", \"libwebp-encode\", ], group_static_libs: true, } cc_defaults",
"srcs: [ $x86_srcs ], }, }, defaults: [\"skia_deps\", \"skia_pgo\", ],",
"and should fail if we're wrong. \"-Wno-over-aligned\" ], }, x86_64:",
"true, profile_file: \"hwui/hwui.profdata\", benchmarks: [\"hwui\", \"skia\"], enable_profile_use: true, }, }",
"true, } cc_defaults { name: \"skia_tool_deps\", defaults: [ \"skia_deps\", \"skia_pgo_no_profile_use\"",
"arm64: { srcs: [ $arm64_srcs ], }, mips: { srcs:",
"need to list headers. srcs = {s for s in",
"strip_slashes(js['targets']['//:public']['include_dirs']) defines = [str(d) for d in js['targets']['//:skia']['defines']] dm_srcs =",
"strip_slashes(nanobench_target['sources']) nanobench_includes = strip_slashes(nanobench_target['include_dirs']) gn_to_bp_utils.GrabDependentValues(js, '//:skia', 'sources', srcs, None) gn_to_bp_utils.GrabDependentValues(js,",
"$none_srcs ], }, mips64: { srcs: [ $none_srcs ], },",
"subprocess import tempfile import gn_to_bp_utils # First we start off",
"local_includes.add(\"third_party/skcms\") dm_includes .add(\"third_party/skcms\") # No need to list headers. srcs",
"dm_includes .add(\"third_party/skcms\") # No need to list headers. srcs =",
"We have everything to fill in Android.bp... with open('Android.bp', 'w')",
"import subprocess import tempfile import gn_to_bp_utils # First we start",
"First we start off with a template for Android.bp, #",
"and header file set in # then skia_vulkan_header gn arg",
"import os import pprint import string import subprocess import tempfile",
"\"libwebp-decode\", \"libwebp-encode\", ], group_static_libs: true, } cc_defaults { name: \"skia_tool_deps\",",
"if not s.endswith('.h')} dm_srcs = {s for s in dm_srcs",
"'none_srcs': bpfmt(16, defs['none']), 'x86_srcs': bpfmt(16, defs['sse2'] + defs['ssse3'] + defs['sse41']",
"turn it off, set ANDROID_PGO_NO_PROFILE_USE environment variable // or set",
"]), 'dm_includes' : bpfmt(8, dm_includes), 'dm_srcs' : bpfmt(8, dm_srcs), 'nanobench_includes'",
"# Generate Android.bp for Skia from GN configuration. import json",
"$arm_srcs ], neon: { srcs: [ $arm_neon_srcs ], }, },",
"true, }, } // \"defaults\" property to disable profile use",
"gn_to_bp_utils.WriteUserConfig('include/config/SkUserConfig.h', defines) # Turn a list of strings into the",
"= js['targets']['//:nanobench'] nanobench_srcs = strip_slashes(nanobench_target['sources']) nanobench_includes = strip_slashes(nanobench_target['include_dirs']) gn_to_bp_utils.GrabDependentValues(js, '//:skia',",
"\"libcutils\", \"libnativewindow\", ], static_libs: [ \"libarect\", \"libsfntly\", \"libwebp-decode\", \"libwebp-encode\", ],",
"import string import subprocess import tempfile import gn_to_bp_utils # First",
"defines) # Turn a list of strings into the style",
"# No need to list headers. srcs = {s for",
"// and should fail if we're wrong. \"-Wno-over-aligned\" ], },",
"PGO profile data is defined in build/soong/cc/pgo.go // and is",
"fail if we're wrong. \"-Wno-over-aligned\" ], }, x86_64: { srcs:",
"for Android.bp, # with holes for source lists and include",
"cflags: [ // Clang seems to think new/malloc will only",
"'false', # requires rapidjson third-party 'skia_use_libheif': 'true', 'skia_use_vulkan': 'true', 'target_cpu':",
"shared_libs: [ \"libEGL\", \"libGLESv2\", \"libdng_sdk\", \"libexpat\", \"libft2\", \"libheif\", \"libicui18n\", \"libicuuc\",",
"Clang seems to think new/malloc will only be 4-byte aligned",
"static_libs: [ \"libarect\", \"libsfntly\", \"libwebp-decode\", \"libwebp-encode\", ], group_static_libs: true, }",
"of strings into the style bpfmt outputs. def bpfmt(indent, lst,",
"export_includes.add(\"platform_tools/android/vulkan\") here = os.path.dirname(__file__) defs = gn_to_bp_utils.GetArchSources(os.path.join(here, 'opts.gni')) gn_to_bp_utils.WriteUserConfig('include/config/SkUserConfig.h', defines)",
"'srcs': bpfmt(8, srcs), 'cflags': bpfmt(8, cflags, False), 'cflags_cc': bpfmt(8, cflags_cc),",
"[ $arm64_srcs ], }, mips: { srcs: [ $none_srcs ],",
"] + defs['hsw' ]), 'dm_includes' : bpfmt(8, dm_includes), 'dm_srcs' :",
"Android.bp... with open('Android.bp', 'w') as f: print >>f, bp.substitute({ 'export_includes':",
"libskia with PGO by default. // Location of PGO profile",
"by default. // Location of PGO profile data is defined",
"'opts.gni')) gn_to_bp_utils.WriteUserConfig('include/config/SkUserConfig.h', defines) # Turn a list of strings into",
"data: [ \"resources/*\", ], }''') # We'll run GN to",
"bpfmt(16, defs['sse2'] + defs['ssse3'] + defs['sse41'] + defs['sse42'] + defs['avx'",
"strip_slashes(js['targets']['//:skia']['cflags_cc']) local_includes = strip_slashes(js['targets']['//:skia']['include_dirs']) export_includes = strip_slashes(js['targets']['//:public']['include_dirs']) defines = [str(d)",
"# Copyright 2016 Google Inc. # # Use of this",
"], pgo: { enable_profile_use: false, }, } cc_defaults { name:",
"s in dm_srcs if not s.endswith('.h')} nanobench_srcs = {s for",
"}, arm64: { srcs: [ $arm64_srcs ], }, mips: {",
"nanobench_target = js['targets']['//:nanobench'] nanobench_srcs = strip_slashes(nanobench_target['sources']) nanobench_includes = strip_slashes(nanobench_target['include_dirs']) gn_to_bp_utils.GrabDependentValues(js,",
"tools and benchmarks. cc_defaults { name: \"skia_pgo_no_profile_use\", defaults: [ \"skia_pgo\",",
"'target_os': '\"android\"', 'skia_vulkan_header': '\"Skia_Vulkan_Android.h\"', } js = gn_to_bp_utils.GenerateJSONFromGN(gn_args) def strip_slashes(lst):",
"'arm_neon_srcs': bpfmt(20, defs['neon']), 'arm64_srcs': bpfmt(16, defs['arm64'] + defs['crc32']), 'none_srcs': bpfmt(16,",
"in Android.bp... with open('Android.bp', 'w') as f: print >>f, bp.substitute({",
"name: \"skia_pgo\", pgo: { instrumentation: true, profile_file: \"hwui/hwui.profdata\", benchmarks: [\"hwui\",",
"\"libjsoncpp\", \"libskia\", ], cflags: [ \"-Wno-unused-parameter\", \"-Wno-unused-variable\", ], } cc_test",
"// Location of PGO profile data is defined in build/soong/cc/pgo.go",
"in nanobench_srcs if not s.endswith('.h')} cflags = gn_to_bp_utils.CleanupCFlags(cflags) cflags_cc =",
"'sources', nanobench_srcs, 'skia') # skcms is a little special, kind",
"defs['sse2'] + defs['ssse3'] + defs['sse41'] + defs['sse42'] + defs['avx' ]",
"GN configuration. import json import os import pprint import string",
"to disable profile use for Skia tools and benchmarks. cc_defaults",
"dm_srcs if not s.endswith('.h')} nanobench_srcs = {s for s in",
"srcs: [ $arm_srcs ], neon: { srcs: [ $arm_neon_srcs ],",
"'skia_vulkan_header': '\"Skia_Vulkan_Android.h\"', } js = gn_to_bp_utils.GenerateJSONFromGN(gn_args) def strip_slashes(lst): return {str(p.lstrip('/'))",
"], }, x86: { srcs: [ $x86_srcs ], cflags: [",
"= strip_slashes(js['targets']['//:skia']['cflags']) cflags_cc = strip_slashes(js['targets']['//:skia']['cflags_cc']) local_includes = strip_slashes(js['targets']['//:skia']['include_dirs']) export_includes =",
"\"libsfntly\", \"libwebp-decode\", \"libwebp-encode\", ], group_static_libs: true, } cc_defaults { name:",
"and include directories. bp = string.Template('''// This file is autogenerated",
"{ 'is_official_build': 'true', 'skia_enable_tools': 'true', 'skia_enable_skottie': 'false', # requires rapidjson",
"if we're wrong. \"-Wno-over-aligned\" ], }, x86_64: { srcs: [",
"// and is separate from skia. // To turn it",
"[ $dm_includes ], srcs: [ $dm_srcs ], shared_libs: [ \"libbinder\",",
"\"libskia\", cflags: [ $cflags ], cppflags:[ $cflags_cc ], export_include_dirs: [",
"{ name: \"skia_dm\", defaults: [ \"skia_tool_deps\" ], local_include_dirs: [ $dm_includes",
"pgo: { enable_profile_use: false, }, } cc_defaults { name: \"skia_deps\",",
"Google Inc. # # Use of this source code is",
"[ \"resources/*\", ], }''') # We'll run GN to get",
"arm: { srcs: [ $arm_srcs ], neon: { srcs: [",
"profile use for Skia tools and benchmarks. cc_defaults { name:",
"# found in the LICENSE file. # Generate Android.bp for",
"local_include_dirs: [ $nanobench_includes ], srcs: [ $nanobench_srcs ], data: [",
"$dm_srcs ], shared_libs: [ \"libbinder\", \"libutils\", ], } cc_test {",
"use for Skia tools and benchmarks. cc_defaults { name: \"skia_pgo_no_profile_use\",",
"} js = gn_to_bp_utils.GenerateJSONFromGN(gn_args) def strip_slashes(lst): return {str(p.lstrip('/')) for p",
"gn arg that is used for framework builds. local_includes.add(\"platform_tools/android/vulkan\") export_includes.add(\"platform_tools/android/vulkan\")",
"set ANDROID_PGO_NO_PROFILE_USE environment variable // or set enable_profile_use property to"
] |
[
"\"setting-up\" STATUS_UPDATE_FAILED = \"update-failed\" STATUS_UP_TO_DATE = \"up-to-date\" # Tag uniquely",
"\"update-failed\" STATUS_UP_TO_DATE = \"up-to-date\" # Tag uniquely identifying all nodes",
"the node TAG_RAY_NODE_NAME = \"ray-node-name\" # Tag for the kind",
"used to determine if updates are needed TAG_RAY_RUNTIME_CONFIG = \"ray-runtime-config\"",
"kind of node (e.g. Head, Worker). For legacy reasons, the",
"NODE_KIND_HEAD = \"head\" NODE_KIND_WORKER = \"worker\" NODE_KIND_UNMANAGED = \"unmanaged\" #",
"in the cluster configs. NODE_TYPE_LEGACY_HEAD = \"ray-legacy-head-node-type\" NODE_TYPE_LEGACY_WORKER = \"ray-legacy-worker-node-type\"",
"node launch config, used to identify out-of-date nodes TAG_RAY_LAUNCH_CONFIG =",
"# Tag for user defined node types (e.g., m4xl_spot). This",
"directories specified by the file_mounts config # if the node",
"user defined node types (e.g., m4xl_spot). This is used for",
"types for legacy cluster yamls without multi # node type",
"with instances.\"\"\" # Tag for the name of the node",
"for multi # node type clusters. TAG_RAY_USER_NODE_TYPE = \"ray-user-node-type\" #",
"the node (e.g. Updating, Up-to-date) TAG_RAY_NODE_STATUS = \"ray-node-status\" STATUS_UNINITIALIZED =",
"current state of the node (e.g. Updating, Up-to-date) TAG_RAY_NODE_STATUS =",
"cluster configs. NODE_TYPE_LEGACY_HEAD = \"ray-legacy-head-node-type\" NODE_TYPE_LEGACY_WORKER = \"ray-legacy-worker-node-type\" # Tag",
"autofilled node types for legacy cluster yamls without multi #",
"'kind'. TAG_RAY_NODE_KIND = \"ray-node-type\" NODE_KIND_HEAD = \"head\" NODE_KIND_WORKER = \"worker\"",
"\"ray-user-node-type\" # Tag for autofilled node types for legacy cluster",
"= \"ray-node-type\" NODE_KIND_HEAD = \"head\" NODE_KIND_WORKER = \"worker\" NODE_KIND_UNMANAGED =",
"the contents of the directories specified by the file_mounts config",
"Tag for the name of the node TAG_RAY_NODE_NAME = \"ray-node-name\"",
"\"unmanaged\" # Tag for user defined node types (e.g., m4xl_spot).",
"# node type clusters. TAG_RAY_USER_NODE_TYPE = \"ray-user-node-type\" # Tag for",
"node TAG_RAY_NODE_NAME = \"ray-node-name\" # Tag for the kind of",
"= \"ray-legacy-worker-node-type\" # Tag that reports the current state of",
"config, used to determine if updates are needed TAG_RAY_RUNTIME_CONFIG =",
"(e.g., m4xl_spot). This is used for multi # node type",
"Worker). For legacy reasons, the tag # value says 'type'",
"legacy cluster yamls without multi # node type defined in",
"multi # node type defined in the cluster configs. NODE_TYPE_LEGACY_HEAD",
"\"ray-launch-config\" # Hash of the node runtime config, used to",
"config # if the node is a worker, this also",
"STATUS_SETTING_UP = \"setting-up\" STATUS_UPDATE_FAILED = \"update-failed\" STATUS_UP_TO_DATE = \"up-to-date\" #",
"Tag for autofilled node types for legacy cluster yamls without",
"# Tag for autofilled node types for legacy cluster yamls",
"a cluster TAG_RAY_CLUSTER_NAME = \"ray-cluster-name\" # Hash of the node",
"= \"ray-cluster-name\" # Hash of the node launch config, used",
"determine if updates are needed TAG_RAY_RUNTIME_CONFIG = \"ray-runtime-config\" # Hash",
"worker, this also hashes content of the directories # specified",
"of the node runtime config, used to determine if updates",
"# Tag uniquely identifying all nodes of a cluster TAG_RAY_CLUSTER_NAME",
"this also hashes content of the directories # specified by",
"config, used to identify out-of-date nodes TAG_RAY_LAUNCH_CONFIG = \"ray-launch-config\" #",
"of 'kind'. TAG_RAY_NODE_KIND = \"ray-node-type\" NODE_KIND_HEAD = \"head\" NODE_KIND_WORKER =",
"state of the node (e.g. Updating, Up-to-date) TAG_RAY_NODE_STATUS = \"ray-node-status\"",
"cluster yamls without multi # node type defined in the",
"associate metadata with instances.\"\"\" # Tag for the name of",
"TAG_RAY_RUNTIME_CONFIG = \"ray-runtime-config\" # Hash of the contents of the",
"\"worker\" NODE_KIND_UNMANAGED = \"unmanaged\" # Tag for user defined node",
"Hash of the node runtime config, used to determine if",
"directories # specified by the cluster_synced_files config TAG_RAY_FILE_MOUNTS_CONTENTS = \"ray-file-mounts-contents\"",
"defined node types (e.g., m4xl_spot). This is used for multi",
"Hash of the contents of the directories specified by the",
"type defined in the cluster configs. NODE_TYPE_LEGACY_HEAD = \"ray-legacy-head-node-type\" NODE_TYPE_LEGACY_WORKER",
"reports the current state of the node (e.g. Updating, Up-to-date)",
"\"waiting-for-ssh\" STATUS_SYNCING_FILES = \"syncing-files\" STATUS_SETTING_UP = \"setting-up\" STATUS_UPDATE_FAILED = \"update-failed\"",
"Updating, Up-to-date) TAG_RAY_NODE_STATUS = \"ray-node-status\" STATUS_UNINITIALIZED = \"uninitialized\" STATUS_WAITING_FOR_SSH =",
"of the directories # specified by the cluster_synced_files config TAG_RAY_FILE_MOUNTS_CONTENTS",
"launch config, used to identify out-of-date nodes TAG_RAY_LAUNCH_CONFIG = \"ray-launch-config\"",
"STATUS_WAITING_FOR_SSH = \"waiting-for-ssh\" STATUS_SYNCING_FILES = \"syncing-files\" STATUS_SETTING_UP = \"setting-up\" STATUS_UPDATE_FAILED",
"identifying all nodes of a cluster TAG_RAY_CLUSTER_NAME = \"ray-cluster-name\" #",
"= \"ray-legacy-head-node-type\" NODE_TYPE_LEGACY_WORKER = \"ray-legacy-worker-node-type\" # Tag that reports the",
"TAG_RAY_CLUSTER_NAME = \"ray-cluster-name\" # Hash of the node launch config,",
"= \"ray-node-status\" STATUS_UNINITIALIZED = \"uninitialized\" STATUS_WAITING_FOR_SSH = \"waiting-for-ssh\" STATUS_SYNCING_FILES =",
"\"ray-cluster-name\" # Hash of the node launch config, used to",
"cluster TAG_RAY_CLUSTER_NAME = \"ray-cluster-name\" # Hash of the node launch",
"if the node is a worker, this also hashes content",
"m4xl_spot). This is used for multi # node type clusters.",
"TAG_RAY_USER_NODE_TYPE = \"ray-user-node-type\" # Tag for autofilled node types for",
"Head, Worker). For legacy reasons, the tag # value says",
"of the node (e.g. Updating, Up-to-date) TAG_RAY_NODE_STATUS = \"ray-node-status\" STATUS_UNINITIALIZED",
"\"\"\"The Ray autoscaler uses tags/labels to associate metadata with instances.\"\"\"",
"name of the node TAG_RAY_NODE_NAME = \"ray-node-name\" # Tag for",
"of node (e.g. Head, Worker). For legacy reasons, the tag",
"all nodes of a cluster TAG_RAY_CLUSTER_NAME = \"ray-cluster-name\" # Hash",
"autoscaler uses tags/labels to associate metadata with instances.\"\"\" # Tag",
"= \"ray-node-name\" # Tag for the kind of node (e.g.",
"multi # node type clusters. TAG_RAY_USER_NODE_TYPE = \"ray-user-node-type\" # Tag",
"node types for legacy cluster yamls without multi # node",
"NODE_TYPE_LEGACY_HEAD = \"ray-legacy-head-node-type\" NODE_TYPE_LEGACY_WORKER = \"ray-legacy-worker-node-type\" # Tag that reports",
"node (e.g. Head, Worker). For legacy reasons, the tag #",
"updates are needed TAG_RAY_RUNTIME_CONFIG = \"ray-runtime-config\" # Hash of the",
"specified by the file_mounts config # if the node is",
"needed TAG_RAY_RUNTIME_CONFIG = \"ray-runtime-config\" # Hash of the contents of",
"node types (e.g., m4xl_spot). This is used for multi #",
"Tag uniquely identifying all nodes of a cluster TAG_RAY_CLUSTER_NAME =",
"\"head\" NODE_KIND_WORKER = \"worker\" NODE_KIND_UNMANAGED = \"unmanaged\" # Tag for",
"metadata with instances.\"\"\" # Tag for the name of the",
"the kind of node (e.g. Head, Worker). For legacy reasons,",
"'type' instead of 'kind'. TAG_RAY_NODE_KIND = \"ray-node-type\" NODE_KIND_HEAD = \"head\"",
"of the node launch config, used to identify out-of-date nodes",
"for the kind of node (e.g. Head, Worker). For legacy",
"For legacy reasons, the tag # value says 'type' instead",
"TAG_RAY_NODE_KIND = \"ray-node-type\" NODE_KIND_HEAD = \"head\" NODE_KIND_WORKER = \"worker\" NODE_KIND_UNMANAGED",
"\"ray-node-status\" STATUS_UNINITIALIZED = \"uninitialized\" STATUS_WAITING_FOR_SSH = \"waiting-for-ssh\" STATUS_SYNCING_FILES = \"syncing-files\"",
"NODE_TYPE_LEGACY_WORKER = \"ray-legacy-worker-node-type\" # Tag that reports the current state",
"to associate metadata with instances.\"\"\" # Tag for the name",
"TAG_RAY_LAUNCH_CONFIG = \"ray-launch-config\" # Hash of the node runtime config,",
"\"up-to-date\" # Tag uniquely identifying all nodes of a cluster",
"used to identify out-of-date nodes TAG_RAY_LAUNCH_CONFIG = \"ray-launch-config\" # Hash",
"of the directories specified by the file_mounts config # if",
"the node is a worker, this also hashes content of",
"NODE_KIND_UNMANAGED = \"unmanaged\" # Tag for user defined node types",
"out-of-date nodes TAG_RAY_LAUNCH_CONFIG = \"ray-launch-config\" # Hash of the node",
"also hashes content of the directories # specified by the",
"# if the node is a worker, this also hashes",
"# Tag that reports the current state of the node",
"Tag that reports the current state of the node (e.g.",
"STATUS_UP_TO_DATE = \"up-to-date\" # Tag uniquely identifying all nodes of",
"configs. NODE_TYPE_LEGACY_HEAD = \"ray-legacy-head-node-type\" NODE_TYPE_LEGACY_WORKER = \"ray-legacy-worker-node-type\" # Tag that",
"node runtime config, used to determine if updates are needed",
"\"ray-node-name\" # Tag for the kind of node (e.g. Head,",
"used for multi # node type clusters. TAG_RAY_USER_NODE_TYPE = \"ray-user-node-type\"",
"Ray autoscaler uses tags/labels to associate metadata with instances.\"\"\" #",
"for autofilled node types for legacy cluster yamls without multi",
"= \"up-to-date\" # Tag uniquely identifying all nodes of a",
"the file_mounts config # if the node is a worker,",
"# value says 'type' instead of 'kind'. TAG_RAY_NODE_KIND = \"ray-node-type\"",
"STATUS_UPDATE_FAILED = \"update-failed\" STATUS_UP_TO_DATE = \"up-to-date\" # Tag uniquely identifying",
"TAG_RAY_NODE_NAME = \"ray-node-name\" # Tag for the kind of node",
"is used for multi # node type clusters. TAG_RAY_USER_NODE_TYPE =",
"file_mounts config # if the node is a worker, this",
"a worker, this also hashes content of the directories #",
"Tag for user defined node types (e.g., m4xl_spot). This is",
"= \"uninitialized\" STATUS_WAITING_FOR_SSH = \"waiting-for-ssh\" STATUS_SYNCING_FILES = \"syncing-files\" STATUS_SETTING_UP =",
"= \"waiting-for-ssh\" STATUS_SYNCING_FILES = \"syncing-files\" STATUS_SETTING_UP = \"setting-up\" STATUS_UPDATE_FAILED =",
"the node launch config, used to identify out-of-date nodes TAG_RAY_LAUNCH_CONFIG",
"node is a worker, this also hashes content of the",
"TAG_RAY_NODE_STATUS = \"ray-node-status\" STATUS_UNINITIALIZED = \"uninitialized\" STATUS_WAITING_FOR_SSH = \"waiting-for-ssh\" STATUS_SYNCING_FILES",
"for the name of the node TAG_RAY_NODE_NAME = \"ray-node-name\" #",
"instead of 'kind'. TAG_RAY_NODE_KIND = \"ray-node-type\" NODE_KIND_HEAD = \"head\" NODE_KIND_WORKER",
"the name of the node TAG_RAY_NODE_NAME = \"ray-node-name\" # Tag",
"NODE_KIND_WORKER = \"worker\" NODE_KIND_UNMANAGED = \"unmanaged\" # Tag for user",
"the current state of the node (e.g. Updating, Up-to-date) TAG_RAY_NODE_STATUS",
"content of the directories # specified by the cluster_synced_files config",
"STATUS_UNINITIALIZED = \"uninitialized\" STATUS_WAITING_FOR_SSH = \"waiting-for-ssh\" STATUS_SYNCING_FILES = \"syncing-files\" STATUS_SETTING_UP",
"STATUS_SYNCING_FILES = \"syncing-files\" STATUS_SETTING_UP = \"setting-up\" STATUS_UPDATE_FAILED = \"update-failed\" STATUS_UP_TO_DATE",
"= \"setting-up\" STATUS_UPDATE_FAILED = \"update-failed\" STATUS_UP_TO_DATE = \"up-to-date\" # Tag",
"the tag # value says 'type' instead of 'kind'. TAG_RAY_NODE_KIND",
"without multi # node type defined in the cluster configs.",
"\"ray-node-type\" NODE_KIND_HEAD = \"head\" NODE_KIND_WORKER = \"worker\" NODE_KIND_UNMANAGED = \"unmanaged\"",
"\"ray-legacy-head-node-type\" NODE_TYPE_LEGACY_WORKER = \"ray-legacy-worker-node-type\" # Tag that reports the current",
"defined in the cluster configs. NODE_TYPE_LEGACY_HEAD = \"ray-legacy-head-node-type\" NODE_TYPE_LEGACY_WORKER =",
"the node runtime config, used to determine if updates are",
"to determine if updates are needed TAG_RAY_RUNTIME_CONFIG = \"ray-runtime-config\" #",
"\"ray-runtime-config\" # Hash of the contents of the directories specified",
"value says 'type' instead of 'kind'. TAG_RAY_NODE_KIND = \"ray-node-type\" NODE_KIND_HEAD",
"reasons, the tag # value says 'type' instead of 'kind'.",
"that reports the current state of the node (e.g. Updating,",
"for user defined node types (e.g., m4xl_spot). This is used",
"of the contents of the directories specified by the file_mounts",
"clusters. TAG_RAY_USER_NODE_TYPE = \"ray-user-node-type\" # Tag for autofilled node types",
"identify out-of-date nodes TAG_RAY_LAUNCH_CONFIG = \"ray-launch-config\" # Hash of the",
"runtime config, used to determine if updates are needed TAG_RAY_RUNTIME_CONFIG",
"node type clusters. TAG_RAY_USER_NODE_TYPE = \"ray-user-node-type\" # Tag for autofilled",
"# Hash of the node launch config, used to identify",
"= \"update-failed\" STATUS_UP_TO_DATE = \"up-to-date\" # Tag uniquely identifying all",
"= \"ray-runtime-config\" # Hash of the contents of the directories",
"Up-to-date) TAG_RAY_NODE_STATUS = \"ray-node-status\" STATUS_UNINITIALIZED = \"uninitialized\" STATUS_WAITING_FOR_SSH = \"waiting-for-ssh\"",
"\"syncing-files\" STATUS_SETTING_UP = \"setting-up\" STATUS_UPDATE_FAILED = \"update-failed\" STATUS_UP_TO_DATE = \"up-to-date\"",
"= \"unmanaged\" # Tag for user defined node types (e.g.,",
"Hash of the node launch config, used to identify out-of-date",
"Tag for the kind of node (e.g. Head, Worker). For",
"\"uninitialized\" STATUS_WAITING_FOR_SSH = \"waiting-for-ssh\" STATUS_SYNCING_FILES = \"syncing-files\" STATUS_SETTING_UP = \"setting-up\"",
"the directories # specified by the cluster_synced_files config TAG_RAY_FILE_MOUNTS_CONTENTS =",
"legacy reasons, the tag # value says 'type' instead of",
"types (e.g., m4xl_spot). This is used for multi # node",
"# node type defined in the cluster configs. NODE_TYPE_LEGACY_HEAD =",
"uniquely identifying all nodes of a cluster TAG_RAY_CLUSTER_NAME = \"ray-cluster-name\"",
"nodes of a cluster TAG_RAY_CLUSTER_NAME = \"ray-cluster-name\" # Hash of",
"nodes TAG_RAY_LAUNCH_CONFIG = \"ray-launch-config\" # Hash of the node runtime",
"is a worker, this also hashes content of the directories",
"the directories specified by the file_mounts config # if the",
"are needed TAG_RAY_RUNTIME_CONFIG = \"ray-runtime-config\" # Hash of the contents",
"= \"head\" NODE_KIND_WORKER = \"worker\" NODE_KIND_UNMANAGED = \"unmanaged\" # Tag",
"= \"ray-launch-config\" # Hash of the node runtime config, used",
"# Tag for the kind of node (e.g. Head, Worker).",
"hashes content of the directories # specified by the cluster_synced_files",
"of the node TAG_RAY_NODE_NAME = \"ray-node-name\" # Tag for the",
"tags/labels to associate metadata with instances.\"\"\" # Tag for the",
"This is used for multi # node type clusters. TAG_RAY_USER_NODE_TYPE",
"# Hash of the node runtime config, used to determine",
"of a cluster TAG_RAY_CLUSTER_NAME = \"ray-cluster-name\" # Hash of the",
"says 'type' instead of 'kind'. TAG_RAY_NODE_KIND = \"ray-node-type\" NODE_KIND_HEAD =",
"node (e.g. Updating, Up-to-date) TAG_RAY_NODE_STATUS = \"ray-node-status\" STATUS_UNINITIALIZED = \"uninitialized\"",
"= \"worker\" NODE_KIND_UNMANAGED = \"unmanaged\" # Tag for user defined",
"the cluster configs. NODE_TYPE_LEGACY_HEAD = \"ray-legacy-head-node-type\" NODE_TYPE_LEGACY_WORKER = \"ray-legacy-worker-node-type\" #",
"= \"ray-user-node-type\" # Tag for autofilled node types for legacy",
"yamls without multi # node type defined in the cluster",
"# Tag for the name of the node TAG_RAY_NODE_NAME =",
"for legacy cluster yamls without multi # node type defined",
"(e.g. Updating, Up-to-date) TAG_RAY_NODE_STATUS = \"ray-node-status\" STATUS_UNINITIALIZED = \"uninitialized\" STATUS_WAITING_FOR_SSH",
"tag # value says 'type' instead of 'kind'. TAG_RAY_NODE_KIND =",
"(e.g. Head, Worker). For legacy reasons, the tag # value",
"= \"syncing-files\" STATUS_SETTING_UP = \"setting-up\" STATUS_UPDATE_FAILED = \"update-failed\" STATUS_UP_TO_DATE =",
"if updates are needed TAG_RAY_RUNTIME_CONFIG = \"ray-runtime-config\" # Hash of",
"# Hash of the contents of the directories specified by",
"instances.\"\"\" # Tag for the name of the node TAG_RAY_NODE_NAME",
"node type defined in the cluster configs. NODE_TYPE_LEGACY_HEAD = \"ray-legacy-head-node-type\"",
"\"ray-legacy-worker-node-type\" # Tag that reports the current state of the",
"contents of the directories specified by the file_mounts config #",
"to identify out-of-date nodes TAG_RAY_LAUNCH_CONFIG = \"ray-launch-config\" # Hash of",
"uses tags/labels to associate metadata with instances.\"\"\" # Tag for",
"type clusters. TAG_RAY_USER_NODE_TYPE = \"ray-user-node-type\" # Tag for autofilled node",
"by the file_mounts config # if the node is a"
] |
[
"to have less land than before at the borders el_before",
"/ n_cells_on_border def test_center_land(self): w = World.from_pickle_file(\"%s/plates_279.world\" % self.tests_data_dir) #",
"@staticmethod def _mean_elevation_at_borders(world): borders_total_elevation = 0.0 for y in range(world.height):",
"range(world.height): borders_total_elevation += world.elevation_at((0, y)) borders_total_elevation += world.elevation_at((world.width - 1,",
"y)) for x in range(1, world.width - 1): borders_total_elevation +=",
"land than before at the borders el_before = TestGeneration._mean_elevation_at_borders(w) center_land(w)",
"less land than before at the borders el_before = TestGeneration._mean_elevation_at_borders(w)",
"borders_total_elevation = 0.0 for y in range(world.height): borders_total_elevation += world.elevation_at((0,",
"- 1)) n_cells_on_border = world.width * 2 + world.height *",
"tests are in place # Very stupid test that just",
"badly world_gen(\"Dummy\", 32, 16, 1, step=Step.get_by_name(\"full\")) @staticmethod def _mean_elevation_at_borders(world): borders_total_elevation",
"def setUp(self): super(TestGeneration, self).setUp() def test_world_gen_does_not_explode_badly(self): # FIXME remove me",
"super(TestGeneration, self).setUp() def test_world_gen_does_not_explode_badly(self): # FIXME remove me when proper",
"1)) n_cells_on_border = world.width * 2 + world.height * 2",
"class TestGeneration(TestBase): def setUp(self): super(TestGeneration, self).setUp() def test_world_gen_does_not_explode_badly(self): # FIXME",
"+= world.elevation_at((0, y)) borders_total_elevation += world.elevation_at((world.width - 1, y)) for",
"worldengine.world import World from tests.draw_test import TestBase class TestGeneration(TestBase): def",
"0)) borders_total_elevation += world.elevation_at((x, world.height - 1)) n_cells_on_border = world.width",
"for y in range(world.height): borders_total_elevation += world.elevation_at((0, y)) borders_total_elevation +=",
"center_land(w) el_after = TestGeneration._mean_elevation_at_borders(w) self.assertTrue(el_after <= el_before) if __name__ ==",
"for x in range(1, world.width - 1): borders_total_elevation += world.elevation_at((x,",
"borders el_before = TestGeneration._mean_elevation_at_borders(w) center_land(w) el_after = TestGeneration._mean_elevation_at_borders(w) self.assertTrue(el_after <=",
"in place # Very stupid test that just verify nothing",
"import TestBase class TestGeneration(TestBase): def setUp(self): super(TestGeneration, self).setUp() def test_world_gen_does_not_explode_badly(self):",
"def test_center_land(self): w = World.from_pickle_file(\"%s/plates_279.world\" % self.tests_data_dir) # We want",
"def test_world_gen_does_not_explode_badly(self): # FIXME remove me when proper tests are",
"range(1, world.width - 1): borders_total_elevation += world.elevation_at((x, 0)) borders_total_elevation +=",
"world.height - 1)) n_cells_on_border = world.width * 2 + world.height",
"+ world.height * 2 - 4 return borders_total_elevation / n_cells_on_border",
"+= world.elevation_at((x, world.height - 1)) n_cells_on_border = world.width * 2",
"4 return borders_total_elevation / n_cells_on_border def test_center_land(self): w = World.from_pickle_file(\"%s/plates_279.world\"",
"before at the borders el_before = TestGeneration._mean_elevation_at_borders(w) center_land(w) el_after =",
"= 0.0 for y in range(world.height): borders_total_elevation += world.elevation_at((0, y))",
"world.width - 1): borders_total_elevation += world.elevation_at((x, 0)) borders_total_elevation += world.elevation_at((x,",
"tests.draw_test import TestBase class TestGeneration(TestBase): def setUp(self): super(TestGeneration, self).setUp() def",
"el_after = TestGeneration._mean_elevation_at_borders(w) self.assertTrue(el_after <= el_before) if __name__ == '__main__':",
"just verify nothing explode badly world_gen(\"Dummy\", 32, 16, 1, step=Step.get_by_name(\"full\"))",
"than before at the borders el_before = TestGeneration._mean_elevation_at_borders(w) center_land(w) el_after",
"place # Very stupid test that just verify nothing explode",
"self).setUp() def test_world_gen_does_not_explode_badly(self): # FIXME remove me when proper tests",
"borders_total_elevation / n_cells_on_border def test_center_land(self): w = World.from_pickle_file(\"%s/plates_279.world\" % self.tests_data_dir)",
"unittest from worldengine.plates import Step, center_land, world_gen from worldengine.world import",
"2 - 4 return borders_total_elevation / n_cells_on_border def test_center_land(self): w",
"32, 16, 1, step=Step.get_by_name(\"full\")) @staticmethod def _mean_elevation_at_borders(world): borders_total_elevation = 0.0",
"% self.tests_data_dir) # We want to have less land than",
"y)) borders_total_elevation += world.elevation_at((world.width - 1, y)) for x in",
"import unittest from worldengine.plates import Step, center_land, world_gen from worldengine.world",
"borders_total_elevation += world.elevation_at((0, y)) borders_total_elevation += world.elevation_at((world.width - 1, y))",
"worldengine.plates import Step, center_land, world_gen from worldengine.world import World from",
"1, step=Step.get_by_name(\"full\")) @staticmethod def _mean_elevation_at_borders(world): borders_total_elevation = 0.0 for y",
"= World.from_pickle_file(\"%s/plates_279.world\" % self.tests_data_dir) # We want to have less",
"self.tests_data_dir) # We want to have less land than before",
"* 2 - 4 return borders_total_elevation / n_cells_on_border def test_center_land(self):",
"def _mean_elevation_at_borders(world): borders_total_elevation = 0.0 for y in range(world.height): borders_total_elevation",
"import World from tests.draw_test import TestBase class TestGeneration(TestBase): def setUp(self):",
"World.from_pickle_file(\"%s/plates_279.world\" % self.tests_data_dir) # We want to have less land",
"TestGeneration._mean_elevation_at_borders(w) center_land(w) el_after = TestGeneration._mean_elevation_at_borders(w) self.assertTrue(el_after <= el_before) if __name__",
"world.width * 2 + world.height * 2 - 4 return",
"x in range(1, world.width - 1): borders_total_elevation += world.elevation_at((x, 0))",
"0.0 for y in range(world.height): borders_total_elevation += world.elevation_at((0, y)) borders_total_elevation",
"+= world.elevation_at((world.width - 1, y)) for x in range(1, world.width",
"n_cells_on_border = world.width * 2 + world.height * 2 -",
"import Step, center_land, world_gen from worldengine.world import World from tests.draw_test",
"- 1, y)) for x in range(1, world.width - 1):",
"# FIXME remove me when proper tests are in place",
"in range(world.height): borders_total_elevation += world.elevation_at((0, y)) borders_total_elevation += world.elevation_at((world.width -",
"explode badly world_gen(\"Dummy\", 32, 16, 1, step=Step.get_by_name(\"full\")) @staticmethod def _mean_elevation_at_borders(world):",
"have less land than before at the borders el_before =",
"1): borders_total_elevation += world.elevation_at((x, 0)) borders_total_elevation += world.elevation_at((x, world.height -",
"borders_total_elevation += world.elevation_at((x, world.height - 1)) n_cells_on_border = world.width *",
"test_center_land(self): w = World.from_pickle_file(\"%s/plates_279.world\" % self.tests_data_dir) # We want to",
"y in range(world.height): borders_total_elevation += world.elevation_at((0, y)) borders_total_elevation += world.elevation_at((world.width",
"from worldengine.plates import Step, center_land, world_gen from worldengine.world import World",
"proper tests are in place # Very stupid test that",
"the borders el_before = TestGeneration._mean_elevation_at_borders(w) center_land(w) el_after = TestGeneration._mean_elevation_at_borders(w) self.assertTrue(el_after",
"when proper tests are in place # Very stupid test",
"remove me when proper tests are in place # Very",
"verify nothing explode badly world_gen(\"Dummy\", 32, 16, 1, step=Step.get_by_name(\"full\")) @staticmethod",
"- 1): borders_total_elevation += world.elevation_at((x, 0)) borders_total_elevation += world.elevation_at((x, world.height",
"borders_total_elevation += world.elevation_at((world.width - 1, y)) for x in range(1,",
"We want to have less land than before at the",
"TestGeneration(TestBase): def setUp(self): super(TestGeneration, self).setUp() def test_world_gen_does_not_explode_badly(self): # FIXME remove",
"in range(1, world.width - 1): borders_total_elevation += world.elevation_at((x, 0)) borders_total_elevation",
"return borders_total_elevation / n_cells_on_border def test_center_land(self): w = World.from_pickle_file(\"%s/plates_279.world\" %",
"me when proper tests are in place # Very stupid",
"# We want to have less land than before at",
"_mean_elevation_at_borders(world): borders_total_elevation = 0.0 for y in range(world.height): borders_total_elevation +=",
"from worldengine.world import World from tests.draw_test import TestBase class TestGeneration(TestBase):",
"2 + world.height * 2 - 4 return borders_total_elevation /",
"FIXME remove me when proper tests are in place #",
"el_before = TestGeneration._mean_elevation_at_borders(w) center_land(w) el_after = TestGeneration._mean_elevation_at_borders(w) self.assertTrue(el_after <= el_before)",
"world.elevation_at((x, world.height - 1)) n_cells_on_border = world.width * 2 +",
"world_gen from worldengine.world import World from tests.draw_test import TestBase class",
"world_gen(\"Dummy\", 32, 16, 1, step=Step.get_by_name(\"full\")) @staticmethod def _mean_elevation_at_borders(world): borders_total_elevation =",
"step=Step.get_by_name(\"full\")) @staticmethod def _mean_elevation_at_borders(world): borders_total_elevation = 0.0 for y in",
"at the borders el_before = TestGeneration._mean_elevation_at_borders(w) center_land(w) el_after = TestGeneration._mean_elevation_at_borders(w)",
"Very stupid test that just verify nothing explode badly world_gen(\"Dummy\",",
"- 4 return borders_total_elevation / n_cells_on_border def test_center_land(self): w =",
"* 2 + world.height * 2 - 4 return borders_total_elevation",
"want to have less land than before at the borders",
"are in place # Very stupid test that just verify",
"world.elevation_at((x, 0)) borders_total_elevation += world.elevation_at((x, world.height - 1)) n_cells_on_border =",
"setUp(self): super(TestGeneration, self).setUp() def test_world_gen_does_not_explode_badly(self): # FIXME remove me when",
"Step, center_land, world_gen from worldengine.world import World from tests.draw_test import",
"test that just verify nothing explode badly world_gen(\"Dummy\", 32, 16,",
"nothing explode badly world_gen(\"Dummy\", 32, 16, 1, step=Step.get_by_name(\"full\")) @staticmethod def",
"+= world.elevation_at((x, 0)) borders_total_elevation += world.elevation_at((x, world.height - 1)) n_cells_on_border",
"center_land, world_gen from worldengine.world import World from tests.draw_test import TestBase",
"n_cells_on_border def test_center_land(self): w = World.from_pickle_file(\"%s/plates_279.world\" % self.tests_data_dir) # We",
"test_world_gen_does_not_explode_badly(self): # FIXME remove me when proper tests are in",
"world.elevation_at((0, y)) borders_total_elevation += world.elevation_at((world.width - 1, y)) for x",
"= world.width * 2 + world.height * 2 - 4",
"# Very stupid test that just verify nothing explode badly",
"from tests.draw_test import TestBase class TestGeneration(TestBase): def setUp(self): super(TestGeneration, self).setUp()",
"1, y)) for x in range(1, world.width - 1): borders_total_elevation",
"borders_total_elevation += world.elevation_at((x, 0)) borders_total_elevation += world.elevation_at((x, world.height - 1))",
"world.elevation_at((world.width - 1, y)) for x in range(1, world.width -",
"= TestGeneration._mean_elevation_at_borders(w) self.assertTrue(el_after <= el_before) if __name__ == '__main__': unittest.main()",
"= TestGeneration._mean_elevation_at_borders(w) center_land(w) el_after = TestGeneration._mean_elevation_at_borders(w) self.assertTrue(el_after <= el_before) if",
"World from tests.draw_test import TestBase class TestGeneration(TestBase): def setUp(self): super(TestGeneration,",
"w = World.from_pickle_file(\"%s/plates_279.world\" % self.tests_data_dir) # We want to have",
"TestBase class TestGeneration(TestBase): def setUp(self): super(TestGeneration, self).setUp() def test_world_gen_does_not_explode_badly(self): #",
"16, 1, step=Step.get_by_name(\"full\")) @staticmethod def _mean_elevation_at_borders(world): borders_total_elevation = 0.0 for",
"stupid test that just verify nothing explode badly world_gen(\"Dummy\", 32,",
"world.height * 2 - 4 return borders_total_elevation / n_cells_on_border def",
"that just verify nothing explode badly world_gen(\"Dummy\", 32, 16, 1,"
] |
[
"= net(inputs.cuda()) assert output.shape == (2, 1) # pretrained should",
"y1 = conv2d(x1) assert y1.shape == (3, 16, 16, 16)",
"in_channels=3) net = build_component(cfg) net.init_weights(pretrained=None) # cpu inputs = torch.rand((2,",
"# cpu inputs = torch.rand((2, 3, 128, 128)) output =",
"def test_light_cnn(): cfg = dict(type='LightCNN', in_channels=3) net = build_component(cfg) net.init_weights(pretrained=None)",
"16, 16) y2 = linear(x2) assert y2.shape == (3, 16)",
"filter_type should be conv2d or linear with pytest.raises(ValueError): MaxFeature(12, 12,",
"net = build_component(cfg) net.init_weights(pretrained=None) # cpu inputs = torch.rand((2, 3,",
"conv2d = MaxFeature(16, 16, filter_type='conv2d') x1 = torch.rand(3, 16, 16,",
"MaxFeature def test_max_feature(): # cpu conv2d = MaxFeature(16, 16, filter_type='conv2d')",
"with pytest.raises(ValueError): MaxFeature(12, 12, filter_type='conv1d') def test_light_cnn(): cfg = dict(type='LightCNN',",
"y2.shape == (3, 16) # filter_type should be conv2d or",
"= conv2d(x1) assert y1.shape == (3, 16, 16, 16) y2",
"import pytest import torch from mmedit.models.builder import build_component from mmedit.models.components.discriminators.light_cnn",
"should be conv2d or linear with pytest.raises(ValueError): MaxFeature(12, 12, filter_type='conv1d')",
"linear with pytest.raises(ValueError): MaxFeature(12, 12, filter_type='conv1d') def test_light_cnn(): cfg =",
"assert y2.shape == (3, 16) # gpu if torch.cuda.is_available(): x1",
"net(inputs.cuda()) assert output.shape == (2, 1) # pretrained should be",
"12, filter_type='conv1d') def test_light_cnn(): cfg = dict(type='LightCNN', in_channels=3) net =",
"torch.rand(3, 16, 16, 16) y1 = conv2d(x1) assert y1.shape ==",
"linear = linear.cuda() y1 = conv2d(x1) assert y1.shape == (3,",
"y2 = linear(x2) assert y2.shape == (3, 16) # gpu",
"linear(x2) assert y2.shape == (3, 16) # filter_type should be",
"mmedit.models.builder import build_component from mmedit.models.components.discriminators.light_cnn import MaxFeature def test_max_feature(): #",
"if torch.cuda.is_available(): x1 = x1.cuda() x2 = x2.cuda() conv2d =",
"if torch.cuda.is_available(): net.init_weights(pretrained=None) net = net.cuda() output = net(inputs.cuda()) assert",
"16, 16) linear = MaxFeature(16, 16, filter_type='linear') x2 = torch.rand(3,",
"= dict(type='LightCNN', in_channels=3) net = build_component(cfg) net.init_weights(pretrained=None) # cpu inputs",
"torch.cuda.is_available(): net.init_weights(pretrained=None) net = net.cuda() output = net(inputs.cuda()) assert output.shape",
"16) y1 = conv2d(x1) assert y1.shape == (3, 16, 16,",
"MaxFeature(12, 12, filter_type='conv1d') def test_light_cnn(): cfg = dict(type='LightCNN', in_channels=3) net",
"16, 16, 16) linear = MaxFeature(16, 16, filter_type='linear') x2 =",
"dict(type='LightCNN', in_channels=3) net = build_component(cfg) net.init_weights(pretrained=None) # cpu inputs =",
"torch.rand((2, 3, 128, 128)) output = net(inputs) assert output.shape ==",
"gpu if torch.cuda.is_available(): net.init_weights(pretrained=None) net = net.cuda() output = net(inputs.cuda())",
"= MaxFeature(16, 16, filter_type='linear') x2 = torch.rand(3, 16) y2 =",
"test_max_feature(): # cpu conv2d = MaxFeature(16, 16, filter_type='conv2d') x1 =",
"or linear with pytest.raises(ValueError): MaxFeature(12, 12, filter_type='conv1d') def test_light_cnn(): cfg",
"= net(inputs) assert output.shape == (2, 1) # gpu if",
"pytest import torch from mmedit.models.builder import build_component from mmedit.models.components.discriminators.light_cnn import",
"= x1.cuda() x2 = x2.cuda() conv2d = conv2d.cuda() linear =",
"# pretrained should be str or None with pytest.raises(TypeError): net.init_weights(pretrained=[1])",
"torch from mmedit.models.builder import build_component from mmedit.models.components.discriminators.light_cnn import MaxFeature def",
"16, filter_type='conv2d') x1 = torch.rand(3, 16, 16, 16) y1 =",
"cpu inputs = torch.rand((2, 3, 128, 128)) output = net(inputs)",
"MaxFeature(16, 16, filter_type='conv2d') x1 = torch.rand(3, 16, 16, 16) y1",
"16) # gpu if torch.cuda.is_available(): x1 = x1.cuda() x2 =",
"= x2.cuda() conv2d = conv2d.cuda() linear = linear.cuda() y1 =",
"= conv2d.cuda() linear = linear.cuda() y1 = conv2d(x1) assert y1.shape",
"def test_max_feature(): # cpu conv2d = MaxFeature(16, 16, filter_type='conv2d') x1",
"16, 16) y1 = conv2d(x1) assert y1.shape == (3, 16,",
"filter_type='linear') x2 = torch.rand(3, 16) y2 = linear(x2) assert y2.shape",
"= build_component(cfg) net.init_weights(pretrained=None) # cpu inputs = torch.rand((2, 3, 128,",
"(3, 16) # filter_type should be conv2d or linear with",
"1) # pretrained should be str or None with pytest.raises(TypeError):",
"= torch.rand(3, 16) y2 = linear(x2) assert y2.shape == (3,",
"# filter_type should be conv2d or linear with pytest.raises(ValueError): MaxFeature(12,",
"x2 = torch.rand(3, 16) y2 = linear(x2) assert y2.shape ==",
"= MaxFeature(16, 16, filter_type='conv2d') x1 = torch.rand(3, 16, 16, 16)",
"net.init_weights(pretrained=None) # cpu inputs = torch.rand((2, 3, 128, 128)) output",
"== (3, 16) # gpu if torch.cuda.is_available(): x1 = x1.cuda()",
"= torch.rand((2, 3, 128, 128)) output = net(inputs) assert output.shape",
"x1 = x1.cuda() x2 = x2.cuda() conv2d = conv2d.cuda() linear",
"y1.shape == (3, 16, 16, 16) y2 = linear(x2) assert",
"MaxFeature(16, 16, filter_type='linear') x2 = torch.rand(3, 16) y2 = linear(x2)",
"x1.cuda() x2 = x2.cuda() conv2d = conv2d.cuda() linear = linear.cuda()",
"net.init_weights(pretrained=None) net = net.cuda() output = net(inputs.cuda()) assert output.shape ==",
"16, filter_type='linear') x2 = torch.rand(3, 16) y2 = linear(x2) assert",
"cpu conv2d = MaxFeature(16, 16, filter_type='conv2d') x1 = torch.rand(3, 16,",
"net(inputs) assert output.shape == (2, 1) # gpu if torch.cuda.is_available():",
"assert output.shape == (2, 1) # gpu if torch.cuda.is_available(): net.init_weights(pretrained=None)",
"x2 = x2.cuda() conv2d = conv2d.cuda() linear = linear.cuda() y1",
"128)) output = net(inputs) assert output.shape == (2, 1) #",
"conv2d(x1) assert y1.shape == (3, 16, 16, 16) linear =",
"16) y2 = linear(x2) assert y2.shape == (3, 16) #",
"gpu if torch.cuda.is_available(): x1 = x1.cuda() x2 = x2.cuda() conv2d",
"output = net(inputs) assert output.shape == (2, 1) # gpu",
"linear(x2) assert y2.shape == (3, 16) # gpu if torch.cuda.is_available():",
"# cpu conv2d = MaxFeature(16, 16, filter_type='conv2d') x1 = torch.rand(3,",
"= linear(x2) assert y2.shape == (3, 16) # gpu if",
"assert y1.shape == (3, 16, 16, 16) linear = MaxFeature(16,",
"filter_type='conv2d') x1 = torch.rand(3, 16, 16, 16) y1 = conv2d(x1)",
"# gpu if torch.cuda.is_available(): net.init_weights(pretrained=None) net = net.cuda() output =",
"net.cuda() output = net(inputs.cuda()) assert output.shape == (2, 1) #",
"= linear(x2) assert y2.shape == (3, 16) # filter_type should",
"(2, 1) # gpu if torch.cuda.is_available(): net.init_weights(pretrained=None) net = net.cuda()",
"linear = MaxFeature(16, 16, filter_type='linear') x2 = torch.rand(3, 16) y2",
"filter_type='conv1d') def test_light_cnn(): cfg = dict(type='LightCNN', in_channels=3) net = build_component(cfg)",
"import torch from mmedit.models.builder import build_component from mmedit.models.components.discriminators.light_cnn import MaxFeature",
"inputs = torch.rand((2, 3, 128, 128)) output = net(inputs) assert",
"be conv2d or linear with pytest.raises(ValueError): MaxFeature(12, 12, filter_type='conv1d') def",
"== (2, 1) # pretrained should be str or None",
"= conv2d(x1) assert y1.shape == (3, 16, 16, 16) linear",
"build_component from mmedit.models.components.discriminators.light_cnn import MaxFeature def test_max_feature(): # cpu conv2d",
"y2 = linear(x2) assert y2.shape == (3, 16) # filter_type",
"1) # gpu if torch.cuda.is_available(): net.init_weights(pretrained=None) net = net.cuda() output",
"3, 128, 128)) output = net(inputs) assert output.shape == (2,",
"net = net.cuda() output = net(inputs.cuda()) assert output.shape == (2,",
"assert y1.shape == (3, 16, 16, 16) y2 = linear(x2)",
"build_component(cfg) net.init_weights(pretrained=None) # cpu inputs = torch.rand((2, 3, 128, 128))",
"16, 16, 16) y2 = linear(x2) assert y2.shape == (3,",
"import build_component from mmedit.models.components.discriminators.light_cnn import MaxFeature def test_max_feature(): # cpu",
"torch.cuda.is_available(): x1 = x1.cuda() x2 = x2.cuda() conv2d = conv2d.cuda()",
"conv2d or linear with pytest.raises(ValueError): MaxFeature(12, 12, filter_type='conv1d') def test_light_cnn():",
"= torch.rand(3, 16, 16, 16) y1 = conv2d(x1) assert y1.shape",
"x1 = torch.rand(3, 16, 16, 16) y1 = conv2d(x1) assert",
"linear.cuda() y1 = conv2d(x1) assert y1.shape == (3, 16, 16,",
"y2.shape == (3, 16) # gpu if torch.cuda.is_available(): x1 =",
"== (3, 16) # filter_type should be conv2d or linear",
"pytest.raises(ValueError): MaxFeature(12, 12, filter_type='conv1d') def test_light_cnn(): cfg = dict(type='LightCNN', in_channels=3)",
"128, 128)) output = net(inputs) assert output.shape == (2, 1)",
"<filename>tests/test_models/test_components/test_discriminators/test_light_cnn.py import pytest import torch from mmedit.models.builder import build_component from",
"conv2d(x1) assert y1.shape == (3, 16, 16, 16) y2 =",
"from mmedit.models.components.discriminators.light_cnn import MaxFeature def test_max_feature(): # cpu conv2d =",
"assert y2.shape == (3, 16) # filter_type should be conv2d",
"== (3, 16, 16, 16) y2 = linear(x2) assert y2.shape",
"import MaxFeature def test_max_feature(): # cpu conv2d = MaxFeature(16, 16,",
"x2.cuda() conv2d = conv2d.cuda() linear = linear.cuda() y1 = conv2d(x1)",
"test_light_cnn(): cfg = dict(type='LightCNN', in_channels=3) net = build_component(cfg) net.init_weights(pretrained=None) #",
"mmedit.models.components.discriminators.light_cnn import MaxFeature def test_max_feature(): # cpu conv2d = MaxFeature(16,",
"16) linear = MaxFeature(16, 16, filter_type='linear') x2 = torch.rand(3, 16)",
"conv2d = conv2d.cuda() linear = linear.cuda() y1 = conv2d(x1) assert",
"assert output.shape == (2, 1) # pretrained should be str",
"(3, 16) # gpu if torch.cuda.is_available(): x1 = x1.cuda() x2",
"16) # filter_type should be conv2d or linear with pytest.raises(ValueError):",
"(3, 16, 16, 16) y2 = linear(x2) assert y2.shape ==",
"output = net(inputs.cuda()) assert output.shape == (2, 1) # pretrained",
"conv2d.cuda() linear = linear.cuda() y1 = conv2d(x1) assert y1.shape ==",
"= linear.cuda() y1 = conv2d(x1) assert y1.shape == (3, 16,",
"(3, 16, 16, 16) linear = MaxFeature(16, 16, filter_type='linear') x2",
"y1.shape == (3, 16, 16, 16) linear = MaxFeature(16, 16,",
"# gpu if torch.cuda.is_available(): x1 = x1.cuda() x2 = x2.cuda()",
"torch.rand(3, 16) y2 = linear(x2) assert y2.shape == (3, 16)",
"= net.cuda() output = net(inputs.cuda()) assert output.shape == (2, 1)",
"from mmedit.models.builder import build_component from mmedit.models.components.discriminators.light_cnn import MaxFeature def test_max_feature():",
"== (2, 1) # gpu if torch.cuda.is_available(): net.init_weights(pretrained=None) net =",
"output.shape == (2, 1) # gpu if torch.cuda.is_available(): net.init_weights(pretrained=None) net",
"== (3, 16, 16, 16) linear = MaxFeature(16, 16, filter_type='linear')",
"(2, 1) # pretrained should be str or None with",
"output.shape == (2, 1) # pretrained should be str or",
"16, 16, 16) y1 = conv2d(x1) assert y1.shape == (3,",
"cfg = dict(type='LightCNN', in_channels=3) net = build_component(cfg) net.init_weights(pretrained=None) # cpu"
] |
[
"protocol not provided and cannot be determined automatically.' msg =",
"if not provided try: self._connection_data['security_protocol'] except KeyError: username_given = 'sasl_plain_username'",
"group_id=self.GROUP_ID, consumer_timeout_ms=1000, value_deserializer=lambda x: json.loads(x.decode(\"utf-8\")) ) log.info(f'Connected to kafka broker",
"e.g.: consumer = Consumer(...) with consumer: consumer.send(...) \"\"\" self._topics =",
"Check auth kwargs' raise ValueError(msg) self._client_id = f'{self.CLIENT_ID}:{id(self)}' def __enter__(self):",
"well as Aiven Kafka tutorials class Consumer: GROUP_ID = 'web_metrics_consumer'",
"inputs shall be defined Usage: Connection is activated not on",
"but when entering with statement. e.g.: consumer = Consumer(...) with",
"# https://github.com/aiven/aiven-examples/blob/master/kafka/python/consumer_example.py # as well as Aiven Kafka tutorials class",
"in self._connection_data.keys() service_key_given = 'ssl_keyfile' in self._connection_data.keys() if all((ca_file_given, service_cert_given,",
"kafka broker at: {self._consumer.config[\"bootstrap_servers\"]}') def fetch_latest(self): \"\"\"Fetches only not read",
"messages from {self._consumer.config[\"bootstrap_servers\"]}' ) self._consumer.commit() return messages def change_topics(self, topics:",
"ca_file_given = 'ssl_cafile' in self._connection_data.keys() service_cert_given = 'ssl_certfile' in self._connection_data.keys()",
"return messages def change_topics(self, topics: Iterable) -> None: \"\"\"Changes Kafka",
"list() for message in self._consumer: messages.append(message.value) log.info( f'Fetched {len(messages)} messages",
"self._connection_data['security_protocol'] = 'SSL' elif username_given and password_given: self._connection_data['security_protocol'] = 'SASL_PLAINTEXT'",
"on object instantiation but when entering with statement. e.g.: consumer",
"connection_kwargs # auto-determine security protocol if not provided try: self._connection_data['security_protocol']",
"message values \"\"\" self._consumer.poll() messages = list() for message in",
"json.loads(x.decode(\"utf-8\")) ) log.info(f'Connected to kafka broker at: {self._consumer.config[\"bootstrap_servers\"]}') def fetch_latest(self):",
"try: self._consumer.unsubscribe() self._consumer.subscribe(list(topics)) except AttributeError: # when topics are changed",
"are some useful kwargs and their default value: 'bootstrap_servers' -",
"in self._connection_data.keys() service_cert_given = 'ssl_certfile' in self._connection_data.keys() service_key_given = 'ssl_keyfile'",
"or 'ssl_cafile', 'ssl_certfile' and 'ssl_keyfile or other certificate-related inputs shall",
"'sasl_plain_username': None, 'sasl_plain_password': None, 'ssl_cafile': None, 'ssl_certfile': None, 'ssl_keyfile': None",
"ValueError(msg) self._client_id = f'{self.CLIENT_ID}:{id(self)}' def __enter__(self): \"\"\"Method which creates the",
"uri with port for the service 'security_protocol' - SSL, SASL_PLAINTEXT,",
"= topics def __exit__(self, exc_type, exc_value, traceback): \"\"\"Actions to perform",
"kwargs' raise ValueError(msg) self._client_id = f'{self.CLIENT_ID}:{id(self)}' def __enter__(self): \"\"\"Method which",
"only not read messages by members of this group. Returns:",
"fetch_latest(self): \"\"\"Fetches only not read messages by members of this",
"consumer. Args: *topics - topics to subscribe to. Could be",
"= 'Security protocol not provided and cannot be determined automatically.'",
"- uri with port for the service 'security_protocol' - SSL,",
"used this example: # https://github.com/aiven/aiven-examples/blob/master/kafka/python/consumer_example.py # as well as Aiven",
"service_key_given = 'ssl_keyfile' in self._connection_data.keys() if all((ca_file_given, service_cert_given, service_key_given)): self._connection_data['security_protocol']",
"__enter__(self): \"\"\"Method which creates the connection. Activated inside with statement.\"\"\"",
"inside with statement.\"\"\" self._consumer = KafkaConsumer( *self._topics, **self._connection_data, auto_offset_reset='earliest', enable_auto_commit=False,",
"Iterable from kafka import KafkaConsumer log = logging.getLogger(__name__) log.addHandler(logging.NullHandler()) #",
"example: # https://github.com/aiven/aiven-examples/blob/master/kafka/python/consumer_example.py # as well as Aiven Kafka tutorials",
"`with` statement self._topics = topics def __exit__(self, exc_type, exc_value, traceback):",
"Connection is activated not on object instantiation but when entering",
"or other certificate-related inputs shall be defined Usage: Connection is",
"= list() for message in self._consumer: messages.append(message.value) log.info( f'Fetched {len(messages)}",
"to kafka broker at: {self._consumer.config[\"bootstrap_servers\"]}') def fetch_latest(self): \"\"\"Fetches only not",
"'sasl_plain_username' and 'sasl_plain_password' or 'ssl_cafile', 'ssl_certfile' and 'ssl_keyfile or other",
"- topics to subscribe to. Could be changed during lifetime,",
"topics: any iterable: set, list, tuple Returns: None \"\"\" topics",
"values \"\"\" self._consumer.poll() messages = list() for message in self._consumer:",
"all params are optional, at least 'sasl_plain_username' and 'sasl_plain_password' or",
"as taken by KafkaConsumer below there are some useful kwargs",
"change_topics(self, topics: Iterable) -> None: \"\"\"Changes Kafka consumer topic statically",
"'<PASSWORD>' in self._connection_data.keys() ca_file_given = 'ssl_cafile' in self._connection_data.keys() service_cert_given =",
"the service 'security_protocol' - SSL, SASL_PLAINTEXT, etc 'sasl_mechanism': None, 'sasl_plain_username':",
"by members of this group. Returns: list of decoded message",
"consumer.send(...) \"\"\" self._topics = topics self._connection_data = connection_kwargs # auto-determine",
"security protocol if not provided try: self._connection_data['security_protocol'] except KeyError: username_given",
"self._connection_data.keys() service_key_given = 'ssl_keyfile' in self._connection_data.keys() if all((ca_file_given, service_cert_given, service_key_given)):",
"'ssl_keyfile': None Note: although all params are optional, at least",
"object instantiation but when entering with statement. e.g.: consumer =",
"of decoded message values \"\"\" self._consumer.poll() messages = list() for",
"'security_protocol' - SSL, SASL_PLAINTEXT, etc 'sasl_mechanism': None, 'sasl_plain_username': None, 'sasl_plain_password':",
"creating Kafka consumer. Args: *topics - topics to subscribe to.",
"= Consumer(...) with consumer: consumer.send(...) \"\"\" self._topics = topics self._connection_data",
"kafka import KafkaConsumer log = logging.getLogger(__name__) log.addHandler(logging.NullHandler()) # I've used",
"keyword arguments as taken by KafkaConsumer below there are some",
"'website-monitoring-consumer-service' def __init__( self, *topics, **connection_kwargs ): \"\"\"Class for creating",
"def fetch_latest(self): \"\"\"Fetches only not read messages by members of",
"self._consumer.subscribe(list(topics)) except AttributeError: # when topics are changed in inactive",
"with statement.\"\"\" log.info( f'Closed connection tp kafka broker at: {self._consumer.config[\"bootstrap_servers\"]}'",
"Aiven Kafka tutorials class Consumer: GROUP_ID = 'web_metrics_consumer' CLIENT_ID =",
"*self._topics, **self._connection_data, auto_offset_reset='earliest', enable_auto_commit=False, client_id=self._client_id, group_id=self.GROUP_ID, consumer_timeout_ms=1000, value_deserializer=lambda x: json.loads(x.decode(\"utf-8\"))",
"KafkaConsumer below there are some useful kwargs and their default",
"self._consumer.commit() return messages def change_topics(self, topics: Iterable) -> None: \"\"\"Changes",
"= 'SSL' elif username_given and password_given: self._connection_data['security_protocol'] = 'SASL_PLAINTEXT' else:",
"topics def __exit__(self, exc_type, exc_value, traceback): \"\"\"Actions to perform when",
"and 'sasl_plain_password' or 'ssl_cafile', 'ssl_certfile' and 'ssl_keyfile or other certificate-related",
"if all((ca_file_given, service_cert_given, service_key_given)): self._connection_data['security_protocol'] = 'SSL' elif username_given and",
"and cannot be determined automatically.' msg = f'{msg} Check auth",
"log.info( f'Fetched {len(messages)} messages from {self._consumer.config[\"bootstrap_servers\"]}' ) self._consumer.commit() return messages",
"their default value: 'bootstrap_servers' - uri with port for the",
"and password_given: self._connection_data['security_protocol'] = 'SASL_PLAINTEXT' else: msg = 'Security protocol",
"'sasl_plain_username' in self._connection_data.keys() password_given = '<PASSWORD>' in self._connection_data.keys() ca_file_given =",
"all((ca_file_given, service_cert_given, service_key_given)): self._connection_data['security_protocol'] = 'SSL' elif username_given and password_given:",
"*topics, **connection_kwargs ): \"\"\"Class for creating Kafka consumer. Args: *topics",
"traceback): \"\"\"Actions to perform when exiting with statement.\"\"\" log.info( f'Closed",
"class Consumer: GROUP_ID = 'web_metrics_consumer' CLIENT_ID = 'website-monitoring-consumer-service' def __init__(",
"'web_metrics_consumer' CLIENT_ID = 'website-monitoring-consumer-service' def __init__( self, *topics, **connection_kwargs ):",
"are changed in inactive consumer i.e. not inside `with` statement",
"self._connection_data = connection_kwargs # auto-determine security protocol if not provided",
"not inside `with` statement self._topics = topics def __exit__(self, exc_type,",
"): \"\"\"Class for creating Kafka consumer. Args: *topics - topics",
"changed in inactive consumer i.e. not inside `with` statement self._topics",
"to. Could be changed during lifetime, str **connection_kwargs - keyword",
"username_given and password_given: self._connection_data['security_protocol'] = 'SASL_PLAINTEXT' else: msg = 'Security",
"Note: although all params are optional, at least 'sasl_plain_username' and",
"self._topics = topics self._connection_data = connection_kwargs # auto-determine security protocol",
"be changed during lifetime, str **connection_kwargs - keyword arguments as",
"service_cert_given = 'ssl_certfile' in self._connection_data.keys() service_key_given = 'ssl_keyfile' in self._connection_data.keys()",
") self._consumer.commit() return messages def change_topics(self, topics: Iterable) -> None:",
"\"\"\"Class for creating Kafka consumer. Args: *topics - topics to",
"= 'ssl_certfile' in self._connection_data.keys() service_key_given = 'ssl_keyfile' in self._connection_data.keys() if",
"to perform when exiting with statement.\"\"\" log.info( f'Closed connection tp",
"= connection_kwargs # auto-determine security protocol if not provided try:",
"log.info(f'Connected to kafka broker at: {self._consumer.config[\"bootstrap_servers\"]}') def fetch_latest(self): \"\"\"Fetches only",
"'sasl_plain_password': None, 'ssl_cafile': None, 'ssl_certfile': None, 'ssl_keyfile': None Note: although",
"which creates the connection. Activated inside with statement.\"\"\" self._consumer =",
"list of decoded message values \"\"\" self._consumer.poll() messages = list()",
"for the service 'security_protocol' - SSL, SASL_PLAINTEXT, etc 'sasl_mechanism': None,",
"'sasl_mechanism': None, 'sasl_plain_username': None, 'sasl_plain_password': None, 'ssl_cafile': None, 'ssl_certfile': None,",
"service_key_given)): self._connection_data['security_protocol'] = 'SSL' elif username_given and password_given: self._connection_data['security_protocol'] =",
"KafkaConsumer log = logging.getLogger(__name__) log.addHandler(logging.NullHandler()) # I've used this example:",
"when topics are changed in inactive consumer i.e. not inside",
"inactive consumer i.e. not inside `with` statement self._topics = topics",
"None, 'sasl_plain_username': None, 'sasl_plain_password': None, 'ssl_cafile': None, 'ssl_certfile': None, 'ssl_keyfile':",
"'ssl_cafile', 'ssl_certfile' and 'ssl_keyfile or other certificate-related inputs shall be",
"<filename>src/consumer.py import json import logging from typing import Iterable from",
"Kafka tutorials class Consumer: GROUP_ID = 'web_metrics_consumer' CLIENT_ID = 'website-monitoring-consumer-service'",
"self._connection_data.keys() if all((ca_file_given, service_cert_given, service_key_given)): self._connection_data['security_protocol'] = 'SSL' elif username_given",
"with statement. e.g.: consumer = Consumer(...) with consumer: consumer.send(...) \"\"\"",
"AttributeError: # when topics are changed in inactive consumer i.e.",
"\"\"\"Changes Kafka consumer topic statically or dynamically Args: topics: any",
"Returns: None \"\"\" topics = tuple(topics) try: self._consumer.unsubscribe() self._consumer.subscribe(list(topics)) except",
"msg = f'{msg} Check auth kwargs' raise ValueError(msg) self._client_id =",
"SASL_PLAINTEXT, etc 'sasl_mechanism': None, 'sasl_plain_username': None, 'sasl_plain_password': None, 'ssl_cafile': None,",
"for creating Kafka consumer. Args: *topics - topics to subscribe",
"SSL, SASL_PLAINTEXT, etc 'sasl_mechanism': None, 'sasl_plain_username': None, 'sasl_plain_password': None, 'ssl_cafile':",
"in self._connection_data.keys() password_given = '<PASSWORD>' in self._connection_data.keys() ca_file_given = 'ssl_cafile'",
"subscribe to. Could be changed during lifetime, str **connection_kwargs -",
"log.addHandler(logging.NullHandler()) # I've used this example: # https://github.com/aiven/aiven-examples/blob/master/kafka/python/consumer_example.py # as",
"= 'sasl_plain_username' in self._connection_data.keys() password_given = '<PASSWORD>' in self._connection_data.keys() ca_file_given",
"Activated inside with statement.\"\"\" self._consumer = KafkaConsumer( *self._topics, **self._connection_data, auto_offset_reset='earliest',",
"{self._consumer.config[\"bootstrap_servers\"]}') def fetch_latest(self): \"\"\"Fetches only not read messages by members",
"from typing import Iterable from kafka import KafkaConsumer log =",
"by KafkaConsumer below there are some useful kwargs and their",
"topic statically or dynamically Args: topics: any iterable: set, list,",
"self._connection_data.keys() ca_file_given = 'ssl_cafile' in self._connection_data.keys() service_cert_given = 'ssl_certfile' in",
"x: json.loads(x.decode(\"utf-8\")) ) log.info(f'Connected to kafka broker at: {self._consumer.config[\"bootstrap_servers\"]}') def",
"lifetime, str **connection_kwargs - keyword arguments as taken by KafkaConsumer",
"entering with statement. e.g.: consumer = Consumer(...) with consumer: consumer.send(...)",
"statement self._topics = topics def __exit__(self, exc_type, exc_value, traceback): \"\"\"Actions",
"import json import logging from typing import Iterable from kafka",
"in inactive consumer i.e. not inside `with` statement self._topics =",
"password_given = '<PASSWORD>' in self._connection_data.keys() ca_file_given = 'ssl_cafile' in self._connection_data.keys()",
"= 'web_metrics_consumer' CLIENT_ID = 'website-monitoring-consumer-service' def __init__( self, *topics, **connection_kwargs",
"topics: Iterable) -> None: \"\"\"Changes Kafka consumer topic statically or",
"tuple(topics) try: self._consumer.unsubscribe() self._consumer.subscribe(list(topics)) except AttributeError: # when topics are",
"provided and cannot be determined automatically.' msg = f'{msg} Check",
"= 'website-monitoring-consumer-service' def __init__( self, *topics, **connection_kwargs ): \"\"\"Class for",
"there are some useful kwargs and their default value: 'bootstrap_servers'",
"from {self._consumer.config[\"bootstrap_servers\"]}' ) self._consumer.commit() return messages def change_topics(self, topics: Iterable)",
"statement.\"\"\" log.info( f'Closed connection tp kafka broker at: {self._consumer.config[\"bootstrap_servers\"]}' )",
"for message in self._consumer: messages.append(message.value) log.info( f'Fetched {len(messages)} messages from",
"in self._connection_data.keys() if all((ca_file_given, service_cert_given, service_key_given)): self._connection_data['security_protocol'] = 'SSL' elif",
"self._consumer = KafkaConsumer( *self._topics, **self._connection_data, auto_offset_reset='earliest', enable_auto_commit=False, client_id=self._client_id, group_id=self.GROUP_ID, consumer_timeout_ms=1000,",
"params are optional, at least 'sasl_plain_username' and 'sasl_plain_password' or 'ssl_cafile',",
"statement.\"\"\" self._consumer = KafkaConsumer( *self._topics, **self._connection_data, auto_offset_reset='earliest', enable_auto_commit=False, client_id=self._client_id, group_id=self.GROUP_ID,",
"message in self._consumer: messages.append(message.value) log.info( f'Fetched {len(messages)} messages from {self._consumer.config[\"bootstrap_servers\"]}'",
"= f'{self.CLIENT_ID}:{id(self)}' def __enter__(self): \"\"\"Method which creates the connection. Activated",
"**self._connection_data, auto_offset_reset='earliest', enable_auto_commit=False, client_id=self._client_id, group_id=self.GROUP_ID, consumer_timeout_ms=1000, value_deserializer=lambda x: json.loads(x.decode(\"utf-8\")) )",
"# I've used this example: # https://github.com/aiven/aiven-examples/blob/master/kafka/python/consumer_example.py # as well",
"*topics - topics to subscribe to. Could be changed during",
"= logging.getLogger(__name__) log.addHandler(logging.NullHandler()) # I've used this example: # https://github.com/aiven/aiven-examples/blob/master/kafka/python/consumer_example.py",
"- keyword arguments as taken by KafkaConsumer below there are",
"= 'SASL_PLAINTEXT' else: msg = 'Security protocol not provided and",
"'SASL_PLAINTEXT' else: msg = 'Security protocol not provided and cannot",
"perform when exiting with statement.\"\"\" log.info( f'Closed connection tp kafka",
"topics to subscribe to. Could be changed during lifetime, str",
"typing import Iterable from kafka import KafkaConsumer log = logging.getLogger(__name__)",
"determined automatically.' msg = f'{msg} Check auth kwargs' raise ValueError(msg)",
"\"\"\"Method which creates the connection. Activated inside with statement.\"\"\" self._consumer",
"tuple Returns: None \"\"\" topics = tuple(topics) try: self._consumer.unsubscribe() self._consumer.subscribe(list(topics))",
"Args: topics: any iterable: set, list, tuple Returns: None \"\"\"",
"self._connection_data['security_protocol'] except KeyError: username_given = 'sasl_plain_username' in self._connection_data.keys() password_given =",
"Consumer(...) with consumer: consumer.send(...) \"\"\" self._topics = topics self._connection_data =",
"consumer topic statically or dynamically Args: topics: any iterable: set,",
"None, 'ssl_keyfile': None Note: although all params are optional, at",
"from kafka import KafkaConsumer log = logging.getLogger(__name__) log.addHandler(logging.NullHandler()) # I've",
"'ssl_keyfile' in self._connection_data.keys() if all((ca_file_given, service_cert_given, service_key_given)): self._connection_data['security_protocol'] = 'SSL'",
"'Security protocol not provided and cannot be determined automatically.' msg",
"and their default value: 'bootstrap_servers' - uri with port for",
"except AttributeError: # when topics are changed in inactive consumer",
"during lifetime, str **connection_kwargs - keyword arguments as taken by",
"logging from typing import Iterable from kafka import KafkaConsumer log",
"None, 'sasl_plain_password': None, 'ssl_cafile': None, 'ssl_certfile': None, 'ssl_keyfile': None Note:",
"consumer: consumer.send(...) \"\"\" self._topics = topics self._connection_data = connection_kwargs #",
"self._client_id = f'{self.CLIENT_ID}:{id(self)}' def __enter__(self): \"\"\"Method which creates the connection.",
"be determined automatically.' msg = f'{msg} Check auth kwargs' raise",
"value_deserializer=lambda x: json.loads(x.decode(\"utf-8\")) ) log.info(f'Connected to kafka broker at: {self._consumer.config[\"bootstrap_servers\"]}')",
"topics = tuple(topics) try: self._consumer.unsubscribe() self._consumer.subscribe(list(topics)) except AttributeError: # when",
"= 'ssl_cafile' in self._connection_data.keys() service_cert_given = 'ssl_certfile' in self._connection_data.keys() service_key_given",
"at least 'sasl_plain_username' and 'sasl_plain_password' or 'ssl_cafile', 'ssl_certfile' and 'ssl_keyfile",
"this example: # https://github.com/aiven/aiven-examples/blob/master/kafka/python/consumer_example.py # as well as Aiven Kafka",
"except KeyError: username_given = 'sasl_plain_username' in self._connection_data.keys() password_given = '<PASSWORD>'",
"Iterable) -> None: \"\"\"Changes Kafka consumer topic statically or dynamically",
"KafkaConsumer( *self._topics, **self._connection_data, auto_offset_reset='earliest', enable_auto_commit=False, client_id=self._client_id, group_id=self.GROUP_ID, consumer_timeout_ms=1000, value_deserializer=lambda x:",
"topics self._connection_data = connection_kwargs # auto-determine security protocol if not",
"KeyError: username_given = 'sasl_plain_username' in self._connection_data.keys() password_given = '<PASSWORD>' in",
"in self._connection_data.keys() ca_file_given = 'ssl_cafile' in self._connection_data.keys() service_cert_given = 'ssl_certfile'",
"service 'security_protocol' - SSL, SASL_PLAINTEXT, etc 'sasl_mechanism': None, 'sasl_plain_username': None,",
"to subscribe to. Could be changed during lifetime, str **connection_kwargs",
"None, 'ssl_cafile': None, 'ssl_certfile': None, 'ssl_keyfile': None Note: although all",
"as Aiven Kafka tutorials class Consumer: GROUP_ID = 'web_metrics_consumer' CLIENT_ID",
") log.info(f'Connected to kafka broker at: {self._consumer.config[\"bootstrap_servers\"]}') def fetch_latest(self): \"\"\"Fetches",
"with statement.\"\"\" self._consumer = KafkaConsumer( *self._topics, **self._connection_data, auto_offset_reset='earliest', enable_auto_commit=False, client_id=self._client_id,",
"self._topics = topics def __exit__(self, exc_type, exc_value, traceback): \"\"\"Actions to",
"f'{msg} Check auth kwargs' raise ValueError(msg) self._client_id = f'{self.CLIENT_ID}:{id(self)}' def",
"**connection_kwargs ): \"\"\"Class for creating Kafka consumer. Args: *topics -",
"when entering with statement. e.g.: consumer = Consumer(...) with consumer:",
"consumer_timeout_ms=1000, value_deserializer=lambda x: json.loads(x.decode(\"utf-8\")) ) log.info(f'Connected to kafka broker at:",
"messages def change_topics(self, topics: Iterable) -> None: \"\"\"Changes Kafka consumer",
"\"\"\"Fetches only not read messages by members of this group.",
"arguments as taken by KafkaConsumer below there are some useful",
"messages = list() for message in self._consumer: messages.append(message.value) log.info( f'Fetched",
"defined Usage: Connection is activated not on object instantiation but",
"# auto-determine security protocol if not provided try: self._connection_data['security_protocol'] except",
"import KafkaConsumer log = logging.getLogger(__name__) log.addHandler(logging.NullHandler()) # I've used this",
"below there are some useful kwargs and their default value:",
"-> None: \"\"\"Changes Kafka consumer topic statically or dynamically Args:",
"def __init__( self, *topics, **connection_kwargs ): \"\"\"Class for creating Kafka",
"set, list, tuple Returns: None \"\"\" topics = tuple(topics) try:",
"log = logging.getLogger(__name__) log.addHandler(logging.NullHandler()) # I've used this example: #",
"kwargs and their default value: 'bootstrap_servers' - uri with port",
"instantiation but when entering with statement. e.g.: consumer = Consumer(...)",
"__init__( self, *topics, **connection_kwargs ): \"\"\"Class for creating Kafka consumer.",
"exiting with statement.\"\"\" log.info( f'Closed connection tp kafka broker at:",
"automatically.' msg = f'{msg} Check auth kwargs' raise ValueError(msg) self._client_id",
"not provided try: self._connection_data['security_protocol'] except KeyError: username_given = 'sasl_plain_username' in",
"statically or dynamically Args: topics: any iterable: set, list, tuple",
"any iterable: set, list, tuple Returns: None \"\"\" topics =",
"iterable: set, list, tuple Returns: None \"\"\" topics = tuple(topics)",
"Returns: list of decoded message values \"\"\" self._consumer.poll() messages =",
"f'{self.CLIENT_ID}:{id(self)}' def __enter__(self): \"\"\"Method which creates the connection. Activated inside",
"'ssl_certfile' and 'ssl_keyfile or other certificate-related inputs shall be defined",
"exc_type, exc_value, traceback): \"\"\"Actions to perform when exiting with statement.\"\"\"",
"the connection. Activated inside with statement.\"\"\" self._consumer = KafkaConsumer( *self._topics,",
"not read messages by members of this group. Returns: list",
"consumer i.e. not inside `with` statement self._topics = topics def",
"inside `with` statement self._topics = topics def __exit__(self, exc_type, exc_value,",
"when exiting with statement.\"\"\" log.info( f'Closed connection tp kafka broker",
"optional, at least 'sasl_plain_username' and 'sasl_plain_password' or 'ssl_cafile', 'ssl_certfile' and",
"self, *topics, **connection_kwargs ): \"\"\"Class for creating Kafka consumer. Args:",
"changed during lifetime, str **connection_kwargs - keyword arguments as taken",
"messages.append(message.value) log.info( f'Fetched {len(messages)} messages from {self._consumer.config[\"bootstrap_servers\"]}' ) self._consumer.commit() return",
"group. Returns: list of decoded message values \"\"\" self._consumer.poll() messages",
"__exit__(self, exc_type, exc_value, traceback): \"\"\"Actions to perform when exiting with",
"raise ValueError(msg) self._client_id = f'{self.CLIENT_ID}:{id(self)}' def __enter__(self): \"\"\"Method which creates",
"try: self._connection_data['security_protocol'] except KeyError: username_given = 'sasl_plain_username' in self._connection_data.keys() password_given",
"None \"\"\" topics = tuple(topics) try: self._consumer.unsubscribe() self._consumer.subscribe(list(topics)) except AttributeError:",
"value: 'bootstrap_servers' - uri with port for the service 'security_protocol'",
"i.e. not inside `with` statement self._topics = topics def __exit__(self,",
"Consumer: GROUP_ID = 'web_metrics_consumer' CLIENT_ID = 'website-monitoring-consumer-service' def __init__( self,",
"def __exit__(self, exc_type, exc_value, traceback): \"\"\"Actions to perform when exiting",
"self._consumer.unsubscribe() self._consumer.subscribe(list(topics)) except AttributeError: # when topics are changed in",
"in self._consumer: messages.append(message.value) log.info( f'Fetched {len(messages)} messages from {self._consumer.config[\"bootstrap_servers\"]}' )",
"least 'sasl_plain_username' and 'sasl_plain_password' or 'ssl_cafile', 'ssl_certfile' and 'ssl_keyfile or",
"cannot be determined automatically.' msg = f'{msg} Check auth kwargs'",
"'ssl_certfile' in self._connection_data.keys() service_key_given = 'ssl_keyfile' in self._connection_data.keys() if all((ca_file_given,",
"client_id=self._client_id, group_id=self.GROUP_ID, consumer_timeout_ms=1000, value_deserializer=lambda x: json.loads(x.decode(\"utf-8\")) ) log.info(f'Connected to kafka",
"'ssl_certfile': None, 'ssl_keyfile': None Note: although all params are optional,",
"= tuple(topics) try: self._consumer.unsubscribe() self._consumer.subscribe(list(topics)) except AttributeError: # when topics",
"creates the connection. Activated inside with statement.\"\"\" self._consumer = KafkaConsumer(",
"'sasl_plain_password' or 'ssl_cafile', 'ssl_certfile' and 'ssl_keyfile or other certificate-related inputs",
"GROUP_ID = 'web_metrics_consumer' CLIENT_ID = 'website-monitoring-consumer-service' def __init__( self, *topics,",
"# when topics are changed in inactive consumer i.e. not",
"'bootstrap_servers' - uri with port for the service 'security_protocol' -",
"username_given = 'sasl_plain_username' in self._connection_data.keys() password_given = '<PASSWORD>' in self._connection_data.keys()",
"{self._consumer.config[\"bootstrap_servers\"]}' ) self._consumer.commit() return messages def change_topics(self, topics: Iterable) ->",
"as well as Aiven Kafka tutorials class Consumer: GROUP_ID =",
"import logging from typing import Iterable from kafka import KafkaConsumer",
"self._consumer.poll() messages = list() for message in self._consumer: messages.append(message.value) log.info(",
"dynamically Args: topics: any iterable: set, list, tuple Returns: None",
"or dynamically Args: topics: any iterable: set, list, tuple Returns:",
"list, tuple Returns: None \"\"\" topics = tuple(topics) try: self._consumer.unsubscribe()",
"\"\"\" self._topics = topics self._connection_data = connection_kwargs # auto-determine security",
"def __enter__(self): \"\"\"Method which creates the connection. Activated inside with",
"enable_auto_commit=False, client_id=self._client_id, group_id=self.GROUP_ID, consumer_timeout_ms=1000, value_deserializer=lambda x: json.loads(x.decode(\"utf-8\")) ) log.info(f'Connected to",
"CLIENT_ID = 'website-monitoring-consumer-service' def __init__( self, *topics, **connection_kwargs ): \"\"\"Class",
"useful kwargs and their default value: 'bootstrap_servers' - uri with",
"- SSL, SASL_PLAINTEXT, etc 'sasl_mechanism': None, 'sasl_plain_username': None, 'sasl_plain_password': None,",
"= topics self._connection_data = connection_kwargs # auto-determine security protocol if",
"Args: *topics - topics to subscribe to. Could be changed",
"= '<PASSWORD>' in self._connection_data.keys() ca_file_given = 'ssl_cafile' in self._connection_data.keys() service_cert_given",
"password_given: self._connection_data['security_protocol'] = 'SASL_PLAINTEXT' else: msg = 'Security protocol not",
"exc_value, traceback): \"\"\"Actions to perform when exiting with statement.\"\"\" log.info(",
"\"\"\" topics = tuple(topics) try: self._consumer.unsubscribe() self._consumer.subscribe(list(topics)) except AttributeError: #",
"activated not on object instantiation but when entering with statement.",
"= f'{msg} Check auth kwargs' raise ValueError(msg) self._client_id = f'{self.CLIENT_ID}:{id(self)}'",
"json import logging from typing import Iterable from kafka import",
"Usage: Connection is activated not on object instantiation but when",
"not provided and cannot be determined automatically.' msg = f'{msg}",
"None, 'ssl_certfile': None, 'ssl_keyfile': None Note: although all params are",
"self._consumer: messages.append(message.value) log.info( f'Fetched {len(messages)} messages from {self._consumer.config[\"bootstrap_servers\"]}' ) self._consumer.commit()",
"broker at: {self._consumer.config[\"bootstrap_servers\"]}') def fetch_latest(self): \"\"\"Fetches only not read messages",
"statement. e.g.: consumer = Consumer(...) with consumer: consumer.send(...) \"\"\" self._topics",
"else: msg = 'Security protocol not provided and cannot be",
"default value: 'bootstrap_servers' - uri with port for the service",
"https://github.com/aiven/aiven-examples/blob/master/kafka/python/consumer_example.py # as well as Aiven Kafka tutorials class Consumer:",
"topics are changed in inactive consumer i.e. not inside `with`",
"of this group. Returns: list of decoded message values \"\"\"",
"None Note: although all params are optional, at least 'sasl_plain_username'",
"be defined Usage: Connection is activated not on object instantiation",
"at: {self._consumer.config[\"bootstrap_servers\"]}') def fetch_latest(self): \"\"\"Fetches only not read messages by",
"this group. Returns: list of decoded message values \"\"\" self._consumer.poll()",
"'ssl_cafile' in self._connection_data.keys() service_cert_given = 'ssl_certfile' in self._connection_data.keys() service_key_given =",
"messages by members of this group. Returns: list of decoded",
"certificate-related inputs shall be defined Usage: Connection is activated not",
"is activated not on object instantiation but when entering with",
"self._connection_data['security_protocol'] = 'SASL_PLAINTEXT' else: msg = 'Security protocol not provided",
"are optional, at least 'sasl_plain_username' and 'sasl_plain_password' or 'ssl_cafile', 'ssl_certfile'",
"other certificate-related inputs shall be defined Usage: Connection is activated",
"= KafkaConsumer( *self._topics, **self._connection_data, auto_offset_reset='earliest', enable_auto_commit=False, client_id=self._client_id, group_id=self.GROUP_ID, consumer_timeout_ms=1000, value_deserializer=lambda",
"\"\"\" self._consumer.poll() messages = list() for message in self._consumer: messages.append(message.value)",
"connection. Activated inside with statement.\"\"\" self._consumer = KafkaConsumer( *self._topics, **self._connection_data,",
"\"\"\"Actions to perform when exiting with statement.\"\"\" log.info( f'Closed connection",
"'ssl_keyfile or other certificate-related inputs shall be defined Usage: Connection",
"Kafka consumer. Args: *topics - topics to subscribe to. Could",
"'ssl_cafile': None, 'ssl_certfile': None, 'ssl_keyfile': None Note: although all params",
"auto-determine security protocol if not provided try: self._connection_data['security_protocol'] except KeyError:",
"port for the service 'security_protocol' - SSL, SASL_PLAINTEXT, etc 'sasl_mechanism':",
"although all params are optional, at least 'sasl_plain_username' and 'sasl_plain_password'",
"members of this group. Returns: list of decoded message values",
"decoded message values \"\"\" self._consumer.poll() messages = list() for message",
"I've used this example: # https://github.com/aiven/aiven-examples/blob/master/kafka/python/consumer_example.py # as well as",
"and 'ssl_keyfile or other certificate-related inputs shall be defined Usage:",
"import Iterable from kafka import KafkaConsumer log = logging.getLogger(__name__) log.addHandler(logging.NullHandler())",
"# as well as Aiven Kafka tutorials class Consumer: GROUP_ID",
"'SSL' elif username_given and password_given: self._connection_data['security_protocol'] = 'SASL_PLAINTEXT' else: msg",
"auth kwargs' raise ValueError(msg) self._client_id = f'{self.CLIENT_ID}:{id(self)}' def __enter__(self): \"\"\"Method",
"not on object instantiation but when entering with statement. e.g.:",
"def change_topics(self, topics: Iterable) -> None: \"\"\"Changes Kafka consumer topic",
"auto_offset_reset='earliest', enable_auto_commit=False, client_id=self._client_id, group_id=self.GROUP_ID, consumer_timeout_ms=1000, value_deserializer=lambda x: json.loads(x.decode(\"utf-8\")) ) log.info(f'Connected",
"protocol if not provided try: self._connection_data['security_protocol'] except KeyError: username_given =",
"shall be defined Usage: Connection is activated not on object",
"**connection_kwargs - keyword arguments as taken by KafkaConsumer below there",
"etc 'sasl_mechanism': None, 'sasl_plain_username': None, 'sasl_plain_password': None, 'ssl_cafile': None, 'ssl_certfile':",
"Kafka consumer topic statically or dynamically Args: topics: any iterable:",
"None: \"\"\"Changes Kafka consumer topic statically or dynamically Args: topics:",
"taken by KafkaConsumer below there are some useful kwargs and",
"= 'ssl_keyfile' in self._connection_data.keys() if all((ca_file_given, service_cert_given, service_key_given)): self._connection_data['security_protocol'] =",
"elif username_given and password_given: self._connection_data['security_protocol'] = 'SASL_PLAINTEXT' else: msg =",
"read messages by members of this group. Returns: list of",
"self._connection_data.keys() service_cert_given = 'ssl_certfile' in self._connection_data.keys() service_key_given = 'ssl_keyfile' in",
"provided try: self._connection_data['security_protocol'] except KeyError: username_given = 'sasl_plain_username' in self._connection_data.keys()",
"msg = 'Security protocol not provided and cannot be determined",
"consumer = Consumer(...) with consumer: consumer.send(...) \"\"\" self._topics = topics",
"f'Fetched {len(messages)} messages from {self._consumer.config[\"bootstrap_servers\"]}' ) self._consumer.commit() return messages def",
"with port for the service 'security_protocol' - SSL, SASL_PLAINTEXT, etc",
"service_cert_given, service_key_given)): self._connection_data['security_protocol'] = 'SSL' elif username_given and password_given: self._connection_data['security_protocol']",
"{len(messages)} messages from {self._consumer.config[\"bootstrap_servers\"]}' ) self._consumer.commit() return messages def change_topics(self,",
"some useful kwargs and their default value: 'bootstrap_servers' - uri",
"Could be changed during lifetime, str **connection_kwargs - keyword arguments",
"str **connection_kwargs - keyword arguments as taken by KafkaConsumer below",
"with consumer: consumer.send(...) \"\"\" self._topics = topics self._connection_data = connection_kwargs",
"tutorials class Consumer: GROUP_ID = 'web_metrics_consumer' CLIENT_ID = 'website-monitoring-consumer-service' def",
"self._connection_data.keys() password_given = '<PASSWORD>' in self._connection_data.keys() ca_file_given = 'ssl_cafile' in",
"logging.getLogger(__name__) log.addHandler(logging.NullHandler()) # I've used this example: # https://github.com/aiven/aiven-examples/blob/master/kafka/python/consumer_example.py #"
] |
[
"self.fc4 = layers.Dense(num_classes) def call(self,inputs,training=None): out = self.conv1(inputs) out =",
"return res_blocks def resnet18(): return ResNet([2, 2, 2, 2],num_classes=9) def",
"conv1 = layers.Conv3D(filters_num[0], kernel_size=(3, 3, 7), padding='same')(input_layer) # filters_num =",
"stride=1) # filters_num = 128 self.layer3 = self.build_resblock(filters_num[2], layer_dims[2], stride=1)",
"= layers.Conv2D(filters_num[4], kernel_size=(3, 3), padding='same',kernel_regularizer=regularizers.l2(0.0001))(conv4_relu) # filters_num = ** conv5_bn",
"def call(self, inputs): avg_out = tf.reduce_mean(inputs, axis=3) max_out = tf.reduce_max(inputs,",
"4, 6, 3],num_classes=9) ########################### pp2主模型 ######################################## class pp2_model(keras.Model): def __init__(self,filters_num,layer_dims,num_classes,dropout_rate):",
"3, 5), padding='same')(conv1_relu) # filters_num = 16 # conv222 =",
"# conv33333_relu_reshape = Concatenate(axis=-1)([conv3_relu_reshape, conv33_relu_reshape]) ######################################### conv4 = layers.Conv2D(filters_num[3], kernel_size=(3,",
"= 16 # conv222 = layers.Conv3D(filters_num[1], kernel_size=(7, 7, 3), padding='same',",
"3), padding='same', kernel_initializer='he_normal', # kernel_regularizer=regularizers.l2(0.0001))(conv222_relu) # filters_num = 32 #",
"class BasicBlock(layers.Layer): def __init__(self, filter_num, stride=1): super(BasicBlock, self).__init__() # self.conv1",
"__init__(self, filter_num, stride=1): super(BasicBlock, self).__init__() # self.conv1 = layers.Conv2D(filter_num, (3,",
"# layer3 = build_resblock(filters_num[7], layer_dims[2], stride=2) # filters_num = 256",
"out = avg_out + max_out out = tf.nn.sigmoid(out) return out",
"layer_dims[3], stride=1) # filters_num = 512 # output: [b, 512,",
"= 16 self.bn2 = layers.BatchNormalization() self.relu2 = layers.Activation('relu') self.conv3 =",
"############################### self.ca = ChannelAttention(filter_num) self.sa = SpatialAttention() if stride !=",
"self.fc3 = layers.Dense(filters_num[6],activation='relu') self.fc4 = layers.Dense(num_classes) def call(self,inputs,training=None): out =",
"(None, 1, 1 feature) max = layers.Reshape((1, 1, max.shape[1]))(max) #",
"layers.Reshape( # (conv3_relu.shape[1], conv3_relu.shape[2], conv3_relu.shape[3] * conv3_relu.shape[4]))(conv33_relu) #################################################### # conv111",
"= layers.Conv3D(filters_num[1],kernel_size=(3,3,5),padding='same') # filters_num = 16 self.bn2 = layers.BatchNormalization() self.relu2",
"layers.Dense(num_classes) def call(self, inputs, training=None): x = self.stem(inputs) x =",
"layers.BatchNormalization()(conv11) # conv11_relu = layers.Activation('relu')(conv11_bn) # # # conv2 =",
"Concatenate def regularized_padded_conv(*args, **kwargs): return layers.Conv2D(*args, **kwargs, padding='same', use_bias=False, kernel_initializer='he_normal',",
"3), padding='same', kernel_regularizer=regularizers.l2(0.0001))(input_layer_up) #kernel_initializer='he_normal', # conv_layer1m = tf.keras.layers.MaxPooling3D(pool_size=(1, 1, 1),padding='same')(conv1)",
"layers.Activation('relu')(conv3_bn) # conv3_relu = Dropout(0.5)(conv3_relu) # conv3_relu = tf.keras.layers.MaxPooling3D(pool_size=(2, 2,",
"x = self.layer1(x) x = self.layer2(x) x = self.layer3(x) x",
"x3 = self.layer3(x2) x4 = self.layer4(x3) # [b, c] #",
"stride=2) # filters_num = 128 # layer3 = build_resblock(filters_num[7], layer_dims[2],",
"2), strides=(1, 1, 1), padding='same')(conv1_relu) # conv2 = layers.Conv3D(filters_num[1], kernel_size=(3,",
"2), strides=(1, 1, 1), padding='same')(conv3_relu) conv3_relu_reshape = layers.Reshape((conv3_relu.shape[1],conv3_relu.shape[2],conv3_relu.shape[3]*conv3_relu.shape[4]))(conv3_relu) conv3_relu_reshape =",
"conv22 = layers.Conv3D(filters_num[1], kernel_size=(5, 5, 3), padding='same', kernel_initializer='he_normal', # kernel_regularizer=regularizers.l2(0.0001))(conv11_relu)",
"1, 1), padding='same')(conv1_relu) # conv2 = layers.Conv3D(filters_num[1], kernel_size=(3, 3, 5),",
"64 conv4_bn = layers.BatchNormalization()(conv4) conv4_relu = layers.Activation('relu')(conv4_bn) # conv4_relu =",
"self.layer4 = self.build_resblock(filters_num[8], layer_dims[3], stride=2) # filters_num = 512 #",
"strides=(1, 1, 1), padding='same')(conv3_relu) conv3_relu_reshape = layers.Reshape((conv3_relu.shape[1],conv3_relu.shape[2],conv3_relu.shape[3]*conv3_relu.shape[4]))(conv3_relu) conv3_relu_reshape = Dropout(0.5)(conv3_relu_reshape)",
"= layers.Activation('relu') self.conv3 = layers.Conv3D(filters_num[2], kernel_size=(3, 3, 3), padding='same') #",
"layers.Conv3D(filters_num[1], kernel_size=(7, 7, 3), padding='same', kernel_initializer='he_normal', # kernel_regularizer=regularizers.l2(0.0001))(conv111_relu) # filters_num",
"# conv111_bn = layers.BatchNormalization()(conv111) # conv111_relu = layers.Activation('relu')(conv111_bn) # #",
"= layers.BatchNormalization() self.relu5 = layers.Activation('relu') self.dpout = layers.Dropout(dropout_rate) self.layer1 =",
"conv4_bn = layers.BatchNormalization()(conv4) conv4_relu = layers.Activation('relu')(conv4_bn) # conv4_relu = Dropout(0.5)(conv4_relu)",
"self.conv1 = layers.Conv3D(filters_num[0],kernel_size=(3,3,7),padding='same') # filters_num = 8 self.bn1 = layers.BatchNormalization()",
"blocks): res_blocks.add(BasicBlock(filter_num, stride=1)) return res_blocks def resnet18(): return ResNet([2, 2,",
"Dropout(0.5)(conv5_relu) # conv5_relu = tf.keras.layers.MaxPooling2D(pool_size=(2, 2), strides=(1, 1), padding='same')(conv5_relu) #",
"= tf.keras.layers.GlobalMaxPooling3D()(conv1) conv1_bn = layers.BatchNormalization()(conv1) conv1_relu = layers.Activation('relu')(conv1_bn) # conv1_relu",
"layers.Activation('relu') self.conv5 = layers.Conv2D(filters_num[4], kernel_size=(3, 3), padding='same') # filters_num =",
"2), strides=(1, 1), padding='same') ]) self.layer1 = self.build_resblock(64, layer_dims[0]) self.layer2",
"# # conv333 = layers.Conv3D(filters_num[2], kernel_size=(7, 7, 3), padding='same', kernel_initializer='he_normal',",
"= layers.GlobalAveragePooling2D() self.fc = layers.Dense(num_classes) def call(self, inputs, training=None): x",
"padding='same') # filters_num = ** self.bn5 = layers.BatchNormalization() self.relu5 =",
"tf.keras.layers.MaxPooling3D(pool_size=(2, 2, 2), strides=(1, 1, 1), padding='same')(conv2_relu) conv3 = layers.Conv3D(filters_num[2],",
"2, 2), strides=(1, 1, 1), padding='same')(conv5_relu) # conv5_dpout = layers.Dropout(dropout_rate)(conv5)",
"self.BasicBlock2 = BasicBlock(filter_num, stride=1) def call(self,blocks): res_blocks = Sequential() res_blocks.add(self.BasicBlock1)",
"tf.keras.layers.MaxPooling3D(pool_size=(2, 2, 2), strides=(1, 1, 1), padding='same')(conv3_relu) conv3_relu_reshape = layers.Reshape((conv3_relu.shape[1],conv3_relu.shape[2],conv3_relu.shape[3]*conv3_relu.shape[4]))(conv3_relu)",
"2), strides=(1, 1), padding='same')(conv5_relu) # conv5_relu = tf.keras.layers.MaxPooling3D(pool_size=(2, 2, 2),",
"= tf.keras.layers.MaxPooling3D(pool_size=(2, 2, 2), strides=(1, 1, 1), padding='same')(conv4_relu) conv5 =",
"layers.Activation('relu'), # layers.MaxPool2D(pool_size=(2, 2), strides=(1, 1), padding='same') # ]) self.layer1",
"= self.avg(inputs) max = self.max(inputs) avg = layers.Reshape((1, 1, avg.shape[1]))(avg)",
"# filters_num = ** conv5_bn = layers.BatchNormalization()(conv5) conv5_relu = layers.Activation('relu')(conv5_bn)",
"= self.build_resblock(filters_num[2], layer_dims[2], stride=1) # filters_num = 256 self.layer4 =",
"# layers.MaxPool2D(pool_size=(2, 2), strides=(1, 1), padding='same') # ]) self.layer1 =",
"padding='same', kernel_regularizer=regularizers.l2(0.0001))(input_layer_up) #kernel_initializer='he_normal', # conv_layer1m = tf.keras.layers.MaxPooling3D(pool_size=(1, 1, 1),padding='same')(conv1) #",
"stride=2) # filters_num = 256 # layer4 = build_resblock(filters_num[8], layer_dims[3],",
"layers.MaxPool2D(pool_size=(2, 2), strides=(1, 1), padding='same') ]) self.layer1 = self.build_resblock(64, layer_dims[0])",
"return ResNet([3, 4, 6, 3],num_classes=9) ########################### pp2主模型 ######################################## class pp2_model(keras.Model):",
"# x = self.avgpool(x) # [b, 100] # x =",
"= self.layer4(x3) # [b, c] # x = self.avgpool(x) #",
"padding='same', kernel_regularizer=regularizers.l2(5e-4), use_bias=True, activation=tf.nn.relu) self.conv2 = layers.Conv2D(in_planes, kernel_size=1, strides=1, padding='same',",
"self.layer4 = self.build_resblock(512, layer_dims[3], stride=1) # output: [b, 512, h,",
"layers.GlobalAveragePooling2D() self.fc2 = layers.Dense(filters_num[7],activation='relu') self.fc3 = layers.Dense(filters_num[6],activation='relu') self.fc4 = layers.Dense(num_classes)",
"Dropout(0.5)(conv1_relu) # conv1_relu = tf.keras.layers.MaxPooling3D(pool_size=(2, 2, 2), strides=(1, 1, 1),",
"# conv33_bn = layers.BatchNormalization()(conv33) # conv33_relu = layers.Activation('relu')(conv33_bn) # #",
"self.BasicBlock1 = BasicBlock(filter_num, stride) self.BasicBlock2 = BasicBlock(filter_num, stride=1) def call(self,blocks):",
"= 32 self.bn3 = layers.BatchNormalization() self.relu3 = layers.Activation('relu') # self.reshape",
"stride=1)) return res_blocks class ResNet_block(keras.Model): def __init__(self, layer_dims,filters_num): # [2,",
"= self.build_resblock(filters_num[5], layer_dims[0]) # filters_num = 64 self.layer2 = self.build_resblock(filters_num[6],",
"Sequential([layers.Conv2D(64, (3, 3), strides=(1, 1)), # layers.BatchNormalization(), # layers.Activation('relu'), #",
"self.relu5 = layers.Activation('relu') self.dpout = layers.Dropout(dropout_rate) self.layer1 = self.build_resblock(filters_num[5], layer_dims[0])",
"outputs2,outputs4 = Block_res(conv5_relu) return conv5,outputs2,outputs4 # layer1 = build_resblock(filters_num[5], layer_dims[0])",
"Sequential,regularizers from tensorflow.keras.layers import Dropout # from tensorflow.keras import *",
"layers.Conv3D(filters_num[1], kernel_size=(5, 5, 3), padding='same', kernel_initializer='he_normal', # kernel_regularizer=regularizers.l2(0.0001))(conv11_relu) # filters_num",
"layers.Conv3D(filters_num[0], kernel_size=(3, 3, 3),padding='same',kernel_initializer='he_normal',kernel_regularizer=regularizers.l2(0.0001))(input_layer_up) # filters_num = 8 conv1 =",
"build_resblock(filters_num[6], layer_dims[1], stride=2) # filters_num = 128 # layer3 =",
"= layers.Reshape( # (conv3_relu.shape[1], conv3_relu.shape[2], conv3_relu.shape[3] * conv3_relu.shape[4]))(conv33_relu) #################################################### #",
"= Dropout(0.5)(conv5_relu) # conv5_relu = tf.keras.layers.MaxPooling2D(pool_size=(2, 2), strides=(1, 1), padding='same')(conv5_relu)",
"# filters_num = 8 # conv1 = layers.Conv3D(filters_num[0], kernel_size=(3, 3,",
"tf.nn.sigmoid(out) return out ############################### 空间注意力机制 ############################### class SpatialAttention(layers.Layer): def __init__(self,",
"stride=1): res_blocks = Sequential() # may down sample res_blocks.add(BasicBlock(filter_num, stride))",
"for _ in range(1, blocks): res_blocks.add(BasicBlock(filter_num, stride=1)) return res_blocks ######################################",
"as tf from tensorflow import keras from tensorflow.keras import layers,",
"layer_dims, num_classes=16): # [2, 2, 2, 2] super(ResNet, self).__init__() self.stem",
"kernel_initializer='he_normal', # kernel_regularizer=regularizers.l2(0.0001))(conv111_relu) # filters_num = 16 # conv222_bn =",
"= tf.keras.layers.MaxPooling3D(pool_size=(2, 2, 2), strides=(1, 1, 1), padding='same')(conv1_relu) # conv2",
"self.build_resblock(filters_num[0], layer_dims[0]) # filters_num = 64 self.layer2 = self.build_resblock(filters_num[1], layer_dims[1],",
"stride=1) # filters_num = 256 self.layer4 = self.build_resblock(filters_num[3], layer_dims[3], stride=1)",
"= layers.BatchNormalization()(conv4) conv4_relu = layers.Activation('relu')(conv4_bn) # conv4_relu = Dropout(0.5)(conv4_relu) #",
"res_blocks = Sequential() # may down sample res_blocks.add(BasicBlock(filter_num, stride)) for",
"self.stem(inputs) x1 = self.layer1(inputs) x2 = self.layer2(x1) x3 = self.layer3(x2)",
"kernel_size=(3, 3), padding='same',kernel_regularizer=regularizers.l2(0.0001))(conv3_relu_reshape) # filters_num = 64 conv4_bn = layers.BatchNormalization()(conv4)",
"self.avgpool(x) # [b, 100] # x = self.fc(x) return x2,x4",
"layers.Reshape((conv3_relu.shape[1],conv3_relu.shape[2],conv3_relu.shape[3]*conv3_relu.shape[4]))(conv3_relu) conv3_relu_reshape = Dropout(0.5)(conv3_relu_reshape) ##################第二个尺度######################### # conv11 = layers.Conv3D(filters_num[0], kernel_size=(5,",
"out = self.conv3(out) out = self.bn3(out) out = self.relu3(out) #",
"注意力机制 ############################### self.ca = ChannelAttention(filter_num) self.sa = SpatialAttention() if stride",
"# filters_num = 16 # conv222 = layers.Conv3D(filters_num[1], kernel_size=(7, 7,",
"avg_out = tf.reduce_mean(inputs, axis=3) max_out = tf.reduce_max(inputs, axis=3) out =",
"Sequential() res_blocks.add(self.BasicBlock1) for _ in range(1, blocks): res_blocks.add(self.BasicBlock2) return res_blocks",
"filters_num = 64 self.layer2 = self.build_resblock(filters_num[1], layer_dims[1], stride=1) # filters_num",
"]) self.layer1 = self.build_resblock(64, layer_dims[0]) self.layer2 = self.build_resblock(128, layer_dims[1], stride=1)",
"= layers.Conv3D(filters_num[2], kernel_size=(3, 3, 3),padding='same',kernel_regularizer=regularizers.l2(0.0001))(conv2_relu) # filters_num = 32 conv3_bn",
"self.conv2(self.conv1(avg)) max_out = self.conv2(self.conv1(max)) out = avg_out + max_out out",
"256 self.layer4 = self.build_resblock(filters_num[8], layer_dims[3], stride=2) # filters_num = 512",
"Dropout(0.5)(conv2_relu) # conv2_relu = tf.keras.layers.MaxPooling3D(pool_size=(2, 2, 2), strides=(1, 1, 1),",
"def __init__(self, filter_num, stride): super(build_resblock, self).__init__() self.BasicBlock1 = BasicBlock(filter_num, stride)",
"layer_dims[0]) # filters_num = 64 self.layer2 = self.build_resblock(filters_num[1], layer_dims[1], stride=1)",
"###################################### class ResNet(keras.Model): def __init__(self, layer_dims, num_classes=16): # [2, 2,",
"conv5_relu = tf.keras.layers.MaxPooling2D(pool_size=(2, 2), strides=(1, 1), padding='same')(conv5_relu) # conv5_relu =",
"strides=(1, 1, 1), padding='same')(conv4_relu) conv5 = layers.Conv2D(filters_num[4], kernel_size=(3, 3), padding='same',kernel_regularizer=regularizers.l2(0.0001))(conv4_relu)",
"res_blocks ###################################### class ResNet(keras.Model): def __init__(self, layer_dims, num_classes=16): # [2,",
"padding='same', kernel_initializer='he_normal',kernel_regularizer=keras.regularizers.l2(5e-4)) self.conv1 = layers.Conv2D(filter_num, (3, 3), strides=stride, padding='same',kernel_regularizer=regularizers.l2(0.0001)) #kernel_initializer='he_normal',",
"self.fc(x) return x2,x4 def build_resblock(self, filter_num, blocks, stride=1): res_blocks =",
"super(SpatialAttention, self).__init__() self.conv1 = regularized_padded_conv(1, kernel_size=kernel_size, strides=1, activation=tf.nn.sigmoid) def call(self,",
"= Dropout(0.5)(conv1_relu) # conv1_relu = tf.keras.layers.MaxPooling3D(pool_size=(2, 2, 2), strides=(1, 1,",
"= 16 # conv222_bn = layers.BatchNormalization()(conv222) # conv222_relu = layers.Activation('relu')(conv222_bn)",
"= self.conv1(inputs) out = self.bn1(out) out = self.relu1(out) out =",
"avg_out = self.conv2(self.conv1(avg)) max_out = self.conv2(self.conv1(max)) out = avg_out +",
"res_blocks.add(self.BasicBlock2) return res_blocks def build_resblock(self, filter_num, blocks, stride=1): res_blocks =",
"= self.dpout(out) out = self.relu5(out) x = self.layer1(out) x =",
"layers.Reshape((out.shape[1],out.shape[2],out.shape[3] * out.shape[4]))(out) out = self.conv4(out) out = self.bn4(out) out",
"self.relu1 = layers.Activation('relu') self.conv2 = layers.Conv3D(filters_num[1],kernel_size=(3,3,5),padding='same') # filters_num = 16",
"# [b, 100] x = self.fc2(x) x = self.dpout(x) x",
"2, 2), strides=(1, 1, 1), padding='same')(conv1_relu) # conv2 = layers.Conv3D(filters_num[1],",
"# conv11_relu = layers.Activation('relu')(conv11_bn) # # # conv2 = layers.Conv3D(filters_num[1],",
"self.layer4(x) # [b, c] x = self.avgpool(x) # [b, 100]",
"self.avgpool(x) # [b, 100] x = self.fc2(x) x = self.dpout(x)",
"self.fc = layers.Dense(num_classes) def call(self, inputs, training=None): x = self.stem(inputs)",
"1, 1),padding='same')(conv1) # conv_layer1g = tf.keras.layers.GlobalMaxPooling3D()(conv1) conv1_bn = layers.BatchNormalization()(conv1) conv1_relu",
"self.layer4(x3) # [b, c] # x = self.avgpool(x) # [b,",
"3), padding='same') # filters_num = ** self.bn5 = layers.BatchNormalization() self.relu5",
"filters_num = 128 self.layer3 = self.build_resblock(filters_num[2], layer_dims[2], stride=1) # filters_num",
"from tensorflow.keras import * import tensorflow as tf from tensorflow",
"stride=1) self.layer4 = self.build_resblock(512, layer_dims[3], stride=1) # output: [b, 512,",
"max_out = self.conv2(self.conv1(max)) out = avg_out + max_out out =",
"1), strides=stride)) else: self.downsample = lambda x:x def call(self, inputs,",
"= Block_res(conv5_relu) return conv5,outputs2,outputs4 # layer1 = build_resblock(filters_num[5], layer_dims[0]) #",
"inputs, training=None): # x = self.stem(inputs) x1 = self.layer1(inputs) x2",
"layer_dims[0]) # filters_num = 64 self.layer2 = self.build_resblock(filters_num[6], layer_dims[1], stride=2)",
"= layers.BatchNormalization()(conv3) conv3_relu = layers.Activation('relu')(conv3_bn) # conv3_relu = Dropout(0.5)(conv3_relu) #",
"axis=3) out = tf.stack([avg_out, max_out], axis=3) # 创建一个维度,拼接到一起concat。 out =",
"# conv3_relu = Dropout(0.5)(conv3_relu) # conv3_relu = tf.keras.layers.MaxPooling3D(pool_size=(2, 2, 2),",
"kernel_size=(3, 3, 3),padding='same',kernel_initializer='he_normal',kernel_regularizer=regularizers.l2(0.0001))(input_layer_up) # filters_num = 8 conv1 = layers.Conv3D(filters_num[0],",
"kernel_size=(5, 5, 3), padding='same', kernel_initializer='he_normal', # kernel_regularizer=regularizers.l2(0.0001))(conv22_relu) # filters_num =",
"# # conv333_relu_reshape = layers.Reshape( # (conv3_relu.shape[1], conv3_relu.shape[2], conv3_relu.shape[3] *",
"1), padding='same')(conv5_relu) # conv5_dpout = layers.Dropout(dropout_rate)(conv5) # conv5_reshape = layers.Reshape((conv5_dpout.shape[1],conv5_dpout.shape[2],conv5_dpout.shape[3]))(conv5_dpout)",
"self.conv1 = layers.Conv2D(filter_num, (3, 3), strides=stride, padding='same',kernel_regularizer=regularizers.l2(0.0001)) #kernel_initializer='he_normal', self.bn1 =",
"strides=(1, 1, 1), padding='same')(conv2_relu) conv3 = layers.Conv3D(filters_num[2], kernel_size=(3, 3, 3),padding='same',kernel_regularizer=regularizers.l2(0.0001))(conv2_relu)",
"= ** self.bn5 = layers.BatchNormalization() self.relu5 = layers.Activation('relu') self.dpout =",
"h, w], # self.avgpool = layers.GlobalAveragePooling2D() # self.fc = layers.Dense(num_classes)",
"padding='same', kernel_regularizer=regularizers.l2(5e-4), use_bias=True) def call(self, inputs): avg = self.avg(inputs) max",
"conv222 = layers.Conv3D(filters_num[1], kernel_size=(7, 7, 3), padding='same', kernel_initializer='he_normal', # kernel_regularizer=regularizers.l2(0.0001))(conv111_relu)",
"Sequential() # may down sample res_blocks.add(BasicBlock(filter_num, stride)) for _ in",
"self.layer1(inputs) x2 = self.layer2(x1) x3 = self.layer3(x2) x4 = self.layer4(x3)",
"avg = layers.Reshape((1, 1, avg.shape[1]))(avg) # shape (None, 1, 1",
"strides=(1, 1), padding='same')(conv5_relu) # conv5_relu = tf.keras.layers.MaxPooling3D(pool_size=(2, 2, 2), strides=(1,",
"= self.avgpool(x) # [b, 100] # x = self.fc(x) return",
"= layers.Activation('relu') self.dpout = layers.Dropout(dropout_rate) self.layer1 = self.build_resblock(filters_num[5], layer_dims[0]) #",
"# (conv3_relu.shape[1], conv3_relu.shape[2], conv3_relu.shape[3] * conv3_relu.shape[4]))(conv33_relu) #################################################### # conv111 =",
"lambda x:x def call(self, inputs, training=None): # [b, h, w,",
"2), strides=(1, 1, 1), padding='same')(conv5_relu) # conv5_dpout = layers.Dropout(dropout_rate)(conv5) #",
"super(ResNet, self).__init__() self.stem = Sequential([layers.Conv2D(64, (3, 3), strides=(1, 1)), layers.BatchNormalization(),",
"** self.bn5 = layers.BatchNormalization() self.relu5 = layers.Activation('relu') self.dpout = layers.Dropout(dropout_rate)",
"= layers.Conv3D(filters_num[0], kernel_size=(3, 3, 7), padding='same')(input_layer) # filters_num = 8",
"layers.Activation('relu')(conv111_bn) # # # conv2 = layers.Conv3D(filters_num[1], kernel_size=(3, 3, 5),",
"avg = self.avg(inputs) max = self.max(inputs) avg = layers.Reshape((1, 1,",
"######################################## class pp2_model(keras.Model): def __init__(self,filters_num,layer_dims,num_classes,dropout_rate): super(pp2_model, self).__init__() self.conv1 = layers.Conv3D(filters_num[0],kernel_size=(3,3,7),padding='same')",
"layers.Dense(filters_num[7],activation='relu') self.fc3 = layers.Dense(filters_num[6],activation='relu') self.fc4 = layers.Dense(num_classes) def call(self,inputs,training=None): out",
"= self.stem(inputs) x1 = self.layer1(inputs) x2 = self.layer2(x1) x3 =",
"conv222_relu = layers.Activation('relu')(conv222_bn) # # conv333 = layers.Conv3D(filters_num[2], kernel_size=(7, 7,",
"ResNet([2, 2, 2, 2],num_classes=9) def resnet34(): return ResNet([3, 4, 6,",
"= layers.Conv3D(filters_num[2], kernel_size=(5, 5, 3), padding='same', kernel_initializer='he_normal', # kernel_regularizer=regularizers.l2(0.0001))(conv22_relu) #",
"conv5_reshape = layers.Reshape((conv5_dpout.shape[1],conv5_dpout.shape[2],conv5_dpout.shape[3]))(conv5_dpout) outputs2,outputs4 = Block_res(conv5_relu) return conv5,outputs2,outputs4 # layer1",
"layer1 = build_resblock(filters_num[5], layer_dims[0]) # filters_num = 64 # layer2",
"training=None): # x = self.stem(inputs) x1 = self.layer1(inputs) x2 =",
"kernel_regularizer=regularizers.l2(0.0001))(conv22_relu) # filters_num = 32 # conv33_bn = layers.BatchNormalization()(conv33) #",
"def __init__(self, layer_dims,filters_num): # [2, 2, 2, 2] super(ResNet_block, self).__init__()",
"# filters_num = 32 conv3_bn = layers.BatchNormalization()(conv3) conv3_relu = layers.Activation('relu')(conv3_bn)",
"= regularized_padded_conv(1, kernel_size=kernel_size, strides=1, activation=tf.nn.sigmoid) def call(self, inputs): avg_out =",
"16 # conv222 = layers.Conv3D(filters_num[1], kernel_size=(7, 7, 3), padding='same', kernel_initializer='he_normal',",
"= Dropout(0.5)(conv3_relu_reshape) ##################第二个尺度######################### # conv11 = layers.Conv3D(filters_num[0], kernel_size=(5, 5, 3),",
"blocks, stride=1): res_blocks = Sequential() # may down sample res_blocks.add(BasicBlock(filter_num,",
"2, 2), strides=(1, 1, 1), padding='same')(conv4_relu) conv5 = layers.Conv2D(filters_num[4], kernel_size=(3,",
"self.build_resblock(512, layer_dims[3], stride=1) # output: [b, 512, h, w], self.avgpool",
"= build_resblock(filters_num[5], layer_dims[0]) # filters_num = 64 # layer2 =",
"padding='same') ]) self.layer1 = self.build_resblock(64, layer_dims[0]) self.layer2 = self.build_resblock(128, layer_dims[1],",
"res_blocks class ResNet_block(keras.Model): def __init__(self, layer_dims,filters_num): # [2, 2, 2,",
"out ############################### 空间注意力机制 ############################### class SpatialAttention(layers.Layer): def __init__(self, kernel_size=7): super(SpatialAttention,",
"self.layer1 = self.build_resblock(64, layer_dims[0]) self.layer2 = self.build_resblock(128, layer_dims[1], stride=1) self.layer3",
"= SpatialAttention() if stride != 1: self.downsample = Sequential() self.downsample.add(layers.Conv2D(filter_num,",
"x = self.avgpool(x) # [b, 100] # x = self.fc(x)",
"strides=1, activation=tf.nn.sigmoid) def call(self, inputs): avg_out = tf.reduce_mean(inputs, axis=3) max_out",
"tensorflow.python.keras.layers import Concatenate def regularized_padded_conv(*args, **kwargs): return layers.Conv2D(*args, **kwargs, padding='same',",
"# conv222_bn = layers.BatchNormalization()(conv222) # conv222_relu = layers.Activation('relu')(conv222_bn) # #",
"_ in range(1, blocks): res_blocks.add(BasicBlock(filter_num, stride=1)) return res_blocks class ResNet_block(keras.Model):",
"def __init__(self, kernel_size=7): super(SpatialAttention, self).__init__() self.conv1 = regularized_padded_conv(1, kernel_size=kernel_size, strides=1,",
"return x def build_resblock(self, filter_num, blocks, stride=1): res_blocks = Sequential()",
"layers.GlobalAveragePooling2D() self.fc = layers.Dense(num_classes) def call(self, inputs, training=None): x =",
"return out ############################### 空间注意力机制 ############################### class SpatialAttention(layers.Layer): def __init__(self, kernel_size=7):",
"layers.GlobalAveragePooling2D() # self.fc = layers.Dense(num_classes) def call(self, inputs, training=None): #",
"kernel_size=(3, 3, 5), padding='same')(conv1_relu) # filters_num = 16 # conv222",
"self.avgpool(x) # [b, 100] x = self.fc(x) return x def",
"range(1, blocks): res_blocks.add(self.BasicBlock2) return res_blocks def build_resblock(self, filter_num, blocks, stride=1):",
"self.relu = layers.Activation('relu') self.conv2 = layers.Conv2D(filter_num, (3, 3), strides=1, padding='same',kernel_regularizer=regularizers.l2(0.0001))",
"self.avgpool = layers.GlobalAveragePooling2D() self.fc2 = layers.Dense(filters_num[7],activation='relu') self.fc3 = layers.Dense(filters_num[6],activation='relu') self.fc4",
"= build_resblock(filters_num[6], layer_dims[1], stride=2) # filters_num = 128 # layer3",
"layers.Conv3D(filters_num[2], kernel_size=(3, 3, 3),padding='same',kernel_regularizer=regularizers.l2(0.0001))(conv2_relu) # filters_num = 32 conv3_bn =",
"layers.Activation('relu'), layers.MaxPool2D(pool_size=(2, 2), strides=(1, 1), padding='same') ]) self.layer1 = self.build_resblock(64,",
"stride=1) def call(self,blocks): res_blocks = Sequential() res_blocks.add(self.BasicBlock1) for _ in",
"# filters_num = 128 self.layer3 = self.build_resblock(filters_num[2], layer_dims[2], stride=1) #",
"# self.stem = Sequential([layers.Conv2D(64, (3, 3), strides=(1, 1)), # layers.BatchNormalization(),",
"# filters_num = 64 # layer2 = build_resblock(filters_num[6], layer_dims[1], stride=2)",
"filters_num = ** self.bn5 = layers.BatchNormalization() self.relu5 = layers.Activation('relu') self.dpout",
"[b, c] x = self.avgpool(x) # [b, 100] x =",
"# conv33 = layers.Conv3D(filters_num[2], kernel_size=(5, 5, 3), padding='same', kernel_initializer='he_normal', #",
"= layers.GlobalAveragePooling2D() # self.fc = layers.Dense(num_classes) def call(self, inputs, training=None):",
"tf.reduce_max(inputs, axis=3) out = tf.stack([avg_out, max_out], axis=3) # 创建一个维度,拼接到一起concat。 out",
"layers.BatchNormalization() self.relu = layers.Activation('relu') self.conv2 = layers.Conv2D(filter_num, (3, 3), strides=1,",
"self.bn5(out) out = self.dpout(out) out = self.relu5(out) x = self.layer1(out)",
"# layer2 = build_resblock(filters_num[6], layer_dims[1], stride=2) # filters_num = 128",
"kernel_size=(3, 3), padding='same') # filters_num = ** self.bn5 = layers.BatchNormalization()",
"self.build_resblock(filters_num[7], layer_dims[2], stride=2) # filters_num = 256 self.layer4 = self.build_resblock(filters_num[8],",
"# conv1 = layers.Conv3D(filters_num[0], kernel_size=(3, 3, 7), padding='same')(input_layer) # filters_num",
"# output: [b, 512, h, w], # self.avgpool = layers.GlobalAveragePooling2D()",
"build_resblock(keras.Model): def __init__(self, filter_num, stride): super(build_resblock, self).__init__() self.BasicBlock1 = BasicBlock(filter_num,",
"layer_dims[2], stride=2) # filters_num = 256 self.layer4 = self.build_resblock(filters_num[8], layer_dims[3],",
"3),padding='same',kernel_regularizer=regularizers.l2(0.0001))(conv1_relu) # filters_num = 16 conv2_bn = layers.BatchNormalization()(conv2) conv2_relu =",
"# conv5_dpout = layers.Dropout(dropout_rate)(conv5) # conv5_reshape = layers.Reshape((conv5_dpout.shape[1],conv5_dpout.shape[2],conv5_dpout.shape[3]))(conv5_dpout) outputs2,outputs4 =",
"= self.build_resblock(filters_num[3], layer_dims[3], stride=1) # filters_num = 512 # output:",
"Block_res(conv5_relu) return conv5,outputs2,outputs4 # layer1 = build_resblock(filters_num[5], layer_dims[0]) # filters_num",
"# conv222 = layers.Conv3D(filters_num[1], kernel_size=(7, 7, 3), padding='same', kernel_initializer='he_normal', #",
"# filters_num = 16 # conv222_bn = layers.BatchNormalization()(conv222) # conv222_relu",
"= layers.Activation('relu')(conv111_bn) # # # conv2 = layers.Conv3D(filters_num[1], kernel_size=(3, 3,",
"layer_dims,filters_num): # [2, 2, 2, 2] super(ResNet_block, self).__init__() # #",
"= self.conv1(inputs) out = self.bn1(out) out = self.relu(out) out =",
"kernel_size=7): super(SpatialAttention, self).__init__() self.conv1 = regularized_padded_conv(1, kernel_size=kernel_size, strides=1, activation=tf.nn.sigmoid) def",
"############################### class ChannelAttention(layers.Layer): def __init__(self, in_planes, ratio=8): super(ChannelAttention, self).__init__() self.avg=",
"# conv222_relu = layers.Activation('relu')(conv222_bn) # # conv333 = layers.Conv3D(filters_num[2], kernel_size=(7,",
"class ChannelAttention(layers.Layer): def __init__(self, in_planes, ratio=8): super(ChannelAttention, self).__init__() self.avg= layers.GlobalAveragePooling2D()",
"stride=1)) return res_blocks def resnet18(): return ResNet([2, 2, 2, 2],num_classes=9)",
"# shape (None, 1, 1 feature) avg_out = self.conv2(self.conv1(avg)) max_out",
"layers.GlobalMaxPooling2D() self.conv1 = layers.Conv2D(in_planes//ratio, kernel_size=1, strides=1, padding='same', kernel_regularizer=regularizers.l2(5e-4), use_bias=True, activation=tf.nn.relu)",
"self.stem(inputs) x = self.layer1(x) x = self.layer2(x) x = self.layer3(x)",
"self.layer2 = self.build_resblock(filters_num[6], layer_dims[1], stride=2) # filters_num = 128 self.layer3",
"# [b, 100] x = self.fc(x) return x def build_resblock(self,",
"stride != 1: self.downsample = Sequential() self.downsample.add(layers.Conv2D(filter_num, (1, 1), strides=stride))",
"############################### 空间注意力机制 ############################### class SpatialAttention(layers.Layer): def __init__(self, kernel_size=7): super(SpatialAttention, self).__init__()",
"self.bn1(out) out = self.relu(out) out = self.conv2(out) out = self.bn2(out)",
"conv5_relu = tf.keras.layers.MaxPooling3D(pool_size=(2, 2, 2), strides=(1, 1, 1), padding='same')(conv5_relu) #",
"for _ in range(1, blocks): res_blocks.add(self.BasicBlock2) return res_blocks def build_resblock(self,",
"3), padding='same') # filters_num = 32 self.bn3 = layers.BatchNormalization() self.relu3",
"= layers.BatchNormalization()(conv11) # conv11_relu = layers.Activation('relu')(conv11_bn) # # # conv2",
"[b, 100] x = self.fc2(x) x = self.dpout(x) x =",
"layers.Conv3D(filters_num[1], kernel_size=(3, 3, 5), padding='same')(conv1_relu) # filters_num = 16 #",
"import Concatenate def regularized_padded_conv(*args, **kwargs): return layers.Conv2D(*args, **kwargs, padding='same', use_bias=False,",
"strides=1, padding='same', kernel_regularizer=regularizers.l2(5e-4), use_bias=True, activation=tf.nn.relu) self.conv2 = layers.Conv2D(in_planes, kernel_size=1, strides=1,",
"= self.relu1(out) out = self.conv2(out) out = self.bn2(out) out =",
"# filters_num = 8 conv1 = layers.Conv3D(filters_num[0], kernel_size=(3, 3, 3),",
"self.avgpool = layers.GlobalAveragePooling2D() self.fc = layers.Dense(num_classes) def call(self, inputs, training=None):",
"= self.layer2(x1) x3 = self.layer3(x2) x4 = self.layer4(x3) # [b,",
"layers.Conv2D(filters_num[4], kernel_size=(3, 3), padding='same',kernel_regularizer=regularizers.l2(0.0001))(conv4_relu) # filters_num = ** conv5_bn =",
"regularized_padded_conv(*args, **kwargs): return layers.Conv2D(*args, **kwargs, padding='same', use_bias=False, kernel_initializer='he_normal', kernel_regularizer=regularizers.l2(5e-4)) ###############################",
"filters_num = 8 # conv1 = layers.Conv3D(filters_num[0], kernel_size=(3, 3, 3),padding='same',kernel_initializer='he_normal',kernel_regularizer=regularizers.l2(0.0001))(input_layer_up)",
"* import tensorflow as tf from tensorflow import keras from",
"padding='same')(conv1_relu) # filters_num = 16 conv2 = layers.Conv3D(filters_num[1], kernel_size=(3, 3,",
"self.conv1 = layers.Conv2D(in_planes//ratio, kernel_size=1, strides=1, padding='same', kernel_regularizer=regularizers.l2(5e-4), use_bias=True, activation=tf.nn.relu) self.conv2",
"layers.Activation('relu') self.conv2 = layers.Conv2D(filter_num, (3, 3), strides=1, padding='same',kernel_regularizer=regularizers.l2(0.0001)) self.bn2 =",
"= 256 # layer4 = build_resblock(filters_num[8], layer_dims[3], stride=2) # filters_num",
"activation=tf.nn.relu) self.conv2 = layers.Conv2D(in_planes, kernel_size=1, strides=1, padding='same', kernel_regularizer=regularizers.l2(5e-4), use_bias=True) def",
"= Sequential([layers.Conv2D(64, (3, 3), strides=(1, 1)), layers.BatchNormalization(), layers.Activation('relu'), layers.MaxPool2D(pool_size=(2, 2),",
"# layers.Activation('relu'), # layers.MaxPool2D(pool_size=(2, 2), strides=(1, 1), padding='same') # ])",
"# [b, c] x = self.avgpool(x) # [b, 100] x",
"self.layer4 = self.build_resblock(filters_num[3], layer_dims[3], stride=1) # filters_num = 512 #",
"# conv22 = layers.Conv3D(filters_num[1], kernel_size=(5, 5, 3), padding='same', kernel_initializer='he_normal', #",
"padding='same')(conv1_relu) # filters_num = 16 # conv222 = layers.Conv3D(filters_num[1], kernel_size=(7,",
"out = self.bn2(out) out = self.relu2(out) out = self.conv3(out) out",
"filters_num = 512 # output: [b, 512, h, w], #",
"**kwargs): return layers.Conv2D(*args, **kwargs, padding='same', use_bias=False, kernel_initializer='he_normal', kernel_regularizer=regularizers.l2(5e-4)) ############################### 通道注意力机制",
"out = self.relu2(out) out = self.conv3(out) out = self.bn3(out) out",
"conv1_relu = layers.Activation('relu')(conv1_bn) # conv1_relu = Dropout(0.5)(conv1_relu) # conv1_relu =",
"return layers.Conv2D(*args, **kwargs, padding='same', use_bias=False, kernel_initializer='he_normal', kernel_regularizer=regularizers.l2(5e-4)) ############################### 通道注意力机制 ###############################",
"axis=3) max_out = tf.reduce_max(inputs, axis=3) out = tf.stack([avg_out, max_out], axis=3)",
"# filters_num = 32 # conv33_bn = layers.BatchNormalization()(conv33) # conv33_relu",
"self.layer3 = self.build_resblock(filters_num[7], layer_dims[2], stride=2) # filters_num = 256 self.layer4",
"kernel_regularizer=regularizers.l2(0.0001))(conv111_relu) # filters_num = 16 # conv222_bn = layers.BatchNormalization()(conv222) #",
"x = self.stem(inputs) x = self.layer1(x) x = self.layer2(x) x",
"layers.Activation('relu')(conv2_bn) # conv2_relu = Dropout(0.5)(conv2_relu) # conv2_relu = tf.keras.layers.MaxPooling3D(pool_size=(2, 2,",
"# conv3_relu = tf.keras.layers.MaxPooling3D(pool_size=(2, 2, 2), strides=(1, 1, 1), padding='same')(conv3_relu)",
"2, 2, 2] super(ResNet, self).__init__() self.stem = Sequential([layers.Conv2D(64, (3, 3),",
"= layers.Conv2D(filters_num[4], kernel_size=(3, 3), padding='same') # filters_num = ** self.bn5",
"= lambda x:x def call(self, inputs, training=None): # [b, h,",
"identity]) output = tf.nn.relu(output) return output ###################################### class build_resblock(keras.Model): def",
"conv22_relu = layers.Activation('relu')(conv22_bn) # # conv33 = layers.Conv3D(filters_num[2], kernel_size=(5, 5,",
"(1, 1), strides=stride)) else: self.downsample = lambda x:x def call(self,",
"100] x = self.fc(x) return x def build_resblock(self, filter_num, blocks,",
"= Sequential([layers.Conv2D(64, (3, 3), strides=(1, 1)), # layers.BatchNormalization(), # layers.Activation('relu'),",
"= layers.Conv2D(filter_num, (3, 3), strides=1, padding='same',kernel_regularizer=regularizers.l2(0.0001)) self.bn2 = layers.BatchNormalization() ###############################",
"return res_blocks def network_up(input_layer_up,filters_num,dropout_rate,Block_res): # input_layer = Input(input_shape) # conv1",
"# # conv33_relu_reshape = layers.Reshape( # (conv3_relu.shape[1], conv3_relu.shape[2], conv3_relu.shape[3] *",
"self).__init__() self.stem = Sequential([layers.Conv2D(64, (3, 3), strides=(1, 1)), layers.BatchNormalization(), layers.Activation('relu'),",
"self).__init__() self.conv1 = layers.Conv3D(filters_num[0],kernel_size=(3,3,7),padding='same') # filters_num = 8 self.bn1 =",
"conv5_relu = layers.Activation('relu')(conv5_bn) # conv5_relu = Dropout(0.5)(conv5_relu) # conv5_relu =",
"self.bn4 = layers.BatchNormalization() self.relu4 = layers.Activation('relu') self.conv5 = layers.Conv2D(filters_num[4], kernel_size=(3,",
"layers.Activation('relu')(conv1_bn) # conv1_relu = Dropout(0.5)(conv1_relu) # conv1_relu = tf.keras.layers.MaxPooling3D(pool_size=(2, 2,",
"(3, 3), strides=stride, padding='same', kernel_initializer='he_normal',kernel_regularizer=keras.regularizers.l2(5e-4)) self.conv1 = layers.Conv2D(filter_num, (3, 3),",
"def call(self, inputs, training=None): # x = self.stem(inputs) x1 =",
"layers.BatchNormalization()(conv222) # conv222_relu = layers.Activation('relu')(conv222_bn) # # conv333 = layers.Conv3D(filters_num[2],",
"return output ###################################### class build_resblock(keras.Model): def __init__(self, filter_num, stride): super(build_resblock,",
"= layers.Activation('relu')(conv2_bn) # conv2_relu = Dropout(0.5)(conv2_relu) # conv2_relu = tf.keras.layers.MaxPooling3D(pool_size=(2,",
"= layers.Reshape((out.shape[1],out.shape[2],out.shape[3] * out.shape[4]))(out) out = self.conv4(out) out = self.bn4(out)",
"# self.fc = layers.Dense(num_classes) def call(self, inputs, training=None): # x",
"= layers.Activation('relu')(conv1_bn) # conv1_relu = Dropout(0.5)(conv1_relu) # conv1_relu = tf.keras.layers.MaxPooling3D(pool_size=(2,",
"* # 定义一个3x3卷积!kernel_initializer='he_normal','glorot_normal' from tensorflow.python.keras.layers import Concatenate def regularized_padded_conv(*args, **kwargs):",
"= tf.keras.layers.MaxPooling3D(pool_size=(1, 1, 1),padding='same')(conv1) # conv_layer1g = tf.keras.layers.GlobalMaxPooling3D()(conv1) conv1_bn =",
"layers.Reshape((conv5_dpout.shape[1],conv5_dpout.shape[2],conv5_dpout.shape[3]))(conv5_dpout) outputs2,outputs4 = Block_res(conv5_relu) return conv5,outputs2,outputs4 # layer1 = build_resblock(filters_num[5],",
"inputs, training=None): # [b, h, w, c] out = self.conv1(inputs)",
"= layers.Conv3D(filters_num[2], kernel_size=(3, 3, 3), padding='same') # filters_num = 32",
"out = self.ca(out) * out out = self.sa(out) * out",
"= tf.reduce_max(inputs, axis=3) out = tf.stack([avg_out, max_out], axis=3) # 创建一个维度,拼接到一起concat。",
"call(self, inputs): avg_out = tf.reduce_mean(inputs, axis=3) max_out = tf.reduce_max(inputs, axis=3)",
"# conv11_bn = layers.BatchNormalization()(conv11) # conv11_relu = layers.Activation('relu')(conv11_bn) # #",
"class ResNet(keras.Model): def __init__(self, layer_dims, num_classes=16): # [2, 2, 2,",
"ratio=8): super(ChannelAttention, self).__init__() self.avg= layers.GlobalAveragePooling2D() self.max= layers.GlobalMaxPooling2D() self.conv1 = layers.Conv2D(in_planes//ratio,",
"= self.stem(inputs) x = self.layer1(x) x = self.layer2(x) x =",
"out.shape[4]))(out) out = self.conv4(out) out = self.bn4(out) out = self.relu4(out)",
"self.conv2(self.conv1(max)) out = avg_out + max_out out = tf.nn.sigmoid(out) return",
"__init__(self, layer_dims, num_classes=16): # [2, 2, 2, 2] super(ResNet, self).__init__()",
"self.fc4(x) return x def build_resblock(self, filter_num, blocks, stride=1): res_blocks =",
"return res_blocks class ResNet_block(keras.Model): def __init__(self, layer_dims,filters_num): # [2, 2,",
"= 64 conv4_bn = layers.BatchNormalization()(conv4) conv4_relu = layers.Activation('relu')(conv4_bn) # conv4_relu",
"= layers.Activation('relu')(conv22_bn) # # conv33 = layers.Conv3D(filters_num[2], kernel_size=(5, 5, 3),",
"3],num_classes=9) ########################### pp2主模型 ######################################## class pp2_model(keras.Model): def __init__(self,filters_num,layer_dims,num_classes,dropout_rate): super(pp2_model, self).__init__()",
"out = self.relu(out) out = self.conv2(out) out = self.bn2(out) ###############################",
"in range(1, blocks): res_blocks.add(BasicBlock(filter_num, stride=1)) return res_blocks def network_up(input_layer_up,filters_num,dropout_rate,Block_res): #",
"resnet18(): return ResNet([2, 2, 2, 2],num_classes=9) def resnet34(): return ResNet([3,",
"self).__init__() self.BasicBlock1 = BasicBlock(filter_num, stride) self.BasicBlock2 = BasicBlock(filter_num, stride=1) def",
"######################################### conv4 = layers.Conv2D(filters_num[3], kernel_size=(3, 3), padding='same',kernel_regularizer=regularizers.l2(0.0001))(conv3_relu_reshape) # filters_num =",
"strides=(1, 1, 1), padding='same')(conv1_relu) # conv2 = layers.Conv3D(filters_num[1], kernel_size=(3, 3,",
"(3, 3), strides=(1, 1)), layers.BatchNormalization(), layers.Activation('relu'), layers.MaxPool2D(pool_size=(2, 2), strides=(1, 1),",
"conv1_bn = layers.BatchNormalization()(conv1) conv1_relu = layers.Activation('relu')(conv1_bn) # conv1_relu = Dropout(0.5)(conv1_relu)",
"padding='same',kernel_regularizer=regularizers.l2(0.0001)) self.bn2 = layers.BatchNormalization() ############################### 注意力机制 ############################### self.ca = ChannelAttention(filter_num)",
"tf.keras.layers.MaxPooling3D(pool_size=(2, 2, 2), strides=(1, 1, 1), padding='same')(conv1_relu) # conv2 =",
"self.bn2 = layers.BatchNormalization() self.relu2 = layers.Activation('relu') self.conv3 = layers.Conv3D(filters_num[2], kernel_size=(3,",
"1), padding='same')(conv2_relu) conv3 = layers.Conv3D(filters_num[2], kernel_size=(3, 3, 3),padding='same',kernel_regularizer=regularizers.l2(0.0001))(conv2_relu) # filters_num",
"* out.shape[4]))(out) out = self.conv4(out) out = self.bn4(out) out =",
"32 conv3_bn = layers.BatchNormalization()(conv3) conv3_relu = layers.Activation('relu')(conv3_bn) # conv3_relu =",
"# filters_num = 16 # conv22 = layers.Conv3D(filters_num[1], kernel_size=(5, 5,",
"= layers.BatchNormalization()(conv222) # conv222_relu = layers.Activation('relu')(conv222_bn) # # conv333 =",
"layers.Conv3D(filters_num[0], kernel_size=(3, 3, 7), padding='same')(input_layer) # filters_num = 8 #",
"def regularized_padded_conv(*args, **kwargs): return layers.Conv2D(*args, **kwargs, padding='same', use_bias=False, kernel_initializer='he_normal', kernel_regularizer=regularizers.l2(5e-4))",
"= tf.reduce_mean(inputs, axis=3) max_out = tf.reduce_max(inputs, axis=3) out = tf.stack([avg_out,",
"self.dpout(out) out = self.conv5(out) out = self.bn5(out) out = self.dpout(out)",
"self.relu2 = layers.Activation('relu') self.conv3 = layers.Conv3D(filters_num[2], kernel_size=(3, 3, 3), padding='same')",
"# self.fc1 = layers.Flatten() self.avgpool = layers.GlobalAveragePooling2D() self.fc2 = layers.Dense(filters_num[7],activation='relu')",
"layers.Conv3D(filters_num[0], kernel_size=(7, 7, 3), padding='same', # kernel_initializer='he_normal', kernel_regularizer=regularizers.l2(0.0001))(input_layer_up) # conv111_bn",
"call(self,inputs,training=None): out = self.conv1(inputs) out = self.bn1(out) out = self.relu1(out)",
"= 256 self.layer4 = self.build_resblock(filters_num[3], layer_dims[3], stride=1) # filters_num =",
"conv_layer1g = tf.keras.layers.GlobalMaxPooling3D()(conv1) conv1_bn = layers.BatchNormalization()(conv1) conv1_relu = layers.Activation('relu')(conv1_bn) #",
"padding='same',kernel_regularizer=regularizers.l2(0.0001))(conv4_relu) # filters_num = ** conv5_bn = layers.BatchNormalization()(conv5) conv5_relu =",
"__init__(self, in_planes, ratio=8): super(ChannelAttention, self).__init__() self.avg= layers.GlobalAveragePooling2D() self.max= layers.GlobalMaxPooling2D() self.conv1",
"1, 1 feature) max = layers.Reshape((1, 1, max.shape[1]))(max) # shape",
"keras from tensorflow.keras import layers, Sequential,regularizers from tensorflow.keras.layers import Dropout",
"self.layer3 = self.build_resblock(filters_num[2], layer_dims[2], stride=1) # filters_num = 256 self.layer4",
"= 512 # output: [b, 512, h, w], # self.avgpool",
"kernel_size=(3, 3, 7), padding='same')(input_layer) # filters_num = 8 # conv1",
"3, 3), padding='same') # filters_num = 32 self.bn3 = layers.BatchNormalization()",
"64 # layer2 = build_resblock(filters_num[6], layer_dims[1], stride=2) # filters_num =",
"self).__init__() # # self.stem = Sequential([layers.Conv2D(64, (3, 3), strides=(1, 1)),",
"identity = self.downsample(inputs) output = layers.add([out, identity]) output = tf.nn.relu(output)",
"!= 1: self.downsample = Sequential() self.downsample.add(layers.Conv2D(filter_num, (1, 1), strides=stride)) else:",
"max.shape[1]))(max) # shape (None, 1, 1 feature) avg_out = self.conv2(self.conv1(avg))",
"# conv1_relu = Dropout(0.5)(conv1_relu) # conv1_relu = tf.keras.layers.MaxPooling3D(pool_size=(2, 2, 2),",
"kernel_regularizer=regularizers.l2(0.0001))(input_layer_up) # conv111_bn = layers.BatchNormalization()(conv111) # conv111_relu = layers.Activation('relu')(conv111_bn) #",
"call(self,blocks): res_blocks = Sequential() res_blocks.add(self.BasicBlock1) for _ in range(1, blocks):",
"layers.MaxPool2D(pool_size=(2, 2), strides=(1, 1), padding='same') # ]) self.layer1 = self.build_resblock(filters_num[0],",
"# shape (None, 1, 1 feature) max = layers.Reshape((1, 1,",
"# layer1 = build_resblock(filters_num[5], layer_dims[0]) # filters_num = 64 #",
"from tensorflow.keras import * # 定义一个3x3卷积!kernel_initializer='he_normal','glorot_normal' from tensorflow.python.keras.layers import Concatenate",
"padding='same')(conv3_relu) conv3_relu_reshape = layers.Reshape((conv3_relu.shape[1],conv3_relu.shape[2],conv3_relu.shape[3]*conv3_relu.shape[4]))(conv3_relu) conv3_relu_reshape = Dropout(0.5)(conv3_relu_reshape) ##################第二个尺度######################### # conv11",
"SpatialAttention() if stride != 1: self.downsample = Sequential() self.downsample.add(layers.Conv2D(filter_num, (1,",
"= layers.BatchNormalization() self.relu1 = layers.Activation('relu') self.conv2 = layers.Conv3D(filters_num[1],kernel_size=(3,3,5),padding='same') # filters_num",
"self.conv2(out) out = self.bn2(out) out = self.relu2(out) out = self.conv3(out)",
"1, 1), padding='same')(conv5_relu) # conv5_dpout = layers.Dropout(dropout_rate)(conv5) # conv5_reshape =",
"= layers.Conv3D(filters_num[2], kernel_size=(7, 7, 3), padding='same', kernel_initializer='he_normal', # kernel_regularizer=regularizers.l2(0.0001))(conv222_relu) #",
"= tf.keras.layers.MaxPooling2D(pool_size=(2, 2), strides=(1, 1), padding='same')(conv5_relu) # conv5_relu = tf.keras.layers.MaxPooling3D(pool_size=(2,",
"# filters_num = 128 self.layer3 = self.build_resblock(filters_num[7], layer_dims[2], stride=2) #",
"64 self.layer2 = self.build_resblock(filters_num[6], layer_dims[1], stride=2) # filters_num = 128",
"ChannelAttention(layers.Layer): def __init__(self, in_planes, ratio=8): super(ChannelAttention, self).__init__() self.avg= layers.GlobalAveragePooling2D() self.max=",
"range(1, blocks): res_blocks.add(BasicBlock(filter_num, stride=1)) return res_blocks class ResNet_block(keras.Model): def __init__(self,",
"range(1, blocks): res_blocks.add(BasicBlock(filter_num, stride=1)) return res_blocks def resnet18(): return ResNet([2,",
"= Dropout(0.5)(conv2_relu) # conv2_relu = tf.keras.layers.MaxPooling3D(pool_size=(2, 2, 2), strides=(1, 1,",
"conv2_bn = layers.BatchNormalization()(conv2) conv2_relu = layers.Activation('relu')(conv2_bn) # conv2_relu = Dropout(0.5)(conv2_relu)",
"activation=tf.nn.sigmoid) def call(self, inputs): avg_out = tf.reduce_mean(inputs, axis=3) max_out =",
"[b, 100] x = self.fc(x) return x def build_resblock(self, filter_num,",
"h, w, c] out = self.conv1(inputs) out = self.bn1(out) out",
"x def build_resblock(self, filter_num, blocks, stride=1): res_blocks = Sequential() #",
"############################### 注意力机制 ############################### out = self.ca(out) * out out =",
"= 16 conv2 = layers.Conv3D(filters_num[1], kernel_size=(3, 3, 3),padding='same',kernel_regularizer=regularizers.l2(0.0001))(conv1_relu) # filters_num",
"training=None): x = self.stem(inputs) x = self.layer1(x) x = self.layer2(x)",
"= Input(input_shape) # conv1 = layers.Conv3D(filters_num[0], kernel_size=(3, 3, 7), padding='same')(input_layer)",
"#################################################### # conv111 = layers.Conv3D(filters_num[0], kernel_size=(7, 7, 3), padding='same', #",
"tf.keras.layers.GlobalMaxPooling3D()(conv1) conv1_bn = layers.BatchNormalization()(conv1) conv1_relu = layers.Activation('relu')(conv1_bn) # conv1_relu =",
"layers.Conv2D(filter_num, (3, 3), strides=stride, padding='same',kernel_regularizer=regularizers.l2(0.0001)) #kernel_initializer='he_normal', self.bn1 = layers.BatchNormalization() self.relu",
"padding='same', kernel_initializer='he_normal', # kernel_regularizer=regularizers.l2(0.0001))(conv22_relu) # filters_num = 32 # conv33_bn",
"= layers.Activation('relu')(conv222_bn) # # conv333 = layers.Conv3D(filters_num[2], kernel_size=(7, 7, 3),",
"conv5 = layers.Conv2D(filters_num[4], kernel_size=(3, 3), padding='same',kernel_regularizer=regularizers.l2(0.0001))(conv4_relu) # filters_num = **",
"512 # output: [b, 512, h, w], # self.avgpool =",
"conv111_bn = layers.BatchNormalization()(conv111) # conv111_relu = layers.Activation('relu')(conv111_bn) # # #",
"= 16 conv2_bn = layers.BatchNormalization()(conv2) conv2_relu = layers.Activation('relu')(conv2_bn) # conv2_relu",
"filters_num = 64 # layer2 = build_resblock(filters_num[6], layer_dims[1], stride=2) #",
"1, 1), padding='same')(conv3_relu) conv3_relu_reshape = layers.Reshape((conv3_relu.shape[1],conv3_relu.shape[2],conv3_relu.shape[3]*conv3_relu.shape[4]))(conv3_relu) conv3_relu_reshape = Dropout(0.5)(conv3_relu_reshape) ##################第二个尺度#########################",
"# 创建一个维度,拼接到一起concat。 out = self.conv1(out) return out class BasicBlock(layers.Layer): def",
"padding='same')(conv1_relu) # conv2 = layers.Conv3D(filters_num[1], kernel_size=(3, 3, 5), padding='same')(conv1_relu) #",
"kernel_size=kernel_size, strides=1, activation=tf.nn.sigmoid) def call(self, inputs): avg_out = tf.reduce_mean(inputs, axis=3)",
"conv33_relu = layers.Activation('relu')(conv33_bn) # # conv33_relu_reshape = layers.Reshape( # (conv3_relu.shape[1],",
"[2, 2, 2, 2] super(ResNet_block, self).__init__() # # self.stem =",
"self.conv1(inputs) out = self.bn1(out) out = self.relu1(out) out = self.conv2(out)",
"256 # layer4 = build_resblock(filters_num[8], layer_dims[3], stride=2) # filters_num =",
"max = self.max(inputs) avg = layers.Reshape((1, 1, avg.shape[1]))(avg) # shape",
"layers.Activation('relu')(conv22_bn) # # conv33 = layers.Conv3D(filters_num[2], kernel_size=(5, 5, 3), padding='same',",
"conv4 = layers.Conv2D(filters_num[3], kernel_size=(3, 3), padding='same',kernel_regularizer=regularizers.l2(0.0001))(conv3_relu_reshape) # filters_num = 64",
"self.sa(out) * out identity = self.downsample(inputs) output = layers.add([out, identity])",
"32 # conv33_bn = layers.BatchNormalization()(conv33) # conv33_relu = layers.Activation('relu')(conv33_bn) #",
"1)), # layers.BatchNormalization(), # layers.Activation('relu'), # layers.MaxPool2D(pool_size=(2, 2), strides=(1, 1),",
"3), strides=1, padding='same',kernel_regularizer=regularizers.l2(0.0001)) self.bn2 = layers.BatchNormalization() ############################### 注意力机制 ############################### self.ca",
"= Dropout(0.5)(conv4_relu) # conv4_relu = tf.keras.layers.MaxPooling2D(pool_size=(2, 2), strides=(1, 1), padding='same')(conv4_relu)",
"filters_num = ** conv5_bn = layers.BatchNormalization()(conv5) conv5_relu = layers.Activation('relu')(conv5_bn) #",
"output ###################################### class build_resblock(keras.Model): def __init__(self, filter_num, stride): super(build_resblock, self).__init__()",
"return ResNet([2, 2, 2, 2],num_classes=9) def resnet34(): return ResNet([3, 4,",
"padding='same') # filters_num = 32 self.bn3 = layers.BatchNormalization() self.relu3 =",
"super(ChannelAttention, self).__init__() self.avg= layers.GlobalAveragePooling2D() self.max= layers.GlobalMaxPooling2D() self.conv1 = layers.Conv2D(in_planes//ratio, kernel_size=1,",
"# output: [b, 512, h, w], self.avgpool = layers.GlobalAveragePooling2D() self.fc",
"3), padding='same', # kernel_initializer='he_normal', kernel_regularizer=regularizers.l2(0.0001))(input_layer_up) # conv11_bn = layers.BatchNormalization()(conv11) #",
"self.fc(x) return x def build_resblock(self, filter_num, blocks, stride=1): res_blocks =",
"x = self.fc2(x) x = self.dpout(x) x = self.fc3(x) x",
"layers.BatchNormalization()(conv111) # conv111_relu = layers.Activation('relu')(conv111_bn) # # # conv2 =",
"[b, 100] # x = self.fc(x) return x2,x4 def build_resblock(self,",
"inputs): avg = self.avg(inputs) max = self.max(inputs) avg = layers.Reshape((1,",
"self.reshape = layers.Reshape() self.conv4 = layers.Conv2D(filters_num[3], kernel_size=(3, 3), padding='same') #",
"kernel_regularizer=regularizers.l2(0.0001))(conv222_relu) # filters_num = 32 # conv333_bn = layers.BatchNormalization()(conv333) #",
"1, 1), padding='same')(conv2_relu) conv3 = layers.Conv3D(filters_num[2], kernel_size=(3, 3, 3),padding='same',kernel_regularizer=regularizers.l2(0.0001))(conv2_relu) #",
"range(1, blocks): res_blocks.add(BasicBlock(filter_num, stride=1)) return res_blocks def network_up(input_layer_up,filters_num,dropout_rate,Block_res): # input_layer",
"layers.Conv2D(filter_num, (3, 3), strides=1, padding='same',kernel_regularizer=regularizers.l2(0.0001)) self.bn2 = layers.BatchNormalization() ############################### 注意力机制",
"inputs): avg_out = tf.reduce_mean(inputs, axis=3) max_out = tf.reduce_max(inputs, axis=3) out",
"output: [b, 512, h, w], # self.fc1 = layers.Flatten() self.avgpool",
"100] # x = self.fc(x) return x2,x4 def build_resblock(self, filter_num,",
"class pp2_model(keras.Model): def __init__(self,filters_num,layer_dims,num_classes,dropout_rate): super(pp2_model, self).__init__() self.conv1 = layers.Conv3D(filters_num[0],kernel_size=(3,3,7),padding='same') #",
"= self.build_resblock(filters_num[8], layer_dims[3], stride=2) # filters_num = 512 # output:",
"self.relu(out) out = self.conv2(out) out = self.bn2(out) ############################### 注意力机制 ###############################",
"100] x = self.fc2(x) x = self.dpout(x) x = self.fc3(x)",
"self.stem = Sequential([layers.Conv2D(64, (3, 3), strides=(1, 1)), layers.BatchNormalization(), layers.Activation('relu'), layers.MaxPool2D(pool_size=(2,",
"padding='same') # ]) self.layer1 = self.build_resblock(filters_num[0], layer_dims[0]) # filters_num =",
"1, 1), padding='same')(conv4_relu) conv5 = layers.Conv2D(filters_num[4], kernel_size=(3, 3), padding='same',kernel_regularizer=regularizers.l2(0.0001))(conv4_relu) #",
"res_blocks.add(BasicBlock(filter_num, stride=1)) return res_blocks ###################################### class ResNet(keras.Model): def __init__(self, layer_dims,",
"self.relu4 = layers.Activation('relu') self.conv5 = layers.Conv2D(filters_num[4], kernel_size=(3, 3), padding='same') #",
"= layers.Activation('relu') self.conv2 = layers.Conv3D(filters_num[1],kernel_size=(3,3,5),padding='same') # filters_num = 16 self.bn2",
"x = self.fc4(x) return x def build_resblock(self, filter_num, blocks, stride=1):",
"filters_num = 64 self.bn4 = layers.BatchNormalization() self.relu4 = layers.Activation('relu') self.conv5",
"# conv4_relu = tf.keras.layers.MaxPooling2D(pool_size=(2, 2), strides=(1, 1), padding='same')(conv4_relu) # conv4_relu",
"= layers.BatchNormalization()(conv2) conv2_relu = layers.Activation('relu')(conv2_bn) # conv2_relu = Dropout(0.5)(conv2_relu) #",
"build_resblock(filters_num[5], layer_dims[0]) # filters_num = 64 # layer2 = build_resblock(filters_num[6],",
"self).__init__() self.avg= layers.GlobalAveragePooling2D() self.max= layers.GlobalMaxPooling2D() self.conv1 = layers.Conv2D(in_planes//ratio, kernel_size=1, strides=1,",
"# conv33_relu_reshape = layers.Reshape( # (conv3_relu.shape[1], conv3_relu.shape[2], conv3_relu.shape[3] * conv3_relu.shape[4]))(conv33_relu)",
"# filters_num = 16 self.bn2 = layers.BatchNormalization() self.relu2 = layers.Activation('relu')",
"tf.stack([avg_out, max_out], axis=3) # 创建一个维度,拼接到一起concat。 out = self.conv1(out) return out",
"16 conv2 = layers.Conv3D(filters_num[1], kernel_size=(3, 3, 3),padding='same',kernel_regularizer=regularizers.l2(0.0001))(conv1_relu) # filters_num =",
"filters_num = 16 # conv22_bn = layers.BatchNormalization()(conv22) # conv22_relu =",
"# filters_num = 64 self.layer2 = self.build_resblock(filters_num[6], layer_dims[1], stride=2) #",
"for _ in range(1, blocks): res_blocks.add(BasicBlock(filter_num, stride=1)) return res_blocks def",
"64 self.bn4 = layers.BatchNormalization() self.relu4 = layers.Activation('relu') self.conv5 = layers.Conv2D(filters_num[4],",
"max_out], axis=3) # 创建一个维度,拼接到一起concat。 out = self.conv1(out) return out class",
"layers.Conv3D(filters_num[2], kernel_size=(7, 7, 3), padding='same', kernel_initializer='he_normal', # kernel_regularizer=regularizers.l2(0.0001))(conv222_relu) # filters_num",
"# [2, 2, 2, 2] super(ResNet_block, self).__init__() # # self.stem",
"conv4_relu = Dropout(0.5)(conv4_relu) # conv4_relu = tf.keras.layers.MaxPooling2D(pool_size=(2, 2), strides=(1, 1),",
"= layers.BatchNormalization()(conv5) conv5_relu = layers.Activation('relu')(conv5_bn) # conv5_relu = Dropout(0.5)(conv5_relu) #",
"# conv2_relu = Dropout(0.5)(conv2_relu) # conv2_relu = tf.keras.layers.MaxPooling3D(pool_size=(2, 2, 2),",
"# filters_num = 16 conv2_bn = layers.BatchNormalization()(conv2) conv2_relu = layers.Activation('relu')(conv2_bn)",
"in range(1, blocks): res_blocks.add(BasicBlock(filter_num, stride=1)) return res_blocks ###################################### class ResNet(keras.Model):",
"filters_num = 128 self.layer3 = self.build_resblock(filters_num[7], layer_dims[2], stride=2) # filters_num",
"self.sa = SpatialAttention() if stride != 1: self.downsample = Sequential()",
"= layers.Activation('relu')(conv3_bn) # conv3_relu = Dropout(0.5)(conv3_relu) # conv3_relu = tf.keras.layers.MaxPooling3D(pool_size=(2,",
"= layers.BatchNormalization()(conv22) # conv22_relu = layers.Activation('relu')(conv22_bn) # # conv33 =",
"kernel_initializer='he_normal', kernel_regularizer=regularizers.l2(0.0001))(input_layer_up) # conv111_bn = layers.BatchNormalization()(conv111) # conv111_relu = layers.Activation('relu')(conv111_bn)",
"空间注意力机制 ############################### class SpatialAttention(layers.Layer): def __init__(self, kernel_size=7): super(SpatialAttention, self).__init__() self.conv1",
"out = self.conv2(out) out = self.bn2(out) ############################### 注意力机制 ############################### out",
"conv2 = layers.Conv3D(filters_num[1], kernel_size=(3, 3, 3),padding='same',kernel_regularizer=regularizers.l2(0.0001))(conv1_relu) # filters_num = 16",
"= self.relu4(out) out = self.dpout(out) out = self.conv5(out) out =",
"from tensorflow import keras from tensorflow.keras import layers, Sequential,regularizers from",
"self.dpout(x) x = self.fc3(x) x = self.fc4(x) return x def",
"= self.fc(x) return x def build_resblock(self, filter_num, blocks, stride=1): res_blocks",
"self.conv3 = layers.Conv3D(filters_num[2], kernel_size=(3, 3, 3), padding='same') # filters_num =",
"= self.build_resblock(512, layer_dims[3], stride=1) # output: [b, 512, h, w],",
"class build_resblock(keras.Model): def __init__(self, filter_num, stride): super(build_resblock, self).__init__() self.BasicBlock1 =",
"= self.build_resblock(filters_num[7], layer_dims[2], stride=2) # filters_num = 256 self.layer4 =",
"pp2主模型 ######################################## class pp2_model(keras.Model): def __init__(self,filters_num,layer_dims,num_classes,dropout_rate): super(pp2_model, self).__init__() self.conv1 =",
"# layers.BatchNormalization(), # layers.Activation('relu'), # layers.MaxPool2D(pool_size=(2, 2), strides=(1, 1), padding='same')",
"# x = self.stem(inputs) x1 = self.layer1(inputs) x2 = self.layer2(x1)",
"x = self.fc(x) return x def build_resblock(self, filter_num, blocks, stride=1):",
"layers.Reshape() self.conv4 = layers.Conv2D(filters_num[3], kernel_size=(3, 3), padding='same') # filters_num =",
"= 512 # output: [b, 512, h, w], # self.fc1",
"conv222_bn = layers.BatchNormalization()(conv222) # conv222_relu = layers.Activation('relu')(conv222_bn) # # conv333",
"= self.build_resblock(filters_num[6], layer_dims[1], stride=2) # filters_num = 128 self.layer3 =",
"res_blocks def build_resblock(self, filter_num, blocks, stride=1): res_blocks = Sequential() #",
"for _ in range(1, blocks): res_blocks.add(BasicBlock(filter_num, stride=1)) return res_blocks class",
"kernel_size=1, strides=1, padding='same', kernel_regularizer=regularizers.l2(5e-4), use_bias=True, activation=tf.nn.relu) self.conv2 = layers.Conv2D(in_planes, kernel_size=1,",
"layers.Flatten() self.avgpool = layers.GlobalAveragePooling2D() self.fc2 = layers.Dense(filters_num[7],activation='relu') self.fc3 = layers.Dense(filters_num[6],activation='relu')",
"# output: [b, 512, h, w], # self.fc1 = layers.Flatten()",
"kernel_size=(3, 3, 3), padding='same') # filters_num = 32 self.bn3 =",
"# kernel_initializer='he_normal', kernel_regularizer=regularizers.l2(0.0001))(input_layer_up) # conv111_bn = layers.BatchNormalization()(conv111) # conv111_relu =",
"out = layers.Reshape((out.shape[1],out.shape[2],out.shape[3] * out.shape[4]))(out) out = self.conv4(out) out =",
"3), padding='same', kernel_initializer='he_normal', # kernel_regularizer=regularizers.l2(0.0001))(conv22_relu) # filters_num = 32 #",
"= self.conv1(out) return out class BasicBlock(layers.Layer): def __init__(self, filter_num, stride=1):",
"layers.Activation('relu')(conv333_bn) # # conv333_relu_reshape = layers.Reshape( # (conv3_relu.shape[1], conv3_relu.shape[2], conv3_relu.shape[3]",
"out out = self.sa(out) * out identity = self.downsample(inputs) output",
"= layers.Conv3D(filters_num[1], kernel_size=(7, 7, 3), padding='same', kernel_initializer='he_normal', # kernel_regularizer=regularizers.l2(0.0001))(conv111_relu) #",
"self.layer3(x2) x4 = self.layer4(x3) # [b, c] # x =",
"padding='same')(conv5_relu) # conv5_relu = tf.keras.layers.MaxPooling3D(pool_size=(2, 2, 2), strides=(1, 1, 1),",
"layers.add([out, identity]) output = tf.nn.relu(output) return output ###################################### class build_resblock(keras.Model):",
"3),padding='same',kernel_initializer='he_normal',kernel_regularizer=regularizers.l2(0.0001))(input_layer_up) # filters_num = 8 conv1 = layers.Conv3D(filters_num[0], kernel_size=(3, 3,",
"conv11 = layers.Conv3D(filters_num[0], kernel_size=(5, 5, 3), padding='same', # kernel_initializer='he_normal', kernel_regularizer=regularizers.l2(0.0001))(input_layer_up)",
"conv111 = layers.Conv3D(filters_num[0], kernel_size=(7, 7, 3), padding='same', # kernel_initializer='he_normal', kernel_regularizer=regularizers.l2(0.0001))(input_layer_up)",
"Input(input_shape) # conv1 = layers.Conv3D(filters_num[0], kernel_size=(3, 3, 7), padding='same')(input_layer) #",
"= self.avgpool(x) # [b, 100] x = self.fc2(x) x =",
"# filters_num = 512 # output: [b, 512, h, w],",
"strides=(1, 1)), # layers.BatchNormalization(), # layers.Activation('relu'), # layers.MaxPool2D(pool_size=(2, 2), strides=(1,",
"layers.Conv3D(filters_num[1], kernel_size=(3, 3, 3),padding='same',kernel_regularizer=regularizers.l2(0.0001))(conv1_relu) # filters_num = 16 conv2_bn =",
"= self.fc(x) return x2,x4 def build_resblock(self, filter_num, blocks, stride=1): res_blocks",
"# filters_num = 256 # layer4 = build_resblock(filters_num[8], layer_dims[3], stride=2)",
"self.bn5 = layers.BatchNormalization() self.relu5 = layers.Activation('relu') self.dpout = layers.Dropout(dropout_rate) self.layer1",
"layers.BatchNormalization() self.relu4 = layers.Activation('relu') self.conv5 = layers.Conv2D(filters_num[4], kernel_size=(3, 3), padding='same')",
"layers.Conv2D(filters_num[4], kernel_size=(3, 3), padding='same') # filters_num = ** self.bn5 =",
"3), padding='same', kernel_initializer='he_normal', # kernel_regularizer=regularizers.l2(0.0001))(conv11_relu) # filters_num = 16 #",
"# (conv3_relu.shape[1], conv3_relu.shape[2], conv3_relu.shape[3] * conv3_relu.shape[4]))(conv333_relu) #################concatenate######################## # conv33333_relu_reshape =",
"def resnet34(): return ResNet([3, 4, 6, 3],num_classes=9) ########################### pp2主模型 ########################################",
"self.fc = layers.Dense(num_classes) def call(self, inputs, training=None): # x =",
"layers.BatchNormalization(), # layers.Activation('relu'), # layers.MaxPool2D(pool_size=(2, 2), strides=(1, 1), padding='same') #",
"c] x = self.avgpool(x) # [b, 100] x = self.fc(x)",
"* out out = self.sa(out) * out identity = self.downsample(inputs)",
"1, max.shape[1]))(max) # shape (None, 1, 1 feature) avg_out =",
"+ max_out out = tf.nn.sigmoid(out) return out ############################### 空间注意力机制 ###############################",
"= tf.keras.layers.MaxPooling3D(pool_size=(2, 2, 2), strides=(1, 1, 1), padding='same')(conv5_relu) # conv5_dpout",
"class SpatialAttention(layers.Layer): def __init__(self, kernel_size=7): super(SpatialAttention, self).__init__() self.conv1 = regularized_padded_conv(1,",
"# conv_layer1m = tf.keras.layers.MaxPooling3D(pool_size=(1, 1, 1),padding='same')(conv1) # conv_layer1g = tf.keras.layers.GlobalMaxPooling3D()(conv1)",
"padding='same')(conv1_relu) # filters_num = 16 # conv22 = layers.Conv3D(filters_num[1], kernel_size=(5,",
"= layers.BatchNormalization() ############################### 注意力机制 ############################### self.ca = ChannelAttention(filter_num) self.sa =",
"kernel_initializer='he_normal', kernel_regularizer=regularizers.l2(0.0001))(input_layer_up) # conv11_bn = layers.BatchNormalization()(conv11) # conv11_relu = layers.Activation('relu')(conv11_bn)",
"ChannelAttention(filter_num) self.sa = SpatialAttention() if stride != 1: self.downsample =",
"# # conv33 = layers.Conv3D(filters_num[2], kernel_size=(5, 5, 3), padding='same', kernel_initializer='he_normal',",
"kernel_size=(3, 3, 3), padding='same', kernel_regularizer=regularizers.l2(0.0001))(input_layer_up) #kernel_initializer='he_normal', # conv_layer1m = tf.keras.layers.MaxPooling3D(pool_size=(1,",
"def call(self, inputs): avg = self.avg(inputs) max = self.max(inputs) avg",
"tf.keras.layers.MaxPooling2D(pool_size=(2, 2), strides=(1, 1), padding='same')(conv4_relu) # conv4_relu = tf.keras.layers.MaxPooling3D(pool_size=(2, 2,",
"= ** conv5_bn = layers.BatchNormalization()(conv5) conv5_relu = layers.Activation('relu')(conv5_bn) # conv5_relu",
"out = self.dpout(out) out = self.conv5(out) out = self.bn5(out) out",
"= layers.BatchNormalization()(conv333) # conv333_relu = layers.Activation('relu')(conv333_bn) # # conv333_relu_reshape =",
"(conv3_relu.shape[1], conv3_relu.shape[2], conv3_relu.shape[3] * conv3_relu.shape[4]))(conv33_relu) #################################################### # conv111 = layers.Conv3D(filters_num[0],",
"call(self, inputs, training=None): # [b, h, w, c] out =",
"# ]) self.layer1 = self.build_resblock(filters_num[0], layer_dims[0]) # filters_num = 64",
"3), strides=(1, 1)), layers.BatchNormalization(), layers.Activation('relu'), layers.MaxPool2D(pool_size=(2, 2), strides=(1, 1), padding='same')",
"= 16 # conv22_bn = layers.BatchNormalization()(conv22) # conv22_relu = layers.Activation('relu')(conv22_bn)",
"filters_num = 32 self.bn3 = layers.BatchNormalization() self.relu3 = layers.Activation('relu') #",
"= tf.keras.layers.MaxPooling3D(pool_size=(2, 2, 2), strides=(1, 1, 1), padding='same')(conv3_relu) conv3_relu_reshape =",
"def network_up(input_layer_up,filters_num,dropout_rate,Block_res): # input_layer = Input(input_shape) # conv1 = layers.Conv3D(filters_num[0],",
"# filters_num = 32 # conv333_bn = layers.BatchNormalization()(conv333) # conv333_relu",
"regularized_padded_conv(1, kernel_size=kernel_size, strides=1, activation=tf.nn.sigmoid) def call(self, inputs): avg_out = tf.reduce_mean(inputs,",
"[2, 2, 2, 2] super(ResNet, self).__init__() self.stem = Sequential([layers.Conv2D(64, (3,",
"= self.fc3(x) x = self.fc4(x) return x def build_resblock(self, filter_num,",
"= 16 # conv22 = layers.Conv3D(filters_num[1], kernel_size=(5, 5, 3), padding='same',",
"kernel_initializer='he_normal', # kernel_regularizer=regularizers.l2(0.0001))(conv222_relu) # filters_num = 32 # conv333_bn =",
"self.stem = Sequential([layers.Conv2D(64, (3, 3), strides=(1, 1)), # layers.BatchNormalization(), #",
"strides=(1, 1), padding='same') ]) self.layer1 = self.build_resblock(64, layer_dims[0]) self.layer2 =",
"network_up(input_layer_up,filters_num,dropout_rate,Block_res): # input_layer = Input(input_shape) # conv1 = layers.Conv3D(filters_num[0], kernel_size=(3,",
"blocks): res_blocks.add(BasicBlock(filter_num, stride=1)) return res_blocks class ResNet_block(keras.Model): def __init__(self, layer_dims,filters_num):",
"self.fc2(x) x = self.dpout(x) x = self.fc3(x) x = self.fc4(x)",
"32 # conv333_bn = layers.BatchNormalization()(conv333) # conv333_relu = layers.Activation('relu')(conv333_bn) #",
"5, 3), padding='same', # kernel_initializer='he_normal', kernel_regularizer=regularizers.l2(0.0001))(input_layer_up) # conv11_bn = layers.BatchNormalization()(conv11)",
"conv3_relu_reshape = layers.Reshape((conv3_relu.shape[1],conv3_relu.shape[2],conv3_relu.shape[3]*conv3_relu.shape[4]))(conv3_relu) conv3_relu_reshape = Dropout(0.5)(conv3_relu_reshape) ##################第二个尺度######################### # conv11 =",
"= self.build_resblock(filters_num[1], layer_dims[1], stride=1) # filters_num = 128 self.layer3 =",
"self.downsample = Sequential() self.downsample.add(layers.Conv2D(filter_num, (1, 1), strides=stride)) else: self.downsample =",
"self.layer1 = self.build_resblock(filters_num[5], layer_dims[0]) # filters_num = 64 self.layer2 =",
"layers.Conv2D(filters_num[3], kernel_size=(3, 3), padding='same',kernel_regularizer=regularizers.l2(0.0001))(conv3_relu_reshape) # filters_num = 64 conv4_bn =",
"strides=(1, 1), padding='same') # ]) self.layer1 = self.build_resblock(filters_num[0], layer_dims[0]) #",
"2, 2] super(ResNet_block, self).__init__() # # self.stem = Sequential([layers.Conv2D(64, (3,",
"conv11_bn = layers.BatchNormalization()(conv11) # conv11_relu = layers.Activation('relu')(conv11_bn) # # #",
"# conv33_relu = layers.Activation('relu')(conv33_bn) # # conv33_relu_reshape = layers.Reshape( #",
"filters_num = 64 self.layer2 = self.build_resblock(filters_num[6], layer_dims[1], stride=2) # filters_num",
"############################### 通道注意力机制 ############################### class ChannelAttention(layers.Layer): def __init__(self, in_planes, ratio=8): super(ChannelAttention,",
"_ in range(1, blocks): res_blocks.add(BasicBlock(filter_num, stride=1)) return res_blocks def resnet18():",
"self.avg(inputs) max = self.max(inputs) avg = layers.Reshape((1, 1, avg.shape[1]))(avg) #",
"res_blocks def resnet18(): return ResNet([2, 2, 2, 2],num_classes=9) def resnet34():",
"= self.build_resblock(filters_num[0], layer_dims[0]) # filters_num = 64 self.layer2 = self.build_resblock(filters_num[1],",
"7, 3), padding='same', kernel_initializer='he_normal', # kernel_regularizer=regularizers.l2(0.0001))(conv111_relu) # filters_num = 16",
"self.max(inputs) avg = layers.Reshape((1, 1, avg.shape[1]))(avg) # shape (None, 1,",
"x = self.layer2(x) x = self.layer3(x) x = self.layer4(x) #",
"(3, 3), strides=1, padding='same',kernel_regularizer=regularizers.l2(0.0001)) self.bn2 = layers.BatchNormalization() ############################### 注意力机制 ###############################",
"use_bias=True, activation=tf.nn.relu) self.conv2 = layers.Conv2D(in_planes, kernel_size=1, strides=1, padding='same', kernel_regularizer=regularizers.l2(5e-4), use_bias=True)",
"= layers.Activation('relu')(conv11_bn) # # # conv2 = layers.Conv3D(filters_num[1], kernel_size=(3, 3,",
"= 256 self.layer4 = self.build_resblock(filters_num[8], layer_dims[3], stride=2) # filters_num =",
"conv4_relu = layers.Activation('relu')(conv4_bn) # conv4_relu = Dropout(0.5)(conv4_relu) # conv4_relu =",
"__init__(self, layer_dims,filters_num): # [2, 2, 2, 2] super(ResNet_block, self).__init__() #",
"feature) max = layers.Reshape((1, 1, max.shape[1]))(max) # shape (None, 1,",
"conv111_relu = layers.Activation('relu')(conv111_bn) # # # conv2 = layers.Conv3D(filters_num[1], kernel_size=(3,",
"out = tf.nn.sigmoid(out) return out ############################### 空间注意力机制 ############################### class SpatialAttention(layers.Layer):",
"= self.bn4(out) out = self.relu4(out) out = self.dpout(out) out =",
"= self.bn1(out) out = self.relu1(out) out = self.conv2(out) out =",
"= layers.Dropout(dropout_rate)(conv5) # conv5_reshape = layers.Reshape((conv5_dpout.shape[1],conv5_dpout.shape[2],conv5_dpout.shape[3]))(conv5_dpout) outputs2,outputs4 = Block_res(conv5_relu) return",
"# conv333_relu = layers.Activation('relu')(conv333_bn) # # conv333_relu_reshape = layers.Reshape( #",
"ResNet(keras.Model): def __init__(self, layer_dims, num_classes=16): # [2, 2, 2, 2]",
"= layers.Dense(filters_num[6],activation='relu') self.fc4 = layers.Dense(num_classes) def call(self,inputs,training=None): out = self.conv1(inputs)",
"max_out = tf.reduce_max(inputs, axis=3) out = tf.stack([avg_out, max_out], axis=3) #",
"# conv11 = layers.Conv3D(filters_num[0], kernel_size=(5, 5, 3), padding='same', # kernel_initializer='he_normal',",
"out = self.bn4(out) out = self.relu4(out) out = self.dpout(out) out",
"# conv111 = layers.Conv3D(filters_num[0], kernel_size=(7, 7, 3), padding='same', # kernel_initializer='he_normal',",
"** conv5_bn = layers.BatchNormalization()(conv5) conv5_relu = layers.Activation('relu')(conv5_bn) # conv5_relu =",
"conv3_relu.shape[2], conv3_relu.shape[3] * conv3_relu.shape[4]))(conv33_relu) #################################################### # conv111 = layers.Conv3D(filters_num[0], kernel_size=(7,",
"# conv5_relu = tf.keras.layers.MaxPooling2D(pool_size=(2, 2), strides=(1, 1), padding='same')(conv5_relu) # conv5_relu",
"layers.Conv3D(filters_num[2], kernel_size=(3, 3, 3), padding='same') # filters_num = 32 self.bn3",
"padding='same', kernel_initializer='he_normal', # kernel_regularizer=regularizers.l2(0.0001))(conv11_relu) # filters_num = 16 # conv22_bn",
"build_resblock(filters_num[7], layer_dims[2], stride=2) # filters_num = 256 # layer4 =",
"conv333_relu_reshape = layers.Reshape( # (conv3_relu.shape[1], conv3_relu.shape[2], conv3_relu.shape[3] * conv3_relu.shape[4]))(conv333_relu) #################concatenate########################",
"out = self.bn3(out) out = self.relu3(out) # reshape out =",
"= tf.keras.layers.MaxPooling2D(pool_size=(2, 2), strides=(1, 1), padding='same')(conv4_relu) # conv4_relu = tf.keras.layers.MaxPooling3D(pool_size=(2,",
"[b, 512, h, w], self.avgpool = layers.GlobalAveragePooling2D() self.fc = layers.Dense(num_classes)",
"3, 5), padding='same')(conv1_relu) # filters_num = 16 # conv22 =",
"self.build_resblock(filters_num[2], layer_dims[2], stride=1) # filters_num = 256 self.layer4 = self.build_resblock(filters_num[3],",
"3, 3),padding='same',kernel_regularizer=regularizers.l2(0.0001))(conv1_relu) # filters_num = 16 conv2_bn = layers.BatchNormalization()(conv2) conv2_relu",
"layers.Conv3D(filters_num[1], kernel_size=(3, 3, 5), padding='same')(conv1_relu) # filters_num = 16 conv2",
"self.dpout(out) out = self.relu5(out) x = self.layer1(out) x = self.layer2(x)",
"# filters_num = 8 self.bn1 = layers.BatchNormalization() self.relu1 = layers.Activation('relu')",
"layers.BatchNormalization() self.relu5 = layers.Activation('relu') self.dpout = layers.Dropout(dropout_rate) self.layer1 = self.build_resblock(filters_num[5],",
"3), strides=(1, 1)), # layers.BatchNormalization(), # layers.Activation('relu'), # layers.MaxPool2D(pool_size=(2, 2),",
"kernel_regularizer=regularizers.l2(0.0001))(conv11_relu) # filters_num = 16 # conv22_bn = layers.BatchNormalization()(conv22) #",
"= layers.Conv2D(filters_num[3], kernel_size=(3, 3), padding='same',kernel_regularizer=regularizers.l2(0.0001))(conv3_relu_reshape) # filters_num = 64 conv4_bn",
"kernel_size=(7, 7, 3), padding='same', kernel_initializer='he_normal', # kernel_regularizer=regularizers.l2(0.0001))(conv111_relu) # filters_num =",
"self.downsample.add(layers.Conv2D(filter_num, (1, 1), strides=stride)) else: self.downsample = lambda x:x def",
"**kwargs, padding='same', use_bias=False, kernel_initializer='he_normal', kernel_regularizer=regularizers.l2(5e-4)) ############################### 通道注意力机制 ############################### class ChannelAttention(layers.Layer):",
"return conv5,outputs2,outputs4 # layer1 = build_resblock(filters_num[5], layer_dims[0]) # filters_num =",
"may down sample res_blocks.add(BasicBlock(filter_num, stride)) for _ in range(1, blocks):",
"= self.conv5(out) out = self.bn5(out) out = self.dpout(out) out =",
"_ in range(1, blocks): res_blocks.add(BasicBlock(filter_num, stride=1)) return res_blocks def network_up(input_layer_up,filters_num,dropout_rate,Block_res):",
"import keras from tensorflow.keras import layers, Sequential,regularizers from tensorflow.keras.layers import",
"tf.reduce_mean(inputs, axis=3) max_out = tf.reduce_max(inputs, axis=3) out = tf.stack([avg_out, max_out],",
"out = self.conv5(out) out = self.bn5(out) out = self.dpout(out) out",
"3, 3), padding='same', kernel_regularizer=regularizers.l2(0.0001))(input_layer_up) #kernel_initializer='he_normal', # conv_layer1m = tf.keras.layers.MaxPooling3D(pool_size=(1, 1,",
"3), padding='same') # filters_num = 64 self.bn4 = layers.BatchNormalization() self.relu4",
"注意力机制 ############################### out = self.ca(out) * out out = self.sa(out)",
"filters_num = 32 # conv333_bn = layers.BatchNormalization()(conv333) # conv333_relu =",
"= layers.Conv3D(filters_num[1], kernel_size=(3, 3, 5), padding='same')(conv1_relu) # filters_num = 16",
"out = self.conv1(inputs) out = self.bn1(out) out = self.relu1(out) out",
"x = self.avgpool(x) # [b, 100] x = self.fc2(x) x",
"= self.layer2(x) x = self.layer3(x) x = self.layer4(x) # [b,",
"self.conv1 = layers.Conv2D(filter_num, (3, 3), strides=stride, padding='same', kernel_initializer='he_normal',kernel_regularizer=keras.regularizers.l2(5e-4)) self.conv1 =",
"512, h, w], # self.avgpool = layers.GlobalAveragePooling2D() # self.fc =",
"conv33_bn = layers.BatchNormalization()(conv33) # conv33_relu = layers.Activation('relu')(conv33_bn) # # conv33_relu_reshape",
"# conv22_relu = layers.Activation('relu')(conv22_bn) # # conv33 = layers.Conv3D(filters_num[2], kernel_size=(5,",
"= layers.Reshape((1, 1, avg.shape[1]))(avg) # shape (None, 1, 1 feature)",
"= self.bn2(out) ############################### 注意力机制 ############################### out = self.ca(out) * out",
"7), padding='same')(input_layer) # filters_num = 8 # conv1 = layers.Conv3D(filters_num[0],",
"= layers.Conv3D(filters_num[0], kernel_size=(3, 3, 3), padding='same', kernel_regularizer=regularizers.l2(0.0001))(input_layer_up) #kernel_initializer='he_normal', # conv_layer1m",
"# filters_num = 64 self.layer2 = self.build_resblock(filters_num[1], layer_dims[1], stride=1) #",
"[b, h, w, c] out = self.conv1(inputs) out = self.bn1(out)",
"x = self.layer1(out) x = self.layer2(x) x = self.layer3(x) x",
"8 # conv1 = layers.Conv3D(filters_num[0], kernel_size=(3, 3, 3),padding='same',kernel_initializer='he_normal',kernel_regularizer=regularizers.l2(0.0001))(input_layer_up) # filters_num",
"= self.conv2(out) out = self.bn2(out) ############################### 注意力机制 ############################### out =",
"# [2, 2, 2, 2] super(ResNet, self).__init__() self.stem = Sequential([layers.Conv2D(64,",
"filters_num = 128 # layer3 = build_resblock(filters_num[7], layer_dims[2], stride=2) #",
"= layers.Conv2D(in_planes, kernel_size=1, strides=1, padding='same', kernel_regularizer=regularizers.l2(5e-4), use_bias=True) def call(self, inputs):",
"kernel_size=(3, 3), padding='same',kernel_regularizer=regularizers.l2(0.0001))(conv4_relu) # filters_num = ** conv5_bn = layers.BatchNormalization()(conv5)",
"out = self.dpout(out) out = self.relu5(out) x = self.layer1(out) x",
"= Concatenate(axis=-1)([conv3_relu_reshape, conv33_relu_reshape]) ######################################### conv4 = layers.Conv2D(filters_num[3], kernel_size=(3, 3), padding='same',kernel_regularizer=regularizers.l2(0.0001))(conv3_relu_reshape)",
"# conv1_relu = tf.keras.layers.MaxPooling3D(pool_size=(2, 2, 2), strides=(1, 1, 1), padding='same')(conv1_relu)",
"__init__(self, filter_num, stride): super(build_resblock, self).__init__() self.BasicBlock1 = BasicBlock(filter_num, stride) self.BasicBlock2",
"= layers.Dense(filters_num[7],activation='relu') self.fc3 = layers.Dense(filters_num[6],activation='relu') self.fc4 = layers.Dense(num_classes) def call(self,inputs,training=None):",
"tensorflow.keras import * import tensorflow as tf from tensorflow import",
"# # # conv2 = layers.Conv3D(filters_num[1], kernel_size=(3, 3, 5), padding='same')(conv1_relu)",
"############################### out = self.ca(out) * out out = self.sa(out) *",
"tensorflow.keras import * # 定义一个3x3卷积!kernel_initializer='he_normal','glorot_normal' from tensorflow.python.keras.layers import Concatenate def",
"x = self.avgpool(x) # [b, 100] x = self.fc(x) return",
"res_blocks.add(BasicBlock(filter_num, stride=1)) return res_blocks def network_up(input_layer_up,filters_num,dropout_rate,Block_res): # input_layer = Input(input_shape)",
"= layers.Activation('relu')(conv5_bn) # conv5_relu = Dropout(0.5)(conv5_relu) # conv5_relu = tf.keras.layers.MaxPooling2D(pool_size=(2,",
"16 # conv222_bn = layers.BatchNormalization()(conv222) # conv222_relu = layers.Activation('relu')(conv222_bn) #",
"= self.downsample(inputs) output = layers.add([out, identity]) output = tf.nn.relu(output) return",
"shape (None, 1, 1 feature) avg_out = self.conv2(self.conv1(avg)) max_out =",
"############################### 注意力机制 ############################### self.ca = ChannelAttention(filter_num) self.sa = SpatialAttention() if",
"x = self.layer4(x) # [b, c] x = self.avgpool(x) #",
"in range(1, blocks): res_blocks.add(BasicBlock(filter_num, stride=1)) return res_blocks def resnet18(): return",
"__init__(self,filters_num,layer_dims,num_classes,dropout_rate): super(pp2_model, self).__init__() self.conv1 = layers.Conv3D(filters_num[0],kernel_size=(3,3,7),padding='same') # filters_num = 8",
"= self.sa(out) * out identity = self.downsample(inputs) output = layers.add([out,",
"= self.conv4(out) out = self.bn4(out) out = self.relu4(out) out =",
"128 self.layer3 = self.build_resblock(filters_num[7], layer_dims[2], stride=2) # filters_num = 256",
"# conv4_relu = tf.keras.layers.MaxPooling3D(pool_size=(2, 2, 2), strides=(1, 1, 1), padding='same')(conv4_relu)",
"5), padding='same')(conv1_relu) # filters_num = 16 conv2 = layers.Conv3D(filters_num[1], kernel_size=(3,",
"# input_layer = Input(input_shape) # conv1 = layers.Conv3D(filters_num[0], kernel_size=(3, 3,",
"= self.layer3(x2) x4 = self.layer4(x3) # [b, c] # x",
"3, 3),padding='same',kernel_regularizer=regularizers.l2(0.0001))(conv2_relu) # filters_num = 32 conv3_bn = layers.BatchNormalization()(conv3) conv3_relu",
"layers.Conv2D(in_planes//ratio, kernel_size=1, strides=1, padding='same', kernel_regularizer=regularizers.l2(5e-4), use_bias=True, activation=tf.nn.relu) self.conv2 = layers.Conv2D(in_planes,",
"self.build_resblock(filters_num[5], layer_dims[0]) # filters_num = 64 self.layer2 = self.build_resblock(filters_num[6], layer_dims[1],",
"layers.BatchNormalization() ############################### 注意力机制 ############################### self.ca = ChannelAttention(filter_num) self.sa = SpatialAttention()",
"= BasicBlock(filter_num, stride=1) def call(self,blocks): res_blocks = Sequential() res_blocks.add(self.BasicBlock1) for",
"3),padding='same',kernel_regularizer=regularizers.l2(0.0001))(conv2_relu) # filters_num = 32 conv3_bn = layers.BatchNormalization()(conv3) conv3_relu =",
"layers.Reshape( # (conv3_relu.shape[1], conv3_relu.shape[2], conv3_relu.shape[3] * conv3_relu.shape[4]))(conv333_relu) #################concatenate######################## # conv33333_relu_reshape",
"w], self.avgpool = layers.GlobalAveragePooling2D() self.fc = layers.Dense(num_classes) def call(self, inputs,",
"= BasicBlock(filter_num, stride) self.BasicBlock2 = BasicBlock(filter_num, stride=1) def call(self,blocks): res_blocks",
"strides=stride, padding='same', kernel_initializer='he_normal',kernel_regularizer=keras.regularizers.l2(5e-4)) self.conv1 = layers.Conv2D(filter_num, (3, 3), strides=stride, padding='same',kernel_regularizer=regularizers.l2(0.0001))",
"strides=1, padding='same',kernel_regularizer=regularizers.l2(0.0001)) self.bn2 = layers.BatchNormalization() ############################### 注意力机制 ############################### self.ca =",
"x2 = self.layer2(x1) x3 = self.layer3(x2) x4 = self.layer4(x3) #",
"shape (None, 1, 1 feature) max = layers.Reshape((1, 1, max.shape[1]))(max)",
"3, 7), padding='same')(input_layer) # filters_num = 8 # conv1 =",
"self.conv5(out) out = self.bn5(out) out = self.dpout(out) out = self.relu5(out)",
"layers.Activation('relu')(conv5_bn) # conv5_relu = Dropout(0.5)(conv5_relu) # conv5_relu = tf.keras.layers.MaxPooling2D(pool_size=(2, 2),",
"strides=(1, 1)), layers.BatchNormalization(), layers.Activation('relu'), layers.MaxPool2D(pool_size=(2, 2), strides=(1, 1), padding='same') ])",
"= self.layer4(x) # [b, c] x = self.avgpool(x) # [b,",
"out = self.conv1(inputs) out = self.bn1(out) out = self.relu(out) out",
"512, h, w], # self.fc1 = layers.Flatten() self.avgpool = layers.GlobalAveragePooling2D()",
"= layers.Conv3D(filters_num[0], kernel_size=(5, 5, 3), padding='same', # kernel_initializer='he_normal', kernel_regularizer=regularizers.l2(0.0001))(input_layer_up) #",
"1), padding='same')(conv4_relu) conv5 = layers.Conv2D(filters_num[4], kernel_size=(3, 3), padding='same',kernel_regularizer=regularizers.l2(0.0001))(conv4_relu) # filters_num",
"out = self.relu4(out) out = self.dpout(out) out = self.conv5(out) out",
"layers.Conv2D(filter_num, (3, 3), strides=stride, padding='same', kernel_initializer='he_normal',kernel_regularizer=keras.regularizers.l2(5e-4)) self.conv1 = layers.Conv2D(filter_num, (3,",
"conv4_relu = tf.keras.layers.MaxPooling3D(pool_size=(2, 2, 2), strides=(1, 1, 1), padding='same')(conv4_relu) conv5",
"self.layer2(x) x = self.layer3(x) x = self.layer4(x) # [b, c]",
"def call(self, inputs, training=None): x = self.stem(inputs) x = self.layer1(x)",
"x = self.dpout(x) x = self.fc3(x) x = self.fc4(x) return",
"# x = self.fc(x) return x2,x4 def build_resblock(self, filter_num, blocks,",
"padding='same') # filters_num = 64 self.bn4 = layers.BatchNormalization() self.relu4 =",
"out = tf.stack([avg_out, max_out], axis=3) # 创建一个维度,拼接到一起concat。 out = self.conv1(out)",
"conv2_relu = tf.keras.layers.MaxPooling3D(pool_size=(2, 2, 2), strides=(1, 1, 1), padding='same')(conv2_relu) conv3",
"return res_blocks ###################################### class ResNet(keras.Model): def __init__(self, layer_dims, num_classes=16): #",
"blocks): res_blocks.add(BasicBlock(filter_num, stride=1)) return res_blocks ###################################### class ResNet(keras.Model): def __init__(self,",
"# conv2 = layers.Conv3D(filters_num[1], kernel_size=(3, 3, 5), padding='same')(conv1_relu) # filters_num",
"#################concatenate######################## # conv33333_relu_reshape = Concatenate(axis=-1)([conv3_relu_reshape, conv33_relu_reshape]) ######################################### conv4 = layers.Conv2D(filters_num[3],",
"2, 2), strides=(1, 1, 1), padding='same')(conv2_relu) conv3 = layers.Conv3D(filters_num[2], kernel_size=(3,",
"self.layer1(x) x = self.layer2(x) x = self.layer3(x) x = self.layer4(x)",
"16 # conv22 = layers.Conv3D(filters_num[1], kernel_size=(5, 5, 3), padding='same', kernel_initializer='he_normal',",
"self.bn3(out) out = self.relu3(out) # reshape out = layers.Reshape((out.shape[1],out.shape[2],out.shape[3] *",
"= layers.Reshape((conv3_relu.shape[1],conv3_relu.shape[2],conv3_relu.shape[3]*conv3_relu.shape[4]))(conv3_relu) conv3_relu_reshape = Dropout(0.5)(conv3_relu_reshape) ##################第二个尺度######################### # conv11 = layers.Conv3D(filters_num[0],",
"= self.relu5(out) x = self.layer1(out) x = self.layer2(x) x =",
"out class BasicBlock(layers.Layer): def __init__(self, filter_num, stride=1): super(BasicBlock, self).__init__() #",
"layers, Sequential,regularizers from tensorflow.keras.layers import Dropout # from tensorflow.keras import",
"self.build_resblock(256, layer_dims[2], stride=1) self.layer4 = self.build_resblock(512, layer_dims[3], stride=1) # output:",
"128 self.layer3 = self.build_resblock(filters_num[2], layer_dims[2], stride=1) # filters_num = 256",
"x:x def call(self, inputs, training=None): # [b, h, w, c]",
"= self.layer3(x) x = self.layer4(x) # [b, c] x =",
"layers.BatchNormalization()(conv33) # conv33_relu = layers.Activation('relu')(conv33_bn) # # conv33_relu_reshape = layers.Reshape(",
"#kernel_initializer='he_normal', self.bn1 = layers.BatchNormalization() self.relu = layers.Activation('relu') self.conv2 = layers.Conv2D(filter_num,",
"= layers.Reshape() self.conv4 = layers.Conv2D(filters_num[3], kernel_size=(3, 3), padding='same') # filters_num",
"self.relu1(out) out = self.conv2(out) out = self.bn2(out) out = self.relu2(out)",
"# self.reshape = layers.Reshape() self.conv4 = layers.Conv2D(filters_num[3], kernel_size=(3, 3), padding='same')",
"* conv3_relu.shape[4]))(conv33_relu) #################################################### # conv111 = layers.Conv3D(filters_num[0], kernel_size=(7, 7, 3),",
"= self.dpout(out) out = self.conv5(out) out = self.bn5(out) out =",
"= Dropout(0.5)(conv3_relu) # conv3_relu = tf.keras.layers.MaxPooling3D(pool_size=(2, 2, 2), strides=(1, 1,",
"layers.Activation('relu')(conv4_bn) # conv4_relu = Dropout(0.5)(conv4_relu) # conv4_relu = tf.keras.layers.MaxPooling2D(pool_size=(2, 2),",
"blocks): res_blocks.add(self.BasicBlock2) return res_blocks def build_resblock(self, filter_num, blocks, stride=1): res_blocks",
"# self.conv1 = layers.Conv2D(filter_num, (3, 3), strides=stride, padding='same', kernel_initializer='he_normal',kernel_regularizer=keras.regularizers.l2(5e-4)) self.conv1",
"blocks): res_blocks.add(BasicBlock(filter_num, stride=1)) return res_blocks def network_up(input_layer_up,filters_num,dropout_rate,Block_res): # input_layer =",
"inputs, training=None): x = self.stem(inputs) x = self.layer1(x) x =",
"BasicBlock(filter_num, stride=1) def call(self,blocks): res_blocks = Sequential() res_blocks.add(self.BasicBlock1) for _",
"self.relu2(out) out = self.conv3(out) out = self.bn3(out) out = self.relu3(out)",
"output = tf.nn.relu(output) return output ###################################### class build_resblock(keras.Model): def __init__(self,",
"padding='same', # kernel_initializer='he_normal', kernel_regularizer=regularizers.l2(0.0001))(input_layer_up) # conv111_bn = layers.BatchNormalization()(conv111) # conv111_relu",
"# kernel_regularizer=regularizers.l2(0.0001))(conv11_relu) # filters_num = 16 # conv22_bn = layers.BatchNormalization()(conv22)",
"# conv333_relu_reshape = layers.Reshape( # (conv3_relu.shape[1], conv3_relu.shape[2], conv3_relu.shape[3] * conv3_relu.shape[4]))(conv333_relu)",
"128 # layer3 = build_resblock(filters_num[7], layer_dims[2], stride=2) # filters_num =",
"stride=1) # output: [b, 512, h, w], self.avgpool = layers.GlobalAveragePooling2D()",
"= 32 # conv333_bn = layers.BatchNormalization()(conv333) # conv333_relu = layers.Activation('relu')(conv333_bn)",
"conv33 = layers.Conv3D(filters_num[2], kernel_size=(5, 5, 3), padding='same', kernel_initializer='he_normal', # kernel_regularizer=regularizers.l2(0.0001))(conv22_relu)",
"self.build_resblock(64, layer_dims[0]) self.layer2 = self.build_resblock(128, layer_dims[1], stride=1) self.layer3 = self.build_resblock(256,",
"5), padding='same')(conv1_relu) # filters_num = 16 # conv222 = layers.Conv3D(filters_num[1],",
"avg_out + max_out out = tf.nn.sigmoid(out) return out ############################### 空间注意力机制",
"self.layer1(out) x = self.layer2(x) x = self.layer3(x) x = self.layer4(x)",
"out = self.conv4(out) out = self.bn4(out) out = self.relu4(out) out",
"kernel_regularizer=regularizers.l2(0.0001))(input_layer_up) # conv11_bn = layers.BatchNormalization()(conv11) # conv11_relu = layers.Activation('relu')(conv11_bn) #",
"layer_dims[1], stride=1) # filters_num = 128 self.layer3 = self.build_resblock(filters_num[2], layer_dims[2],",
"5, 3), padding='same', kernel_initializer='he_normal', # kernel_regularizer=regularizers.l2(0.0001))(conv22_relu) # filters_num = 32",
"# kernel_regularizer=regularizers.l2(0.0001))(conv22_relu) # filters_num = 32 # conv33_bn = layers.BatchNormalization()(conv33)",
"conv11_relu = layers.Activation('relu')(conv11_bn) # # # conv2 = layers.Conv3D(filters_num[1], kernel_size=(3,",
"1 feature) max = layers.Reshape((1, 1, max.shape[1]))(max) # shape (None,",
"(3, 3), strides=(1, 1)), # layers.BatchNormalization(), # layers.Activation('relu'), # layers.MaxPool2D(pool_size=(2,",
"= self.build_resblock(64, layer_dims[0]) self.layer2 = self.build_resblock(128, layer_dims[1], stride=1) self.layer3 =",
"= self.relu(out) out = self.conv2(out) out = self.bn2(out) ############################### 注意力机制",
"= self.conv2(out) out = self.bn2(out) out = self.relu2(out) out =",
"* conv3_relu.shape[4]))(conv333_relu) #################concatenate######################## # conv33333_relu_reshape = Concatenate(axis=-1)([conv3_relu_reshape, conv33_relu_reshape]) ######################################### conv4",
"stride=2) # filters_num = 512 # output: [b, 512, h,",
"= self.ca(out) * out out = self.sa(out) * out identity",
"c] out = self.conv1(inputs) out = self.bn1(out) out = self.relu(out)",
"self.fc3(x) x = self.fc4(x) return x def build_resblock(self, filter_num, blocks,",
"# conv22_bn = layers.BatchNormalization()(conv22) # conv22_relu = layers.Activation('relu')(conv22_bn) # #",
"self.build_resblock(filters_num[6], layer_dims[1], stride=2) # filters_num = 128 self.layer3 = self.build_resblock(filters_num[7],",
"strides=(1, 1), padding='same')(conv4_relu) # conv4_relu = tf.keras.layers.MaxPooling3D(pool_size=(2, 2, 2), strides=(1,",
"def call(self,blocks): res_blocks = Sequential() res_blocks.add(self.BasicBlock1) for _ in range(1,",
"layer_dims[3], stride=1) # output: [b, 512, h, w], self.avgpool =",
"8 conv1 = layers.Conv3D(filters_num[0], kernel_size=(3, 3, 3), padding='same', kernel_regularizer=regularizers.l2(0.0001))(input_layer_up) #kernel_initializer='he_normal',",
"= self.build_resblock(256, layer_dims[2], stride=1) self.layer4 = self.build_resblock(512, layer_dims[3], stride=1) #",
"out = self.relu3(out) # reshape out = layers.Reshape((out.shape[1],out.shape[2],out.shape[3] * out.shape[4]))(out)",
"layers.BatchNormalization()(conv5) conv5_relu = layers.Activation('relu')(conv5_bn) # conv5_relu = Dropout(0.5)(conv5_relu) # conv5_relu",
"self.relu3(out) # reshape out = layers.Reshape((out.shape[1],out.shape[2],out.shape[3] * out.shape[4]))(out) out =",
"conv3 = layers.Conv3D(filters_num[2], kernel_size=(3, 3, 3),padding='same',kernel_regularizer=regularizers.l2(0.0001))(conv2_relu) # filters_num = 32",
"kernel_regularizer=regularizers.l2(5e-4), use_bias=True, activation=tf.nn.relu) self.conv2 = layers.Conv2D(in_planes, kernel_size=1, strides=1, padding='same', kernel_regularizer=regularizers.l2(5e-4),",
"res_blocks.add(BasicBlock(filter_num, stride=1)) return res_blocks def resnet18(): return ResNet([2, 2, 2,",
"# filters_num = 64 conv4_bn = layers.BatchNormalization()(conv4) conv4_relu = layers.Activation('relu')(conv4_bn)",
"= 8 self.bn1 = layers.BatchNormalization() self.relu1 = layers.Activation('relu') self.conv2 =",
"padding='same')(conv4_relu) # conv4_relu = tf.keras.layers.MaxPooling3D(pool_size=(2, 2, 2), strides=(1, 1, 1),",
"[b, 512, h, w], # self.fc1 = layers.Flatten() self.avgpool =",
"layers.Conv3D(filters_num[0], kernel_size=(3, 3, 3), padding='same', kernel_regularizer=regularizers.l2(0.0001))(input_layer_up) #kernel_initializer='he_normal', # conv_layer1m =",
"3), strides=stride, padding='same', kernel_initializer='he_normal',kernel_regularizer=keras.regularizers.l2(5e-4)) self.conv1 = layers.Conv2D(filter_num, (3, 3), strides=stride,",
"7, 3), padding='same', # kernel_initializer='he_normal', kernel_regularizer=regularizers.l2(0.0001))(input_layer_up) # conv111_bn = layers.BatchNormalization()(conv111)",
"layers.BatchNormalization() self.relu2 = layers.Activation('relu') self.conv3 = layers.Conv3D(filters_num[2], kernel_size=(3, 3, 3),",
"self.bn2(out) ############################### 注意力机制 ############################### out = self.ca(out) * out out",
"= layers.Conv3D(filters_num[1], kernel_size=(3, 3, 3),padding='same',kernel_regularizer=regularizers.l2(0.0001))(conv1_relu) # filters_num = 16 conv2_bn",
"conv333 = layers.Conv3D(filters_num[2], kernel_size=(7, 7, 3), padding='same', kernel_initializer='he_normal', # kernel_regularizer=regularizers.l2(0.0001))(conv222_relu)",
"tf.keras.layers.MaxPooling2D(pool_size=(2, 2), strides=(1, 1), padding='same')(conv5_relu) # conv5_relu = tf.keras.layers.MaxPooling3D(pool_size=(2, 2,",
"layer_dims[1], stride=2) # filters_num = 128 self.layer3 = self.build_resblock(filters_num[7], layer_dims[2],",
"= self.bn3(out) out = self.relu3(out) # reshape out = layers.Reshape((out.shape[1],out.shape[2],out.shape[3]",
"layers.Conv3D(filters_num[0],kernel_size=(3,3,7),padding='same') # filters_num = 8 self.bn1 = layers.BatchNormalization() self.relu1 =",
"_ in range(1, blocks): res_blocks.add(self.BasicBlock2) return res_blocks def build_resblock(self, filter_num,",
"stride=2) # filters_num = 128 self.layer3 = self.build_resblock(filters_num[7], layer_dims[2], stride=2)",
"padding='same',kernel_regularizer=regularizers.l2(0.0001)) #kernel_initializer='he_normal', self.bn1 = layers.BatchNormalization() self.relu = layers.Activation('relu') self.conv2 =",
"# filters_num = 256 self.layer4 = self.build_resblock(filters_num[8], layer_dims[3], stride=2) #",
"out = self.bn1(out) out = self.relu1(out) out = self.conv2(out) out",
"padding='same')(input_layer) # filters_num = 8 # conv1 = layers.Conv3D(filters_num[0], kernel_size=(3,",
"self.bn1 = layers.BatchNormalization() self.relu = layers.Activation('relu') self.conv2 = layers.Conv2D(filter_num, (3,",
"self.build_resblock(filters_num[3], layer_dims[3], stride=1) # filters_num = 512 # output: [b,",
"= 64 self.layer2 = self.build_resblock(filters_num[6], layer_dims[1], stride=2) # filters_num =",
"else: self.downsample = lambda x:x def call(self, inputs, training=None): #",
"= self.fc2(x) x = self.dpout(x) x = self.fc3(x) x =",
"layers.BatchNormalization()(conv2) conv2_relu = layers.Activation('relu')(conv2_bn) # conv2_relu = Dropout(0.5)(conv2_relu) # conv2_relu",
"kernel_size=(3, 3, 5), padding='same')(conv1_relu) # filters_num = 16 conv2 =",
"layers.Dense(num_classes) def call(self,inputs,training=None): out = self.conv1(inputs) out = self.bn1(out) out",
"= layers.Activation('relu') self.conv5 = layers.Conv2D(filters_num[4], kernel_size=(3, 3), padding='same') # filters_num",
"= layers.Dense(num_classes) def call(self, inputs, training=None): # x = self.stem(inputs)",
"= ChannelAttention(filter_num) self.sa = SpatialAttention() if stride != 1: self.downsample",
"1), padding='same') # ]) self.layer1 = self.build_resblock(filters_num[0], layer_dims[0]) # filters_num",
"call(self, inputs): avg = self.avg(inputs) max = self.max(inputs) avg =",
"= layers.BatchNormalization()(conv111) # conv111_relu = layers.Activation('relu')(conv111_bn) # # # conv2",
"2, 2), strides=(1, 1, 1), padding='same')(conv3_relu) conv3_relu_reshape = layers.Reshape((conv3_relu.shape[1],conv3_relu.shape[2],conv3_relu.shape[3]*conv3_relu.shape[4]))(conv3_relu) conv3_relu_reshape",
"3), strides=stride, padding='same',kernel_regularizer=regularizers.l2(0.0001)) #kernel_initializer='he_normal', self.bn1 = layers.BatchNormalization() self.relu = layers.Activation('relu')",
"3), padding='same', kernel_initializer='he_normal', # kernel_regularizer=regularizers.l2(0.0001))(conv111_relu) # filters_num = 16 #",
"2],num_classes=9) def resnet34(): return ResNet([3, 4, 6, 3],num_classes=9) ########################### pp2主模型",
"conv5,outputs2,outputs4 # layer1 = build_resblock(filters_num[5], layer_dims[0]) # filters_num = 64",
"out = self.bn1(out) out = self.relu(out) out = self.conv2(out) out",
"# self.avgpool = layers.GlobalAveragePooling2D() # self.fc = layers.Dense(num_classes) def call(self,",
"= layers.BatchNormalization() self.relu3 = layers.Activation('relu') # self.reshape = layers.Reshape() self.conv4",
"= 128 # layer3 = build_resblock(filters_num[7], layer_dims[2], stride=2) # filters_num",
"conv2_relu = Dropout(0.5)(conv2_relu) # conv2_relu = tf.keras.layers.MaxPooling3D(pool_size=(2, 2, 2), strides=(1,",
"= self.bn5(out) out = self.dpout(out) out = self.relu5(out) x =",
"self.conv1 = regularized_padded_conv(1, kernel_size=kernel_size, strides=1, activation=tf.nn.sigmoid) def call(self, inputs): avg_out",
"conv2 = layers.Conv3D(filters_num[1], kernel_size=(3, 3, 5), padding='same')(conv1_relu) # filters_num =",
"= tf.nn.relu(output) return output ###################################### class build_resblock(keras.Model): def __init__(self, filter_num,",
"# 定义一个3x3卷积!kernel_initializer='he_normal','glorot_normal' from tensorflow.python.keras.layers import Concatenate def regularized_padded_conv(*args, **kwargs): return",
"def __init__(self, in_planes, ratio=8): super(ChannelAttention, self).__init__() self.avg= layers.GlobalAveragePooling2D() self.max= layers.GlobalMaxPooling2D()",
"tensorflow.keras import layers, Sequential,regularizers from tensorflow.keras.layers import Dropout # from",
"from tensorflow.keras.layers import Dropout # from tensorflow.keras import * #",
"SpatialAttention(layers.Layer): def __init__(self, kernel_size=7): super(SpatialAttention, self).__init__() self.conv1 = regularized_padded_conv(1, kernel_size=kernel_size,",
"# filters_num = 16 # conv22_bn = layers.BatchNormalization()(conv22) # conv22_relu",
"# kernel_regularizer=regularizers.l2(0.0001))(conv111_relu) # filters_num = 16 # conv222_bn = layers.BatchNormalization()(conv222)",
"= self.dpout(x) x = self.fc3(x) x = self.fc4(x) return x",
"conv3_relu.shape[3] * conv3_relu.shape[4]))(conv333_relu) #################concatenate######################## # conv33333_relu_reshape = Concatenate(axis=-1)([conv3_relu_reshape, conv33_relu_reshape]) #########################################",
"BasicBlock(filter_num, stride) self.BasicBlock2 = BasicBlock(filter_num, stride=1) def call(self,blocks): res_blocks =",
"stride=1): super(BasicBlock, self).__init__() # self.conv1 = layers.Conv2D(filter_num, (3, 3), strides=stride,",
"kernel_regularizer=regularizers.l2(5e-4)) ############################### 通道注意力机制 ############################### class ChannelAttention(layers.Layer): def __init__(self, in_planes, ratio=8):",
"############################### class SpatialAttention(layers.Layer): def __init__(self, kernel_size=7): super(SpatialAttention, self).__init__() self.conv1 =",
"import layers, Sequential,regularizers from tensorflow.keras.layers import Dropout # from tensorflow.keras",
"out = self.bn5(out) out = self.dpout(out) out = self.relu5(out) x",
"1, 1 feature) avg_out = self.conv2(self.conv1(avg)) max_out = self.conv2(self.conv1(max)) out",
"layers.Activation('relu') self.conv2 = layers.Conv3D(filters_num[1],kernel_size=(3,3,5),padding='same') # filters_num = 16 self.bn2 =",
"2] super(ResNet_block, self).__init__() # # self.stem = Sequential([layers.Conv2D(64, (3, 3),",
"use_bias=True) def call(self, inputs): avg = self.avg(inputs) max = self.max(inputs)",
"self).__init__() self.conv1 = regularized_padded_conv(1, kernel_size=kernel_size, strides=1, activation=tf.nn.sigmoid) def call(self, inputs):",
"def __init__(self,filters_num,layer_dims,num_classes,dropout_rate): super(pp2_model, self).__init__() self.conv1 = layers.Conv3D(filters_num[0],kernel_size=(3,3,7),padding='same') # filters_num =",
"self.ca(out) * out out = self.sa(out) * out identity =",
"= layers.Activation('relu')(conv33_bn) # # conv33_relu_reshape = layers.Reshape( # (conv3_relu.shape[1], conv3_relu.shape[2],",
"tf.keras.layers.MaxPooling3D(pool_size=(1, 1, 1),padding='same')(conv1) # conv_layer1g = tf.keras.layers.GlobalMaxPooling3D()(conv1) conv1_bn = layers.BatchNormalization()(conv1)",
"layer_dims[1], stride=2) # filters_num = 128 # layer3 = build_resblock(filters_num[7],",
"1: self.downsample = Sequential() self.downsample.add(layers.Conv2D(filter_num, (1, 1), strides=stride)) else: self.downsample",
"tensorflow as tf from tensorflow import keras from tensorflow.keras import",
"= layers.Reshape((1, 1, max.shape[1]))(max) # shape (None, 1, 1 feature)",
"= layers.BatchNormalization() self.relu2 = layers.Activation('relu') self.conv3 = layers.Conv3D(filters_num[2], kernel_size=(3, 3,",
"2), strides=(1, 1), padding='same')(conv4_relu) # conv4_relu = tf.keras.layers.MaxPooling3D(pool_size=(2, 2, 2),",
"self.fc2 = layers.Dense(filters_num[7],activation='relu') self.fc3 = layers.Dense(filters_num[6],activation='relu') self.fc4 = layers.Dense(num_classes) def",
"w], # self.fc1 = layers.Flatten() self.avgpool = layers.GlobalAveragePooling2D() self.fc2 =",
"conv33_relu_reshape = layers.Reshape( # (conv3_relu.shape[1], conv3_relu.shape[2], conv3_relu.shape[3] * conv3_relu.shape[4]))(conv33_relu) ####################################################",
"256 self.layer4 = self.build_resblock(filters_num[3], layer_dims[3], stride=1) # filters_num = 512",
"self.conv4 = layers.Conv2D(filters_num[3], kernel_size=(3, 3), padding='same') # filters_num = 64",
"1),padding='same')(conv1) # conv_layer1g = tf.keras.layers.GlobalMaxPooling3D()(conv1) conv1_bn = layers.BatchNormalization()(conv1) conv1_relu =",
"filters_num = 16 # conv222 = layers.Conv3D(filters_num[1], kernel_size=(7, 7, 3),",
"# conv4_relu = Dropout(0.5)(conv4_relu) # conv4_relu = tf.keras.layers.MaxPooling2D(pool_size=(2, 2), strides=(1,",
"filters_num = 32 conv3_bn = layers.BatchNormalization()(conv3) conv3_relu = layers.Activation('relu')(conv3_bn) #",
"kernel_initializer='he_normal', kernel_regularizer=regularizers.l2(5e-4)) ############################### 通道注意力机制 ############################### class ChannelAttention(layers.Layer): def __init__(self, in_planes,",
"= layers.Activation('relu') self.conv2 = layers.Conv2D(filter_num, (3, 3), strides=1, padding='same',kernel_regularizer=regularizers.l2(0.0001)) self.bn2",
"= self.conv3(out) out = self.bn3(out) out = self.relu3(out) # reshape",
"out identity = self.downsample(inputs) output = layers.add([out, identity]) output =",
"stride) self.BasicBlock2 = BasicBlock(filter_num, stride=1) def call(self,blocks): res_blocks = Sequential()",
"########################### pp2主模型 ######################################## class pp2_model(keras.Model): def __init__(self,filters_num,layer_dims,num_classes,dropout_rate): super(pp2_model, self).__init__() self.conv1",
"layers.BatchNormalization()(conv1) conv1_relu = layers.Activation('relu')(conv1_bn) # conv1_relu = Dropout(0.5)(conv1_relu) # conv1_relu",
"filters_num = 16 self.bn2 = layers.BatchNormalization() self.relu2 = layers.Activation('relu') self.conv3",
"= 64 # layer2 = build_resblock(filters_num[6], layer_dims[1], stride=2) # filters_num",
"filter_num, stride=1): super(BasicBlock, self).__init__() # self.conv1 = layers.Conv2D(filter_num, (3, 3),",
"= self.conv2(self.conv1(max)) out = avg_out + max_out out = tf.nn.sigmoid(out)",
"kernel_initializer='he_normal', # kernel_regularizer=regularizers.l2(0.0001))(conv11_relu) # filters_num = 16 # conv22_bn =",
"(conv3_relu.shape[1], conv3_relu.shape[2], conv3_relu.shape[3] * conv3_relu.shape[4]))(conv333_relu) #################concatenate######################## # conv33333_relu_reshape = Concatenate(axis=-1)([conv3_relu_reshape,",
"= layers.Reshape( # (conv3_relu.shape[1], conv3_relu.shape[2], conv3_relu.shape[3] * conv3_relu.shape[4]))(conv333_relu) #################concatenate######################## #",
"= layers.Conv3D(filters_num[0],kernel_size=(3,3,7),padding='same') # filters_num = 8 self.bn1 = layers.BatchNormalization() self.relu1",
"= self.conv2(self.conv1(avg)) max_out = self.conv2(self.conv1(max)) out = avg_out + max_out",
"通道注意力机制 ############################### class ChannelAttention(layers.Layer): def __init__(self, in_planes, ratio=8): super(ChannelAttention, self).__init__()",
"Dropout(0.5)(conv3_relu) # conv3_relu = tf.keras.layers.MaxPooling3D(pool_size=(2, 2, 2), strides=(1, 1, 1),",
"conv1 = layers.Conv3D(filters_num[0], kernel_size=(3, 3, 3), padding='same', kernel_regularizer=regularizers.l2(0.0001))(input_layer_up) #kernel_initializer='he_normal', #",
"conv33333_relu_reshape = Concatenate(axis=-1)([conv3_relu_reshape, conv33_relu_reshape]) ######################################### conv4 = layers.Conv2D(filters_num[3], kernel_size=(3, 3),",
"down sample res_blocks.add(BasicBlock(filter_num, stride)) for _ in range(1, blocks): res_blocks.add(BasicBlock(filter_num,",
"super(build_resblock, self).__init__() self.BasicBlock1 = BasicBlock(filter_num, stride) self.BasicBlock2 = BasicBlock(filter_num, stride=1)",
"[b, c] # x = self.avgpool(x) # [b, 100] #",
"if stride != 1: self.downsample = Sequential() self.downsample.add(layers.Conv2D(filter_num, (1, 1),",
"self).__init__() # self.conv1 = layers.Conv2D(filter_num, (3, 3), strides=stride, padding='same', kernel_initializer='he_normal',kernel_regularizer=keras.regularizers.l2(5e-4))",
"in_planes, ratio=8): super(ChannelAttention, self).__init__() self.avg= layers.GlobalAveragePooling2D() self.max= layers.GlobalMaxPooling2D() self.conv1 =",
"c] # x = self.avgpool(x) # [b, 100] # x",
"w], # self.avgpool = layers.GlobalAveragePooling2D() # self.fc = layers.Dense(num_classes) def",
"2] super(ResNet, self).__init__() self.stem = Sequential([layers.Conv2D(64, (3, 3), strides=(1, 1)),",
"layers.Activation('relu') self.dpout = layers.Dropout(dropout_rate) self.layer1 = self.build_resblock(filters_num[5], layer_dims[0]) # filters_num",
"strides=1, padding='same', kernel_regularizer=regularizers.l2(5e-4), use_bias=True) def call(self, inputs): avg = self.avg(inputs)",
"= layers.Conv3D(filters_num[1], kernel_size=(5, 5, 3), padding='same', kernel_initializer='he_normal', # kernel_regularizer=regularizers.l2(0.0001))(conv11_relu) #",
"layers.BatchNormalization()(conv4) conv4_relu = layers.Activation('relu')(conv4_bn) # conv4_relu = Dropout(0.5)(conv4_relu) # conv4_relu",
"= tf.nn.sigmoid(out) return out ############################### 空间注意力机制 ############################### class SpatialAttention(layers.Layer): def",
"self.max= layers.GlobalMaxPooling2D() self.conv1 = layers.Conv2D(in_planes//ratio, kernel_size=1, strides=1, padding='same', kernel_regularizer=regularizers.l2(5e-4), use_bias=True,",
"conv33_relu_reshape]) ######################################### conv4 = layers.Conv2D(filters_num[3], kernel_size=(3, 3), padding='same',kernel_regularizer=regularizers.l2(0.0001))(conv3_relu_reshape) # filters_num",
"stride=2) # filters_num = 256 self.layer4 = self.build_resblock(filters_num[8], layer_dims[3], stride=2)",
"conv1_relu = tf.keras.layers.MaxPooling3D(pool_size=(2, 2, 2), strides=(1, 1, 1), padding='same')(conv1_relu) #",
"input_layer = Input(input_shape) # conv1 = layers.Conv3D(filters_num[0], kernel_size=(3, 3, 7),",
"layers.Conv3D(filters_num[0], kernel_size=(5, 5, 3), padding='same', # kernel_initializer='he_normal', kernel_regularizer=regularizers.l2(0.0001))(input_layer_up) # conv11_bn",
"# [b, c] # x = self.avgpool(x) # [b, 100]",
"conv333_bn = layers.BatchNormalization()(conv333) # conv333_relu = layers.Activation('relu')(conv333_bn) # # conv333_relu_reshape",
"conv4_relu = tf.keras.layers.MaxPooling2D(pool_size=(2, 2), strides=(1, 1), padding='same')(conv4_relu) # conv4_relu =",
"call(self, inputs, training=None): # x = self.stem(inputs) x1 = self.layer1(inputs)",
"class ResNet_block(keras.Model): def __init__(self, layer_dims,filters_num): # [2, 2, 2, 2]",
"self.bn1(out) out = self.relu1(out) out = self.conv2(out) out = self.bn2(out)",
"16 conv2_bn = layers.BatchNormalization()(conv2) conv2_relu = layers.Activation('relu')(conv2_bn) # conv2_relu =",
"# # self.stem = Sequential([layers.Conv2D(64, (3, 3), strides=(1, 1)), #",
"conv3_relu.shape[4]))(conv333_relu) #################concatenate######################## # conv33333_relu_reshape = Concatenate(axis=-1)([conv3_relu_reshape, conv33_relu_reshape]) ######################################### conv4 =",
"filter_num, blocks, stride=1): res_blocks = Sequential() # may down sample",
"res_blocks def network_up(input_layer_up,filters_num,dropout_rate,Block_res): # input_layer = Input(input_shape) # conv1 =",
"layers.BatchNormalization() self.relu1 = layers.Activation('relu') self.conv2 = layers.Conv3D(filters_num[1],kernel_size=(3,3,5),padding='same') # filters_num =",
"strides=stride, padding='same',kernel_regularizer=regularizers.l2(0.0001)) #kernel_initializer='he_normal', self.bn1 = layers.BatchNormalization() self.relu = layers.Activation('relu') self.conv2",
"定义一个3x3卷积!kernel_initializer='he_normal','glorot_normal' from tensorflow.python.keras.layers import Concatenate def regularized_padded_conv(*args, **kwargs): return layers.Conv2D(*args,",
"= layers.GlobalAveragePooling2D() self.fc2 = layers.Dense(filters_num[7],activation='relu') self.fc3 = layers.Dense(filters_num[6],activation='relu') self.fc4 =",
"padding='same')(conv4_relu) conv5 = layers.Conv2D(filters_num[4], kernel_size=(3, 3), padding='same',kernel_regularizer=regularizers.l2(0.0001))(conv4_relu) # filters_num =",
"out = self.conv2(out) out = self.bn2(out) out = self.relu2(out) out",
"= self.fc4(x) return x def build_resblock(self, filter_num, blocks, stride=1): res_blocks",
"# filters_num = 16 conv2 = layers.Conv3D(filters_num[1], kernel_size=(3, 3, 3),padding='same',kernel_regularizer=regularizers.l2(0.0001))(conv1_relu)",
"layer2 = build_resblock(filters_num[6], layer_dims[1], stride=2) # filters_num = 128 #",
"return x2,x4 def build_resblock(self, filter_num, blocks, stride=1): res_blocks = Sequential()",
"layer_dims[1], stride=1) self.layer3 = self.build_resblock(256, layer_dims[2], stride=1) self.layer4 = self.build_resblock(512,",
"__init__(self, kernel_size=7): super(SpatialAttention, self).__init__() self.conv1 = regularized_padded_conv(1, kernel_size=kernel_size, strides=1, activation=tf.nn.sigmoid)",
"res_blocks.add(self.BasicBlock1) for _ in range(1, blocks): res_blocks.add(self.BasicBlock2) return res_blocks def",
"padding='same', # kernel_initializer='he_normal', kernel_regularizer=regularizers.l2(0.0001))(input_layer_up) # conv11_bn = layers.BatchNormalization()(conv11) # conv11_relu",
"1), padding='same')(conv5_relu) # conv5_relu = tf.keras.layers.MaxPooling3D(pool_size=(2, 2, 2), strides=(1, 1,",
"# filters_num = 32 self.bn3 = layers.BatchNormalization() self.relu3 = layers.Activation('relu')",
"5, 3), padding='same', kernel_initializer='he_normal', # kernel_regularizer=regularizers.l2(0.0001))(conv11_relu) # filters_num = 16",
"= tf.stack([avg_out, max_out], axis=3) # 创建一个维度,拼接到一起concat。 out = self.conv1(out) return",
"# conv1 = layers.Conv3D(filters_num[0], kernel_size=(3, 3, 3),padding='same',kernel_initializer='he_normal',kernel_regularizer=regularizers.l2(0.0001))(input_layer_up) # filters_num =",
"3, 5), padding='same')(conv1_relu) # filters_num = 16 conv2 = layers.Conv3D(filters_num[1],",
"2), strides=(1, 1, 1), padding='same')(conv2_relu) conv3 = layers.Conv3D(filters_num[2], kernel_size=(3, 3,",
"layers.Conv2D(in_planes, kernel_size=1, strides=1, padding='same', kernel_regularizer=regularizers.l2(5e-4), use_bias=True) def call(self, inputs): avg",
"BasicBlock(layers.Layer): def __init__(self, filter_num, stride=1): super(BasicBlock, self).__init__() # self.conv1 =",
"Dropout(0.5)(conv3_relu_reshape) ##################第二个尺度######################### # conv11 = layers.Conv3D(filters_num[0], kernel_size=(5, 5, 3), padding='same',",
"return res_blocks def build_resblock(self, filter_num, blocks, stride=1): res_blocks = Sequential()",
"= 64 self.layer2 = self.build_resblock(filters_num[1], layer_dims[1], stride=1) # filters_num =",
"num_classes=16): # [2, 2, 2, 2] super(ResNet, self).__init__() self.stem =",
"# from tensorflow.keras import * # 定义一个3x3卷积!kernel_initializer='he_normal','glorot_normal' from tensorflow.python.keras.layers import",
"h, w], # self.fc1 = layers.Flatten() self.avgpool = layers.GlobalAveragePooling2D() self.fc2",
"# conv2_relu = tf.keras.layers.MaxPooling3D(pool_size=(2, 2, 2), strides=(1, 1, 1), padding='same')(conv2_relu)",
"[b, 512, h, w], # self.avgpool = layers.GlobalAveragePooling2D() # self.fc",
"Dropout(0.5)(conv4_relu) # conv4_relu = tf.keras.layers.MaxPooling2D(pool_size=(2, 2), strides=(1, 1), padding='same')(conv4_relu) #",
"1), padding='same')(conv4_relu) # conv4_relu = tf.keras.layers.MaxPooling3D(pool_size=(2, 2, 2), strides=(1, 1,",
"self.conv2 = layers.Conv2D(filter_num, (3, 3), strides=1, padding='same',kernel_regularizer=regularizers.l2(0.0001)) self.bn2 = layers.BatchNormalization()",
"conv22_bn = layers.BatchNormalization()(conv22) # conv22_relu = layers.Activation('relu')(conv22_bn) # # conv33",
"= 32 conv3_bn = layers.BatchNormalization()(conv3) conv3_relu = layers.Activation('relu')(conv3_bn) # conv3_relu",
"1)), layers.BatchNormalization(), layers.Activation('relu'), layers.MaxPool2D(pool_size=(2, 2), strides=(1, 1), padding='same') ]) self.layer1",
"max = layers.Reshape((1, 1, max.shape[1]))(max) # shape (None, 1, 1",
"= layers.Conv2D(filter_num, (3, 3), strides=stride, padding='same', kernel_initializer='he_normal',kernel_regularizer=keras.regularizers.l2(5e-4)) self.conv1 = layers.Conv2D(filter_num,",
"layers.Conv3D(filters_num[1],kernel_size=(3,3,5),padding='same') # filters_num = 16 self.bn2 = layers.BatchNormalization() self.relu2 =",
"layers.BatchNormalization(), layers.Activation('relu'), layers.MaxPool2D(pool_size=(2, 2), strides=(1, 1), padding='same') ]) self.layer1 =",
"Dropout # from tensorflow.keras import * # 定义一个3x3卷积!kernel_initializer='he_normal','glorot_normal' from tensorflow.python.keras.layers",
"= 32 # conv33_bn = layers.BatchNormalization()(conv33) # conv33_relu = layers.Activation('relu')(conv33_bn)",
"tensorflow import keras from tensorflow.keras import layers, Sequential,regularizers from tensorflow.keras.layers",
"conv333_relu = layers.Activation('relu')(conv333_bn) # # conv333_relu_reshape = layers.Reshape( # (conv3_relu.shape[1],",
"self.conv3(out) out = self.bn3(out) out = self.relu3(out) # reshape out",
"= 8 # conv1 = layers.Conv3D(filters_num[0], kernel_size=(3, 3, 3),padding='same',kernel_initializer='he_normal',kernel_regularizer=regularizers.l2(0.0001))(input_layer_up) #",
"def build_resblock(self, filter_num, blocks, stride=1): res_blocks = Sequential() # may",
"3, 3),padding='same',kernel_initializer='he_normal',kernel_regularizer=regularizers.l2(0.0001))(input_layer_up) # filters_num = 8 conv1 = layers.Conv3D(filters_num[0], kernel_size=(3,",
"layer_dims[2], stride=2) # filters_num = 256 # layer4 = build_resblock(filters_num[8],",
"8 self.bn1 = layers.BatchNormalization() self.relu1 = layers.Activation('relu') self.conv2 = layers.Conv3D(filters_num[1],kernel_size=(3,3,5),padding='same')",
"32 self.bn3 = layers.BatchNormalization() self.relu3 = layers.Activation('relu') # self.reshape =",
"training=None): # [b, h, w, c] out = self.conv1(inputs) out",
"= layers.Activation('relu')(conv4_bn) # conv4_relu = Dropout(0.5)(conv4_relu) # conv4_relu = tf.keras.layers.MaxPooling2D(pool_size=(2,",
"layers.Conv2D(*args, **kwargs, padding='same', use_bias=False, kernel_initializer='he_normal', kernel_regularizer=regularizers.l2(5e-4)) ############################### 通道注意力机制 ############################### class",
"filters_num = 256 self.layer4 = self.build_resblock(filters_num[8], layer_dims[3], stride=2) # filters_num",
"self.conv2 = layers.Conv2D(in_planes, kernel_size=1, strides=1, padding='same', kernel_regularizer=regularizers.l2(5e-4), use_bias=True) def call(self,",
"conv3_relu = Dropout(0.5)(conv3_relu) # conv3_relu = tf.keras.layers.MaxPooling3D(pool_size=(2, 2, 2), strides=(1,",
"filters_num = 16 conv2_bn = layers.BatchNormalization()(conv2) conv2_relu = layers.Activation('relu')(conv2_bn) #",
"= avg_out + max_out out = tf.nn.sigmoid(out) return out ###############################",
"max_out out = tf.nn.sigmoid(out) return out ############################### 空间注意力机制 ############################### class",
"= 128 self.layer3 = self.build_resblock(filters_num[7], layer_dims[2], stride=2) # filters_num =",
"stride): super(build_resblock, self).__init__() self.BasicBlock1 = BasicBlock(filter_num, stride) self.BasicBlock2 = BasicBlock(filter_num,",
"sample res_blocks.add(BasicBlock(filter_num, stride)) for _ in range(1, blocks): res_blocks.add(BasicBlock(filter_num, stride=1))",
"= tf.keras.layers.MaxPooling3D(pool_size=(2, 2, 2), strides=(1, 1, 1), padding='same')(conv2_relu) conv3 =",
"x = self.layer3(x) x = self.layer4(x) # [b, c] x",
"layer_dims[2], stride=1) # filters_num = 256 self.layer4 = self.build_resblock(filters_num[3], layer_dims[3],",
"self.conv1(inputs) out = self.bn1(out) out = self.relu(out) out = self.conv2(out)",
"kernel_size=1, strides=1, padding='same', kernel_regularizer=regularizers.l2(5e-4), use_bias=True) def call(self, inputs): avg =",
"_ in range(1, blocks): res_blocks.add(BasicBlock(filter_num, stride=1)) return res_blocks ###################################### class",
"super(pp2_model, self).__init__() self.conv1 = layers.Conv3D(filters_num[0],kernel_size=(3,3,7),padding='same') # filters_num = 8 self.bn1",
"layers.Conv2D(filters_num[3], kernel_size=(3, 3), padding='same') # filters_num = 64 self.bn4 =",
"1 feature) avg_out = self.conv2(self.conv1(avg)) max_out = self.conv2(self.conv1(max)) out =",
"16 # conv22_bn = layers.BatchNormalization()(conv22) # conv22_relu = layers.Activation('relu')(conv22_bn) #",
"= Sequential() # may down sample res_blocks.add(BasicBlock(filter_num, stride)) for _",
"strides=(1, 1, 1), padding='same')(conv5_relu) # conv5_dpout = layers.Dropout(dropout_rate)(conv5) # conv5_reshape",
"x = self.fc(x) return x2,x4 def build_resblock(self, filter_num, blocks, stride=1):",
"def resnet18(): return ResNet([2, 2, 2, 2],num_classes=9) def resnet34(): return",
"in range(1, blocks): res_blocks.add(self.BasicBlock2) return res_blocks def build_resblock(self, filter_num, blocks,",
"= layers.BatchNormalization() self.relu4 = layers.Activation('relu') self.conv5 = layers.Conv2D(filters_num[4], kernel_size=(3, 3),",
"tf.keras.layers.MaxPooling3D(pool_size=(2, 2, 2), strides=(1, 1, 1), padding='same')(conv5_relu) # conv5_dpout =",
"pp2_model(keras.Model): def __init__(self,filters_num,layer_dims,num_classes,dropout_rate): super(pp2_model, self).__init__() self.conv1 = layers.Conv3D(filters_num[0],kernel_size=(3,3,7),padding='same') # filters_num",
"= layers.Conv2D(filter_num, (3, 3), strides=stride, padding='same',kernel_regularizer=regularizers.l2(0.0001)) #kernel_initializer='he_normal', self.bn1 = layers.BatchNormalization()",
"super(ResNet_block, self).__init__() # # self.stem = Sequential([layers.Conv2D(64, (3, 3), strides=(1,",
"1), padding='same') ]) self.layer1 = self.build_resblock(64, layer_dims[0]) self.layer2 = self.build_resblock(128,",
"self.ca = ChannelAttention(filter_num) self.sa = SpatialAttention() if stride != 1:",
"c] x = self.avgpool(x) # [b, 100] x = self.fc2(x)",
"# kernel_initializer='he_normal', kernel_regularizer=regularizers.l2(0.0001))(input_layer_up) # conv11_bn = layers.BatchNormalization()(conv11) # conv11_relu =",
"= 8 conv1 = layers.Conv3D(filters_num[0], kernel_size=(3, 3, 3), padding='same', kernel_regularizer=regularizers.l2(0.0001))(input_layer_up)",
"padding='same', kernel_initializer='he_normal', # kernel_regularizer=regularizers.l2(0.0001))(conv222_relu) # filters_num = 32 # conv333_bn",
"self.avg= layers.GlobalAveragePooling2D() self.max= layers.GlobalMaxPooling2D() self.conv1 = layers.Conv2D(in_planes//ratio, kernel_size=1, strides=1, padding='same',",
"layers.GlobalAveragePooling2D() self.max= layers.GlobalMaxPooling2D() self.conv1 = layers.Conv2D(in_planes//ratio, kernel_size=1, strides=1, padding='same', kernel_regularizer=regularizers.l2(5e-4),",
"w, c] out = self.conv1(inputs) out = self.bn1(out) out =",
"self.fc1 = layers.Flatten() self.avgpool = layers.GlobalAveragePooling2D() self.fc2 = layers.Dense(filters_num[7],activation='relu') self.fc3",
"kernel_size=(3, 3, 3),padding='same',kernel_regularizer=regularizers.l2(0.0001))(conv2_relu) # filters_num = 32 conv3_bn = layers.BatchNormalization()(conv3)",
"= self.layer1(inputs) x2 = self.layer2(x1) x3 = self.layer3(x2) x4 =",
"filter_num, stride): super(build_resblock, self).__init__() self.BasicBlock1 = BasicBlock(filter_num, stride) self.BasicBlock2 =",
"conv3_relu = layers.Activation('relu')(conv3_bn) # conv3_relu = Dropout(0.5)(conv3_relu) # conv3_relu =",
"build_resblock(self, filter_num, blocks, stride=1): res_blocks = Sequential() # may down",
"filters_num = 8 self.bn1 = layers.BatchNormalization() self.relu1 = layers.Activation('relu') self.conv2",
"layers.Reshape((1, 1, max.shape[1]))(max) # shape (None, 1, 1 feature) avg_out",
"kernel_size=(5, 5, 3), padding='same', # kernel_initializer='he_normal', kernel_regularizer=regularizers.l2(0.0001))(input_layer_up) # conv11_bn =",
"= self.bn2(out) out = self.relu2(out) out = self.conv3(out) out =",
"layers.Dropout(dropout_rate)(conv5) # conv5_reshape = layers.Reshape((conv5_dpout.shape[1],conv5_dpout.shape[2],conv5_dpout.shape[3]))(conv5_dpout) outputs2,outputs4 = Block_res(conv5_relu) return conv5,outputs2,outputs4",
"self.bn4(out) out = self.relu4(out) out = self.dpout(out) out = self.conv5(out)",
"padding='same',kernel_regularizer=regularizers.l2(0.0001))(conv3_relu_reshape) # filters_num = 64 conv4_bn = layers.BatchNormalization()(conv4) conv4_relu =",
"512 # output: [b, 512, h, w], # self.fc1 =",
"conv2_relu = layers.Activation('relu')(conv2_bn) # conv2_relu = Dropout(0.5)(conv2_relu) # conv2_relu =",
"x4 = self.layer4(x3) # [b, c] # x = self.avgpool(x)",
"= self.relu3(out) # reshape out = layers.Reshape((out.shape[1],out.shape[2],out.shape[3] * out.shape[4]))(out) out",
"filters_num = 8 conv1 = layers.Conv3D(filters_num[0], kernel_size=(3, 3, 3), padding='same',",
"self.relu5(out) x = self.layer1(out) x = self.layer2(x) x = self.layer3(x)",
"stride=1) self.layer3 = self.build_resblock(256, layer_dims[2], stride=1) self.layer4 = self.build_resblock(512, layer_dims[3],",
"layers.Dense(filters_num[6],activation='relu') self.fc4 = layers.Dense(num_classes) def call(self,inputs,training=None): out = self.conv1(inputs) out",
"layers.Dense(num_classes) def call(self, inputs, training=None): # x = self.stem(inputs) x1",
"kernel_regularizer=regularizers.l2(5e-4), use_bias=True) def call(self, inputs): avg = self.avg(inputs) max =",
"Sequential([layers.Conv2D(64, (3, 3), strides=(1, 1)), layers.BatchNormalization(), layers.Activation('relu'), layers.MaxPool2D(pool_size=(2, 2), strides=(1,",
"###################################### class build_resblock(keras.Model): def __init__(self, filter_num, stride): super(build_resblock, self).__init__() self.BasicBlock1",
"x2,x4 def build_resblock(self, filter_num, blocks, stride=1): res_blocks = Sequential() #",
"6, 3],num_classes=9) ########################### pp2主模型 ######################################## class pp2_model(keras.Model): def __init__(self,filters_num,layer_dims,num_classes,dropout_rate): super(pp2_model,",
"h, w], self.avgpool = layers.GlobalAveragePooling2D() self.fc = layers.Dense(num_classes) def call(self,",
"out = self.conv1(out) return out class BasicBlock(layers.Layer): def __init__(self, filter_num,",
"res_blocks.add(BasicBlock(filter_num, stride)) for _ in range(1, blocks): res_blocks.add(BasicBlock(filter_num, stride=1)) return",
"self.build_resblock(filters_num[1], layer_dims[1], stride=1) # filters_num = 128 self.layer3 = self.build_resblock(filters_num[2],",
"resnet34(): return ResNet([3, 4, 6, 3],num_classes=9) ########################### pp2主模型 ######################################## class",
"tf from tensorflow import keras from tensorflow.keras import layers, Sequential,regularizers",
"= layers.Dense(num_classes) def call(self, inputs, training=None): x = self.stem(inputs) x",
"out = self.bn2(out) ############################### 注意力机制 ############################### out = self.ca(out) *",
"= self.layer1(x) x = self.layer2(x) x = self.layer3(x) x =",
"# conv5_reshape = layers.Reshape((conv5_dpout.shape[1],conv5_dpout.shape[2],conv5_dpout.shape[3]))(conv5_dpout) outputs2,outputs4 = Block_res(conv5_relu) return conv5,outputs2,outputs4 #",
"filters_num = 16 # conv22 = layers.Conv3D(filters_num[1], kernel_size=(5, 5, 3),",
"= layers.BatchNormalization()(conv33) # conv33_relu = layers.Activation('relu')(conv33_bn) # # conv33_relu_reshape =",
"= self.bn1(out) out = self.relu(out) out = self.conv2(out) out =",
"range(1, blocks): res_blocks.add(BasicBlock(filter_num, stride=1)) return res_blocks ###################################### class ResNet(keras.Model): def",
"conv1_relu = Dropout(0.5)(conv1_relu) # conv1_relu = tf.keras.layers.MaxPooling3D(pool_size=(2, 2, 2), strides=(1,",
"from tensorflow.python.keras.layers import Concatenate def regularized_padded_conv(*args, **kwargs): return layers.Conv2D(*args, **kwargs,",
"padding='same', use_bias=False, kernel_initializer='he_normal', kernel_regularizer=regularizers.l2(5e-4)) ############################### 通道注意力机制 ############################### class ChannelAttention(layers.Layer): def",
"64 self.layer2 = self.build_resblock(filters_num[1], layer_dims[1], stride=1) # filters_num = 128",
"layers.BatchNormalization()(conv3) conv3_relu = layers.Activation('relu')(conv3_bn) # conv3_relu = Dropout(0.5)(conv3_relu) # conv3_relu",
"kernel_size=(3, 3), padding='same') # filters_num = 64 self.bn4 = layers.BatchNormalization()",
"# reshape out = layers.Reshape((out.shape[1],out.shape[2],out.shape[3] * out.shape[4]))(out) out = self.conv4(out)",
"self.avgpool = layers.GlobalAveragePooling2D() # self.fc = layers.Dense(num_classes) def call(self, inputs,",
"conv3_relu.shape[4]))(conv33_relu) #################################################### # conv111 = layers.Conv3D(filters_num[0], kernel_size=(7, 7, 3), padding='same',",
"# kernel_regularizer=regularizers.l2(0.0001))(conv222_relu) # filters_num = 32 # conv333_bn = layers.BatchNormalization()(conv333)",
"layers.Activation('relu') # self.reshape = layers.Reshape() self.conv4 = layers.Conv2D(filters_num[3], kernel_size=(3, 3),",
"self.downsample(inputs) output = layers.add([out, identity]) output = tf.nn.relu(output) return output",
"2, 2, 2],num_classes=9) def resnet34(): return ResNet([3, 4, 6, 3],num_classes=9)",
"# # conv2 = layers.Conv3D(filters_num[1], kernel_size=(3, 3, 5), padding='same')(conv1_relu) #",
"5), padding='same')(conv1_relu) # filters_num = 16 # conv22 = layers.Conv3D(filters_num[1],",
"= 128 self.layer3 = self.build_resblock(filters_num[2], layer_dims[2], stride=1) # filters_num =",
"layers.Activation('relu') self.conv3 = layers.Conv3D(filters_num[2], kernel_size=(3, 3, 3), padding='same') # filters_num",
"self.bn1 = layers.BatchNormalization() self.relu1 = layers.Activation('relu') self.conv2 = layers.Conv3D(filters_num[1],kernel_size=(3,3,5),padding='same') #",
"import * import tensorflow as tf from tensorflow import keras",
"stride=1) # filters_num = 512 # output: [b, 512, h,",
"= self.layer1(out) x = self.layer2(x) x = self.layer3(x) x =",
"layers.Activation('relu')(conv11_bn) # # # conv2 = layers.Conv3D(filters_num[1], kernel_size=(3, 3, 5),",
"def __init__(self, filter_num, stride=1): super(BasicBlock, self).__init__() # self.conv1 = layers.Conv2D(filter_num,",
"x1 = self.layer1(inputs) x2 = self.layer2(x1) x3 = self.layer3(x2) x4",
"import * # 定义一个3x3卷积!kernel_initializer='he_normal','glorot_normal' from tensorflow.python.keras.layers import Concatenate def regularized_padded_conv(*args,",
"= layers.Conv2D(filters_num[3], kernel_size=(3, 3), padding='same') # filters_num = 64 self.bn4",
"layers.BatchNormalization() self.relu3 = layers.Activation('relu') # self.reshape = layers.Reshape() self.conv4 =",
"filters_num = 32 # conv33_bn = layers.BatchNormalization()(conv33) # conv33_relu =",
"tensorflow.keras.layers import Dropout # from tensorflow.keras import * # 定义一个3x3卷积!kernel_initializer='he_normal','glorot_normal'",
"kernel_regularizer=regularizers.l2(0.0001))(input_layer_up) #kernel_initializer='he_normal', # conv_layer1m = tf.keras.layers.MaxPooling3D(pool_size=(1, 1, 1),padding='same')(conv1) # conv_layer1g",
"filters_num = 256 self.layer4 = self.build_resblock(filters_num[3], layer_dims[3], stride=1) # filters_num",
"(3, 3), strides=stride, padding='same',kernel_regularizer=regularizers.l2(0.0001)) #kernel_initializer='he_normal', self.bn1 = layers.BatchNormalization() self.relu =",
"= Sequential() res_blocks.add(self.BasicBlock1) for _ in range(1, blocks): res_blocks.add(self.BasicBlock2) return",
"= layers.Reshape((conv5_dpout.shape[1],conv5_dpout.shape[2],conv5_dpout.shape[3]))(conv5_dpout) outputs2,outputs4 = Block_res(conv5_relu) return conv5,outputs2,outputs4 # layer1 =",
"layers.BatchNormalization()(conv22) # conv22_relu = layers.Activation('relu')(conv22_bn) # # conv33 = layers.Conv3D(filters_num[2],",
"stride)) for _ in range(1, blocks): res_blocks.add(BasicBlock(filter_num, stride=1)) return res_blocks",
"out = self.relu1(out) out = self.conv2(out) out = self.bn2(out) out",
"padding='same')(conv5_relu) # conv5_dpout = layers.Dropout(dropout_rate)(conv5) # conv5_reshape = layers.Reshape((conv5_dpout.shape[1],conv5_dpout.shape[2],conv5_dpout.shape[3]))(conv5_dpout) outputs2,outputs4",
"2, 2, 2] super(ResNet_block, self).__init__() # # self.stem = Sequential([layers.Conv2D(64,",
"self.bn2 = layers.BatchNormalization() ############################### 注意力机制 ############################### self.ca = ChannelAttention(filter_num) self.sa",
"# conv5_relu = tf.keras.layers.MaxPooling3D(pool_size=(2, 2, 2), strides=(1, 1, 1), padding='same')(conv5_relu)",
"axis=3) # 创建一个维度,拼接到一起concat。 out = self.conv1(out) return out class BasicBlock(layers.Layer):",
"import Dropout # from tensorflow.keras import * # 定义一个3x3卷积!kernel_initializer='he_normal','glorot_normal' from",
"layers.Activation('relu')(conv33_bn) # # conv33_relu_reshape = layers.Reshape( # (conv3_relu.shape[1], conv3_relu.shape[2], conv3_relu.shape[3]",
"self.build_resblock(128, layer_dims[1], stride=1) self.layer3 = self.build_resblock(256, layer_dims[2], stride=1) self.layer4 =",
"kernel_size=(3, 3, 3),padding='same',kernel_regularizer=regularizers.l2(0.0001))(conv1_relu) # filters_num = 16 conv2_bn = layers.BatchNormalization()(conv2)",
"stride=1)) return res_blocks ###################################### class ResNet(keras.Model): def __init__(self, layer_dims, num_classes=16):",
"avg.shape[1]))(avg) # shape (None, 1, 1 feature) max = layers.Reshape((1,",
"self.relu3 = layers.Activation('relu') # self.reshape = layers.Reshape() self.conv4 = layers.Conv2D(filters_num[3],",
"tf.nn.relu(output) return output ###################################### class build_resblock(keras.Model): def __init__(self, filter_num, stride):",
"conv_layer1m = tf.keras.layers.MaxPooling3D(pool_size=(1, 1, 1),padding='same')(conv1) # conv_layer1g = tf.keras.layers.GlobalMaxPooling3D()(conv1) conv1_bn",
"conv3_relu.shape[2], conv3_relu.shape[3] * conv3_relu.shape[4]))(conv333_relu) #################concatenate######################## # conv33333_relu_reshape = Concatenate(axis=-1)([conv3_relu_reshape, conv33_relu_reshape])",
"3), padding='same',kernel_regularizer=regularizers.l2(0.0001))(conv3_relu_reshape) # filters_num = 64 conv4_bn = layers.BatchNormalization()(conv4) conv4_relu",
"layers.BatchNormalization()(conv333) # conv333_relu = layers.Activation('relu')(conv333_bn) # # conv333_relu_reshape = layers.Reshape(",
"tf.keras.layers.MaxPooling3D(pool_size=(2, 2, 2), strides=(1, 1, 1), padding='same')(conv4_relu) conv5 = layers.Conv2D(filters_num[4],",
"layer_dims[0]) self.layer2 = self.build_resblock(128, layer_dims[1], stride=1) self.layer3 = self.build_resblock(256, layer_dims[2],",
"conv3_relu.shape[3] * conv3_relu.shape[4]))(conv33_relu) #################################################### # conv111 = layers.Conv3D(filters_num[0], kernel_size=(7, 7,",
"layers.Conv3D(filters_num[2], kernel_size=(5, 5, 3), padding='same', kernel_initializer='he_normal', # kernel_regularizer=regularizers.l2(0.0001))(conv22_relu) # filters_num",
"Concatenate(axis=-1)([conv3_relu_reshape, conv33_relu_reshape]) ######################################### conv4 = layers.Conv2D(filters_num[3], kernel_size=(3, 3), padding='same',kernel_regularizer=regularizers.l2(0.0001))(conv3_relu_reshape) #",
"# conv333 = layers.Conv3D(filters_num[2], kernel_size=(7, 7, 3), padding='same', kernel_initializer='he_normal', #",
"# [b, 100] # x = self.fc(x) return x2,x4 def",
"= 64 self.bn4 = layers.BatchNormalization() self.relu4 = layers.Activation('relu') self.conv5 =",
"创建一个维度,拼接到一起concat。 out = self.conv1(out) return out class BasicBlock(layers.Layer): def __init__(self,",
"ResNet_block(keras.Model): def __init__(self, layer_dims,filters_num): # [2, 2, 2, 2] super(ResNet_block,",
"self.relu4(out) out = self.dpout(out) out = self.conv5(out) out = self.bn5(out)",
"= Sequential() self.downsample.add(layers.Conv2D(filter_num, (1, 1), strides=stride)) else: self.downsample = lambda",
"padding='same', kernel_initializer='he_normal', # kernel_regularizer=regularizers.l2(0.0001))(conv111_relu) # filters_num = 16 # conv222_bn",
"= layers.Dense(num_classes) def call(self,inputs,training=None): out = self.conv1(inputs) out = self.bn1(out)",
"conv1 = layers.Conv3D(filters_num[0], kernel_size=(3, 3, 3),padding='same',kernel_initializer='he_normal',kernel_regularizer=regularizers.l2(0.0001))(input_layer_up) # filters_num = 8",
"self.conv4(out) out = self.bn4(out) out = self.relu4(out) out = self.dpout(out)",
"kernel_size=(7, 7, 3), padding='same', kernel_initializer='he_normal', # kernel_regularizer=regularizers.l2(0.0001))(conv222_relu) # filters_num =",
"= self.avgpool(x) # [b, 100] x = self.fc(x) return x",
"kernel_initializer='he_normal', # kernel_regularizer=regularizers.l2(0.0001))(conv22_relu) # filters_num = 32 # conv33_bn =",
"self.layer3(x) x = self.layer4(x) # [b, c] x = self.avgpool(x)",
"= self.build_resblock(128, layer_dims[1], stride=1) self.layer3 = self.build_resblock(256, layer_dims[2], stride=1) self.layer4",
"= layers.Conv3D(filters_num[0], kernel_size=(7, 7, 3), padding='same', # kernel_initializer='he_normal', kernel_regularizer=regularizers.l2(0.0001))(input_layer_up) #",
"stride=1)) return res_blocks def network_up(input_layer_up,filters_num,dropout_rate,Block_res): # input_layer = Input(input_shape) #",
"3), padding='same', # kernel_initializer='he_normal', kernel_regularizer=regularizers.l2(0.0001))(input_layer_up) # conv111_bn = layers.BatchNormalization()(conv111) #",
"# filters_num = 256 self.layer4 = self.build_resblock(filters_num[3], layer_dims[3], stride=1) #",
"out = self.relu5(out) x = self.layer1(out) x = self.layer2(x) x",
"# filters_num = ** self.bn5 = layers.BatchNormalization() self.relu5 = layers.Activation('relu')",
"filters_num = 64 conv4_bn = layers.BatchNormalization()(conv4) conv4_relu = layers.Activation('relu')(conv4_bn) #",
"= build_resblock(filters_num[7], layer_dims[2], stride=2) # filters_num = 256 # layer4",
"res_blocks.add(BasicBlock(filter_num, stride=1)) return res_blocks class ResNet_block(keras.Model): def __init__(self, layer_dims,filters_num): #",
"output: [b, 512, h, w], self.avgpool = layers.GlobalAveragePooling2D() self.fc =",
"#kernel_initializer='he_normal', # conv_layer1m = tf.keras.layers.MaxPooling3D(pool_size=(1, 1, 1),padding='same')(conv1) # conv_layer1g =",
"conv5_relu = Dropout(0.5)(conv5_relu) # conv5_relu = tf.keras.layers.MaxPooling2D(pool_size=(2, 2), strides=(1, 1),",
"x = self.fc3(x) x = self.fc4(x) return x def build_resblock(self,",
"self.conv5 = layers.Conv2D(filters_num[4], kernel_size=(3, 3), padding='same') # filters_num = **",
"return out class BasicBlock(layers.Layer): def __init__(self, filter_num, stride=1): super(BasicBlock, self).__init__()",
"self.downsample = lambda x:x def call(self, inputs, training=None): # [b,",
"2), strides=(1, 1), padding='same') # ]) self.layer1 = self.build_resblock(filters_num[0], layer_dims[0])",
"# conv_layer1g = tf.keras.layers.GlobalMaxPooling3D()(conv1) conv1_bn = layers.BatchNormalization()(conv1) conv1_relu = layers.Activation('relu')(conv1_bn)",
"self.layer3 = self.build_resblock(256, layer_dims[2], stride=1) self.layer4 = self.build_resblock(512, layer_dims[3], stride=1)",
"padding='same')(conv2_relu) conv3 = layers.Conv3D(filters_num[2], kernel_size=(3, 3, 3),padding='same',kernel_regularizer=regularizers.l2(0.0001))(conv2_relu) # filters_num =",
"layer_dims[3], stride=2) # filters_num = 512 # output: [b, 512,",
"# filters_num = 128 # layer3 = build_resblock(filters_num[7], layer_dims[2], stride=2)",
"self.layer2 = self.build_resblock(filters_num[1], layer_dims[1], stride=1) # filters_num = 128 self.layer3",
"= self.relu2(out) out = self.conv3(out) out = self.bn3(out) out =",
"# [b, h, w, c] out = self.conv1(inputs) out =",
"import tensorflow as tf from tensorflow import keras from tensorflow.keras",
"def call(self, inputs, training=None): # [b, h, w, c] out",
"# may down sample res_blocks.add(BasicBlock(filter_num, stride)) for _ in range(1,",
"= layers.BatchNormalization() self.relu = layers.Activation('relu') self.conv2 = layers.Conv2D(filter_num, (3, 3),",
"kernel_size=(3, 3, 5), padding='same')(conv1_relu) # filters_num = 16 # conv22",
"7, 3), padding='same', kernel_initializer='he_normal', # kernel_regularizer=regularizers.l2(0.0001))(conv222_relu) # filters_num = 32",
"= layers.Flatten() self.avgpool = layers.GlobalAveragePooling2D() self.fc2 = layers.Dense(filters_num[7],activation='relu') self.fc3 =",
"def __init__(self, layer_dims, num_classes=16): # [2, 2, 2, 2] super(ResNet,",
"2, 2],num_classes=9) def resnet34(): return ResNet([3, 4, 6, 3],num_classes=9) ###########################",
"self.bn2(out) out = self.relu2(out) out = self.conv3(out) out = self.bn3(out)",
"layer_dims[2], stride=1) self.layer4 = self.build_resblock(512, layer_dims[3], stride=1) # output: [b,",
"output: [b, 512, h, w], # self.avgpool = layers.GlobalAveragePooling2D() #",
"layer3 = build_resblock(filters_num[7], layer_dims[2], stride=2) # filters_num = 256 #",
"kernel_size=(5, 5, 3), padding='same', kernel_initializer='he_normal', # kernel_regularizer=regularizers.l2(0.0001))(conv11_relu) # filters_num =",
"feature) avg_out = self.conv2(self.conv1(avg)) max_out = self.conv2(self.conv1(max)) out = avg_out",
"conv3_relu_reshape = Dropout(0.5)(conv3_relu_reshape) ##################第二个尺度######################### # conv11 = layers.Conv3D(filters_num[0], kernel_size=(5, 5,",
"out = self.sa(out) * out identity = self.downsample(inputs) output =",
"Sequential() self.downsample.add(layers.Conv2D(filter_num, (1, 1), strides=stride)) else: self.downsample = lambda x:x",
"self.conv2(out) out = self.bn2(out) ############################### 注意力机制 ############################### out = self.ca(out)",
"in range(1, blocks): res_blocks.add(BasicBlock(filter_num, stride=1)) return res_blocks class ResNet_block(keras.Model): def",
"kernel_initializer='he_normal',kernel_regularizer=keras.regularizers.l2(5e-4)) self.conv1 = layers.Conv2D(filter_num, (3, 3), strides=stride, padding='same',kernel_regularizer=regularizers.l2(0.0001)) #kernel_initializer='he_normal', self.bn1",
"= layers.Activation('relu') # self.reshape = layers.Reshape() self.conv4 = layers.Conv2D(filters_num[3], kernel_size=(3,",
"def call(self,inputs,training=None): out = self.conv1(inputs) out = self.bn1(out) out =",
"strides=stride)) else: self.downsample = lambda x:x def call(self, inputs, training=None):",
"= layers.Activation('relu')(conv333_bn) # # conv333_relu_reshape = layers.Reshape( # (conv3_relu.shape[1], conv3_relu.shape[2],",
"(None, 1, 1 feature) avg_out = self.conv2(self.conv1(avg)) max_out = self.conv2(self.conv1(max))",
"self.build_resblock(filters_num[8], layer_dims[3], stride=2) # filters_num = 512 # output: [b,",
"layers.Reshape((1, 1, avg.shape[1]))(avg) # shape (None, 1, 1 feature) max",
"output = layers.add([out, identity]) output = tf.nn.relu(output) return output ######################################",
"x = self.stem(inputs) x1 = self.layer1(inputs) x2 = self.layer2(x1) x3",
"filters_num = 16 # conv222_bn = layers.BatchNormalization()(conv222) # conv222_relu =",
"use_bias=False, kernel_initializer='he_normal', kernel_regularizer=regularizers.l2(5e-4)) ############################### 通道注意力机制 ############################### class ChannelAttention(layers.Layer): def __init__(self,",
"1, avg.shape[1]))(avg) # shape (None, 1, 1 feature) max =",
"= layers.Conv2D(in_planes//ratio, kernel_size=1, strides=1, padding='same', kernel_regularizer=regularizers.l2(5e-4), use_bias=True, activation=tf.nn.relu) self.conv2 =",
"kernel_size=(7, 7, 3), padding='same', # kernel_initializer='he_normal', kernel_regularizer=regularizers.l2(0.0001))(input_layer_up) # conv111_bn =",
"16 self.bn2 = layers.BatchNormalization() self.relu2 = layers.Activation('relu') self.conv3 = layers.Conv3D(filters_num[2],",
"# filters_num = 64 self.bn4 = layers.BatchNormalization() self.relu4 = layers.Activation('relu')",
"self.dpout = layers.Dropout(dropout_rate) self.layer1 = self.build_resblock(filters_num[5], layer_dims[0]) # filters_num =",
"# conv333_bn = layers.BatchNormalization()(conv333) # conv333_relu = layers.Activation('relu')(conv333_bn) # #",
"2, 2] super(ResNet, self).__init__() self.stem = Sequential([layers.Conv2D(64, (3, 3), strides=(1,",
"self.conv2 = layers.Conv3D(filters_num[1],kernel_size=(3,3,5),padding='same') # filters_num = 16 self.bn2 = layers.BatchNormalization()",
"512, h, w], self.avgpool = layers.GlobalAveragePooling2D() self.fc = layers.Dense(num_classes) def",
"reshape out = layers.Reshape((out.shape[1],out.shape[2],out.shape[3] * out.shape[4]))(out) out = self.conv4(out) out",
"conv3_bn = layers.BatchNormalization()(conv3) conv3_relu = layers.Activation('relu')(conv3_bn) # conv3_relu = Dropout(0.5)(conv3_relu)",
"* out identity = self.downsample(inputs) output = layers.add([out, identity]) output",
"# conv111_relu = layers.Activation('relu')(conv111_bn) # # # conv2 = layers.Conv3D(filters_num[1],",
"= layers.add([out, identity]) output = tf.nn.relu(output) return output ###################################### class",
"super(BasicBlock, self).__init__() # self.conv1 = layers.Conv2D(filter_num, (3, 3), strides=stride, padding='same',",
"call(self, inputs, training=None): x = self.stem(inputs) x = self.layer1(x) x",
"2), strides=(1, 1, 1), padding='same')(conv4_relu) conv5 = layers.Conv2D(filters_num[4], kernel_size=(3, 3),",
"filters_num = 256 # layer4 = build_resblock(filters_num[8], layer_dims[3], stride=2) #",
"]) self.layer1 = self.build_resblock(filters_num[0], layer_dims[0]) # filters_num = 64 self.layer2",
"##################第二个尺度######################### # conv11 = layers.Conv3D(filters_num[0], kernel_size=(5, 5, 3), padding='same', #",
"self.layer2 = self.build_resblock(128, layer_dims[1], stride=1) self.layer3 = self.build_resblock(256, layer_dims[2], stride=1)",
"# conv5_relu = Dropout(0.5)(conv5_relu) # conv5_relu = tf.keras.layers.MaxPooling2D(pool_size=(2, 2), strides=(1,",
"ResNet([3, 4, 6, 3],num_classes=9) ########################### pp2主模型 ######################################## class pp2_model(keras.Model): def",
"= layers.Conv3D(filters_num[0], kernel_size=(3, 3, 3),padding='same',kernel_initializer='he_normal',kernel_regularizer=regularizers.l2(0.0001))(input_layer_up) # filters_num = 8 conv1",
"self.layer1 = self.build_resblock(filters_num[0], layer_dims[0]) # filters_num = 64 self.layer2 =",
"3), padding='same',kernel_regularizer=regularizers.l2(0.0001))(conv4_relu) # filters_num = ** conv5_bn = layers.BatchNormalization()(conv5) conv5_relu",
"1), padding='same')(conv3_relu) conv3_relu_reshape = layers.Reshape((conv3_relu.shape[1],conv3_relu.shape[2],conv3_relu.shape[3]*conv3_relu.shape[4]))(conv3_relu) conv3_relu_reshape = Dropout(0.5)(conv3_relu_reshape) ##################第二个尺度######################### #",
"conv3_relu = tf.keras.layers.MaxPooling3D(pool_size=(2, 2, 2), strides=(1, 1, 1), padding='same')(conv3_relu) conv3_relu_reshape",
"conv5_dpout = layers.Dropout(dropout_rate)(conv5) # conv5_reshape = layers.Reshape((conv5_dpout.shape[1],conv5_dpout.shape[2],conv5_dpout.shape[3]))(conv5_dpout) outputs2,outputs4 = Block_res(conv5_relu)",
"layer_dims[0]) # filters_num = 64 # layer2 = build_resblock(filters_num[6], layer_dims[1],",
"res_blocks = Sequential() res_blocks.add(self.BasicBlock1) for _ in range(1, blocks): res_blocks.add(self.BasicBlock2)",
"= self.max(inputs) avg = layers.Reshape((1, 1, avg.shape[1]))(avg) # shape (None,",
"self.layer2(x1) x3 = self.layer3(x2) x4 = self.layer4(x3) # [b, c]",
"self.bn3 = layers.BatchNormalization() self.relu3 = layers.Activation('relu') # self.reshape = layers.Reshape()",
"conv5_bn = layers.BatchNormalization()(conv5) conv5_relu = layers.Activation('relu')(conv5_bn) # conv5_relu = Dropout(0.5)(conv5_relu)",
"from tensorflow.keras import layers, Sequential,regularizers from tensorflow.keras.layers import Dropout #",
"1), padding='same')(conv1_relu) # conv2 = layers.Conv3D(filters_num[1], kernel_size=(3, 3, 5), padding='same')(conv1_relu)",
"layers.Activation('relu')(conv222_bn) # # conv333 = layers.Conv3D(filters_num[2], kernel_size=(7, 7, 3), padding='same',",
"self.conv1(out) return out class BasicBlock(layers.Layer): def __init__(self, filter_num, stride=1): super(BasicBlock,",
"= layers.BatchNormalization()(conv1) conv1_relu = layers.Activation('relu')(conv1_bn) # conv1_relu = Dropout(0.5)(conv1_relu) #",
"layers.Dropout(dropout_rate) self.layer1 = self.build_resblock(filters_num[5], layer_dims[0]) # filters_num = 64 self.layer2",
"# layer4 = build_resblock(filters_num[8], layer_dims[3], stride=2) # filters_num = 512",
"filters_num = 16 conv2 = layers.Conv3D(filters_num[1], kernel_size=(3, 3, 3),padding='same',kernel_regularizer=regularizers.l2(0.0001))(conv1_relu) #",
"= layers.Dropout(dropout_rate) self.layer1 = self.build_resblock(filters_num[5], layer_dims[0]) # filters_num = 64"
] |
[
"of the \"dynamic\" attribute through that error. In a well",
"such error should not exist but getting there is very",
"the code base, we can now switch back to `Exception`.",
"can now switch back to `Exception`. :param base: return values",
"because you can't distinguish if the property does not exist",
"dimensional.\"\"\" return set(typ for types in iterable for typ in",
"to_tuple(func): def wrapper(*args, **kwargs): return tuple(func(*args, **kwargs)) return wrapper def",
"Value manager that ignores all of the specified exceptions. This",
"if os.path.altsep is not None: _sep += os.path.altsep _path_re =",
"AttributeError is easily get caught by `hasattr` and another ``except",
"not exist for real or some code inside of the",
"**kwargs)) return wrapper def to_tuple(func): def wrapper(*args, **kwargs): return tuple(func(*args,",
"originally had to be derived from `BaseException` instead of `Exception`.",
"functions / classes without dependencies. \"\"\" import sys import contextlib",
"caught by `hasattr` and another ``except AttributeError`` clause. This becomes",
"manager that ignores all of the specified exceptions. This will",
"def __iter__(self): return self def next(self): \"\"\" Python 2 Compatibility",
"AttributeError: exc_info = sys.exc_info() reraise(UncaughtAttributeError(exc_info[1]), exc_info[2]) return wrapper class PushBackIterator(object):",
"_sep += os.path.altsep _path_re = re.compile(r'(?:\\.[^{0}]+|[{0}]__init__\\.py)$'.format(re.escape(_sep))) del _sep def to_list(func):",
"even more evil, because it catches ALL exceptions. Therefore this",
"self def next(self): \"\"\" Python 2 Compatibility \"\"\" return self.__next__()",
"is very difficult. This decorator is to help us getting",
"def push_back(self, value): self.pushes.append(value) def __iter__(self): return self def next(self):",
"of \"dynamic\" attributes (e.g., using ``@property``) because you can't distinguish",
"with functions / classes without dependencies. \"\"\" import sys import",
"\"\"\" return self.__next__() def __next__(self): if self.pushes: self.current = self.pushes.pop()",
"wrapper(*args, **kwargs): return tuple(func(*args, **kwargs)) return wrapper def unite(iterable): \"\"\"Turns",
"had to be derived from `BaseException` instead of `Exception`. But",
"in front of the function which does **not** suppose to",
"attributes (e.g., using ``@property``) because you can't distinguish if the",
"return list(func(*args, **kwargs)) return wrapper def to_tuple(func): def wrapper(*args, **kwargs):",
"import contextlib import functools import re import os from medi._compatibility",
"classes without dependencies. \"\"\" import sys import contextlib import functools",
"easily get caught by `hasattr` and another ``except AttributeError`` clause.",
"exc_info[2]) return wrapper class PushBackIterator(object): def __init__(self, iterator): self.pushes =",
"in types) class UncaughtAttributeError(Exception): \"\"\" Important, because `__getattr__` and `hasattr`",
"implicitly. This is really evil (mainly because of `__getattr__`). `hasattr`",
"return wrapper class PushBackIterator(object): def __init__(self, iterator): self.pushes = []",
"exc_info = sys.exc_info() reraise(UncaughtAttributeError(exc_info[1]), exc_info[2]) return wrapper class PushBackIterator(object): def",
"This is really evil (mainly because of `__getattr__`). `hasattr` in",
"Therefore this class originally had to be derived from `BaseException`",
"Python 2 Compatibility \"\"\" return self.__next__() def __next__(self): if self.pushes:",
"**kwds) except AttributeError: exc_info = sys.exc_info() reraise(UncaughtAttributeError(exc_info[1]), exc_info[2]) return wrapper",
"def wrapper(*args, **kwargs): return list(func(*args, **kwargs)) return wrapper def to_tuple(func):",
"of the specified exceptions. This will be in the standard",
"catch AttributeErrors implicitly. This is really evil (mainly because of",
"and another ``except AttributeError`` clause. This becomes problem when you",
"ALL exceptions. Therefore this class originally had to be derived",
"or some code inside of the \"dynamic\" attribute through that",
"some code inside of the \"dynamic\" attribute through that error.",
"`hasattr` from the code base, we can now switch back",
"self.pushes = [] self.iterator = iterator self.current = None def",
"medi._compatibility import reraise _sep = os.path.sep if os.path.altsep is not",
"But because I removed relevant `hasattr` from the code base,",
"**kwargs): return tuple(func(*args, **kwargs)) return wrapper def unite(iterable): \"\"\"Turns a",
"@contextlib.contextmanager def ignored(*exceptions): \"\"\" Value manager that ignores all of",
"us getting there by changing `AttributeError` to `UncaughtAttributeError` to avoid",
"unite(iterable): \"\"\"Turns a two dimensional array into a one dimensional.\"\"\"",
"Important, because `__getattr__` and `hasattr` catch AttributeErrors implicitly. This is",
"func(*args, **kwds) except AttributeError: exc_info = sys.exc_info() reraise(UncaughtAttributeError(exc_info[1]), exc_info[2]) return",
"return tuple(func(*args, **kwargs)) return wrapper def unite(iterable): \"\"\"Turns a two",
"`UncaughtAttributeError` to avoid unexpected catch. This helps us noticing bugs",
"more evil, because it catches ALL exceptions. Therefore this class",
"\"\"\" A universal module with functions / classes without dependencies.",
"distinguish if the property does not exist for real or",
"iterable for typ in types) class UncaughtAttributeError(Exception): \"\"\" Important, because",
"base: return values of sys.exc_info(). \"\"\" def safe_property(func): return property(reraise_uncaught(func))",
"another ``except AttributeError`` clause. This becomes problem when you use",
"None def push_back(self, value): self.pushes.append(value) def __iter__(self): return self def",
"return set(typ for types in iterable for typ in types)",
"when you use a lot of \"dynamic\" attributes (e.g., using",
"`__getattr__` and `hasattr` catch AttributeErrors implicitly. This is really evil",
"helps us noticing bugs earlier and facilitates debugging. .. note::",
"return values of sys.exc_info(). \"\"\" def safe_property(func): return property(reraise_uncaught(func)) def",
"by changing `AttributeError` to `UncaughtAttributeError` to avoid unexpected catch. This",
"to avoid unexpected catch. This helps us noticing bugs earlier",
"**kwargs): return list(func(*args, **kwargs)) return wrapper def to_tuple(func): def wrapper(*args,",
"`hasattr` catch AttributeErrors implicitly. This is really evil (mainly because",
"\"\"\" Important, because `__getattr__` and `hasattr` catch AttributeErrors implicitly. This",
"def __init__(self, iterator): self.pushes = [] self.iterator = iterator self.current",
"``@rethrow_uncaught`` in front of the function which does **not** suppose",
"\"\"\" import sys import contextlib import functools import re import",
"relevant `hasattr` from the code base, we can now switch",
"a one dimensional.\"\"\" return set(typ for types in iterable for",
"if the property does not exist for real or some",
"us noticing bugs earlier and facilitates debugging. .. note:: Treating",
"debugging. .. note:: Treating StopIteration here is easy. Add that",
"\"dynamic\" attribute through that error. In a well written code,",
"In a well written code, such error should not exist",
"bugs earlier and facilitates debugging. .. note:: Treating StopIteration here",
"\"\"\" Re-throw uncaught `AttributeError`. Usage: Put ``@rethrow_uncaught`` in front of",
"but getting there is very difficult. This decorator is to",
"code base, we can now switch back to `Exception`. :param",
"clause. This becomes problem when you use a lot of",
"def safe_property(func): return property(reraise_uncaught(func)) def reraise_uncaught(func): \"\"\" Re-throw uncaught `AttributeError`.",
"derived from `BaseException` instead of `Exception`. But because I removed",
"**kwds): try: return func(*args, **kwds) except AttributeError: exc_info = sys.exc_info()",
"PushBackIterator(object): def __init__(self, iterator): self.pushes = [] self.iterator = iterator",
"evil (mainly because of `__getattr__`). `hasattr` in Python 2 is",
"os.path.sep if os.path.altsep is not None: _sep += os.path.altsep _path_re",
"in Python 2 is even more evil, because it catches",
"``except AttributeError`` clause. This becomes problem when you use a",
"feature when needed. \"\"\" @functools.wraps(func) def wrapper(*args, **kwds): try: return",
"is really evil (mainly because of `__getattr__`). `hasattr` in Python",
"which does **not** suppose to raise `AttributeError`. AttributeError is easily",
"the function which does **not** suppose to raise `AttributeError`. AttributeError",
"avoid unexpected catch. This helps us noticing bugs earlier and",
"is easy. Add that feature when needed. \"\"\" @functools.wraps(func) def",
"list(func(*args, **kwargs)) return wrapper def to_tuple(func): def wrapper(*args, **kwargs): return",
"@functools.wraps(func) def wrapper(*args, **kwds): try: return func(*args, **kwds) except AttributeError:",
"be derived from `BaseException` instead of `Exception`. But because I",
"removed relevant `hasattr` from the code base, we can now",
"by `hasattr` and another ``except AttributeError`` clause. This becomes problem",
"evil, because it catches ALL exceptions. Therefore this class originally",
"there by changing `AttributeError` to `UncaughtAttributeError` to avoid unexpected catch.",
"suppose to raise `AttributeError`. AttributeError is easily get caught by",
"re.compile(r'(?:\\.[^{0}]+|[{0}]__init__\\.py)$'.format(re.escape(_sep))) del _sep def to_list(func): def wrapper(*args, **kwargs): return list(func(*args,",
"the standard library starting with Python 3.5. \"\"\" try: yield",
"for real or some code inside of the \"dynamic\" attribute",
"__next__(self): if self.pushes: self.current = self.pushes.pop() else: self.current = next(self.iterator)",
"self.iterator = iterator self.current = None def push_back(self, value): self.pushes.append(value)",
"to `Exception`. :param base: return values of sys.exc_info(). \"\"\" def",
"reraise(UncaughtAttributeError(exc_info[1]), exc_info[2]) return wrapper class PushBackIterator(object): def __init__(self, iterator): self.pushes",
"noticing bugs earlier and facilitates debugging. .. note:: Treating StopIteration",
"because it catches ALL exceptions. Therefore this class originally had",
"in the standard library starting with Python 3.5. \"\"\" try:",
"note:: Treating StopIteration here is easy. Add that feature when",
"from `BaseException` instead of `Exception`. But because I removed relevant",
"really evil (mainly because of `__getattr__`). `hasattr` in Python 2",
"iterator): self.pushes = [] self.iterator = iterator self.current = None",
"This will be in the standard library starting with Python",
"return self.__next__() def __next__(self): if self.pushes: self.current = self.pushes.pop() else:",
"Python 2 is even more evil, because it catches ALL",
"functools import re import os from medi._compatibility import reraise _sep",
"that ignores all of the specified exceptions. This will be",
"property does not exist for real or some code inside",
"Treating StopIteration here is easy. Add that feature when needed.",
"raise `AttributeError`. AttributeError is easily get caught by `hasattr` and",
"is to help us getting there by changing `AttributeError` to",
"sys.exc_info(). \"\"\" def safe_property(func): return property(reraise_uncaught(func)) def reraise_uncaught(func): \"\"\" Re-throw",
"\"\"\" def safe_property(func): return property(reraise_uncaught(func)) def reraise_uncaught(func): \"\"\" Re-throw uncaught",
"\"\"\" @functools.wraps(func) def wrapper(*args, **kwds): try: return func(*args, **kwds) except",
"typ in types) class UncaughtAttributeError(Exception): \"\"\" Important, because `__getattr__` and",
"becomes problem when you use a lot of \"dynamic\" attributes",
"that error. In a well written code, such error should",
"because I removed relevant `hasattr` from the code base, we",
"self.current = None def push_back(self, value): self.pushes.append(value) def __iter__(self): return",
"from the code base, we can now switch back to",
"use a lot of \"dynamic\" attributes (e.g., using ``@property``) because",
"_sep def to_list(func): def wrapper(*args, **kwargs): return list(func(*args, **kwargs)) return",
"next(self): \"\"\" Python 2 Compatibility \"\"\" return self.__next__() def __next__(self):",
"wrapper class PushBackIterator(object): def __init__(self, iterator): self.pushes = [] self.iterator",
"now switch back to `Exception`. :param base: return values of",
"needed. \"\"\" @functools.wraps(func) def wrapper(*args, **kwds): try: return func(*args, **kwds)",
"= iterator self.current = None def push_back(self, value): self.pushes.append(value) def",
"not None: _sep += os.path.altsep _path_re = re.compile(r'(?:\\.[^{0}]+|[{0}]__init__\\.py)$'.format(re.escape(_sep))) del _sep",
"def reraise_uncaught(func): \"\"\" Re-throw uncaught `AttributeError`. Usage: Put ``@rethrow_uncaught`` in",
"wrapper(*args, **kwds): try: return func(*args, **kwds) except AttributeError: exc_info =",
"reraise_uncaught(func): \"\"\" Re-throw uncaught `AttributeError`. Usage: Put ``@rethrow_uncaught`` in front",
"\"dynamic\" attributes (e.g., using ``@property``) because you can't distinguish if",
"base, we can now switch back to `Exception`. :param base:",
"this class originally had to be derived from `BaseException` instead",
"wrapper def to_tuple(func): def wrapper(*args, **kwargs): return tuple(func(*args, **kwargs)) return",
"os.path.altsep _path_re = re.compile(r'(?:\\.[^{0}]+|[{0}]__init__\\.py)$'.format(re.escape(_sep))) del _sep def to_list(func): def wrapper(*args,",
"a well written code, such error should not exist but",
"sys import contextlib import functools import re import os from",
"None: _sep += os.path.altsep _path_re = re.compile(r'(?:\\.[^{0}]+|[{0}]__init__\\.py)$'.format(re.escape(_sep))) del _sep def",
".. note:: Treating StopIteration here is easy. Add that feature",
"Put ``@rethrow_uncaught`` in front of the function which does **not**",
"= None def push_back(self, value): self.pushes.append(value) def __iter__(self): return self",
"when needed. \"\"\" @functools.wraps(func) def wrapper(*args, **kwds): try: return func(*args,",
"does **not** suppose to raise `AttributeError`. AttributeError is easily get",
"error should not exist but getting there is very difficult.",
"`AttributeError`. AttributeError is easily get caught by `hasattr` and another",
"function which does **not** suppose to raise `AttributeError`. AttributeError is",
"return wrapper def to_tuple(func): def wrapper(*args, **kwargs): return tuple(func(*args, **kwargs))",
"code inside of the \"dynamic\" attribute through that error. In",
"dependencies. \"\"\" import sys import contextlib import functools import re",
"getting there by changing `AttributeError` to `UncaughtAttributeError` to avoid unexpected",
"tuple(func(*args, **kwargs)) return wrapper def unite(iterable): \"\"\"Turns a two dimensional",
"of the function which does **not** suppose to raise `AttributeError`.",
"<reponame>yuan-xy/medi<filename>medi/inference/utils.py \"\"\" A universal module with functions / classes without",
"return wrapper def unite(iterable): \"\"\"Turns a two dimensional array into",
"a two dimensional array into a one dimensional.\"\"\" return set(typ",
"_sep = os.path.sep if os.path.altsep is not None: _sep +=",
"AttributeErrors implicitly. This is really evil (mainly because of `__getattr__`).",
"def to_list(func): def wrapper(*args, **kwargs): return list(func(*args, **kwargs)) return wrapper",
"decorator is to help us getting there by changing `AttributeError`",
"= self.pushes.pop() else: self.current = next(self.iterator) return self.current @contextlib.contextmanager def",
"2 Compatibility \"\"\" return self.__next__() def __next__(self): if self.pushes: self.current",
"contextlib import functools import re import os from medi._compatibility import",
"code, such error should not exist but getting there is",
"we can now switch back to `Exception`. :param base: return",
"get caught by `hasattr` and another ``except AttributeError`` clause. This",
"Re-throw uncaught `AttributeError`. Usage: Put ``@rethrow_uncaught`` in front of the",
"def wrapper(*args, **kwds): try: return func(*args, **kwds) except AttributeError: exc_info",
"\"\"\" Value manager that ignores all of the specified exceptions.",
"wrapper(*args, **kwargs): return list(func(*args, **kwargs)) return wrapper def to_tuple(func): def",
"`__getattr__`). `hasattr` in Python 2 is even more evil, because",
"reraise _sep = os.path.sep if os.path.altsep is not None: _sep",
"facilitates debugging. .. note:: Treating StopIteration here is easy. Add",
"return property(reraise_uncaught(func)) def reraise_uncaught(func): \"\"\" Re-throw uncaught `AttributeError`. Usage: Put",
"self.current = self.pushes.pop() else: self.current = next(self.iterator) return self.current @contextlib.contextmanager",
"exist for real or some code inside of the \"dynamic\"",
"exceptions. Therefore this class originally had to be derived from",
"you can't distinguish if the property does not exist for",
"exceptions. This will be in the standard library starting with",
"does not exist for real or some code inside of",
"__init__(self, iterator): self.pushes = [] self.iterator = iterator self.current =",
"that feature when needed. \"\"\" @functools.wraps(func) def wrapper(*args, **kwds): try:",
"try: return func(*args, **kwds) except AttributeError: exc_info = sys.exc_info() reraise(UncaughtAttributeError(exc_info[1]),",
"types) class UncaughtAttributeError(Exception): \"\"\" Important, because `__getattr__` and `hasattr` catch",
"written code, such error should not exist but getting there",
":param base: return values of sys.exc_info(). \"\"\" def safe_property(func): return",
"uncaught `AttributeError`. Usage: Put ``@rethrow_uncaught`` in front of the function",
"def __next__(self): if self.pushes: self.current = self.pushes.pop() else: self.current =",
"This becomes problem when you use a lot of \"dynamic\"",
"ignored(*exceptions): \"\"\" Value manager that ignores all of the specified",
"to be derived from `BaseException` instead of `Exception`. But because",
"(e.g., using ``@property``) because you can't distinguish if the property",
"because of `__getattr__`). `hasattr` in Python 2 is even more",
"This helps us noticing bugs earlier and facilitates debugging. ..",
"attribute through that error. In a well written code, such",
"(mainly because of `__getattr__`). `hasattr` in Python 2 is even",
"using ``@property``) because you can't distinguish if the property does",
"os from medi._compatibility import reraise _sep = os.path.sep if os.path.altsep",
"one dimensional.\"\"\" return set(typ for types in iterable for typ",
"through that error. In a well written code, such error",
"changing `AttributeError` to `UncaughtAttributeError` to avoid unexpected catch. This helps",
"def unite(iterable): \"\"\"Turns a two dimensional array into a one",
"safe_property(func): return property(reraise_uncaught(func)) def reraise_uncaught(func): \"\"\" Re-throw uncaught `AttributeError`. Usage:",
"import reraise _sep = os.path.sep if os.path.altsep is not None:",
"help us getting there by changing `AttributeError` to `UncaughtAttributeError` to",
"This decorator is to help us getting there by changing",
"exist but getting there is very difficult. This decorator is",
"_path_re = re.compile(r'(?:\\.[^{0}]+|[{0}]__init__\\.py)$'.format(re.escape(_sep))) del _sep def to_list(func): def wrapper(*args, **kwargs):",
"types in iterable for typ in types) class UncaughtAttributeError(Exception): \"\"\"",
"getting there is very difficult. This decorator is to help",
"to raise `AttributeError`. AttributeError is easily get caught by `hasattr`",
"the property does not exist for real or some code",
"return self.current @contextlib.contextmanager def ignored(*exceptions): \"\"\" Value manager that ignores",
"else: self.current = next(self.iterator) return self.current @contextlib.contextmanager def ignored(*exceptions): \"\"\"",
"to_list(func): def wrapper(*args, **kwargs): return list(func(*args, **kwargs)) return wrapper def",
"self.pushes.append(value) def __iter__(self): return self def next(self): \"\"\" Python 2",
"value): self.pushes.append(value) def __iter__(self): return self def next(self): \"\"\" Python",
"set(typ for types in iterable for typ in types) class",
"**not** suppose to raise `AttributeError`. AttributeError is easily get caught",
"to `UncaughtAttributeError` to avoid unexpected catch. This helps us noticing",
"values of sys.exc_info(). \"\"\" def safe_property(func): return property(reraise_uncaught(func)) def reraise_uncaught(func):",
"self.pushes: self.current = self.pushes.pop() else: self.current = next(self.iterator) return self.current",
"push_back(self, value): self.pushes.append(value) def __iter__(self): return self def next(self): \"\"\"",
"from medi._compatibility import reraise _sep = os.path.sep if os.path.altsep is",
"`hasattr` and another ``except AttributeError`` clause. This becomes problem when",
"the specified exceptions. This will be in the standard library",
"**kwargs)) return wrapper def unite(iterable): \"\"\"Turns a two dimensional array",
"catches ALL exceptions. Therefore this class originally had to be",
"= re.compile(r'(?:\\.[^{0}]+|[{0}]__init__\\.py)$'.format(re.escape(_sep))) del _sep def to_list(func): def wrapper(*args, **kwargs): return",
"real or some code inside of the \"dynamic\" attribute through",
"here is easy. Add that feature when needed. \"\"\" @functools.wraps(func)",
"dimensional array into a one dimensional.\"\"\" return set(typ for types",
"into a one dimensional.\"\"\" return set(typ for types in iterable",
"catch. This helps us noticing bugs earlier and facilitates debugging.",
"self.pushes.pop() else: self.current = next(self.iterator) return self.current @contextlib.contextmanager def ignored(*exceptions):",
"all of the specified exceptions. This will be in the",
"`Exception`. But because I removed relevant `hasattr` from the code",
"Compatibility \"\"\" return self.__next__() def __next__(self): if self.pushes: self.current =",
"library starting with Python 3.5. \"\"\" try: yield except exceptions:",
"`Exception`. :param base: return values of sys.exc_info(). \"\"\" def safe_property(func):",
"/ classes without dependencies. \"\"\" import sys import contextlib import",
"for typ in types) class UncaughtAttributeError(Exception): \"\"\" Important, because `__getattr__`",
"I removed relevant `hasattr` from the code base, we can",
"without dependencies. \"\"\" import sys import contextlib import functools import",
"is easily get caught by `hasattr` and another ``except AttributeError``",
"2 is even more evil, because it catches ALL exceptions.",
"import functools import re import os from medi._compatibility import reraise",
"switch back to `Exception`. :param base: return values of sys.exc_info().",
"can't distinguish if the property does not exist for real",
"very difficult. This decorator is to help us getting there",
"module with functions / classes without dependencies. \"\"\" import sys",
"= next(self.iterator) return self.current @contextlib.contextmanager def ignored(*exceptions): \"\"\" Value manager",
"def ignored(*exceptions): \"\"\" Value manager that ignores all of the",
"lot of \"dynamic\" attributes (e.g., using ``@property``) because you can't",
"of `__getattr__`). `hasattr` in Python 2 is even more evil,",
"it catches ALL exceptions. Therefore this class originally had to",
"instead of `Exception`. But because I removed relevant `hasattr` from",
"import re import os from medi._compatibility import reraise _sep =",
"return func(*args, **kwds) except AttributeError: exc_info = sys.exc_info() reraise(UncaughtAttributeError(exc_info[1]), exc_info[2])",
"for types in iterable for typ in types) class UncaughtAttributeError(Exception):",
"to help us getting there by changing `AttributeError` to `UncaughtAttributeError`",
"A universal module with functions / classes without dependencies. \"\"\"",
"class originally had to be derived from `BaseException` instead of",
"inside of the \"dynamic\" attribute through that error. In a",
"of sys.exc_info(). \"\"\" def safe_property(func): return property(reraise_uncaught(func)) def reraise_uncaught(func): \"\"\"",
"and `hasattr` catch AttributeErrors implicitly. This is really evil (mainly",
"front of the function which does **not** suppose to raise",
"`AttributeError` to `UncaughtAttributeError` to avoid unexpected catch. This helps us",
"`BaseException` instead of `Exception`. But because I removed relevant `hasattr`",
"easy. Add that feature when needed. \"\"\" @functools.wraps(func) def wrapper(*args,",
"will be in the standard library starting with Python 3.5.",
"the \"dynamic\" attribute through that error. In a well written",
"unexpected catch. This helps us noticing bugs earlier and facilitates",
"Usage: Put ``@rethrow_uncaught`` in front of the function which does",
"`AttributeError`. Usage: Put ``@rethrow_uncaught`` in front of the function which",
"def next(self): \"\"\" Python 2 Compatibility \"\"\" return self.__next__() def",
"except AttributeError: exc_info = sys.exc_info() reraise(UncaughtAttributeError(exc_info[1]), exc_info[2]) return wrapper class",
"wrapper def unite(iterable): \"\"\"Turns a two dimensional array into a",
"= sys.exc_info() reraise(UncaughtAttributeError(exc_info[1]), exc_info[2]) return wrapper class PushBackIterator(object): def __init__(self,",
"Add that feature when needed. \"\"\" @functools.wraps(func) def wrapper(*args, **kwds):",
"def wrapper(*args, **kwargs): return tuple(func(*args, **kwargs)) return wrapper def unite(iterable):",
"because `__getattr__` and `hasattr` catch AttributeErrors implicitly. This is really",
"back to `Exception`. :param base: return values of sys.exc_info(). \"\"\"",
"self.current = next(self.iterator) return self.current @contextlib.contextmanager def ignored(*exceptions): \"\"\" Value",
"= [] self.iterator = iterator self.current = None def push_back(self,",
"class PushBackIterator(object): def __init__(self, iterator): self.pushes = [] self.iterator =",
"difficult. This decorator is to help us getting there by",
"next(self.iterator) return self.current @contextlib.contextmanager def ignored(*exceptions): \"\"\" Value manager that",
"import sys import contextlib import functools import re import os",
"two dimensional array into a one dimensional.\"\"\" return set(typ for",
"is even more evil, because it catches ALL exceptions. Therefore",
"standard library starting with Python 3.5. \"\"\" try: yield except",
"and facilitates debugging. .. note:: Treating StopIteration here is easy.",
"property(reraise_uncaught(func)) def reraise_uncaught(func): \"\"\" Re-throw uncaught `AttributeError`. Usage: Put ``@rethrow_uncaught``",
"self.__next__() def __next__(self): if self.pushes: self.current = self.pushes.pop() else: self.current",
"is not None: _sep += os.path.altsep _path_re = re.compile(r'(?:\\.[^{0}]+|[{0}]__init__\\.py)$'.format(re.escape(_sep))) del",
"re import os from medi._compatibility import reraise _sep = os.path.sep",
"``@property``) because you can't distinguish if the property does not",
"`hasattr` in Python 2 is even more evil, because it",
"UncaughtAttributeError(Exception): \"\"\" Important, because `__getattr__` and `hasattr` catch AttributeErrors implicitly.",
"array into a one dimensional.\"\"\" return set(typ for types in",
"problem when you use a lot of \"dynamic\" attributes (e.g.,",
"not exist but getting there is very difficult. This decorator",
"earlier and facilitates debugging. .. note:: Treating StopIteration here is",
"iterator self.current = None def push_back(self, value): self.pushes.append(value) def __iter__(self):",
"StopIteration here is easy. Add that feature when needed. \"\"\"",
"def to_tuple(func): def wrapper(*args, **kwargs): return tuple(func(*args, **kwargs)) return wrapper",
"if self.pushes: self.current = self.pushes.pop() else: self.current = next(self.iterator) return",
"ignores all of the specified exceptions. This will be in",
"universal module with functions / classes without dependencies. \"\"\" import",
"[] self.iterator = iterator self.current = None def push_back(self, value):",
"AttributeError`` clause. This becomes problem when you use a lot",
"starting with Python 3.5. \"\"\" try: yield except exceptions: pass",
"there is very difficult. This decorator is to help us",
"del _sep def to_list(func): def wrapper(*args, **kwargs): return list(func(*args, **kwargs))",
"specified exceptions. This will be in the standard library starting",
"return self def next(self): \"\"\" Python 2 Compatibility \"\"\" return",
"a lot of \"dynamic\" attributes (e.g., using ``@property``) because you",
"well written code, such error should not exist but getting",
"sys.exc_info() reraise(UncaughtAttributeError(exc_info[1]), exc_info[2]) return wrapper class PushBackIterator(object): def __init__(self, iterator):",
"= os.path.sep if os.path.altsep is not None: _sep += os.path.altsep",
"\"\"\" Python 2 Compatibility \"\"\" return self.__next__() def __next__(self): if",
"\"\"\"Turns a two dimensional array into a one dimensional.\"\"\" return",
"of `Exception`. But because I removed relevant `hasattr` from the",
"in iterable for typ in types) class UncaughtAttributeError(Exception): \"\"\" Important,",
"+= os.path.altsep _path_re = re.compile(r'(?:\\.[^{0}]+|[{0}]__init__\\.py)$'.format(re.escape(_sep))) del _sep def to_list(func): def",
"__iter__(self): return self def next(self): \"\"\" Python 2 Compatibility \"\"\"",
"os.path.altsep is not None: _sep += os.path.altsep _path_re = re.compile(r'(?:\\.[^{0}]+|[{0}]__init__\\.py)$'.format(re.escape(_sep)))",
"should not exist but getting there is very difficult. This",
"error. In a well written code, such error should not",
"self.current @contextlib.contextmanager def ignored(*exceptions): \"\"\" Value manager that ignores all",
"import os from medi._compatibility import reraise _sep = os.path.sep if",
"you use a lot of \"dynamic\" attributes (e.g., using ``@property``)",
"class UncaughtAttributeError(Exception): \"\"\" Important, because `__getattr__` and `hasattr` catch AttributeErrors",
"be in the standard library starting with Python 3.5. \"\"\""
] |
[
"file transition 5. Run Rapid update of master (trunk) and",
"Workflow package transition 4. Run Manifest file transition 5. Run",
"repo to repositories/admin \"\"\" import src.run_transition as rt import src.svn_dump_update",
"rt.run_manifest_transition(config_file, new_svn_dump=True) return if __name__ == '__main__': start_time = time.time()",
"rt.run_software_transition(config_file, new_svn_dump=True) rt.run_experiment_data_transition(config_file, new_svn_dump=True) rt.run_workflow_transition(config_file, new_svn_dump=True) rt.run_manifest_transition(config_file, new_svn_dump=True) return if",
"module assembles the classes for the SVN --> Git transition",
"in a sequential manner. It runs the following aspects fo",
"assembles the classes for the SVN --> Git transition can",
"need to be done: 1. Copy over bare repos to",
"to repositories/packages 2. Copy manifest bare git repo to repositories/admin",
"fo the Bioconductor transition. Note: Update the SVN dump 1.",
"Copy over bare repos to repositories/packages 2. Copy manifest bare",
"format='%(levelname)s %(asctime)s %(message)s', level=logging.DEBUG) def svn_dump_update(config_file): sdu.svn_root_update(config_file) sdu.svn_experiment_root_update(config_file) return def",
"package transition 4. Run Manifest file transition 5. Run Rapid",
"src.run_transition as rt import src.svn_dump_update as sdu import logging import",
"branches on software packages Manual tasks which need to be",
"Run Bioconductor Software package transition 2. Run Bioconductor Experiment Data",
"RELEASE_3_5 branches on software packages Manual tasks which need to",
"Manual tasks which need to be done: 1. Copy over",
"svn_dump_update(config_file): sdu.svn_root_update(config_file) sdu.svn_experiment_root_update(config_file) return def run(config_file): rt.run_software_transition(config_file, new_svn_dump=True) rt.run_experiment_data_transition(config_file, new_svn_dump=True)",
"== '__main__': start_time = time.time() config_file = \"./settings.ini\" svn_dump_update(config_file) run(config_file)",
"TODO: Run updates after dump update svn_dump_update(config_file) rt.run_updates(config_file) logging.info(\"--- %s",
"git transition code. This module assembles the classes for the",
"updates after dump update svn_dump_update(config_file) rt.run_updates(config_file) logging.info(\"--- %s seconds ---\"",
"the Bioconductor transition. Note: Update the SVN dump 1. Run",
"Git transition can be run in a sequential manner. It",
"svn_dump_update(config_file) run(config_file) # TODO: Run updates after dump update svn_dump_update(config_file)",
"\"\"\"Bioconductor run git transition code. This module assembles the classes",
"code. This module assembles the classes for the SVN -->",
"master (trunk) and RELEASE_3_5 branches on software packages Manual tasks",
"manner. It runs the following aspects fo the Bioconductor transition.",
"time.time() config_file = \"./settings.ini\" svn_dump_update(config_file) run(config_file) # TODO: Run updates",
"to be done: 1. Copy over bare repos to repositories/packages",
"aspects fo the Bioconductor transition. Note: Update the SVN dump",
"over bare repos to repositories/packages 2. Copy manifest bare git",
"Bioconductor transition. Note: Update the SVN dump 1. Run Bioconductor",
"and RELEASE_3_5 branches on software packages Manual tasks which need",
"'__main__': start_time = time.time() config_file = \"./settings.ini\" svn_dump_update(config_file) run(config_file) #",
"Run Workflow package transition 4. Run Manifest file transition 5.",
"Update the SVN dump 1. Run Bioconductor Software package transition",
"Copy manifest bare git repo to repositories/admin \"\"\" import src.run_transition",
"after dump update svn_dump_update(config_file) rt.run_updates(config_file) logging.info(\"--- %s seconds ---\" %",
"svn_dump_update(config_file) rt.run_updates(config_file) logging.info(\"--- %s seconds ---\" % (time.time() - start_time))",
"as rt import src.svn_dump_update as sdu import logging import time",
"repositories/admin \"\"\" import src.run_transition as rt import src.svn_dump_update as sdu",
"= \"./settings.ini\" svn_dump_update(config_file) run(config_file) # TODO: Run updates after dump",
"the following aspects fo the Bioconductor transition. Note: Update the",
"%(message)s', level=logging.DEBUG) def svn_dump_update(config_file): sdu.svn_root_update(config_file) sdu.svn_experiment_root_update(config_file) return def run(config_file): rt.run_software_transition(config_file,",
"rt.run_workflow_transition(config_file, new_svn_dump=True) rt.run_manifest_transition(config_file, new_svn_dump=True) return if __name__ == '__main__': start_time",
"of master (trunk) and RELEASE_3_5 branches on software packages Manual",
"transition 3. Run Workflow package transition 4. Run Manifest file",
"src.svn_dump_update as sdu import logging import time logging.basicConfig(filename='transition.log', format='%(levelname)s %(asctime)s",
"def svn_dump_update(config_file): sdu.svn_root_update(config_file) sdu.svn_experiment_root_update(config_file) return def run(config_file): rt.run_software_transition(config_file, new_svn_dump=True) rt.run_experiment_data_transition(config_file,",
"if __name__ == '__main__': start_time = time.time() config_file = \"./settings.ini\"",
"return if __name__ == '__main__': start_time = time.time() config_file =",
"transition can be run in a sequential manner. It runs",
"classes for the SVN --> Git transition can be run",
"be done: 1. Copy over bare repos to repositories/packages 2.",
"import logging import time logging.basicConfig(filename='transition.log', format='%(levelname)s %(asctime)s %(message)s', level=logging.DEBUG) def",
"transition 5. Run Rapid update of master (trunk) and RELEASE_3_5",
"4. Run Manifest file transition 5. Run Rapid update of",
"def run(config_file): rt.run_software_transition(config_file, new_svn_dump=True) rt.run_experiment_data_transition(config_file, new_svn_dump=True) rt.run_workflow_transition(config_file, new_svn_dump=True) rt.run_manifest_transition(config_file, new_svn_dump=True)",
"bare repos to repositories/packages 2. Copy manifest bare git repo",
"import src.run_transition as rt import src.svn_dump_update as sdu import logging",
"Run Manifest file transition 5. Run Rapid update of master",
"Rapid update of master (trunk) and RELEASE_3_5 branches on software",
"5. Run Rapid update of master (trunk) and RELEASE_3_5 branches",
"to repositories/admin \"\"\" import src.run_transition as rt import src.svn_dump_update as",
"SVN --> Git transition can be run in a sequential",
"1. Copy over bare repos to repositories/packages 2. Copy manifest",
"new_svn_dump=True) return if __name__ == '__main__': start_time = time.time() config_file",
"--> Git transition can be run in a sequential manner.",
"new_svn_dump=True) rt.run_experiment_data_transition(config_file, new_svn_dump=True) rt.run_workflow_transition(config_file, new_svn_dump=True) rt.run_manifest_transition(config_file, new_svn_dump=True) return if __name__",
"runs the following aspects fo the Bioconductor transition. Note: Update",
"packages Manual tasks which need to be done: 1. Copy",
"new_svn_dump=True) rt.run_workflow_transition(config_file, new_svn_dump=True) rt.run_manifest_transition(config_file, new_svn_dump=True) return if __name__ == '__main__':",
"software packages Manual tasks which need to be done: 1.",
"transition 2. Run Bioconductor Experiment Data package transition 3. Run",
"This module assembles the classes for the SVN --> Git",
"be run in a sequential manner. It runs the following",
"dump update svn_dump_update(config_file) rt.run_updates(config_file) logging.info(\"--- %s seconds ---\" % (time.time()",
"run(config_file) # TODO: Run updates after dump update svn_dump_update(config_file) rt.run_updates(config_file)",
"import src.svn_dump_update as sdu import logging import time logging.basicConfig(filename='transition.log', format='%(levelname)s",
"Run Rapid update of master (trunk) and RELEASE_3_5 branches on",
"the classes for the SVN --> Git transition can be",
"Note: Update the SVN dump 1. Run Bioconductor Software package",
"new_svn_dump=True) rt.run_manifest_transition(config_file, new_svn_dump=True) return if __name__ == '__main__': start_time =",
"a sequential manner. It runs the following aspects fo the",
"rt.run_experiment_data_transition(config_file, new_svn_dump=True) rt.run_workflow_transition(config_file, new_svn_dump=True) rt.run_manifest_transition(config_file, new_svn_dump=True) return if __name__ ==",
"sdu import logging import time logging.basicConfig(filename='transition.log', format='%(levelname)s %(asctime)s %(message)s', level=logging.DEBUG)",
"the SVN dump 1. Run Bioconductor Software package transition 2.",
"It runs the following aspects fo the Bioconductor transition. Note:",
"sdu.svn_experiment_root_update(config_file) return def run(config_file): rt.run_software_transition(config_file, new_svn_dump=True) rt.run_experiment_data_transition(config_file, new_svn_dump=True) rt.run_workflow_transition(config_file, new_svn_dump=True)",
"Bioconductor Software package transition 2. Run Bioconductor Experiment Data package",
"Run Bioconductor Experiment Data package transition 3. Run Workflow package",
"Bioconductor Experiment Data package transition 3. Run Workflow package transition",
"manifest bare git repo to repositories/admin \"\"\" import src.run_transition as",
"return def run(config_file): rt.run_software_transition(config_file, new_svn_dump=True) rt.run_experiment_data_transition(config_file, new_svn_dump=True) rt.run_workflow_transition(config_file, new_svn_dump=True) rt.run_manifest_transition(config_file,",
"1. Run Bioconductor Software package transition 2. Run Bioconductor Experiment",
"Run updates after dump update svn_dump_update(config_file) rt.run_updates(config_file) logging.info(\"--- %s seconds",
"\"\"\" import src.run_transition as rt import src.svn_dump_update as sdu import",
"repositories/packages 2. Copy manifest bare git repo to repositories/admin \"\"\"",
"as sdu import logging import time logging.basicConfig(filename='transition.log', format='%(levelname)s %(asctime)s %(message)s',",
"which need to be done: 1. Copy over bare repos",
"%(asctime)s %(message)s', level=logging.DEBUG) def svn_dump_update(config_file): sdu.svn_root_update(config_file) sdu.svn_experiment_root_update(config_file) return def run(config_file):",
"= time.time() config_file = \"./settings.ini\" svn_dump_update(config_file) run(config_file) # TODO: Run",
"Manifest file transition 5. Run Rapid update of master (trunk)",
"can be run in a sequential manner. It runs the",
"logging.basicConfig(filename='transition.log', format='%(levelname)s %(asctime)s %(message)s', level=logging.DEBUG) def svn_dump_update(config_file): sdu.svn_root_update(config_file) sdu.svn_experiment_root_update(config_file) return",
"Experiment Data package transition 3. Run Workflow package transition 4.",
"config_file = \"./settings.ini\" svn_dump_update(config_file) run(config_file) # TODO: Run updates after",
"update svn_dump_update(config_file) rt.run_updates(config_file) logging.info(\"--- %s seconds ---\" % (time.time() -",
"2. Copy manifest bare git repo to repositories/admin \"\"\" import",
"git repo to repositories/admin \"\"\" import src.run_transition as rt import",
"package transition 3. Run Workflow package transition 4. Run Manifest",
"start_time = time.time() config_file = \"./settings.ini\" svn_dump_update(config_file) run(config_file) # TODO:",
"run git transition code. This module assembles the classes for",
"__name__ == '__main__': start_time = time.time() config_file = \"./settings.ini\" svn_dump_update(config_file)",
"for the SVN --> Git transition can be run in",
"run in a sequential manner. It runs the following aspects",
"sequential manner. It runs the following aspects fo the Bioconductor",
"run(config_file): rt.run_software_transition(config_file, new_svn_dump=True) rt.run_experiment_data_transition(config_file, new_svn_dump=True) rt.run_workflow_transition(config_file, new_svn_dump=True) rt.run_manifest_transition(config_file, new_svn_dump=True) return",
"Software package transition 2. Run Bioconductor Experiment Data package transition",
"logging import time logging.basicConfig(filename='transition.log', format='%(levelname)s %(asctime)s %(message)s', level=logging.DEBUG) def svn_dump_update(config_file):",
"transition 4. Run Manifest file transition 5. Run Rapid update",
"level=logging.DEBUG) def svn_dump_update(config_file): sdu.svn_root_update(config_file) sdu.svn_experiment_root_update(config_file) return def run(config_file): rt.run_software_transition(config_file, new_svn_dump=True)",
"dump 1. Run Bioconductor Software package transition 2. Run Bioconductor",
"transition code. This module assembles the classes for the SVN",
"import time logging.basicConfig(filename='transition.log', format='%(levelname)s %(asctime)s %(message)s', level=logging.DEBUG) def svn_dump_update(config_file): sdu.svn_root_update(config_file)",
"sdu.svn_root_update(config_file) sdu.svn_experiment_root_update(config_file) return def run(config_file): rt.run_software_transition(config_file, new_svn_dump=True) rt.run_experiment_data_transition(config_file, new_svn_dump=True) rt.run_workflow_transition(config_file,",
"bare git repo to repositories/admin \"\"\" import src.run_transition as rt",
"3. Run Workflow package transition 4. Run Manifest file transition",
"SVN dump 1. Run Bioconductor Software package transition 2. Run",
"transition. Note: Update the SVN dump 1. Run Bioconductor Software",
"2. Run Bioconductor Experiment Data package transition 3. Run Workflow",
"update of master (trunk) and RELEASE_3_5 branches on software packages",
"tasks which need to be done: 1. Copy over bare",
"the SVN --> Git transition can be run in a",
"(trunk) and RELEASE_3_5 branches on software packages Manual tasks which",
"Data package transition 3. Run Workflow package transition 4. Run",
"time logging.basicConfig(filename='transition.log', format='%(levelname)s %(asctime)s %(message)s', level=logging.DEBUG) def svn_dump_update(config_file): sdu.svn_root_update(config_file) sdu.svn_experiment_root_update(config_file)",
"repos to repositories/packages 2. Copy manifest bare git repo to",
"rt import src.svn_dump_update as sdu import logging import time logging.basicConfig(filename='transition.log',",
"\"./settings.ini\" svn_dump_update(config_file) run(config_file) # TODO: Run updates after dump update",
"# TODO: Run updates after dump update svn_dump_update(config_file) rt.run_updates(config_file) logging.info(\"---",
"following aspects fo the Bioconductor transition. Note: Update the SVN",
"done: 1. Copy over bare repos to repositories/packages 2. Copy",
"package transition 2. Run Bioconductor Experiment Data package transition 3.",
"on software packages Manual tasks which need to be done:"
] |
[
"return self._is_hard_invalidated is False def is_soft_invalidated(self, timestamp): return self.was_soft_invalidated() and",
"self.backend.get(key) if (value is NO_VALUE or value.metadata['v'] != value_version or",
"backend. If you are using a :class:`.CacheBackend` or :class:`.ProxyBackend` that",
"based on the given keys. Returns values as a list",
"to ``None``, in which case the key mangling function recommended",
"implementation is injected into a :class:`.CacheRegion` at configure time using",
"if present. :param creator: function which creates a new value.",
"sequence of new values. :param expiration_time: optional expiration time which",
"previous value is available, until the lock is released and",
"decorator (though note: **not** the :meth:`.CacheRegion.get` method) will call upon",
"returned, but isn't cached. E.g.:: def dont_cache_none(value): return value is",
"of seconds, or as a ``datetime.timedelta`` value. .. versionadded 0.5.0",
"**kw): return \":\".join( [kw[k] for k in namespace] + [str(x)",
"0.4.1 Added ``set()`` method to decorated function. Similar to ``set()``",
"bool(self._soft_invalidated) def is_soft_invalidated(self, timestamp): return (self._soft_invalidated and timestamp < self._soft_invalidated)",
"being returned. The method will attempt to acquire the dogpile",
"values based on keys corresponds to that of :meth:`.Region.get_or_create`, with",
"pushed back before the expiration time so that a return+regen",
"may be passed as a callable to :meth:`.CacheRegion.cache_on_arguments`. :param should_cache_fn:",
"methods. Given the example:: class MyClass(object): @region.cache_on_arguments(namespace=\"foo\") def one(self, a,",
"backwards compatible key_generator = function_key_generator(namespace, fn) else: key_generator = function_key_generator(",
"be invoked. .. versionadded:: 0.5.1 \"\"\" self.region_invalidator.invalidate(hard) def configure_from_config(self, config_dict,",
"keys. Returns values as a list matching the keys given.",
"cached is passed as the first argument, and the arguments",
"value into the cache with the new value, as well",
"dict(zip(mangled_keys, self.backend.get_multi(mangled_keys))) for orig_key, mangled_key in orig_to_mangled.items(): with Lock( self._mutex(mangled_key),",
"be optionally passed as a ``datetime.timedelta`` value. The :meth:`.CacheRegion.get_or_create` method",
"the lock is released and a new value available. If",
"proxy.wrap(self.backend) def _mutex(self, key): return self._lock_registry.get(key) class _LockWrapper(object): \"\"\"weakref-capable wrapper",
"region.\") @property def is_configured(self): \"\"\"Return True if the backend has",
"This method is the \"multiple key\" analogue to the :meth:`.CacheRegion.cache_on_arguments`",
"True, the existing cache backend will be replaced. Without this",
"Example use cases include \"cache the result until the end",
"cache. .. versionadded:: 0.5.0 :param function_key_generator: a function that will",
"the constructor of the :class:`.CacheBackend` in use, though is typically",
"is older than the current invalidation time, the ``NO_VALUE`` token",
"Given the example:: class MyClass(object): @region.cache_on_arguments(namespace=\"foo\") def one(self, a, b):",
"else: return value return value_fn def get_multi(self, keys, expiration_time=None, ignore_expiration=False):",
"to :meth:`.CacheRegion.cache_multi_on_arguments` have the same meaning as those passed to",
"default, the configured expiration time of the :class:`.CacheRegion`, or alternatively",
"if value is NO_VALUE: return value elif expiration_time is not",
"self._is_hard_invalidated = bool(hard) self._invalidated = time.time() def is_invalidated(self, timestamp): return",
"present, but its creation time is older than the current",
"else: if expiration_time is None: expiration_time = self.expiration_time current_time =",
"mutex = self.backend.get_mutex(key) if mutex is not None: return mutex",
"sequence corresponding to the order of the keys. The method",
"% prefix, wrap=config_dict.get( \"%swrap\" % prefix, None), ) @memoized_property def",
"and is resolved by loading the class from the ``dogpile.cache``",
"v in mapping.items()) self.backend.set_multi(mapping) def delete(self, key): \"\"\"Remove a value",
"be substituted, but note this will produce unicode cache keys",
"should_cache_fn) def invalidate(*arg, **kw): key = key_generator(*arg, **kw) self.delete(key) def",
"decorator might be used as:: @my_region.cache_on_arguments(namespace=('x', 'y')) def my_function(a, b,",
") Remember that the first request for a key with",
".. versionadded:: 0.5.0 :param function_key_generator: a function that will produce",
"values as a list matching the keys given. E.g.:: values",
"``zip()``:: keys = [\"one\", \"two\", \"three\"] values = region.get_multi(keys) dictionary",
"be specified as a callable, taking no arguments, that returns",
"``False``, the decorated function should return its result as a",
"return should_cache_fn(value) result = self.get_or_create_multi( keys, dict_create, timeout, wrap_cache_fn) result",
"will cache multiple return values from the function using a",
"if a backend is already configured. .. versionadded:: 0.5.7 :param",
"value.payload, 0 else: ct = value.metadata[\"ct\"] if self.region_invalidator.is_soft_invalidated(ct): ct =",
"fn, to_str=to_str) @wraps(fn) def decorate(*arg, **kw): key = key_generator(*arg, **kw)",
"backend. ''' # if we were passed a type rather",
"from .proxy import ProxyBackend from ..util import compat import time",
"prefix. Example:: local_region = make_region() memcached_region = make_region() # regions",
"against the expiration time, rather than returning the value unconditionally.",
"the data creation function, return a new function that generates",
"somedatabase.query(key) for key in keys ] The decorated function can",
"class and wraps the attached backend. ''' # if we",
"``unicode()`` builtin can be substituted, but note this will produce",
"a ``set()`` method, which here accepts a mapping of keys",
"creation time is prior to this timestamp is considered to",
":param namespace: optional string argument which will be established as",
"= make_region( async_creation_runner=async_creation_runner, ).configure( 'dogpile.cache.memcached', expiration_time=5, arguments={ 'url': '127.0.0.1:11211', 'distributed_lock':",
"Remember that the first request for a key with no",
"new one is available. Usage of \"soft\" invalidation requires that",
"in self.__dict__ def get(self, key, expiration_time=None, ignore_expiration=False): \"\"\"Return a value",
"key: self.key_mangler(key), keys)) self.backend.delete_multi(keys) def cache_on_arguments( self, namespace=None, expiration_time=None, should_cache_fn=None,",
"dogpile system. May be passed as an integer number of",
"region was invalidated in hard mode. :return: Boolean. True if",
"raise TypeError(\"Type %s is not a valid ProxyBackend\" % type(proxy))",
"the value unconditionally. The method also interprets the cached value",
"return result def invalidate(*arg): keys = key_generator(*arg) self.delete_multi(keys) def set_(mapping):",
"timestamp < self._soft_invalidated) The custom implementation is injected into a",
"of \"soft\" invalidation requires that the region or the method",
"@memoized_property def backend(self): raise exception.RegionNotConfigured( \"No backend is configured on",
"Optional. A function that will produce a \"cache key\" given",
"value.metadata[\"ct\"] if expiration_time is None: expiration_time = self.expiration_time if (expiration_time",
"result = generate_something(5, 6) The function is also given an",
"replace_existing_backend: if True, the existing cache backend will be replaced.",
"a cache key. Given a function ``one`` inside the module",
"\"\"\"Remove a value from the cache. This operation is idempotent",
"for orig_key, mangled_key in orig_to_mangled.items(): with Lock( self._mutex(mangled_key), gen_value, lambda:",
"seealso:: :ref:`changing_backend_behavior` :param replace_existing_backend: if True, the existing cache backend",
"applied in a chain to ultimately wrap the original backend,",
"invalidation options. With \"hard\" invalidation, :meth:`.CacheRegion.get_or_create` will force an immediate",
"custom functionality augmentation can be applied. .. versionadded:: 0.5.0 ..",
"into a :class:`.CacheRegion` at configure time using the :paramref:`.CacheRegion.configure.region_invalidator` parameter::",
"'distributed_lock': True, } ) Remember that the first request for",
":meth:`.CacheRegion.get_or_create_multi` - multiple key/value version \"\"\" orig_key = key if",
"self._user_defined_key_mangler = key_mangler self.async_creation_runner = async_creation_runner self.region_invalidator = DefaultInvalidationStrategy() def",
"0.5.0 \"\"\" if not mapping: return if self.key_mangler: mapping =",
"not a number or timedelta.') if not self._user_defined_key_mangler: self.key_mangler =",
"not. If it can't, it means a different thread or",
"coerce_string_conf from .util import function_key_generator, function_multi_key_generator from .api import NO_VALUE,",
"The method also interprets the cached value in terms of",
"it returns to the calling function. A correct implementation of",
"a, b): return a + b The cache key above",
"'dogpile.cache.memcached', expiration_time=5, arguments={ 'url': '127.0.0.1:11211', 'distributed_lock': True, } ) Remember",
"(self._hard_invalidated and timestamp < self._hard_invalidated)) def was_hard_invalidated(self): return bool(self._hard_invalidated) def",
"result = dict( (k, v) for k, v in zip(cache_keys,",
"NotImplementedError() def is_invalidated(self, timestamp): \"\"\"Check timestamp to determine if it",
"self._is_hard_invalidated is False def is_soft_invalidated(self, timestamp): return self.was_soft_invalidated() and self.is_invalidated(timestamp)",
":meth:`.CacheRegion.cache_multi_on_arguments` have the same meaning as those passed to :meth:`.CacheRegion.cache_on_arguments`.",
"= time.time() def value_fn(value): if value is NO_VALUE: return value",
"and pass implementation instance to :meth:`.CacheRegion.configure` to override default region",
"set to ``None``. .. versionadded:: 0.4.2 added the async_creation_runner feature.",
"any way, and is also local to this instance of",
"the decorated function is also provided with a ``set()`` method,",
"values as a sequence corresponding to the order of the",
"``set()`` method, which here accepts a mapping of keys and",
"self.region_invalidator = region_invalidator return self def wrap(self, proxy): ''' Takes",
"terms of the current \"invalidation\" time as set by the",
"value is ignored and the ``NO_VALUE`` token is returned. Passing",
"in hard mode. \"\"\" raise NotImplementedError() class DefaultInvalidationStrategy(RegionInvalidationStrategy): def __init__(self):",
"time. May be specified as a callable, taking no arguments,",
"if it was soft invalidated. :return: Boolean. True if ``timestamp``",
"one configured on the :class:`.CacheRegion` itself. .. versionadded:: 0.5.5 ..",
"generate_something.invalidate(\"k1\", \"k2\", \"k3\") ...a ``refresh()`` method, which will call the",
"None: expiration_time = self.expiration_time current_time = time.time() def value_fn(value): if",
"= self.get_or_create_multi( keys, creator, timeout, should_cache_fn) return result def invalidate(*arg):",
"isinstance(expiration_time, Number): self.expiration_time = expiration_time elif isinstance(expiration_time, datetime.timedelta): self.expiration_time =",
"seealso:: :meth:`.CacheRegion.cache_multi_on_arguments` :meth:`.CacheRegion.get_or_create` \"\"\" def get_value(key): value = values.get(key, NO_VALUE)",
"import threading _backend_loader = PluginLoader(\"dogpile.cache\") register_backend = _backend_loader.register from .",
"call the function. See that method for additional behavioral details.",
"will force an immediate regeneration of the value which all",
"function argument in order to convert to a string. Defaults",
"string argument which will be established as part of each",
"for k, v in mapping.items()) self.backend.set_multi(mapping) def delete(self, key): \"\"\"Remove",
"expiration_time is None: expiration_time = self.expiration_time if (expiration_time is None",
"idea is to prevent deadlocks. # though haven't been able",
"region): self.region = region # ... # ... region =",
"asynchronous means the provided async_creation_runner callable implements. By default the",
"args] return generate_keys :param key_mangler: Function which will be used",
"be refreshed by whatever asynchronous means the provided async_creation_runner callable",
"need regeneration will be assembled into a new argument list,",
"arguments you'd pass to the function itself to represent a",
"same mechanism as that of :meth:`.CacheRegion.delete_multi`:: generate_something.invalidate(\"k1\", \"k2\", \"k3\") ...a",
"in keys_to_create]) timeout = expiration_time() if expiration_time_is_callable \\ else expiration_time",
"key, safely) \"\"\" if self.key_mangler: key = self.key_mangler(key) self.backend.delete(key) def",
"of, for example, a background thread, a long-running queue, or",
"aren't present in the list are returned as the ``NO_VALUE``",
"0.5.0 Added ``refresh()`` method to decorated function. Lastly, the ``get()``",
"**kw) value = fn(*arg, **kw) self.set(key, value) return value decorate.set",
":meth:`.CacheRegion.cache_on_arguments` decorator (though note: **not** the :meth:`.CacheRegion.get` method) will call",
"creation time of the retrieved value versus the current time",
"Optional. A list of :class:`.ProxyBackend` classes and/or instances, each of",
"is_hard_invalidated(self, timestamp): \"\"\"Check timestamp to determine if it was hard",
"value and persist the newly generated value in the cache.",
"backend, before being optionally processed by the key_mangler function, so",
"return its result as a list of values, and the",
"invalidation, subsequent getters will return the \"old\" value until the",
"this key against the cache. When the dogpile lock cannot",
"such as those associated with classes - note that the",
"the flag ``ignore_expiration=True`` bypasses the invalidation time check. .. versionadded::",
"decorate.invalidate = invalidate decorate.refresh = refresh decorate.get = get decorate.original",
"cached value in terms of the current \"invalidation\" time as",
"configuring a region from a config file. :param function_key_generator: Optional.",
"will also be a dictionary. If left at its default",
".proxy import ProxyBackend from ..util import compat import time import",
"analogue to the :meth:`.CacheRegion.cache_on_arguments` method. Example:: @someregion.cache_multi_on_arguments() def generate_something(*keys): return",
"arguments. The decorator internally makes use of the :meth:`.CacheRegion.get_or_create` method",
"consult the cache using the same mechanism as that of",
"def my_key_generator(namespace, fn): def generate_key(*arg, **kw): return \":\".join( [kw[k] for",
"an immediate regeneration of the value which all getters will",
"use for function # decorators, but not yet for actual",
"is returned. Passing the flag ``ignore_expiration=True`` bypasses the expiration time",
"function_key_generator self.function_multi_key_generator = function_multi_key_generator self.key_mangler = self._user_defined_key_mangler = key_mangler self.async_creation_runner",
"and ``creator()`` should return the generated values as a sequence",
"of the function using a key derived from the function",
":meth:`.CacheRegion.cache_on_arguments` method. The structure of this function should be two",
"does not affect the data in the cache in any",
"override default region invalidation. Example:: class CustomInvalidationStrategy(RegionInvalidationStrategy): def __init__(self): self._soft_invalidated",
"= region.configure(region_invalidator=CustomInvalidationStrategy()) Invalidation strategies that wish to have access to",
"``mapping`` dict. :param keys: Sequence of keys to be retrieved.",
"+ [str(x) for x in arg] ) return generate_key Where",
"the cache in any way, and is also local to",
"for invalidation of the value. Pass to ``invalidate()`` the same",
"new value into the cache with the new value, as",
"mechanics otherwise prevent the decorator from having awareness of the",
"str(a) for a in args] return generate_keys :param key_mangler: Function",
"Where the decorator might be used as:: @my_region.cache_on_arguments(namespace=('x', 'y')) def",
"current_time = time.time() def value_fn(value): if value is NO_VALUE: return",
"\"_\" + fname + \"_\".join(str(s) for s in arg) return",
"given key, or the token ``NO_VALUE`` if no such key",
"invalidated. :return: Boolean. True if ``timestamp`` is older than the",
"orig_key, mangled_key in orig_to_mangled.items(): with Lock( self._mutex(mangled_key), gen_value, lambda: get_value(mangled_key),",
"decorator from having awareness of the ``MyClass`` and ``MyOtherClass`` names,",
"cache.set(somekey, value) finally: mutex.release() thread = threading.Thread(target=runner) thread.start() region =",
"time is older than the last call to :meth:`.invalidate`. :param",
"decorate.refresh = refresh decorate.get = get decorate.original = fn return",
"None: function_multi_key_generator = self.function_multi_key_generator def decorator(fn): key_generator = function_multi_key_generator( namespace,",
"NO_VALUE: return value elif expiration_time is not None and \\",
"the :class:`.CacheRegion`, or alternatively the expiration time supplied by the",
"value.metadata[\"ct\"] > expiration_time: return NO_VALUE elif self.region_invalidator.is_invalidated( value.metadata[\"ct\"]): return NO_VALUE",
"regenerated if the creation time is older than the last",
"soft invalidation\") if expiration_time == -1: expiration_time = None mutexes",
"skipped. The ``namespace`` parameter is optional, and is used normally",
"``set()`` method to decorated function. Similar to ``set()`` is ``refresh()``.",
"it can't, it means a different thread or process is",
"if expiration_time_is_callable \\ else expiration_time if asdict: def dict_create(*keys): d_values",
"tuple, used to specify arguments to pluck from \\**kw:: def",
"or Unicode keys to bytestrings, which is needed when using",
"which will be applied in a chain to ultimately wrap",
"the keys. The method uses the same approach as :meth:`.Region.get_multi`",
"creator, mutex) else: async_creator = None with Lock( self._mutex(key), gen_value,",
"passed, as well as an optional \"namespace\" parameter in order",
"on the given arguments. Such as:: def my_key_generator(namespace, fn, **kw):",
"key_lookup = dict(zip(keys, cache_keys)) @wraps(fn) def creator(*keys_to_create): return fn(*[key_lookup[k] for",
"_unexpired_value_fn(self, expiration_time, ignore_expiration): if ignore_expiration: return lambda value: value else:",
"value to be cached is passed as the first argument,",
"it can be passed as a tuple, used to specify",
"is still returned, but isn't cached. .. versionadded:: 0.5.0 ..",
"def cache_on_arguments( self, namespace=None, expiration_time=None, should_cache_fn=None, to_str=compat.string_type, function_key_generator=None): \"\"\"A function",
"if ``timestamp`` is older than the last region invalidation time.",
"Override default invalidation strategy with custom implementation of :class:`.RegionInvalidationStrategy`. ..",
"result. Example use cases include \"cache the result until the",
"return self.async_creation_runner( self, orig_key, creator, mutex) else: async_creator = None",
"get_value(key): value = values.get(key, NO_VALUE) if (value is NO_VALUE or",
"as a list matching the keys given. E.g.:: values =",
"data in the cache in any way, and is also",
"region = CacheRegion() region = region.configure(region_invalidator=MyInvalidator(region)) .. versionadded:: 0.6.2 ..",
") The ``namespace`` is that passed to :meth:`.CacheRegion.cache_on_arguments`. It's not",
"\"\"\"Return a value from the cache, based on the given",
"of the current \"invalidation\" time as set by the :meth:`.invalidate`",
"``str()``. If the function accepts non-ascii unicode arguments on Python",
"were to produce the value ``3`` as the value to",
"\"dogpile.cache.dbm\", expiration_time=300, arguments={ \"filename\":\"file.dbm\" } ) The ``namespace`` is that",
"None if self.async_creation_runner: def async_creator(mutex): return self.async_creation_runner( self, orig_key, creator,",
"list matching the keys given. E.g.:: values = region.get_multi([\"one\", \"two\",",
"def one(self, a, b): return a + b The cache",
"[kw[k] for k in namespace] + [str(x) for x in",
"you are using a :class:`.CacheBackend` or :class:`.ProxyBackend` that modifies values,",
"keys): \"\"\"Remove multiple values from the cache. This operation is",
"get(*arg, **kw): key = key_generator(*arg, **kw) return self.get(key) def refresh(*arg,",
"the original backend, so that custom functionality augmentation can be",
"use cases include \"cache the result until the end of",
"produce unicode cache keys which may require key mangling before",
"cached. .. versionadded:: 0.5.0 .. seealso:: :meth:`.CacheRegion.cache_multi_on_arguments` :meth:`.CacheRegion.get_or_create` \"\"\" def",
"be passed as a callable to :meth:`.CacheRegion.cache_on_arguments`. :param should_cache_fn: passed",
"= key_generator(*arg) self.delete_multi(keys) def set_(mapping): keys = list(mapping) gen_keys =",
"in mapping.items()) self.backend.set_multi(mapping) def delete(self, key): \"\"\"Remove a value from",
"not replace_existing_backend: raise exception.RegionAlreadyConfigured( \"This region is already \" \"configured",
"expiration_time return self.get_or_create(key, creator, timeout, should_cache_fn) def invalidate(*arg, **kw): key",
"will be used. A typical mangler is the SHA1 mangler",
"import with_statement from .. import Lock, NeedRegenerationException from ..util import",
"a chain to ultimately wrap the original backend, so that",
"example using async_creation_runner, new values can be created in a",
"as the ``NO_VALUE`` token. ``NO_VALUE`` evaluates to False, but is",
"as an optional \"namespace\" parameter in order to generate a",
"self.is_invalidated(timestamp) def was_soft_invalidated(self): return self._is_hard_invalidated is False def is_soft_invalidated(self, timestamp):",
"time check. .. versionchanged:: 0.3.0 :meth:`.CacheRegion.get` now checks the value's",
"arguments=None, _config_argument_dict=None, _config_prefix=None, wrap=None, replace_existing_backend=False, region_invalidator=None ): \"\"\"Configure a :class:`.CacheRegion`.",
"yet for actual caching # later, when config is available",
"incoming keys before passing to the backend. Defaults to ``None``,",
"expiration_time=None, ignore_expiration=False): \"\"\"Return multiple values from the cache, based on",
"value in ( _unexpired_value_fn(value) for value in backend_values ) ]",
"already configured. .. versionadded:: 0.5.7 :param region_invalidator: Optional. Override default",
"self.set_multi( dict(zip(keys, [values[a] for a in arg])) ) return values",
"value_version }) def set(self, key, value): \"\"\"Place a new value",
"invalidation time. \"\"\" raise NotImplementedError() def was_soft_invalidated(self): \"\"\"Indicate the region",
"also interprets the cached value in terms of the current",
"'expiration_time is not a number or timedelta.') if not self._user_defined_key_mangler:",
"value:: newvalue = generate_something.refresh(5, 6) .. versionadded:: 0.5.0 Added ``refresh()``",
":param async_creation_runner: A callable that, when specified, will be passed",
"on a sequence of keys. The behavior for generation of",
"async_creator(key, mutex): mutexes[key] = mutex if expiration_time is None: expiration_time",
"will wait for. With \"soft\" invalidation, subsequent getters will return",
"invalidation system works by setting a current timestamp (using ``time.time()``)",
"= time.time() else: self._soft_invalidated = time.time() self._hard_invalidated = None def",
"should_cache_fn: passed to :meth:`.CacheRegion.get_or_create`. .. versionadded:: 0.4.3 :param to_str: callable,",
"prefix, wrap=config_dict.get( \"%swrap\" % prefix, None), ) @memoized_property def backend(self):",
"way, and is also local to this instance of :class:`.CacheRegion`.",
"returned. Passing the flag ``ignore_expiration=True`` bypasses the expiration time check.",
"be cached or not. If it returns False, the value",
"values it returns to the calling function. A correct implementation",
"values_w_created = dict( (orig_to_mangled[k], self._value(v)) for k, v in zip(keys_to_get,",
"None self._hard_invalidated = None def invalidate(self, hard=None): if hard: self._soft_invalidated",
"then return True or False, indicating if the value should",
"versionadded:: 0.5.1 \"\"\" self.region_invalidator.invalidate(hard) def configure_from_config(self, config_dict, prefix): \"\"\"Configure from",
"generated values as a sequence corresponding to the order of",
"value.metadata[\"ct\"] if self.region_invalidator.is_soft_invalidated(ct): ct = time.time() - expiration_time - .0001",
"\"\"\"Return a cached value based on the given key. If",
"Example:: local_region = make_region() memcached_region = make_region() # regions are",
"non-None expiration time. .. versionadded:: 0.3.0 :param hard: if True,",
"# backwards compatible key_generator = function_key_generator(namespace, fn) else: key_generator =",
"NotImplementedError() def is_soft_invalidated(self, timestamp): \"\"\"Check timestamp to determine if it",
"= _backend_loader.register from . import backends # noqa value_version =",
"be needed to disambiguate functions of the same name within",
"of keys derived from the function itself and the arguments",
"\"\"\"Region invalidation strategy interface Implement this interface and pass implementation",
"to replace.\" % self.backend) backend_cls = _backend_loader.load(backend) if _config_argument_dict: self.backend",
"__init__(self, region): self.region = region # ... # ... region",
"basis using the ``function_key_generator`` argument present on :func:`.make_region` and :class:`.CacheRegion`.",
"else: mangled_keys = sorted_unique_keys orig_to_mangled = dict(zip(sorted_unique_keys, mangled_keys)) values =",
"the same name within the same source file, such as",
"flag ``ignore_expiration=True`` bypasses the expiration time check. .. versionadded:: 0.5.0",
"access to the :class:`.CacheRegion` itself should construct the invalidator given",
"to :meth:`.CacheRegion.cache_on_arguments`. It's not consulted outside this function, so in",
"invalidate(self, hard=True): self._is_hard_invalidated = bool(hard) self._invalidated = time.time() def is_invalidated(self,",
"to specify arguments to pluck from \\**kw:: def my_key_generator(namespace, fn):",
"from . import backends # noqa value_version = 1 \"\"\"An",
"will still return promptly. They will be refreshed by whatever",
"the ``expiration_time`` argument, is tested against the creation time of",
"return (self._soft_invalidated and timestamp < self._soft_invalidated) The custom implementation is",
"the region was invalidated in hard mode. :return: Boolean. True",
"This operation is idempotent (can be called multiple times, or",
"stale, the cached value is ignored and the ``NO_VALUE`` token",
"used as the ``expiration_time``. This callable will be called whenever",
"keys which may require key mangling before reaching the cache.",
"configured via the :meth:`.CacheRegion.configure` method already. .. versionadded:: 0.5.1 \"\"\"",
":param backend: Required. This is the name of the :class:`.CacheBackend`",
"invokes ``.set_multi()`` for newly generated values using the same values",
"using async_creation_runner, new values can be created in a background",
"as well as the :meth:`.CacheRegion.cache_on_arguments` decorator (though note: **not** the",
"1 \"\"\"An integer placed in the :class:`.CachedValue` so that new",
"cached value based on the given key. If the value",
"dict(zip(keys, [values[a] for a in arg])) ) return values else:",
"backend is configured on this region.\") @property def is_configured(self): \"\"\"Return",
"without calling the decorated function. The value to be cached",
"normally to disambiguate two functions of the same name within",
"of each key. It will then consult the cache using",
"defer the computation of expensive creator functions to later points",
"\"cache the result until the end of the day, week",
"the same mechanism as that of :meth:`.CacheRegion.delete_multi`:: generate_something.invalidate(\"k1\", \"k2\", \"k3\")",
"= None def is_invalidated(self, timestamp): return ((self._soft_invalidated and timestamp <",
"subsequent getters will return the \"old\" value until the new",
"a configuration dictionary and a prefix. Example:: local_region = make_region()",
":meth:`.CacheRegion.get_or_create` will force an immediate regeneration of the value which",
"function decorator that will cache the return value of the",
"value.metadata['v'] != value_version or self.region_invalidator.is_hard_invalidated( value.metadata[\"ct\"])): raise NeedRegenerationException() ct =",
"new values in the cache under the given keys. ..",
"a specific example using async_creation_runner, new values can be created",
"method, which has the effect of deleting the given sequence",
"arg])) ) return values else: self.set_multi( dict(zip(keys, values)) ) return",
"invalidator given the region as an argument:: class MyInvalidator(RegionInvalidationStrategy): def",
"for a in args] return generate_keys :param key_mangler: Function which",
"is None and self.region_invalidator.was_soft_invalidated()): raise exception.DogpileCacheException( \"Non-None expiration time required",
"with the exception that the ``creator()`` function may be asked",
"of keys and returns a sequence of new values. :param",
"[values[orig_to_mangled[k]].payload for k in keys] finally: for mutex in mutexes.values():",
"uses keyword arguments :param function_multi_key_generator: Optional. Similar to ``function_key_generator`` parameter,",
".0001 return value.payload, ct def gen_value(): created_value = creator() value",
"to ``creator()``, and ``creator()`` should return the generated values as",
"be cached. .. versionadded:: 0.4.3 .. seealso:: :meth:`.CacheRegion.cache_on_arguments` - applies",
"and timestamp < self._soft_invalidated) or (self._hard_invalidated and timestamp < self._hard_invalidated))",
"accepts a sequence of keys and returns a sequence of",
"a non-existent key, safely) \"\"\" if self.key_mangler: key = self.key_mangler(key)",
"self._invalidated) def was_hard_invalidated(self): return self._is_hard_invalidated is True def is_hard_invalidated(self, timestamp):",
"keys] def wrap_cache_fn(value): if value is NO_VALUE: return False elif",
"asdict: if ``True``, the decorated function should return its result",
"prior to this timestamp is considered to be stale. It",
"caching # later, when config is available myconfig = {",
"b): return a + b Above, calling ``one(3, 4)`` will",
"expiration_time_is_callable \\ else expiration_time if asdict: def dict_create(*keys): d_values =",
"checks the value's creation time against the expiration time, rather",
"mutexes = {} sorted_unique_keys = sorted(set(keys)) if self.key_mangler: mangled_keys =",
"def generate_something(x, y): return somedatabase.query(x, y) The decorated function can",
"the module name for the function, the arguments passed, as",
"one(self, a, b): return a + b The cache key",
"[values[a] for a in arg])) ) return values else: self.set_multi(",
"argument, is tested against the creation time of the retrieved",
"mangled_keys)) values = dict(zip(mangled_keys, self.backend.get_multi(mangled_keys))) for orig_key, mangled_key in orig_to_mangled.items():",
"``None`` to distinguish between a cached value of ``None``. By",
"retrieved value versus the current time (as reported by ``time.time()``).",
"'url': '127.0.0.1:11211', 'distributed_lock': True, } ) Remember that the first",
"somemethod(self, x, y): \"\" Above, the ``namespace`` parameter disambiguates between",
"key_generator(*arg, **kw) key_lookup = dict(zip(keys, cache_keys)) @wraps(fn) def creator(*keys_to_create): return",
"its creation time is older than the current invalidation time,",
"promptly. They will be refreshed by whatever asynchronous means the",
"self.backend.set(key, value) return value.payload, value.metadata[\"ct\"] if expiration_time is None: expiration_time",
"retrieved. :param creator: function which accepts a sequence of keys",
"can be used to defer the computation of expensive creator",
"is None: expiration_time = self.expiration_time if (expiration_time is None and",
"@region.cache_on_arguments(namespace=\"foo\") def one(a, b): return a + b Above, calling",
"= dict(zip(mangled_keys, self.backend.get_multi(mangled_keys))) for orig_key, mangled_key in orig_to_mangled.items(): with Lock(",
"should construct the invalidator given the region as an argument::",
"the \"multiple key\" analogue to the :meth:`.CacheRegion.cache_on_arguments` method. Example:: @someregion.cache_multi_on_arguments()",
"values decorate.set = set_ decorate.invalidate = invalidate decorate.refresh = refresh",
"value.metadata[\"ct\"])): raise NeedRegenerationException() ct = value.metadata[\"ct\"] if self.region_invalidator.is_soft_invalidated(ct): ct =",
"= expiration_time() if expiration_time_is_callable \\ else expiration_time return self.get_or_create(key, creator,",
"import wraps import threading _backend_loader = PluginLoader(\"dogpile.cache\") register_backend = _backend_loader.register",
"not. If it returns False, the value is still returned,",
"the value to be cached. .. versionadded:: 0.4.1 Added ``set()``",
"Python 2.x in conjunction with Unicode keys. :param async_creation_runner: A",
"can be called normally. The decorator will produce a list",
"While it's typical for a key to be a string,",
"the optional namespace and with the string form of each",
"the cached function result. Example use cases include \"cache the",
"methods as below:: class MyClass(object): @region.cache_on_arguments(namespace='MC') def somemethod(self, x, y):",
"keys_to_create]) timeout = expiration_time() if expiration_time_is_callable \\ else expiration_time if",
"the value and persist the newly generated value in the",
"value = fn(*arg, **kw) self.set(key, value) return value decorate.set =",
"times or whether or not :meth:`.invalidate` was called. .. versionadded::",
"NotImplementedError() def was_hard_invalidated(self): \"\"\"Indicate the region was invalidated in hard",
"considered to be expired based on its creation time, the",
"value. The :meth:`.CacheRegion.get_or_create` method as well as the :meth:`.CacheRegion.cache_on_arguments` decorator",
"if should_cache_fn(v[0]) )) values.update(values_w_created) return [values[orig_to_mangled[k]].payload for k in keys]",
"can't, it means a different thread or process is already",
"def was_soft_invalidated(self): \"\"\"Indicate the region was invalidated in soft mode.",
"since the last generation. :param arguments: Optional. The structure here",
"y): return somedatabase.query(x, y) The decorated function can then be",
"will invoke the decorated function and populate a new value",
"of ``myapp.tools:one|foo|3 4`` - the name ``self`` is skipped. The",
"\"\" Above, the ``namespace`` parameter disambiguates between ``somemethod`` on ``MyClass``",
"itself is called, in caching or retrieving. Thus, this can",
"def async_creator(key, mutex): mutexes[key] = mutex if expiration_time is None:",
"this will produce unicode cache keys which may require key",
"to produce the value ``3`` as the value to be",
"mutex): ''' Used by dogpile.core:Lock when appropriate ''' def runner():",
"mutex else: return self._LockWrapper() def invalidate(self, hard=True): \"\"\"Invalidate this :class:`.CacheRegion`.",
"future by way of, for example, a background thread, a",
"\"\"\" if self.key_mangler: key = self.key_mangler(key) value = self.backend.get(key) value",
"a creation function for this key against the cache. When",
"if self.key_mangler: key = self.key_mangler(key) self.backend.set(key, self._value(value)) def set_multi(self, mapping):",
"extra caching possibilities relative to the function. This is a",
"\"k3\") ...and a ``get()`` method, which will return values based",
"present, the method returns the token ``NO_VALUE``. ``NO_VALUE`` evaluates to",
"creator(*keys_to_get) values_w_created = dict( (orig_to_mangled[k], self._value(v)) for k, v in",
":meth:`.CacheRegion.get_or_create` \"\"\" expiration_time_is_callable = compat.callable(expiration_time) if function_key_generator is None: function_key_generator",
"6) .. versionadded:: 0.5.0 Added ``refresh()`` method to decorated function.",
"cached. .. versionadded:: 0.4.3 .. seealso:: :meth:`.CacheRegion.cache_on_arguments` - applies :meth:`.get_or_create`",
"local to this instance of :class:`.CacheRegion`. Once set, the invalidation",
"available. Usage of \"soft\" invalidation requires that the region or",
"``ignore_expiration=True`` bypasses the expiration time check. .. versionchanged:: 0.3.0 :meth:`.CacheRegion.get`",
"value is present, but its creation time is older than",
"its default value of ``False``, the decorated function should return",
"bsddb or dbm under Python 2.x in conjunction with Unicode",
") return values decorate.set = set_ decorate.invalidate = invalidate decorate.refresh",
"the :class:`.CacheRegion` itself. .. versionadded:: 0.3.0 :param ignore_expiration: if ``True``,",
"the expiration time check. .. versionadded:: 0.5.0 \"\"\" if not",
"is not None and timestamp < self._invalidated) def was_hard_invalidated(self): return",
"True else: return should_cache_fn(value) result = self.get_or_create_multi( keys, dict_create, timeout,",
"is unconditionally prevented from being returned. The method will attempt",
"region = region.configure(region_invalidator=MyInvalidator(region)) .. versionadded:: 0.6.2 .. seealso:: :paramref:`.CacheRegion.configure.region_invalidator` \"\"\"",
"be expired based on its creation time, the given creation",
"and/or instances, each of which will be applied in a",
"access the cache and conditionally call the function. See that",
"cache and conditionally call the function. See that method for",
"new value. :param expiration_time: optional expiration time which will overide",
"passed to and called by dogpile.lock when there is a",
"generated value in the cache. Whether or not the function",
":class:`.CacheRegion` if not None. To set no expiration, use the",
"generate any subset of the given keys. The list of",
"in caching or retrieving. Thus, this can be used to",
"dogpile.cache can detect cached values from a previous, backwards-incompatible version.",
"\"\"\" orig_key = key if self.key_mangler: key = self.key_mangler(key) def",
"+ str(a) for a in args] return generate_keys :param key_mangler:",
"__init__(self): self._is_hard_invalidated = None self._invalidated = None def invalidate(self, hard=True):",
"is ignored and the ``NO_VALUE`` token is returned. Passing the",
"prefix], expiration_time=config_dict.get( \"%sexpiration_time\" % prefix, None), _config_argument_dict=config_dict, _config_prefix=\"%sarguments.\" % prefix,",
"representing the \"minimum creation time\" for a value. Any retrieved",
"is already configured. .. versionadded:: 0.5.7 :param region_invalidator: Optional. Override",
"is the \"multiple key\" analogue to the :meth:`.CacheRegion.cache_on_arguments` method. Example::",
"= time.time() def is_invalidated(self, timestamp): return (self._invalidated is not None",
"is honored by the :meth:`.CacheRegion.get_or_create`, :meth:`.CacheRegion.get_or_create_multi` and :meth:`.CacheRegion.get` methods. The",
"token is returned. Passing the flag ``ignore_expiration=True`` bypasses the expiration",
"on the :class:`.CacheRegion` itself. .. versionadded:: 0.3.0 :param ignore_expiration: if",
":param should_cache_fn: optional callable function which will receive each value",
"in the cache under the given keys. .. versionadded:: 0.5.0",
"to_str: callable, will be called on each function argument in",
"self._soft_invalidated = None self._hard_invalidated = None def invalidate(self, hard=None): if",
"from the function using a sequence of keys derived from",
"+ \"_\".join(str(s) for s in arg) return generate_key region =",
"default the async_creation_runner is disabled and is set to ``None``.",
"by the decorated function is missing keys, those keys will",
"as a callable, taking no arguments, that returns a value",
"called by dogpile.lock when there is a stale value present",
"optional string argument which will be established as part of",
"be passed the mutex and is responsible releasing that mutex",
"asdict: def dict_create(*keys): d_values = creator(*keys) return [ d_values.get(key_lookup[k], NO_VALUE)",
"region was invalidated in soft mode. \"\"\" raise NotImplementedError() def",
"is_soft_invalidated(self, timestamp): return (self._soft_invalidated and timestamp < self._soft_invalidated) The custom",
"= key_mangler self.async_creation_runner = async_creation_runner self.region_invalidator = DefaultInvalidationStrategy() def configure(",
"attribute ``invalidate()``, which provides for invalidation of the value. Pass",
"keys before passing to the backend. Defaults to ``None``, in",
"from the cache, based on the given key. If the",
"a cached value based on the given key. If the",
"sorted_unique_keys orig_to_mangled = dict(zip(sorted_unique_keys, mangled_keys)) values = dict(zip(mangled_keys, self.backend.get_multi(mangled_keys))) for",
"function, cache the new values, and return them:: values =",
"async_creation_runner self.region_invalidator = DefaultInvalidationStrategy() def configure( self, backend, expiration_time=None, arguments=None,",
"y) The decorated function can then be called normally, where",
"with the new value, as well as returning that value::",
"``get()`` method to decorated function. The default key generation will",
"all current values; the originally passed keys corresponding to those",
"provided async_creation_runner callable implements. By default the async_creation_runner is disabled",
"config_dict, prefix): \"\"\"Configure from a configuration dictionary and a prefix.",
"current_time - value.metadata[\"ct\"] > expiration_time: return NO_VALUE elif self.region_invalidator.is_invalidated( value.metadata[\"ct\"]):",
"dogpile.lock when there is a stale value present in the",
"the ``unicode()`` builtin can be substituted, but note this will",
"0.5.0 \"\"\" if not keys: return [] if self.key_mangler: keys",
"keys derived from the function itself and the arguments passed",
"hard mode. \"\"\" raise NotImplementedError() def is_soft_invalidated(self, timestamp): \"\"\"Check timestamp",
"decorated function will also be a dictionary. If left at",
"used internally but can be accessed via the ``.name`` parameter,",
"function_key_generator=function_key_generator, function_multi_key_generator=function_multi_key_generator, key_mangler=None, async_creation_runner=None, ): \"\"\"Construct a new :class:`.CacheRegion`.\"\"\" self.name",
"is passed directly to the constructor of the :class:`.CacheBackend` in",
"self.key_mangler: key = self.key_mangler(key) value = self.backend.get(key) value = self._unexpired_value_fn(",
"the given keys. The list of keys to be generated",
"well as the :meth:`.CacheRegion.cache_on_arguments` decorator (though note: **not** the :meth:`.CacheRegion.get`",
"the keys, the idea is to prevent deadlocks. # though",
"= generate_something.get(5, 6) .. versionadded:: 0.5.3 Added ``get()`` method to",
"region is already \" \"configured with backend: %s. \" \"Specify",
"or time passes\". .. versionchanged:: 0.5.0 ``expiration_time`` may be passed",
"modifies values, take note this function invokes ``.set_multi()`` for newly",
"mutex.release() def _value(self, value): \"\"\"Return a :class:`.CachedValue` given a value.\"\"\"",
"region was invalidated in hard mode. \"\"\" raise NotImplementedError() class",
"argument present on :func:`.make_region` and :class:`.CacheRegion`. If defaults to :func:`.function_key_generator`.",
"a function as the class is being declared. :param expiration_time:",
"to the function. This is a convenience method for :meth:`.CacheRegion.set`",
"be of any type recognized by the backend or by",
"..util import NameRegistry from . import exception from ..util import",
"missing keys, those keys will not be cached. :param to_str:",
"by whatever asynchronous means the provided async_creation_runner callable implements. By",
"by way of, for example, a background thread, a long-running",
"coerces keys into a SHA1 hash, so that the string",
"in soft mode. :return: Boolean. True if region was invalidated",
"cache keys which may require key mangling before reaching the",
"implements. By default the async_creation_runner is disabled and is set",
"if _config_argument_dict: self.backend = backend_cls.from_config_dict( _config_argument_dict, _config_prefix ) else: self.backend",
"which aren't generated or need regeneration will be assembled into",
"NeedRegenerationException from ..util import NameRegistry from . import exception from",
"will be replaced. Without this flag, an exception is raised",
"Key to be retrieved. While it's typical for a key",
"ProxyBackend instance or class and wraps the attached backend. '''",
"bypasses the expiration time check. .. versionadded:: 0.5.0 \"\"\" if",
"a particular value:: generate_something.invalidate(5, 6) Another attribute ``set()`` is added",
"will store a given value directly without calling the decorated",
"of each cache key. :param expiration_time: if not None, will",
"hard=None): if hard: self._soft_invalidated = None self._hard_invalidated = time.time() else:",
"it returns False, the value is still returned, but isn't",
"\"\"\" config_dict = coerce_string_conf(config_dict) return self.configure( config_dict[\"%sbackend\" % prefix], expiration_time=config_dict.get(",
"should_cache_fn: optional callable function which will receive each value returned",
"in values_w_created.items() if should_cache_fn(v[0]) )) values.update(values_w_created) return [values[orig_to_mangled[k]].payload for k",
"expiration time check. .. versionchanged:: 0.3.0 :meth:`.CacheRegion.get` now checks the",
"as that of :meth:`.CacheRegion.delete_multi`:: generate_something.invalidate(\"k1\", \"k2\", \"k3\") ...a ``refresh()`` method,",
"is_soft_invalidated(self, timestamp): return self.was_soft_invalidated() and self.is_invalidated(timestamp) class CacheRegion(object): \"\"\"A front",
"cache backend. :param name: Optional, a string name for the",
"call. The default invalidation system works by setting a current",
"time passed to the dogpile system. May be passed as",
"self.get_or_create_multi( keys, creator, timeout, should_cache_fn) return result def invalidate(*arg): keys",
"mutexes.values(): mutex.release() def _value(self, value): \"\"\"Return a :class:`.CachedValue` given a",
"current invalidation time, the ``NO_VALUE`` token is returned. Passing the",
"should_cache_fn: optional callable function which will receive the value returned",
"in mutexes.values(): mutex.release() def _value(self, value): \"\"\"Return a :class:`.CachedValue` given",
"DefaultInvalidationStrategy() def configure( self, backend, expiration_time=None, arguments=None, _config_argument_dict=None, _config_prefix=None, wrap=None,",
"keys as arguments. Like :meth:`.CacheRegion.cache_on_arguments`, the decorated function is also",
"is a passthrough to :class:`.CacheRegion`. See that class for constructor",
"value from the cache. This operation is idempotent (can be",
"with a single function signature, one which takes a simple",
"- .0001 return value.payload, ct def gen_value(): created_value = creator()",
"(using ``time.time()``) to consider all older timestamps effectively invalidated. \"\"\"",
"current \"invalidation\" time as set by the :meth:`.invalidate` method. If",
"arguments, that returns a value to be used as the",
"method, which will call the creation function, cache the new",
"keys)) backend_values = self.backend.get_multi(keys) _unexpired_value_fn = self._unexpired_value_fn( expiration_time, ignore_expiration) return",
"in arg] ) return generate_key Where the decorator might be",
"expiration time already configured on this :class:`.CacheRegion` if not None.",
"\"two\", \"three\"]) To convert values to a dictionary, use ``zip()``::",
"arguments={ \"filename\":\"file.dbm\" } ) The ``namespace`` is that passed to",
"None with Lock( self._mutex(key), gen_value, get_value, expiration_time, async_creator) as value:",
"region_invalidator: self.region_invalidator = region_invalidator return self def wrap(self, proxy): '''",
"on the submitted ``mapping`` dict. :param keys: Sequence of keys",
"return value_fn def get_multi(self, keys, expiration_time=None, ignore_expiration=False): \"\"\"Return multiple values",
"from a configuration dictionary and a prefix. Example:: local_region =",
"values, take note this function invokes ``.set_multi()`` for newly generated",
"provides for invalidation of the value. Pass to ``invalidate()`` the",
"function should be two levels: given the data creation function,",
"be a string, it is ultimately passed directly down to",
"current timestamp (using ``time.time()``) representing the \"minimum creation time\" for",
"keys->values, and the final result of calling the decorated function",
"this interface and pass implementation instance to :meth:`.CacheRegion.configure` to override",
"the configured expiration time of the :class:`.CacheRegion`, or alternatively the",
"for generation of values based on keys corresponds to that",
"region_invalidator: Optional. Override default invalidation strategy with custom implementation of",
"if function_key_generator is None: function_key_generator = self.function_key_generator def decorator(fn): if",
"be called multiple times, or on a non-existent key, safely)",
"the last region invalidation time and region is invalidated in",
"for k in namespace] + [str(x) for x in arg]",
"if no previous value is available, until the lock is",
"with that subset of arguments. The returned result is a",
"def gen_value(): raise NotImplementedError() def async_creator(key, mutex): mutexes[key] = mutex",
"key_generator(*arg) values = fn(*arg) if asdict: self.set_multi( dict(zip(keys, [values[a] for",
"decorate.get = get return decorate return decorator def make_region(*arg, **kw):",
"== type: proxy = proxy() if not issubclass(type(proxy), ProxyBackend): raise",
"``False``. Another typical mangler is the built-in Python function ``str``,",
"hash, so that the string length is fixed. To disable",
"is disabled and is set to ``None``. .. versionadded:: 0.4.2",
"the decorated function itself is called, in caching or retrieving.",
"return self.get(key) def refresh(*arg, **kw): key = key_generator(*arg, **kw) value",
"in zip(cache_keys, result) if v is not NO_VALUE) else: result",
"a value from the cache, based on the given key.",
"in mapping.items()) else: mapping = dict((k, self._value(v)) for k, v",
"typically a dictionary. :param wrap: Optional. A list of :class:`.ProxyBackend`",
"method for :meth:`.CacheRegion.set` which will store a given value directly",
"The default invalidation system works by setting a current timestamp",
"argument list, and the decorated function is then called with",
"values based on the given arguments:: values = generate_something.get(\"k1\", \"k2\",",
"but can be accessed via the ``.name`` parameter, helpful for",
"arguments on Python 2.x, the ``unicode()`` builtin can be substituted,",
"async_creation_runner, new values can be created in a background thread",
"by ``time.time()``). If stale, the cached value is ignored and",
"returns either the value cached for the given key, or",
"if region was invalidated in hard mode. \"\"\" raise NotImplementedError()",
"valid ProxyBackend\" % type(proxy)) self.backend = proxy.wrap(self.backend) def _mutex(self, key):",
"True if ``timestamp`` is older than the last region invalidation",
"to convert non-string or Unicode keys to bytestrings, which is",
"in the cache. It will be passed the mutex and",
"dogpile logic won't be used. If False, the creation time",
"that will produce a \"cache key\". This function will supersede",
"seealso:: :paramref:`.CacheRegion.configure.region_invalidator` \"\"\" def invalidate(self, hard=True): \"\"\"Region invalidation. :class:`.CacheRegion` propagated",
"= self.key_mangler(key) self.backend.set(key, self._value(value)) def set_multi(self, mapping): \"\"\"Place new values",
"or ``cls``, making the decorator suitable (with caveats) for use",
"declaration mechanics otherwise prevent the decorator from having awareness of",
"long-running queue, or a task manager system like Celery. For",
"using a :class:`.CacheBackend` or :class:`.ProxyBackend` that modifies values, take note",
"returns a sequence of new values. :param expiration_time: optional expiration",
"key generator will ignore an initial argument of ``self`` or",
"decorator that will cache multiple return values from the function",
"= self.backend.get_multi(keys) _unexpired_value_fn = self._unexpired_value_fn( expiration_time, ignore_expiration) return [ value.payload",
"my_key_generator(namespace, fn, **kw): fname = fn.__name__ def generate_key(*arg): return namespace",
"or by the key_mangler function, if present. :param creator: function",
"Optional. Similar to ``function_key_generator`` parameter, but it's used in :meth:`.CacheRegion.cache_multi_on_arguments`.",
"\"This region is already \" \"configured with backend: %s. \"",
"keys corresponds to that of :meth:`.Region.get_or_create`, with the exception that",
"the ``namespace`` parameter disambiguates between ``somemethod`` on ``MyClass`` and ``MyOtherClass``.",
"key as follows:: myapp.tools:one|foo|3 4 The key generator will ignore",
"self._is_hard_invalidated is True def is_hard_invalidated(self, timestamp): return self.was_hard_invalidated() and self.is_invalidated(timestamp)",
"ignore_expiration: if ``True``, the value is returned from the cache",
"self._mutex(mangled_key), gen_value, lambda: get_value(mangled_key), expiration_time, async_creator=lambda mutex: async_creator(orig_key, mutex) ):",
"of keys->values, and the final result of calling the decorated",
"namespace, fn, to_str=to_str) @wraps(fn) def decorate(*arg, **kw): key = key_generator(*arg,",
"function, so in fact can be of any form. For",
"``NO_VALUE`` if no such key exists:: value = generate_something.get(5, 6)",
"decorator itself can't see the parent class on a function",
"keys to be retrieved. :param creator: function which accepts a",
"result as a list of values, and the final result",
"set in the cache:: generate_something.set({\"k1\": \"value1\", \"k2\": \"value2\", \"k3\": \"value3\"})",
"b Above, calling ``one(3, 4)`` will produce a cache key",
"the last region invalidation time. \"\"\" raise NotImplementedError() def was_soft_invalidated(self):",
"self._invalidated = None def invalidate(self, hard=True): self._is_hard_invalidated = bool(hard) self._invalidated",
"To convert values to a dictionary, use ``zip()``:: keys =",
"dictionary and a prefix. Example:: local_region = make_region() memcached_region =",
"asdict=False, to_str=compat.string_type, function_multi_key_generator=None): \"\"\"A function decorator that will cache multiple",
"@region.cache_on_arguments(namespace=\"foo\") def one(self, a, b): return a + b The",
"keys. This function will supersede the one configured on the",
"hard=True): \"\"\"Invalidate this :class:`.CacheRegion`. The default invalidation system works by",
"Above, the function returns the value of create_value() if the",
"By default the async_creation_runner is disabled and is set to",
"-1. :param should_cache_fn: optional callable function which will receive the",
"and timestamp < self._soft_invalidated) The custom implementation is injected into",
"of keys and values to set in the cache:: generate_something.set({\"k1\":",
"expiration_time_is_callable \\ else expiration_time return self.get_or_create(key, creator, timeout, should_cache_fn) def",
"in use, though is typically a dictionary. :param wrap: Optional.",
"\"v\": value_version }) def set(self, key, value): \"\"\"Place a new",
"The structure of this function should be two levels: given",
"NameRegistry from . import exception from ..util import PluginLoader, memoized_property,",
"in fact can be of any form. For example, it",
"is already running a creation function for this key against",
"self._LockWrapper() def invalidate(self, hard=True): \"\"\"Invalidate this :class:`.CacheRegion`. The default invalidation",
"return value.payload, value.metadata[\"ct\"] if expiration_time is None: expiration_time = self.expiration_time",
"calling ``generate_something(5, 6)``, if the function were to produce the",
"a background thread like so:: import threading def async_creation_runner(cache, somekey,",
"When the dogpile lock cannot be acquired, the method will",
"times, or on a non-existent key, safely) \"\"\" if self.key_mangler:",
"produce a \"cache key\" given a data creation function and",
":class:`.CacheRegion` at configure time using the :paramref:`.CacheRegion.configure.region_invalidator` parameter:: region =",
"recreate the value and persist the newly generated value in",
"the function using a key derived from the function itself",
"**kw) self.set(key, value) def get(*arg, **kw): key = key_generator(*arg, **kw)",
"isn't cached. .. versionadded:: 0.5.0 .. seealso:: :meth:`.CacheRegion.cache_multi_on_arguments` :meth:`.CacheRegion.get_or_create` \"\"\"",
"return value def get_or_create_multi( self, keys, creator, expiration_time=None, should_cache_fn=None): \"\"\"Return",
"= make_region() # regions are ready to use for function",
"0.5.1 \"\"\" self.region_invalidator.invalidate(hard) def configure_from_config(self, config_dict, prefix): \"\"\"Configure from a",
"wait=True): return self.lock.acquire(wait) def release(self): self.lock.release() def _create_mutex(self, key): mutex",
"in-place on the submitted ``mapping`` dict. :param keys: Sequence of",
"detect cached values from a previous, backwards-incompatible version. \"\"\" class",
"lock cannot be acquired, the method will block if no",
"True, cache values will all require immediate regeneration; dogpile logic",
"hard mode. :return: Boolean. True if region was invalidated in",
"attached backend. ''' # if we were passed a type",
"return NO_VALUE else: return value return value_fn def get_multi(self, keys,",
"NameRegistry(self._create_mutex) if getattr(wrap, '__iter__', False): for wrapper in reversed(wrap): self.wrap(wrapper)",
"the \"old\" value until the new one is available. Usage",
"the decorator suitable (with caveats) for use with instance or",
"expiration_time: if not None, will override the normal expiration time.",
"is already \" \"configured with backend: %s. \" \"Specify replace_existing_backend=True",
"arg keys = key_generator(*arg, **kw) key_lookup = dict(zip(keys, cache_keys)) @wraps(fn)",
"0.5.1 \"\"\" return 'backend' in self.__dict__ def get(self, key, expiration_time=None,",
"values)) ) return values decorate.set = set_ decorate.invalidate = invalidate",
"\"\"\"weakref-capable wrapper for threading.Lock\"\"\" def __init__(self): self.lock = threading.Lock() def",
":class:`.ProxyBackend` that modifies values, take note this function invokes ``.set_multi()``",
"of the ``MyClass`` and ``MyOtherClass`` names, as the function is",
"False, but is separate from ``None`` to distinguish between a",
"the given key.\"\"\" if self.key_mangler: key = self.key_mangler(key) self.backend.set(key, self._value(value))",
"Function which will be used on all incoming keys before",
":class:`.CacheBackend` or :class:`.ProxyBackend` that modifies values, take note this function",
"return value of the function using a key derived from",
"``get()`` method returns either the value cached for the given",
"= fn.__name__ + (namespace or '') def generate_keys(*args): return [namespace",
"on a per-region basis using the ``function_key_generator`` argument present on",
"whatever asynchronous means the provided async_creation_runner callable implements. By default",
"lock is released and a new value available. If a",
"will be called whenever the decorated function itself is called,",
"be assembled into a new argument list, and the decorated",
"= arg keys = key_generator(*arg, **kw) key_lookup = dict(zip(keys, cache_keys))",
"expiration_time=None, should_cache_fn=None): \"\"\"Return a cached value based on the given",
"return the generated values as a sequence corresponding to the",
"\"\"\" return 'backend' in self.__dict__ def get(self, key, expiration_time=None, ignore_expiration=False):",
"existing cache backend will be replaced. Without this flag, an",
"of deleting the given sequence of keys using the same",
"last call to :meth:`.invalidate`. :param key: Key to be retrieved.",
"- the name ``self`` is skipped. The ``namespace`` parameter is",
"the normal expiration time. May be specified as a callable,",
"and the arguments passed to it. This method is the",
"should return list of keys. For example:: def my_multi_key_generator(namespace, fn,",
"possibilities relative to the function. This is a convenience method",
"function_key_generator, function_multi_key_generator from .api import NO_VALUE, CachedValue from .proxy import",
"values = dict(zip(mangled_keys, self.backend.get_multi(mangled_keys))) for orig_key, mangled_key in orig_to_mangled.items(): with",
"expiration_time, async_creator=lambda mutex: async_creator(orig_key, mutex) ): pass try: if mutexes:",
"returned result is a list:: result = generate_something(\"key1\", \"key2\", \"key3\")",
"def creator(*keys_to_create): return fn(*[key_lookup[k] for k in keys_to_create]) timeout =",
"new function that generates the key based on the given",
"for configuring a region from a config file. :param function_key_generator:",
"initialize it. if type(proxy) == type: proxy = proxy() if",
"'127.0.0.1:11211', 'distributed_lock': True, } ) Remember that the first request",
"method to decorated function. Lastly, the ``get()`` method returns either",
"_config_argument_dict: self.backend = backend_cls.from_config_dict( _config_argument_dict, _config_prefix ) else: self.backend =",
"value = self.backend.get(key) if (value is NO_VALUE or value.metadata['v'] !=",
"required \" \"for soft invalidation\") if expiration_time == -1: expiration_time",
"seealso:: :func:`.function_key_generator` - default key generator :func:`.kwarg_function_key_generator` - optional gen",
"to the dogpile system. May be passed as an integer",
"the ``expiration_time``. This callable will be called whenever the decorated",
"from the cache, based on the given keys. Returns values",
"for key in keys ] The decorated function can be",
":param ignore_expiration: if ``True``, the value is returned from the",
"date or time passes\". .. versionchanged:: 0.5.0 ``expiration_time`` may be",
"[ d_values.get(key_lookup[k], NO_VALUE) for k in keys] def wrap_cache_fn(value): if",
"if expiration_time is None: expiration_time = self.expiration_time current_time = time.time()",
") @memoized_property def backend(self): raise exception.RegionNotConfigured( \"No backend is configured",
"regeneration of the value which all getters will wait for.",
"of configured expiration times or whether or not :meth:`.invalidate` was",
"\"\"\" raise NotImplementedError() def is_soft_invalidated(self, timestamp): \"\"\"Check timestamp to determine",
"is not present, the method returns the token ``NO_VALUE``. ``NO_VALUE``",
"within the same source file, such as those associated with",
"( _unexpired_value_fn(value) for value in backend_values ) ] def get_or_create(",
"given key. If the value is not present, the method",
"on each function argument in order to convert to a",
"2.x, the ``unicode()`` builtin can be substituted, but note this",
"_config_argument_dict=config_dict, _config_prefix=\"%sarguments.\" % prefix, wrap=config_dict.get( \"%swrap\" % prefix, None), )",
"= self.function_key_generator def decorator(fn): if to_str is compat.string_type: # backwards",
":func:`.function_key_generator` - default key generator :func:`.kwarg_function_key_generator` - optional gen that",
"given keys. The list of keys to be generated is",
":meth:`.CacheRegion.cache_multi_on_arguments` :meth:`.CacheRegion.get_or_create` \"\"\" def get_value(key): value = values.get(key, NO_VALUE) if",
":class:`.CacheRegion`. Currently, :func:`.make_region` is a passthrough to :class:`.CacheRegion`. See that",
"mode. \"\"\" raise NotImplementedError() def was_hard_invalidated(self): \"\"\"Indicate the region was",
"proxy() if not issubclass(type(proxy), ProxyBackend): raise TypeError(\"Type %s is not",
"not modify values in-place on the submitted ``mapping`` dict. :param",
"= time.time() self._hard_invalidated = None def is_invalidated(self, timestamp): return ((self._soft_invalidated",
"derived from the function itself and its arguments. The decorator",
"in the list are returned as the ``NO_VALUE`` token. ``NO_VALUE``",
"new_values) ) if not should_cache_fn: self.backend.set_multi(values_w_created) else: self.backend.set_multi(dict( (k, v)",
"def __init__(self, region): self.region = region # ... # ...",
"finished. This can be used to defer the computation of",
"be stale. It does not affect the data in the",
"\"soft\" invalidation, subsequent getters will return the \"old\" value until",
"expiration time supplied by the ``expiration_time`` argument, is tested against",
"= self.backend.get(key) value = self._unexpired_value_fn( expiration_time, ignore_expiration)(value) return value.payload def",
"submitted ``mapping`` dict. :param keys: Sequence of keys to be",
"keys = list(map(lambda key: self.key_mangler(key), keys)) backend_values = self.backend.get_multi(keys) _unexpired_value_fn",
"k in sorted_unique_keys] else: mangled_keys = sorted_unique_keys orig_to_mangled = dict(zip(sorted_unique_keys,",
"may require key mangling before reaching the cache. .. versionadded::",
"= refresh decorate.get = get decorate.original = fn return decorate",
"different thread or process is already running a creation function",
"0.3.0 The value is unconditionally regenerated if the creation time",
"creator(*keys_to_create): return fn(*[key_lookup[k] for k in keys_to_create]) timeout = expiration_time()",
") return values else: self.set_multi( dict(zip(keys, values)) ) return values",
"task manager system like Celery. For a specific example using",
"value is available, that value is returned immediately without blocking.",
"default key generation will use the name of the function,",
"be entirely replaced on a per-region basis using the ``function_key_generator``",
"be applied. .. versionadded:: 0.5.0 .. seealso:: :ref:`changing_backend_behavior` :param replace_existing_backend:",
"for function # decorators, but not yet for actual caching",
"thread.start() region = make_region( async_creation_runner=async_creation_runner, ).configure( 'dogpile.cache.memcached', expiration_time=5, arguments={ 'url':",
":meth:`.Region.set_multi` to get and set values from the backend. If",
"self.lock = threading.Lock() def acquire(self, wait=True): return self.lock.acquire(wait) def release(self):",
"``str``, which can be used to convert non-string or Unicode",
"self.region_invalidator.invalidate(hard) def configure_from_config(self, config_dict, prefix): \"\"\"Configure from a configuration dictionary",
"when config is available myconfig = { \"cache.local.backend\":\"dogpile.cache.dbm\", \"cache.local.arguments.filename\":\"/path/to/dbmfile.dbm\", \"cache.memcached.backend\":\"dogpile.cache.pylibmc\",",
"you'd pass to the function itself to represent a particular",
"cache. It will be passed the mutex and is responsible",
":param function_multi_key_generator: Optional. Similar to ``function_key_generator`` parameter, but it's used",
"def _mutex(self, key): return self._lock_registry.get(key) class _LockWrapper(object): \"\"\"weakref-capable wrapper for",
"= function_key_generator( namespace, fn, to_str=to_str) @wraps(fn) def decorate(*arg, **kw): key",
"See that class for constructor arguments. \"\"\" return CacheRegion(*arg, **kw)",
"to generate any subset of the given keys. The list",
"Optional expiration time value which will supersede that configured on",
"datetime.timedelta): self.expiration_time = int( compat.timedelta_total_seconds(expiration_time)) else: raise exception.ValidationError( 'expiration_time is",
"self.key_mangler(key) def get_value(): value = self.backend.get(key) if (value is NO_VALUE",
"- default key generator :func:`.kwarg_function_key_generator` - optional gen that also",
"< self._hard_invalidated)) def was_hard_invalidated(self): return bool(self._hard_invalidated) def is_hard_invalidated(self, timestamp): return",
"self.key_mangler: keys = list(map(lambda key: self.key_mangler(key), keys)) self.backend.delete_multi(keys) def cache_on_arguments(",
"- value.metadata[\"ct\"] > expiration_time: return NO_VALUE elif self.region_invalidator.is_invalidated( value.metadata[\"ct\"]): return",
"NotImplementedError() def is_hard_invalidated(self, timestamp): \"\"\"Check timestamp to determine if it",
"invoked. However, subsequent requests for cached-but-expired values will still return",
"The above example is equivalent to calling ``generate_something(5, 6)``, if",
"to False, but is separate from ``None`` to distinguish between",
"the dogpile system. May be passed as an integer number",
"\"k3\") .. versionadded:: 0.5.3 Added ``get()`` method to decorated function.",
"Optional. Override default invalidation strategy with custom implementation of :class:`.RegionInvalidationStrategy`.",
"value:: generate_something.invalidate(5, 6) Another attribute ``set()`` is added to provide",
"time as set by the :meth:`.invalidate` method. If a value",
"function_key_generator = self.function_key_generator def decorator(fn): if to_str is compat.string_type: #",
"*arg, **kw): key = key_generator(*arg, **kw) self.set(key, value) def get(*arg,",
". import exception from ..util import PluginLoader, memoized_property, coerce_string_conf from",
"region # ... # ... region = CacheRegion() region =",
"lock* can be acquired or not. If it can't, it",
"until the lock is released to return the new value.",
".. versionadded:: 0.5.0 \"\"\" if not keys: return [] if",
"value_version = 1 \"\"\"An integer placed in the :class:`.CachedValue` so",
"memcached_region.configure_from_config(myconfig, \"cache.memcached.\") \"\"\" config_dict = coerce_string_conf(config_dict) return self.configure( config_dict[\"%sbackend\" %",
"value unconditionally. The method also interprets the cached value in",
"of the given keys. The list of keys to be",
"new_values = creator(*keys_to_get) values_w_created = dict( (orig_to_mangled[k], self._value(v)) for k,",
"calling the decorated function. The value to be cached is",
"should follow:: generate_something.set(3, 5, 6) The above example is equivalent",
"decorate.get = get decorate.original = fn return decorate return decorator",
"can be used to determine a *dynamic* expiration time for",
"key = self.key_mangler(key) self.backend.set(key, self._value(value)) def set_multi(self, mapping): \"\"\"Place new",
"sorted_unique_keys = sorted(set(keys)) if self.key_mangler: mangled_keys = [self.key_mangler(k) for k",
"retrieved value whose creation time is prior to this timestamp",
"versionadded:: 0.5.5 .. seealso:: :meth:`.CacheRegion.cache_on_arguments` :meth:`.CacheRegion.get_or_create_multi` \"\"\" expiration_time_is_callable = compat.callable(expiration_time)",
".. versionadded:: 0.5.5 .. seealso:: :meth:`.CacheRegion.cache_multi_on_arguments` :meth:`.CacheRegion.get_or_create` \"\"\" expiration_time_is_callable =",
"decorated function. Parameters passed to :meth:`.CacheRegion.cache_multi_on_arguments` have the same meaning",
"it was invalidated. :return: Boolean. True if ``timestamp`` is older",
"= bool(hard) self._invalidated = time.time() def is_invalidated(self, timestamp): return (self._invalidated",
"``dogpile.cache`` entrypoint. :param expiration_time: Optional. The expiration time passed to",
"The expiration time passed to the dogpile system. May be",
"using a decorator. :meth:`.CacheRegion.get_or_create_multi` - multiple key/value version \"\"\" orig_key",
"order of the keys. The method uses the same approach",
"def get(*arg, **kw): key = key_generator(*arg, **kw) return self.get(key) def",
"function is given a value as returned by the creator,",
"= int( compat.timedelta_total_seconds(expiration_time)) else: raise exception.ValidationError( 'expiration_time is not a",
".. versionchanged:: 0.5.0 ``expiration_time`` may be passed as a callable",
"works by setting a current timestamp (using ``time.time()``) to consider",
"to ``str()``. If the function accepts non-ascii unicode arguments on",
"def __init__(self): self.lock = threading.Lock() def acquire(self, wait=True): return self.lock.acquire(wait)",
"namespace=None, expiration_time=None, should_cache_fn=None, asdict=False, to_str=compat.string_type, function_multi_key_generator=None): \"\"\"A function decorator that",
"expiration_time() if expiration_time_is_callable \\ else expiration_time if asdict: def dict_create(*keys):",
"decorate return decorator def make_region(*arg, **kw): \"\"\"Instantiate a new :class:`.CacheRegion`.",
"for s in arg) return generate_key region = make_region( function_key_generator",
"tested against the creation time of the retrieved value versus",
"Another attribute ``set()`` is added to provide extra caching possibilities",
"= generate_something(\"key1\", \"key2\", \"key3\") The decorator internally makes use of",
"expiration_time or isinstance(expiration_time, Number): self.expiration_time = expiration_time elif isinstance(expiration_time, datetime.timedelta):",
"function itself is called, in caching or retrieving. Thus, this",
"\\ else expiration_time return self.get_or_create(key, creator, timeout, should_cache_fn) def invalidate(*arg,",
".. versionadded:: 0.5.0 \"\"\" if not mapping: return if self.key_mangler:",
"might be used as:: @my_region.cache_on_arguments(namespace=('x', 'y')) def my_function(a, b, **kw):",
"configured on this :class:`.CacheRegion` if not None. To set no",
"y): \"\" class MyOtherClass(object): @region.cache_on_arguments(namespace='MOC') def somemethod(self, x, y): \"\"",
"is ultimately passed directly down to the cache backend, before",
"within the same module, as can occur when decorating instance",
"not None, will override the normal expiration time. May be",
"name: Optional, a string name for the region. This isn't",
"``datetime.timedelta`` value. The :meth:`.CacheRegion.get_or_create` method as well as the :meth:`.CacheRegion.cache_on_arguments`",
"in order to convert to a string. Defaults to ``str()``.",
"generate_something.set({\"k1\": \"value1\", \"k2\": \"value2\", \"k3\": \"value3\"}) ...an ``invalidate()`` method, which",
"argument which will be established as part of each cache",
"keys = list(mapping) gen_keys = key_generator(*keys) self.set_multi(dict( (gen_key, mapping[key]) for",
"where data will be pulled from the cache region unless",
"by setting a current timestamp (using ``time.time()``) to consider all",
"my_key_generator ).configure( \"dogpile.cache.dbm\", expiration_time=300, arguments={ \"filename\":\"file.dbm\" } ) The ``namespace``",
"is prior to this timestamp is considered to be stale.",
"time which will overide the expiration time already configured on",
"a function ``one`` inside the module ``myapp.tools``:: @region.cache_on_arguments(namespace=\"foo\") def one(a,",
"that the string length is fixed. To disable all key",
"def somemethod(self, x, y): \"\" Above, the ``namespace`` parameter disambiguates",
"used to determine a *dynamic* expiration time for the cached",
".. versionadded:: 0.5.3 Added ``get()`` method to decorated function. Parameters",
"invalidated in soft mode. \"\"\" raise NotImplementedError() def was_hard_invalidated(self): \"\"\"Indicate",
"time check. .. versionadded:: 0.5.0 \"\"\" if not keys: return",
"configured on the :class:`.CacheRegion` itself. .. versionadded:: 0.5.5 .. seealso::",
"creation function, cache the new values, and return them:: values",
"was invalidated in hard mode. \"\"\" raise NotImplementedError() class DefaultInvalidationStrategy(RegionInvalidationStrategy):",
"For example:: def my_multi_key_generator(namespace, fn, **kw): namespace = fn.__name__ +",
"timestamp): \"\"\"Check timestamp to determine if it was hard invalidated.",
"- optional gen that also uses keyword arguments :param function_multi_key_generator:",
"called normally, where data will be pulled from the cache",
"fn, **kw): namespace = fn.__name__ + (namespace or '') def",
"the string length is fixed. To disable all key mangling,",
"not the function is used depends on if the *dogpile",
"string form of each key. It will then consult the",
"backend: %s. \" \"Specify replace_existing_backend=True to replace.\" % self.backend) backend_cls",
"function_multi_key_generator=None): \"\"\"A function decorator that will cache multiple return values",
":meth:`.Region.get_multi` and :meth:`.Region.set_multi` to get and set values from the",
"None value = region.get_or_create(\"some key\", create_value, should_cache_fn=dont_cache_none) Above, the function",
"creator, expiration_time=None, should_cache_fn=None): \"\"\"Return a sequence of cached values based",
"values, and the final result of calling the decorated function",
"versionadded:: 0.5.0 \"\"\" if not keys: return [] if self.key_mangler:",
"expiration_time is not None and \\ current_time - value.metadata[\"ct\"] >",
"creation function after this time period has passed since the",
"key = key_generator(*arg, **kw) @wraps(fn) def creator(): return fn(*arg, **kw)",
"function_key_generator=None): \"\"\"A function decorator that will cache the return value",
"older than the last region invalidation time. \"\"\" raise NotImplementedError()",
"in sorted_unique_keys] else: mangled_keys = sorted_unique_keys orig_to_mangled = dict(zip(sorted_unique_keys, mangled_keys))",
"= backend_cls.from_config_dict( _config_argument_dict, _config_prefix ) else: self.backend = backend_cls(arguments or",
"expiration time check. .. versionadded:: 0.5.0 \"\"\" if not keys:",
"to :meth:`.CacheRegion.configure` to override default region invalidation. Example:: class CustomInvalidationStrategy(RegionInvalidationStrategy):",
"return somedatabase.query(x, y) The decorated function can then be called",
"the cache using the same mechanism as that of :meth:`.CacheRegion.get_multi`",
"value which will supersede that configured on the :class:`.CacheRegion` itself.",
"\" \"for soft invalidation\") if expiration_time == -1: expiration_time =",
"to be used as the ``expiration_time``. This callable will be",
"cache. .. versionadded:: 0.5.0 :param function_multi_key_generator: a function that will",
"**kw): \"\"\"Instantiate a new :class:`.CacheRegion`. Currently, :func:`.make_region` is a passthrough",
"wrap_cache_fn) result = dict( (k, v) for k, v in",
"depends on if the *dogpile lock* can be acquired or",
"a key to be a string, it is ultimately passed",
"be passed as an integer number of seconds, or as",
"+ b Above, calling ``one(3, 4)`` will produce a cache",
"def get_or_create_multi( self, keys, creator, expiration_time=None, should_cache_fn=None): \"\"\"Return a sequence",
"value directly without calling the decorated function. The value to",
"key: self.key_mangler(key), keys)) backend_values = self.backend.get_multi(keys) _unexpired_value_fn = self._unexpired_value_fn( expiration_time,",
"caching possibilities relative to the function. This is a convenience",
"v is not NO_VALUE) else: result = self.get_or_create_multi( keys, creator,",
"default value of ``False``, the decorated function should return its",
"is returned from the cache if present, regardless of configured",
"return value.payload, ct def gen_value(): raise NotImplementedError() def async_creator(key, mutex):",
"a new value available. If a previous value is available,",
"function using a decorator. :meth:`.CacheRegion.get_or_create_multi` - multiple key/value version \"\"\"",
"present. :param creator: function which creates a new value. :param",
"from the cache. This operation is idempotent (can be called",
"running a creation function for this key against the cache.",
"as:: @my_region.cache_on_arguments(namespace=('x', 'y')) def my_function(a, b, **kw): return my_data() ..",
"optionally passed as a ``datetime.timedelta`` value. The :meth:`.CacheRegion.get_or_create` method as",
"function which will receive the value returned by the \"creator\",",
"of the :class:`.CacheBackend` in use, though is typically a dictionary.",
"note this will produce unicode cache keys which may require",
"# decorators, but not yet for actual caching # later,",
"= generate_something.refresh(\"k1\", \"k2\", \"k3\") ...and a ``get()`` method, which will",
"optional gen that also uses keyword arguments :param function_multi_key_generator: Optional.",
"by the key_mangler function, so can be of any type",
"\"_\".join(str(s) for s in arg) return generate_key region = make_region(",
"name of the function, the module name for the function,",
"under the given key.\"\"\" if self.key_mangler: key = self.key_mangler(key) self.backend.set(key,",
"= key_generator(*arg, **kw) self.delete(key) def set_(value, *arg, **kw): key =",
"name for the region. This isn't used internally but can",
"= self.backend.key_mangler self._lock_registry = NameRegistry(self._create_mutex) if getattr(wrap, '__iter__', False): for",
"to :meth:`.CacheRegion.cache_on_arguments`. :param namespace: optional string argument which will be",
"will that value be placed in the cache. :param asdict:",
"return values else: self.set_multi( dict(zip(keys, values)) ) return values decorate.set",
"gen_value, lambda: get_value(mangled_key), expiration_time, async_creator=lambda mutex: async_creator(orig_key, mutex) ): pass",
"set(self, key, value): \"\"\"Place a new value in the cache",
"from the cache region unless a new value is needed::",
"list, and the decorated function is then called with that",
"def decorate(*arg, **kw): cache_keys = arg keys = key_generator(*arg, **kw)",
"mangling function recommended by the cache backend will be used.",
"0.3.0 :meth:`.CacheRegion.get` now checks the value's creation time against the",
"The ``namespace`` is that passed to :meth:`.CacheRegion.cache_on_arguments`. It's not consulted",
"creation function for this key against the cache. When the",
".. versionadded:: 0.5.0 .. seealso:: :ref:`changing_backend_behavior` :param replace_existing_backend: if True,",
"versions of dogpile.cache can detect cached values from a previous,",
"config_dict[\"%sbackend\" % prefix], expiration_time=config_dict.get( \"%sexpiration_time\" % prefix, None), _config_argument_dict=config_dict, _config_prefix=\"%sarguments.\"",
"finally: mutex.release() thread = threading.Thread(target=runner) thread.start() region = make_region( async_creation_runner=async_creation_runner,",
"values = region.get_multi(keys) dictionary = dict(zip(keys, values)) Keys which aren't",
"will be used on all incoming keys before passing to",
"\"\"\" self.region_invalidator.invalidate(hard) def configure_from_config(self, config_dict, prefix): \"\"\"Configure from a configuration",
"value is not None value = region.get_or_create(\"some key\", create_value, should_cache_fn=dont_cache_none)",
"+ \"_\" + fname + \"_\".join(str(s) for s in arg)",
"whose creation time is prior to this timestamp is considered",
"return value.payload def _unexpired_value_fn(self, expiration_time, ignore_expiration): if ignore_expiration: return lambda",
"ignore_expiration=False): \"\"\"Return multiple values from the cache, based on the",
"value.payload, ct def gen_value(): created_value = creator() value = self._value(created_value)",
"a key derived from the function itself and its arguments.",
"if the dictionary returned by the decorated function is missing",
"at its default value of ``False``, the decorated function should",
"given an attribute ``invalidate()``, which provides for invalidation of the",
"self.key_mangler = self._user_defined_key_mangler = key_mangler self.async_creation_runner = async_creation_runner self.region_invalidator =",
"of ``False``, the decorated function should return its result as",
"works by setting a current timestamp (using ``time.time()``) representing the",
"self.backend.get(key) value = self._unexpired_value_fn( expiration_time, ignore_expiration)(value) return value.payload def _unexpired_value_fn(self,",
"all getters will wait for. With \"soft\" invalidation, subsequent getters",
"k in keys] def wrap_cache_fn(value): if value is NO_VALUE: return",
"is returned. :param backend: Required. This is the name of",
"invalid, however if the return value is None, it won't",
"gen_value(): created_value = creator() value = self._value(created_value) if not should_cache_fn",
"as a tuple, used to specify arguments to pluck from",
"versionadded:: 0.4.3 :param to_str: callable, will be called on each",
"key_mangler function, if present. :param expiration_time: Optional expiration time value",
"keys)) self.backend.delete_multi(keys) def cache_on_arguments( self, namespace=None, expiration_time=None, should_cache_fn=None, to_str=compat.string_type, function_key_generator=None):",
":class:`.CacheRegion` itself. .. versionadded:: 0.3.0 :param ignore_expiration: if ``True``, the",
"value based on the given key. If the value does",
"self.backend.set_multi(dict( (k, v) for k, v in values_w_created.items() if should_cache_fn(v[0])",
"from the ``dogpile.cache`` entrypoint. :param expiration_time: Optional. The expiration time",
"system works by setting a current timestamp (using ``time.time()``) representing",
"is_configured(self): \"\"\"Return True if the backend has been configured via",
"in the cache:: generate_something.set({\"k1\": \"value1\", \"k2\": \"value2\", \"k3\": \"value3\"}) ...an",
"is ``refresh()``. This attribute will invoke the decorated function and",
"- multiple key/value version \"\"\" orig_key = key if self.key_mangler:",
"keys to be generated is passed to ``creator()``, and ``creator()``",
"the given key, or the token ``NO_VALUE`` if no such",
"of ``.set_multi()`` will not modify values in-place on the submitted",
":meth:`.Region.get_or_create`, with the exception that the ``creator()`` function may be",
"0.6.2 .. seealso:: :paramref:`.CacheRegion.configure.region_invalidator` \"\"\" def invalidate(self, hard=True): \"\"\"Region invalidation.",
"keys: return [] if self.key_mangler: keys = list(map(lambda key: self.key_mangler(key),",
"a sequence of keys. The behavior for generation of values",
"substituted, but note this will produce unicode cache keys which",
"supports both \"hard\" and \"soft\" invalidation options. With \"hard\" invalidation,",
"a backend is already configured. .. versionadded:: 0.5.7 :param region_invalidator:",
":meth:`.CacheRegion.cache_on_arguments`, the decorated function is also provided with a ``set()``",
"decorated function is then called with that subset of arguments.",
"key_generator(*arg, **kw) return self.get(key) def refresh(*arg, **kw): key = key_generator(*arg,",
"until the lock is released and a new value available.",
"_config_prefix=\"%sarguments.\" % prefix, wrap=config_dict.get( \"%swrap\" % prefix, None), ) @memoized_property",
"non-ascii unicode arguments on Python 2.x, the ``unicode()`` builtin can",
".. seealso:: :ref:`changing_backend_behavior` :param replace_existing_backend: if True, the existing cache",
"function which accepts a sequence of keys and returns a",
"time supplied by the ``expiration_time`` argument, is tested against the",
"NO_VALUE) for k in keys] def wrap_cache_fn(value): if value is",
"mangler is the SHA1 mangler found at :func:`.sha1_mangle_key` which coerces",
"key = self.key_mangler(key) value = self.backend.get(key) value = self._unexpired_value_fn( expiration_time,",
"is added to provide extra caching possibilities relative to the",
"is True def is_hard_invalidated(self, timestamp): return self.was_hard_invalidated() and self.is_invalidated(timestamp) def",
"= DefaultInvalidationStrategy() def configure( self, backend, expiration_time=None, arguments=None, _config_argument_dict=None, _config_prefix=None,",
"decorator def cache_multi_on_arguments( self, namespace=None, expiration_time=None, should_cache_fn=None, asdict=False, to_str=compat.string_type, function_multi_key_generator=None):",
"_config_prefix ) else: self.backend = backend_cls(arguments or {}) if not",
"\\ current_time - value.metadata[\"ct\"] > expiration_time: return NO_VALUE elif self.region_invalidator.is_invalidated(",
"override the normal expiration time. May be passed as an",
"such as bsddb or dbm under Python 2.x in conjunction",
"If it can't, it means a different thread or process",
"expiration_time == -1: expiration_time = None if self.async_creation_runner: def async_creator(mutex):",
"e.g. # _has_value() will return False. return value.payload, 0 else:",
"pass try: if mutexes: # sort the keys, the idea",
"expiration_time - .0001 return value.payload, ct def gen_value(): raise NotImplementedError()",
"present in the cache. It will be passed the mutex",
"return values decorate.set = set_ decorate.invalidate = invalidate decorate.refresh =",
"may or may not be used to recreate the value",
"and timestamp < self._invalidated) def was_hard_invalidated(self): return self._is_hard_invalidated is True",
"it won't be cached. .. versionadded:: 0.4.3 .. seealso:: :meth:`.CacheRegion.cache_on_arguments`",
"compat.callable(expiration_time) if function_key_generator is None: function_key_generator = self.function_key_generator def decorator(fn):",
"else: result = self.get_or_create_multi( keys, creator, timeout, should_cache_fn) return result",
"which here accepts a mapping of keys and values to",
"values = generate_something.refresh(\"k1\", \"k2\", \"k3\") ...and a ``get()`` method, which",
"\"\"\"Region invalidation. :class:`.CacheRegion` propagated call. The default invalidation system works",
"= list(map(lambda key: self.key_mangler(key), keys)) self.backend.delete_multi(keys) def cache_on_arguments( self, namespace=None,",
"dictionary. If left at its default value of ``False``, the",
"= key_generator(*arg, **kw) value = fn(*arg, **kw) self.set(key, value) return",
"mapping.items()) self.backend.set_multi(mapping) def delete(self, key): \"\"\"Remove a value from the",
"key. It will then consult the cache using the same",
"``asdict==True`` if the dictionary returned by the decorated function is",
").configure( 'dogpile.cache.memcached', expiration_time=5, arguments={ 'url': '127.0.0.1:11211', 'distributed_lock': True, } )",
"for ``MyClass().one(3, 4)`` will again produce the same cache key",
"Whether or not the function is used depends on if",
"number of seconds, or as a ``datetime.timedelta`` value. .. versionadded",
"current time (as reported by ``time.time()``). If stale, the cached",
"threading.Thread(target=runner) thread.start() region = make_region( async_creation_runner=async_creation_runner, ).configure( 'dogpile.cache.memcached', expiration_time=5, arguments={",
"False, indicating if the value should actually be cached or",
"normal expiration time. May be passed as an integer or",
"like so:: import threading def async_creation_runner(cache, somekey, creator, mutex): '''",
"itself can't see the parent class on a function as",
"async_creation_runner=async_creation_runner, ).configure( 'dogpile.cache.memcached', expiration_time=5, arguments={ 'url': '127.0.0.1:11211', 'distributed_lock': True, }",
"Thus, this can be used to determine a *dynamic* expiration",
"in args] return generate_keys :param key_mangler: Function which will be",
"older than the last call to :meth:`.invalidate`. :param key: Key",
"corresponding to the order of the keys. The method uses",
"callable will be called whenever the decorated function itself is",
"= self.function_multi_key_generator def decorator(fn): key_generator = function_multi_key_generator( namespace, fn, to_str=to_str)",
"lambda: get_value(mangled_key), expiration_time, async_creator=lambda mutex: async_creator(orig_key, mutex) ): pass try:",
"the same mechanism as that of :meth:`.CacheRegion.get_multi` to retrieve all",
"**kw) key_lookup = dict(zip(keys, cache_keys)) @wraps(fn) def creator(*keys_to_create): return fn(*[key_lookup[k]",
"if True, the existing cache backend will be replaced. Without",
"exception from ..util import PluginLoader, memoized_property, coerce_string_conf from .util import",
"value in backend_values ) ] def get_or_create( self, key, creator,",
"require key mangling before reaching the cache. .. versionadded:: 0.5.0",
":meth:`.CacheRegion.cache_on_arguments` method. Example:: @someregion.cache_multi_on_arguments() def generate_something(*keys): return [ somedatabase.query(key) for",
"sequence of cached values based on a sequence of keys.",
"the function accepts non-ascii unicode arguments on Python 2.x, the",
"Currently, :func:`.make_region` is a passthrough to :class:`.CacheRegion`. See that class",
"returned as the ``NO_VALUE`` token. ``NO_VALUE`` evaluates to False, but",
"expiration_time: Optional. The expiration time passed to the dogpile system.",
"and a new value available. If a previous value is",
"wraps import threading _backend_loader = PluginLoader(\"dogpile.cache\") register_backend = _backend_loader.register from",
"value. .. versionchanged:: 0.3.0 The value is unconditionally regenerated if",
"passed to :meth:`.CacheRegion.cache_on_arguments`. :param namespace: optional string argument which will",
"and the final result of calling the decorated function will",
"self.lock.acquire(wait) def release(self): self.lock.release() def _create_mutex(self, key): mutex = self.backend.get_mutex(key)",
"region unless a new value is needed:: result = generate_something(5,",
"By default, the configured expiration time of the :class:`.CacheRegion`, or",
"which will store a given value directly without calling the",
"a dictionary of keys->values, and the final result of calling",
"- applies :meth:`.get_or_create` to any function using a decorator. :meth:`.CacheRegion.get_or_create_multi`",
"a convenience method for :meth:`.CacheRegion.set` which will store a given",
"retrieved. While it's typical for a key to be a",
"mangled_keys = [self.key_mangler(k) for k in sorted_unique_keys] else: mangled_keys =",
"or process is already running a creation function for this",
"\"soft\" invalidation options. With \"hard\" invalidation, :meth:`.CacheRegion.get_or_create` will force an",
"function will also be a list. When ``asdict==True`` if the",
"will supersede that configured on the :class:`.CacheRegion` itself. .. versionadded::",
"parameter in order to generate a cache key. Given a",
"MyClass(object): @region.cache_on_arguments(namespace=\"foo\") def one(self, a, b): return a + b",
"a value as returned by the creator, and only if",
"the decorated function and populate a new value into the",
"time, the ``NO_VALUE`` token is returned. Passing the flag ``ignore_expiration=True``",
"bytestrings, which is needed when using a backend such as",
"value is None, it won't be cached. .. versionadded:: 0.4.3",
"instance to :meth:`.CacheRegion.configure` to override default region invalidation. Example:: class",
"should_cache_fn=None): \"\"\"Return a sequence of cached values based on a",
"keys] finally: for mutex in mutexes.values(): mutex.release() def _value(self, value):",
"for k in keys] finally: for mutex in mutexes.values(): mutex.release()",
"key, value): \"\"\"Place a new value in the cache under",
":class:`.RegionInvalidationStrategy`. .. versionadded:: 0.6.2 \"\"\" if \"backend\" in self.__dict__ and",
"\"\"\"Place new values in the cache under the given keys.",
"called whenever the decorated function itself is called, in caching",
"be used as the ``expiration_time``. This callable will be called",
"keys, dict_create, timeout, wrap_cache_fn) result = dict( (k, v) for",
"self._hard_invalidated)) def was_hard_invalidated(self): return bool(self._hard_invalidated) def is_hard_invalidated(self, timestamp): return (self._hard_invalidated",
"new :class:`.CacheRegion`. Currently, :func:`.make_region` is a passthrough to :class:`.CacheRegion`. See",
"passed as a tuple, used to specify arguments to pluck",
"a list. When ``asdict==True`` if the dictionary returned by the",
"CacheRegion(object): \"\"\"A front end to a particular cache backend. :param",
"a sequence of keys and returns a sequence of new",
"else: self.backend = backend_cls(arguments or {}) if not expiration_time or",
"not consulted outside this function, so in fact can be",
"def set(self, key, value): \"\"\"Place a new value in the",
"**kw): fname = fn.__name__ def generate_key(*arg): return namespace + \"_\"",
"will be pulled from the cache region unless a new",
"# dogpile.core understands a 0 here as # \"the value",
"function is missing keys, those keys will not be cached.",
"namespace and with the string form of each key. It",
":func:`.kwarg_function_key_generator` - optional gen that also uses keyword arguments :param",
"cannot be acquired, the method will block if no previous",
"unconditionally prevented from being returned. The method will attempt to",
"the :class:`.CacheBackend` to use, and is resolved by loading the",
"outside this function, so in fact can be of any",
"\"k2\", \"k3\") ...a ``refresh()`` method, which will call the creation",
"both \"hard\" and \"soft\" invalidation options. With \"hard\" invalidation, :meth:`.CacheRegion.get_or_create`",
"values in the cache under the given keys. .. versionadded::",
"result until the end of the day, week or time",
"should_cache_fn: self.backend.set_multi(values_w_created) else: self.backend.set_multi(dict( (k, v) for k, v in",
"on this region.\") @property def is_configured(self): \"\"\"Return True if the",
"if no such key exists:: value = generate_something.get(5, 6) ..",
"time. .. versionadded:: 0.3.0 :param hard: if True, cache values",
"not keys: return [] if self.key_mangler: keys = list(map(lambda key:",
"method to decorated function. Similar to ``set()`` is ``refresh()``. This",
"Invalidation strategies that wish to have access to the :class:`.CacheRegion`",
"class CacheRegion(object): \"\"\"A front end to a particular cache backend.",
"is the name of the :class:`.CacheBackend` to use, and is",
"versionadded:: 0.6.2 .. seealso:: :paramref:`.CacheRegion.configure.region_invalidator` \"\"\" def invalidate(self, hard=True): \"\"\"Region",
"which accepts a sequence of keys and returns a sequence",
"``MyClass`` and ``MyOtherClass`` names, as the function is received by",
"may be needed to disambiguate functions of the same name",
"front end to a particular cache backend. :param name: Optional,",
"value_fn def get_multi(self, keys, expiration_time=None, ignore_expiration=False): \"\"\"Return multiple values from",
"honored by the :meth:`.CacheRegion.get_or_create`, :meth:`.CacheRegion.get_or_create_multi` and :meth:`.CacheRegion.get` methods. The method",
"the cache with the new value, as well as returning",
"backend_cls = _backend_loader.load(backend) if _config_argument_dict: self.backend = backend_cls.from_config_dict( _config_argument_dict, _config_prefix",
"or value.metadata['v'] != value_version or self.region_invalidator.is_hard_invalidated( value.metadata['v'])): # dogpile.core understands",
"value is not available\", e.g. # _has_value() will return False.",
"x, y): \"\" Above, the ``namespace`` parameter disambiguates between ``somemethod``",
"\\ else expiration_time if asdict: def dict_create(*keys): d_values = creator(*keys)",
"region as an argument:: class MyInvalidator(RegionInvalidationStrategy): def __init__(self, region): self.region",
"the backend or by the key_mangler function, if present. :param",
"the cached value in terms of the current \"invalidation\" time",
":class:`.CacheBackend` in use, though is typically a dictionary. :param wrap:",
"``.set_multi()`` will not modify values in-place on the submitted ``mapping``",
"will receive each value returned by the \"creator\", and will",
"and is also local to this instance of :class:`.CacheRegion`. Once",
"method to decorated function. The default key generation will use",
"be acquired, the method will block if no previous value",
"returning the value unconditionally. The method also interprets the cached",
"def set_(value, *arg, **kw): key = key_generator(*arg, **kw) self.set(key, value)",
":meth:`.CacheRegion.invalidate` method. :param key: Key to be retrieved. While it's",
"value) finally: mutex.release() thread = threading.Thread(target=runner) thread.start() region = make_region(",
"function may or may not be used to recreate the",
"produce a list of keys. This function will supersede the",
"if self.key_mangler: keys = list(map(lambda key: self.key_mangler(key), keys)) self.backend.delete_multi(keys) def",
"as returning that value:: newvalue = generate_something.refresh(5, 6) .. versionadded::",
"versionadded 0.5.0 ``expiration_time`` may be optionally passed as a ``datetime.timedelta``",
"creation time\" for a value. Any retrieved value whose creation",
"region invalidation time and region is invalidated in hard mode.",
"else: mapping = dict((k, self._value(v)) for k, v in mapping.items())",
"expiration time. May be passed as an integer or a",
"k, v in zip(cache_keys, result) if v is not NO_VALUE)",
"fn(*arg, **kw) timeout = expiration_time() if expiration_time_is_callable \\ else expiration_time",
"timestamp is considered to be stale. It does not affect",
"an instance method. The function key generation can be entirely",
"but not yet for actual caching # later, when config",
"for this key against the cache. When the dogpile lock",
"has been called, and the retrieved value's timestamp is older",
"parameter is optional, and is used normally to disambiguate two",
"and its arguments. The decorator internally makes use of the",
"replace.\" % self.backend) backend_cls = _backend_loader.load(backend) if _config_argument_dict: self.backend =",
"``myapp.tools``:: @region.cache_on_arguments(namespace=\"foo\") def one(a, b): return a + b Above,",
"= region.configure(region_invalidator=MyInvalidator(region)) .. versionadded:: 0.6.2 .. seealso:: :paramref:`.CacheRegion.configure.region_invalidator` \"\"\" def",
"but isn't cached. .. versionadded:: 0.5.0 .. seealso:: :meth:`.CacheRegion.cache_multi_on_arguments` :meth:`.CacheRegion.get_or_create`",
"use of the :meth:`.CacheRegion.get_or_create` method to access the cache and",
"module name for the function, the arguments passed, as well",
"from functools import wraps import threading _backend_loader = PluginLoader(\"dogpile.cache\") register_backend",
"until a certain date or time passes\". .. versionchanged:: 0.5.0",
"``ignore_expiration=True`` bypasses the expiration time check. .. versionadded:: 0.5.0 \"\"\"",
"callable to :meth:`.CacheRegion.cache_on_arguments`. :param should_cache_fn: passed to :meth:`.CacheRegion.get_or_create`. .. versionadded::",
"will produce a \"cache key\". This function will supersede the",
"to :meth:`.invalidate`. :param key: Key to be retrieved. While it's",
"the same meaning as those passed to :meth:`.CacheRegion.cache_on_arguments`. :param namespace:",
"two functions of the same name within the same module,",
"if asdict: self.set_multi( dict(zip(keys, [values[a] for a in arg])) )",
"creator() value = self._value(created_value) if not should_cache_fn or \\ should_cache_fn(created_value):",
"This function is given a value as returned by the",
"is being declared. :param expiration_time: if not None, will override",
"with custom implementation of :class:`.RegionInvalidationStrategy`. .. versionadded:: 0.6.2 \"\"\" if",
"self.is_invalidated(timestamp) class CacheRegion(object): \"\"\"A front end to a particular cache",
"class MyInvalidator(RegionInvalidationStrategy): def __init__(self, region): self.region = region # ...",
"be used to convert non-string or Unicode keys to bytestrings,",
"creator() cache.set(somekey, value) finally: mutex.release() thread = threading.Thread(target=runner) thread.start() region",
"0.5.7 :param region_invalidator: Optional. Override default invalidation strategy with custom",
"last region invalidation time and region is invalidated in hard",
"return self.get_multi(keys) def refresh(*arg): keys = key_generator(*arg) values = fn(*arg)",
"} ) The ``namespace`` is that passed to :meth:`.CacheRegion.cache_on_arguments`. It's",
"{} sorted_unique_keys = sorted(set(keys)) if self.key_mangler: mangled_keys = [self.key_mangler(k) for",
"``namespace`` is that passed to :meth:`.CacheRegion.cache_on_arguments`. It's not consulted outside",
"def configure( self, backend, expiration_time=None, arguments=None, _config_argument_dict=None, _config_prefix=None, wrap=None, replace_existing_backend=False,",
"cache backend, before being optionally processed by the key_mangler function,",
"a function that will produce a \"cache key\". This function",
"timeout, wrap_cache_fn) result = dict( (k, v) for k, v",
"if v is not NO_VALUE) else: result = self.get_or_create_multi( keys,",
"dogpile.core:Lock when appropriate ''' def runner(): try: value = creator()",
"= creator(*keys) return [ d_values.get(key_lookup[k], NO_VALUE) for k in keys]",
"[\"one\", \"two\", \"three\"] values = region.get_multi(keys) dictionary = dict(zip(keys, values))",
"produce the same cache key of ``myapp.tools:one|foo|3 4`` - the",
"expiration_time=None, should_cache_fn=None, to_str=compat.string_type, function_key_generator=None): \"\"\"A function decorator that will cache",
"function_multi_key_generator: Optional. Similar to ``function_key_generator`` parameter, but it's used in",
"if the *dogpile lock* can be acquired or not. If",
"zip(cache_keys, result) if v is not NO_VALUE) else: result =",
"``generate_something(5, 6)``, if the function were to produce the value",
"this region.\") @property def is_configured(self): \"\"\"Return True if the backend",
"instance or class methods as below:: class MyClass(object): @region.cache_on_arguments(namespace='MC') def",
"not NO_VALUE else value for value in ( _unexpired_value_fn(value) for",
"as bsddb or dbm under Python 2.x in conjunction with",
"it. This method is the \"multiple key\" analogue to the",
"dict((k, self._value(v)) for k, v in mapping.items()) self.backend.set_multi(mapping) def delete(self,",
"before passing to the backend. Defaults to ``None``, in which",
"the arguments passed to it. This method is the \"multiple",
"this function should be two levels: given the data creation",
"backend, so that custom functionality augmentation can be applied. ..",
"mangling before reaching the cache. .. versionadded:: 0.5.0 :param function_key_generator:",
"< self._hard_invalidated) def was_soft_invalidated(self): return bool(self._soft_invalidated) def is_soft_invalidated(self, timestamp): return",
"self.key_mangler: keys = list(map(lambda key: self.key_mangler(key), keys)) backend_values = self.backend.get_multi(keys)",
"be used to determine a *dynamic* expiration time for the",
"new values can be created in a background thread like",
"dict( (k, v) for k, v in zip(cache_keys, result) if",
"= compat.callable(expiration_time) if function_multi_key_generator is None: function_multi_key_generator = self.function_multi_key_generator def",
"that value be placed in the cache. :param asdict: if",
"a number or timedelta.') if not self._user_defined_key_mangler: self.key_mangler = self.backend.key_mangler",
"\"Non-None expiration time required \" \"for soft invalidation\") if expiration_time",
"0 here as # \"the value is not available\", e.g.",
"the calling function. A correct implementation of ``.set_multi()`` will not",
"a + b Above, calling ``one(3, 4)`` will produce a",
"available myconfig = { \"cache.local.backend\":\"dogpile.cache.dbm\", \"cache.local.arguments.filename\":\"/path/to/dbmfile.dbm\", \"cache.memcached.backend\":\"dogpile.cache.pylibmc\", \"cache.memcached.arguments.url\":\"127.0.0.1, 10.0.0.1\", }",
"the new value. .. versionchanged:: 0.3.0 The value is unconditionally",
"return list of keys. For example:: def my_multi_key_generator(namespace, fn, **kw):",
"namespace: optional string argument which will be established as part",
"use the value -1. :param should_cache_fn: optional callable function which",
"called multiple times, or on a non-existent key, safely) ..",
"sequence of keys. The behavior for generation of values based",
"be used. A typical mangler is the SHA1 mangler found",
"set values from the backend. If you are using a",
"self.set(key, value) return value decorate.set = set_ decorate.invalidate = invalidate",
"If the function accepts non-ascii unicode arguments on Python 2.x,",
"self._soft_invalidated = None self._hard_invalidated = time.time() else: self._soft_invalidated = time.time()",
"of keys using the same mechanism as that of :meth:`.CacheRegion.delete_multi`::",
"chain to ultimately wrap the original backend, so that custom",
"newly generated value in the cache. Whether or not the",
"hard: if True, cache values will all require immediate regeneration;",
"region is invalidated in soft mode. \"\"\" raise NotImplementedError() def",
"to :func:`.function_key_generator`. :param namespace: optional string argument which will be",
"``refresh()`` method, which will call the creation function, cache the",
"refreshed by whatever asynchronous means the provided async_creation_runner callable implements.",
"self.region_invalidator.is_hard_invalidated( value.metadata['v'])): # dogpile.core understands a 0 here as #",
"can be acquired or not. If it can't, it means",
"cache backend will be replaced. Without this flag, an exception",
"or dbm under Python 2.x in conjunction with Unicode keys.",
"!= value_version or self.region_invalidator.is_hard_invalidated( value.metadata[\"ct\"])): raise NeedRegenerationException() ct = value.metadata[\"ct\"]",
"The decorator internally makes use of the :meth:`.CacheRegion.get_or_create_multi` method to",
"region invalidation time and region is invalidated in soft mode.",
"sorted(set(keys)) if self.key_mangler: mangled_keys = [self.key_mangler(k) for k in sorted_unique_keys]",
"defaults to :func:`.function_key_generator`. :param namespace: optional string argument which will",
"import exception from ..util import PluginLoader, memoized_property, coerce_string_conf from .util",
"applied. .. versionadded:: 0.5.0 .. seealso:: :ref:`changing_backend_behavior` :param replace_existing_backend: if",
"{}) if not expiration_time or isinstance(expiration_time, Number): self.expiration_time = expiration_time",
"will return the \"old\" value until the new one is",
"is returned. Passing the flag ``ignore_expiration=True`` bypasses the invalidation time",
"for the region. This isn't used internally but can be",
"the creation function, cache the new values, and return them::",
"create_value, should_cache_fn=dont_cache_none) Above, the function returns the value of create_value()",
"dictionary. :param wrap: Optional. A list of :class:`.ProxyBackend` classes and/or",
"calling the decorated function will also be a list. When",
"note this function invokes ``.set_multi()`` for newly generated values using",
"versionadded:: 0.5.3 Added ``get()`` method to decorated function. The default",
"key. If the value is not present, the method returns",
"list(mapping) gen_keys = key_generator(*keys) self.set_multi(dict( (gen_key, mapping[key]) for gen_key, key",
"rather than an instance then # initialize it. if type(proxy)",
"def __init__(self): self._soft_invalidated = None self._hard_invalidated = None def invalidate(self,",
"value from the cache, based on the given key. If",
"self.name = name self.function_key_generator = function_key_generator self.function_multi_key_generator = function_multi_key_generator self.key_mangler",
"any function using a decorator. :meth:`.CacheRegion.get_or_create_multi` - multiple key/value version",
"a tuple, used to specify arguments to pluck from \\**kw::",
"is resolved by loading the class from the ``dogpile.cache`` entrypoint.",
"releasing that mutex when finished. This can be used to",
"of :meth:`.CacheRegion.delete_multi`:: generate_something.invalidate(\"k1\", \"k2\", \"k3\") ...a ``refresh()`` method, which will",
"function, return a new function that generates the key based",
"be passed to the function should follow:: generate_something.set(3, 5, 6)",
"value = generate_something.get(5, 6) .. versionadded:: 0.5.3 Added ``get()`` method",
"placed in the :class:`.CachedValue` so that new versions of dogpile.cache",
"a sequence of keys derived from the function itself and",
"This isn't used internally but can be accessed via the",
"parameter, helpful for configuring a region from a config file.",
"If stale, the cached value is ignored and the ``NO_VALUE``",
"value is returned from the cache if present, regardless of",
"time, the given creation function may or may not be",
"produce a list of cache keys using a mechanism similar",
"self.delete(key) def set_(value, *arg, **kw): key = key_generator(*arg, **kw) self.set(key,",
"generation will use the name of the function, the module",
"Generated function should return list of keys. For example:: def",
"be two levels: given the data creation function, return a",
"to be cached. .. versionadded:: 0.4.1 Added ``set()`` method to",
":meth:`.CacheRegion.get_or_create_multi` method to access the cache and conditionally call the",
"for k in sorted_unique_keys] else: mangled_keys = sorted_unique_keys orig_to_mangled =",
"decorated function can then be called normally, where data will",
"function, if present. :param creator: function which creates a new",
"would normally be passed to the function should follow:: generate_something.set(3,",
"originally passed keys corresponding to those values which aren't generated",
"the creation time is older than the last call to",
"a new value, or will wait until the lock is",
"its arguments. The decorator internally makes use of the :meth:`.CacheRegion.get_or_create`",
"is needed:: result = generate_something(5, 6) The function is also",
"values, and return them:: values = generate_something.refresh(\"k1\", \"k2\", \"k3\") ...and",
"optional \"namespace\" parameter in order to generate a cache key.",
"be a dictionary. If left at its default value of",
"zip(keys_to_get, new_values) ) if not should_cache_fn: self.backend.set_multi(values_w_created) else: self.backend.set_multi(dict( (k,",
"else: return self._LockWrapper() def invalidate(self, hard=True): \"\"\"Invalidate this :class:`.CacheRegion`. The",
"return [ value.payload if value is not NO_VALUE else value",
"self._value(v)) for k, v in mapping.items()) else: mapping = dict((k,",
"will attempt to acquire the dogpile lock to generate a",
"on the :class:`.CacheRegion` itself. .. versionadded:: 0.5.5 .. seealso:: :meth:`.CacheRegion.cache_on_arguments`",
"values = fn(*arg) if asdict: self.set_multi( dict(zip(keys, [values[a] for a",
"structure of this function should be two levels: given the",
"-1: expiration_time = None if self.async_creation_runner: def async_creator(mutex): return self.async_creation_runner(",
"dict(( self.key_mangler(k), self._value(v)) for k, v in mapping.items()) else: mapping",
"\"\"\"Construct a new :class:`.CacheRegion`.\"\"\" self.name = name self.function_key_generator = function_key_generator",
"if not keys: return [] if self.key_mangler: keys = list(map(lambda",
"None: return mutex else: return self._LockWrapper() def invalidate(self, hard=True): \"\"\"Invalidate",
"and the ``NO_VALUE`` token is returned. Passing the flag ``ignore_expiration=True``",
"details. E.g.:: @someregion.cache_on_arguments() def generate_something(x, y): return somedatabase.query(x, y) The",
"the cache if present, regardless of configured expiration times or",
"before reaching the cache. .. versionadded:: 0.5.0 :param function_key_generator: a",
"those values which aren't generated or need regeneration will be",
"\"\"\" raise NotImplementedError() def was_hard_invalidated(self): \"\"\"Indicate the region was invalidated",
"dogpile lock cannot be acquired, the method will block if",
"on the :class:`.CacheRegion` itself. .. versionadded:: 0.5.5 .. seealso:: :meth:`.CacheRegion.cache_multi_on_arguments`",
":meth:`.CacheRegion.cache_on_arguments`. :param namespace: optional string argument which will be established",
"the exception that the ``creator()`` function may be asked to",
"value, or will wait until the lock is released to",
"still returned, but isn't cached. .. versionadded:: 0.5.0 .. seealso::",
"flag ``ignore_expiration=True`` bypasses the expiration time check. .. versionchanged:: 0.3.0",
"which takes a simple list of keys as arguments. Like",
"@wraps(fn) def decorate(*arg, **kw): key = key_generator(*arg, **kw) @wraps(fn) def",
"if the backend has been configured via the :meth:`.CacheRegion.configure` method",
"to generate a new value, or will wait until the",
"value returned by the \"creator\", and will then return True",
"\"\"\" if not mapping: return if self.key_mangler: mapping = dict((",
"keys using a mechanism similar to that of :meth:`.CacheRegion.cache_on_arguments`, combining",
"convert non-string or Unicode keys to bytestrings, which is needed",
"values to set in the cache:: generate_something.set({\"k1\": \"value1\", \"k2\": \"value2\",",
"not issubclass(type(proxy), ProxyBackend): raise TypeError(\"Type %s is not a valid",
"same name within the same source file, such as those",
"= _backend_loader.load(backend) if _config_argument_dict: self.backend = backend_cls.from_config_dict( _config_argument_dict, _config_prefix )",
"for a key to be a string, it is ultimately",
"immediately without blocking. If the :meth:`.invalidate` method has been called,",
"or a task manager system like Celery. For a specific",
"will then return True or False, indicating if the value",
"in the cache in any way, and is also local",
"to generate a cache key. Given a function ``one`` inside",
"else: return should_cache_fn(value) result = self.get_or_create_multi( keys, dict_create, timeout, wrap_cache_fn)",
"if not issubclass(type(proxy), ProxyBackend): raise TypeError(\"Type %s is not a",
"If a previous value is available, that value is returned",
"This is a convenience method for :meth:`.CacheRegion.set` which will store",
"return mutex else: return self._LockWrapper() def invalidate(self, hard=True): \"\"\"Invalidate this",
":param key_mangler: Function which will be used on all incoming",
"Above, calling ``one(3, 4)`` will produce a cache key as",
"import Lock, NeedRegenerationException from ..util import NameRegistry from . import",
"in which case the key mangling function recommended by the",
"as part of each cache key. :param expiration_time: if not",
"dont_cache_none(value): return value is not None value = region.get_or_create(\"some key\",",
"generation can be entirely replaced on a per-region basis using",
":meth:`.CacheRegion.get_multi` to retrieve all current values; the originally passed keys",
"(using ``time.time()``) representing the \"minimum creation time\" for a value.",
"one which takes a simple list of keys as arguments.",
"passed to the function should follow:: generate_something.set(3, 5, 6) The",
"decorated function is also provided with a ``set()`` method, which",
"generator will ignore an initial argument of ``self`` or ``cls``,",
"def decorator(fn): key_generator = function_multi_key_generator( namespace, fn, to_str=to_str) @wraps(fn) def",
"ignore_expiration): if ignore_expiration: return lambda value: value else: if expiration_time",
"'y')) def my_function(a, b, **kw): return my_data() .. seealso:: :func:`.function_key_generator`",
"period has passed since the last generation. :param arguments: Optional.",
"name ``self`` is skipped. The ``namespace`` parameter is optional, and",
"raise NotImplementedError() def is_soft_invalidated(self, timestamp): \"\"\"Check timestamp to determine if",
"mangler found at :func:`.sha1_mangle_key` which coerces keys into a SHA1",
"key_mangler function, if present. :param creator: function which creates a",
"the generated values as a sequence corresponding to the order",
"\"cache key\" given a data creation function and arguments, when",
"backend has been configured via the :meth:`.CacheRegion.configure` method already. ..",
"to the calling function. A correct implementation of ``.set_multi()`` will",
"retrieving. Thus, this can be used to determine a *dynamic*",
"as can occur when decorating instance or class methods as",
"needed when using a backend such as bsddb or dbm",
"there is a stale value present in the cache. It",
"the return value is None, it won't be cached. ..",
"as # \"the value is not available\", e.g. # _has_value()",
"the mutex and is responsible releasing that mutex when finished.",
":param region_invalidator: Optional. Override default invalidation strategy with custom implementation",
"The decorated function can be called normally. The decorator will",
"# initialize it. if type(proxy) == type: proxy = proxy()",
"dict_create(*keys): d_values = creator(*keys) return [ d_values.get(key_lookup[k], NO_VALUE) for k",
"string argument which will be established as part of the",
"function. Parameters passed to :meth:`.CacheRegion.cache_multi_on_arguments` have the same meaning as",
"given. E.g.:: values = region.get_multi([\"one\", \"two\", \"three\"]) To convert values",
"value.payload if value is not NO_VALUE else value for value",
"the originally passed keys corresponding to those values which aren't",
"to determine if it was hard invalidated. :return: Boolean. True",
"def invalidate(self, hard=True): \"\"\"Invalidate this :class:`.CacheRegion`. The default invalidation system",
"Lock( self._mutex(mangled_key), gen_value, lambda: get_value(mangled_key), expiration_time, async_creator=lambda mutex: async_creator(orig_key, mutex)",
"all key mangling, set to ``False``. Another typical mangler is",
"given a value.\"\"\" return CachedValue( value, { \"ct\": time.time(), \"v\":",
"mapping of keys and values to set in the cache::",
"but is separate from ``None`` to distinguish between a cached",
"cache the new values, and return them:: values = generate_something.refresh(\"k1\",",
"of calling the decorated function will also be a dictionary.",
"alternatively the expiration time supplied by the ``expiration_time`` argument, is",
"result) if v is not NO_VALUE) else: result = self.get_or_create_multi(",
"be used. If False, the creation time of existing values",
"ct def gen_value(): raise NotImplementedError() def async_creator(key, mutex): mutexes[key] =",
"to the function should follow:: generate_something.set(3, 5, 6) The above",
"dictionary, use ``zip()``:: keys = [\"one\", \"two\", \"three\"] values =",
"function itself to represent a particular value:: generate_something.invalidate(5, 6) Another",
"self.backend) backend_cls = _backend_loader.load(backend) if _config_argument_dict: self.backend = backend_cls.from_config_dict( _config_argument_dict,",
"be asked to generate any subset of the given keys.",
"cache multiple return values from the function using a sequence",
"the cache. .. versionadded:: 0.5.0 :param function_multi_key_generator: a function that",
"passed as the first argument, and the arguments which would",
"or timedelta.') if not self._user_defined_key_mangler: self.key_mangler = self.backend.key_mangler self._lock_registry =",
"value is needed:: result = generate_something(5, 6) The function is",
"here accepts a mapping of keys and values to set",
"creation function, return a new function that generates the key",
"try: if mutexes: # sort the keys, the idea is",
"key mangling function recommended by the cache backend will be",
"established as part of each cache key. :param expiration_time: if",
"region was invalidated in soft mode. :return: Boolean. True if",
"timestamp): return (self._hard_invalidated and timestamp < self._hard_invalidated) def was_soft_invalidated(self): return",
"A callable that, when specified, will be passed to and",
"make_region( async_creation_runner=async_creation_runner, ).configure( 'dogpile.cache.memcached', expiration_time=5, arguments={ 'url': '127.0.0.1:11211', 'distributed_lock': True,",
"gen_value, get_value, expiration_time, async_creator) as value: return value def get_or_create_multi(",
"invalidation requires that the region or the method is given",
"mapping = dict((k, self._value(v)) for k, v in mapping.items()) self.backend.set_multi(mapping)",
"be placed in the cache. :param asdict: if ``True``, the",
"exception that the ``creator()`` function may be asked to generate",
"proxy = proxy() if not issubclass(type(proxy), ProxyBackend): raise TypeError(\"Type %s",
"function itself and the arguments passed to it. This method",
"my_function(a, b, **kw): return my_data() .. seealso:: :func:`.function_key_generator` - default",
":param creator: function which creates a new value. :param expiration_time:",
"a dictionary, use ``zip()``:: keys = [\"one\", \"two\", \"three\"] values",
"that generates the key based on the given arguments. Such",
"which will receive each value returned by the \"creator\", and",
"generate_keys(*args): return [namespace + ':' + str(a) for a in",
"key = key_generator(*arg, **kw) return self.get(key) def refresh(*arg, **kw): key",
"the :meth:`.CacheRegion.get_or_create_multi` method to access the cache and conditionally call",
"then called with that subset of arguments. The returned result",
"from .util import function_key_generator, function_multi_key_generator from .api import NO_VALUE, CachedValue",
"disabled and is set to ``None``. .. versionadded:: 0.4.2 added",
"given keys. Returns values as a list matching the keys",
"values_w_created.items() if should_cache_fn(v[0]) )) values.update(values_w_created) return [values[orig_to_mangled[k]].payload for k in",
"isn't cached. E.g.:: def dont_cache_none(value): return value is not None",
"part of each cache key. :param expiration_time: if not None,",
"= expiration_time() if expiration_time_is_callable \\ else expiration_time if asdict: def",
"\"\"\"Remove multiple values from the cache. This operation is idempotent",
"no arguments, that returns a value to be used as",
"time of existing values will be pushed back before the",
"should_cache_fn(value) result = self.get_or_create_multi( keys, dict_create, timeout, wrap_cache_fn) result =",
"self._hard_invalidated = time.time() else: self._soft_invalidated = time.time() self._hard_invalidated = None",
"used to recreate the value and persist the newly generated",
".. seealso:: :meth:`.CacheRegion.cache_multi_on_arguments` :meth:`.CacheRegion.get_or_create` \"\"\" def get_value(key): value = values.get(key,",
"deadlocks. # though haven't been able to simulate one anyway.",
"self.backend.delete(key) def delete_multi(self, keys): \"\"\"Remove multiple values from the cache.",
"The :meth:`.CacheRegion.get_or_create` method as well as the :meth:`.CacheRegion.cache_on_arguments` decorator (though",
"\\ should_cache_fn(created_value): self.backend.set(key, value) return value.payload, value.metadata[\"ct\"] if expiration_time is",
"expiration_time - .0001 return value.payload, ct def gen_value(): created_value =",
"type rather than an instance then # initialize it. if",
"v in zip(cache_keys, result) if v is not NO_VALUE) else:",
"key_generator(*keys) self.set_multi(dict( (gen_key, mapping[key]) for gen_key, key in zip(gen_keys, keys))",
"\"\"\" raise NotImplementedError() def is_hard_invalidated(self, timestamp): \"\"\"Check timestamp to determine",
"def value_fn(value): if value is NO_VALUE: return value elif expiration_time",
".. versionadded:: 0.5.0 .. seealso:: :meth:`.CacheRegion.cache_multi_on_arguments` :meth:`.CacheRegion.get_or_create` \"\"\" def get_value(key):",
"backend, expiration_time=None, arguments=None, _config_argument_dict=None, _config_prefix=None, wrap=None, replace_existing_backend=False, region_invalidator=None ): \"\"\"Configure",
"may be asked to generate any subset of the given",
"Number): self.expiration_time = expiration_time elif isinstance(expiration_time, datetime.timedelta): self.expiration_time = int(",
"parameter disambiguates between ``somemethod`` on ``MyClass`` and ``MyOtherClass``. Python class",
"NotImplementedError() def was_soft_invalidated(self): \"\"\"Indicate the region was invalidated in soft",
"May be specified as a callable, taking no arguments, that",
"created_value = creator() value = self._value(created_value) if not should_cache_fn or",
"the :class:`.CacheBackend` in use, though is typically a dictionary. :param",
"-1. :param should_cache_fn: optional callable function which will receive each",
"on ``MyClass`` and ``MyOtherClass``. Python class declaration mechanics otherwise prevent",
"It does not affect the data in the cache in",
"by the key_mangler function, if present. :param creator: function which",
"those passed to :meth:`.CacheRegion.cache_on_arguments`. :param namespace: optional string argument which",
"as the class is being declared. :param expiration_time: if not",
"built-in Python function ``str``, which can be used to convert",
"None. To set no expiration, use the value -1. :param",
"orig_to_mangled = dict(zip(sorted_unique_keys, mangled_keys)) values = dict(zip(mangled_keys, self.backend.get_multi(mangled_keys))) for orig_key,",
"invalidation. :class:`.CacheRegion` propagated call. The default invalidation system works by",
"when appropriate ''' def runner(): try: value = creator() cache.set(somekey,",
"time against the expiration time, rather than returning the value",
"_unexpired_value_fn = self._unexpired_value_fn( expiration_time, ignore_expiration) return [ value.payload if value",
"callable function which will receive the value returned by the",
"using the same mechanism as that of :meth:`.CacheRegion.get_multi` to retrieve",
"string, it is ultimately passed directly down to the cache",
"the value returned by the \"creator\", and will then return",
"is NO_VALUE or value.metadata['v'] != value_version or self.region_invalidator.is_hard_invalidated( value.metadata['v'])): #",
"\"No backend is configured on this region.\") @property def is_configured(self):",
"cache. Whether or not the function is used depends on",
"function that will produce a \"cache key\" given a data",
":param name: Optional, a string name for the region. This",
"or class methods. Given the example:: class MyClass(object): @region.cache_on_arguments(namespace=\"foo\") def",
"``ignore_expiration=True`` bypasses the invalidation time check. .. versionadded:: 0.3.0 Support",
"= backend_cls(arguments or {}) if not expiration_time or isinstance(expiration_time, Number):",
"so that custom functionality augmentation can be applied. .. versionadded::",
"timestamp): return (self._invalidated is not None and timestamp < self._invalidated)",
"or the token ``NO_VALUE`` if no such key exists:: value",
"timeout, should_cache_fn) return result def invalidate(*arg): keys = key_generator(*arg) self.delete_multi(keys)",
"function, the module name for the function, the arguments passed,",
"= self.expiration_time if (expiration_time is None and self.region_invalidator.was_soft_invalidated()): raise exception.DogpileCacheException(",
"backend or by the key_mangler function, if present. :param expiration_time:",
"Optional. The structure here is passed directly to the constructor",
"values will still return promptly. They will be refreshed by",
"parameter:: region = CacheRegion() region = region.configure(region_invalidator=CustomInvalidationStrategy()) Invalidation strategies that",
"the backend. If you are using a :class:`.CacheBackend` or :class:`.ProxyBackend`",
"optional, and is used normally to disambiguate two functions of",
"function for this key against the cache. When the dogpile",
"will return False. return value.payload, 0 else: ct = value.metadata[\"ct\"]",
"the invalidation timestamp, the value is unconditionally prevented from being",
"key): return self._lock_registry.get(key) class _LockWrapper(object): \"\"\"weakref-capable wrapper for threading.Lock\"\"\" def",
"self, name=None, function_key_generator=function_key_generator, function_multi_key_generator=function_multi_key_generator, key_mangler=None, async_creation_runner=None, ): \"\"\"Construct a new",
"return (self._hard_invalidated and timestamp < self._hard_invalidated) def was_soft_invalidated(self): return bool(self._soft_invalidated)",
"of :class:`.CacheRegion`. Once set, the invalidation time is honored by",
"\"three\"] values = region.get_multi(keys) dictionary = dict(zip(keys, values)) Keys which",
"as returned by the creator, and only if it returns",
"hard invalidated. :return: Boolean. True if ``timestamp`` is older than",
"making the decorator suitable (with caveats) for use with instance",
"_mutex(self, key): return self._lock_registry.get(key) class _LockWrapper(object): \"\"\"weakref-capable wrapper for threading.Lock\"\"\"",
"classes and/or instances, each of which will be applied in",
"% prefix, None), _config_argument_dict=config_dict, _config_prefix=\"%sarguments.\" % prefix, wrap=config_dict.get( \"%swrap\" %",
".. versionadded:: 0.3.0 \"\"\" if self.key_mangler: key = self.key_mangler(key) value",
"in any way, and is also local to this instance",
"be acquired or not. If it can't, it means a",
"value.metadata['v'] != value_version or self.region_invalidator.is_hard_invalidated( value.metadata['v'])): # dogpile.core understands a",
"returned by the decorated function is missing keys, those keys",
"the async_creation_runner is disabled and is set to ``None``. ..",
"key_mangler=None, async_creation_runner=None, ): \"\"\"Construct a new :class:`.CacheRegion`.\"\"\" self.name = name",
"list(map(lambda key: self.key_mangler(key), keys)) backend_values = self.backend.get_multi(keys) _unexpired_value_fn = self._unexpired_value_fn(",
":class:`.CacheRegion`. Once set, the invalidation time is honored by the",
"self.configure( config_dict[\"%sbackend\" % prefix], expiration_time=config_dict.get( \"%sexpiration_time\" % prefix, None), _config_argument_dict=config_dict,",
"False, the creation time of existing values will be pushed",
"follow:: generate_something.set(3, 5, 6) The above example is equivalent to",
"as a ``datetime.timedelta`` value. The :meth:`.CacheRegion.get_or_create` method as well as",
"key\" given a data creation function and arguments, when using",
":class:`.CacheRegion` itself. .. versionadded:: 0.5.5 .. seealso:: :meth:`.CacheRegion.cache_on_arguments` :meth:`.CacheRegion.get_or_create_multi` \"\"\"",
"self.expiration_time = expiration_time elif isinstance(expiration_time, datetime.timedelta): self.expiration_time = int( compat.timedelta_total_seconds(expiration_time))",
"internally but can be accessed via the ``.name`` parameter, helpful",
"set, the invalidation time is honored by the :meth:`.CacheRegion.get_or_create`, :meth:`.CacheRegion.get_or_create_multi`",
"mutex when finished. This can be used to defer the",
"versionadded:: 0.3.0 \"\"\" if self.key_mangler: key = self.key_mangler(key) value =",
"multiple values from the cache, based on the given keys.",
"the creator, and only if it returns True will that",
"will be applied in a chain to ultimately wrap the",
"self.lock.release() def _create_mutex(self, key): mutex = self.backend.get_mutex(key) if mutex is",
"= None if self.async_creation_runner: def async_creator(mutex): return self.async_creation_runner( self, orig_key,",
"The function is also given an attribute ``invalidate()``, which provides",
"that passed to :meth:`.CacheRegion.cache_on_arguments`. It's not consulted outside this function,",
"decorator internally makes use of the :meth:`.CacheRegion.get_or_create_multi` method to access",
"process is already running a creation function for this key",
"in reversed(wrap): self.wrap(wrapper) if region_invalidator: self.region_invalidator = region_invalidator return self",
"} local_region.configure_from_config(myconfig, \"cache.local.\") memcached_region.configure_from_config(myconfig, \"cache.memcached.\") \"\"\" config_dict = coerce_string_conf(config_dict) return",
"expiration_time_is_callable = compat.callable(expiration_time) if function_multi_key_generator is None: function_multi_key_generator = self.function_multi_key_generator",
"list(map(lambda key: self.key_mangler(key), keys)) self.backend.delete_multi(keys) def cache_on_arguments( self, namespace=None, expiration_time=None,",
"is released and a new value available. If a previous",
"inside the module ``myapp.tools``:: @region.cache_on_arguments(namespace=\"foo\") def one(a, b): return a",
"cache in any way, and is also local to this",
"ready to use for function # decorators, but not yet",
"expiration_time: return NO_VALUE elif self.region_invalidator.is_invalidated( value.metadata[\"ct\"]): return NO_VALUE else: return",
"arguments passed, as well as an optional \"namespace\" parameter in",
"Another typical mangler is the built-in Python function ``str``, which",
"again produce the same cache key of ``myapp.tools:one|foo|3 4`` -",
"in a chain to ultimately wrap the original backend, so",
"keys corresponding to those values which aren't generated or need",
"def generate_key(*arg, **kw): return \":\".join( [kw[k] for k in namespace]",
"4 The key generator will ignore an initial argument of",
"``self`` or ``cls``, making the decorator suitable (with caveats) for",
"which may require key mangling before reaching the cache. ..",
"def one(a, b): return a + b Above, calling ``one(3,",
"is not None: return mutex else: return self._LockWrapper() def invalidate(self,",
"particular value:: generate_something.invalidate(5, 6) Another attribute ``set()`` is added to",
"as part of the cache key. This may be needed",
"the given arguments:: values = generate_something.get(\"k1\", \"k2\", \"k3\") .. versionadded::",
"lock is released to return the new value. .. versionchanged::",
"function and arguments, when using the :meth:`.CacheRegion.cache_on_arguments` method. The structure",
"the key_mangler function, if present. :param creator: function which creates",
"method returns the token ``NO_VALUE``. ``NO_VALUE`` evaluates to False, but",
"bypasses the invalidation time check. .. versionadded:: 0.3.0 Support for",
"that new versions of dogpile.cache can detect cached values from",
"<gh_stars>1000+ from __future__ import with_statement from .. import Lock, NeedRegenerationException",
"returns a value to be used as the ``expiration_time``. This",
"itself. .. versionadded:: 0.5.5 .. seealso:: :meth:`.CacheRegion.cache_on_arguments` :meth:`.CacheRegion.get_or_create_multi` \"\"\" expiration_time_is_callable",
":meth:`.CacheRegion.get_or_create`, :meth:`.CacheRegion.get_or_create_multi` and :meth:`.CacheRegion.get` methods. The method supports both \"hard\"",
"unconditionally regenerated if the creation time is older than the",
"in soft mode. \"\"\" raise NotImplementedError() def was_hard_invalidated(self): \"\"\"Indicate the",
"``time.time()``). If stale, the cached value is ignored and the",
"expiration time required \" \"for soft invalidation\") if expiration_time ==",
"the function itself and its arguments. The decorator internally makes",
"value_fn(value): if value is NO_VALUE: return value elif expiration_time is",
"int( compat.timedelta_total_seconds(expiration_time)) else: raise exception.ValidationError( 'expiration_time is not a number",
"established as part of the cache key. This may be",
"value. .. versionadded 0.5.0 ``expiration_time`` may be optionally passed as",
"than the invalidation timestamp, the value is unconditionally prevented from",
"can be created in a background thread like so:: import",
"value in the cache under the given key.\"\"\" if self.key_mangler:",
"token. ``NO_VALUE`` evaluates to False, but is separate from ``None``",
"= fn return decorate return decorator def cache_multi_on_arguments( self, namespace=None,",
"expiration time which will overide the expiration time already configured",
"``one`` inside the module ``myapp.tools``:: @region.cache_on_arguments(namespace=\"foo\") def one(a, b): return",
"will call the creation function, cache the new values, and",
"decorated function. Similar to ``set()`` is ``refresh()``. This attribute will",
"the existing cache backend will be replaced. Without this flag,",
"generate_something.get(5, 6) .. versionadded:: 0.5.3 Added ``get()`` method to decorated",
"decorator suitable (with caveats) for use with instance or class",
"dbm under Python 2.x in conjunction with Unicode keys. :param",
"True if region was invalidated in hard mode. \"\"\" raise",
"value of the function using a key derived from the",
"to be cached is passed as the first argument, and",
".. versionchanged:: 0.3.0 The value is unconditionally regenerated if the",
"in keys] def wrap_cache_fn(value): if value is NO_VALUE: return False",
"from ..util import NameRegistry from . import exception from ..util",
"from .api import NO_VALUE, CachedValue from .proxy import ProxyBackend from",
"def was_hard_invalidated(self): return bool(self._hard_invalidated) def is_hard_invalidated(self, timestamp): return (self._hard_invalidated and",
"self.key_mangler: mangled_keys = [self.key_mangler(k) for k in sorted_unique_keys] else: mangled_keys",
"time period\" and \"cache until a certain date or time",
"function using a key derived from the function itself and",
"\"k3\") ...a ``refresh()`` method, which will call the creation function,",
"decorator def make_region(*arg, **kw): \"\"\"Instantiate a new :class:`.CacheRegion`. Currently, :func:`.make_region`",
"configured. .. versionadded:: 0.5.7 :param region_invalidator: Optional. Override default invalidation",
"this :class:`.CacheRegion` if not None. To set no expiration, use",
"safely) .. versionadded:: 0.5.0 \"\"\" if self.key_mangler: keys = list(map(lambda",
"6) The function is also given an attribute ``invalidate()``, which",
"False): for wrapper in reversed(wrap): self.wrap(wrapper) if region_invalidator: self.region_invalidator =",
"require immediate regeneration; dogpile logic won't be used. If False,",
"the value of create_value() if the cache is invalid, however",
"async_creator=lambda mutex: async_creator(orig_key, mutex) ): pass try: if mutexes: #",
"time check. .. versionadded:: 0.3.0 Support for the :meth:`.CacheRegion.invalidate` method.",
"result as a dictionary of keys->values, and the final result",
"region.configure(region_invalidator=CustomInvalidationStrategy()) Invalidation strategies that wish to have access to the",
"a current timestamp (using ``time.time()``) to consider all older timestamps",
"is not NO_VALUE) else: result = self.get_or_create_multi( keys, creator, timeout,",
"\"\"\"An integer placed in the :class:`.CachedValue` so that new versions",
"k, v in zip(keys_to_get, new_values) ) if not should_cache_fn: self.backend.set_multi(values_w_created)",
"def is_invalidated(self, timestamp): \"\"\"Check timestamp to determine if it was",
"specified, will be passed to and called by dogpile.lock when",
"< self._invalidated) def was_hard_invalidated(self): return self._is_hard_invalidated is True def is_hard_invalidated(self,",
"ignore_expiration=False): \"\"\"Return a value from the cache, based on the",
"self.region_invalidator = DefaultInvalidationStrategy() def configure( self, backend, expiration_time=None, arguments=None, _config_argument_dict=None,",
"arguments, when using the :meth:`.CacheRegion.cache_on_arguments` method. The structure of this",
"_backend_loader.load(backend) if _config_argument_dict: self.backend = backend_cls.from_config_dict( _config_argument_dict, _config_prefix ) else:",
"also given an attribute ``invalidate()``, which provides for invalidation of",
"used to specify arguments to pluck from \\**kw:: def my_key_generator(namespace,",
"is None: expiration_time = self.expiration_time current_time = time.time() def value_fn(value):",
"should actually be cached or not. If it returns False,",
"later points in the future by way of, for example,",
"return value return value_fn def get_multi(self, keys, expiration_time=None, ignore_expiration=False): \"\"\"Return",
"the value is still returned, but isn't cached. E.g.:: def",
"versionchanged:: 0.3.0 :meth:`.CacheRegion.get` now checks the value's creation time against",
"def runner(): try: value = creator() cache.set(somekey, value) finally: mutex.release()",
"local_region.configure_from_config(myconfig, \"cache.local.\") memcached_region.configure_from_config(myconfig, \"cache.memcached.\") \"\"\" config_dict = coerce_string_conf(config_dict) return self.configure(",
"of the :meth:`.CacheRegion.get_or_create` method to access the cache and conditionally",
":meth:`.CacheRegion.set` which will store a given value directly without calling",
"the function were to produce the value ``3`` as the",
"is raised if a backend is already configured. .. versionadded::",
"\" \"Specify replace_existing_backend=True to replace.\" % self.backend) backend_cls = _backend_loader.load(backend)",
"The function key generation can be entirely replaced on a",
"self.get(key) def refresh(*arg, **kw): key = key_generator(*arg, **kw) value =",
"invalidate(*arg): keys = key_generator(*arg) self.delete_multi(keys) def set_(mapping): keys = list(mapping)",
"from a previous, backwards-incompatible version. \"\"\" class RegionInvalidationStrategy(object): \"\"\"Region invalidation",
"def generate_key(*arg): return namespace + \"_\" + fname + \"_\".join(str(s)",
"anyway. keys_to_get = sorted(mutexes) new_values = creator(*keys_to_get) values_w_created = dict(",
"a sequence corresponding to the order of the keys. The",
"= sorted(set(keys)) if self.key_mangler: mangled_keys = [self.key_mangler(k) for k in",
"not yet for actual caching # later, when config is",
"supplied by the ``expiration_time`` argument, is tested against the creation",
"above for ``MyClass().one(3, 4)`` will again produce the same cache",
"= generate_something(5, 6) The function is also given an attribute",
"be pulled from the cache region unless a new value",
"dogpile lock to generate a new value, or will wait",
"the :class:`.CachedValue` so that new versions of dogpile.cache can detect",
"having awareness of the ``MyClass`` and ``MyOtherClass`` names, as the",
"fn(*[key_lookup[k] for k in keys_to_create]) timeout = expiration_time() if expiration_time_is_callable",
"def invalidate(self, hard=True): \"\"\"Region invalidation. :class:`.CacheRegion` propagated call. The default",
"invalidated in soft mode. :return: Boolean. True if region was",
"and region is invalidated in soft mode. \"\"\" raise NotImplementedError()",
"implementation of :class:`.RegionInvalidationStrategy`. .. versionadded:: 0.6.2 \"\"\" if \"backend\" in",
"behavior for generation of values based on keys corresponds to",
"dictionary = dict(zip(keys, values)) Keys which aren't present in the",
".. versionadded:: 0.5.0 \"\"\" if self.key_mangler: keys = list(map(lambda key:",
"last region invalidation time. \"\"\" raise NotImplementedError() def was_soft_invalidated(self): \"\"\"Indicate",
"datetime from numbers import Number from functools import wraps import",
"A list of :class:`.ProxyBackend` classes and/or instances, each of which",
"It's not consulted outside this function, so in fact can",
"expiration_time=config_dict.get( \"%sexpiration_time\" % prefix, None), _config_argument_dict=config_dict, _config_prefix=\"%sarguments.\" % prefix, wrap=config_dict.get(",
"expiration_time = None if self.async_creation_runner: def async_creator(mutex): return self.async_creation_runner( self,",
"as those passed to :meth:`.CacheRegion.cache_on_arguments`. :param namespace: optional string argument",
"creator, timeout, should_cache_fn) return result def invalidate(*arg): keys = key_generator(*arg)",
"creator functions to later points in the future by way",
"derived from the function itself and the arguments passed to",
"None def invalidate(self, hard=None): if hard: self._soft_invalidated = None self._hard_invalidated",
"is available myconfig = { \"cache.local.backend\":\"dogpile.cache.dbm\", \"cache.local.arguments.filename\":\"/path/to/dbmfile.dbm\", \"cache.memcached.backend\":\"dogpile.cache.pylibmc\", \"cache.memcached.arguments.url\":\"127.0.0.1, 10.0.0.1\",",
"key generation will use the name of the function, the",
"of the :class:`.CacheBackend` to use, and is resolved by loading",
"called, in caching or retrieving. Thus, this can be used",
"a new argument list, and the decorated function is then",
"using the same mechanism as that of :meth:`.CacheRegion.delete_multi`:: generate_something.invalidate(\"k1\", \"k2\",",
"that will produce a list of keys. This function will",
"value else: if expiration_time is None: expiration_time = self.expiration_time current_time",
"...an ``invalidate()`` method, which has the effect of deleting the",
"which will be used on all incoming keys before passing",
"a string, it is ultimately passed directly down to the",
"to this instance of :class:`.CacheRegion`. Once set, the invalidation time",
":meth:`.invalidate` was called. .. versionadded:: 0.3.0 \"\"\" if self.key_mangler: key",
":param hard: if True, cache values will all require immediate",
"invalidation strategy with custom implementation of :class:`.RegionInvalidationStrategy`. .. versionadded:: 0.6.2",
"the value -1. :param should_cache_fn: optional callable function which will",
"dict_create, timeout, wrap_cache_fn) result = dict( (k, v) for k,",
"v in mapping.items()) else: mapping = dict((k, self._value(v)) for k,",
"call the creation function, cache the new values, and return",
"a current timestamp (using ``time.time()``) representing the \"minimum creation time\"",
"keys, expiration_time=None, ignore_expiration=False): \"\"\"Return multiple values from the cache, based",
"NO_VALUE else value for value in ( _unexpired_value_fn(value) for value",
"value. :param expiration_time: optional expiration time which will overide the",
"integer number of seconds, or as a ``datetime.timedelta`` value. ..",
"optional callable function which will receive the value returned by",
"the day, week or time period\" and \"cache until a",
"a list of cache keys using a mechanism similar to",
"if it returns True will that value be placed in",
"expiration_time = None mutexes = {} sorted_unique_keys = sorted(set(keys)) if",
"soft mode. :return: Boolean. True if region was invalidated in",
"prevent the decorator from having awareness of the ``MyClass`` and",
"= set_ decorate.invalidate = invalidate decorate.refresh = refresh decorate.get =",
"value = self._value(created_value) if not should_cache_fn or \\ should_cache_fn(created_value): self.backend.set(key,",
"generate_something(x, y): return somedatabase.query(x, y) The decorated function can then",
"arguments:: values = generate_something.get(\"k1\", \"k2\", \"k3\") .. versionadded:: 0.5.3 Added",
"= dict( (k, v) for k, v in zip(cache_keys, result)",
"the attached backend. ''' # if we were passed a",
"the same arguments you'd pass to the function itself to",
"of which will be applied in a chain to ultimately",
"of keys. For example:: def my_multi_key_generator(namespace, fn, **kw): namespace =",
"return True or False, indicating if the value should actually",
"value = values.get(key, NO_VALUE) if (value is NO_VALUE or value.metadata['v']",
"k, v in mapping.items()) else: mapping = dict((k, self._value(v)) for",
"set_(mapping): keys = list(mapping) gen_keys = key_generator(*keys) self.set_multi(dict( (gen_key, mapping[key])",
"to_str=compat.string_type, function_key_generator=None): \"\"\"A function decorator that will cache the return",
"class on a function as the class is being declared.",
"or :class:`.ProxyBackend` that modifies values, take note this function invokes",
"= mutex if expiration_time is None: expiration_time = self.expiration_time if",
"called on each function argument in order to convert to",
"0.5.0 :param function_multi_key_generator: a function that will produce a list",
"= self.backend.get_mutex(key) if mutex is not None: return mutex else:",
"as that of :meth:`.CacheRegion.get_multi` to retrieve all current values; the",
"\"\"\" if self.key_mangler: key = self.key_mangler(key) self.backend.delete(key) def delete_multi(self, keys):",
"or will wait until the lock is released to return",
"PluginLoader, memoized_property, coerce_string_conf from .util import function_key_generator, function_multi_key_generator from .api",
"all older timestamps effectively invalidated. \"\"\" raise NotImplementedError() def is_hard_invalidated(self,",
"of ``self`` or ``cls``, making the decorator suitable (with caveats)",
"or a callable. :param should_cache_fn: passed to :meth:`.CacheRegion.get_or_create_multi`. This function",
"self.function_multi_key_generator = function_multi_key_generator self.key_mangler = self._user_defined_key_mangler = key_mangler self.async_creation_runner =",
"a particular cache backend. :param name: Optional, a string name",
"generate_something(5, 6) The function is also given an attribute ``invalidate()``,",
"backend_values = self.backend.get_multi(keys) _unexpired_value_fn = self._unexpired_value_fn( expiration_time, ignore_expiration) return [",
"Used by dogpile.core:Lock when appropriate ''' def runner(): try: value",
"**kw): cache_keys = arg keys = key_generator(*arg, **kw) key_lookup =",
"Usage of \"soft\" invalidation requires that the region or the",
"function invokes ``.set_multi()`` for newly generated values using the same",
"versionadded:: 0.5.1 \"\"\" return 'backend' in self.__dict__ def get(self, key,",
"a data creation function and arguments, when using the :meth:`.CacheRegion.cache_on_arguments`",
"name within the same source file, such as those associated",
"generate_something(*keys): return [ somedatabase.query(key) for key in keys ] The",
"will be assembled into a new argument list, and the",
"generate_something.get(\"k1\", \"k2\", \"k3\") .. versionadded:: 0.5.3 Added ``get()`` method to",
"using a sequence of keys derived from the function itself",
"to a particular cache backend. :param name: Optional, a string",
"the :meth:`.CacheRegion.cache_on_arguments` method. Example:: @someregion.cache_multi_on_arguments() def generate_something(*keys): return [ somedatabase.query(key)",
"method) will call upon the value creation function after this",
"keys. The method uses the same approach as :meth:`.Region.get_multi` and",
"creates a new value. :param expiration_time: optional expiration time which",
"is typically a dictionary. :param wrap: Optional. A list of",
"values from the cache. This operation is idempotent (can be",
"itself to represent a particular value:: generate_something.invalidate(5, 6) Another attribute",
"dictionary returned by the decorated function is missing keys, those",
"call upon the value creation function after this time period",
"last region invalidation time and region is invalidated in soft",
"from . import exception from ..util import PluginLoader, memoized_property, coerce_string_conf",
"[self.key_mangler(k) for k in sorted_unique_keys] else: mangled_keys = sorted_unique_keys orig_to_mangled",
"self._hard_invalidated = None def invalidate(self, hard=None): if hard: self._soft_invalidated =",
"of the value which all getters will wait for. With",
"example, it can be passed as a tuple, used to",
"makes use of the :meth:`.CacheRegion.get_or_create` method to access the cache",
"soft invalidated. :return: Boolean. True if ``timestamp`` is older than",
"_config_argument_dict=None, _config_prefix=None, wrap=None, replace_existing_backend=False, region_invalidator=None ): \"\"\"Configure a :class:`.CacheRegion`. The",
"``NO_VALUE`` evaluates to False, but is separate from ``None`` to",
"same values it returns to the calling function. A correct",
"with Lock( self._mutex(mangled_key), gen_value, lambda: get_value(mangled_key), expiration_time, async_creator=lambda mutex: async_creator(orig_key,",
"feature. \"\"\" def __init__( self, name=None, function_key_generator=function_key_generator, function_multi_key_generator=function_multi_key_generator, key_mangler=None, async_creation_runner=None,",
"class declaration mechanics otherwise prevent the decorator from having awareness",
"def invalidate(*arg): keys = key_generator(*arg) self.delete_multi(keys) def set_(mapping): keys =",
"timeout = expiration_time() if expiration_time_is_callable \\ else expiration_time return self.get_or_create(key,",
"one(a, b): return a + b Above, calling ``one(3, 4)``",
"return 'backend' in self.__dict__ def get(self, key, expiration_time=None, ignore_expiration=False): \"\"\"Return",
"the last call to :meth:`.invalidate`. :param key: Key to be",
"any form. For example, it can be passed as a",
"self._lock_registry = NameRegistry(self._create_mutex) if getattr(wrap, '__iter__', False): for wrapper in",
"returned immediately without blocking. If the :meth:`.invalidate` method has been",
"prefix, None), _config_argument_dict=config_dict, _config_prefix=\"%sarguments.\" % prefix, wrap=config_dict.get( \"%swrap\" % prefix,",
"versionchanged:: 0.3.0 The value is unconditionally regenerated if the creation",
"elif isinstance(expiration_time, datetime.timedelta): self.expiration_time = int( compat.timedelta_total_seconds(expiration_time)) else: raise exception.ValidationError(",
"will overide the expiration time already configured on this :class:`.CacheRegion`",
"invalidation\") if expiration_time == -1: expiration_time = None mutexes =",
"callable. :param should_cache_fn: passed to :meth:`.CacheRegion.get_or_create_multi`. This function is given",
"returning that value:: newvalue = generate_something.refresh(5, 6) .. versionadded:: 0.5.0",
"should_cache_fn: passed to :meth:`.CacheRegion.get_or_create_multi`. This function is given a value",
"of :class:`.RegionInvalidationStrategy`. .. versionadded:: 0.6.2 \"\"\" if \"backend\" in self.__dict__",
"a type rather than an instance then # initialize it.",
"``creator()`` should return the generated values as a sequence corresponding",
"the :meth:`.CacheRegion.get_or_create`, :meth:`.CacheRegion.get_or_create_multi` and :meth:`.CacheRegion.get` methods. The method supports both",
"implementation instance to :meth:`.CacheRegion.configure` to override default region invalidation. Example::",
"when finished. This can be used to defer the computation",
"This is the name of the :class:`.CacheBackend` to use, and",
"implementation of ``.set_multi()`` will not modify values in-place on the",
"= creator() cache.set(somekey, value) finally: mutex.release() thread = threading.Thread(target=runner) thread.start()",
"from .. import Lock, NeedRegenerationException from ..util import NameRegistry from",
"the new one is available. Usage of \"soft\" invalidation requires",
"to disambiguate functions of the same name within the same",
"class RegionInvalidationStrategy(object): \"\"\"Region invalidation strategy interface Implement this interface and",
"May be passed as an integer or a callable. :param",
"the newly generated value in the cache. Whether or not",
"by the creator, and only if it returns True will",
"function is also provided with a ``set()`` method, which here",
"generated values using the same values it returns to the",
"call to :meth:`.invalidate`. :param key: Key to be retrieved. While",
"\"cache until a certain date or time passes\". .. versionchanged::",
"the order of the keys. The method uses the same",
"value to be used as the ``expiration_time``. This callable will",
"function, so can be of any type recognized by the",
":class:`.CacheRegion` itself should construct the invalidator given the region as",
"given a non-None expiration time. .. versionadded:: 0.3.0 :param hard:",
"based on the given arguments. Such as:: def my_key_generator(namespace, fn,",
"timestamp < self._invalidated) def was_hard_invalidated(self): return self._is_hard_invalidated is True def",
"the *dogpile lock* can be acquired or not. If it",
"produce the value ``3`` as the value to be cached.",
"= self.key_mangler(key) def get_value(): value = self.backend.get(key) if (value is",
"for k, v in zip(keys_to_get, new_values) ) if not should_cache_fn:",
"effect of deleting the given sequence of keys using the",
"the decorated function should return its result as a list",
"or self.region_invalidator.is_hard_invalidated( value.metadata['v'])): # dogpile.core understands a 0 here as",
"def __init__(self): self._is_hard_invalidated = None self._invalidated = None def invalidate(self,",
"requests for cached-but-expired values will still return promptly. They will",
"check. .. versionchanged:: 0.3.0 :meth:`.CacheRegion.get` now checks the value's creation",
"callable function which will receive each value returned by the",
"refresh decorate.get = get decorate.original = fn return decorate return",
"= region # ... # ... region = CacheRegion() region",
"Added ``refresh()`` method to decorated function. Lastly, the ``get()`` method",
"on Python 2.x, the ``unicode()`` builtin can be substituted, but",
"self._unexpired_value_fn( expiration_time, ignore_expiration) return [ value.payload if value is not",
"on the given keys. Returns values as a list matching",
"None, will override the normal expiration time. May be passed",
"and set values from the backend. If you are using",
"key, or the token ``NO_VALUE`` if no such key exists::",
"The default key generation will use the name of the",
"also provided with a ``set()`` method, which here accepts a",
"wrap=None, replace_existing_backend=False, region_invalidator=None ): \"\"\"Configure a :class:`.CacheRegion`. The :class:`.CacheRegion` itself",
"be retrieved. :param creator: function which accepts a sequence of",
"if not mapping: return if self.key_mangler: mapping = dict(( self.key_mangler(k),",
"arguments to pluck from \\**kw:: def my_key_generator(namespace, fn): def generate_key(*arg,",
"The method supports both \"hard\" and \"soft\" invalidation options. With",
"timestamp to determine if it was invalidated. :return: Boolean. True",
"passed the mutex and is responsible releasing that mutex when",
"type(proxy)) self.backend = proxy.wrap(self.backend) def _mutex(self, key): return self._lock_registry.get(key) class",
":meth:`.CacheRegion.configure` method already. .. versionadded:: 0.5.1 \"\"\" return 'backend' in",
"block; async_creator will not be invoked. However, subsequent requests for",
"applies :meth:`.get_or_create` to any function using a decorator. :meth:`.CacheRegion.get_or_create_multi` -",
"soft invalidation\") if expiration_time == -1: expiration_time = None if",
"def _create_mutex(self, key): mutex = self.backend.get_mutex(key) if mutex is not",
"the return value of the function using a key derived",
"value is still returned, but isn't cached. E.g.:: def dont_cache_none(value):",
"of keys to be generated is passed to ``creator()``, and",
"value whose creation time is prior to this timestamp is",
"k, v in mapping.items()) self.backend.set_multi(mapping) def delete(self, key): \"\"\"Remove a",
"safely) \"\"\" if self.key_mangler: key = self.key_mangler(key) self.backend.delete(key) def delete_multi(self,",
"method to access the cache and conditionally call the function.",
"default key generator :func:`.kwarg_function_key_generator` - optional gen that also uses",
"= key_generator(*arg, **kw) self.set(key, value) def get(*arg, **kw): key =",
"the dictionary returned by the decorated function is missing keys,",
"make_region() # regions are ready to use for function #",
"a new function that generates the key based on the",
"return value decorate.set = set_ decorate.invalidate = invalidate decorate.refresh =",
"and \\ current_time - value.metadata[\"ct\"] > expiration_time: return NO_VALUE elif",
"if it was hard invalidated. :return: Boolean. True if ``timestamp``",
"entirely replaced on a per-region basis using the ``function_key_generator`` argument",
"used as:: @my_region.cache_on_arguments(namespace=('x', 'y')) def my_function(a, b, **kw): return my_data()",
"by the :meth:`.invalidate` method. If a value is present, but",
"so that the string length is fixed. To disable all",
"expiration time for the cached function result. Example use cases",
"return values from the function using a sequence of keys",
"to :meth:`.CacheRegion.get_or_create`. .. versionadded:: 0.4.3 :param to_str: callable, will be",
":class:`.CacheBackend` to use, and is resolved by loading the class",
"string name for the region. This isn't used internally but",
"blocking. If the :meth:`.invalidate` method has been called, and the",
"This can be used to defer the computation of expensive",
"threading def async_creation_runner(cache, somekey, creator, mutex): ''' Used by dogpile.core:Lock",
"and region is invalidated in hard mode. \"\"\" raise NotImplementedError()",
"way of, for example, a background thread, a long-running queue,",
"''' Used by dogpile.core:Lock when appropriate ''' def runner(): try:",
"value.payload def _unexpired_value_fn(self, expiration_time, ignore_expiration): if ignore_expiration: return lambda value:",
"which provides for invalidation of the value. Pass to ``invalidate()``",
"same approach as :meth:`.Region.get_multi` and :meth:`.Region.set_multi` to get and set",
"and is used normally to disambiguate two functions of the",
"\"k2\", \"k3\") ...and a ``get()`` method, which will return values",
"backend(self): raise exception.RegionNotConfigured( \"No backend is configured on this region.\")",
"won't be used. If False, the creation time of existing",
"matching the keys given. E.g.:: values = region.get_multi([\"one\", \"two\", \"three\"])",
"function with the optional namespace and with the string form",
"used depends on if the *dogpile lock* can be acquired",
"exception is raised if a backend is already configured. ..",
"With \"soft\" invalidation, subsequent getters will return the \"old\" value",
"the keys given. E.g.:: values = region.get_multi([\"one\", \"two\", \"three\"]) To",
"a :class:`.CacheBackend` or :class:`.ProxyBackend` that modifies values, take note this",
"may not be used to recreate the value and persist",
"def delete(self, key): \"\"\"Remove a value from the cache. This",
"the current \"invalidation\" time as set by the :meth:`.invalidate` method.",
"expiration_time: Optional expiration time value which will supersede that configured",
"given key.\"\"\" if self.key_mangler: key = self.key_mangler(key) self.backend.set(key, self._value(value)) def",
"is called, in caching or retrieving. Thus, this can be",
":meth:`.CacheRegion.get_or_create_multi`. This function is given a value as returned by",
"used to convert non-string or Unicode keys to bytestrings, which",
"itself should construct the invalidator given the region as an",
"is available, until the lock is released and a new",
"backend or by the key_mangler function, if present. :param creator:",
"If defaults to :func:`.function_key_generator`. :param namespace: optional string argument which",
"is also local to this instance of :class:`.CacheRegion`. Once set,",
"function that generates the key based on the given arguments.",
"return its result as a dictionary of keys->values, and the",
"= function_multi_key_generator( namespace, fn, to_str=to_str) @wraps(fn) def decorate(*arg, **kw): cache_keys",
"should_cache_fn=dont_cache_none) Above, the function returns the value of create_value() if",
"= threading.Thread(target=runner) thread.start() region = make_region( async_creation_runner=async_creation_runner, ).configure( 'dogpile.cache.memcached', expiration_time=5,",
"the new values, and return them:: values = generate_something.refresh(\"k1\", \"k2\",",
"cache values will all require immediate regeneration; dogpile logic won't",
"self.key_mangler(key) value = self.backend.get(key) value = self._unexpired_value_fn( expiration_time, ignore_expiration)(value) return",
"can be applied. .. versionadded:: 0.5.0 .. seealso:: :ref:`changing_backend_behavior` :param",
"return False. return value.payload, 0 else: ct = value.metadata[\"ct\"] if",
"for k, v in mapping.items()) else: mapping = dict((k, self._value(v))",
"for actual caching # later, when config is available myconfig",
"``.set_multi()`` for newly generated values using the same values it",
"check. .. versionadded:: 0.3.0 Support for the :meth:`.CacheRegion.invalidate` method. :param",
"not available\", e.g. # _has_value() will return False. return value.payload,",
"will override the normal expiration time. May be specified as",
"function_key_generator: Optional. A function that will produce a \"cache key\"",
"create_value() if the cache is invalid, however if the return",
"to any function using a decorator. :meth:`.CacheRegion.get_or_create_multi` - multiple key/value",
"than an instance then # initialize it. if type(proxy) ==",
"specify arguments to pluck from \\**kw:: def my_key_generator(namespace, fn): def",
"region = make_region( function_key_generator = my_key_generator ).configure( \"dogpile.cache.dbm\", expiration_time=300, arguments={",
"value, as well as returning that value:: newvalue = generate_something.refresh(5,",
".. versionadded:: 0.5.0 Added ``refresh()`` method to decorated function. Lastly,",
"self._user_defined_key_mangler: self.key_mangler = self.backend.key_mangler self._lock_registry = NameRegistry(self._create_mutex) if getattr(wrap, '__iter__',",
"a list matching the keys given. E.g.:: values = region.get_multi([\"one\",",
"a per-region basis using the ``function_key_generator`` argument present on :func:`.make_region`",
"to consider all older timestamps effectively invalidated. \"\"\" raise NotImplementedError()",
"consulted outside this function, so in fact can be of",
"key_generator(*arg, **kw) self.set(key, value) def get(*arg, **kw): key = key_generator(*arg,",
"dict(zip(keys, values)) Keys which aren't present in the list are",
"function_multi_key_generator: a function that will produce a list of keys.",
"new versions of dogpile.cache can detect cached values from a",
"first request for a key with no associated value will",
"unicode arguments on Python 2.x, the ``unicode()`` builtin can be",
"None, it won't be cached. .. versionadded:: 0.4.3 .. seealso::",
"be passed as a tuple, used to specify arguments to",
"memoized_property, coerce_string_conf from .util import function_key_generator, function_multi_key_generator from .api import",
"mutex) ): pass try: if mutexes: # sort the keys,",
"aren't generated or need regeneration will be assembled into a",
"decorated function will also be a list. When ``asdict==True`` if",
"and conditionally call the function. See that method for additional",
"\"\"\"Return True if the backend has been configured via the",
":meth:`.CacheRegion.get_or_create` method to access the cache and conditionally call the",
"is skipped. The ``namespace`` parameter is optional, and is used",
"won't be cached. .. versionadded:: 0.4.3 .. seealso:: :meth:`.CacheRegion.cache_on_arguments` -",
"key_generator(*arg, **kw) value = fn(*arg, **kw) self.set(key, value) return value",
"of the cache key. This may be needed to disambiguate",
"if expiration_time is None: expiration_time = self.expiration_time if (expiration_time is",
"soft mode. \"\"\" raise NotImplementedError() def was_hard_invalidated(self): \"\"\"Indicate the region",
"NeedRegenerationException() ct = value.metadata[\"ct\"] if self.region_invalidator.is_soft_invalidated(ct): ct = time.time() -",
"for x in arg] ) return generate_key Where the decorator",
"is received by the decorator before it becomes an instance",
"caching or retrieving. Thus, this can be used to determine",
"= proxy() if not issubclass(type(proxy), ProxyBackend): raise TypeError(\"Type %s is",
"self, namespace=None, expiration_time=None, should_cache_fn=None, asdict=False, to_str=compat.string_type, function_multi_key_generator=None): \"\"\"A function decorator",
"self.get_or_create(key, creator, timeout, should_cache_fn) def invalidate(*arg, **kw): key = key_generator(*arg,",
"internally makes use of the :meth:`.CacheRegion.get_or_create` method to access the",
"value = creator() cache.set(somekey, value) finally: mutex.release() thread = threading.Thread(target=runner)",
"the new value, as well as returning that value:: newvalue",
"\"ct\": time.time(), \"v\": value_version }) def set(self, key, value): \"\"\"Place",
"def is_invalidated(self, timestamp): return ((self._soft_invalidated and timestamp < self._soft_invalidated) or",
"key/value version \"\"\" orig_key = key if self.key_mangler: key =",
"to use for function # decorators, but not yet for",
"was_hard_invalidated(self): \"\"\"Indicate the region was invalidated in hard mode. :return:",
"for the function, the arguments passed, as well as an",
"but note this will produce unicode cache keys which may",
"released and a new value available. If a previous value",
"NO_VALUE) if (value is NO_VALUE or value.metadata['v'] != value_version or",
"the cache. .. versionadded:: 0.5.0 :param function_key_generator: a function that",
"self.was_soft_invalidated() and self.is_invalidated(timestamp) class CacheRegion(object): \"\"\"A front end to a",
"return lambda value: value else: if expiration_time is None: expiration_time",
"of this function should be two levels: given the data",
"or class and wraps the attached backend. ''' # if",
"value versus the current time (as reported by ``time.time()``). If",
"Unlike the :meth:`.CacheRegion.cache_on_arguments` method, :meth:`.CacheRegion.cache_multi_on_arguments` works only with a single",
"make_region( function_key_generator = my_key_generator ).configure( \"dogpile.cache.dbm\", expiration_time=300, arguments={ \"filename\":\"file.dbm\" }",
"orig_key = key if self.key_mangler: key = self.key_mangler(key) def get_value():",
"are using a :class:`.CacheBackend` or :class:`.ProxyBackend` that modifies values, take",
"placed in the cache. :param asdict: if ``True``, the decorated",
"values. :param expiration_time: optional expiration time which will overide the",
"value is returned immediately without blocking. If the :meth:`.invalidate` method",
"backwards-incompatible version. \"\"\" class RegionInvalidationStrategy(object): \"\"\"Region invalidation strategy interface Implement",
"the creation time of the retrieved value versus the current",
"new :class:`.CacheRegion`.\"\"\" self.name = name self.function_key_generator = function_key_generator self.function_multi_key_generator =",
"key_generator(*arg, **kw) @wraps(fn) def creator(): return fn(*arg, **kw) timeout =",
"that configured on the :class:`.CacheRegion` itself. .. versionadded:: 0.3.0 :param",
"if expiration_time == -1: expiration_time = None if self.async_creation_runner: def",
"keys)) ) def get(*arg): keys = key_generator(*arg) return self.get_multi(keys) def",
"arguments. The returned result is a list:: result = generate_something(\"key1\",",
"self.delete_multi(keys) def set_(mapping): keys = list(mapping) gen_keys = key_generator(*keys) self.set_multi(dict(",
"list of keys to be generated is passed to ``creator()``,",
"the cache:: generate_something.set({\"k1\": \"value1\", \"k2\": \"value2\", \"k3\": \"value3\"}) ...an ``invalidate()``",
".. versionchanged:: 0.3.0 :meth:`.CacheRegion.get` now checks the value's creation time",
"versionadded:: 0.5.0 \"\"\" if not mapping: return if self.key_mangler: mapping",
"of new values. :param expiration_time: optional expiration time which will",
"list of keys. This function will supersede the one configured",
"is NO_VALUE: return False elif not should_cache_fn: return True else:",
"somedatabase.query(x, y) The decorated function can then be called normally,",
"determine a *dynamic* expiration time for the cached function result.",
"values from the function using a sequence of keys derived",
"timestamp to determine if it was soft invalidated. :return: Boolean.",
"propagated call. The default invalidation system works by setting a",
"= None with Lock( self._mutex(key), gen_value, get_value, expiration_time, async_creator) as",
"self.set_multi( dict(zip(keys, values)) ) return values decorate.set = set_ decorate.invalidate",
"actual caching # later, when config is available myconfig =",
"``True``, the value is returned from the cache if present,",
"get(self, key, expiration_time=None, ignore_expiration=False): \"\"\"Return a value from the cache,",
"a sequence of new values. :param expiration_time: optional expiration time",
"the value which all getters will wait for. With \"soft\"",
"``one(3, 4)`` will produce a cache key as follows:: myapp.tools:one|foo|3",
"the name of the function with the optional namespace and",
"of :class:`.ProxyBackend` classes and/or instances, each of which will be",
"those keys will not be cached. :param to_str: callable, will",
"backend_cls.from_config_dict( _config_argument_dict, _config_prefix ) else: self.backend = backend_cls(arguments or {})",
"async_creator(orig_key, mutex) ): pass try: if mutexes: # sort the",
"versionadded:: 0.5.0 .. seealso:: :ref:`changing_backend_behavior` :param replace_existing_backend: if True, the",
") def get(*arg): keys = key_generator(*arg) return self.get_multi(keys) def refresh(*arg):",
"value: value else: if expiration_time is None: expiration_time = self.expiration_time",
"the same approach as :meth:`.Region.get_multi` and :meth:`.Region.set_multi` to get and",
"part of the cache key. This may be needed to",
"against the creation time of the retrieved value versus the",
"the value should actually be cached or not. If it",
"_LockWrapper(object): \"\"\"weakref-capable wrapper for threading.Lock\"\"\" def __init__(self): self.lock = threading.Lock()",
"if self.async_creation_runner: def async_creator(mutex): return self.async_creation_runner( self, orig_key, creator, mutex)",
"in hard mode. \"\"\" raise NotImplementedError() def is_soft_invalidated(self, timestamp): \"\"\"Check",
"the cache, based on the given key. If the value",
"a sequence of cached values based on a sequence of",
"effectively invalidated. \"\"\" raise NotImplementedError() def is_hard_invalidated(self, timestamp): \"\"\"Check timestamp",
"to access the cache and conditionally call the function. See",
"refresh(*arg): keys = key_generator(*arg) values = fn(*arg) if asdict: self.set_multi(",
"The :class:`.CacheRegion` itself is returned. :param backend: Required. This is",
"The behavior for generation of values based on keys corresponds",
"the :meth:`.CacheRegion.get_or_create` method to access the cache and conditionally call",
"...a ``refresh()`` method, which will call the creation function, cache",
"somemethod(self, x, y): \"\" class MyOtherClass(object): @region.cache_on_arguments(namespace='MOC') def somemethod(self, x,",
"cached values from a previous, backwards-incompatible version. \"\"\" class RegionInvalidationStrategy(object):",
"region or the method is given a non-None expiration time.",
"creator, and only if it returns True will that value",
"be called normally, where data will be pulled from the",
"configuration dictionary and a prefix. Example:: local_region = make_region() memcached_region",
"value is not present, the method returns the token ``NO_VALUE``.",
"for the :meth:`.CacheRegion.invalidate` method. :param key: Key to be retrieved.",
"function. The value to be cached is passed as the",
"\"\"\" if \"backend\" in self.__dict__ and not replace_existing_backend: raise exception.RegionAlreadyConfigured(",
"mode. \"\"\" raise NotImplementedError() def is_invalidated(self, timestamp): \"\"\"Check timestamp to",
"cache under the given key.\"\"\" if self.key_mangler: key = self.key_mangler(key)",
"timestamp): return (self._soft_invalidated and timestamp < self._soft_invalidated) The custom implementation",
"not be cached. :param to_str: callable, will be called on",
"= function_multi_key_generator self.key_mangler = self._user_defined_key_mangler = key_mangler self.async_creation_runner = async_creation_runner",
"function. See that method for additional behavioral details. Unlike the",
"for a key with no associated value will always block;",
"**kw): namespace = fn.__name__ + (namespace or '') def generate_keys(*args):",
"an integer number of seconds, or as a ``datetime.timedelta`` value.",
"means the provided async_creation_runner callable implements. By default the async_creation_runner",
"time is prior to this timestamp is considered to be",
"was called. .. versionadded:: 0.3.0 \"\"\" if self.key_mangler: key =",
"4)`` will produce a cache key as follows:: myapp.tools:one|foo|3 4",
":func:`.function_key_generator`. :param namespace: optional string argument which will be established",
"return fn(*arg, **kw) timeout = expiration_time() if expiration_time_is_callable \\ else",
":meth:`.CacheRegion.get_or_create` \"\"\" def get_value(key): value = values.get(key, NO_VALUE) if (value",
"== -1: expiration_time = None mutexes = {} sorted_unique_keys =",
"is a list:: result = generate_something(\"key1\", \"key2\", \"key3\") The decorator",
"into the cache with the new value, as well as",
"a decorator. :meth:`.CacheRegion.get_or_create_multi` - multiple key/value version \"\"\" orig_key =",
"should_cache_fn: return True else: return should_cache_fn(value) result = self.get_or_create_multi( keys,",
"method will attempt to acquire the dogpile lock to generate",
"the future by way of, for example, a background thread,",
"type(proxy) == type: proxy = proxy() if not issubclass(type(proxy), ProxyBackend):",
"retrieved value's timestamp is older than the invalidation timestamp, the",
"which creates a new value. :param expiration_time: optional expiration time",
"The cache key above for ``MyClass().one(3, 4)`` will again produce",
"will be established as part of the cache key. This",
"the same module, as can occur when decorating instance or",
"to the constructor of the :class:`.CacheBackend` in use, though is",
"versionadded:: 0.5.0 .. seealso:: :meth:`.CacheRegion.cache_multi_on_arguments` :meth:`.CacheRegion.get_or_create` \"\"\" def get_value(key): value",
"def _value(self, value): \"\"\"Return a :class:`.CachedValue` given a value.\"\"\" return",
"left at its default value of ``False``, the decorated function",
"which will overide the expiration time already configured on this",
"same name within the same module, as can occur when",
"the SHA1 mangler found at :func:`.sha1_mangle_key` which coerces keys into",
"now checks the value's creation time against the expiration time,",
"attempt to acquire the dogpile lock to generate a new",
"interface Implement this interface and pass implementation instance to :meth:`.CacheRegion.configure`",
"and the arguments which would normally be passed to the",
"CacheRegion() region = region.configure(region_invalidator=MyInvalidator(region)) .. versionadded:: 0.6.2 .. seealso:: :paramref:`.CacheRegion.configure.region_invalidator`",
"not None and timestamp < self._invalidated) def was_hard_invalidated(self): return self._is_hard_invalidated",
"..util import PluginLoader, memoized_property, coerce_string_conf from .util import function_key_generator, function_multi_key_generator",
"function ``str``, which can be used to convert non-string or",
"will be invoked. .. versionadded:: 0.5.1 \"\"\" self.region_invalidator.invalidate(hard) def configure_from_config(self,",
"def is_hard_invalidated(self, timestamp): return (self._hard_invalidated and timestamp < self._hard_invalidated) def",
"after this time period has passed since the last generation.",
"value def get_or_create_multi( self, keys, creator, expiration_time=None, should_cache_fn=None): \"\"\"Return a",
"values which aren't generated or need regeneration will be assembled",
"if hard: self._soft_invalidated = None self._hard_invalidated = time.time() else: self._soft_invalidated",
":param function_key_generator: Optional. A function that will produce a \"cache",
"below:: class MyClass(object): @region.cache_on_arguments(namespace='MC') def somemethod(self, x, y): \"\" class",
"a valid ProxyBackend\" % type(proxy)) self.backend = proxy.wrap(self.backend) def _mutex(self,",
"async_creation_runner feature. \"\"\" def __init__( self, name=None, function_key_generator=function_key_generator, function_multi_key_generator=function_multi_key_generator, key_mangler=None,",
"the retrieved value versus the current time (as reported by",
"value of create_value() if the cache is invalid, however if",
"the class from the ``dogpile.cache`` entrypoint. :param expiration_time: Optional. The",
"key above for ``MyClass().one(3, 4)`` will again produce the same",
"be applied in a chain to ultimately wrap the original",
"regions are ready to use for function # decorators, but",
"source file, such as those associated with classes - note",
"structure here is passed directly to the constructor of the",
"import function_key_generator, function_multi_key_generator from .api import NO_VALUE, CachedValue from .proxy",
"with_statement from .. import Lock, NeedRegenerationException from ..util import NameRegistry",
"0.5.0 ``expiration_time`` may be optionally passed as a ``datetime.timedelta`` value.",
"# regions are ready to use for function # decorators,",
"the current invalidation time, the ``NO_VALUE`` token is returned. Passing",
"directly down to the cache backend, before being optionally processed",
"the value is unconditionally prevented from being returned. The method",
"cache is invalid, however if the return value is None,",
"disambiguate two functions of the same name within the same",
"0.5.0 :param function_key_generator: a function that will produce a \"cache",
"versionadded:: 0.3.0 :param ignore_expiration: if ``True``, the value is returned",
"convert values to a dictionary, use ``zip()``:: keys = [\"one\",",
"self.backend.get_mutex(key) if mutex is not None: return mutex else: return",
"were passed a type rather than an instance then #",
"supersede the one configured on the :class:`.CacheRegion` itself. .. versionadded::",
"versionadded:: 0.5.0 Added ``refresh()`` method to decorated function. Lastly, the",
"if region_invalidator: self.region_invalidator = region_invalidator return self def wrap(self, proxy):",
"wrapper for threading.Lock\"\"\" def __init__(self): self.lock = threading.Lock() def acquire(self,",
"fname = fn.__name__ def generate_key(*arg): return namespace + \"_\" +",
"keyword arguments :param function_multi_key_generator: Optional. Similar to ``function_key_generator`` parameter, but",
"False, the value is still returned, but isn't cached. ..",
"the name of the :class:`.CacheBackend` to use, and is resolved",
"and :meth:`.CacheRegion.get` methods. The method supports both \"hard\" and \"soft\"",
"Python 2.x, the ``unicode()`` builtin can be substituted, but note",
"prevent deadlocks. # though haven't been able to simulate one",
"fn): def generate_key(*arg, **kw): return \":\".join( [kw[k] for k in",
"async_creation_runner callable implements. By default the async_creation_runner is disabled and",
"haven't been able to simulate one anyway. keys_to_get = sorted(mutexes)",
"provide extra caching possibilities relative to the function. This is",
"bool(hard) self._invalidated = time.time() def is_invalidated(self, timestamp): return (self._invalidated is",
"based on the given arguments:: values = generate_something.get(\"k1\", \"k2\", \"k3\")",
"the key based on the given arguments. Such as:: def",
"'backend' in self.__dict__ def get(self, key, expiration_time=None, ignore_expiration=False): \"\"\"Return a",
"will cache the return value of the function using a",
"fn(*arg, **kw) self.set(key, value) return value decorate.set = set_ decorate.invalidate",
"was_hard_invalidated(self): return bool(self._hard_invalidated) def is_hard_invalidated(self, timestamp): return (self._hard_invalidated and timestamp",
"self.key_mangler(k), self._value(v)) for k, v in mapping.items()) else: mapping =",
"classes - note that the decorator itself can't see the",
"also be a dictionary. If left at its default value",
"dict(zip(keys, cache_keys)) @wraps(fn) def creator(*keys_to_create): return fn(*[key_lookup[k] for k in",
"def get_value(key): value = values.get(key, NO_VALUE) if (value is NO_VALUE",
"available\", e.g. # _has_value() will return False. return value.payload, 0",
"return (self._invalidated is not None and timestamp < self._invalidated) def",
"for the cached function result. Example use cases include \"cache",
"assembled into a new argument list, and the decorated function",
"the function itself to represent a particular value:: generate_something.invalidate(5, 6)",
".. versionadded:: 0.4.3 :param to_str: callable, will be called on",
"@someregion.cache_on_arguments() def generate_something(x, y): return somedatabase.query(x, y) The decorated function",
"method uses the same approach as :meth:`.Region.get_multi` and :meth:`.Region.set_multi` to",
"custom implementation of :class:`.RegionInvalidationStrategy`. .. versionadded:: 0.6.2 \"\"\" if \"backend\"",
"keys: Sequence of keys to be retrieved. :param creator: function",
"store a given value directly without calling the decorated function.",
"the value is still returned, but isn't cached. .. versionadded::",
"example is equivalent to calling ``generate_something(5, 6)``, if the function",
"None: function_key_generator = self.function_key_generator def decorator(fn): if to_str is compat.string_type:",
"With \"hard\" invalidation, :meth:`.CacheRegion.get_or_create` will force an immediate regeneration of",
"function signature, one which takes a simple list of keys",
"example:: class MyClass(object): @region.cache_on_arguments(namespace=\"foo\") def one(self, a, b): return a",
"the cache, based on the given keys. Returns values as",
"a passthrough to :class:`.CacheRegion`. See that class for constructor arguments.",
"ultimately wrap the original backend, so that custom functionality augmentation",
"the ``NO_VALUE`` token is returned. Passing the flag ``ignore_expiration=True`` bypasses",
"actually be cached or not. If it returns False, the",
"itself. .. versionadded:: 0.5.5 .. seealso:: :meth:`.CacheRegion.cache_multi_on_arguments` :meth:`.CacheRegion.get_or_create` \"\"\" expiration_time_is_callable",
"the :class:`.CacheRegion` itself should construct the invalidator given the region",
"is given a non-None expiration time. .. versionadded:: 0.3.0 :param",
"values.update(values_w_created) return [values[orig_to_mangled[k]].payload for k in keys] finally: for mutex",
"week or time period\" and \"cache until a certain date",
"correct implementation of ``.set_multi()`` will not modify values in-place on",
"mechanism similar to that of :meth:`.CacheRegion.cache_on_arguments`, combining the name of",
":meth:`.CacheRegion.get` now checks the value's creation time against the expiration",
"expiration_time() if expiration_time_is_callable \\ else expiration_time return self.get_or_create(key, creator, timeout,",
"was invalidated in soft mode. :return: Boolean. True if region",
"in self.__dict__ and not replace_existing_backend: raise exception.RegionAlreadyConfigured( \"This region is",
"added to provide extra caching possibilities relative to the function.",
"timestamp < self._hard_invalidated) def was_soft_invalidated(self): return bool(self._soft_invalidated) def is_soft_invalidated(self, timestamp):",
"``timestamp`` is older than the last region invalidation time. \"\"\"",
"self.function_multi_key_generator def decorator(fn): key_generator = function_multi_key_generator( namespace, fn, to_str=to_str) @wraps(fn)",
"Any retrieved value whose creation time is prior to this",
"numbers import Number from functools import wraps import threading _backend_loader",
"v in zip(keys_to_get, new_values) ) if not should_cache_fn: self.backend.set_multi(values_w_created) else:",
"arg] ) return generate_key Where the decorator might be used",
"invalidation time is honored by the :meth:`.CacheRegion.get_or_create`, :meth:`.CacheRegion.get_or_create_multi` and :meth:`.CacheRegion.get`",
"the retrieved value's timestamp is older than the invalidation timestamp,",
"or '') def generate_keys(*args): return [namespace + ':' + str(a)",
"self._value(v)) for k, v in zip(keys_to_get, new_values) ) if not",
"using a key derived from the function itself and its",
"as well as an optional \"namespace\" parameter in order to",
"evaluates to False, but is separate from ``None`` to distinguish",
"y): \"\" Above, the ``namespace`` parameter disambiguates between ``somemethod`` on",
"will also be a list. When ``asdict==True`` if the dictionary",
"decorated function and populate a new value into the cache",
"the last generation. :param arguments: Optional. The structure here is",
"key = key_generator(*arg, **kw) self.set(key, value) def get(*arg, **kw): key",
"sequence of keys using the same mechanism as that of",
"the cache under the given key.\"\"\" if self.key_mangler: key =",
"the decorated function should return its result as a dictionary",
"the async_creation_runner feature. \"\"\" def __init__( self, name=None, function_key_generator=function_key_generator, function_multi_key_generator=function_multi_key_generator,",
"time is honored by the :meth:`.CacheRegion.get_or_create`, :meth:`.CacheRegion.get_or_create_multi` and :meth:`.CacheRegion.get` methods.",
"config_dict = coerce_string_conf(config_dict) return self.configure( config_dict[\"%sbackend\" % prefix], expiration_time=config_dict.get( \"%sexpiration_time\"",
"... # ... region = CacheRegion() region = region.configure(region_invalidator=MyInvalidator(region)) ..",
"mutex is not None: return mutex else: return self._LockWrapper() def",
"def dont_cache_none(value): return value is not None value = region.get_or_create(\"some",
") if not should_cache_fn: self.backend.set_multi(values_w_created) else: self.backend.set_multi(dict( (k, v) for",
"example:: def my_multi_key_generator(namespace, fn, **kw): namespace = fn.__name__ + (namespace",
"as an integer number of seconds, or as a ``datetime.timedelta``",
"but its creation time is older than the current invalidation",
"in keys] finally: for mutex in mutexes.values(): mutex.release() def _value(self,",
":class:`.CachedValue` given a value.\"\"\" return CachedValue( value, { \"ct\": time.time(),",
":meth:`.CacheRegion.cache_on_arguments` method, :meth:`.CacheRegion.cache_multi_on_arguments` works only with a single function signature,",
"the :meth:`.CacheRegion.cache_on_arguments` method. The structure of this function should be",
"method. If a value is present, but its creation time",
"is needed when using a backend such as bsddb or",
"declared. :param expiration_time: if not None, will override the normal",
"\"\"\" raise NotImplementedError() class DefaultInvalidationStrategy(RegionInvalidationStrategy): def __init__(self): self._is_hard_invalidated = None",
"= None self._hard_invalidated = time.time() else: self._soft_invalidated = time.time() self._hard_invalidated",
"mode. \"\"\" raise NotImplementedError() class DefaultInvalidationStrategy(RegionInvalidationStrategy): def __init__(self): self._is_hard_invalidated =",
"\"%sexpiration_time\" % prefix, None), _config_argument_dict=config_dict, _config_prefix=\"%sarguments.\" % prefix, wrap=config_dict.get( \"%swrap\"",
"The value is unconditionally regenerated if the creation time is",
"if the return value is None, it won't be cached.",
"used normally to disambiguate two functions of the same name",
"using a backend such as bsddb or dbm under Python",
"Takes a ProxyBackend instance or class and wraps the attached",
"ultimately passed directly down to the cache backend, before being",
"associated value will always block; async_creator will not be invoked.",
"fact can be of any form. For example, it can",
"can be accessed via the ``.name`` parameter, helpful for configuring",
"values from the cache, based on the given keys. Returns",
"for newly generated values using the same values it returns",
"returned. :param backend: Required. This is the name of the",
"None), _config_argument_dict=config_dict, _config_prefix=\"%sarguments.\" % prefix, wrap=config_dict.get( \"%swrap\" % prefix, None),",
"``expiration_time`` may be passed as a callable to :meth:`.CacheRegion.cache_on_arguments`. :param",
"mutex and is responsible releasing that mutex when finished. This",
"strategy interface Implement this interface and pass implementation instance to",
"itself. .. versionadded:: 0.3.0 :param ignore_expiration: if ``True``, the value",
"``datetime.timedelta`` value. .. versionadded 0.5.0 ``expiration_time`` may be optionally passed",
"To set no expiration, use the value -1. :param should_cache_fn:",
"timestamp): return ((self._soft_invalidated and timestamp < self._soft_invalidated) or (self._hard_invalidated and",
"as set by the :meth:`.invalidate` method. If a value is",
"to decorated function. Similar to ``set()`` is ``refresh()``. This attribute",
"b The cache key above for ``MyClass().one(3, 4)`` will again",
"If left at its default value of ``False``, the decorated",
"its result as a list of values, and the final",
"function is also given an attribute ``invalidate()``, which provides for",
"timeout = expiration_time() if expiration_time_is_callable \\ else expiration_time if asdict:",
":class:`.CachedValue` so that new versions of dogpile.cache can detect cached",
"though haven't been able to simulate one anyway. keys_to_get =",
"acquire the dogpile lock to generate a new value, or",
"operation is idempotent (can be called multiple times, or on",
"used in :meth:`.CacheRegion.cache_multi_on_arguments`. Generated function should return list of keys.",
"\"\"\"Check timestamp to determine if it was soft invalidated. :return:",
"the expiration time so that a return+regen will be invoked.",
"or not. If it can't, it means a different thread",
"cached values based on a sequence of keys. The behavior",
"seconds, or as a ``datetime.timedelta`` value. .. versionadded 0.5.0 ``expiration_time``",
"be replaced. Without this flag, an exception is raised if",
"to determine if it was invalidated. :return: Boolean. True if",
"modify values in-place on the submitted ``mapping`` dict. :param keys:",
"gen_key, key in zip(gen_keys, keys)) ) def get(*arg): keys =",
"@my_region.cache_on_arguments(namespace=('x', 'y')) def my_function(a, b, **kw): return my_data() .. seealso::",
"non-existent key, safely) \"\"\" if self.key_mangler: key = self.key_mangler(key) self.backend.delete(key)",
"in hard mode. :return: Boolean. True if region was invalidated",
"as a callable to :meth:`.CacheRegion.cache_on_arguments`. :param should_cache_fn: passed to :meth:`.CacheRegion.get_or_create`.",
"orig_key, creator, mutex) else: async_creator = None with Lock( self._mutex(key),",
"(orig_to_mangled[k], self._value(v)) for k, v in zip(keys_to_get, new_values) ) if",
"that value is returned immediately without blocking. If the :meth:`.invalidate`",
"the submitted ``mapping`` dict. :param keys: Sequence of keys to",
"passed to it. This method is the \"multiple key\" analogue",
"approach as :meth:`.Region.get_multi` and :meth:`.Region.set_multi` to get and set values",
"to prevent deadlocks. # though haven't been able to simulate",
"= get decorate.original = fn return decorate return decorator def",
"the function with the optional namespace and with the string",
"backend will be used. A typical mangler is the SHA1",
"is optional, and is used normally to disambiguate two functions",
"given arguments. Such as:: def my_key_generator(namespace, fn, **kw): fname =",
"a value is present, but its creation time is older",
"will be called on each function argument in order to",
"def cache_multi_on_arguments( self, namespace=None, expiration_time=None, should_cache_fn=None, asdict=False, to_str=compat.string_type, function_multi_key_generator=None): \"\"\"A",
"\"key3\") The decorator internally makes use of the :meth:`.CacheRegion.get_or_create_multi` method",
"in namespace] + [str(x) for x in arg] ) return",
"backend. Defaults to ``None``, in which case the key mangling",
"if not expiration_time or isinstance(expiration_time, Number): self.expiration_time = expiration_time elif",
"the invalidator given the region as an argument:: class MyInvalidator(RegionInvalidationStrategy):",
"system works by setting a current timestamp (using ``time.time()``) to",
"that also uses keyword arguments :param function_multi_key_generator: Optional. Similar to",
"stale value present in the cache. It will be passed",
"return a + b The cache key above for ``MyClass().one(3,",
"= name self.function_key_generator = function_key_generator self.function_multi_key_generator = function_multi_key_generator self.key_mangler =",
"\"filename\":\"file.dbm\" } ) The ``namespace`` is that passed to :meth:`.CacheRegion.cache_on_arguments`.",
"region_invalidator=None ): \"\"\"Configure a :class:`.CacheRegion`. The :class:`.CacheRegion` itself is returned.",
"[namespace + ':' + str(a) for a in args] return",
"will produce a \"cache key\" given a data creation function",
"E.g.:: def dont_cache_none(value): return value is not None value =",
"fname + \"_\".join(str(s) for s in arg) return generate_key region",
"self.set(key, value) def get(*arg, **kw): key = key_generator(*arg, **kw) return",
"not :meth:`.invalidate` was called. .. versionadded:: 0.3.0 \"\"\" if self.key_mangler:",
".. versionadded:: 0.5.7 :param region_invalidator: Optional. Override default invalidation strategy",
"not be invoked. However, subsequent requests for cached-but-expired values will",
"background thread, a long-running queue, or a task manager system",
"which can be used to convert non-string or Unicode keys",
"of the same name within the same module, as can",
"passes\". .. versionchanged:: 0.5.0 ``expiration_time`` may be passed as a",
"expiration_time: optional expiration time which will overide the expiration time",
"the :meth:`.CacheRegion.invalidate` method. :param key: Key to be retrieved. While",
"interprets the cached value in terms of the current \"invalidation\"",
"the cached value is ignored and the ``NO_VALUE`` token is",
"which coerces keys into a SHA1 hash, so that the",
"the idea is to prevent deadlocks. # though haven't been",
"generate_something(\"key1\", \"key2\", \"key3\") The decorator internally makes use of the",
"Unicode keys to bytestrings, which is needed when using a",
"a single function signature, one which takes a simple list",
"noqa value_version = 1 \"\"\"An integer placed in the :class:`.CachedValue`",
"key_mangler: Function which will be used on all incoming keys",
"here is passed directly to the constructor of the :class:`.CacheBackend`",
"cache, based on the given key. If the value is",
"seealso:: :meth:`.CacheRegion.cache_on_arguments` - applies :meth:`.get_or_create` to any function using a",
"key mangling, set to ``False``. Another typical mangler is the",
"mapping): \"\"\"Place new values in the cache under the given",
"behavioral details. E.g.:: @someregion.cache_on_arguments() def generate_something(x, y): return somedatabase.query(x, y)",
"returned. The method will attempt to acquire the dogpile lock",
"a + b The cache key above for ``MyClass().one(3, 4)``",
"only if it returns True will that value be placed",
"background thread like so:: import threading def async_creation_runner(cache, somekey, creator,",
"= None self._hard_invalidated = None def invalidate(self, hard=None): if hard:",
"to ``None``. .. versionadded:: 0.4.2 added the async_creation_runner feature. \"\"\"",
"def is_configured(self): \"\"\"Return True if the backend has been configured",
"method already. .. versionadded:: 0.5.1 \"\"\" return 'backend' in self.__dict__",
"already running a creation function for this key against the",
"new value available. If a previous value is available, that",
"is older than the invalidation timestamp, the value is unconditionally",
"time.time() else: self._soft_invalidated = time.time() self._hard_invalidated = None def is_invalidated(self,",
"\"cache.memcached.arguments.url\":\"127.0.0.1, 10.0.0.1\", } local_region.configure_from_config(myconfig, \"cache.local.\") memcached_region.configure_from_config(myconfig, \"cache.memcached.\") \"\"\" config_dict =",
"from having awareness of the ``MyClass`` and ``MyOtherClass`` names, as",
"a *dynamic* expiration time for the cached function result. Example",
". import backends # noqa value_version = 1 \"\"\"An integer",
"of the keys. The method uses the same approach as",
"\"minimum creation time\" for a value. Any retrieved value whose",
"passed as a callable to :meth:`.CacheRegion.cache_on_arguments`. :param should_cache_fn: passed to",
"from the function itself and the arguments passed to it.",
"backend such as bsddb or dbm under Python 2.x in",
"the backend. Defaults to ``None``, in which case the key",
"to determine if it was soft invalidated. :return: Boolean. True",
"will call upon the value creation function after this time",
"value available. If a previous value is available, that value",
"cache. This operation is idempotent (can be called multiple times,",
"expiration_time=5, arguments={ 'url': '127.0.0.1:11211', 'distributed_lock': True, } ) Remember that",
"older timestamps effectively invalidated. \"\"\" raise NotImplementedError() def is_hard_invalidated(self, timestamp):",
"value = self._unexpired_value_fn( expiration_time, ignore_expiration)(value) return value.payload def _unexpired_value_fn(self, expiration_time,",
"See that method for additional behavioral details. E.g.:: @someregion.cache_on_arguments() def",
"coerce_string_conf(config_dict) return self.configure( config_dict[\"%sbackend\" % prefix], expiration_time=config_dict.get( \"%sexpiration_time\" % prefix,",
"force an immediate regeneration of the value which all getters",
"arg) return generate_key region = make_region( function_key_generator = my_key_generator ).configure(",
"# ... # ... region = CacheRegion() region = region.configure(region_invalidator=MyInvalidator(region))",
"a in args] return generate_keys :param key_mangler: Function which will",
"to that of :meth:`.Region.get_or_create`, with the exception that the ``creator()``",
"the decorated function will also be a list. When ``asdict==True``",
"expiration time, rather than returning the value unconditionally. The method",
"\"three\"]) To convert values to a dictionary, use ``zip()``:: keys",
"def invalidate(*arg, **kw): key = key_generator(*arg, **kw) self.delete(key) def set_(value,",
"be retrieved. While it's typical for a key to be",
"by the backend or by the key_mangler function, if present.",
"raise NotImplementedError() def is_invalidated(self, timestamp): \"\"\"Check timestamp to determine if",
"mode. :return: Boolean. True if region was invalidated in hard",
"itself is returned. :param backend: Required. This is the name",
"def backend(self): raise exception.RegionNotConfigured( \"No backend is configured on this",
"the flag ``ignore_expiration=True`` bypasses the expiration time check. .. versionadded::",
"on a function as the class is being declared. :param",
"same mechanism as that of :meth:`.CacheRegion.get_multi` to retrieve all current",
"self.set_multi(dict( (gen_key, mapping[key]) for gen_key, key in zip(gen_keys, keys)) )",
"(value is NO_VALUE or value.metadata['v'] != value_version or self.region_invalidator.is_hard_invalidated( value.metadata[\"ct\"])):",
"timestamp (using ``time.time()``) representing the \"minimum creation time\" for a",
"async_creation_runner is disabled and is set to ``None``. .. versionadded::",
"used. If False, the creation time of existing values will",
"\"\"\"Place a new value in the cache under the given",
"Example:: @someregion.cache_multi_on_arguments() def generate_something(*keys): return [ somedatabase.query(key) for key in",
"return NO_VALUE elif self.region_invalidator.is_invalidated( value.metadata[\"ct\"]): return NO_VALUE else: return value",
"for use with instance or class methods. Given the example::",
"region_invalidator return self def wrap(self, proxy): ''' Takes a ProxyBackend",
"to the backend. Defaults to ``None``, in which case the",
"self.was_hard_invalidated() and self.is_invalidated(timestamp) def was_soft_invalidated(self): return self._is_hard_invalidated is False def",
"6) Another attribute ``set()`` is added to provide extra caching",
"names, as the function is received by the decorator before",
"a callable, taking no arguments, that returns a value to",
"return generate_keys :param key_mangler: Function which will be used on",
"passed as an integer or a callable. :param should_cache_fn: passed",
"\"old\" value until the new one is available. Usage of",
"in arg])) ) return values else: self.set_multi( dict(zip(keys, values)) )",
"raise exception.ValidationError( 'expiration_time is not a number or timedelta.') if",
"region.get_or_create(\"some key\", create_value, should_cache_fn=dont_cache_none) Above, the function returns the value",
"expiration_time=None, ignore_expiration=False): \"\"\"Return a value from the cache, based on",
"region = make_region( async_creation_runner=async_creation_runner, ).configure( 'dogpile.cache.memcached', expiration_time=5, arguments={ 'url': '127.0.0.1:11211',",
"keys, creator, expiration_time=None, should_cache_fn=None): \"\"\"Return a sequence of cached values",
"decorated function. The value to be cached is passed as",
"(self._soft_invalidated and timestamp < self._soft_invalidated) The custom implementation is injected",
":return: Boolean. True if region was invalidated in soft mode.",
"key in keys ] The decorated function can be called",
"a list of values, and the final result of calling",
"mutex: async_creator(orig_key, mutex) ): pass try: if mutexes: # sort",
"been able to simulate one anyway. keys_to_get = sorted(mutexes) new_values",
"..util import compat import time import datetime from numbers import",
"original backend, so that custom functionality augmentation can be applied.",
"value for value in ( _unexpired_value_fn(value) for value in backend_values",
"return value is not None value = region.get_or_create(\"some key\", create_value,",
":return: Boolean. True if ``timestamp`` is older than the last",
"and with the string form of each key. It will",
"in the cache. :param asdict: if ``True``, the decorated function",
"= key_generator(*arg) values = fn(*arg) if asdict: self.set_multi( dict(zip(keys, [values[a]",
"# noqa value_version = 1 \"\"\"An integer placed in the",
"request for a key with no associated value will always",
"= invalidate decorate.refresh = refresh decorate.get = get return decorate",
"needed:: result = generate_something(5, 6) The function is also given",
"NotImplementedError() class DefaultInvalidationStrategy(RegionInvalidationStrategy): def __init__(self): self._is_hard_invalidated = None self._invalidated =",
"or class methods as below:: class MyClass(object): @region.cache_on_arguments(namespace='MC') def somemethod(self,",
"``invalidate()`` the same arguments you'd pass to the function itself",
"same meaning as those passed to :meth:`.CacheRegion.cache_on_arguments`. :param namespace: optional",
"The decorated function can then be called normally, where data",
"determine if it was hard invalidated. :return: Boolean. True if",
"Boolean. True if ``timestamp`` is older than the last region",
"versionadded:: 0.5.5 .. seealso:: :meth:`.CacheRegion.cache_multi_on_arguments` :meth:`.CacheRegion.get_or_create` \"\"\" expiration_time_is_callable = compat.callable(expiration_time)",
"keys into a SHA1 hash, so that the string length",
"raise NotImplementedError() class DefaultInvalidationStrategy(RegionInvalidationStrategy): def __init__(self): self._is_hard_invalidated = None self._invalidated",
"keys_to_get = sorted(mutexes) new_values = creator(*keys_to_get) values_w_created = dict( (orig_to_mangled[k],",
"to ``invalidate()`` the same arguments you'd pass to the function",
"given keys. .. versionadded:: 0.5.0 \"\"\" if not mapping: return",
"is invalid, however if the return value is None, it",
"a :class:`.CachedValue` given a value.\"\"\" return CachedValue( value, { \"ct\":",
"the given sequence of keys using the same mechanism as",
"passed to :meth:`.CacheRegion.cache_on_arguments`. It's not consulted outside this function, so",
"meaning as those passed to :meth:`.CacheRegion.cache_on_arguments`. :param namespace: optional string",
"pulled from the cache region unless a new value is",
"the :meth:`.CacheRegion.cache_on_arguments` method, :meth:`.CacheRegion.cache_multi_on_arguments` works only with a single function",
"(k, v) for k, v in zip(cache_keys, result) if v",
"configure( self, backend, expiration_time=None, arguments=None, _config_argument_dict=None, _config_prefix=None, wrap=None, replace_existing_backend=False, region_invalidator=None",
"an optional \"namespace\" parameter in order to generate a cache",
"**kw): key = key_generator(*arg, **kw) @wraps(fn) def creator(): return fn(*arg,",
"data creation function, return a new function that generates the",
"be cached. :param to_str: callable, will be called on each",
"else: self.backend.set_multi(dict( (k, v) for k, v in values_w_created.items() if",
"so that a return+regen will be invoked. .. versionadded:: 0.5.1",
"is older than the last region invalidation time. \"\"\" raise",
"the :paramref:`.CacheRegion.configure.region_invalidator` parameter:: region = CacheRegion() region = region.configure(region_invalidator=CustomInvalidationStrategy()) Invalidation",
"= my_key_generator ).configure( \"dogpile.cache.dbm\", expiration_time=300, arguments={ \"filename\":\"file.dbm\" } ) The",
"self.region_invalidator.is_invalidated( value.metadata[\"ct\"]): return NO_VALUE else: return value return value_fn def",
"%s is not a valid ProxyBackend\" % type(proxy)) self.backend =",
"be passed as an integer or a callable. :param should_cache_fn:",
"asdict: self.set_multi( dict(zip(keys, [values[a] for a in arg])) ) return",
"is considered to be expired based on its creation time,",
"the given keys. .. versionadded:: 0.5.0 \"\"\" if not mapping:",
"Added ``get()`` method to decorated function. Parameters passed to :meth:`.CacheRegion.cache_multi_on_arguments`",
"convert to a string. Defaults to ``str()``. If the function",
":meth:`.CacheRegion.get_or_create_multi` and :meth:`.CacheRegion.get` methods. The method supports both \"hard\" and",
"expiration time. .. versionadded:: 0.3.0 :param hard: if True, cache",
"refresh(*arg, **kw): key = key_generator(*arg, **kw) value = fn(*arg, **kw)",
"if ignore_expiration: return lambda value: value else: if expiration_time is",
"the token ``NO_VALUE`` if no such key exists:: value =",
") else: self.backend = backend_cls(arguments or {}) if not expiration_time",
"by the key_mangler function, if present. :param expiration_time: Optional expiration",
"setting a current timestamp (using ``time.time()``) representing the \"minimum creation",
"Sequence of keys to be retrieved. :param creator: function which",
"occur when decorating instance or class methods as below:: class",
"a task manager system like Celery. For a specific example",
"hard=True): \"\"\"Region invalidation. :class:`.CacheRegion` propagated call. The default invalidation system",
".. versionadded:: 0.4.1 Added ``set()`` method to decorated function. Similar",
"argument which will be established as part of the cache",
"time, rather than returning the value unconditionally. The method also",
"self.async_creation_runner: def async_creator(mutex): return self.async_creation_runner( self, orig_key, creator, mutex) else:",
"decorated function. The default key generation will use the name",
"= dict(zip(keys, values)) Keys which aren't present in the list",
"async_creator = None with Lock( self._mutex(key), gen_value, get_value, expiration_time, async_creator)",
"invalidation time check. .. versionadded:: 0.3.0 Support for the :meth:`.CacheRegion.invalidate`",
"is None: function_key_generator = self.function_key_generator def decorator(fn): if to_str is",
"file. :param function_key_generator: Optional. A function that will produce a",
"it returns True will that value be placed in the",
"hard: self._soft_invalidated = None self._hard_invalidated = time.time() else: self._soft_invalidated =",
"namespace, fn, to_str=to_str) @wraps(fn) def decorate(*arg, **kw): cache_keys = arg",
"\"\"\" def get_value(key): value = values.get(key, NO_VALUE) if (value is",
"v) for k, v in zip(cache_keys, result) if v is",
"always block; async_creator will not be invoked. However, subsequent requests",
"If False, the creation time of existing values will be",
"for cached-but-expired values will still return promptly. They will be",
"ignore_expiration) return [ value.payload if value is not NO_VALUE else",
"passed as an integer number of seconds, or as a",
"function, the arguments passed, as well as an optional \"namespace\"",
"fn.__name__ def generate_key(*arg): return namespace + \"_\" + fname +",
"form. For example, it can be passed as a tuple,",
"thread like so:: import threading def async_creation_runner(cache, somekey, creator, mutex):",
"be accessed via the ``.name`` parameter, helpful for configuring a",
"Required. This is the name of the :class:`.CacheBackend` to use,",
"time\" for a value. Any retrieved value whose creation time",
"order to convert to a string. Defaults to ``str()``. If",
"key\". This function will supersede the one configured on the",
"function. A correct implementation of ``.set_multi()`` will not modify values",
"``get()`` method, which will return values based on the given",
"generate_key Where the decorator might be used as:: @my_region.cache_on_arguments(namespace=('x', 'y'))",
"the ``get()`` method returns either the value cached for the",
"``True``, the decorated function should return its result as a",
"arguments. Like :meth:`.CacheRegion.cache_on_arguments`, the decorated function is also provided with",
"function # decorators, but not yet for actual caching #",
"\"\"\"A function decorator that will cache the return value of",
"if (value is NO_VALUE or value.metadata['v'] != value_version or self.region_invalidator.is_hard_invalidated(",
"available, that value is returned immediately without blocking. If the",
"to that of :meth:`.CacheRegion.cache_on_arguments`, combining the name of the function",
"decorator. :meth:`.CacheRegion.get_or_create_multi` - multiple key/value version \"\"\" orig_key = key",
"result def invalidate(*arg): keys = key_generator(*arg) self.delete_multi(keys) def set_(mapping): keys",
"def get(*arg): keys = key_generator(*arg) return self.get_multi(keys) def refresh(*arg): keys",
"if not should_cache_fn or \\ should_cache_fn(created_value): self.backend.set(key, value) return value.payload,",
"the ``MyClass`` and ``MyOtherClass`` names, as the function is received",
"for wrapper in reversed(wrap): self.wrap(wrapper) if region_invalidator: self.region_invalidator = region_invalidator",
"+ (namespace or '') def generate_keys(*args): return [namespace + ':'",
"0.3.0 Support for the :meth:`.CacheRegion.invalidate` method. :param key: Key to",
"given a data creation function and arguments, when using the",
"no such key exists:: value = generate_something.get(5, 6) .. versionadded::",
"invalidation\") if expiration_time == -1: expiration_time = None if self.async_creation_runner:",
"Once set, the invalidation time is honored by the :meth:`.CacheRegion.get_or_create`,",
"available. If a previous value is available, that value is",
"form of each key. It will then consult the cache",
"cache key. This may be needed to disambiguate functions of",
"= 1 \"\"\"An integer placed in the :class:`.CachedValue` so that",
"the key mangling function recommended by the cache backend will",
"(with caveats) for use with instance or class methods. Given",
"new value. .. versionchanged:: 0.3.0 The value is unconditionally regenerated",
"a \"cache key\" given a data creation function and arguments,",
"when using a backend such as bsddb or dbm under",
"on its creation time, the given creation function may or",
"example, a background thread, a long-running queue, or a task",
"def dict_create(*keys): d_values = creator(*keys) return [ d_values.get(key_lookup[k], NO_VALUE) for",
"wrapper in reversed(wrap): self.wrap(wrapper) if region_invalidator: self.region_invalidator = region_invalidator return",
"here as # \"the value is not available\", e.g. #",
"``invalidate()`` method, which has the effect of deleting the given",
"if self.key_mangler: key = self.key_mangler(key) value = self.backend.get(key) value =",
"keys and values to set in the cache:: generate_something.set({\"k1\": \"value1\",",
"cache_keys = arg keys = key_generator(*arg, **kw) key_lookup = dict(zip(keys,",
"prevented from being returned. The method will attempt to acquire",
"or on a non-existent key, safely) .. versionadded:: 0.5.0 \"\"\"",
"): \"\"\"Construct a new :class:`.CacheRegion`.\"\"\" self.name = name self.function_key_generator =",
"via the :meth:`.CacheRegion.configure` method already. .. versionadded:: 0.5.1 \"\"\" return",
"the key_mangler function, if present. :param expiration_time: Optional expiration time",
"under the given keys. .. versionadded:: 0.5.0 \"\"\" if not",
":param function_key_generator: a function that will produce a \"cache key\".",
":param keys: Sequence of keys to be retrieved. :param creator:",
"which would normally be passed to the function should follow::",
"value_version or self.region_invalidator.is_hard_invalidated( value.metadata['v'])): # dogpile.core understands a 0 here",
"a callable. :param should_cache_fn: passed to :meth:`.CacheRegion.get_or_create_multi`. This function is",
"d_values.get(key_lookup[k], NO_VALUE) for k in keys] def wrap_cache_fn(value): if value",
"used. A typical mangler is the SHA1 mangler found at",
"A correct implementation of ``.set_multi()`` will not modify values in-place",
"directly without calling the decorated function. The value to be",
":meth:`.CacheRegion.get_or_create` method as well as the :meth:`.CacheRegion.cache_on_arguments` decorator (though note:",
"the :meth:`.CacheRegion.cache_on_arguments` decorator (though note: **not** the :meth:`.CacheRegion.get` method) will",
"= dict(zip(keys, cache_keys)) @wraps(fn) def creator(*keys_to_create): return fn(*[key_lookup[k] for k",
"= PluginLoader(\"dogpile.cache\") register_backend = _backend_loader.register from . import backends #",
"when using the :meth:`.CacheRegion.cache_on_arguments` method. The structure of this function",
"``None``, in which case the key mangling function recommended by",
"is responsible releasing that mutex when finished. This can be",
"this time period has passed since the last generation. :param",
"passed to :meth:`.CacheRegion.get_or_create_multi`. This function is given a value as",
"versionadded:: 0.5.0 :param function_multi_key_generator: a function that will produce a",
"(self._hard_invalidated and timestamp < self._hard_invalidated) def was_soft_invalidated(self): return bool(self._soft_invalidated) def",
"works only with a single function signature, one which takes",
"value = region.get_or_create(\"some key\", create_value, should_cache_fn=dont_cache_none) Above, the function returns",
"that modifies values, take note this function invokes ``.set_multi()`` for",
"by the \"creator\", and will then return True or False,",
"@region.cache_on_arguments(namespace='MOC') def somemethod(self, x, y): \"\" Above, the ``namespace`` parameter",
"computation of expensive creator functions to later points in the",
"one anyway. keys_to_get = sorted(mutexes) new_values = creator(*keys_to_get) values_w_created =",
"self.key_mangler(key) self.backend.delete(key) def delete_multi(self, keys): \"\"\"Remove multiple values from the",
"value is not NO_VALUE else value for value in (",
"same arguments you'd pass to the function itself to represent",
"a non-None expiration time. .. versionadded:: 0.3.0 :param hard: if",
"if not self._user_defined_key_mangler: self.key_mangler = self.backend.key_mangler self._lock_registry = NameRegistry(self._create_mutex) if",
"expiration_time=300, arguments={ \"filename\":\"file.dbm\" } ) The ``namespace`` is that passed",
".. versionadded:: 0.4.3 .. seealso:: :meth:`.CacheRegion.cache_on_arguments` - applies :meth:`.get_or_create` to",
"given the data creation function, return a new function that",
"b): return a + b The cache key above for",
"\"\"\" raise NotImplementedError() def was_soft_invalidated(self): \"\"\"Indicate the region was invalidated",
"if we were passed a type rather than an instance",
"cache key as follows:: myapp.tools:one|foo|3 4 The key generator will",
"list of keys. For example:: def my_multi_key_generator(namespace, fn, **kw): namespace",
"(k, v) for k, v in values_w_created.items() if should_cache_fn(v[0]) ))",
"function and populate a new value into the cache with",
"``MyClass`` and ``MyOtherClass``. Python class declaration mechanics otherwise prevent the",
"is_hard_invalidated(self, timestamp): return self.was_hard_invalidated() and self.is_invalidated(timestamp) def was_soft_invalidated(self): return self._is_hard_invalidated",
"value = self.backend.get(key) value = self._unexpired_value_fn( expiration_time, ignore_expiration)(value) return value.payload",
"return namespace + \"_\" + fname + \"_\".join(str(s) for s",
"mutex.release() thread = threading.Thread(target=runner) thread.start() region = make_region( async_creation_runner=async_creation_runner, ).configure(",
"should return the generated values as a sequence corresponding to",
"has the effect of deleting the given sequence of keys",
"':' + str(a) for a in args] return generate_keys :param",
"\"hard\" invalidation, :meth:`.CacheRegion.get_or_create` will force an immediate regeneration of the",
"the region was invalidated in soft mode. :return: Boolean. True",
"timedelta.') if not self._user_defined_key_mangler: self.key_mangler = self.backend.key_mangler self._lock_registry = NameRegistry(self._create_mutex)",
"value of ``None``. By default, the configured expiration time of",
"if the cache is invalid, however if the return value",
"invalidation, :meth:`.CacheRegion.get_or_create` will force an immediate regeneration of the value",
"async_creator) as value: return value def get_or_create_multi( self, keys, creator,",
"is given a value as returned by the creator, and",
"is_soft_invalidated(self, timestamp): \"\"\"Check timestamp to determine if it was soft",
"subsequent requests for cached-but-expired values will still return promptly. They",
"the cache key. This may be needed to disambiguate functions",
"will override the normal expiration time. May be passed as",
"timestamp, the value is unconditionally prevented from being returned. The",
"as an argument:: class MyInvalidator(RegionInvalidationStrategy): def __init__(self, region): self.region =",
"passed since the last generation. :param arguments: Optional. The structure",
"a :class:`.CacheRegion`. The :class:`.CacheRegion` itself is returned. :param backend: Required.",
"that value:: newvalue = generate_something.refresh(5, 6) .. versionadded:: 0.5.0 Added",
"soft mode. \"\"\" raise NotImplementedError() def is_invalidated(self, timestamp): \"\"\"Check timestamp",
"a cached value of ``None``. By default, the configured expiration",
"if the creation time is older than the last call",
"result of calling the decorated function will also be a",
"value until the new one is available. Usage of \"soft\"",
"expiration_time, ignore_expiration) return [ value.payload if value is not NO_VALUE",
"CachedValue( value, { \"ct\": time.time(), \"v\": value_version }) def set(self,",
"- expiration_time - .0001 return value.payload, ct def gen_value(): created_value",
"It will be passed the mutex and is responsible releasing",
"on the given key. If the value is not present,",
"False def is_soft_invalidated(self, timestamp): return self.was_soft_invalidated() and self.is_invalidated(timestamp) class CacheRegion(object):",
"for threading.Lock\"\"\" def __init__(self): self.lock = threading.Lock() def acquire(self, wait=True):",
"keys. :param async_creation_runner: A callable that, when specified, will be",
"invalidate(*arg, **kw): key = key_generator(*arg, **kw) self.delete(key) def set_(value, *arg,",
"region from a config file. :param function_key_generator: Optional. A function",
"return self._LockWrapper() def invalidate(self, hard=True): \"\"\"Invalidate this :class:`.CacheRegion`. The default",
"final result of calling the decorated function will also be",
"timestamp < self._hard_invalidated)) def was_hard_invalidated(self): return bool(self._hard_invalidated) def is_hard_invalidated(self, timestamp):",
"value does not exist or is considered to be expired",
"timeout, should_cache_fn) def invalidate(*arg, **kw): key = key_generator(*arg, **kw) self.delete(key)",
"of the same name within the same source file, such",
"keys, the idea is to prevent deadlocks. # though haven't",
"values; the originally passed keys corresponding to those values which",
"method, which here accepts a mapping of keys and values",
"timestamp is older than the invalidation timestamp, the value is",
"# _has_value() will return False. return value.payload, 0 else: ct",
"being optionally processed by the key_mangler function, so can be",
"represent a particular value:: generate_something.invalidate(5, 6) Another attribute ``set()`` is",
"for. With \"soft\" invalidation, subsequent getters will return the \"old\"",
"the value ``3`` as the value to be cached. ..",
"calling ``one(3, 4)`` will produce a cache key as follows::",
"\"value2\", \"k3\": \"value3\"}) ...an ``invalidate()`` method, which has the effect",
"seealso:: :meth:`.CacheRegion.cache_on_arguments` :meth:`.CacheRegion.get_or_create_multi` \"\"\" expiration_time_is_callable = compat.callable(expiration_time) if function_multi_key_generator is",
"The list of keys to be generated is passed to",
"If the value does not exist or is considered to",
"raised if a backend is already configured. .. versionadded:: 0.5.7",
"make_region(*arg, **kw): \"\"\"Instantiate a new :class:`.CacheRegion`. Currently, :func:`.make_region` is a",
"async_creation_runner: A callable that, when specified, will be passed to",
"times, or on a non-existent key, safely) .. versionadded:: 0.5.0",
"of the :meth:`.CacheRegion.get_or_create_multi` method to access the cache and conditionally",
"\"cache.local.backend\":\"dogpile.cache.dbm\", \"cache.local.arguments.filename\":\"/path/to/dbmfile.dbm\", \"cache.memcached.backend\":\"dogpile.cache.pylibmc\", \"cache.memcached.arguments.url\":\"127.0.0.1, 10.0.0.1\", } local_region.configure_from_config(myconfig, \"cache.local.\") memcached_region.configure_from_config(myconfig, \"cache.memcached.\")",
"= { \"cache.local.backend\":\"dogpile.cache.dbm\", \"cache.local.arguments.filename\":\"/path/to/dbmfile.dbm\", \"cache.memcached.backend\":\"dogpile.cache.pylibmc\", \"cache.memcached.arguments.url\":\"127.0.0.1, 10.0.0.1\", } local_region.configure_from_config(myconfig, \"cache.local.\")",
"self.key_mangler: mapping = dict(( self.key_mangler(k), self._value(v)) for k, v in",
"cache with the new value, as well as returning that",
"in order to generate a cache key. Given a function",
"getters will wait for. With \"soft\" invalidation, subsequent getters will",
"region.get_multi([\"one\", \"two\", \"three\"]) To convert values to a dictionary, use",
":class:`.CacheRegion`. The :class:`.CacheRegion` itself is returned. :param backend: Required. This",
"threading.Lock\"\"\" def __init__(self): self.lock = threading.Lock() def acquire(self, wait=True): return",
"issubclass(type(proxy), ProxyBackend): raise TypeError(\"Type %s is not a valid ProxyBackend\"",
"invoked. .. versionadded:: 0.5.1 \"\"\" self.region_invalidator.invalidate(hard) def configure_from_config(self, config_dict, prefix):",
"argument, and the arguments which would normally be passed to",
"a mapping of keys and values to set in the",
"function is used depends on if the *dogpile lock* can",
"each function argument in order to convert to a string.",
"function that will produce a list of keys. This function",
"PluginLoader(\"dogpile.cache\") register_backend = _backend_loader.register from . import backends # noqa",
"follows:: myapp.tools:one|foo|3 4 The key generator will ignore an initial",
"arguments. Such as:: def my_key_generator(namespace, fn, **kw): fname = fn.__name__",
"to bytestrings, which is needed when using a backend such",
"value): \"\"\"Place a new value in the cache under the",
"caveats) for use with instance or class methods. Given the",
"each cache key. :param expiration_time: if not None, will override",
"**kw) return self.get(key) def refresh(*arg, **kw): key = key_generator(*arg, **kw)",
"was hard invalidated. :return: Boolean. True if ``timestamp`` is older",
"the value's creation time against the expiration time, rather than",
"\"\"\"A front end to a particular cache backend. :param name:",
"a different thread or process is already running a creation",
"``function_key_generator`` argument present on :func:`.make_region` and :class:`.CacheRegion`. If defaults to",
"with classes - note that the decorator itself can't see",
"mangled_keys = sorted_unique_keys orig_to_mangled = dict(zip(sorted_unique_keys, mangled_keys)) values = dict(zip(mangled_keys,",
"and ``MyOtherClass``. Python class declaration mechanics otherwise prevent the decorator",
"this can be used to determine a *dynamic* expiration time",
"time for the cached function result. Example use cases include",
"function decorator that will cache multiple return values from the",
"the list are returned as the ``NO_VALUE`` token. ``NO_VALUE`` evaluates",
"key generation can be entirely replaced on a per-region basis",
"instance or class and wraps the attached backend. ''' #",
"value) return value.payload, value.metadata[\"ct\"] if expiration_time is None: expiration_time =",
"namespace=None, expiration_time=None, should_cache_fn=None, to_str=compat.string_type, function_key_generator=None): \"\"\"A function decorator that will",
"be called whenever the decorated function itself is called, in",
"**not** the :meth:`.CacheRegion.get` method) will call upon the value creation",
"created in a background thread like so:: import threading def",
"May be passed as an integer number of seconds, or",
"disable all key mangling, set to ``False``. Another typical mangler",
"the name ``self`` is skipped. The ``namespace`` parameter is optional,",
"None def invalidate(self, hard=True): self._is_hard_invalidated = bool(hard) self._invalidated = time.time()",
"module ``myapp.tools``:: @region.cache_on_arguments(namespace=\"foo\") def one(a, b): return a + b",
"default region invalidation. Example:: class CustomInvalidationStrategy(RegionInvalidationStrategy): def __init__(self): self._soft_invalidated =",
"``MyOtherClass`` names, as the function is received by the decorator",
":meth:`.CacheRegion.cache_on_arguments`. :param should_cache_fn: passed to :meth:`.CacheRegion.get_or_create`. .. versionadded:: 0.4.3 :param",
"of the day, week or time period\" and \"cache until",
"not affect the data in the cache in any way,",
"E.g.:: values = region.get_multi([\"one\", \"two\", \"three\"]) To convert values to",
"return fn(*[key_lookup[k] for k in keys_to_create]) timeout = expiration_time() if",
"acquired or not. If it can't, it means a different",
":param should_cache_fn: passed to :meth:`.CacheRegion.get_or_create`. .. versionadded:: 0.4.3 :param to_str:",
"should_cache_fn(created_value): self.backend.set(key, value) return value.payload, value.metadata[\"ct\"] if expiration_time is None:",
"the cache region unless a new value is needed:: result",
"Passing the flag ``ignore_expiration=True`` bypasses the expiration time check. ..",
"0.3.0 \"\"\" if self.key_mangler: key = self.key_mangler(key) value = self.backend.get(key)",
"awareness of the ``MyClass`` and ``MyOtherClass`` names, as the function",
"not be used to recreate the value and persist the",
"self.backend = backend_cls(arguments or {}) if not expiration_time or isinstance(expiration_time,",
"generation. :param arguments: Optional. The structure here is passed directly",
"conditionally call the function. See that method for additional behavioral",
"= expiration_time elif isinstance(expiration_time, datetime.timedelta): self.expiration_time = int( compat.timedelta_total_seconds(expiration_time)) else:",
"time period has passed since the last generation. :param arguments:",
"return self.lock.acquire(wait) def release(self): self.lock.release() def _create_mutex(self, key): mutex =",
"self._invalidated = time.time() def is_invalidated(self, timestamp): return (self._invalidated is not",
"helpful for configuring a region from a config file. :param",
"``NO_VALUE``. ``NO_VALUE`` evaluates to False, but is separate from ``None``",
"expiration_time, async_creator) as value: return value def get_or_create_multi( self, keys,",
"then consult the cache using the same mechanism as that",
"ProxyBackend): raise TypeError(\"Type %s is not a valid ProxyBackend\" %",
"than the current invalidation time, the ``NO_VALUE`` token is returned.",
"will ignore an initial argument of ``self`` or ``cls``, making",
"decorated function can be called normally. The decorator will produce",
"associated with classes - note that the decorator itself can't",
":param key: Key to be retrieved. While it's typical for",
"been configured via the :meth:`.CacheRegion.configure` method already. .. versionadded:: 0.5.1",
"... region = CacheRegion() region = region.configure(region_invalidator=MyInvalidator(region)) .. versionadded:: 0.6.2",
"_has_value() will return False. return value.payload, 0 else: ct =",
"suitable (with caveats) for use with instance or class methods.",
"should_cache_fn=None): \"\"\"Return a cached value based on the given key.",
"a given value directly without calling the decorated function. The",
"in orig_to_mangled.items(): with Lock( self._mutex(mangled_key), gen_value, lambda: get_value(mangled_key), expiration_time, async_creator=lambda",
"needed to disambiguate functions of the same name within the",
"\"value3\"}) ...an ``invalidate()`` method, which has the effect of deleting",
"though is typically a dictionary. :param wrap: Optional. A list",
"The returned result is a list:: result = generate_something(\"key1\", \"key2\",",
"is NO_VALUE: return value elif expiration_time is not None and",
"= key_generator(*keys) self.set_multi(dict( (gen_key, mapping[key]) for gen_key, key in zip(gen_keys,",
"a value to be used as the ``expiration_time``. This callable",
"as arguments. Like :meth:`.CacheRegion.cache_on_arguments`, the decorated function is also provided",
"get decorate.original = fn return decorate return decorator def cache_multi_on_arguments(",
"False. return value.payload, 0 else: ct = value.metadata[\"ct\"] if self.region_invalidator.is_soft_invalidated(ct):",
"any type recognized by the backend or by the key_mangler",
"the :class:`.CacheRegion` itself. .. versionadded:: 0.5.5 .. seealso:: :meth:`.CacheRegion.cache_multi_on_arguments` :meth:`.CacheRegion.get_or_create`",
"to disambiguate two functions of the same name within the",
"given arguments:: values = generate_something.get(\"k1\", \"k2\", \"k3\") .. versionadded:: 0.5.3",
"to defer the computation of expensive creator functions to later",
"is_invalidated(self, timestamp): return ((self._soft_invalidated and timestamp < self._soft_invalidated) or (self._hard_invalidated",
"be used to defer the computation of expensive creator functions",
"E.g.:: @someregion.cache_on_arguments() def generate_something(x, y): return somedatabase.query(x, y) The decorated",
"timestamp): \"\"\"Check timestamp to determine if it was soft invalidated.",
"to be retrieved. While it's typical for a key to",
"key, expiration_time=None, ignore_expiration=False): \"\"\"Return a value from the cache, based",
"it. if type(proxy) == type: proxy = proxy() if not",
"older than the last region invalidation time and region is",
"the region. This isn't used internally but can be accessed",
"= dict(( self.key_mangler(k), self._value(v)) for k, v in mapping.items()) else:",
"function. Lastly, the ``get()`` method returns either the value cached",
"as a list of values, and the final result of",
"of values, and the final result of calling the decorated",
"SHA1 mangler found at :func:`.sha1_mangle_key` which coerces keys into a",
"ProxyBackend\" % type(proxy)) self.backend = proxy.wrap(self.backend) def _mutex(self, key): return",
"self.expiration_time if (expiration_time is None and self.region_invalidator.was_soft_invalidated()): raise exception.DogpileCacheException( \"Non-None",
"v in values_w_created.items() if should_cache_fn(v[0]) )) values.update(values_w_created) return [values[orig_to_mangled[k]].payload for",
"the module ``myapp.tools``:: @region.cache_on_arguments(namespace=\"foo\") def one(a, b): return a +",
"a cache key as follows:: myapp.tools:one|foo|3 4 The key generator",
"The custom implementation is injected into a :class:`.CacheRegion` at configure",
"system. May be passed as an integer number of seconds,",
"number or timedelta.') if not self._user_defined_key_mangler: self.key_mangler = self.backend.key_mangler self._lock_registry",
"keys. The list of keys to be generated is passed",
"None and \\ current_time - value.metadata[\"ct\"] > expiration_time: return NO_VALUE",
"If a value is present, but its creation time is",
"a config file. :param function_key_generator: Optional. A function that will",
"A typical mangler is the SHA1 mangler found at :func:`.sha1_mangle_key`",
"return bool(self._soft_invalidated) def is_soft_invalidated(self, timestamp): return (self._soft_invalidated and timestamp <",
"the cache. It will be passed the mutex and is",
"same cache key of ``myapp.tools:one|foo|3 4`` - the name ``self``",
"= key_generator(*arg, **kw) key_lookup = dict(zip(keys, cache_keys)) @wraps(fn) def creator(*keys_to_create):",
"keys = key_generator(*arg) return self.get_multi(keys) def refresh(*arg): keys = key_generator(*arg)",
"which case the key mangling function recommended by the cache",
"functions of the same name within the same source file,",
"thread = threading.Thread(target=runner) thread.start() region = make_region( async_creation_runner=async_creation_runner, ).configure( 'dogpile.cache.memcached',",
"creator(*keys) return [ d_values.get(key_lookup[k], NO_VALUE) for k in keys] def",
"details. Unlike the :meth:`.CacheRegion.cache_on_arguments` method, :meth:`.CacheRegion.cache_multi_on_arguments` works only with a",
"= list(map(lambda key: self.key_mangler(key), keys)) backend_values = self.backend.get_multi(keys) _unexpired_value_fn =",
".. versionadded:: 0.5.3 Added ``get()`` method to decorated function. The",
"class CustomInvalidationStrategy(RegionInvalidationStrategy): def __init__(self): self._soft_invalidated = None self._hard_invalidated = None",
"the normal expiration time. May be passed as an integer",
"immediate regeneration of the value which all getters will wait",
"@wraps(fn) def decorate(*arg, **kw): cache_keys = arg keys = key_generator(*arg,",
"% type(proxy)) self.backend = proxy.wrap(self.backend) def _mutex(self, key): return self._lock_registry.get(key)",
":func:`.make_region` is a passthrough to :class:`.CacheRegion`. See that class for",
"**kw) self.set(key, value) return value decorate.set = set_ decorate.invalidate =",
"used to defer the computation of expensive creator functions to",
"generate a cache key. Given a function ``one`` inside the",
"result = self.get_or_create_multi( keys, dict_create, timeout, wrap_cache_fn) result = dict(",
"new value in the cache under the given key.\"\"\" if",
"decorator before it becomes an instance method. The function key",
"for k in keys_to_create]) timeout = expiration_time() if expiration_time_is_callable \\",
"not a valid ProxyBackend\" % type(proxy)) self.backend = proxy.wrap(self.backend) def",
"the :meth:`.invalidate` method has been called, and the retrieved value's",
"import PluginLoader, memoized_property, coerce_string_conf from .util import function_key_generator, function_multi_key_generator from",
"and is set to ``None``. .. versionadded:: 0.4.2 added the",
"This may be needed to disambiguate functions of the same",
")) values.update(values_w_created) return [values[orig_to_mangled[k]].payload for k in keys] finally: for",
".. seealso:: :paramref:`.CacheRegion.configure.region_invalidator` \"\"\" def invalidate(self, hard=True): \"\"\"Region invalidation. :class:`.CacheRegion`",
"MyClass(object): @region.cache_on_arguments(namespace='MC') def somemethod(self, x, y): \"\" class MyOtherClass(object): @region.cache_on_arguments(namespace='MOC')",
"\"\"\"Return a :class:`.CachedValue` given a value.\"\"\" return CachedValue( value, {",
"it's used in :meth:`.CacheRegion.cache_multi_on_arguments`. Generated function should return list of",
"wrap_cache_fn(value): if value is NO_VALUE: return False elif not should_cache_fn:",
"async_creator(mutex): return self.async_creation_runner( self, orig_key, creator, mutex) else: async_creator =",
"fn.__name__ + (namespace or '') def generate_keys(*args): return [namespace +",
"use, and is resolved by loading the class from the",
"keys = list(map(lambda key: self.key_mangler(key), keys)) self.backend.delete_multi(keys) def cache_on_arguments( self,",
"expired based on its creation time, the given creation function",
"generation of values based on keys corresponds to that of",
"a previous value is available, that value is returned immediately",
"versionadded:: 0.5.7 :param region_invalidator: Optional. Override default invalidation strategy with",
"Pass to ``invalidate()`` the same arguments you'd pass to the",
"``time.time()``) to consider all older timestamps effectively invalidated. \"\"\" raise",
"mapping.items()) else: mapping = dict((k, self._value(v)) for k, v in",
"versionadded:: 0.5.0 :param function_key_generator: a function that will produce a",
"set_(value, *arg, **kw): key = key_generator(*arg, **kw) self.set(key, value) def",
"not should_cache_fn or \\ should_cache_fn(created_value): self.backend.set(key, value) return value.payload, value.metadata[\"ct\"]",
"to determine a *dynamic* expiration time for the cached function",
"to ultimately wrap the original backend, so that custom functionality",
"not None and \\ current_time - value.metadata[\"ct\"] > expiration_time: return",
"first argument, and the arguments which would normally be passed",
"and only if it returns True will that value be",
"\"\"\" expiration_time_is_callable = compat.callable(expiration_time) if function_key_generator is None: function_key_generator =",
"return [namespace + ':' + str(a) for a in args]",
"timestamp to determine if it was hard invalidated. :return: Boolean.",
"passed to ``creator()``, and ``creator()`` should return the generated values",
"class methods as below:: class MyClass(object): @region.cache_on_arguments(namespace='MC') def somemethod(self, x,",
"no expiration, use the value -1. :param should_cache_fn: optional callable",
"entrypoint. :param expiration_time: Optional. The expiration time passed to the",
"return [values[orig_to_mangled[k]].payload for k in keys] finally: for mutex in",
"``get()`` method to decorated function. Parameters passed to :meth:`.CacheRegion.cache_multi_on_arguments` have",
"a new :class:`.CacheRegion`. Currently, :func:`.make_region` is a passthrough to :class:`.CacheRegion`.",
"values based on a sequence of keys. The behavior for",
"region invalidation. Example:: class CustomInvalidationStrategy(RegionInvalidationStrategy): def __init__(self): self._soft_invalidated = None",
"key. If the value does not exist or is considered",
"given the region as an argument:: class MyInvalidator(RegionInvalidationStrategy): def __init__(self,",
"Lastly, the ``get()`` method returns either the value cached for",
"``MyClass().one(3, 4)`` will again produce the same cache key of",
"override the normal expiration time. May be specified as a",
"function_key_generator( namespace, fn, to_str=to_str) @wraps(fn) def decorate(*arg, **kw): key =",
"based on the given key. If the value is not",
"value in the cache. Whether or not the function is",
"also be a list. When ``asdict==True`` if the dictionary returned",
"= list(mapping) gen_keys = key_generator(*keys) self.set_multi(dict( (gen_key, mapping[key]) for gen_key,",
"new argument list, and the decorated function is then called",
"by setting a current timestamp (using ``time.time()``) representing the \"minimum",
"cases include \"cache the result until the end of the",
"to calling ``generate_something(5, 6)``, if the function were to produce",
"reaching the cache. .. versionadded:: 0.5.0 :param function_key_generator: a function",
"set by the :meth:`.invalidate` method. If a value is present,",
"Similar to ``set()`` is ``refresh()``. This attribute will invoke the",
"returns True will that value be placed in the cache.",
"function returns the value of create_value() if the cache is",
"% self.backend) backend_cls = _backend_loader.load(backend) if _config_argument_dict: self.backend = backend_cls.from_config_dict(",
"Optional. The expiration time passed to the dogpile system. May",
"the result until the end of the day, week or",
"self._hard_invalidated = None def is_invalidated(self, timestamp): return ((self._soft_invalidated and timestamp",
"\"\"\" expiration_time_is_callable = compat.callable(expiration_time) if function_multi_key_generator is None: function_multi_key_generator =",
"a return+regen will be invoked. .. versionadded:: 0.5.1 \"\"\" self.region_invalidator.invalidate(hard)",
"the function should follow:: generate_something.set(3, 5, 6) The above example",
"ignored and the ``NO_VALUE`` token is returned. Passing the flag",
"period\" and \"cache until a certain date or time passes\".",
"(as reported by ``time.time()``). If stale, the cached value is",
") ] def get_or_create( self, key, creator, expiration_time=None, should_cache_fn=None): \"\"\"Return",
"but isn't cached. E.g.:: def dont_cache_none(value): return value is not",
"return False elif not should_cache_fn: return True else: return should_cache_fn(value)",
"existing values will be pushed back before the expiration time",
"will produce unicode cache keys which may require key mangling",
"key. :param expiration_time: if not None, will override the normal",
"returned. Passing the flag ``ignore_expiration=True`` bypasses the invalidation time check.",
"indicating if the value should actually be cached or not.",
"getters will return the \"old\" value until the new one",
"function will supersede the one configured on the :class:`.CacheRegion` itself.",
"or on a non-existent key, safely) \"\"\" if self.key_mangler: key",
"invalidated in hard mode. \"\"\" raise NotImplementedError() def is_soft_invalidated(self, timestamp):",
"wish to have access to the :class:`.CacheRegion` itself should construct",
"versionadded:: 0.3.0 Support for the :meth:`.CacheRegion.invalidate` method. :param key: Key",
"``self`` is skipped. The ``namespace`` parameter is optional, and is",
"means a different thread or process is already running a",
"that will cache multiple return values from the function using",
"for k, v in zip(cache_keys, result) if v is not",
"Defaults to ``None``, in which case the key mangling function",
"myapp.tools:one|foo|3 4 The key generator will ignore an initial argument",
"exception.ValidationError( 'expiration_time is not a number or timedelta.') if not",
"a new value is needed:: result = generate_something(5, 6) The",
"a string. Defaults to ``str()``. If the function accepts non-ascii",
"0.5.0 ``expiration_time`` may be passed as a callable to :meth:`.CacheRegion.cache_on_arguments`.",
"region is invalidated in hard mode. \"\"\" raise NotImplementedError() def",
"else expiration_time return self.get_or_create(key, creator, timeout, should_cache_fn) def invalidate(*arg, **kw):",
"mechanism as that of :meth:`.CacheRegion.get_multi` to retrieve all current values;",
"my_multi_key_generator(namespace, fn, **kw): namespace = fn.__name__ + (namespace or '')",
"decorate.refresh = refresh decorate.get = get return decorate return decorator",
"generate_key region = make_region( function_key_generator = my_key_generator ).configure( \"dogpile.cache.dbm\", expiration_time=300,",
"generate_key(*arg, **kw): return \":\".join( [kw[k] for k in namespace] +",
"is not None and \\ current_time - value.metadata[\"ct\"] > expiration_time:",
"received by the decorator before it becomes an instance method.",
"as below:: class MyClass(object): @region.cache_on_arguments(namespace='MC') def somemethod(self, x, y): \"\"",
"key = key_generator(*arg, **kw) self.delete(key) def set_(value, *arg, **kw): key",
"invalidate decorate.refresh = refresh decorate.get = get decorate.original = fn",
"the string form of each key. It will then consult",
"See that method for additional behavioral details. Unlike the :meth:`.CacheRegion.cache_on_arguments`",
"before it becomes an instance method. The function key generation",
"the decorated function is then called with that subset of",
"return values based on the given arguments:: values = generate_something.get(\"k1\",",
"callable implements. By default the async_creation_runner is disabled and is",
"x, y): \"\" class MyOtherClass(object): @region.cache_on_arguments(namespace='MOC') def somemethod(self, x, y):",
"generate_keys :param key_mangler: Function which will be used on all",
"which is needed when using a backend such as bsddb",
"self._lock_registry.get(key) class _LockWrapper(object): \"\"\"weakref-capable wrapper for threading.Lock\"\"\" def __init__(self): self.lock",
"be pushed back before the expiration time so that a",
"!= value_version or self.region_invalidator.is_hard_invalidated( value.metadata['v'])): # dogpile.core understands a 0",
"type: proxy = proxy() if not issubclass(type(proxy), ProxyBackend): raise TypeError(\"Type",
"self.function_key_generator = function_key_generator self.function_multi_key_generator = function_multi_key_generator self.key_mangler = self._user_defined_key_mangler =",
"mutexes[key] = mutex if expiration_time is None: expiration_time = self.expiration_time",
"then be called normally, where data will be pulled from",
"each key. It will then consult the cache using the",
"list:: result = generate_something(\"key1\", \"key2\", \"key3\") The decorator internally makes",
"keys, those keys will not be cached. :param to_str: callable,",
"non-existent key, safely) .. versionadded:: 0.5.0 \"\"\" if self.key_mangler: keys",
"gen_keys = key_generator(*keys) self.set_multi(dict( (gen_key, mapping[key]) for gen_key, key in",
"the cache backend will be used. A typical mangler is",
"by loading the class from the ``dogpile.cache`` entrypoint. :param expiration_time:",
"using the same values it returns to the calling function.",
"or (self._hard_invalidated and timestamp < self._hard_invalidated)) def was_hard_invalidated(self): return bool(self._hard_invalidated)",
"values from the backend. If you are using a :class:`.CacheBackend`",
"a value.\"\"\" return CachedValue( value, { \"ct\": time.time(), \"v\": value_version",
"self, orig_key, creator, mutex) else: async_creator = None with Lock(",
"def creator(): return fn(*arg, **kw) timeout = expiration_time() if expiration_time_is_callable",
"k, v in values_w_created.items() if should_cache_fn(v[0]) )) values.update(values_w_created) return [values[orig_to_mangled[k]].payload",
"= fn(*arg, **kw) self.set(key, value) return value decorate.set = set_",
"from numbers import Number from functools import wraps import threading",
"== -1: expiration_time = None if self.async_creation_runner: def async_creator(mutex): return",
"def acquire(self, wait=True): return self.lock.acquire(wait) def release(self): self.lock.release() def _create_mutex(self,",
"set no expiration, use the value -1. :param should_cache_fn: optional",
"Given a function ``one`` inside the module ``myapp.tools``:: @region.cache_on_arguments(namespace=\"foo\") def",
"list of keys as arguments. Like :meth:`.CacheRegion.cache_on_arguments`, the decorated function",
"can be passed as a tuple, used to specify arguments",
"all incoming keys before passing to the backend. Defaults to",
"previous value is available, that value is returned immediately without",
"is not available\", e.g. # _has_value() will return False. return",
"``somemethod`` on ``MyClass`` and ``MyOtherClass``. Python class declaration mechanics otherwise",
"be established as part of each cache key. :param expiration_time:",
"= region.get_multi([\"one\", \"two\", \"three\"]) To convert values to a dictionary,",
"else value for value in ( _unexpired_value_fn(value) for value in",
"able to simulate one anyway. keys_to_get = sorted(mutexes) new_values =",
"the dogpile lock to generate a new value, or will",
"until the end of the day, week or time period\"",
"multiple key/value version \"\"\" orig_key = key if self.key_mangler: key",
"< self._soft_invalidated) The custom implementation is injected into a :class:`.CacheRegion`",
"= creator() value = self._value(created_value) if not should_cache_fn or \\",
":paramref:`.CacheRegion.configure.region_invalidator` parameter:: region = CacheRegion() region = region.configure(region_invalidator=CustomInvalidationStrategy()) Invalidation strategies",
"= [self.key_mangler(k) for k in sorted_unique_keys] else: mangled_keys = sorted_unique_keys",
"day, week or time period\" and \"cache until a certain",
"return my_data() .. seealso:: :func:`.function_key_generator` - default key generator :func:`.kwarg_function_key_generator`",
"function which creates a new value. :param expiration_time: optional expiration",
"arguments: Optional. The structure here is passed directly to the",
"of keys. This function will supersede the one configured on",
"is injected into a :class:`.CacheRegion` at configure time using the",
"the arguments passed, as well as an optional \"namespace\" parameter",
"The value to be cached is passed as the first",
"NO_VALUE or value.metadata['v'] != value_version or self.region_invalidator.is_hard_invalidated( value.metadata[\"ct\"])): raise NeedRegenerationException()",
"time and region is invalidated in hard mode. \"\"\" raise",
"the function. See that method for additional behavioral details. E.g.::",
"function_key_generator(namespace, fn) else: key_generator = function_key_generator( namespace, fn, to_str=to_str) @wraps(fn)",
":class:`.CacheRegion`, or alternatively the expiration time supplied by the ``expiration_time``",
"however if the return value is None, it won't be",
"namespace + \"_\" + fname + \"_\".join(str(s) for s in",
":param function_multi_key_generator: a function that will produce a list of",
"which will return values based on the given arguments:: values",
"Lock, NeedRegenerationException from ..util import NameRegistry from . import exception",
"self._soft_invalidated) The custom implementation is injected into a :class:`.CacheRegion` at",
":paramref:`.CacheRegion.configure.region_invalidator` \"\"\" def invalidate(self, hard=True): \"\"\"Region invalidation. :class:`.CacheRegion` propagated call.",
":meth:`.get_or_create` to any function using a decorator. :meth:`.CacheRegion.get_or_create_multi` - multiple",
"if self.region_invalidator.is_soft_invalidated(ct): ct = time.time() - expiration_time - .0001 return",
"True will that value be placed in the cache. :param",
"method also interprets the cached value in terms of the",
"\"configured with backend: %s. \" \"Specify replace_existing_backend=True to replace.\" %",
"will always block; async_creator will not be invoked. However, subsequent",
"def invalidate(self, hard=True): self._is_hard_invalidated = bool(hard) self._invalidated = time.time() def",
"region. This isn't used internally but can be accessed via",
"Support for the :meth:`.CacheRegion.invalidate` method. :param key: Key to be",
"\"\"\"Configure from a configuration dictionary and a prefix. Example:: local_region",
"value present in the cache. It will be passed the",
"[ value.payload if value is not NO_VALUE else value for",
"ignore_expiration)(value) return value.payload def _unexpired_value_fn(self, expiration_time, ignore_expiration): if ignore_expiration: return",
".. versionadded:: 0.3.0 :param hard: if True, cache values will",
"using the :paramref:`.CacheRegion.configure.region_invalidator` parameter:: region = CacheRegion() region = region.configure(region_invalidator=CustomInvalidationStrategy())",
"taking no arguments, that returns a value to be used",
"in conjunction with Unicode keys. :param async_creation_runner: A callable that,",
"release(self): self.lock.release() def _create_mutex(self, key): mutex = self.backend.get_mutex(key) if mutex",
"length is fixed. To disable all key mangling, set to",
"the function using a sequence of keys derived from the",
"generate_key(*arg): return namespace + \"_\" + fname + \"_\".join(str(s) for",
"a function that will produce a list of keys. This",
"the decorator might be used as:: @my_region.cache_on_arguments(namespace=('x', 'y')) def my_function(a,",
"region = region.configure(region_invalidator=CustomInvalidationStrategy()) Invalidation strategies that wish to have access",
"cached. E.g.:: def dont_cache_none(value): return value is not None value",
"cache under the given keys. .. versionadded:: 0.5.0 \"\"\" if",
"raise NotImplementedError() def is_hard_invalidated(self, timestamp): \"\"\"Check timestamp to determine if",
"def is_soft_invalidated(self, timestamp): return self.was_soft_invalidated() and self.is_invalidated(timestamp) class CacheRegion(object): \"\"\"A",
"A function that will produce a \"cache key\" given a",
"the expiration time check. .. versionchanged:: 0.3.0 :meth:`.CacheRegion.get` now checks",
"time.time() def value_fn(value): if value is NO_VALUE: return value elif",
"the final result of calling the decorated function will also",
"versionchanged:: 0.5.0 ``expiration_time`` may be passed as a callable to",
"this function invokes ``.set_multi()`` for newly generated values using the",
"a backend such as bsddb or dbm under Python 2.x",
"= values.get(key, NO_VALUE) if (value is NO_VALUE or value.metadata['v'] !=",
"itself and its arguments. The decorator internally makes use of",
"@wraps(fn) def creator(): return fn(*arg, **kw) timeout = expiration_time() if",
"= self._unexpired_value_fn( expiration_time, ignore_expiration) return [ value.payload if value is",
"0.3.0 :param hard: if True, cache values will all require",
"not present, the method returns the token ``NO_VALUE``. ``NO_VALUE`` evaluates",
"= self._unexpired_value_fn( expiration_time, ignore_expiration)(value) return value.payload def _unexpired_value_fn(self, expiration_time, ignore_expiration):",
"dict( (orig_to_mangled[k], self._value(v)) for k, v in zip(keys_to_get, new_values) )",
"function_key_generator is None: function_key_generator = self.function_key_generator def decorator(fn): if to_str",
"of keys to be retrieved. :param creator: function which accepts",
"unless a new value is needed:: result = generate_something(5, 6)",
"def release(self): self.lock.release() def _create_mutex(self, key): mutex = self.backend.get_mutex(key) if",
"self.backend.set_multi(values_w_created) else: self.backend.set_multi(dict( (k, v) for k, v in values_w_created.items()",
":class:`.CacheRegion` itself. .. versionadded:: 0.5.5 .. seealso:: :meth:`.CacheRegion.cache_multi_on_arguments` :meth:`.CacheRegion.get_or_create` \"\"\"",
"in zip(gen_keys, keys)) ) def get(*arg): keys = key_generator(*arg) return",
"with a ``set()`` method, which here accepts a mapping of",
"keys = [\"one\", \"two\", \"three\"] values = region.get_multi(keys) dictionary =",
"and a prefix. Example:: local_region = make_region() memcached_region = make_region()",
"the cache. This operation is idempotent (can be called multiple",
":meth:`.CacheRegion.cache_multi_on_arguments` works only with a single function signature, one which",
"delete(self, key): \"\"\"Remove a value from the cache. This operation",
"is to prevent deadlocks. # though haven't been able to",
"for k, v in values_w_created.items() if should_cache_fn(v[0]) )) values.update(values_w_created) return",
"non-string or Unicode keys to bytestrings, which is needed when",
"backend. :param name: Optional, a string name for the region.",
"before being optionally processed by the key_mangler function, so can",
"additional behavioral details. Unlike the :meth:`.CacheRegion.cache_on_arguments` method, :meth:`.CacheRegion.cache_multi_on_arguments` works only",
"time of the retrieved value versus the current time (as",
"= sorted_unique_keys orig_to_mangled = dict(zip(sorted_unique_keys, mangled_keys)) values = dict(zip(mangled_keys, self.backend.get_multi(mangled_keys)))",
"_backend_loader.register from . import backends # noqa value_version = 1",
"NotImplementedError() def async_creator(key, mutex): mutexes[key] = mutex if expiration_time is",
"dict(zip(keys, values)) ) return values decorate.set = set_ decorate.invalidate =",
"a value from the cache. This operation is idempotent (can",
"replace_existing_backend: raise exception.RegionAlreadyConfigured( \"This region is already \" \"configured with",
"creation time against the expiration time, rather than returning the",
"multiple values from the cache. This operation is idempotent (can",
"the value is not present, the method returns the token",
"the ``function_key_generator`` argument present on :func:`.make_region` and :class:`.CacheRegion`. If defaults",
"def __init__( self, name=None, function_key_generator=function_key_generator, function_multi_key_generator=function_multi_key_generator, key_mangler=None, async_creation_runner=None, ): \"\"\"Construct",
"''' # if we were passed a type rather than",
"def invalidate(self, hard=None): if hard: self._soft_invalidated = None self._hard_invalidated =",
"= self.key_mangler(key) value = self.backend.get(key) value = self._unexpired_value_fn( expiration_time, ignore_expiration)(value)",
"}) def set(self, key, value): \"\"\"Place a new value in",
"sorted_unique_keys] else: mangled_keys = sorted_unique_keys orig_to_mangled = dict(zip(sorted_unique_keys, mangled_keys)) values",
"as follows:: myapp.tools:one|foo|3 4 The key generator will ignore an",
"use of the :meth:`.CacheRegion.get_or_create_multi` method to access the cache and",
"similar to that of :meth:`.CacheRegion.cache_on_arguments`, combining the name of the",
"key. This may be needed to disambiguate functions of the",
"will wait until the lock is released to return the",
"attribute ``set()`` is added to provide extra caching possibilities relative",
"callable, will be called on each function argument in order",
"cache. :param asdict: if ``True``, the decorated function should return",
"= NameRegistry(self._create_mutex) if getattr(wrap, '__iter__', False): for wrapper in reversed(wrap):",
"def was_soft_invalidated(self): return self._is_hard_invalidated is False def is_soft_invalidated(self, timestamp): return",
"Lock( self._mutex(key), gen_value, get_value, expiration_time, async_creator) as value: return value",
"import datetime from numbers import Number from functools import wraps",
"value. Pass to ``invalidate()`` the same arguments you'd pass to",
"the token ``NO_VALUE``. ``NO_VALUE`` evaluates to False, but is separate",
"value.payload, ct def gen_value(): raise NotImplementedError() def async_creator(key, mutex): mutexes[key]",
"a simple list of keys as arguments. Like :meth:`.CacheRegion.cache_on_arguments`, the",
"None and self.region_invalidator.was_soft_invalidated()): raise exception.DogpileCacheException( \"Non-None expiration time required \"",
"if region was invalidated in soft mode. \"\"\" raise NotImplementedError()",
"Above, the ``namespace`` parameter disambiguates between ``somemethod`` on ``MyClass`` and",
"timestamp): return self.was_hard_invalidated() and self.is_invalidated(timestamp) def was_soft_invalidated(self): return self._is_hard_invalidated is",
"should_cache_fn=None, asdict=False, to_str=compat.string_type, function_multi_key_generator=None): \"\"\"A function decorator that will cache",
"passed directly down to the cache backend, before being optionally",
":meth:`.CacheRegion.cache_multi_on_arguments`. Generated function should return list of keys. For example::",
"was invalidated. :return: Boolean. True if ``timestamp`` is older than",
"takes a simple list of keys as arguments. Like :meth:`.CacheRegion.cache_on_arguments`,",
"Added ``set()`` method to decorated function. Similar to ``set()`` is",
"is None: function_multi_key_generator = self.function_multi_key_generator def decorator(fn): key_generator = function_multi_key_generator(",
"or retrieving. Thus, this can be used to determine a",
"keys = key_generator(*arg) self.delete_multi(keys) def set_(mapping): keys = list(mapping) gen_keys",
"To disable all key mangling, set to ``False``. Another typical",
"(value is NO_VALUE or value.metadata['v'] != value_version or self.region_invalidator.is_hard_invalidated( value.metadata['v'])):",
"is idempotent (can be called multiple times, or on a",
"was_soft_invalidated(self): \"\"\"Indicate the region was invalidated in soft mode. :return:",
"wrap: Optional. A list of :class:`.ProxyBackend` classes and/or instances, each",
"if (expiration_time is None and self.region_invalidator.was_soft_invalidated()): raise exception.DogpileCacheException( \"Non-None expiration",
".. seealso:: :meth:`.CacheRegion.cache_on_arguments` - applies :meth:`.get_or_create` to any function using",
"a SHA1 hash, so that the string length is fixed.",
":param expiration_time: optional expiration time which will overide the expiration",
"value -1. :param should_cache_fn: optional callable function which will receive",
"b, **kw): return my_data() .. seealso:: :func:`.function_key_generator` - default key",
"that mutex when finished. This can be used to defer",
"backend will be replaced. Without this flag, an exception is",
"the cache backend, before being optionally processed by the key_mangler",
"__init__( self, name=None, function_key_generator=function_key_generator, function_multi_key_generator=function_multi_key_generator, key_mangler=None, async_creation_runner=None, ): \"\"\"Construct a",
"the one configured on the :class:`.CacheRegion` itself. .. versionadded:: 0.5.5",
".. versionadded:: 0.5.5 .. seealso:: :meth:`.CacheRegion.cache_on_arguments` :meth:`.CacheRegion.get_or_create_multi` \"\"\" expiration_time_is_callable =",
"} ) Remember that the first request for a key",
"when specified, will be passed to and called by dogpile.lock",
"0.5.3 Added ``get()`` method to decorated function. Parameters passed to",
"value as returned by the creator, and only if it",
"returned by the \"creator\", and will then return True or",
"return decorator def make_region(*arg, **kw): \"\"\"Instantiate a new :class:`.CacheRegion`. Currently,",
"result is a list:: result = generate_something(\"key1\", \"key2\", \"key3\") The",
"will not be cached. :param to_str: callable, will be called",
"configure time using the :paramref:`.CacheRegion.configure.region_invalidator` parameter:: region = CacheRegion() region",
"in :meth:`.CacheRegion.cache_multi_on_arguments`. Generated function should return list of keys. For",
"functionality augmentation can be applied. .. versionadded:: 0.5.0 .. seealso::",
"``expiration_time`` may be optionally passed as a ``datetime.timedelta`` value. The",
"if getattr(wrap, '__iter__', False): for wrapper in reversed(wrap): self.wrap(wrapper) if",
"or whether or not :meth:`.invalidate` was called. .. versionadded:: 0.3.0",
"get_value, expiration_time, async_creator) as value: return value def get_or_create_multi( self,",
"+ b The cache key above for ``MyClass().one(3, 4)`` will",
"function_multi_key_generator( namespace, fn, to_str=to_str) @wraps(fn) def decorate(*arg, **kw): cache_keys =",
"fn return decorate return decorator def cache_multi_on_arguments( self, namespace=None, expiration_time=None,",
"raise NotImplementedError() def was_hard_invalidated(self): \"\"\"Indicate the region was invalidated in",
"requires that the region or the method is given a",
"backend: Required. This is the name of the :class:`.CacheBackend` to",
"self.region_invalidator.is_soft_invalidated(ct): ct = time.time() - expiration_time - .0001 return value.payload,",
"certain date or time passes\". .. versionchanged:: 0.5.0 ``expiration_time`` may",
"configured expiration time of the :class:`.CacheRegion`, or alternatively the expiration",
"values from a previous, backwards-incompatible version. \"\"\" class RegionInvalidationStrategy(object): \"\"\"Region",
"the value creation function after this time period has passed",
"check. .. versionadded:: 0.5.0 \"\"\" if not keys: return []",
"with the optional namespace and with the string form of",
"\"\"\"A function decorator that will cache multiple return values from",
"to later points in the future by way of, for",
"def async_creation_runner(cache, somekey, creator, mutex): ''' Used by dogpile.core:Lock when",
"= CacheRegion() region = region.configure(region_invalidator=MyInvalidator(region)) .. versionadded:: 0.6.2 .. seealso::",
"if mutex is not None: return mutex else: return self._LockWrapper()",
"= make_region() memcached_region = make_region() # regions are ready to",
"return value.payload, 0 else: ct = value.metadata[\"ct\"] if self.region_invalidator.is_soft_invalidated(ct): ct",
"being declared. :param expiration_time: if not None, will override the",
"key_generator = function_key_generator(namespace, fn) else: key_generator = function_key_generator( namespace, fn,",
"invalidate decorate.refresh = refresh decorate.get = get return decorate return",
"prefix, None), ) @memoized_property def backend(self): raise exception.RegionNotConfigured( \"No backend",
"present. :param expiration_time: Optional expiration time value which will supersede",
"cache if present, regardless of configured expiration times or whether",
"fn, **kw): fname = fn.__name__ def generate_key(*arg): return namespace +",
"already configured on this :class:`.CacheRegion` if not None. To set",
"default invalidation strategy with custom implementation of :class:`.RegionInvalidationStrategy`. .. versionadded::",
"if type(proxy) == type: proxy = proxy() if not issubclass(type(proxy),",
"the first argument, and the arguments which would normally be",
"receive each value returned by the \"creator\", and will then",
"(though note: **not** the :meth:`.CacheRegion.get` method) will call upon the",
"and self.is_invalidated(timestamp) def was_soft_invalidated(self): return self._is_hard_invalidated is False def is_soft_invalidated(self,",
"= sorted(mutexes) new_values = creator(*keys_to_get) values_w_created = dict( (orig_to_mangled[k], self._value(v))",
"time. May be passed as an integer or a callable.",
"is considered to be stale. It does not affect the",
"conjunction with Unicode keys. :param async_creation_runner: A callable that, when",
"time import datetime from numbers import Number from functools import",
"function_key_generator: a function that will produce a \"cache key\". This",
"...and a ``get()`` method, which will return values based on",
"self.region_invalidator.was_soft_invalidated()): raise exception.DogpileCacheException( \"Non-None expiration time required \" \"for soft",
"key derived from the function itself and its arguments. The",
"= dict((k, self._value(v)) for k, v in mapping.items()) self.backend.set_multi(mapping) def",
"it was soft invalidated. :return: Boolean. True if ``timestamp`` is",
"is the built-in Python function ``str``, which can be used",
"value which all getters will wait for. With \"soft\" invalidation,",
"will be pushed back before the expiration time so that",
"= dict(zip(sorted_unique_keys, mangled_keys)) values = dict(zip(mangled_keys, self.backend.get_multi(mangled_keys))) for orig_key, mangled_key",
"that will cache the return value of the function using",
"cached-but-expired values will still return promptly. They will be refreshed",
"self._is_hard_invalidated = None self._invalidated = None def invalidate(self, hard=True): self._is_hard_invalidated",
"self.backend.set(key, self._value(value)) def set_multi(self, mapping): \"\"\"Place new values in the",
"generated is passed to ``creator()``, and ``creator()`` should return the",
"use the name of the function, the module name for",
"class MyOtherClass(object): @region.cache_on_arguments(namespace='MOC') def somemethod(self, x, y): \"\" Above, the",
"or the method is given a non-None expiration time. ..",
"normal expiration time. May be specified as a callable, taking",
"subset of the given keys. The list of keys to",
"one is available. Usage of \"soft\" invalidation requires that the",
"\"cache.memcached.\") \"\"\" config_dict = coerce_string_conf(config_dict) return self.configure( config_dict[\"%sbackend\" % prefix],",
"replaced. Without this flag, an exception is raised if a",
"@property def is_configured(self): \"\"\"Return True if the backend has been",
"def somemethod(self, x, y): \"\" class MyOtherClass(object): @region.cache_on_arguments(namespace='MOC') def somemethod(self,",
"function_multi_key_generator from .api import NO_VALUE, CachedValue from .proxy import ProxyBackend",
"return self def wrap(self, proxy): ''' Takes a ProxyBackend instance",
"can then be called normally, where data will be pulled",
"function can be called normally. The decorator will produce a",
"attribute will invoke the decorated function and populate a new",
"processed by the key_mangler function, so can be of any",
"flag ``ignore_expiration=True`` bypasses the invalidation time check. .. versionadded:: 0.3.0",
":func:`.make_region` and :class:`.CacheRegion`. If defaults to :func:`.function_key_generator`. :param namespace: optional",
"functions of the same name within the same module, as",
"async_creation_runner(cache, somekey, creator, mutex): ''' Used by dogpile.core:Lock when appropriate",
"if ``True``, the decorated function should return its result as",
"which will supersede that configured on the :class:`.CacheRegion` itself. ..",
":class:`.CacheRegion`. The default invalidation system works by setting a current",
"``invalidate()``, which provides for invalidation of the value. Pass to",
"method. The function key generation can be entirely replaced on",
"function is then called with that subset of arguments. The",
"arguments :param function_multi_key_generator: Optional. Similar to ``function_key_generator`` parameter, but it's",
"is that passed to :meth:`.CacheRegion.cache_on_arguments`. It's not consulted outside this",
"For example, it can be passed as a tuple, used",
"invalidation of the value. Pass to ``invalidate()`` the same arguments",
"of the retrieved value versus the current time (as reported",
"= function_key_generator self.function_multi_key_generator = function_multi_key_generator self.key_mangler = self._user_defined_key_mangler = key_mangler",
"be cached is passed as the first argument, and the",
"**kw): key = key_generator(*arg, **kw) return self.get(key) def refresh(*arg, **kw):",
"from \\**kw:: def my_key_generator(namespace, fn): def generate_key(*arg, **kw): return \":\".join(",
"or as a ``datetime.timedelta`` value. .. versionadded 0.5.0 ``expiration_time`` may",
"on this :class:`.CacheRegion` if not None. To set no expiration,",
"specified as a callable, taking no arguments, that returns a",
"called with that subset of arguments. The returned result is",
"function will also be a dictionary. If left at its",
"cache_keys)) @wraps(fn) def creator(*keys_to_create): return fn(*[key_lookup[k] for k in keys_to_create])",
"``expiration_time``. This callable will be called whenever the decorated function",
"It will then consult the cache using the same mechanism",
"value in terms of the current \"invalidation\" time as set",
"as the value to be cached. .. versionadded:: 0.4.1 Added",
"< self._soft_invalidated) or (self._hard_invalidated and timestamp < self._hard_invalidated)) def was_hard_invalidated(self):",
"is not a number or timedelta.') if not self._user_defined_key_mangler: self.key_mangler",
"key = self.key_mangler(key) def get_value(): value = self.backend.get(key) if (value",
"is None, it won't be cached. .. versionadded:: 0.4.3 ..",
"= self.get_or_create_multi( keys, dict_create, timeout, wrap_cache_fn) result = dict( (k,",
"returns False, the value is still returned, but isn't cached.",
"multiple return values from the function using a sequence of",
"try: value = creator() cache.set(somekey, value) finally: mutex.release() thread =",
"of calling the decorated function will also be a list.",
"decorator that will cache the return value of the function",
"method. The structure of this function should be two levels:",
":meth:`.CacheRegion.cache_on_arguments`. It's not consulted outside this function, so in fact",
"Keys which aren't present in the list are returned as",
"%s. \" \"Specify replace_existing_backend=True to replace.\" % self.backend) backend_cls =",
"the ``NO_VALUE`` token. ``NO_VALUE`` evaluates to False, but is separate",
"\"hard\" and \"soft\" invalidation options. With \"hard\" invalidation, :meth:`.CacheRegion.get_or_create` will",
"self, backend, expiration_time=None, arguments=None, _config_argument_dict=None, _config_prefix=None, wrap=None, replace_existing_backend=False, region_invalidator=None ):",
"\"\"\"Check timestamp to determine if it was invalidated. :return: Boolean.",
"None self._hard_invalidated = time.time() else: self._soft_invalidated = time.time() self._hard_invalidated =",
"expiration_time, ignore_expiration)(value) return value.payload def _unexpired_value_fn(self, expiration_time, ignore_expiration): if ignore_expiration:",
"value will always block; async_creator will not be invoked. However,",
"If you are using a :class:`.CacheBackend` or :class:`.ProxyBackend` that modifies",
"an initial argument of ``self`` or ``cls``, making the decorator",
"class from the ``dogpile.cache`` entrypoint. :param expiration_time: Optional. The expiration",
"constructor of the :class:`.CacheBackend` in use, though is typically a",
"than the last region invalidation time and region is invalidated",
"NO_VALUE or value.metadata['v'] != value_version or self.region_invalidator.is_hard_invalidated( value.metadata['v'])): # dogpile.core",
"\"the value is not available\", e.g. # _has_value() will return",
"the function itself and the arguments passed to it. This",
"key): mutex = self.backend.get_mutex(key) if mutex is not None: return",
"of ``None``. By default, the configured expiration time of the",
"keys given. E.g.:: values = region.get_multi([\"one\", \"two\", \"three\"]) To convert",
"and timestamp < self._hard_invalidated)) def was_hard_invalidated(self): return bool(self._hard_invalidated) def is_hard_invalidated(self,",
"''' def runner(): try: value = creator() cache.set(somekey, value) finally:",
"self.backend.get_multi(keys) _unexpired_value_fn = self._unexpired_value_fn( expiration_time, ignore_expiration) return [ value.payload if",
"self.expiration_time current_time = time.time() def value_fn(value): if value is NO_VALUE:",
"have the same meaning as those passed to :meth:`.CacheRegion.cache_on_arguments`. :param",
"of cached values based on a sequence of keys. The",
"new value, or will wait until the lock is released",
"per-region basis using the ``function_key_generator`` argument present on :func:`.make_region` and",
"return value.payload, ct def gen_value(): created_value = creator() value =",
"as a dictionary of keys->values, and the final result of",
"points in the future by way of, for example, a",
"# ... region = CacheRegion() region = region.configure(region_invalidator=MyInvalidator(region)) .. versionadded::",
"creator, mutex): ''' Used by dogpile.core:Lock when appropriate ''' def",
"a ProxyBackend instance or class and wraps the attached backend.",
"value is available, until the lock is released and a",
".. versionadded:: 0.3.0 :param ignore_expiration: if ``True``, the value is",
"''' Takes a ProxyBackend instance or class and wraps the",
"): \"\"\"Configure a :class:`.CacheRegion`. The :class:`.CacheRegion` itself is returned. :param",
"self._unexpired_value_fn( expiration_time, ignore_expiration)(value) return value.payload def _unexpired_value_fn(self, expiration_time, ignore_expiration): if",
"argument:: class MyInvalidator(RegionInvalidationStrategy): def __init__(self, region): self.region = region #",
"TypeError(\"Type %s is not a valid ProxyBackend\" % type(proxy)) self.backend",
"cache, based on the given keys. Returns values as a",
":param creator: function which accepts a sequence of keys and",
"for k in keys] def wrap_cache_fn(value): if value is NO_VALUE:",
"can be used to convert non-string or Unicode keys to",
"it means a different thread or process is already running",
"that a return+regen will be invoked. .. versionadded:: 0.5.1 \"\"\"",
"cache key of ``myapp.tools:one|foo|3 4`` - the name ``self`` is",
"function, if present. :param expiration_time: Optional expiration time value which",
"to the :class:`.CacheRegion` itself should construct the invalidator given the",
"if value is not NO_VALUE else value for value in",
"exception.DogpileCacheException( \"Non-None expiration time required \" \"for soft invalidation\") if",
"method is the \"multiple key\" analogue to the :meth:`.CacheRegion.cache_on_arguments` method.",
"new value, as well as returning that value:: newvalue =",
"self.key_mangler: key = self.key_mangler(key) self.backend.set(key, self._value(value)) def set_multi(self, mapping): \"\"\"Place",
"strategy with custom implementation of :class:`.RegionInvalidationStrategy`. .. versionadded:: 0.6.2 \"\"\"",
"time (as reported by ``time.time()``). If stale, the cached value",
"levels: given the data creation function, return a new function",
"mangler is the built-in Python function ``str``, which can be",
"pluck from \\**kw:: def my_key_generator(namespace, fn): def generate_key(*arg, **kw): return",
"is passed as the first argument, and the arguments which",
"provided with a ``set()`` method, which here accepts a mapping",
"not should_cache_fn: self.backend.set_multi(values_w_created) else: self.backend.set_multi(dict( (k, v) for k, v",
"timestamp (using ``time.time()``) to consider all older timestamps effectively invalidated.",
"asked to generate any subset of the given keys. The",
"function were to produce the value ``3`` as the value",
"to be a string, it is ultimately passed directly down",
"cached. .. versionadded:: 0.4.1 Added ``set()`` method to decorated function.",
"will not be invoked. However, subsequent requests for cached-but-expired values",
"self._hard_invalidated) def was_soft_invalidated(self): return bool(self._soft_invalidated) def is_soft_invalidated(self, timestamp): return (self._soft_invalidated",
"have access to the :class:`.CacheRegion` itself should construct the invalidator",
"creation function and arguments, when using the :meth:`.CacheRegion.cache_on_arguments` method. The",
"is NO_VALUE or value.metadata['v'] != value_version or self.region_invalidator.is_hard_invalidated( value.metadata[\"ct\"])): raise",
"self, namespace=None, expiration_time=None, should_cache_fn=None, to_str=compat.string_type, function_key_generator=None): \"\"\"A function decorator that",
"to the order of the keys. The method uses the",
":func:`.sha1_mangle_key` which coerces keys into a SHA1 hash, so that",
"values can be created in a background thread like so::",
"to override default region invalidation. Example:: class CustomInvalidationStrategy(RegionInvalidationStrategy): def __init__(self):",
":meth:`.CacheRegion.get_or_create_multi` \"\"\" expiration_time_is_callable = compat.callable(expiration_time) if function_multi_key_generator is None: function_multi_key_generator",
"memcached_region = make_region() # regions are ready to use for",
"acquire(self, wait=True): return self.lock.acquire(wait) def release(self): self.lock.release() def _create_mutex(self, key):",
"MyOtherClass(object): @region.cache_on_arguments(namespace='MOC') def somemethod(self, x, y): \"\" Above, the ``namespace``",
"builtin can be substituted, but note this will produce unicode",
"value return value_fn def get_multi(self, keys, expiration_time=None, ignore_expiration=False): \"\"\"Return multiple",
"function ``one`` inside the module ``myapp.tools``:: @region.cache_on_arguments(namespace=\"foo\") def one(a, b):",
"the given key. If the value does not exist or",
"exception.RegionNotConfigured( \"No backend is configured on this region.\") @property def",
"to those values which aren't generated or need regeneration will",
"passed to the dogpile system. May be passed as an",
"produce a \"cache key\". This function will supersede the one",
"``function_key_generator`` parameter, but it's used in :meth:`.CacheRegion.cache_multi_on_arguments`. Generated function should",
"cached. :param to_str: callable, will be called on each function",
"is still returned, but isn't cached. E.g.:: def dont_cache_none(value): return",
"value decorate.set = set_ decorate.invalidate = invalidate decorate.refresh = refresh",
"newvalue = generate_something.refresh(5, 6) .. versionadded:: 0.5.0 Added ``refresh()`` method",
"produce a cache key as follows:: myapp.tools:one|foo|3 4 The key",
"expiration_time is None: expiration_time = self.expiration_time current_time = time.time() def",
"sequence of keys derived from the function itself and the",
"token ``NO_VALUE``. ``NO_VALUE`` evaluates to False, but is separate from",
"register_backend = _backend_loader.register from . import backends # noqa value_version",
"keys. For example:: def my_multi_key_generator(namespace, fn, **kw): namespace = fn.__name__",
"creator, timeout, should_cache_fn) def invalidate(*arg, **kw): key = key_generator(*arg, **kw)",
"reversed(wrap): self.wrap(wrapper) if region_invalidator: self.region_invalidator = region_invalidator return self def",
"stale. It does not affect the data in the cache",
"function key generation can be entirely replaced on a per-region",
"from __future__ import with_statement from .. import Lock, NeedRegenerationException from",
"if ``timestamp`` is older than the last region invalidation time",
"def decorate(*arg, **kw): key = key_generator(*arg, **kw) @wraps(fn) def creator():",
"is available, that value is returned immediately without blocking. If",
"parameter, but it's used in :meth:`.CacheRegion.cache_multi_on_arguments`. Generated function should return",
"with Lock( self._mutex(key), gen_value, get_value, expiration_time, async_creator) as value: return",
"creation time of existing values will be pushed back before",
"namespace = fn.__name__ + (namespace or '') def generate_keys(*args): return",
"invalidation timestamp, the value is unconditionally prevented from being returned.",
"\":\".join( [kw[k] for k in namespace] + [str(x) for x",
"``set()`` is added to provide extra caching possibilities relative to",
"value is NO_VALUE: return False elif not should_cache_fn: return True",
"parent class on a function as the class is being",
"accepts non-ascii unicode arguments on Python 2.x, the ``unicode()`` builtin",
"two levels: given the data creation function, return a new",
"understands a 0 here as # \"the value is not",
"The ``namespace`` parameter is optional, and is used normally to",
"and self.is_invalidated(timestamp) class CacheRegion(object): \"\"\"A front end to a particular",
"the first request for a key with no associated value",
"the method is given a non-None expiration time. .. versionadded::",
"a list of keys. This function will supersede the one",
"the decorated function. The value to be cached is passed",
"to retrieve all current values; the originally passed keys corresponding",
"older than the current invalidation time, the ``NO_VALUE`` token is",
"versionadded:: 0.4.3 .. seealso:: :meth:`.CacheRegion.cache_on_arguments` - applies :meth:`.get_or_create` to any",
"0.6.2 \"\"\" if \"backend\" in self.__dict__ and not replace_existing_backend: raise",
"function as the class is being declared. :param expiration_time: if",
"= fn(*arg) if asdict: self.set_multi( dict(zip(keys, [values[a] for a in",
"method to decorated function. Parameters passed to :meth:`.CacheRegion.cache_multi_on_arguments` have the",
"then # initialize it. if type(proxy) == type: proxy =",
"manager system like Celery. For a specific example using async_creation_runner,",
"fixed. To disable all key mangling, set to ``False``. Another",
"to represent a particular value:: generate_something.invalidate(5, 6) Another attribute ``set()``",
"\"key2\", \"key3\") The decorator internally makes use of the :meth:`.CacheRegion.get_or_create_multi`",
"the :meth:`.invalidate` method. If a value is present, but its",
"the dogpile lock cannot be acquired, the method will block",
"self.expiration_time = int( compat.timedelta_total_seconds(expiration_time)) else: raise exception.ValidationError( 'expiration_time is not",
"Unicode keys. :param async_creation_runner: A callable that, when specified, will",
"to acquire the dogpile lock to generate a new value,",
"method for additional behavioral details. Unlike the :meth:`.CacheRegion.cache_on_arguments` method, :meth:`.CacheRegion.cache_multi_on_arguments`",
"mutex) else: async_creator = None with Lock( self._mutex(key), gen_value, get_value,",
"Without this flag, an exception is raised if a backend",
"it is ultimately passed directly down to the cache backend,",
"returns to the calling function. A correct implementation of ``.set_multi()``",
"to ``set()`` is ``refresh()``. This attribute will invoke the decorated",
":class:`.CacheRegion`. See that class for constructor arguments. \"\"\" return CacheRegion(*arg,",
"time value which will supersede that configured on the :class:`.CacheRegion`",
"be a list. When ``asdict==True`` if the dictionary returned by",
"to be retrieved. :param creator: function which accepts a sequence",
"timestamp): \"\"\"Check timestamp to determine if it was invalidated. :return:",
"if not should_cache_fn: self.backend.set_multi(values_w_created) else: self.backend.set_multi(dict( (k, v) for k,",
"@region.cache_on_arguments(namespace='MC') def somemethod(self, x, y): \"\" class MyOtherClass(object): @region.cache_on_arguments(namespace='MOC') def",
"can be entirely replaced on a per-region basis using the",
"can't see the parent class on a function as the",
"passed directly to the constructor of the :class:`.CacheBackend` in use,",
"import time import datetime from numbers import Number from functools",
"self.backend = proxy.wrap(self.backend) def _mutex(self, key): return self._lock_registry.get(key) class _LockWrapper(object):",
"the method returns the token ``NO_VALUE``. ``NO_VALUE`` evaluates to False,",
"based on a sequence of keys. The behavior for generation",
"idempotent (can be called multiple times, or on a non-existent",
"if not None. To set no expiration, use the value",
"which will be established as part of each cache key.",
"False elif not should_cache_fn: return True else: return should_cache_fn(value) result",
"__future__ import with_statement from .. import Lock, NeedRegenerationException from ..util",
"method has been called, and the retrieved value's timestamp is",
"a :class:`.CacheRegion` at configure time using the :paramref:`.CacheRegion.configure.region_invalidator` parameter:: region",
"is used normally to disambiguate two functions of the same",
"+ ':' + str(a) for a in args] return generate_keys",
"elif self.region_invalidator.is_invalidated( value.metadata[\"ct\"]): return NO_VALUE else: return value return value_fn",
"the backend has been configured via the :meth:`.CacheRegion.configure` method already.",
"use ``zip()``:: keys = [\"one\", \"two\", \"three\"] values = region.get_multi(keys)",
"def delete_multi(self, keys): \"\"\"Remove multiple values from the cache. This",
"not NO_VALUE) else: result = self.get_or_create_multi( keys, creator, timeout, should_cache_fn)",
":class:`.ProxyBackend` classes and/or instances, each of which will be applied",
"hard=True): self._is_hard_invalidated = bool(hard) self._invalidated = time.time() def is_invalidated(self, timestamp):",
"corresponding to those values which aren't generated or need regeneration",
"def async_creator(mutex): return self.async_creation_runner( self, orig_key, creator, mutex) else: async_creator",
"typical mangler is the SHA1 mangler found at :func:`.sha1_mangle_key` which",
"def wrap_cache_fn(value): if value is NO_VALUE: return False elif not",
"the decorator from having awareness of the ``MyClass`` and ``MyOtherClass``",
"key to be a string, it is ultimately passed directly",
"the function returns the value of create_value() if the cache",
"def get_value(): value = self.backend.get(key) if (value is NO_VALUE or",
"key_mangler function, so can be of any type recognized by",
"or may not be used to recreate the value and",
"CacheRegion() region = region.configure(region_invalidator=CustomInvalidationStrategy()) Invalidation strategies that wish to have",
"make_region() memcached_region = make_region() # regions are ready to use",
"sequence of keys and returns a sequence of new values.",
"key_mangler self.async_creation_runner = async_creation_runner self.region_invalidator = DefaultInvalidationStrategy() def configure( self,",
"a background thread, a long-running queue, or a task manager",
"of the :class:`.CacheRegion`, or alternatively the expiration time supplied by",
"cache region unless a new value is needed:: result =",
":meth:`.invalidate`. :param key: Key to be retrieved. While it's typical",
"returned by the creator, and only if it returns True",
"= key_generator(*arg, **kw) return self.get(key) def refresh(*arg, **kw): key =",
"versionadded:: 0.6.2 \"\"\" if \"backend\" in self.__dict__ and not replace_existing_backend:",
"expiration, use the value -1. :param should_cache_fn: optional callable function",
"is_hard_invalidated(self, timestamp): return (self._hard_invalidated and timestamp < self._hard_invalidated) def was_soft_invalidated(self):",
"**kw) timeout = expiration_time() if expiration_time_is_callable \\ else expiration_time return",
"This callable will be called whenever the decorated function itself",
"the effect of deleting the given sequence of keys using",
"for value in ( _unexpired_value_fn(value) for value in backend_values )",
"return generate_key Where the decorator might be used as:: @my_region.cache_on_arguments(namespace=('x',",
":meth:`.CacheRegion.cache_multi_on_arguments` :meth:`.CacheRegion.get_or_create` \"\"\" expiration_time_is_callable = compat.callable(expiration_time) if function_key_generator is None:",
"string. Defaults to ``str()``. If the function accepts non-ascii unicode",
"the decorated function will also be a dictionary. If left",
"if ``True``, the value is returned from the cache if",
"new values, and return them:: values = generate_something.refresh(\"k1\", \"k2\", \"k3\")",
"or value.metadata['v'] != value_version or self.region_invalidator.is_hard_invalidated( value.metadata[\"ct\"])): raise NeedRegenerationException() ct",
"value. Any retrieved value whose creation time is prior to",
"as the ``expiration_time``. This callable will be called whenever the",
"a region from a config file. :param function_key_generator: Optional. A",
"typical mangler is the built-in Python function ``str``, which can",
"default invalidation system works by setting a current timestamp (using",
"True, } ) Remember that the first request for a",
"on if the *dogpile lock* can be acquired or not.",
"Number from functools import wraps import threading _backend_loader = PluginLoader(\"dogpile.cache\")",
"``NO_VALUE`` token. ``NO_VALUE`` evaluates to False, but is separate from",
"be passed to and called by dogpile.lock when there is",
"cache_multi_on_arguments( self, namespace=None, expiration_time=None, should_cache_fn=None, asdict=False, to_str=compat.string_type, function_multi_key_generator=None): \"\"\"A function",
"True if the backend has been configured via the :meth:`.CacheRegion.configure`",
"proxy): ''' Takes a ProxyBackend instance or class and wraps",
"to be stale. It does not affect the data in",
"that subset of arguments. The returned result is a list::",
"result = self.get_or_create_multi( keys, creator, timeout, should_cache_fn) return result def",
"cached value of ``None``. By default, the configured expiration time",
"sorted(mutexes) new_values = creator(*keys_to_get) values_w_created = dict( (orig_to_mangled[k], self._value(v)) for",
"6)``, if the function were to produce the value ``3``",
"methods. The method supports both \"hard\" and \"soft\" invalidation options.",
"k in namespace] + [str(x) for x in arg] )",
"compat.timedelta_total_seconds(expiration_time)) else: raise exception.ValidationError( 'expiration_time is not a number or",
"to provide extra caching possibilities relative to the function. This",
"before the expiration time so that a return+regen will be",
"supersede that configured on the :class:`.CacheRegion` itself. .. versionadded:: 0.3.0",
"_unexpired_value_fn(value) for value in backend_values ) ] def get_or_create( self,",
"Example:: class CustomInvalidationStrategy(RegionInvalidationStrategy): def __init__(self): self._soft_invalidated = None self._hard_invalidated =",
"and wraps the attached backend. ''' # if we were",
"uses the same approach as :meth:`.Region.get_multi` and :meth:`.Region.set_multi` to get",
"else: raise exception.ValidationError( 'expiration_time is not a number or timedelta.')",
"on the given arguments:: values = generate_something.get(\"k1\", \"k2\", \"k3\") ..",
"the ``creator()`` function may be asked to generate any subset",
":param asdict: if ``True``, the decorated function should return its",
"self.backend.key_mangler self._lock_registry = NameRegistry(self._create_mutex) if getattr(wrap, '__iter__', False): for wrapper",
"# later, when config is available myconfig = { \"cache.local.backend\":\"dogpile.cache.dbm\",",
"passing to the backend. Defaults to ``None``, in which case",
"[] if self.key_mangler: keys = list(map(lambda key: self.key_mangler(key), keys)) backend_values",
"pass implementation instance to :meth:`.CacheRegion.configure` to override default region invalidation.",
"NO_VALUE elif self.region_invalidator.is_invalidated( value.metadata[\"ct\"]): return NO_VALUE else: return value return",
"\"k2\": \"value2\", \"k3\": \"value3\"}) ...an ``invalidate()`` method, which has the",
"on all incoming keys before passing to the backend. Defaults",
"backend_cls(arguments or {}) if not expiration_time or isinstance(expiration_time, Number): self.expiration_time",
"versionadded:: 0.4.1 Added ``set()`` method to decorated function. Similar to",
"to decorated function. Parameters passed to :meth:`.CacheRegion.cache_multi_on_arguments` have the same",
"s in arg) return generate_key region = make_region( function_key_generator =",
"that the decorator itself can't see the parent class on",
"The decorator will produce a list of cache keys using",
"which aren't present in the list are returned as the",
"cached function result. Example use cases include \"cache the result",
"mutex): mutexes[key] = mutex if expiration_time is None: expiration_time =",
"back before the expiration time so that a return+regen will",
"function. The default key generation will use the name of",
"will produce a cache key as follows:: myapp.tools:one|foo|3 4 The",
"cache:: generate_something.set({\"k1\": \"value1\", \"k2\": \"value2\", \"k3\": \"value3\"}) ...an ``invalidate()`` method,",
"elif expiration_time is not None and \\ current_time - value.metadata[\"ct\"]",
"time and region is invalidated in soft mode. \"\"\" raise",
"def refresh(*arg): keys = key_generator(*arg) values = fn(*arg) if asdict:",
"arguments passed to it. This method is the \"multiple key\"",
"or {}) if not expiration_time or isinstance(expiration_time, Number): self.expiration_time =",
"backend_values ) ] def get_or_create( self, key, creator, expiration_time=None, should_cache_fn=None):",
"return self.configure( config_dict[\"%sbackend\" % prefix], expiration_time=config_dict.get( \"%sexpiration_time\" % prefix, None),",
"key exists:: value = generate_something.get(5, 6) .. versionadded:: 0.5.3 Added",
"the ``.name`` parameter, helpful for configuring a region from a",
"can be substituted, but note this will produce unicode cache",
"upon the value creation function after this time period has",
"self.backend.set_multi(mapping) def delete(self, key): \"\"\"Remove a value from the cache.",
"order to generate a cache key. Given a function ``one``",
"invalidation time and region is invalidated in hard mode. \"\"\"",
"will produce a list of cache keys using a mechanism",
"\"\"\" raise NotImplementedError() def is_invalidated(self, timestamp): \"\"\"Check timestamp to determine",
"arguments={ 'url': '127.0.0.1:11211', 'distributed_lock': True, } ) Remember that the",
"self def wrap(self, proxy): ''' Takes a ProxyBackend instance or",
"function recommended by the cache backend will be used. A",
"returns the token ``NO_VALUE``. ``NO_VALUE`` evaluates to False, but is",
"particular cache backend. :param name: Optional, a string name for",
"mapping: return if self.key_mangler: mapping = dict(( self.key_mangler(k), self._value(v)) for",
"function is received by the decorator before it becomes an",
"decorated function should return its result as a dictionary of",
"same source file, such as those associated with classes -",
"] def get_or_create( self, key, creator, expiration_time=None, should_cache_fn=None): \"\"\"Return a",
"not None: return mutex else: return self._LockWrapper() def invalidate(self, hard=True):",
"def get(self, key, expiration_time=None, ignore_expiration=False): \"\"\"Return a value from the",
"generate_something.refresh(5, 6) .. versionadded:: 0.5.0 Added ``refresh()`` method to decorated",
"return [ somedatabase.query(key) for key in keys ] The decorated",
"value is unconditionally prevented from being returned. The method will",
"to and called by dogpile.lock when there is a stale",
"the value. Pass to ``invalidate()`` the same arguments you'd pass",
"given creation function may or may not be used to",
"_create_mutex(self, key): mutex = self.backend.get_mutex(key) if mutex is not None:",
"augmentation can be applied. .. versionadded:: 0.5.0 .. seealso:: :ref:`changing_backend_behavior`",
"self.wrap(wrapper) if region_invalidator: self.region_invalidator = region_invalidator return self def wrap(self,",
"k in keys_to_create]) timeout = expiration_time() if expiration_time_is_callable \\ else",
"well as returning that value:: newvalue = generate_something.refresh(5, 6) ..",
"= invalidate decorate.refresh = refresh decorate.get = get decorate.original =",
"has passed since the last generation. :param arguments: Optional. The",
"to a dictionary, use ``zip()``:: keys = [\"one\", \"two\", \"three\"]",
"compat import time import datetime from numbers import Number from",
"in soft mode. \"\"\" raise NotImplementedError() def is_invalidated(self, timestamp): \"\"\"Check",
":param wrap: Optional. A list of :class:`.ProxyBackend` classes and/or instances,",
"region.configure(region_invalidator=MyInvalidator(region)) .. versionadded:: 0.6.2 .. seealso:: :paramref:`.CacheRegion.configure.region_invalidator` \"\"\" def invalidate(self,",
"backend is already configured. .. versionadded:: 0.5.7 :param region_invalidator: Optional.",
"on keys corresponds to that of :meth:`.Region.get_or_create`, with the exception",
"additional behavioral details. E.g.:: @someregion.cache_on_arguments() def generate_something(x, y): return somedatabase.query(x,",
"an argument:: class MyInvalidator(RegionInvalidationStrategy): def __init__(self, region): self.region = region",
"function accepts non-ascii unicode arguments on Python 2.x, the ``unicode()``",
"keys ] The decorated function can be called normally. The",
"cached for the given key, or the token ``NO_VALUE`` if",
"decorated function is missing keys, those keys will not be",
"keys = key_generator(*arg, **kw) key_lookup = dict(zip(keys, cache_keys)) @wraps(fn) def",
"\" \"configured with backend: %s. \" \"Specify replace_existing_backend=True to replace.\"",
"versionadded:: 0.4.2 added the async_creation_runner feature. \"\"\" def __init__( self,",
"of values based on keys corresponds to that of :meth:`.Region.get_or_create`,",
"file, such as those associated with classes - note that",
"``MyOtherClass``. Python class declaration mechanics otherwise prevent the decorator from",
"the cache. :param asdict: if ``True``, the decorated function should",
"already. .. versionadded:: 0.5.1 \"\"\" return 'backend' in self.__dict__ def",
"# though haven't been able to simulate one anyway. keys_to_get",
"= None mutexes = {} sorted_unique_keys = sorted(set(keys)) if self.key_mangler:",
"invalidation. Example:: class CustomInvalidationStrategy(RegionInvalidationStrategy): def __init__(self): self._soft_invalidated = None self._hard_invalidated",
"= self.key_mangler(key) self.backend.delete(key) def delete_multi(self, keys): \"\"\"Remove multiple values from",
"cache key. Given a function ``one`` inside the module ``myapp.tools``::",
"Implement this interface and pass implementation instance to :meth:`.CacheRegion.configure` to",
"self.async_creation_runner = async_creation_runner self.region_invalidator = DefaultInvalidationStrategy() def configure( self, backend,",
"to decorated function. Lastly, the ``get()`` method returns either the",
"class is being declared. :param expiration_time: if not None, will",
"time.time(), \"v\": value_version }) def set(self, key, value): \"\"\"Place a",
"and called by dogpile.lock when there is a stale value",
"still returned, but isn't cached. E.g.:: def dont_cache_none(value): return value",
"else: async_creator = None with Lock( self._mutex(key), gen_value, get_value, expiration_time,",
"\"backend\" in self.__dict__ and not replace_existing_backend: raise exception.RegionAlreadyConfigured( \"This region",
"when there is a stale value present in the cache.",
"recommended by the cache backend will be used. A typical",
"was_soft_invalidated(self): return bool(self._soft_invalidated) def is_soft_invalidated(self, timestamp): return (self._soft_invalidated and timestamp",
"invalidation strategy interface Implement this interface and pass implementation instance",
"When ``asdict==True`` if the dictionary returned by the decorated function",
"returned from the cache if present, regardless of configured expiration",
"in arg) return generate_key region = make_region( function_key_generator = my_key_generator",
"a non-existent key, safely) .. versionadded:: 0.5.0 \"\"\" if self.key_mangler:",
"is compat.string_type: # backwards compatible key_generator = function_key_generator(namespace, fn) else:",
"key, creator, expiration_time=None, should_cache_fn=None): \"\"\"Return a cached value based on",
"= coerce_string_conf(config_dict) return self.configure( config_dict[\"%sbackend\" % prefix], expiration_time=config_dict.get( \"%sexpiration_time\" %",
"an integer or a callable. :param should_cache_fn: passed to :meth:`.CacheRegion.get_or_create_multi`.",
"function_multi_key_generator is None: function_multi_key_generator = self.function_multi_key_generator def decorator(fn): key_generator =",
"``creator()``, and ``creator()`` should return the generated values as a",
"if mutexes: # sort the keys, the idea is to",
"cache key. :param expiration_time: if not None, will override the",
"def is_soft_invalidated(self, timestamp): return (self._soft_invalidated and timestamp < self._soft_invalidated) The",
"invalidate(self, hard=None): if hard: self._soft_invalidated = None self._hard_invalidated = time.time()",
"regeneration will be assembled into a new argument list, and",
"retrieve all current values; the originally passed keys corresponding to",
"cached or not. If it returns False, the value is",
"should return its result as a dictionary of keys->values, and",
"] The decorated function can be called normally. The decorator",
"expiration time passed to the dogpile system. May be passed",
"return decorate return decorator def cache_multi_on_arguments( self, namespace=None, expiration_time=None, should_cache_fn=None,",
"raise exception.DogpileCacheException( \"Non-None expiration time required \" \"for soft invalidation\")",
"the expiration time, rather than returning the value unconditionally. The",
"method as well as the :meth:`.CacheRegion.cache_on_arguments` decorator (though note: **not**",
":param expiration_time: if not None, will override the normal expiration",
"configured on the :class:`.CacheRegion` itself. .. versionadded:: 0.3.0 :param ignore_expiration:",
"a in arg])) ) return values else: self.set_multi( dict(zip(keys, values))",
"= region.get_multi(keys) dictionary = dict(zip(keys, values)) Keys which aren't present",
"so in fact can be of any form. For example,",
"and \"cache until a certain date or time passes\". ..",
"``None``. .. versionadded:: 0.4.2 added the async_creation_runner feature. \"\"\" def",
"def get_multi(self, keys, expiration_time=None, ignore_expiration=False): \"\"\"Return multiple values from the",
"__init__(self): self._soft_invalidated = None self._hard_invalidated = None def invalidate(self, hard=None):",
"the :class:`.CacheRegion` itself. .. versionadded:: 0.5.5 .. seealso:: :meth:`.CacheRegion.cache_on_arguments` :meth:`.CacheRegion.get_or_create_multi`",
"The key generator will ignore an initial argument of ``self``",
"returns the value of create_value() if the cache is invalid,",
"the \"minimum creation time\" for a value. Any retrieved value",
"to be expired based on its creation time, the given",
"by the :meth:`.CacheRegion.get_or_create`, :meth:`.CacheRegion.get_or_create_multi` and :meth:`.CacheRegion.get` methods. The method supports",
":param expiration_time: Optional expiration time value which will supersede that",
":meth:`.CacheRegion.cache_on_arguments` - applies :meth:`.get_or_create` to any function using a decorator.",
"# if we were passed a type rather than an",
"raise NeedRegenerationException() ct = value.metadata[\"ct\"] if self.region_invalidator.is_soft_invalidated(ct): ct = time.time()",
"key\", create_value, should_cache_fn=dont_cache_none) Above, the function returns the value of",
"self._value(v)) for k, v in mapping.items()) self.backend.set_multi(mapping) def delete(self, key):",
"generate_something.set(3, 5, 6) The above example is equivalent to calling",
"available, until the lock is released and a new value",
"is also provided with a ``set()`` method, which here accepts",
"mangling, set to ``False``. Another typical mangler is the built-in",
"self.region_invalidator.is_hard_invalidated( value.metadata[\"ct\"])): raise NeedRegenerationException() ct = value.metadata[\"ct\"] if self.region_invalidator.is_soft_invalidated(ct): ct",
"was_soft_invalidated(self): return self._is_hard_invalidated is False def is_soft_invalidated(self, timestamp): return self.was_soft_invalidated()",
"a list:: result = generate_something(\"key1\", \"key2\", \"key3\") The decorator internally",
"{ \"ct\": time.time(), \"v\": value_version }) def set(self, key, value):",
"self.key_mangler: key = self.key_mangler(key) def get_value(): value = self.backend.get(key) if",
"is available. Usage of \"soft\" invalidation requires that the region",
"still return promptly. They will be refreshed by whatever asynchronous",
"expiration_time=None, should_cache_fn=None): \"\"\"Return a sequence of cached values based on",
"expiration time. May be specified as a callable, taking no",
"\"\"\"Check timestamp to determine if it was hard invalidated. :return:",
"to the :meth:`.CacheRegion.cache_on_arguments` method. Example:: @someregion.cache_multi_on_arguments() def generate_something(*keys): return [",
"method. Example:: @someregion.cache_multi_on_arguments() def generate_something(*keys): return [ somedatabase.query(key) for key",
"creation time is older than the last call to :meth:`.invalidate`.",
"get(*arg): keys = key_generator(*arg) return self.get_multi(keys) def refresh(*arg): keys =",
"for additional behavioral details. Unlike the :meth:`.CacheRegion.cache_on_arguments` method, :meth:`.CacheRegion.cache_multi_on_arguments` works",
"expiration_time elif isinstance(expiration_time, datetime.timedelta): self.expiration_time = int( compat.timedelta_total_seconds(expiration_time)) else: raise",
"values to a dictionary, use ``zip()``:: keys = [\"one\", \"two\",",
":param expiration_time: Optional. The expiration time passed to the dogpile",
"into a SHA1 hash, so that the string length is",
"by dogpile.lock when there is a stale value present in",
"None self._invalidated = None def invalidate(self, hard=True): self._is_hard_invalidated = bool(hard)",
"For a specific example using async_creation_runner, new values can be",
"myconfig = { \"cache.local.backend\":\"dogpile.cache.dbm\", \"cache.local.arguments.filename\":\"/path/to/dbmfile.dbm\", \"cache.memcached.backend\":\"dogpile.cache.pylibmc\", \"cache.memcached.arguments.url\":\"127.0.0.1, 10.0.0.1\", } local_region.configure_from_config(myconfig,",
"seealso:: :meth:`.CacheRegion.cache_multi_on_arguments` :meth:`.CacheRegion.get_or_create` \"\"\" expiration_time_is_callable = compat.callable(expiration_time) if function_key_generator is",
"mode. :return: Boolean. True if region was invalidated in soft",
"None), ) @memoized_property def backend(self): raise exception.RegionNotConfigured( \"No backend is",
"return a + b Above, calling ``one(3, 4)`` will produce",
"``set()`` is ``refresh()``. This attribute will invoke the decorated function",
"key based on the given arguments. Such as:: def my_key_generator(namespace,",
"of existing values will be pushed back before the expiration",
"v) for k, v in values_w_created.items() if should_cache_fn(v[0]) )) values.update(values_w_created)",
"else expiration_time if asdict: def dict_create(*keys): d_values = creator(*keys) return",
"custom implementation is injected into a :class:`.CacheRegion` at configure time",
"function can then be called normally, where data will be",
"is released to return the new value. .. versionchanged:: 0.3.0",
"will block if no previous value is available, until the",
"using the ``function_key_generator`` argument present on :func:`.make_region` and :class:`.CacheRegion`. If",
"- note that the decorator itself can't see the parent",
"> expiration_time: return NO_VALUE elif self.region_invalidator.is_invalidated( value.metadata[\"ct\"]): return NO_VALUE else:",
"a new :class:`.CacheRegion`.\"\"\" self.name = name self.function_key_generator = function_key_generator self.function_multi_key_generator",
"to recreate the value and persist the newly generated value",
"set_multi(self, mapping): \"\"\"Place new values in the cache under the",
"class _LockWrapper(object): \"\"\"weakref-capable wrapper for threading.Lock\"\"\" def __init__(self): self.lock =",
"value of ``False``, the decorated function should return its result",
"return decorate return decorator def make_region(*arg, **kw): \"\"\"Instantiate a new",
"DefaultInvalidationStrategy(RegionInvalidationStrategy): def __init__(self): self._is_hard_invalidated = None self._invalidated = None def",
"end to a particular cache backend. :param name: Optional, a",
"the current time (as reported by ``time.time()``). If stale, the",
"considered to be stale. It does not affect the data",
"or False, indicating if the value should actually be cached",
"same module, as can occur when decorating instance or class",
"the cache is invalid, however if the return value is",
"cache key above for ``MyClass().one(3, 4)`` will again produce the",
"with the string form of each key. It will then",
"value_version or self.region_invalidator.is_hard_invalidated( value.metadata[\"ct\"])): raise NeedRegenerationException() ct = value.metadata[\"ct\"] if",
"the arguments which would normally be passed to the function",
"all require immediate regeneration; dogpile logic won't be used. If",
"not expiration_time or isinstance(expiration_time, Number): self.expiration_time = expiration_time elif isinstance(expiration_time,",
"self.key_mangler: key = self.key_mangler(key) self.backend.delete(key) def delete_multi(self, keys): \"\"\"Remove multiple",
"creator, expiration_time=None, should_cache_fn=None): \"\"\"Return a cached value based on the",
"list. When ``asdict==True`` if the dictionary returned by the decorated",
"``.name`` parameter, helpful for configuring a region from a config",
"if to_str is compat.string_type: # backwards compatible key_generator = function_key_generator(namespace,",
"this instance of :class:`.CacheRegion`. Once set, the invalidation time is",
".. import Lock, NeedRegenerationException from ..util import NameRegistry from .",
".. versionadded:: 0.4.2 added the async_creation_runner feature. \"\"\" def __init__(",
"_value(self, value): \"\"\"Return a :class:`.CachedValue` given a value.\"\"\" return CachedValue(",
"time of the :class:`.CacheRegion`, or alternatively the expiration time supplied",
"if not None, will override the normal expiration time. May",
".. versionadded 0.5.0 ``expiration_time`` may be optionally passed as a",
":param should_cache_fn: optional callable function which will receive the value",
"loading the class from the ``dogpile.cache`` entrypoint. :param expiration_time: Optional.",
"key): \"\"\"Remove a value from the cache. This operation is",
"equivalent to calling ``generate_something(5, 6)``, if the function were to",
"None, will override the normal expiration time. May be specified",
"sort the keys, the idea is to prevent deadlocks. #",
"fn, to_str=to_str) @wraps(fn) def decorate(*arg, **kw): cache_keys = arg keys",
"which will call the creation function, cache the new values,",
"generator :func:`.kwarg_function_key_generator` - optional gen that also uses keyword arguments",
"): pass try: if mutexes: # sort the keys, the",
":param arguments: Optional. The structure here is passed directly to",
"passed to :meth:`.CacheRegion.get_or_create`. .. versionadded:: 0.4.3 :param to_str: callable, will",
"\"\"\" if not keys: return [] if self.key_mangler: keys =",
"is older than the last call to :meth:`.invalidate`. :param key:",
"expiration_time_is_callable = compat.callable(expiration_time) if function_key_generator is None: function_key_generator = self.function_key_generator",
"creator: function which accepts a sequence of keys and returns",
"compat.string_type: # backwards compatible key_generator = function_key_generator(namespace, fn) else: key_generator",
"bool(self._hard_invalidated) def is_hard_invalidated(self, timestamp): return (self._hard_invalidated and timestamp < self._hard_invalidated)",
"will then consult the cache using the same mechanism as",
"was invalidated in soft mode. \"\"\" raise NotImplementedError() def was_hard_invalidated(self):",
"so:: import threading def async_creation_runner(cache, somekey, creator, mutex): ''' Used",
"\"cache.memcached.backend\":\"dogpile.cache.pylibmc\", \"cache.memcached.arguments.url\":\"127.0.0.1, 10.0.0.1\", } local_region.configure_from_config(myconfig, \"cache.local.\") memcached_region.configure_from_config(myconfig, \"cache.memcached.\") \"\"\" config_dict",
"of :meth:`.Region.get_or_create`, with the exception that the ``creator()`` function may",
"to decorated function. The default key generation will use the",
"\"for soft invalidation\") if expiration_time == -1: expiration_time = None",
"time already configured on this :class:`.CacheRegion` if not None. To",
"a new value. :param expiration_time: optional expiration time which will",
"that of :meth:`.Region.get_or_create`, with the exception that the ``creator()`` function",
"True or False, indicating if the value should actually be",
"prefix): \"\"\"Configure from a configuration dictionary and a prefix. Example::",
"None mutexes = {} sorted_unique_keys = sorted(set(keys)) if self.key_mangler: mangled_keys",
"invalidated in hard mode. :return: Boolean. True if region was",
"will be passed to and called by dogpile.lock when there",
"0.5.5 .. seealso:: :meth:`.CacheRegion.cache_on_arguments` :meth:`.CacheRegion.get_or_create_multi` \"\"\" expiration_time_is_callable = compat.callable(expiration_time) if",
"simple list of keys as arguments. Like :meth:`.CacheRegion.cache_on_arguments`, the decorated",
"mode. \"\"\" raise NotImplementedError() def is_soft_invalidated(self, timestamp): \"\"\"Check timestamp to",
"use, though is typically a dictionary. :param wrap: Optional. A",
"6) The above example is equivalent to calling ``generate_something(5, 6)``,",
"will be established as part of each cache key. :param",
"decorator(fn): key_generator = function_multi_key_generator( namespace, fn, to_str=to_str) @wraps(fn) def decorate(*arg,",
"to ``function_key_generator`` parameter, but it's used in :meth:`.CacheRegion.cache_multi_on_arguments`. Generated function",
"value's timestamp is older than the invalidation timestamp, the value",
"optional callable function which will receive each value returned by",
"*dogpile lock* can be acquired or not. If it can't,",
"the given keys. Returns values as a list matching the",
"def is_soft_invalidated(self, timestamp): \"\"\"Check timestamp to determine if it was",
"in backend_values ) ] def get_or_create( self, key, creator, expiration_time=None,",
"in terms of the current \"invalidation\" time as set by",
"string length is fixed. To disable all key mangling, set",
"queue, or a task manager system like Celery. For a",
"will all require immediate regeneration; dogpile logic won't be used.",
"block if no previous value is available, until the lock",
".util import function_key_generator, function_multi_key_generator from .api import NO_VALUE, CachedValue from",
"the same source file, such as those associated with classes",
"instance then # initialize it. if type(proxy) == type: proxy",
"'') def generate_keys(*args): return [namespace + ':' + str(a) for",
"orig_to_mangled.items(): with Lock( self._mutex(mangled_key), gen_value, lambda: get_value(mangled_key), expiration_time, async_creator=lambda mutex:",
"if True, cache values will all require immediate regeneration; dogpile",
"= get return decorate return decorator def make_region(*arg, **kw): \"\"\"Instantiate",
"for :meth:`.CacheRegion.set` which will store a given value directly without",
"self.key_mangler(key), keys)) backend_values = self.backend.get_multi(keys) _unexpired_value_fn = self._unexpired_value_fn( expiration_time, ignore_expiration)",
"def _unexpired_value_fn(self, expiration_time, ignore_expiration): if ignore_expiration: return lambda value: value",
"self.__dict__ def get(self, key, expiration_time=None, ignore_expiration=False): \"\"\"Return a value from",
"is fixed. To disable all key mangling, set to ``False``.",
"import compat import time import datetime from numbers import Number",
"if asdict: def dict_create(*keys): d_values = creator(*keys) return [ d_values.get(key_lookup[k],",
"expensive creator functions to later points in the future by",
"function_multi_key_generator self.key_mangler = self._user_defined_key_mangler = key_mangler self.async_creation_runner = async_creation_runner self.region_invalidator",
"which has the effect of deleting the given sequence of",
"self.function_key_generator def decorator(fn): if to_str is compat.string_type: # backwards compatible",
"setting a current timestamp (using ``time.time()``) to consider all older",
"of cache keys using a mechanism similar to that of",
"not should_cache_fn: return True else: return should_cache_fn(value) result = self.get_or_create_multi(",
"def is_hard_invalidated(self, timestamp): return self.was_hard_invalidated() and self.is_invalidated(timestamp) def was_soft_invalidated(self): return",
"return [] if self.key_mangler: keys = list(map(lambda key: self.key_mangler(key), keys))",
"that the ``creator()`` function may be asked to generate any",
"when decorating instance or class methods as below:: class MyClass(object):",
"or need regeneration will be assembled into a new argument",
"subset of arguments. The returned result is a list:: result",
"if expiration_time == -1: expiration_time = None mutexes = {}",
"directly to the constructor of the :class:`.CacheBackend` in use, though",
"present on :func:`.make_region` and :class:`.CacheRegion`. If defaults to :func:`.function_key_generator`. :param",
"and return them:: values = generate_something.refresh(\"k1\", \"k2\", \"k3\") ...and a",
"timestamp): return self.was_soft_invalidated() and self.is_invalidated(timestamp) class CacheRegion(object): \"\"\"A front end",
"to :meth:`.CacheRegion.cache_on_arguments`. :param should_cache_fn: passed to :meth:`.CacheRegion.get_or_create`. .. versionadded:: 0.4.3",
"async_creation_runner=None, ): \"\"\"Construct a new :class:`.CacheRegion`.\"\"\" self.name = name self.function_key_generator",
"note: **not** the :meth:`.CacheRegion.get` method) will call upon the value",
"down to the cache backend, before being optionally processed by",
"= function_key_generator(namespace, fn) else: key_generator = function_key_generator( namespace, fn, to_str=to_str)",
"the function is used depends on if the *dogpile lock*",
"``time.time()``) representing the \"minimum creation time\" for a value. Any",
"function should follow:: generate_something.set(3, 5, 6) The above example is",
"via the ``.name`` parameter, helpful for configuring a region from",
"invalidate(self, hard=True): \"\"\"Region invalidation. :class:`.CacheRegion` propagated call. The default invalidation",
"= time.time() - expiration_time - .0001 return value.payload, ct def",
"the value is returned from the cache if present, regardless",
"of the function, the module name for the function, the",
"the function is received by the decorator before it becomes",
"a callable to :meth:`.CacheRegion.cache_on_arguments`. :param should_cache_fn: passed to :meth:`.CacheRegion.get_or_create`. ..",
"key_generator(*arg) self.delete_multi(keys) def set_(mapping): keys = list(mapping) gen_keys = key_generator(*keys)",
"the region or the method is given a non-None expiration",
"method will block if no previous value is available, until",
"from ..util import PluginLoader, memoized_property, coerce_string_conf from .util import function_key_generator,",
"for a in arg])) ) return values else: self.set_multi( dict(zip(keys,",
"of keys. The behavior for generation of values based on",
"exception.RegionAlreadyConfigured( \"This region is already \" \"configured with backend: %s.",
"\"\"\"Configure a :class:`.CacheRegion`. The :class:`.CacheRegion` itself is returned. :param backend:",
"a key with no associated value will always block; async_creator",
"\"\"\" def invalidate(self, hard=True): \"\"\"Region invalidation. :class:`.CacheRegion` propagated call. The",
"to distinguish between a cached value of ``None``. By default,",
"between a cached value of ``None``. By default, the configured",
"def make_region(*arg, **kw): \"\"\"Instantiate a new :class:`.CacheRegion`. Currently, :func:`.make_region` is",
"``NO_VALUE`` token is returned. Passing the flag ``ignore_expiration=True`` bypasses the",
"invalidated in hard mode. \"\"\" raise NotImplementedError() class DefaultInvalidationStrategy(RegionInvalidationStrategy): def",
"disambiguates between ``somemethod`` on ``MyClass`` and ``MyOtherClass``. Python class declaration",
"the cache. When the dogpile lock cannot be acquired, the",
"which will receive the value returned by the \"creator\", and",
"self, keys, creator, expiration_time=None, should_cache_fn=None): \"\"\"Return a sequence of cached",
"return [ d_values.get(key_lookup[k], NO_VALUE) for k in keys] def wrap_cache_fn(value):",
"responsible releasing that mutex when finished. This can be used",
":class:`.CacheRegion` itself is returned. :param backend: Required. This is the",
"cache keys using a mechanism similar to that of :meth:`.CacheRegion.cache_on_arguments`,",
"finally: for mutex in mutexes.values(): mutex.release() def _value(self, value): \"\"\"Return",
"from ..util import compat import time import datetime from numbers",
"def generate_something(*keys): return [ somedatabase.query(key) for key in keys ]",
"\"Specify replace_existing_backend=True to replace.\" % self.backend) backend_cls = _backend_loader.load(backend) if",
"that of :meth:`.CacheRegion.get_multi` to retrieve all current values; the originally",
"time. \"\"\" raise NotImplementedError() def was_soft_invalidated(self): \"\"\"Indicate the region was",
"take note this function invokes ``.set_multi()`` for newly generated values",
"delete_multi(self, keys): \"\"\"Remove multiple values from the cache. This operation",
"as well as returning that value:: newvalue = generate_something.refresh(5, 6)",
"keys. .. versionadded:: 0.5.0 \"\"\" if not mapping: return if",
"gen that also uses keyword arguments :param function_multi_key_generator: Optional. Similar",
"raise exception.RegionNotConfigured( \"No backend is configured on this region.\") @property",
"on a non-existent key, safely) .. versionadded:: 0.5.0 \"\"\" if",
"for additional behavioral details. E.g.:: @someregion.cache_on_arguments() def generate_something(x, y): return",
"generate a new value, or will wait until the lock",
"keys using the same mechanism as that of :meth:`.CacheRegion.delete_multi`:: generate_something.invalidate(\"k1\",",
"def configure_from_config(self, config_dict, prefix): \"\"\"Configure from a configuration dictionary and",
"= self.backend.get(key) if (value is NO_VALUE or value.metadata['v'] != value_version",
"values will all require immediate regeneration; dogpile logic won't be",
"keys and returns a sequence of new values. :param expiration_time:",
"to be generated is passed to ``creator()``, and ``creator()`` should",
"function which will receive each value returned by the \"creator\",",
"which will be established as part of the cache key.",
"refresh decorate.get = get return decorate return decorator def make_region(*arg,",
"based on the given key. If the value does not",
"key: Key to be retrieved. While it's typical for a",
"to simulate one anyway. keys_to_get = sorted(mutexes) new_values = creator(*keys_to_get)",
"Like :meth:`.CacheRegion.cache_on_arguments`, the decorated function is also provided with a",
"values.get(key, NO_VALUE) if (value is NO_VALUE or value.metadata['v'] != value_version",
"**kw): return my_data() .. seealso:: :func:`.function_key_generator` - default key generator",
"\"invalidation\" time as set by the :meth:`.invalidate` method. If a",
"not mapping: return if self.key_mangler: mapping = dict(( self.key_mangler(k), self._value(v))",
"like Celery. For a specific example using async_creation_runner, new values",
"somekey, creator, mutex): ''' Used by dogpile.core:Lock when appropriate '''",
"using the :meth:`.CacheRegion.cache_on_arguments` method. The structure of this function should",
"configure_from_config(self, config_dict, prefix): \"\"\"Configure from a configuration dictionary and a",
"thread or process is already running a creation function for",
"replace_existing_backend=False, region_invalidator=None ): \"\"\"Configure a :class:`.CacheRegion`. The :class:`.CacheRegion` itself is",
"key, safely) .. versionadded:: 0.5.0 \"\"\" if self.key_mangler: keys =",
"generate_something.invalidate(5, 6) Another attribute ``set()`` is added to provide extra",
"it becomes an instance method. The function key generation can",
"the \"creator\", and will then return True or False, indicating",
"= creator(*keys_to_get) values_w_created = dict( (orig_to_mangled[k], self._value(v)) for k, v",
"that wish to have access to the :class:`.CacheRegion` itself should",
"is tested against the creation time of the retrieved value",
"key against the cache. When the dogpile lock cannot be",
"``namespace`` parameter disambiguates between ``somemethod`` on ``MyClass`` and ``MyOtherClass``. Python",
"the function. See that method for additional behavioral details. Unlike",
"be used on all incoming keys before passing to the",
"self._soft_invalidated = time.time() self._hard_invalidated = None def is_invalidated(self, timestamp): return",
"expiration time of the :class:`.CacheRegion`, or alternatively the expiration time",
"multiple times, or on a non-existent key, safely) .. versionadded::",
"the expiration time already configured on this :class:`.CacheRegion` if not",
"Similar to ``function_key_generator`` parameter, but it's used in :meth:`.CacheRegion.cache_multi_on_arguments`. Generated",
"6) .. versionadded:: 0.5.3 Added ``get()`` method to decorated function.",
"compatible key_generator = function_key_generator(namespace, fn) else: key_generator = function_key_generator( namespace,",
"the built-in Python function ``str``, which can be used to",
"``namespace`` parameter is optional, and is used normally to disambiguate",
"values will be pushed back before the expiration time so",
"and persist the newly generated value in the cache. Whether",
"type recognized by the backend or by the key_mangler function,",
"the same name within the same module, as can occur",
"a value. Any retrieved value whose creation time is prior",
"versus the current time (as reported by ``time.time()``). If stale,",
"function that will produce a \"cache key\". This function will",
"to this timestamp is considered to be stale. It does",
"return self._lock_registry.get(key) class _LockWrapper(object): \"\"\"weakref-capable wrapper for threading.Lock\"\"\" def __init__(self):",
"is equivalent to calling ``generate_something(5, 6)``, if the function were",
"= None self._invalidated = None def invalidate(self, hard=True): self._is_hard_invalidated =",
"reaching the cache. .. versionadded:: 0.5.0 :param function_multi_key_generator: a function",
"separate from ``None`` to distinguish between a cached value of",
"see the parent class on a function as the class",
"CachedValue from .proxy import ProxyBackend from ..util import compat import",
"getattr(wrap, '__iter__', False): for wrapper in reversed(wrap): self.wrap(wrapper) if region_invalidator:",
":meth:`.CacheRegion.cache_on_arguments`, combining the name of the function with the optional",
"- expiration_time - .0001 return value.payload, ct def gen_value(): raise",
"persist the newly generated value in the cache. Whether or",
"to_str is compat.string_type: # backwards compatible key_generator = function_key_generator(namespace, fn)",
"a new value in the cache under the given key.\"\"\"",
"mangling before reaching the cache. .. versionadded:: 0.5.0 :param function_multi_key_generator:",
"construct the invalidator given the region as an argument:: class",
"the expiration time supplied by the ``expiration_time`` argument, is tested",
"# sort the keys, the idea is to prevent deadlocks.",
"callable, taking no arguments, that returns a value to be",
"zip(gen_keys, keys)) ) def get(*arg): keys = key_generator(*arg) return self.get_multi(keys)",
"to use, and is resolved by loading the class from",
"is_invalidated(self, timestamp): return (self._invalidated is not None and timestamp <",
"each of which will be applied in a chain to",
"the invalidation time is honored by the :meth:`.CacheRegion.get_or_create`, :meth:`.CacheRegion.get_or_create_multi` and",
"the cache and conditionally call the function. See that method",
"of any form. For example, it can be passed as",
"time using the :paramref:`.CacheRegion.configure.region_invalidator` parameter:: region = CacheRegion() region =",
"*dynamic* expiration time for the cached function result. Example use",
"\"\"\" class RegionInvalidationStrategy(object): \"\"\"Region invalidation strategy interface Implement this interface",
"expiration time value which will supersede that configured on the",
"0.5.0 \"\"\" if self.key_mangler: keys = list(map(lambda key: self.key_mangler(key), keys))",
"ignore an initial argument of ``self`` or ``cls``, making the",
"the :meth:`.CacheRegion.get` method) will call upon the value creation function",
"passed to :meth:`.CacheRegion.cache_multi_on_arguments` have the same meaning as those passed",
"invalidation time and region is invalidated in soft mode. \"\"\"",
"= [\"one\", \"two\", \"three\"] values = region.get_multi(keys) dictionary = dict(zip(keys,",
"Python function ``str``, which can be used to convert non-string",
"value: return value def get_or_create_multi( self, keys, creator, expiration_time=None, should_cache_fn=None):",
"are ready to use for function # decorators, but not",
"MyInvalidator(RegionInvalidationStrategy): def __init__(self, region): self.region = region # ... #",
"The method will attempt to acquire the dogpile lock to",
"by the decorator before it becomes an instance method. The",
"= refresh decorate.get = get return decorate return decorator def",
"is configured on this region.\") @property def is_configured(self): \"\"\"Return True",
"= key if self.key_mangler: key = self.key_mangler(key) def get_value(): value",
"not self._user_defined_key_mangler: self.key_mangler = self.backend.key_mangler self._lock_registry = NameRegistry(self._create_mutex) if getattr(wrap,",
"value cached for the given key, or the token ``NO_VALUE``",
"should be two levels: given the data creation function, return",
".. versionadded:: 0.5.1 \"\"\" return 'backend' in self.__dict__ def get(self,",
"optionally processed by the key_mangler function, so can be of",
"this function, so in fact can be of any form.",
"return them:: values = generate_something.refresh(\"k1\", \"k2\", \"k3\") ...and a ``get()``",
"was soft invalidated. :return: Boolean. True if ``timestamp`` is older",
"released to return the new value. .. versionchanged:: 0.3.0 The",
"calling function. A correct implementation of ``.set_multi()`` will not modify",
"or not :meth:`.invalidate` was called. .. versionadded:: 0.3.0 \"\"\" if",
"= generate_something.refresh(5, 6) .. versionadded:: 0.5.0 Added ``refresh()`` method to",
"return self.was_hard_invalidated() and self.is_invalidated(timestamp) def was_soft_invalidated(self): return self._is_hard_invalidated is False",
"def gen_value(): created_value = creator() value = self._value(created_value) if not",
"compat.callable(expiration_time) if function_multi_key_generator is None: function_multi_key_generator = self.function_multi_key_generator def decorator(fn):",
"keys to bytestrings, which is needed when using a backend",
"the lock is released to return the new value. ..",
"end of the day, week or time period\" and \"cache",
"integer or a callable. :param should_cache_fn: passed to :meth:`.CacheRegion.get_or_create_multi`. This",
"logic won't be used. If False, the creation time of",
"to convert to a string. Defaults to ``str()``. If the",
"if it was invalidated. :return: Boolean. True if ``timestamp`` is",
"This attribute will invoke the decorated function and populate a",
"used on all incoming keys before passing to the backend.",
"``timestamp`` is older than the last region invalidation time and",
"def wrap(self, proxy): ''' Takes a ProxyBackend instance or class",
"that the first request for a key with no associated",
":meth:`.invalidate` method. If a value is present, but its creation",
"list are returned as the ``NO_VALUE`` token. ``NO_VALUE`` evaluates to",
"a dictionary. If left at its default value of ``False``,",
"get_or_create_multi( self, keys, creator, expiration_time=None, should_cache_fn=None): \"\"\"Return a sequence of",
"5, 6) The above example is equivalent to calling ``generate_something(5,",
"mutex if expiration_time is None: expiration_time = self.expiration_time if (expiration_time",
"such key exists:: value = generate_something.get(5, 6) .. versionadded:: 0.5.3",
"be established as part of the cache key. This may",
"import Number from functools import wraps import threading _backend_loader =",
"self.__dict__ and not replace_existing_backend: raise exception.RegionAlreadyConfigured( \"This region is already",
"``refresh()``. This attribute will invoke the decorated function and populate",
"unconditionally. The method also interprets the cached value in terms",
"to ``False``. Another typical mangler is the built-in Python function",
"if expiration_time_is_callable \\ else expiration_time return self.get_or_create(key, creator, timeout, should_cache_fn)",
"disambiguate functions of the same name within the same source",
"itself and the arguments passed to it. This method is",
"behavioral details. Unlike the :meth:`.CacheRegion.cache_on_arguments` method, :meth:`.CacheRegion.cache_multi_on_arguments` works only with",
"the cache under the given keys. .. versionadded:: 0.5.0 \"\"\"",
"of keys as arguments. Like :meth:`.CacheRegion.cache_on_arguments`, the decorated function is",
"until the new one is available. Usage of \"soft\" invalidation",
"value is NO_VALUE: return value elif expiration_time is not None",
"\"\"\"Indicate the region was invalidated in soft mode. :return: Boolean.",
"as value: return value def get_or_create_multi( self, keys, creator, expiration_time=None,",
"generate_something.refresh(\"k1\", \"k2\", \"k3\") ...and a ``get()`` method, which will return",
"than returning the value unconditionally. The method also interprets the",
"mapping[key]) for gen_key, key in zip(gen_keys, keys)) ) def get(*arg):",
"them:: values = generate_something.refresh(\"k1\", \"k2\", \"k3\") ...and a ``get()`` method,",
"0.4.3 .. seealso:: :meth:`.CacheRegion.cache_on_arguments` - applies :meth:`.get_or_create` to any function",
"immediate regeneration; dogpile logic won't be used. If False, the",
"The structure here is passed directly to the constructor of",
"as those associated with classes - note that the decorator",
"Optional, a string name for the region. This isn't used",
"return True else: return should_cache_fn(value) result = self.get_or_create_multi( keys, dict_create,",
"value) def get(*arg, **kw): key = key_generator(*arg, **kw) return self.get(key)",
"function result. Example use cases include \"cache the result until",
".0001 return value.payload, ct def gen_value(): raise NotImplementedError() def async_creator(key,",
"to set in the cache:: generate_something.set({\"k1\": \"value1\", \"k2\": \"value2\", \"k3\":",
"key\" analogue to the :meth:`.CacheRegion.cache_on_arguments` method. Example:: @someregion.cache_multi_on_arguments() def generate_something(*keys):",
"or time period\" and \"cache until a certain date or",
"to get and set values from the backend. If you",
"0.5.0 .. seealso:: :meth:`.CacheRegion.cache_multi_on_arguments` :meth:`.CacheRegion.get_or_create` \"\"\" def get_value(key): value =",
"``creator()`` function may be asked to generate any subset of",
"was invalidated in hard mode. :return: Boolean. True if region",
"value's creation time against the expiration time, rather than returning",
"self._soft_invalidated) or (self._hard_invalidated and timestamp < self._hard_invalidated)) def was_hard_invalidated(self): return",
"with no associated value will always block; async_creator will not",
"return decorator def cache_multi_on_arguments( self, namespace=None, expiration_time=None, should_cache_fn=None, asdict=False, to_str=compat.string_type,",
"at configure time using the :paramref:`.CacheRegion.configure.region_invalidator` parameter:: region = CacheRegion()",
"[str(x) for x in arg] ) return generate_key Where the",
"pass to the function itself to represent a particular value::",
"instance method. The function key generation can be entirely replaced",
"the region as an argument:: class MyInvalidator(RegionInvalidationStrategy): def __init__(self, region):",
"def was_hard_invalidated(self): return self._is_hard_invalidated is True def is_hard_invalidated(self, timestamp): return",
"decorate return decorator def cache_multi_on_arguments( self, namespace=None, expiration_time=None, should_cache_fn=None, asdict=False,",
"\"k2\", \"k3\") .. versionadded:: 0.5.3 Added ``get()`` method to decorated",
"to have access to the :class:`.CacheRegion` itself should construct the",
"self.region = region # ... # ... region = CacheRegion()",
"decorated function. Lastly, the ``get()`` method returns either the value",
":param to_str: callable, will be called on each function argument",
"if self.key_mangler: key = self.key_mangler(key) def get_value(): value = self.backend.get(key)",
"given value directly without calling the decorated function. The value",
"otherwise prevent the decorator from having awareness of the ``MyClass``",
"= key_generator(*arg) return self.get_multi(keys) def refresh(*arg): keys = key_generator(*arg) values",
"2.x in conjunction with Unicode keys. :param async_creation_runner: A callable",
"from the cache if present, regardless of configured expiration times",
"ignore_expiration: return lambda value: value else: if expiration_time is None:",
"the same values it returns to the calling function. A",
"method, which will return values based on the given arguments::",
"\"%swrap\" % prefix, None), ) @memoized_property def backend(self): raise exception.RegionNotConfigured(",
"internally makes use of the :meth:`.CacheRegion.get_or_create_multi` method to access the",
"% prefix, None), ) @memoized_property def backend(self): raise exception.RegionNotConfigured( \"No",
"def set_multi(self, mapping): \"\"\"Place new values in the cache under",
"value ``3`` as the value to be cached. .. versionadded::",
"config is available myconfig = { \"cache.local.backend\":\"dogpile.cache.dbm\", \"cache.local.arguments.filename\":\"/path/to/dbmfile.dbm\", \"cache.memcached.backend\":\"dogpile.cache.pylibmc\", \"cache.memcached.arguments.url\":\"127.0.0.1,",
"dict(zip(sorted_unique_keys, mangled_keys)) values = dict(zip(mangled_keys, self.backend.get_multi(mangled_keys))) for orig_key, mangled_key in",
"lambda value: value else: if expiration_time is None: expiration_time =",
"my_data() .. seealso:: :func:`.function_key_generator` - default key generator :func:`.kwarg_function_key_generator` -",
"and not replace_existing_backend: raise exception.RegionAlreadyConfigured( \"This region is already \"",
"reported by ``time.time()``). If stale, the cached value is ignored",
"the :meth:`.CacheRegion.configure` method already. .. versionadded:: 0.5.1 \"\"\" return 'backend'",
"and returns a sequence of new values. :param expiration_time: optional",
"multiple times, or on a non-existent key, safely) \"\"\" if",
"the method will block if no previous value is available,",
"key = self.key_mangler(key) self.backend.delete(key) def delete_multi(self, keys): \"\"\"Remove multiple values",
"= None def invalidate(self, hard=True): self._is_hard_invalidated = bool(hard) self._invalidated =",
"generates the key based on the given arguments. Such as::",
"exist or is considered to be expired based on its",
"SHA1 hash, so that the string length is fixed. To",
"be used as:: @my_region.cache_on_arguments(namespace=('x', 'y')) def my_function(a, b, **kw): return",
"either the value cached for the given key, or the",
"a previous, backwards-incompatible version. \"\"\" class RegionInvalidationStrategy(object): \"\"\"Region invalidation strategy",
"and :meth:`.Region.set_multi` to get and set values from the backend.",
"and the decorated function is then called with that subset",
"self, key, creator, expiration_time=None, should_cache_fn=None): \"\"\"Return a cached value based",
"= None def invalidate(self, hard=None): if hard: self._soft_invalidated = None",
"0.3.0 :param ignore_expiration: if ``True``, the value is returned from",
"in the cache under the given key.\"\"\" if self.key_mangler: key",
"function should return its result as a dictionary of keys->values,",
"the provided async_creation_runner callable implements. By default the async_creation_runner is",
"wait until the lock is released to return the new",
"or isinstance(expiration_time, Number): self.expiration_time = expiration_time elif isinstance(expiration_time, datetime.timedelta): self.expiration_time",
"function may be asked to generate any subset of the",
"thread, a long-running queue, or a task manager system like",
"backends # noqa value_version = 1 \"\"\"An integer placed in",
"= make_region( function_key_generator = my_key_generator ).configure( \"dogpile.cache.dbm\", expiration_time=300, arguments={ \"filename\":\"file.dbm\"",
"0 else: ct = value.metadata[\"ct\"] if self.region_invalidator.is_soft_invalidated(ct): ct = time.time()",
":meth:`.CacheRegion.get_or_create`. .. versionadded:: 0.4.3 :param to_str: callable, will be called",
"keys = key_generator(*arg) values = fn(*arg) if asdict: self.set_multi( dict(zip(keys,",
"or is considered to be expired based on its creation",
"self.key_mangler = self.backend.key_mangler self._lock_registry = NameRegistry(self._create_mutex) if getattr(wrap, '__iter__', False):",
"well as an optional \"namespace\" parameter in order to generate",
"method returns either the value cached for the given key,",
"\"two\", \"three\"] values = region.get_multi(keys) dictionary = dict(zip(keys, values)) Keys",
"will not modify values in-place on the submitted ``mapping`` dict.",
"gen_value(): raise NotImplementedError() def async_creator(key, mutex): mutexes[key] = mutex if",
"from a config file. :param function_key_generator: Optional. A function that",
"Python class declaration mechanics otherwise prevent the decorator from having",
"include \"cache the result until the end of the day,",
"decorate.set = set_ decorate.invalidate = invalidate decorate.refresh = refresh decorate.get",
"expiration_time, ignore_expiration): if ignore_expiration: return lambda value: value else: if",
"is not a valid ProxyBackend\" % type(proxy)) self.backend = proxy.wrap(self.backend)",
"result = generate_something(\"key1\", \"key2\", \"key3\") The decorator internally makes use",
"from the backend. If you are using a :class:`.CacheBackend` or",
"the same cache key of ``myapp.tools:one|foo|3 4`` - the name",
"get_or_create( self, key, creator, expiration_time=None, should_cache_fn=None): \"\"\"Return a cached value",
"its result as a dictionary of keys->values, and the final",
"a string name for the region. This isn't used internally",
"= async_creation_runner self.region_invalidator = DefaultInvalidationStrategy() def configure( self, backend, expiration_time=None,",
"ct = value.metadata[\"ct\"] if self.region_invalidator.is_soft_invalidated(ct): ct = time.time() - expiration_time",
"If it returns False, the value is still returned, but",
"method. :param key: Key to be retrieved. While it's typical",
"previous, backwards-incompatible version. \"\"\" class RegionInvalidationStrategy(object): \"\"\"Region invalidation strategy interface",
"each value returned by the \"creator\", and will then return",
"class MyClass(object): @region.cache_on_arguments(namespace=\"foo\") def one(self, a, b): return a +",
"only with a single function signature, one which takes a",
"decorated function should return its result as a list of",
"the creation time of existing values will be pushed back",
"wrap the original backend, so that custom functionality augmentation can",
"expiration_time = self.expiration_time if (expiration_time is None and self.region_invalidator.was_soft_invalidated()): raise",
":meth:`.invalidate` method has been called, and the retrieved value's timestamp",
"expiration_time=None, should_cache_fn=None, asdict=False, to_str=compat.string_type, function_multi_key_generator=None): \"\"\"A function decorator that will",
").configure( \"dogpile.cache.dbm\", expiration_time=300, arguments={ \"filename\":\"file.dbm\" } ) The ``namespace`` is",
"given key. If the value does not exist or is",
"with instance or class methods. Given the example:: class MyClass(object):",
"to return the new value. .. versionchanged:: 0.3.0 The value",
"else: self.set_multi( dict(zip(keys, values)) ) return values decorate.set = set_",
"can be of any type recognized by the backend or",
"return self.was_soft_invalidated() and self.is_invalidated(timestamp) class CacheRegion(object): \"\"\"A front end to",
"value, { \"ct\": time.time(), \"v\": value_version }) def set(self, key,",
"bypasses the expiration time check. .. versionchanged:: 0.3.0 :meth:`.CacheRegion.get` now",
"was_hard_invalidated(self): return self._is_hard_invalidated is True def is_hard_invalidated(self, timestamp): return self.was_hard_invalidated()",
"becomes an instance method. The function key generation can be",
"that, when specified, will be passed to and called by",
"is then called with that subset of arguments. The returned",
"mapping = dict(( self.key_mangler(k), self._value(v)) for k, v in mapping.items())",
"value creation function after this time period has passed since",
"on the given key. If the value does not exist",
"def decorator(fn): if to_str is compat.string_type: # backwards compatible key_generator",
"config file. :param function_key_generator: Optional. A function that will produce",
"value be placed in the cache. :param asdict: if ``True``,",
"functools import wraps import threading _backend_loader = PluginLoader(\"dogpile.cache\") register_backend =",
"keys. The behavior for generation of values based on keys",
":class:`.CacheRegion`. If defaults to :func:`.function_key_generator`. :param namespace: optional string argument",
"as the function is received by the decorator before it",
"cache. When the dogpile lock cannot be acquired, the method",
"class DefaultInvalidationStrategy(RegionInvalidationStrategy): def __init__(self): self._is_hard_invalidated = None self._invalidated = None",
"will supersede the one configured on the :class:`.CacheRegion` itself. ..",
"to :meth:`.CacheRegion.get_or_create_multi`. This function is given a value as returned",
"in zip(keys_to_get, new_values) ) if not should_cache_fn: self.backend.set_multi(values_w_created) else: self.backend.set_multi(dict(",
"threading _backend_loader = PluginLoader(\"dogpile.cache\") register_backend = _backend_loader.register from . import",
"return generate_key region = make_region( function_key_generator = my_key_generator ).configure( \"dogpile.cache.dbm\",",
"return CachedValue( value, { \"ct\": time.time(), \"v\": value_version }) def",
"simulate one anyway. keys_to_get = sorted(mutexes) new_values = creator(*keys_to_get) values_w_created",
"that returns a value to be used as the ``expiration_time``.",
"of expensive creator functions to later points in the future",
":class:`.CacheRegion`.\"\"\" self.name = name self.function_key_generator = function_key_generator self.function_multi_key_generator = function_multi_key_generator",
"``None``. By default, the configured expiration time of the :class:`.CacheRegion`,",
"the given creation function may or may not be used",
"expiration_time=None, arguments=None, _config_argument_dict=None, _config_prefix=None, wrap=None, replace_existing_backend=False, region_invalidator=None ): \"\"\"Configure a",
"argument of ``self`` or ``cls``, making the decorator suitable (with",
"import NO_VALUE, CachedValue from .proxy import ProxyBackend from ..util import",
"region = CacheRegion() region = region.configure(region_invalidator=CustomInvalidationStrategy()) Invalidation strategies that wish",
"a long-running queue, or a task manager system like Celery.",
"fn) else: key_generator = function_key_generator( namespace, fn, to_str=to_str) @wraps(fn) def",
"function_key_generator = my_key_generator ).configure( \"dogpile.cache.dbm\", expiration_time=300, arguments={ \"filename\":\"file.dbm\" } )",
"values = region.get_multi([\"one\", \"two\", \"three\"]) To convert values to a",
"strategies that wish to have access to the :class:`.CacheRegion` itself",
"new value is needed:: result = generate_something(5, 6) The function",
"def my_key_generator(namespace, fn, **kw): fname = fn.__name__ def generate_key(*arg): return",
"or by the key_mangler function, if present. :param expiration_time: Optional",
"{ \"cache.local.backend\":\"dogpile.cache.dbm\", \"cache.local.arguments.filename\":\"/path/to/dbmfile.dbm\", \"cache.memcached.backend\":\"dogpile.cache.pylibmc\", \"cache.memcached.arguments.url\":\"127.0.0.1, 10.0.0.1\", } local_region.configure_from_config(myconfig, \"cache.local.\") memcached_region.configure_from_config(myconfig,",
"dict. :param keys: Sequence of keys to be retrieved. :param",
"wrap=config_dict.get( \"%swrap\" % prefix, None), ) @memoized_property def backend(self): raise",
"accepts a mapping of keys and values to set in",
"rather than returning the value unconditionally. The method also interprets",
"key.\"\"\" if self.key_mangler: key = self.key_mangler(key) self.backend.set(key, self._value(value)) def set_multi(self,",
"also uses keyword arguments :param function_multi_key_generator: Optional. Similar to ``function_key_generator``",
"key_generator = function_multi_key_generator( namespace, fn, to_str=to_str) @wraps(fn) def decorate(*arg, **kw):",
"values using the same values it returns to the calling",
"with backend: %s. \" \"Specify replace_existing_backend=True to replace.\" % self.backend)",
"signature, one which takes a simple list of keys as",
"it's typical for a key to be a string, it",
"from being returned. The method will attempt to acquire the",
"for gen_key, key in zip(gen_keys, keys)) ) def get(*arg): keys",
"key if self.key_mangler: key = self.key_mangler(key) def get_value(): value =",
"as the first argument, and the arguments which would normally",
"populate a new value into the cache with the new",
"calling the decorated function will also be a dictionary. If",
"regeneration; dogpile logic won't be used. If False, the creation",
"be used to recreate the value and persist the newly",
"decorate(*arg, **kw): cache_keys = arg keys = key_generator(*arg, **kw) key_lookup",
"cache the return value of the function using a key",
"key of ``myapp.tools:one|foo|3 4`` - the name ``self`` is skipped.",
"\"k3\": \"value3\"}) ...an ``invalidate()`` method, which has the effect of",
"and arguments, when using the :meth:`.CacheRegion.cache_on_arguments` method. The structure of",
"mechanism as that of :meth:`.CacheRegion.delete_multi`:: generate_something.invalidate(\"k1\", \"k2\", \"k3\") ...a ``refresh()``",
"an exception is raised if a backend is already configured.",
"= region_invalidator return self def wrap(self, proxy): ''' Takes a",
":class:`.CacheRegion` propagated call. The default invalidation system works by setting",
"is invalidated in hard mode. \"\"\" raise NotImplementedError() def is_soft_invalidated(self,",
"typical for a key to be a string, it is",
"than the last call to :meth:`.invalidate`. :param key: Key to",
"isn't used internally but can be accessed via the ``.name``",
"case the key mangling function recommended by the cache backend",
"that method for additional behavioral details. Unlike the :meth:`.CacheRegion.cache_on_arguments` method,",
"return self._is_hard_invalidated is True def is_hard_invalidated(self, timestamp): return self.was_hard_invalidated() and",
"on a non-existent key, safely) \"\"\" if self.key_mangler: key =",
"if self.key_mangler: mangled_keys = [self.key_mangler(k) for k in sorted_unique_keys] else:",
"time required \" \"for soft invalidation\") if expiration_time == -1:",
"function itself and its arguments. The decorator internally makes use",
"in ( _unexpired_value_fn(value) for value in backend_values ) ] def",
"return+regen will be invoked. .. versionadded:: 0.5.1 \"\"\" self.region_invalidator.invalidate(hard) def",
"x in arg] ) return generate_key Where the decorator might",
"will be passed the mutex and is responsible releasing that",
"if present, regardless of configured expiration times or whether or",
"be generated is passed to ``creator()``, and ``creator()`` should return",
"if the function were to produce the value ``3`` as",
"functions to later points in the future by way of,",
"However, subsequent requests for cached-but-expired values will still return promptly.",
"before reaching the cache. .. versionadded:: 0.5.0 :param function_multi_key_generator: a",
"and values to set in the cache:: generate_something.set({\"k1\": \"value1\", \"k2\":",
".. seealso:: :meth:`.CacheRegion.cache_on_arguments` :meth:`.CacheRegion.get_or_create_multi` \"\"\" expiration_time_is_callable = compat.callable(expiration_time) if function_multi_key_generator",
"so that new versions of dogpile.cache can detect cached values",
"receive the value returned by the \"creator\", and will then",
"version. \"\"\" class RegionInvalidationStrategy(object): \"\"\"Region invalidation strategy interface Implement this",
"for a value. Any retrieved value whose creation time is",
"if self.key_mangler: mapping = dict(( self.key_mangler(k), self._value(v)) for k, v",
"keys will not be cached. :param to_str: callable, will be",
"at :func:`.sha1_mangle_key` which coerces keys into a SHA1 hash, so",
"creation time is older than the current invalidation time, the",
"is set to ``None``. .. versionadded:: 0.4.2 added the async_creation_runner",
":param replace_existing_backend: if True, the existing cache backend will be",
"in the cache. Whether or not the function is used",
"as :meth:`.Region.get_multi` and :meth:`.Region.set_multi` to get and set values from",
"**kw): key = key_generator(*arg, **kw) self.delete(key) def set_(value, *arg, **kw):",
"invalidated. \"\"\" raise NotImplementedError() def is_hard_invalidated(self, timestamp): \"\"\"Check timestamp to",
"key_generator(*arg) return self.get_multi(keys) def refresh(*arg): keys = key_generator(*arg) values =",
"Boolean. True if region was invalidated in hard mode. \"\"\"",
"and self.region_invalidator.was_soft_invalidated()): raise exception.DogpileCacheException( \"Non-None expiration time required \" \"for",
"[ somedatabase.query(key) for key in keys ] The decorated function",
"\\**kw:: def my_key_generator(namespace, fn): def generate_key(*arg, **kw): return \":\".join( [kw[k]",
".. seealso:: :meth:`.CacheRegion.cache_multi_on_arguments` :meth:`.CacheRegion.get_or_create` \"\"\" expiration_time_is_callable = compat.callable(expiration_time) if function_key_generator",
"values = generate_something.get(\"k1\", \"k2\", \"k3\") .. versionadded:: 0.5.3 Added ``get()``",
"keys, creator, timeout, should_cache_fn) return result def invalidate(*arg): keys =",
"this :class:`.CacheRegion`. The default invalidation system works by setting a",
"decorator will produce a list of cache keys using a",
"return if self.key_mangler: mapping = dict(( self.key_mangler(k), self._value(v)) for k,",
"expiration_time if asdict: def dict_create(*keys): d_values = creator(*keys) return [",
"present in the list are returned as the ``NO_VALUE`` token.",
"+ fname + \"_\".join(str(s) for s in arg) return generate_key",
"later, when config is available myconfig = { \"cache.local.backend\":\"dogpile.cache.dbm\", \"cache.local.arguments.filename\":\"/path/to/dbmfile.dbm\",",
"is older than the last region invalidation time and region",
"get and set values from the backend. If you are",
"or not. If it returns False, the value is still",
"@wraps(fn) def creator(*keys_to_create): return fn(*[key_lookup[k] for k in keys_to_create]) timeout",
"added the async_creation_runner feature. \"\"\" def __init__( self, name=None, function_key_generator=function_key_generator,",
"list of values, and the final result of calling the",
"will be refreshed by whatever asynchronous means the provided async_creation_runner",
"without blocking. If the :meth:`.invalidate` method has been called, and",
"data creation function and arguments, when using the :meth:`.CacheRegion.cache_on_arguments` method.",
"function. This is a convenience method for :meth:`.CacheRegion.set` which will",
"based on keys corresponds to that of :meth:`.Region.get_or_create`, with the",
"0.5.3 Added ``get()`` method to decorated function. The default key",
"raise NotImplementedError() def async_creator(key, mutex): mutexes[key] = mutex if expiration_time",
"time is older than the current invalidation time, the ``NO_VALUE``",
"is a stale value present in the cache. It will",
"instances, each of which will be applied in a chain",
"If the :meth:`.invalidate` method has been called, and the retrieved",
"injected into a :class:`.CacheRegion` at configure time using the :paramref:`.CacheRegion.configure.region_invalidator`",
".. versionadded:: 0.3.0 Support for the :meth:`.CacheRegion.invalidate` method. :param key:",
"the decorator before it becomes an instance method. The function",
"if \"backend\" in self.__dict__ and not replace_existing_backend: raise exception.RegionAlreadyConfigured( \"This",
"be of any form. For example, it can be passed",
"wrap(self, proxy): ''' Takes a ProxyBackend instance or class and",
"is separate from ``None`` to distinguish between a cached value",
"value elif expiration_time is not None and \\ current_time -",
"creation function may or may not be used to recreate",
"value is unconditionally regenerated if the creation time is older",
"None: expiration_time = self.expiration_time if (expiration_time is None and self.region_invalidator.was_soft_invalidated()):",
"if self.key_mangler: key = self.key_mangler(key) self.backend.delete(key) def delete_multi(self, keys): \"\"\"Remove",
"arguments which would normally be passed to the function should",
"appropriate ''' def runner(): try: value = creator() cache.set(somekey, value)",
"True if region was invalidated in soft mode. \"\"\" raise",
"versionadded:: 0.3.0 :param hard: if True, cache values will all",
"into a new argument list, and the decorated function is",
"the cache. Whether or not the function is used depends",
"than the last region invalidation time. \"\"\" raise NotImplementedError() def",
"a prefix. Example:: local_region = make_region() memcached_region = make_region() #",
"key = key_generator(*arg, **kw) value = fn(*arg, **kw) self.set(key, value)",
"has been configured via the :meth:`.CacheRegion.configure` method already. .. versionadded::",
"creator(): return fn(*arg, **kw) timeout = expiration_time() if expiration_time_is_callable \\",
"recognized by the backend or by the key_mangler function, if",
"my_key_generator(namespace, fn): def generate_key(*arg, **kw): return \":\".join( [kw[k] for k",
"be invoked. However, subsequent requests for cached-but-expired values will still",
"= self._value(created_value) if not should_cache_fn or \\ should_cache_fn(created_value): self.backend.set(key, value)",
"an attribute ``invalidate()``, which provides for invalidation of the value.",
"decorated function itself is called, in caching or retrieving. Thus,",
"values else: self.set_multi( dict(zip(keys, values)) ) return values decorate.set =",
"return value is None, it won't be cached. .. versionadded::",
"\"cache.local.\") memcached_region.configure_from_config(myconfig, \"cache.memcached.\") \"\"\" config_dict = coerce_string_conf(config_dict) return self.configure( config_dict[\"%sbackend\"",
"invoke the decorated function and populate a new value into",
"cache using the same mechanism as that of :meth:`.CacheRegion.get_multi` to",
":ref:`changing_backend_behavior` :param replace_existing_backend: if True, the existing cache backend will",
"the function, the module name for the function, the arguments",
"value) return value decorate.set = set_ decorate.invalidate = invalidate decorate.refresh",
"to_str=to_str) @wraps(fn) def decorate(*arg, **kw): cache_keys = arg keys =",
"= proxy.wrap(self.backend) def _mutex(self, key): return self._lock_registry.get(key) class _LockWrapper(object): \"\"\"weakref-capable",
"def my_function(a, b, **kw): return my_data() .. seealso:: :func:`.function_key_generator` -",
"of the value. Pass to ``invalidate()`` the same arguments you'd",
"the invalidation time check. .. versionadded:: 0.3.0 Support for the",
"and \"soft\" invalidation options. With \"hard\" invalidation, :meth:`.CacheRegion.get_or_create` will force",
"are returned as the ``NO_VALUE`` token. ``NO_VALUE`` evaluates to False,",
"decorate.original = fn return decorate return decorator def cache_multi_on_arguments( self,",
"def is_invalidated(self, timestamp): return (self._invalidated is not None and timestamp",
"under Python 2.x in conjunction with Unicode keys. :param async_creation_runner:",
"if function_multi_key_generator is None: function_multi_key_generator = self.function_multi_key_generator def decorator(fn): key_generator",
"time.time() def is_invalidated(self, timestamp): return (self._invalidated is not None and",
"NO_VALUE: return False elif not should_cache_fn: return True else: return",
"instance or class methods. Given the example:: class MyClass(object): @region.cache_on_arguments(namespace=\"foo\")",
"combining the name of the function with the optional namespace",
"generated or need regeneration will be assembled into a new",
".. seealso:: :func:`.function_key_generator` - default key generator :func:`.kwarg_function_key_generator` - optional",
"that will produce a \"cache key\" given a data creation",
"to the function itself to represent a particular value:: generate_something.invalidate(5,",
"self._value(value)) def set_multi(self, mapping): \"\"\"Place new values in the cache",
"is False def is_soft_invalidated(self, timestamp): return self.was_soft_invalidated() and self.is_invalidated(timestamp) class",
"but it's used in :meth:`.CacheRegion.cache_multi_on_arguments`. Generated function should return list",
"4)`` will again produce the same cache key of ``myapp.tools:one|foo|3",
"function should return its result as a list of values,",
"return a new function that generates the key based on",
"the given key. If the value is not present, the",
"function. See that method for additional behavioral details. E.g.:: @someregion.cache_on_arguments()",
"a new value into the cache with the new value,",
"# \"the value is not available\", e.g. # _has_value() will",
"``3`` as the value to be cached. .. versionadded:: 0.4.1",
"**kw) self.delete(key) def set_(value, *arg, **kw): key = key_generator(*arg, **kw)",
"\"creator\", and will then return True or False, indicating if",
"or \\ should_cache_fn(created_value): self.backend.set(key, value) return value.payload, value.metadata[\"ct\"] if expiration_time",
"cache backend will be used. A typical mangler is the",
"version \"\"\" orig_key = key if self.key_mangler: key = self.key_mangler(key)",
"be called normally. The decorator will produce a list of",
"mutex in mutexes.values(): mutex.release() def _value(self, value): \"\"\"Return a :class:`.CachedValue`",
"import threading def async_creation_runner(cache, somekey, creator, mutex): ''' Used by",
"optional expiration time which will overide the expiration time already",
"= dict( (orig_to_mangled[k], self._value(v)) for k, v in zip(keys_to_get, new_values)",
"specific example using async_creation_runner, new values can be created in",
"that of :meth:`.CacheRegion.delete_multi`:: generate_something.invalidate(\"k1\", \"k2\", \"k3\") ...a ``refresh()`` method, which",
"or not the function is used depends on if the",
":meth:`.CacheRegion.get` methods. The method supports both \"hard\" and \"soft\" invalidation",
"(namespace or '') def generate_keys(*args): return [namespace + ':' +",
"on :func:`.make_region` and :class:`.CacheRegion`. If defaults to :func:`.function_key_generator`. :param namespace:",
"wait for. With \"soft\" invalidation, subsequent getters will return the",
"affect the data in the cache in any way, and",
"= threading.Lock() def acquire(self, wait=True): return self.lock.acquire(wait) def release(self): self.lock.release()",
"False, the value is still returned, but isn't cached. E.g.::",
"use with instance or class methods. Given the example:: class",
"value to be cached. .. versionadded:: 0.4.1 Added ``set()`` method",
"def is_hard_invalidated(self, timestamp): \"\"\"Check timestamp to determine if it was",
"a dictionary. :param wrap: Optional. A list of :class:`.ProxyBackend` classes",
"creation time, the given creation function may or may not",
"not exist or is considered to be expired based on",
"data will be pulled from the cache region unless a",
"list of cache keys using a mechanism similar to that",
"import ProxyBackend from ..util import compat import time import datetime",
"integer placed in the :class:`.CachedValue` so that new versions of",
"region invalidation time. \"\"\" raise NotImplementedError() def was_soft_invalidated(self): \"\"\"Indicate the",
"(self._invalidated is not None and timestamp < self._invalidated) def was_hard_invalidated(self):",
"from ``None`` to distinguish between a cached value of ``None``.",
"if the value should actually be cached or not. If",
"else: ct = value.metadata[\"ct\"] if self.region_invalidator.is_soft_invalidated(ct): ct = time.time() -",
"**kw) @wraps(fn) def creator(): return fn(*arg, **kw) timeout = expiration_time()",
"function using a sequence of keys derived from the function",
"is not None value = region.get_or_create(\"some key\", create_value, should_cache_fn=dont_cache_none) Above,",
"name=None, function_key_generator=function_key_generator, function_multi_key_generator=function_multi_key_generator, key_mangler=None, async_creation_runner=None, ): \"\"\"Construct a new :class:`.CacheRegion`.\"\"\"",
"def set_(mapping): keys = list(mapping) gen_keys = key_generator(*keys) self.set_multi(dict( (gen_key,",
"time.time() self._hard_invalidated = None def is_invalidated(self, timestamp): return ((self._soft_invalidated and",
"consider all older timestamps effectively invalidated. \"\"\" raise NotImplementedError() def",
"invalidate(self, hard=True): \"\"\"Invalidate this :class:`.CacheRegion`. The default invalidation system works",
"\"\"\"Invalidate this :class:`.CacheRegion`. The default invalidation system works by setting",
"The method uses the same approach as :meth:`.Region.get_multi` and :meth:`.Region.set_multi`",
"be called on each function argument in order to convert",
"against the cache. When the dogpile lock cannot be acquired,",
"using a mechanism similar to that of :meth:`.CacheRegion.cache_on_arguments`, combining the",
"key_generator(*arg, **kw) self.delete(key) def set_(value, *arg, **kw): key = key_generator(*arg,",
"function. Similar to ``set()`` is ``refresh()``. This attribute will invoke",
"not None. To set no expiration, use the value -1.",
"name for the function, the arguments passed, as well as",
"0.4.2 added the async_creation_runner feature. \"\"\" def __init__( self, name=None,",
"ProxyBackend from ..util import compat import time import datetime from",
"get_value(): value = self.backend.get(key) if (value is NO_VALUE or value.metadata['v']",
"acquired, the method will block if no previous value is",
":meth:`.CacheRegion.configure` to override default region invalidation. Example:: class CustomInvalidationStrategy(RegionInvalidationStrategy): def",
"NO_VALUE) else: result = self.get_or_create_multi( keys, creator, timeout, should_cache_fn) return",
"will produce a list of keys. This function will supersede",
"called, and the retrieved value's timestamp is older than the",
"to the cache backend, before being optionally processed by the",
"value should actually be cached or not. If it returns",
"based on its creation time, the given creation function may",
"timestamp < self._soft_invalidated) or (self._hard_invalidated and timestamp < self._hard_invalidated)) def",
"that method for additional behavioral details. E.g.:: @someregion.cache_on_arguments() def generate_something(x,",
"of arguments. The returned result is a list:: result =",
"note that the decorator itself can't see the parent class",
"to_str=compat.string_type, function_multi_key_generator=None): \"\"\"A function decorator that will cache multiple return",
"= fn.__name__ def generate_key(*arg): return namespace + \"_\" + fname",
"set to ``False``. Another typical mangler is the built-in Python",
"passed a type rather than an instance then # initialize",
"values in-place on the submitted ``mapping`` dict. :param keys: Sequence",
"**kw): key = key_generator(*arg, **kw) value = fn(*arg, **kw) self.set(key,",
"returned, but isn't cached. .. versionadded:: 0.5.0 .. seealso:: :meth:`.CacheRegion.cache_multi_on_arguments`",
"will receive the value returned by the \"creator\", and will",
"return ((self._soft_invalidated and timestamp < self._soft_invalidated) or (self._hard_invalidated and timestamp",
"which all getters will wait for. With \"soft\" invalidation, subsequent",
"this flag, an exception is raised if a backend is",
"single function signature, one which takes a simple list of",
"= region.get_or_create(\"some key\", create_value, should_cache_fn=dont_cache_none) Above, the function returns the",
"the data in the cache in any way, and is",
"def was_soft_invalidated(self): return bool(self._soft_invalidated) def is_soft_invalidated(self, timestamp): return (self._soft_invalidated and",
"whenever the decorated function itself is called, in caching or",
"is returned immediately without blocking. If the :meth:`.invalidate` method has",
"They will be refreshed by whatever asynchronous means the provided",
"been called, and the retrieved value's timestamp is older than",
"of create_value() if the cache is invalid, however if the",
"= CacheRegion() region = region.configure(region_invalidator=CustomInvalidationStrategy()) Invalidation strategies that wish to",
"last generation. :param arguments: Optional. The structure here is passed",
"the computation of expensive creator functions to later points in",
"\"\" class MyOtherClass(object): @region.cache_on_arguments(namespace='MOC') def somemethod(self, x, y): \"\" Above,",
"the decorator itself can't see the parent class on a",
"is not NO_VALUE else value for value in ( _unexpired_value_fn(value)",
"unicode cache keys which may require key mangling before reaching",
"key_generator = function_key_generator( namespace, fn, to_str=to_str) @wraps(fn) def decorate(*arg, **kw):",
"the key_mangler function, so can be of any type recognized",
"wraps the attached backend. ''' # if we were passed",
"Such as:: def my_key_generator(namespace, fn, **kw): fname = fn.__name__ def",
"((self._soft_invalidated and timestamp < self._soft_invalidated) or (self._hard_invalidated and timestamp <",
"the class is being declared. :param expiration_time: if not None,",
"replace_existing_backend=True to replace.\" % self.backend) backend_cls = _backend_loader.load(backend) if _config_argument_dict:",
"initial argument of ``self`` or ``cls``, making the decorator suitable",
"def refresh(*arg, **kw): key = key_generator(*arg, **kw) value = fn(*arg,",
"normally be passed to the function should follow:: generate_something.set(3, 5,",
"invalidation time, the ``NO_VALUE`` token is returned. Passing the flag",
":param should_cache_fn: passed to :meth:`.CacheRegion.get_or_create_multi`. This function is given a",
"called multiple times, or on a non-existent key, safely) \"\"\"",
"resolved by loading the class from the ``dogpile.cache`` entrypoint. :param",
"function_multi_key_generator = self.function_multi_key_generator def decorator(fn): key_generator = function_multi_key_generator( namespace, fn,",
"% prefix], expiration_time=config_dict.get( \"%sexpiration_time\" % prefix, None), _config_argument_dict=config_dict, _config_prefix=\"%sarguments.\" %",
"is missing keys, those keys will not be cached. :param",
"function_multi_key_generator=function_multi_key_generator, key_mangler=None, async_creation_runner=None, ): \"\"\"Construct a new :class:`.CacheRegion`.\"\"\" self.name =",
"(can be called multiple times, or on a non-existent key,",
"time so that a return+regen will be invoked. .. versionadded::",
"accessed via the ``.name`` parameter, helpful for configuring a region",
"already \" \"configured with backend: %s. \" \"Specify replace_existing_backend=True to",
"\"cache key\". This function will supersede the one configured on",
"= compat.callable(expiration_time) if function_key_generator is None: function_key_generator = self.function_key_generator def",
"-1: expiration_time = None mutexes = {} sorted_unique_keys = sorted(set(keys))",
"and timestamp < self._hard_invalidated) def was_soft_invalidated(self): return bool(self._soft_invalidated) def is_soft_invalidated(self,",
"invalidated in soft mode. \"\"\" raise NotImplementedError() def is_invalidated(self, timestamp):",
"\"\"\"Indicate the region was invalidated in hard mode. :return: Boolean.",
"given a value as returned by the creator, and only",
"key with no associated value will always block; async_creator will",
"as an integer or a callable. :param should_cache_fn: passed to",
"by dogpile.core:Lock when appropriate ''' def runner(): try: value =",
"\"namespace\" parameter in order to generate a cache key. Given",
"@someregion.cache_multi_on_arguments() def generate_something(*keys): return [ somedatabase.query(key) for key in keys",
"a 0 here as # \"the value is not available\",",
"the value does not exist or is considered to be",
"threading.Lock() def acquire(self, wait=True): return self.lock.acquire(wait) def release(self): self.lock.release() def",
"return bool(self._hard_invalidated) def is_hard_invalidated(self, timestamp): return (self._hard_invalidated and timestamp <",
"convenience method for :meth:`.CacheRegion.set` which will store a given value",
"- .0001 return value.payload, ct def gen_value(): raise NotImplementedError() def",
"time passes\". .. versionchanged:: 0.5.0 ``expiration_time`` may be passed as",
"a stale value present in the cache. It will be",
"will return values based on the given arguments:: values =",
"method is given a non-None expiration time. .. versionadded:: 0.3.0",
"given sequence of keys using the same mechanism as that",
"regardless of configured expiration times or whether or not :meth:`.invalidate`",
"method supports both \"hard\" and \"soft\" invalidation options. With \"hard\"",
"self.backend.get_multi(mangled_keys))) for orig_key, mangled_key in orig_to_mangled.items(): with Lock( self._mutex(mangled_key), gen_value,",
"10.0.0.1\", } local_region.configure_from_config(myconfig, \"cache.local.\") memcached_region.configure_from_config(myconfig, \"cache.memcached.\") \"\"\" config_dict = coerce_string_conf(config_dict)",
"async_creator will not be invoked. However, subsequent requests for cached-but-expired",
"relative to the function. This is a convenience method for",
"those associated with classes - note that the decorator itself",
"of :meth:`.CacheRegion.cache_on_arguments`, combining the name of the function with the",
"distinguish between a cached value of ``None``. By default, the",
"configured expiration times or whether or not :meth:`.invalidate` was called.",
"replaced on a per-region basis using the ``function_key_generator`` argument present",
"is used depends on if the *dogpile lock* can be",
"in a background thread like so:: import threading def async_creation_runner(cache,",
"cached value is ignored and the ``NO_VALUE`` token is returned.",
"def my_multi_key_generator(namespace, fn, **kw): namespace = fn.__name__ + (namespace or",
"\"\"\"Instantiate a new :class:`.CacheRegion`. Currently, :func:`.make_region` is a passthrough to",
"the value cached for the given key, or the token",
"hard mode. \"\"\" raise NotImplementedError() class DefaultInvalidationStrategy(RegionInvalidationStrategy): def __init__(self): self._is_hard_invalidated",
"system like Celery. For a specific example using async_creation_runner, new",
"self.backend.delete_multi(keys) def cache_on_arguments( self, namespace=None, expiration_time=None, should_cache_fn=None, to_str=compat.string_type, function_key_generator=None): \"\"\"A",
"should_cache_fn=None, to_str=compat.string_type, function_key_generator=None): \"\"\"A function decorator that will cache the",
"is also given an attribute ``invalidate()``, which provides for invalidation",
"Added ``get()`` method to decorated function. The default key generation",
"by the cache backend will be used. A typical mangler",
"to a string. Defaults to ``str()``. If the function accepts",
"list of :class:`.ProxyBackend` classes and/or instances, each of which will",
"NO_VALUE, CachedValue from .proxy import ProxyBackend from ..util import compat",
"in the :class:`.CachedValue` so that new versions of dogpile.cache can",
"expiration time so that a return+regen will be invoked. ..",
"and :class:`.CacheRegion`. If defaults to :func:`.function_key_generator`. :param namespace: optional string",
"dogpile.core understands a 0 here as # \"the value is",
"is a convenience method for :meth:`.CacheRegion.set` which will store a",
"isinstance(expiration_time, datetime.timedelta): self.expiration_time = int( compat.timedelta_total_seconds(expiration_time)) else: raise exception.ValidationError( 'expiration_time",
"Passing the flag ``ignore_expiration=True`` bypasses the invalidation time check. ..",
"versionadded:: 0.5.3 Added ``get()`` method to decorated function. Parameters passed",
"timestamps effectively invalidated. \"\"\" raise NotImplementedError() def is_hard_invalidated(self, timestamp): \"\"\"Check",
"name self.function_key_generator = function_key_generator self.function_multi_key_generator = function_multi_key_generator self.key_mangler = self._user_defined_key_mangler",
"class methods. Given the example:: class MyClass(object): @region.cache_on_arguments(namespace=\"foo\") def one(self,",
"self.get_or_create_multi( keys, dict_create, timeout, wrap_cache_fn) result = dict( (k, v)",
"to :class:`.CacheRegion`. See that class for constructor arguments. \"\"\" return",
"fn(*arg) if asdict: self.set_multi( dict(zip(keys, [values[a] for a in arg]))",
"= generate_something.get(\"k1\", \"k2\", \"k3\") .. versionadded:: 0.5.3 Added ``get()`` method",
"as a ``datetime.timedelta`` value. .. versionadded 0.5.0 ``expiration_time`` may be",
"of the function with the optional namespace and with the",
"raise NotImplementedError() def was_soft_invalidated(self): \"\"\"Indicate the region was invalidated in",
"a ``get()`` method, which will return values based on the",
"the flag ``ignore_expiration=True`` bypasses the expiration time check. .. versionchanged::",
"get return decorate return decorator def make_region(*arg, **kw): \"\"\"Instantiate a",
"value.\"\"\" return CachedValue( value, { \"ct\": time.time(), \"v\": value_version })",
"is invalidated in soft mode. \"\"\" raise NotImplementedError() def is_invalidated(self,",
"if self.key_mangler: keys = list(map(lambda key: self.key_mangler(key), keys)) backend_values =",
"can detect cached values from a previous, backwards-incompatible version. \"\"\"",
"instance of :class:`.CacheRegion`. Once set, the invalidation time is honored",
"\"\"\"Return a sequence of cached values based on a sequence",
"and ``MyOtherClass`` names, as the function is received by the",
"_config_prefix=None, wrap=None, replace_existing_backend=False, region_invalidator=None ): \"\"\"Configure a :class:`.CacheRegion`. The :class:`.CacheRegion`",
"above example is equivalent to calling ``generate_something(5, 6)``, if the",
"the ``dogpile.cache`` entrypoint. :param expiration_time: Optional. The expiration time passed",
"determine if it was invalidated. :return: Boolean. True if ``timestamp``",
"RegionInvalidationStrategy(object): \"\"\"Region invalidation strategy interface Implement this interface and pass",
"be created in a background thread like so:: import threading",
"is present, but its creation time is older than the",
"the given arguments. Such as:: def my_key_generator(namespace, fn, **kw): fname",
"should_cache_fn(v[0]) )) values.update(values_w_created) return [values[orig_to_mangled[k]].payload for k in keys] finally:",
"cache_on_arguments( self, namespace=None, expiration_time=None, should_cache_fn=None, to_str=compat.string_type, function_key_generator=None): \"\"\"A function decorator",
"None def is_invalidated(self, timestamp): return ((self._soft_invalidated and timestamp < self._soft_invalidated)",
"token is returned. Passing the flag ``ignore_expiration=True`` bypasses the invalidation",
"token ``NO_VALUE`` if no such key exists:: value = generate_something.get(5,",
"Defaults to ``str()``. If the function accepts non-ascii unicode arguments",
".. versionadded:: 0.5.0 :param function_multi_key_generator: a function that will produce",
"determine if it was soft invalidated. :return: Boolean. True if",
"older than the invalidation timestamp, the value is unconditionally prevented",
"that custom functionality augmentation can be applied. .. versionadded:: 0.5.0",
"key mangling before reaching the cache. .. versionadded:: 0.5.0 :param",
"name of the function with the optional namespace and with",
"as:: def my_key_generator(namespace, fn, **kw): fname = fn.__name__ def generate_key(*arg):",
"If the value is not present, the method returns the",
"or alternatively the expiration time supplied by the ``expiration_time`` argument,",
"self.async_creation_runner( self, orig_key, creator, mutex) else: async_creator = None with",
"self.key_mangler(key) self.backend.set(key, self._value(value)) def set_multi(self, mapping): \"\"\"Place new values in",
"ct = time.time() - expiration_time - .0001 return value.payload, ct",
"and will then return True or False, indicating if the",
"\"\"\" def __init__( self, name=None, function_key_generator=function_key_generator, function_multi_key_generator=function_multi_key_generator, key_mangler=None, async_creation_runner=None, ):",
"optional namespace and with the string form of each key.",
"CustomInvalidationStrategy(RegionInvalidationStrategy): def __init__(self): self._soft_invalidated = None self._hard_invalidated = None def",
"found at :func:`.sha1_mangle_key` which coerces keys into a SHA1 hash,",
"function should return list of keys. For example:: def my_multi_key_generator(namespace,",
"does not exist or is considered to be expired based",
"that the region or the method is given a non-None",
"Returns values as a list matching the keys given. E.g.::",
"values)) Keys which aren't present in the list are returned",
"corresponds to that of :meth:`.Region.get_or_create`, with the exception that the",
"value): \"\"\"Return a :class:`.CachedValue` given a value.\"\"\" return CachedValue( value,",
"flag, an exception is raised if a backend is already",
"by the ``expiration_time`` argument, is tested against the creation time",
"of :meth:`.CacheRegion.get_multi` to retrieve all current values; the originally passed",
"and is responsible releasing that mutex when finished. This can",
"= key_generator(*arg, **kw) @wraps(fn) def creator(): return fn(*arg, **kw) timeout",
"passthrough to :class:`.CacheRegion`. See that class for constructor arguments. \"\"\"",
"for mutex in mutexes.values(): mutex.release() def _value(self, value): \"\"\"Return a",
"__init__(self): self.lock = threading.Lock() def acquire(self, wait=True): return self.lock.acquire(wait) def",
"callable that, when specified, will be passed to and called",
"for value in backend_values ) ] def get_or_create( self, key,",
"``cls``, making the decorator suitable (with caveats) for use with",
"decorate(*arg, **kw): key = key_generator(*arg, **kw) @wraps(fn) def creator(): return",
"name of the :class:`.CacheBackend` to use, and is resolved by",
"options. With \"hard\" invalidation, :meth:`.CacheRegion.get_or_create` will force an immediate regeneration",
"of any type recognized by the backend or by the",
"a certain date or time passes\". .. versionchanged:: 0.5.0 ``expiration_time``",
"0.5.5 .. seealso:: :meth:`.CacheRegion.cache_multi_on_arguments` :meth:`.CacheRegion.get_or_create` \"\"\" expiration_time_is_callable = compat.callable(expiration_time) if",
".api import NO_VALUE, CachedValue from .proxy import ProxyBackend from ..util",
"we were passed a type rather than an instance then",
"it was hard invalidated. :return: Boolean. True if ``timestamp`` is",
"set_ decorate.invalidate = invalidate decorate.refresh = refresh decorate.get = get",
"is passed to ``creator()``, and ``creator()`` should return the generated",
"decorator internally makes use of the :meth:`.CacheRegion.get_or_create` method to access",
"current timestamp (using ``time.time()``) to consider all older timestamps effectively",
"and populate a new value into the cache with the",
"creator: function which creates a new value. :param expiration_time: optional",
"``myapp.tools:one|foo|3 4`` - the name ``self`` is skipped. The ``namespace``",
"**kw): key = key_generator(*arg, **kw) self.set(key, value) def get(*arg, **kw):",
"newly generated values using the same values it returns to",
"to it. This method is the \"multiple key\" analogue to",
"to_str=to_str) @wraps(fn) def decorate(*arg, **kw): key = key_generator(*arg, **kw) @wraps(fn)",
"method, :meth:`.CacheRegion.cache_multi_on_arguments` works only with a single function signature, one",
"an instance then # initialize it. if type(proxy) == type:",
"lock to generate a new value, or will wait until",
"should_cache_fn) return result def invalidate(*arg): keys = key_generator(*arg) self.delete_multi(keys) def",
"of dogpile.cache can detect cached values from a previous, backwards-incompatible",
"Boolean. True if region was invalidated in soft mode. \"\"\"",
"def was_hard_invalidated(self): \"\"\"Indicate the region was invalidated in hard mode.",
"function after this time period has passed since the last",
"method for additional behavioral details. E.g.:: @someregion.cache_on_arguments() def generate_something(x, y):",
"will use the name of the function, the module name",
"may be optionally passed as a ``datetime.timedelta`` value. The :meth:`.CacheRegion.get_or_create`",
"so can be of any type recognized by the backend",
"4`` - the name ``self`` is skipped. The ``namespace`` parameter",
"normally. The decorator will produce a list of cache keys",
"= value.metadata[\"ct\"] if self.region_invalidator.is_soft_invalidated(ct): ct = time.time() - expiration_time -",
"overide the expiration time already configured on this :class:`.CacheRegion` if",
"the name of the function, the module name for the",
"any subset of the given keys. The list of keys",
"whether or not :meth:`.invalidate` was called. .. versionadded:: 0.3.0 \"\"\"",
"= self._user_defined_key_mangler = key_mangler self.async_creation_runner = async_creation_runner self.region_invalidator = DefaultInvalidationStrategy()",
"Parameters passed to :meth:`.CacheRegion.cache_multi_on_arguments` have the same meaning as those",
"decorate.invalidate = invalidate decorate.refresh = refresh decorate.get = get return",
"= self.expiration_time current_time = time.time() def value_fn(value): if value is",
"get_multi(self, keys, expiration_time=None, ignore_expiration=False): \"\"\"Return multiple values from the cache,",
"decorator(fn): if to_str is compat.string_type: # backwards compatible key_generator =",
"a mechanism similar to that of :meth:`.CacheRegion.cache_on_arguments`, combining the name",
"\"cache.local.arguments.filename\":\"/path/to/dbmfile.dbm\", \"cache.memcached.backend\":\"dogpile.cache.pylibmc\", \"cache.memcached.arguments.url\":\"127.0.0.1, 10.0.0.1\", } local_region.configure_from_config(myconfig, \"cache.local.\") memcached_region.configure_from_config(myconfig, \"cache.memcached.\") \"\"\"",
"return \":\".join( [kw[k] for k in namespace] + [str(x) for",
"should return its result as a list of values, and",
") return generate_key Where the decorator might be used as::",
"this timestamp is considered to be stale. It does not",
"its creation time, the given creation function may or may",
"a ``datetime.timedelta`` value. The :meth:`.CacheRegion.get_or_create` method as well as the",
"\"\"\" if self.key_mangler: keys = list(map(lambda key: self.key_mangler(key), keys)) self.backend.delete_multi(keys)",
"expiration_time == -1: expiration_time = None mutexes = {} sorted_unique_keys",
"local_region = make_region() memcached_region = make_region() # regions are ready",
"self.key_mangler(key), keys)) self.backend.delete_multi(keys) def cache_on_arguments( self, namespace=None, expiration_time=None, should_cache_fn=None, to_str=compat.string_type,",
"key. Given a function ``one`` inside the module ``myapp.tools``:: @region.cache_on_arguments(namespace=\"foo\")",
"``expiration_time`` argument, is tested against the creation time of the",
"return promptly. They will be refreshed by whatever asynchronous means",
"makes use of the :meth:`.CacheRegion.get_or_create_multi` method to access the cache",
"expiration_time = self.expiration_time current_time = time.time() def value_fn(value): if value",
"ct def gen_value(): created_value = creator() value = self._value(created_value) if",
"\"\"\"Return multiple values from the cache, based on the given",
"None and timestamp < self._invalidated) def was_hard_invalidated(self): return self._is_hard_invalidated is",
"self.get_multi(keys) def refresh(*arg): keys = key_generator(*arg) values = fn(*arg) if",
"be cached. .. versionadded:: 0.4.1 Added ``set()`` method to decorated",
"deleting the given sequence of keys using the same mechanism",
"also local to this instance of :class:`.CacheRegion`. Once set, the",
"called normally. The decorator will produce a list of cache",
"that of :meth:`.CacheRegion.cache_on_arguments`, combining the name of the function with",
"def generate_keys(*args): return [namespace + ':' + str(a) for a",
"0.4.3 :param to_str: callable, will be called on each function",
"The decorator internally makes use of the :meth:`.CacheRegion.get_or_create` method to",
"for the given key, or the token ``NO_VALUE`` if no",
"self._mutex(key), gen_value, get_value, expiration_time, async_creator) as value: return value def",
"new values. :param expiration_time: optional expiration time which will overide",
"normally, where data will be pulled from the cache region",
"dictionary of keys->values, and the final result of calling the",
"key in zip(gen_keys, keys)) ) def get(*arg): keys = key_generator(*arg)",
"is unconditionally regenerated if the creation time is older than",
"key generator :func:`.kwarg_function_key_generator` - optional gen that also uses keyword",
"the example:: class MyClass(object): @region.cache_on_arguments(namespace=\"foo\") def one(self, a, b): return",
"k in keys] finally: for mutex in mutexes.values(): mutex.release() def",
"the function. This is a convenience method for :meth:`.CacheRegion.set` which",
"called. .. versionadded:: 0.3.0 \"\"\" if self.key_mangler: key = self.key_mangler(key)",
"if value is NO_VALUE: return False elif not should_cache_fn: return",
"import backends # noqa value_version = 1 \"\"\"An integer placed",
"\"multiple key\" analogue to the :meth:`.CacheRegion.cache_on_arguments` method. Example:: @someregion.cache_multi_on_arguments() def",
"Celery. For a specific example using async_creation_runner, new values can",
"not None value = region.get_or_create(\"some key\", create_value, should_cache_fn=dont_cache_none) Above, the",
"passed keys corresponding to those values which aren't generated or",
"in keys ] The decorated function can be called normally.",
"from the function itself and its arguments. The decorator internally",
"exists:: value = generate_something.get(5, 6) .. versionadded:: 0.5.3 Added ``get()``",
"return self.get_or_create(key, creator, timeout, should_cache_fn) def invalidate(*arg, **kw): key =",
"def get_or_create( self, key, creator, expiration_time=None, should_cache_fn=None): \"\"\"Return a cached",
"and the retrieved value's timestamp is older than the invalidation",
"value.metadata['v'])): # dogpile.core understands a 0 here as # \"the",
"decorating instance or class methods as below:: class MyClass(object): @region.cache_on_arguments(namespace='MC')",
"runner(): try: value = creator() cache.set(somekey, value) finally: mutex.release() thread",
"passed as a ``datetime.timedelta`` value. The :meth:`.CacheRegion.get_or_create` method as well",
"raise exception.RegionAlreadyConfigured( \"This region is already \" \"configured with backend:",
"region.get_multi(keys) dictionary = dict(zip(keys, values)) Keys which aren't present in",
":meth:`.CacheRegion.cache_on_arguments` :meth:`.CacheRegion.get_or_create_multi` \"\"\" expiration_time_is_callable = compat.callable(expiration_time) if function_multi_key_generator is None:",
"no associated value will always block; async_creator will not be",
"'__iter__', False): for wrapper in reversed(wrap): self.wrap(wrapper) if region_invalidator: self.region_invalidator",
"expiration times or whether or not :meth:`.invalidate` was called. ..",
"_backend_loader = PluginLoader(\"dogpile.cache\") register_backend = _backend_loader.register from . import backends",
"return the \"old\" value until the new one is available.",
"versionadded:: 0.5.0 \"\"\" if self.key_mangler: keys = list(map(lambda key: self.key_mangler(key),",
"as the :meth:`.CacheRegion.cache_on_arguments` decorator (though note: **not** the :meth:`.CacheRegion.get` method)",
"_config_argument_dict, _config_prefix ) else: self.backend = backend_cls(arguments or {}) if",
"no previous value is available, until the lock is released",
"the function, the arguments passed, as well as an optional",
"between ``somemethod`` on ``MyClass`` and ``MyOtherClass``. Python class declaration mechanics",
"This function will supersede the one configured on the :class:`.CacheRegion`",
"decorators, but not yet for actual caching # later, when",
".. versionadded:: 0.5.1 \"\"\" self.region_invalidator.invalidate(hard) def configure_from_config(self, config_dict, prefix): \"\"\"Configure",
"``refresh()`` method to decorated function. Lastly, the ``get()`` method returns",
"current values; the originally passed keys corresponding to those values",
"elif not should_cache_fn: return True else: return should_cache_fn(value) result =",
"a ``datetime.timedelta`` value. .. versionadded 0.5.0 ``expiration_time`` may be optionally",
"value.metadata[\"ct\"]): return NO_VALUE else: return value return value_fn def get_multi(self,",
"for example, a background thread, a long-running queue, or a",
"module, as can occur when decorating instance or class methods",
"interface and pass implementation instance to :meth:`.CacheRegion.configure` to override default",
"self.backend = backend_cls.from_config_dict( _config_argument_dict, _config_prefix ) else: self.backend = backend_cls(arguments",
"a \"cache key\". This function will supersede the one configured",
"the parent class on a function as the class is",
"class MyClass(object): @region.cache_on_arguments(namespace='MC') def somemethod(self, x, y): \"\" class MyOtherClass(object):",
"value.payload, value.metadata[\"ct\"] if expiration_time is None: expiration_time = self.expiration_time if",
"return value elif expiration_time is not None and \\ current_time",
"NO_VALUE else: return value return value_fn def get_multi(self, keys, expiration_time=None,",
"\"value1\", \"k2\": \"value2\", \"k3\": \"value3\"}) ...an ``invalidate()`` method, which has",
"get_value(mangled_key), expiration_time, async_creator=lambda mutex: async_creator(orig_key, mutex) ): pass try: if",
".. versionadded:: 0.6.2 \"\"\" if \"backend\" in self.__dict__ and not",
"import NameRegistry from . import exception from ..util import PluginLoader,",
"self._value(created_value) if not should_cache_fn or \\ should_cache_fn(created_value): self.backend.set(key, value) return",
"else: self._soft_invalidated = time.time() self._hard_invalidated = None def is_invalidated(self, timestamp):",
"\"soft\" invalidation requires that the region or the method is",
"value is still returned, but isn't cached. .. versionadded:: 0.5.0",
"mutexes: # sort the keys, the idea is to prevent",
"is_invalidated(self, timestamp): \"\"\"Check timestamp to determine if it was invalidated.",
"if present. :param expiration_time: Optional expiration time value which will",
":meth:`.CacheRegion.get` method) will call upon the value creation function after",
"as a sequence corresponding to the order of the keys.",
"= {} sorted_unique_keys = sorted(set(keys)) if self.key_mangler: mangled_keys = [self.key_mangler(k)",
"can be of any form. For example, it can be",
"time.time() - expiration_time - .0001 return value.payload, ct def gen_value():",
"present, regardless of configured expiration times or whether or not",
"to pluck from \\**kw:: def my_key_generator(namespace, fn): def generate_key(*arg, **kw):",
"name within the same module, as can occur when decorating",
"d_values = creator(*keys) return [ d_values.get(key_lookup[k], NO_VALUE) for k in",
"can occur when decorating instance or class methods as below::",
"namespace] + [str(x) for x in arg] ) return generate_key",
"is the SHA1 mangler found at :func:`.sha1_mangle_key` which coerces keys",
"the end of the day, week or time period\" and",
"configured on this region.\") @property def is_configured(self): \"\"\"Return True if",
"with Unicode keys. :param async_creation_runner: A callable that, when specified,",
":meth:`.CacheRegion.delete_multi`:: generate_something.invalidate(\"k1\", \"k2\", \"k3\") ...a ``refresh()`` method, which will call",
"(gen_key, mapping[key]) for gen_key, key in zip(gen_keys, keys)) ) def",
".. versionadded:: 0.6.2 .. seealso:: :paramref:`.CacheRegion.configure.region_invalidator` \"\"\" def invalidate(self, hard=True):",
"mangled_key in orig_to_mangled.items(): with Lock( self._mutex(mangled_key), gen_value, lambda: get_value(mangled_key), expiration_time,",
"the decorated function is missing keys, those keys will not",
"argument in order to convert to a string. Defaults to",
"else: key_generator = function_key_generator( namespace, fn, to_str=to_str) @wraps(fn) def decorate(*arg,",
"should_cache_fn or \\ should_cache_fn(created_value): self.backend.set(key, value) return value.payload, value.metadata[\"ct\"] if",
"0.5.0 .. seealso:: :ref:`changing_backend_behavior` :param replace_existing_backend: if True, the existing",
"in the future by way of, for example, a background",
":return: Boolean. True if region was invalidated in hard mode.",
"will again produce the same cache key of ``myapp.tools:one|foo|3 4``",
"True def is_hard_invalidated(self, timestamp): return self.was_hard_invalidated() and self.is_invalidated(timestamp) def was_soft_invalidated(self):",
"(expiration_time is None and self.region_invalidator.was_soft_invalidated()): raise exception.DogpileCacheException( \"Non-None expiration time",
"return the new value. .. versionchanged:: 0.3.0 The value is",
"or self.region_invalidator.is_hard_invalidated( value.metadata[\"ct\"])): raise NeedRegenerationException() ct = value.metadata[\"ct\"] if self.region_invalidator.is_soft_invalidated(ct):"
] |
[
"import_module(version) montecarlo.simulatie(100,50) #Deze waarden dienen enkel als test if __name__",
"waarden dienen enkel als test if __name__ == \"__main__\": simulatie()",
"functie voert alle versies uit zodat deze vergeleken kunnen worden",
"simulatie importeren en achtereenvolgens uitvoeren. version = f\"montecarlo_v{i}\" montecarlo =",
"uitvoeren. version = f\"montecarlo_v{i}\" montecarlo = import_module(version) montecarlo.simulatie(100,50) #Deze waarden",
"= f\"montecarlo_v{i}\" montecarlo = import_module(version) montecarlo.simulatie(100,50) #Deze waarden dienen enkel",
"Module projectparallelprogrammeren.codesimulatie ================================================================= Deze module simuleert alles. \"\"\" import projectparallelprogrammeren",
"coding: utf-8 -*- \"\"\" Module projectparallelprogrammeren.codesimulatie ================================================================= Deze module simuleert",
"versies van de simulatie importeren en achtereenvolgens uitvoeren. version =",
"timing. \"\"\" from importlib import import_module for i in range(4):",
"utf-8 -*- \"\"\" Module projectparallelprogrammeren.codesimulatie ================================================================= Deze module simuleert alles.",
"\"\"\" Deze functie voert alle versies uit zodat deze vergeleken",
"projectparallelprogrammeren def simulatie(): \"\"\" Deze functie voert alle versies uit",
"= import_module(version) montecarlo.simulatie(100,50) #Deze waarden dienen enkel als test if",
"montecarlo.simulatie(100,50) #Deze waarden dienen enkel als test if __name__ ==",
"i in range(4): #alle versies van de simulatie importeren en",
"#alle versies van de simulatie importeren en achtereenvolgens uitvoeren. version",
"\"\"\" from importlib import import_module for i in range(4): #alle",
"qua timing. \"\"\" from importlib import import_module for i in",
"alles. \"\"\" import projectparallelprogrammeren def simulatie(): \"\"\" Deze functie voert",
"from importlib import import_module for i in range(4): #alle versies",
"\"\"\" Module projectparallelprogrammeren.codesimulatie ================================================================= Deze module simuleert alles. \"\"\" import",
"deze vergeleken kunnen worden qua timing. \"\"\" from importlib import",
"# -*- coding: utf-8 -*- \"\"\" Module projectparallelprogrammeren.codesimulatie ================================================================= Deze",
"import projectparallelprogrammeren def simulatie(): \"\"\" Deze functie voert alle versies",
"uit zodat deze vergeleken kunnen worden qua timing. \"\"\" from",
"projectparallelprogrammeren.codesimulatie ================================================================= Deze module simuleert alles. \"\"\" import projectparallelprogrammeren def",
"range(4): #alle versies van de simulatie importeren en achtereenvolgens uitvoeren.",
"achtereenvolgens uitvoeren. version = f\"montecarlo_v{i}\" montecarlo = import_module(version) montecarlo.simulatie(100,50) #Deze",
"import_module for i in range(4): #alle versies van de simulatie",
"module simuleert alles. \"\"\" import projectparallelprogrammeren def simulatie(): \"\"\" Deze",
"import import_module for i in range(4): #alle versies van de",
"================================================================= Deze module simuleert alles. \"\"\" import projectparallelprogrammeren def simulatie():",
"simulatie(): \"\"\" Deze functie voert alle versies uit zodat deze",
"worden qua timing. \"\"\" from importlib import import_module for i",
"alle versies uit zodat deze vergeleken kunnen worden qua timing.",
"in range(4): #alle versies van de simulatie importeren en achtereenvolgens",
"en achtereenvolgens uitvoeren. version = f\"montecarlo_v{i}\" montecarlo = import_module(version) montecarlo.simulatie(100,50)",
"kunnen worden qua timing. \"\"\" from importlib import import_module for",
"-*- coding: utf-8 -*- \"\"\" Module projectparallelprogrammeren.codesimulatie ================================================================= Deze module",
"Deze functie voert alle versies uit zodat deze vergeleken kunnen",
"version = f\"montecarlo_v{i}\" montecarlo = import_module(version) montecarlo.simulatie(100,50) #Deze waarden dienen",
"f\"montecarlo_v{i}\" montecarlo = import_module(version) montecarlo.simulatie(100,50) #Deze waarden dienen enkel als",
"montecarlo = import_module(version) montecarlo.simulatie(100,50) #Deze waarden dienen enkel als test",
"#Deze waarden dienen enkel als test if __name__ == \"__main__\":",
"importeren en achtereenvolgens uitvoeren. version = f\"montecarlo_v{i}\" montecarlo = import_module(version)",
"def simulatie(): \"\"\" Deze functie voert alle versies uit zodat",
"voert alle versies uit zodat deze vergeleken kunnen worden qua",
"importlib import import_module for i in range(4): #alle versies van",
"for i in range(4): #alle versies van de simulatie importeren",
"Deze module simuleert alles. \"\"\" import projectparallelprogrammeren def simulatie(): \"\"\"",
"\"\"\" import projectparallelprogrammeren def simulatie(): \"\"\" Deze functie voert alle",
"van de simulatie importeren en achtereenvolgens uitvoeren. version = f\"montecarlo_v{i}\"",
"-*- \"\"\" Module projectparallelprogrammeren.codesimulatie ================================================================= Deze module simuleert alles. \"\"\"",
"vergeleken kunnen worden qua timing. \"\"\" from importlib import import_module",
"de simulatie importeren en achtereenvolgens uitvoeren. version = f\"montecarlo_v{i}\" montecarlo",
"<gh_stars>0 # -*- coding: utf-8 -*- \"\"\" Module projectparallelprogrammeren.codesimulatie =================================================================",
"simuleert alles. \"\"\" import projectparallelprogrammeren def simulatie(): \"\"\" Deze functie",
"dienen enkel als test if __name__ == \"__main__\": simulatie() #eof",
"versies uit zodat deze vergeleken kunnen worden qua timing. \"\"\"",
"zodat deze vergeleken kunnen worden qua timing. \"\"\" from importlib"
] |
[
"self.assertEqual(decrypted.rstrip(b'\\x08'), self.secret_msg) def test_cbc_encrypt(self): data = bytes_to_intlist(self.secret_msg) encrypted = intlist_to_bytes(aes_cbc_encrypt(data,",
"from haruhi_dl.aes import aes_decrypt, aes_encrypt, aes_cbc_decrypt, aes_cbc_encrypt, aes_decrypt_text from haruhi_dl.utils",
"self.assertEqual( encrypted, b\"\\x97\\x92+\\xe5\\x0b\\xc3\\x18\\x91ky9m&\\xb3\\xb5@\\xe6'\\xc2\\x96.\\xc8u\\x88\\xab9-[\\x9e|\\xf1\\xcd\") def test_decrypt_text(self): password = intlist_to_bytes(self.key).decode('utf-8') encrypted =",
"list(range(16)) encrypted = aes_encrypt(bytes_to_intlist(msg), key) decrypted = intlist_to_bytes(aes_decrypt(encrypted, key)) self.assertEqual(decrypted,",
"base64.b64encode( intlist_to_bytes(self.iv[:8]) + b'\\x0b\\xe6\\xa4\\xd9z\\x0e\\xb8\\xb9\\xd0\\xd4i_\\x85\\x1d\\x99\\x98_\\xe5\\x80\\xe7.\\xbf\\xa5\\x83' ).decode('utf-8') decrypted = (aes_decrypt_text(encrypted, password, 32))",
"b'Secret message goes here' def test_encrypt(self): msg = b'message' key",
"+ b'\\x0b\\xe6\\xa4\\xd9z\\x0e\\xb8\\xb9\\xd0\\xd4i_\\x85\\x1d\\x99\\x98_\\xe5\\x80\\xe7.\\xbf\\xa5\\x83' ).decode('utf-8') decrypted = (aes_decrypt_text(encrypted, password, 32)) self.assertEqual(decrypted, self.secret_msg)",
"haruhi_dl.utils import bytes_to_intlist, intlist_to_bytes import base64 # the encrypted data",
"password = intlist_to_bytes(self.key).decode('utf-8') encrypted = base64.b64encode( intlist_to_bytes(self.iv[:8]) + b'\\x17\\x15\\x93\\xab\\x8d\\x80V\\xcdV\\xe0\\t\\xcdo\\xc2\\xa5\\xd8ksM\\r\\xe27N\\xae' ).decode('utf-8')",
"intlist_to_bytes(self.iv[:8]) + b'\\x0b\\xe6\\xa4\\xd9z\\x0e\\xb8\\xb9\\xd0\\xd4i_\\x85\\x1d\\x99\\x98_\\xe5\\x80\\xe7.\\xbf\\xa5\\x83' ).decode('utf-8') decrypted = (aes_decrypt_text(encrypted, password, 32)) self.assertEqual(decrypted,",
"base64 # the encrypted data can be generate with 'devscripts/generate_aes_testdata.py'",
"test_cbc_encrypt(self): data = bytes_to_intlist(self.secret_msg) encrypted = intlist_to_bytes(aes_cbc_encrypt(data, self.key, self.iv)) self.assertEqual(",
"b'\\x0b\\xe6\\xa4\\xd9z\\x0e\\xb8\\xb9\\xd0\\xd4i_\\x85\\x1d\\x99\\x98_\\xe5\\x80\\xe7.\\xbf\\xa5\\x83' ).decode('utf-8') decrypted = (aes_decrypt_text(encrypted, password, 32)) self.assertEqual(decrypted, self.secret_msg) if",
"b'\\x17\\x15\\x93\\xab\\x8d\\x80V\\xcdV\\xe0\\t\\xcdo\\xc2\\xa5\\xd8ksM\\r\\xe27N\\xae' ).decode('utf-8') decrypted = (aes_decrypt_text(encrypted, password, 16)) self.assertEqual(decrypted, self.secret_msg) password",
"direct execution import os import sys import unittest sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))",
"key) decrypted = intlist_to_bytes(aes_decrypt(encrypted, key)) self.assertEqual(decrypted, msg) def test_cbc_decrypt(self): data",
"goes here' def test_encrypt(self): msg = b'message' key = list(range(16))",
"decrypted = intlist_to_bytes(aes_cbc_decrypt(data, self.key, self.iv)) self.assertEqual(decrypted.rstrip(b'\\x08'), self.secret_msg) def test_cbc_encrypt(self): data",
"unittest sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) from haruhi_dl.aes import aes_decrypt, aes_encrypt, aes_cbc_decrypt, aes_cbc_encrypt,",
"(aes_decrypt_text(encrypted, password, 32)) self.assertEqual(decrypted, self.secret_msg) if __name__ == '__main__': unittest.main()",
"decrypted = intlist_to_bytes(aes_decrypt(encrypted, key)) self.assertEqual(decrypted, msg) def test_cbc_decrypt(self): data =",
"encrypted = base64.b64encode( intlist_to_bytes(self.iv[:8]) + b'\\x17\\x15\\x93\\xab\\x8d\\x80V\\xcdV\\xe0\\t\\xcdo\\xc2\\xa5\\xd8ksM\\r\\xe27N\\xae' ).decode('utf-8') decrypted = (aes_decrypt_text(encrypted,",
"from __future__ import unicode_literals # Allow direct execution import os",
"encrypted = base64.b64encode( intlist_to_bytes(self.iv[:8]) + b'\\x0b\\xe6\\xa4\\xd9z\\x0e\\xb8\\xb9\\xd0\\xd4i_\\x85\\x1d\\x99\\x98_\\xe5\\x80\\xe7.\\xbf\\xa5\\x83' ).decode('utf-8') decrypted = (aes_decrypt_text(encrypted,",
"from haruhi_dl.utils import bytes_to_intlist, intlist_to_bytes import base64 # the encrypted",
"import unittest sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) from haruhi_dl.aes import aes_decrypt, aes_encrypt, aes_cbc_decrypt,",
"decrypted = (aes_decrypt_text(encrypted, password, 16)) self.assertEqual(decrypted, self.secret_msg) password = intlist_to_bytes(self.key).decode('utf-8')",
"def test_cbc_encrypt(self): data = bytes_to_intlist(self.secret_msg) encrypted = intlist_to_bytes(aes_cbc_encrypt(data, self.key, self.iv))",
"self.iv = [0x20, 0x15] + 14 * [0] self.secret_msg =",
"test_decrypt_text(self): password = intlist_to_bytes(self.key).decode('utf-8') encrypted = base64.b64encode( intlist_to_bytes(self.iv[:8]) + b'\\x17\\x15\\x93\\xab\\x8d\\x80V\\xcdV\\xe0\\t\\xcdo\\xc2\\xa5\\xd8ksM\\r\\xe27N\\xae'",
"unicode_literals # Allow direct execution import os import sys import",
"self.key = self.iv = [0x20, 0x15] + 14 * [0]",
"= intlist_to_bytes(aes_cbc_decrypt(data, self.key, self.iv)) self.assertEqual(decrypted.rstrip(b'\\x08'), self.secret_msg) def test_cbc_encrypt(self): data =",
"= b'message' key = list(range(16)) encrypted = aes_encrypt(bytes_to_intlist(msg), key) decrypted",
"self.assertEqual(decrypted, self.secret_msg) password = intlist_to_bytes(self.key).decode('utf-8') encrypted = base64.b64encode( intlist_to_bytes(self.iv[:8]) +",
"bytes_to_intlist( b\"\\x97\\x92+\\xe5\\x0b\\xc3\\x18\\x91ky9m&\\xb3\\xb5@\\xe6'\\xc2\\x96.\\xc8u\\x88\\xab9-[\\x9e|\\xf1\\xcd\" ) decrypted = intlist_to_bytes(aes_cbc_decrypt(data, self.key, self.iv)) self.assertEqual(decrypted.rstrip(b'\\x08'), self.secret_msg)",
"encrypted, b\"\\x97\\x92+\\xe5\\x0b\\xc3\\x18\\x91ky9m&\\xb3\\xb5@\\xe6'\\xc2\\x96.\\xc8u\\x88\\xab9-[\\x9e|\\xf1\\xcd\") def test_decrypt_text(self): password = intlist_to_bytes(self.key).decode('utf-8') encrypted = base64.b64encode(",
"os import sys import unittest sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) from haruhi_dl.aes import",
"'devscripts/generate_aes_testdata.py' class TestAES(unittest.TestCase): def setUp(self): self.key = self.iv = [0x20,",
"data can be generate with 'devscripts/generate_aes_testdata.py' class TestAES(unittest.TestCase): def setUp(self):",
"= intlist_to_bytes(aes_decrypt(encrypted, key)) self.assertEqual(decrypted, msg) def test_cbc_decrypt(self): data = bytes_to_intlist(",
"encrypted = intlist_to_bytes(aes_cbc_encrypt(data, self.key, self.iv)) self.assertEqual( encrypted, b\"\\x97\\x92+\\xe5\\x0b\\xc3\\x18\\x91ky9m&\\xb3\\xb5@\\xe6'\\xc2\\x96.\\xc8u\\x88\\xab9-[\\x9e|\\xf1\\xcd\") def test_decrypt_text(self):",
"sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) from haruhi_dl.aes import aes_decrypt, aes_encrypt, aes_cbc_decrypt, aes_cbc_encrypt, aes_decrypt_text",
"= base64.b64encode( intlist_to_bytes(self.iv[:8]) + b'\\x17\\x15\\x93\\xab\\x8d\\x80V\\xcdV\\xe0\\t\\xcdo\\xc2\\xa5\\xd8ksM\\r\\xe27N\\xae' ).decode('utf-8') decrypted = (aes_decrypt_text(encrypted, password,",
"import aes_decrypt, aes_encrypt, aes_cbc_decrypt, aes_cbc_encrypt, aes_decrypt_text from haruhi_dl.utils import bytes_to_intlist,",
"= intlist_to_bytes(self.key).decode('utf-8') encrypted = base64.b64encode( intlist_to_bytes(self.iv[:8]) + b'\\x0b\\xe6\\xa4\\xd9z\\x0e\\xb8\\xb9\\xd0\\xd4i_\\x85\\x1d\\x99\\x98_\\xe5\\x80\\xe7.\\xbf\\xa5\\x83' ).decode('utf-8') decrypted",
"data = bytes_to_intlist( b\"\\x97\\x92+\\xe5\\x0b\\xc3\\x18\\x91ky9m&\\xb3\\xb5@\\xe6'\\xc2\\x96.\\xc8u\\x88\\xab9-[\\x9e|\\xf1\\xcd\" ) decrypted = intlist_to_bytes(aes_cbc_decrypt(data, self.key, self.iv))",
"self.key, self.iv)) self.assertEqual( encrypted, b\"\\x97\\x92+\\xe5\\x0b\\xc3\\x18\\x91ky9m&\\xb3\\xb5@\\xe6'\\xc2\\x96.\\xc8u\\x88\\xab9-[\\x9e|\\xf1\\xcd\") def test_decrypt_text(self): password = intlist_to_bytes(self.key).decode('utf-8')",
"__future__ import unicode_literals # Allow direct execution import os import",
"message goes here' def test_encrypt(self): msg = b'message' key =",
"intlist_to_bytes import base64 # the encrypted data can be generate",
").decode('utf-8') decrypted = (aes_decrypt_text(encrypted, password, 16)) self.assertEqual(decrypted, self.secret_msg) password =",
"14 * [0] self.secret_msg = b'Secret message goes here' def",
"the encrypted data can be generate with 'devscripts/generate_aes_testdata.py' class TestAES(unittest.TestCase):",
"data = bytes_to_intlist(self.secret_msg) encrypted = intlist_to_bytes(aes_cbc_encrypt(data, self.key, self.iv)) self.assertEqual( encrypted,",
"bytes_to_intlist(self.secret_msg) encrypted = intlist_to_bytes(aes_cbc_encrypt(data, self.key, self.iv)) self.assertEqual( encrypted, b\"\\x97\\x92+\\xe5\\x0b\\xc3\\x18\\x91ky9m&\\xb3\\xb5@\\xe6'\\xc2\\x96.\\xc8u\\x88\\xab9-[\\x9e|\\xf1\\xcd\") def",
"= [0x20, 0x15] + 14 * [0] self.secret_msg = b'Secret",
"encrypted data can be generate with 'devscripts/generate_aes_testdata.py' class TestAES(unittest.TestCase): def",
"[0x20, 0x15] + 14 * [0] self.secret_msg = b'Secret message",
"(aes_decrypt_text(encrypted, password, 16)) self.assertEqual(decrypted, self.secret_msg) password = intlist_to_bytes(self.key).decode('utf-8') encrypted =",
").decode('utf-8') decrypted = (aes_decrypt_text(encrypted, password, 32)) self.assertEqual(decrypted, self.secret_msg) if __name__",
"b'message' key = list(range(16)) encrypted = aes_encrypt(bytes_to_intlist(msg), key) decrypted =",
"msg) def test_cbc_decrypt(self): data = bytes_to_intlist( b\"\\x97\\x92+\\xe5\\x0b\\xc3\\x18\\x91ky9m&\\xb3\\xb5@\\xe6'\\xc2\\x96.\\xc8u\\x88\\xab9-[\\x9e|\\xf1\\xcd\" ) decrypted =",
"haruhi_dl.aes import aes_decrypt, aes_encrypt, aes_cbc_decrypt, aes_cbc_encrypt, aes_decrypt_text from haruhi_dl.utils import",
"msg = b'message' key = list(range(16)) encrypted = aes_encrypt(bytes_to_intlist(msg), key)",
"self.secret_msg) def test_cbc_encrypt(self): data = bytes_to_intlist(self.secret_msg) encrypted = intlist_to_bytes(aes_cbc_encrypt(data, self.key,",
"= base64.b64encode( intlist_to_bytes(self.iv[:8]) + b'\\x0b\\xe6\\xa4\\xd9z\\x0e\\xb8\\xb9\\xd0\\xd4i_\\x85\\x1d\\x99\\x98_\\xe5\\x80\\xe7.\\xbf\\xa5\\x83' ).decode('utf-8') decrypted = (aes_decrypt_text(encrypted, password,",
"intlist_to_bytes(aes_cbc_encrypt(data, self.key, self.iv)) self.assertEqual( encrypted, b\"\\x97\\x92+\\xe5\\x0b\\xc3\\x18\\x91ky9m&\\xb3\\xb5@\\xe6'\\xc2\\x96.\\xc8u\\x88\\xab9-[\\x9e|\\xf1\\xcd\") def test_decrypt_text(self): password =",
"key)) self.assertEqual(decrypted, msg) def test_cbc_decrypt(self): data = bytes_to_intlist( b\"\\x97\\x92+\\xe5\\x0b\\xc3\\x18\\x91ky9m&\\xb3\\xb5@\\xe6'\\xc2\\x96.\\xc8u\\x88\\xab9-[\\x9e|\\xf1\\xcd\" )",
"self.iv)) self.assertEqual( encrypted, b\"\\x97\\x92+\\xe5\\x0b\\xc3\\x18\\x91ky9m&\\xb3\\xb5@\\xe6'\\xc2\\x96.\\xc8u\\x88\\xab9-[\\x9e|\\xf1\\xcd\") def test_decrypt_text(self): password = intlist_to_bytes(self.key).decode('utf-8') encrypted",
"<gh_stars>10-100 #!/usr/bin/env python from __future__ import unicode_literals # Allow direct",
"b\"\\x97\\x92+\\xe5\\x0b\\xc3\\x18\\x91ky9m&\\xb3\\xb5@\\xe6'\\xc2\\x96.\\xc8u\\x88\\xab9-[\\x9e|\\xf1\\xcd\") def test_decrypt_text(self): password = intlist_to_bytes(self.key).decode('utf-8') encrypted = base64.b64encode( intlist_to_bytes(self.iv[:8])",
"self.iv)) self.assertEqual(decrypted.rstrip(b'\\x08'), self.secret_msg) def test_cbc_encrypt(self): data = bytes_to_intlist(self.secret_msg) encrypted =",
"self.secret_msg = b'Secret message goes here' def test_encrypt(self): msg =",
"encrypted = aes_encrypt(bytes_to_intlist(msg), key) decrypted = intlist_to_bytes(aes_decrypt(encrypted, key)) self.assertEqual(decrypted, msg)",
"[0] self.secret_msg = b'Secret message goes here' def test_encrypt(self): msg",
"* [0] self.secret_msg = b'Secret message goes here' def test_encrypt(self):",
"aes_decrypt, aes_encrypt, aes_cbc_decrypt, aes_cbc_encrypt, aes_decrypt_text from haruhi_dl.utils import bytes_to_intlist, intlist_to_bytes",
"= bytes_to_intlist( b\"\\x97\\x92+\\xe5\\x0b\\xc3\\x18\\x91ky9m&\\xb3\\xb5@\\xe6'\\xc2\\x96.\\xc8u\\x88\\xab9-[\\x9e|\\xf1\\xcd\" ) decrypted = intlist_to_bytes(aes_cbc_decrypt(data, self.key, self.iv)) self.assertEqual(decrypted.rstrip(b'\\x08'),",
"import sys import unittest sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) from haruhi_dl.aes import aes_decrypt,",
"sys import unittest sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) from haruhi_dl.aes import aes_decrypt, aes_encrypt,",
"aes_cbc_encrypt, aes_decrypt_text from haruhi_dl.utils import bytes_to_intlist, intlist_to_bytes import base64 #",
"TestAES(unittest.TestCase): def setUp(self): self.key = self.iv = [0x20, 0x15] +",
"can be generate with 'devscripts/generate_aes_testdata.py' class TestAES(unittest.TestCase): def setUp(self): self.key",
"test_cbc_decrypt(self): data = bytes_to_intlist( b\"\\x97\\x92+\\xe5\\x0b\\xc3\\x18\\x91ky9m&\\xb3\\xb5@\\xe6'\\xc2\\x96.\\xc8u\\x88\\xab9-[\\x9e|\\xf1\\xcd\" ) decrypted = intlist_to_bytes(aes_cbc_decrypt(data, self.key,",
"= intlist_to_bytes(aes_cbc_encrypt(data, self.key, self.iv)) self.assertEqual( encrypted, b\"\\x97\\x92+\\xe5\\x0b\\xc3\\x18\\x91ky9m&\\xb3\\xb5@\\xe6'\\xc2\\x96.\\xc8u\\x88\\xab9-[\\x9e|\\xf1\\xcd\") def test_decrypt_text(self): password",
"aes_cbc_decrypt, aes_cbc_encrypt, aes_decrypt_text from haruhi_dl.utils import bytes_to_intlist, intlist_to_bytes import base64",
"import unicode_literals # Allow direct execution import os import sys",
"intlist_to_bytes(aes_decrypt(encrypted, key)) self.assertEqual(decrypted, msg) def test_cbc_decrypt(self): data = bytes_to_intlist( b\"\\x97\\x92+\\xe5\\x0b\\xc3\\x18\\x91ky9m&\\xb3\\xb5@\\xe6'\\xc2\\x96.\\xc8u\\x88\\xab9-[\\x9e|\\xf1\\xcd\"",
"intlist_to_bytes(self.key).decode('utf-8') encrypted = base64.b64encode( intlist_to_bytes(self.iv[:8]) + b'\\x0b\\xe6\\xa4\\xd9z\\x0e\\xb8\\xb9\\xd0\\xd4i_\\x85\\x1d\\x99\\x98_\\xe5\\x80\\xe7.\\xbf\\xa5\\x83' ).decode('utf-8') decrypted =",
"os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) from haruhi_dl.aes import aes_decrypt, aes_encrypt, aes_cbc_decrypt, aes_cbc_encrypt, aes_decrypt_text from",
"= aes_encrypt(bytes_to_intlist(msg), key) decrypted = intlist_to_bytes(aes_decrypt(encrypted, key)) self.assertEqual(decrypted, msg) def",
"def test_cbc_decrypt(self): data = bytes_to_intlist( b\"\\x97\\x92+\\xe5\\x0b\\xc3\\x18\\x91ky9m&\\xb3\\xb5@\\xe6'\\xc2\\x96.\\xc8u\\x88\\xab9-[\\x9e|\\xf1\\xcd\" ) decrypted = intlist_to_bytes(aes_cbc_decrypt(data,",
"bytes_to_intlist, intlist_to_bytes import base64 # the encrypted data can be",
"python from __future__ import unicode_literals # Allow direct execution import",
"+ b'\\x17\\x15\\x93\\xab\\x8d\\x80V\\xcdV\\xe0\\t\\xcdo\\xc2\\xa5\\xd8ksM\\r\\xe27N\\xae' ).decode('utf-8') decrypted = (aes_decrypt_text(encrypted, password, 16)) self.assertEqual(decrypted, self.secret_msg)",
"= intlist_to_bytes(self.key).decode('utf-8') encrypted = base64.b64encode( intlist_to_bytes(self.iv[:8]) + b'\\x17\\x15\\x93\\xab\\x8d\\x80V\\xcdV\\xe0\\t\\xcdo\\xc2\\xa5\\xd8ksM\\r\\xe27N\\xae' ).decode('utf-8') decrypted",
"self.key, self.iv)) self.assertEqual(decrypted.rstrip(b'\\x08'), self.secret_msg) def test_cbc_encrypt(self): data = bytes_to_intlist(self.secret_msg) encrypted",
"= self.iv = [0x20, 0x15] + 14 * [0] self.secret_msg",
"Allow direct execution import os import sys import unittest sys.path.insert(0,",
"import bytes_to_intlist, intlist_to_bytes import base64 # the encrypted data can",
"password = intlist_to_bytes(self.key).decode('utf-8') encrypted = base64.b64encode( intlist_to_bytes(self.iv[:8]) + b'\\x0b\\xe6\\xa4\\xd9z\\x0e\\xb8\\xb9\\xd0\\xd4i_\\x85\\x1d\\x99\\x98_\\xe5\\x80\\xe7.\\xbf\\xa5\\x83' ).decode('utf-8')",
"def setUp(self): self.key = self.iv = [0x20, 0x15] + 14",
"here' def test_encrypt(self): msg = b'message' key = list(range(16)) encrypted",
"key = list(range(16)) encrypted = aes_encrypt(bytes_to_intlist(msg), key) decrypted = intlist_to_bytes(aes_decrypt(encrypted,",
"test_encrypt(self): msg = b'message' key = list(range(16)) encrypted = aes_encrypt(bytes_to_intlist(msg),",
"class TestAES(unittest.TestCase): def setUp(self): self.key = self.iv = [0x20, 0x15]",
"password, 16)) self.assertEqual(decrypted, self.secret_msg) password = intlist_to_bytes(self.key).decode('utf-8') encrypted = base64.b64encode(",
"= list(range(16)) encrypted = aes_encrypt(bytes_to_intlist(msg), key) decrypted = intlist_to_bytes(aes_decrypt(encrypted, key))",
"#!/usr/bin/env python from __future__ import unicode_literals # Allow direct execution",
"import base64 # the encrypted data can be generate with",
"intlist_to_bytes(self.key).decode('utf-8') encrypted = base64.b64encode( intlist_to_bytes(self.iv[:8]) + b'\\x17\\x15\\x93\\xab\\x8d\\x80V\\xcdV\\xe0\\t\\xcdo\\xc2\\xa5\\xd8ksM\\r\\xe27N\\xae' ).decode('utf-8') decrypted =",
"be generate with 'devscripts/generate_aes_testdata.py' class TestAES(unittest.TestCase): def setUp(self): self.key =",
"= (aes_decrypt_text(encrypted, password, 16)) self.assertEqual(decrypted, self.secret_msg) password = intlist_to_bytes(self.key).decode('utf-8') encrypted",
"import os import sys import unittest sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) from haruhi_dl.aes",
"b\"\\x97\\x92+\\xe5\\x0b\\xc3\\x18\\x91ky9m&\\xb3\\xb5@\\xe6'\\xc2\\x96.\\xc8u\\x88\\xab9-[\\x9e|\\xf1\\xcd\" ) decrypted = intlist_to_bytes(aes_cbc_decrypt(data, self.key, self.iv)) self.assertEqual(decrypted.rstrip(b'\\x08'), self.secret_msg) def",
"= (aes_decrypt_text(encrypted, password, 32)) self.assertEqual(decrypted, self.secret_msg) if __name__ == '__main__':",
"aes_encrypt(bytes_to_intlist(msg), key) decrypted = intlist_to_bytes(aes_decrypt(encrypted, key)) self.assertEqual(decrypted, msg) def test_cbc_decrypt(self):",
"= b'Secret message goes here' def test_encrypt(self): msg = b'message'",
"base64.b64encode( intlist_to_bytes(self.iv[:8]) + b'\\x17\\x15\\x93\\xab\\x8d\\x80V\\xcdV\\xe0\\t\\xcdo\\xc2\\xa5\\xd8ksM\\r\\xe27N\\xae' ).decode('utf-8') decrypted = (aes_decrypt_text(encrypted, password, 16))",
") decrypted = intlist_to_bytes(aes_cbc_decrypt(data, self.key, self.iv)) self.assertEqual(decrypted.rstrip(b'\\x08'), self.secret_msg) def test_cbc_encrypt(self):",
"decrypted = (aes_decrypt_text(encrypted, password, 32)) self.assertEqual(decrypted, self.secret_msg) if __name__ ==",
"aes_decrypt_text from haruhi_dl.utils import bytes_to_intlist, intlist_to_bytes import base64 # the",
"aes_encrypt, aes_cbc_decrypt, aes_cbc_encrypt, aes_decrypt_text from haruhi_dl.utils import bytes_to_intlist, intlist_to_bytes import",
"def test_decrypt_text(self): password = intlist_to_bytes(self.key).decode('utf-8') encrypted = base64.b64encode( intlist_to_bytes(self.iv[:8]) +",
"intlist_to_bytes(aes_cbc_decrypt(data, self.key, self.iv)) self.assertEqual(decrypted.rstrip(b'\\x08'), self.secret_msg) def test_cbc_encrypt(self): data = bytes_to_intlist(self.secret_msg)",
"# the encrypted data can be generate with 'devscripts/generate_aes_testdata.py' class",
"self.secret_msg) password = intlist_to_bytes(self.key).decode('utf-8') encrypted = base64.b64encode( intlist_to_bytes(self.iv[:8]) + b'\\x0b\\xe6\\xa4\\xd9z\\x0e\\xb8\\xb9\\xd0\\xd4i_\\x85\\x1d\\x99\\x98_\\xe5\\x80\\xe7.\\xbf\\xa5\\x83'",
"+ 14 * [0] self.secret_msg = b'Secret message goes here'",
"execution import os import sys import unittest sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) from",
"16)) self.assertEqual(decrypted, self.secret_msg) password = intlist_to_bytes(self.key).decode('utf-8') encrypted = base64.b64encode( intlist_to_bytes(self.iv[:8])",
"= bytes_to_intlist(self.secret_msg) encrypted = intlist_to_bytes(aes_cbc_encrypt(data, self.key, self.iv)) self.assertEqual( encrypted, b\"\\x97\\x92+\\xe5\\x0b\\xc3\\x18\\x91ky9m&\\xb3\\xb5@\\xe6'\\xc2\\x96.\\xc8u\\x88\\xab9-[\\x9e|\\xf1\\xcd\")",
"intlist_to_bytes(self.iv[:8]) + b'\\x17\\x15\\x93\\xab\\x8d\\x80V\\xcdV\\xe0\\t\\xcdo\\xc2\\xa5\\xd8ksM\\r\\xe27N\\xae' ).decode('utf-8') decrypted = (aes_decrypt_text(encrypted, password, 16)) self.assertEqual(decrypted,",
"setUp(self): self.key = self.iv = [0x20, 0x15] + 14 *",
"# Allow direct execution import os import sys import unittest",
"generate with 'devscripts/generate_aes_testdata.py' class TestAES(unittest.TestCase): def setUp(self): self.key = self.iv",
"with 'devscripts/generate_aes_testdata.py' class TestAES(unittest.TestCase): def setUp(self): self.key = self.iv =",
"def test_encrypt(self): msg = b'message' key = list(range(16)) encrypted =",
"0x15] + 14 * [0] self.secret_msg = b'Secret message goes",
"self.assertEqual(decrypted, msg) def test_cbc_decrypt(self): data = bytes_to_intlist( b\"\\x97\\x92+\\xe5\\x0b\\xc3\\x18\\x91ky9m&\\xb3\\xb5@\\xe6'\\xc2\\x96.\\xc8u\\x88\\xab9-[\\x9e|\\xf1\\xcd\" ) decrypted"
] |
[
"in training_aps])) == 1 @pytest.mark.gpu @pytest.mark.notebooks def test_02_notebook_run(detection_notebooks, tiny_od_mask_data_path): notebook_path",
"def test_02_notebook_run(detection_notebooks, tiny_od_mask_data_path): notebook_path = detection_notebooks[\"02\"] pm.execute_notebook( notebook_path, OUTPUT_NOTEBOOK, parameters=dict(",
"def test_12_notebook_run( detection_notebooks, tiny_od_data_path, tiny_ic_negatives_path ): notebook_path = detection_notebooks[\"12\"] pm.execute_notebook(",
"OUTPUT_NOTEBOOK, parameters=dict( PM_VERSION=pm.__version__, DATA_PATH=tiny_od_mask_data_path, EPOCHS=1, IM_SIZE=100, ), kernel_name=KERNEL_NAME, ) nb_output",
"# This test is based on the test suite implemented",
"jupyter kernel # that runs on the activated conda environment",
"activated conda environment KERNEL_NAME = \"python3\" OUTPUT_NOTEBOOK = \"output.ipynb\" @pytest.mark.notebooks",
"@pytest.mark.notebooks def test_00_notebook_run(detection_notebooks): notebook_path = detection_notebooks[\"00\"] pm.execute_notebook( notebook_path, OUTPUT_NOTEBOOK, parameters=dict(PM_VERSION=pm.__version__),",
"import scrapbook as sb from utils_cv.common.data import unzip_url from utils_cv.detection.data",
"@pytest.mark.gpu @pytest.mark.notebooks def test_03_notebook_run( detection_notebooks, tiny_od_keypoint_data_path, tmp_session ): notebook_path =",
"len(nb_output.scraps[\"detection_bounding_box\"].data) > 0 @pytest.mark.gpu @pytest.mark.notebooks def test_01_notebook_run(detection_notebooks, tiny_od_data_path): notebook_path =",
"== len( nb_output.scraps[\"bboxes\"].data ) @pytest.mark.gpu @pytest.mark.notebooks def test_12_notebook_run( detection_notebooks, tiny_od_data_path,",
"notebook_path = detection_notebooks[\"01\"] pm.execute_notebook( notebook_path, OUTPUT_NOTEBOOK, parameters=dict( PM_VERSION=pm.__version__, DATA_PATH=tiny_od_data_path, EPOCHS=1,",
"suite implemented for Recommenders project # https://github.com/Microsoft/Recommenders/tree/master/tests import papermill as",
"= detection_notebooks[\"01\"] pm.execute_notebook( notebook_path, OUTPUT_NOTEBOOK, parameters=dict( PM_VERSION=pm.__version__, DATA_PATH=tiny_od_data_path, EPOCHS=1, IM_SIZE=100,",
"nb_output.scraps[\"bboxes\"].data ) @pytest.mark.gpu @pytest.mark.notebooks def test_12_notebook_run( detection_notebooks, tiny_od_data_path, tiny_ic_negatives_path ):",
"runs on the activated conda environment KERNEL_NAME = \"python3\" OUTPUT_NOTEBOOK",
"notebook_path, OUTPUT_NOTEBOOK, parameters=dict( PM_VERSION=pm.__version__, DATA_PATH=tiny_od_mask_data_path, EPOCHS=1, IM_SIZE=100, ), kernel_name=KERNEL_NAME, )",
"d in training_aps: assert isinstance(d, dict) assert len(set([len(d) for d",
"the MIT License. # This test is based on the",
") nb_output = sb.read_notebook(OUTPUT_NOTEBOOK) assert len(nb_output.scraps[\"detection_bounding_box\"].data) > 0 @pytest.mark.gpu @pytest.mark.notebooks",
"isinstance(d, dict) assert len(set([len(d) for d in training_aps])) == 1",
"detection_notebooks[\"01\"] pm.execute_notebook( notebook_path, OUTPUT_NOTEBOOK, parameters=dict( PM_VERSION=pm.__version__, DATA_PATH=tiny_od_data_path, EPOCHS=1, IM_SIZE=100, ),",
"project # https://github.com/Microsoft/Recommenders/tree/master/tests import papermill as pm import pytest import",
"detection_notebooks, tiny_od_data_path, tiny_ic_negatives_path ): notebook_path = detection_notebooks[\"12\"] pm.execute_notebook( notebook_path, OUTPUT_NOTEBOOK,",
"assert len(set([len(d) for d in training_aps])) == 1 @pytest.mark.gpu @pytest.mark.notebooks",
"kernel_name=KERNEL_NAME, ) nb_output = sb.read_notebook(OUTPUT_NOTEBOOK) assert len(nb_output.scraps[\"valid_accs\"].data) == 1 assert",
"should be # the name of the current jupyter kernel",
"be # the name of the current jupyter kernel #",
"OUTPUT_NOTEBOOK, parameters=dict(PM_VERSION=pm.__version__), kernel_name=KERNEL_NAME, ) nb_output = sb.read_notebook(OUTPUT_NOTEBOOK) assert len(nb_output.scraps[\"detection_bounding_box\"].data) >",
"PM_VERSION=pm.__version__, DATA_PATH=tiny_od_mask_data_path, EPOCHS=1, IM_SIZE=100, ), kernel_name=KERNEL_NAME, ) nb_output = sb.read_notebook(OUTPUT_NOTEBOOK)",
"OUTPUT_NOTEBOOK, parameters=dict( PM_VERSION=pm.__version__, IM_SIZE=100, EPOCHS=1, DATA_PATH=tiny_od_keypoint_data_path, DATA_PATH2=data_path2, THRESHOLD=0.01, ), kernel_name=KERNEL_NAME,",
"nb_output = sb.read_notebook(OUTPUT_NOTEBOOK) assert len(nb_output.scraps[\"valid_accs\"].data) == 1 assert 5 <=",
"kernel_name=KERNEL_NAME, ) nb_output = sb.read_notebook(OUTPUT_NOTEBOOK) assert len(nb_output.scraps[\"keypoints\"].data) == len( nb_output.scraps[\"bboxes\"].data",
"== 1 @pytest.mark.gpu @pytest.mark.notebooks def test_03_notebook_run( detection_notebooks, tiny_od_keypoint_data_path, tmp_session ):",
"pm.execute_notebook( notebook_path, OUTPUT_NOTEBOOK, parameters=dict( PM_VERSION=pm.__version__, DATA_PATH=tiny_od_mask_data_path, EPOCHS=1, IM_SIZE=100, ), kernel_name=KERNEL_NAME,",
"notebook_path = detection_notebooks[\"02\"] pm.execute_notebook( notebook_path, OUTPUT_NOTEBOOK, parameters=dict( PM_VERSION=pm.__version__, DATA_PATH=tiny_od_mask_data_path, EPOCHS=1,",
"= sb.read_notebook(OUTPUT_NOTEBOOK) assert len(nb_output.scraps[\"training_losses\"].data) > 0 training_aps = nb_output.scraps[\"training_average_precision\"].data assert",
"OUTPUT_NOTEBOOK = \"output.ipynb\" @pytest.mark.notebooks def test_00_notebook_run(detection_notebooks): notebook_path = detection_notebooks[\"00\"] pm.execute_notebook(",
"), kernel_name=KERNEL_NAME, ) nb_output = sb.read_notebook(OUTPUT_NOTEBOOK) assert len(nb_output.scraps[\"training_losses\"].data) > 0",
"0 training_aps = nb_output.scraps[\"training_average_precision\"].data assert len(training_aps) > 0 for d",
"d in training_aps])) == 1 @pytest.mark.gpu @pytest.mark.notebooks def test_02_notebook_run(detection_notebooks, tiny_od_mask_data_path):",
"tiny_od_keypoint_data_path, tmp_session ): notebook_path = detection_notebooks[\"03\"] data_path2 = unzip_url( Urls.fridge_objects_keypoint_top_bottom_tiny_path,",
"THRESHOLD=0.01, ), kernel_name=KERNEL_NAME, ) nb_output = sb.read_notebook(OUTPUT_NOTEBOOK) assert len(nb_output.scraps[\"keypoints\"].data) ==",
"detection_notebooks[\"02\"] pm.execute_notebook( notebook_path, OUTPUT_NOTEBOOK, parameters=dict( PM_VERSION=pm.__version__, DATA_PATH=tiny_od_mask_data_path, EPOCHS=1, IM_SIZE=100, ),",
"notebook_path = detection_notebooks[\"00\"] pm.execute_notebook( notebook_path, OUTPUT_NOTEBOOK, parameters=dict(PM_VERSION=pm.__version__), kernel_name=KERNEL_NAME, ) nb_output",
"assert len(nb_output.scraps[\"training_losses\"].data) > 0 training_aps = nb_output.scraps[\"training_average_precision\"].data assert len(training_aps) >",
"import unzip_url from utils_cv.detection.data import Urls # Unless manually modified,",
"training_aps = nb_output.scraps[\"training_average_precision\"].data assert len(training_aps) > 0 for d in",
"= sb.read_notebook(OUTPUT_NOTEBOOK) assert len(nb_output.scraps[\"keypoints\"].data) == len( nb_output.scraps[\"bboxes\"].data ) @pytest.mark.gpu @pytest.mark.notebooks",
"papermill as pm import pytest import scrapbook as sb from",
"PM_VERSION=pm.__version__, DATA_PATH=tiny_od_data_path, EPOCHS=1, IM_SIZE=100, ), kernel_name=KERNEL_NAME, ) nb_output = sb.read_notebook(OUTPUT_NOTEBOOK)",
"the test suite implemented for Recommenders project # https://github.com/Microsoft/Recommenders/tree/master/tests import",
"= \"python3\" OUTPUT_NOTEBOOK = \"output.ipynb\" @pytest.mark.notebooks def test_00_notebook_run(detection_notebooks): notebook_path =",
"nb_output.scraps[\"training_average_precision\"].data assert len(training_aps) > 0 for d in training_aps: assert",
"of the current jupyter kernel # that runs on the",
"DATA_PATH=tiny_od_mask_data_path, EPOCHS=1, IM_SIZE=100, ), kernel_name=KERNEL_NAME, ) nb_output = sb.read_notebook(OUTPUT_NOTEBOOK) assert",
"assert isinstance(d, dict) assert len(set([len(d) for d in training_aps])) ==",
") nb_output = sb.read_notebook(OUTPUT_NOTEBOOK) assert len(nb_output.scraps[\"training_losses\"].data) > 0 training_aps =",
"= detection_notebooks[\"02\"] pm.execute_notebook( notebook_path, OUTPUT_NOTEBOOK, parameters=dict( PM_VERSION=pm.__version__, DATA_PATH=tiny_od_mask_data_path, EPOCHS=1, IM_SIZE=100,",
"# https://github.com/Microsoft/Recommenders/tree/master/tests import papermill as pm import pytest import scrapbook",
"the name of the current jupyter kernel # that runs",
"= unzip_url( Urls.fridge_objects_keypoint_top_bottom_tiny_path, fpath=tmp_session, dest=tmp_session, exist_ok=True, ) pm.execute_notebook( notebook_path, OUTPUT_NOTEBOOK,",
"# the name of the current jupyter kernel # that",
"implemented for Recommenders project # https://github.com/Microsoft/Recommenders/tree/master/tests import papermill as pm",
"python3 should be # the name of the current jupyter",
"\"python3\" OUTPUT_NOTEBOOK = \"output.ipynb\" @pytest.mark.notebooks def test_00_notebook_run(detection_notebooks): notebook_path = detection_notebooks[\"00\"]",
"test_12_notebook_run( detection_notebooks, tiny_od_data_path, tiny_ic_negatives_path ): notebook_path = detection_notebooks[\"12\"] pm.execute_notebook( notebook_path,",
"KERNEL_NAME = \"python3\" OUTPUT_NOTEBOOK = \"output.ipynb\" @pytest.mark.notebooks def test_00_notebook_run(detection_notebooks): notebook_path",
"that runs on the activated conda environment KERNEL_NAME = \"python3\"",
"under the MIT License. # This test is based on",
"# Copyright (c) Microsoft Corporation. All rights reserved. # Licensed",
"d in training_aps])) == 1 @pytest.mark.gpu @pytest.mark.notebooks def test_03_notebook_run( detection_notebooks,",
"len(training_aps) > 0 for d in training_aps: assert isinstance(d, dict)",
"utils_cv.detection.data import Urls # Unless manually modified, python3 should be",
") nb_output = sb.read_notebook(OUTPUT_NOTEBOOK) assert len(nb_output.scraps[\"keypoints\"].data) == len( nb_output.scraps[\"bboxes\"].data )",
"PM_VERSION=pm.__version__, DATA_PATH=tiny_od_data_path, NEG_DATA_PATH=tiny_ic_negatives_path, EPOCHS=1, IM_SIZE=100, ), kernel_name=KERNEL_NAME, ) nb_output =",
"OUTPUT_NOTEBOOK, parameters=dict( PM_VERSION=pm.__version__, DATA_PATH=tiny_od_data_path, EPOCHS=1, IM_SIZE=100, ), kernel_name=KERNEL_NAME, ) nb_output",
"sb.read_notebook(OUTPUT_NOTEBOOK) assert len(nb_output.scraps[\"training_losses\"].data) > 0 training_aps = nb_output.scraps[\"training_average_precision\"].data assert len(training_aps)",
"0 for d in training_aps: assert isinstance(d, dict) assert len(set([len(d)",
"kernel_name=KERNEL_NAME, ) nb_output = sb.read_notebook(OUTPUT_NOTEBOOK) assert len(nb_output.scraps[\"detection_bounding_box\"].data) > 0 @pytest.mark.gpu",
"Urls.fridge_objects_keypoint_top_bottom_tiny_path, fpath=tmp_session, dest=tmp_session, exist_ok=True, ) pm.execute_notebook( notebook_path, OUTPUT_NOTEBOOK, parameters=dict( PM_VERSION=pm.__version__,",
"= \"output.ipynb\" @pytest.mark.notebooks def test_00_notebook_run(detection_notebooks): notebook_path = detection_notebooks[\"00\"] pm.execute_notebook( notebook_path,",
"notebook_path = detection_notebooks[\"12\"] pm.execute_notebook( notebook_path, OUTPUT_NOTEBOOK, parameters=dict( PM_VERSION=pm.__version__, DATA_PATH=tiny_od_data_path, NEG_DATA_PATH=tiny_ic_negatives_path,",
"pm.execute_notebook( notebook_path, OUTPUT_NOTEBOOK, parameters=dict( PM_VERSION=pm.__version__, DATA_PATH=tiny_od_data_path, NEG_DATA_PATH=tiny_ic_negatives_path, EPOCHS=1, IM_SIZE=100, ),",
"test is based on the test suite implemented for Recommenders",
"assert len(training_aps) > 0 for d in training_aps: assert isinstance(d,",
"the current jupyter kernel # that runs on the activated",
"tmp_session ): notebook_path = detection_notebooks[\"03\"] data_path2 = unzip_url( Urls.fridge_objects_keypoint_top_bottom_tiny_path, fpath=tmp_session,",
"fpath=tmp_session, dest=tmp_session, exist_ok=True, ) pm.execute_notebook( notebook_path, OUTPUT_NOTEBOOK, parameters=dict( PM_VERSION=pm.__version__, IM_SIZE=100,",
"> 0 for d in training_aps: assert isinstance(d, dict) assert",
"OUTPUT_NOTEBOOK, parameters=dict( PM_VERSION=pm.__version__, DATA_PATH=tiny_od_data_path, NEG_DATA_PATH=tiny_ic_negatives_path, EPOCHS=1, IM_SIZE=100, ), kernel_name=KERNEL_NAME, )",
"assert len(nb_output.scraps[\"valid_accs\"].data) == 1 assert 5 <= len(nb_output.scraps[\"hard_im_scores\"].data) <= 10",
"training_aps])) == 1 @pytest.mark.gpu @pytest.mark.notebooks def test_03_notebook_run( detection_notebooks, tiny_od_keypoint_data_path, tmp_session",
"rights reserved. # Licensed under the MIT License. # This",
"EPOCHS=1, DATA_PATH=tiny_od_keypoint_data_path, DATA_PATH2=data_path2, THRESHOLD=0.01, ), kernel_name=KERNEL_NAME, ) nb_output = sb.read_notebook(OUTPUT_NOTEBOOK)",
"Corporation. All rights reserved. # Licensed under the MIT License.",
"# Unless manually modified, python3 should be # the name",
"This test is based on the test suite implemented for",
"= sb.read_notebook(OUTPUT_NOTEBOOK) assert len(nb_output.scraps[\"valid_accs\"].data) == 1 assert 5 <= len(nb_output.scraps[\"hard_im_scores\"].data)",
"1 @pytest.mark.gpu @pytest.mark.notebooks def test_02_notebook_run(detection_notebooks, tiny_od_mask_data_path): notebook_path = detection_notebooks[\"02\"] pm.execute_notebook(",
"sb from utils_cv.common.data import unzip_url from utils_cv.detection.data import Urls #",
"@pytest.mark.notebooks def test_02_notebook_run(detection_notebooks, tiny_od_mask_data_path): notebook_path = detection_notebooks[\"02\"] pm.execute_notebook( notebook_path, OUTPUT_NOTEBOOK,",
"len( nb_output.scraps[\"bboxes\"].data ) @pytest.mark.gpu @pytest.mark.notebooks def test_12_notebook_run( detection_notebooks, tiny_od_data_path, tiny_ic_negatives_path",
"pm.execute_notebook( notebook_path, OUTPUT_NOTEBOOK, parameters=dict( PM_VERSION=pm.__version__, IM_SIZE=100, EPOCHS=1, DATA_PATH=tiny_od_keypoint_data_path, DATA_PATH2=data_path2, THRESHOLD=0.01,",
"MIT License. # This test is based on the test",
"detection_notebooks, tiny_od_keypoint_data_path, tmp_session ): notebook_path = detection_notebooks[\"03\"] data_path2 = unzip_url(",
"sb.read_notebook(OUTPUT_NOTEBOOK) assert len(nb_output.scraps[\"detection_bounding_box\"].data) > 0 @pytest.mark.gpu @pytest.mark.notebooks def test_01_notebook_run(detection_notebooks, tiny_od_data_path):",
"@pytest.mark.notebooks def test_03_notebook_run( detection_notebooks, tiny_od_keypoint_data_path, tmp_session ): notebook_path = detection_notebooks[\"03\"]",
"detection_notebooks[\"12\"] pm.execute_notebook( notebook_path, OUTPUT_NOTEBOOK, parameters=dict( PM_VERSION=pm.__version__, DATA_PATH=tiny_od_data_path, NEG_DATA_PATH=tiny_ic_negatives_path, EPOCHS=1, IM_SIZE=100,",
"DATA_PATH=tiny_od_keypoint_data_path, DATA_PATH2=data_path2, THRESHOLD=0.01, ), kernel_name=KERNEL_NAME, ) nb_output = sb.read_notebook(OUTPUT_NOTEBOOK) assert",
"def test_00_notebook_run(detection_notebooks): notebook_path = detection_notebooks[\"00\"] pm.execute_notebook( notebook_path, OUTPUT_NOTEBOOK, parameters=dict(PM_VERSION=pm.__version__), kernel_name=KERNEL_NAME,",
") pm.execute_notebook( notebook_path, OUTPUT_NOTEBOOK, parameters=dict( PM_VERSION=pm.__version__, IM_SIZE=100, EPOCHS=1, DATA_PATH=tiny_od_keypoint_data_path, DATA_PATH2=data_path2,",
"IM_SIZE=100, ), kernel_name=KERNEL_NAME, ) nb_output = sb.read_notebook(OUTPUT_NOTEBOOK) assert len(nb_output.scraps[\"valid_accs\"].data) ==",
"@pytest.mark.gpu @pytest.mark.notebooks def test_02_notebook_run(detection_notebooks, tiny_od_mask_data_path): notebook_path = detection_notebooks[\"02\"] pm.execute_notebook( notebook_path,",
"), kernel_name=KERNEL_NAME, ) nb_output = sb.read_notebook(OUTPUT_NOTEBOOK) assert len(nb_output.scraps[\"valid_accs\"].data) == 1",
"in training_aps: assert isinstance(d, dict) assert len(set([len(d) for d in",
"pm import pytest import scrapbook as sb from utils_cv.common.data import",
"parameters=dict(PM_VERSION=pm.__version__), kernel_name=KERNEL_NAME, ) nb_output = sb.read_notebook(OUTPUT_NOTEBOOK) assert len(nb_output.scraps[\"detection_bounding_box\"].data) > 0",
"PM_VERSION=pm.__version__, IM_SIZE=100, EPOCHS=1, DATA_PATH=tiny_od_keypoint_data_path, DATA_PATH2=data_path2, THRESHOLD=0.01, ), kernel_name=KERNEL_NAME, ) nb_output",
"@pytest.mark.gpu @pytest.mark.notebooks def test_12_notebook_run( detection_notebooks, tiny_od_data_path, tiny_ic_negatives_path ): notebook_path =",
"is based on the test suite implemented for Recommenders project",
"Licensed under the MIT License. # This test is based",
"len(nb_output.scraps[\"training_losses\"].data) > 0 training_aps = nb_output.scraps[\"training_average_precision\"].data assert len(training_aps) > 0",
"scrapbook as sb from utils_cv.common.data import unzip_url from utils_cv.detection.data import",
"== 1 @pytest.mark.gpu @pytest.mark.notebooks def test_02_notebook_run(detection_notebooks, tiny_od_mask_data_path): notebook_path = detection_notebooks[\"02\"]",
"> 0 @pytest.mark.gpu @pytest.mark.notebooks def test_01_notebook_run(detection_notebooks, tiny_od_data_path): notebook_path = detection_notebooks[\"01\"]",
"notebook_path = detection_notebooks[\"03\"] data_path2 = unzip_url( Urls.fridge_objects_keypoint_top_bottom_tiny_path, fpath=tmp_session, dest=tmp_session, exist_ok=True,",
"): notebook_path = detection_notebooks[\"12\"] pm.execute_notebook( notebook_path, OUTPUT_NOTEBOOK, parameters=dict( PM_VERSION=pm.__version__, DATA_PATH=tiny_od_data_path,",
"# that runs on the activated conda environment KERNEL_NAME =",
"License. # This test is based on the test suite",
"pytest import scrapbook as sb from utils_cv.common.data import unzip_url from",
"EPOCHS=1, IM_SIZE=100, ), kernel_name=KERNEL_NAME, ) nb_output = sb.read_notebook(OUTPUT_NOTEBOOK) assert len(nb_output.scraps[\"valid_accs\"].data)",
"based on the test suite implemented for Recommenders project #",
"IM_SIZE=100, EPOCHS=1, DATA_PATH=tiny_od_keypoint_data_path, DATA_PATH2=data_path2, THRESHOLD=0.01, ), kernel_name=KERNEL_NAME, ) nb_output =",
"training_aps: assert isinstance(d, dict) assert len(set([len(d) for d in training_aps]))",
"parameters=dict( PM_VERSION=pm.__version__, IM_SIZE=100, EPOCHS=1, DATA_PATH=tiny_od_keypoint_data_path, DATA_PATH2=data_path2, THRESHOLD=0.01, ), kernel_name=KERNEL_NAME, )",
"): notebook_path = detection_notebooks[\"03\"] data_path2 = unzip_url( Urls.fridge_objects_keypoint_top_bottom_tiny_path, fpath=tmp_session, dest=tmp_session,",
"detection_notebooks[\"00\"] pm.execute_notebook( notebook_path, OUTPUT_NOTEBOOK, parameters=dict(PM_VERSION=pm.__version__), kernel_name=KERNEL_NAME, ) nb_output = sb.read_notebook(OUTPUT_NOTEBOOK)",
"dict) assert len(set([len(d) for d in training_aps])) == 1 @pytest.mark.gpu",
"for d in training_aps])) == 1 @pytest.mark.gpu @pytest.mark.notebooks def test_03_notebook_run(",
") nb_output = sb.read_notebook(OUTPUT_NOTEBOOK) assert len(nb_output.scraps[\"valid_accs\"].data) == 1 assert 5",
"EPOCHS=1, IM_SIZE=100, ), kernel_name=KERNEL_NAME, ) nb_output = sb.read_notebook(OUTPUT_NOTEBOOK) assert len(nb_output.scraps[\"training_losses\"].data)",
"tiny_od_data_path, tiny_ic_negatives_path ): notebook_path = detection_notebooks[\"12\"] pm.execute_notebook( notebook_path, OUTPUT_NOTEBOOK, parameters=dict(",
"current jupyter kernel # that runs on the activated conda",
"nb_output = sb.read_notebook(OUTPUT_NOTEBOOK) assert len(nb_output.scraps[\"training_losses\"].data) > 0 training_aps = nb_output.scraps[\"training_average_precision\"].data",
"parameters=dict( PM_VERSION=pm.__version__, DATA_PATH=tiny_od_data_path, NEG_DATA_PATH=tiny_ic_negatives_path, EPOCHS=1, IM_SIZE=100, ), kernel_name=KERNEL_NAME, ) nb_output",
"conda environment KERNEL_NAME = \"python3\" OUTPUT_NOTEBOOK = \"output.ipynb\" @pytest.mark.notebooks def",
"def test_03_notebook_run( detection_notebooks, tiny_od_keypoint_data_path, tmp_session ): notebook_path = detection_notebooks[\"03\"] data_path2",
"), kernel_name=KERNEL_NAME, ) nb_output = sb.read_notebook(OUTPUT_NOTEBOOK) assert len(nb_output.scraps[\"keypoints\"].data) == len(",
"on the test suite implemented for Recommenders project # https://github.com/Microsoft/Recommenders/tree/master/tests",
"name of the current jupyter kernel # that runs on",
"test_01_notebook_run(detection_notebooks, tiny_od_data_path): notebook_path = detection_notebooks[\"01\"] pm.execute_notebook( notebook_path, OUTPUT_NOTEBOOK, parameters=dict( PM_VERSION=pm.__version__,",
"= sb.read_notebook(OUTPUT_NOTEBOOK) assert len(nb_output.scraps[\"detection_bounding_box\"].data) > 0 @pytest.mark.gpu @pytest.mark.notebooks def test_01_notebook_run(detection_notebooks,",
"manually modified, python3 should be # the name of the",
"IM_SIZE=100, ), kernel_name=KERNEL_NAME, ) nb_output = sb.read_notebook(OUTPUT_NOTEBOOK) assert len(nb_output.scraps[\"training_losses\"].data) >",
"dest=tmp_session, exist_ok=True, ) pm.execute_notebook( notebook_path, OUTPUT_NOTEBOOK, parameters=dict( PM_VERSION=pm.__version__, IM_SIZE=100, EPOCHS=1,",
"utils_cv.common.data import unzip_url from utils_cv.detection.data import Urls # Unless manually",
"Recommenders project # https://github.com/Microsoft/Recommenders/tree/master/tests import papermill as pm import pytest",
"Unless manually modified, python3 should be # the name of",
"unzip_url( Urls.fridge_objects_keypoint_top_bottom_tiny_path, fpath=tmp_session, dest=tmp_session, exist_ok=True, ) pm.execute_notebook( notebook_path, OUTPUT_NOTEBOOK, parameters=dict(",
"notebook_path, OUTPUT_NOTEBOOK, parameters=dict( PM_VERSION=pm.__version__, DATA_PATH=tiny_od_data_path, EPOCHS=1, IM_SIZE=100, ), kernel_name=KERNEL_NAME, )",
"DATA_PATH=tiny_od_data_path, EPOCHS=1, IM_SIZE=100, ), kernel_name=KERNEL_NAME, ) nb_output = sb.read_notebook(OUTPUT_NOTEBOOK) assert",
"kernel_name=KERNEL_NAME, ) nb_output = sb.read_notebook(OUTPUT_NOTEBOOK) assert len(nb_output.scraps[\"training_losses\"].data) > 0 training_aps",
"tiny_ic_negatives_path ): notebook_path = detection_notebooks[\"12\"] pm.execute_notebook( notebook_path, OUTPUT_NOTEBOOK, parameters=dict( PM_VERSION=pm.__version__,",
"Urls # Unless manually modified, python3 should be # the",
"for d in training_aps])) == 1 @pytest.mark.gpu @pytest.mark.notebooks def test_02_notebook_run(detection_notebooks,",
"(c) Microsoft Corporation. All rights reserved. # Licensed under the",
"kernel # that runs on the activated conda environment KERNEL_NAME",
"assert len(nb_output.scraps[\"keypoints\"].data) == len( nb_output.scraps[\"bboxes\"].data ) @pytest.mark.gpu @pytest.mark.notebooks def test_12_notebook_run(",
"= detection_notebooks[\"12\"] pm.execute_notebook( notebook_path, OUTPUT_NOTEBOOK, parameters=dict( PM_VERSION=pm.__version__, DATA_PATH=tiny_od_data_path, NEG_DATA_PATH=tiny_ic_negatives_path, EPOCHS=1,",
"def test_01_notebook_run(detection_notebooks, tiny_od_data_path): notebook_path = detection_notebooks[\"01\"] pm.execute_notebook( notebook_path, OUTPUT_NOTEBOOK, parameters=dict(",
"= detection_notebooks[\"03\"] data_path2 = unzip_url( Urls.fridge_objects_keypoint_top_bottom_tiny_path, fpath=tmp_session, dest=tmp_session, exist_ok=True, )",
"parameters=dict( PM_VERSION=pm.__version__, DATA_PATH=tiny_od_data_path, EPOCHS=1, IM_SIZE=100, ), kernel_name=KERNEL_NAME, ) nb_output =",
"@pytest.mark.gpu @pytest.mark.notebooks def test_01_notebook_run(detection_notebooks, tiny_od_data_path): notebook_path = detection_notebooks[\"01\"] pm.execute_notebook( notebook_path,",
"DATA_PATH=tiny_od_data_path, NEG_DATA_PATH=tiny_ic_negatives_path, EPOCHS=1, IM_SIZE=100, ), kernel_name=KERNEL_NAME, ) nb_output = sb.read_notebook(OUTPUT_NOTEBOOK)",
"in training_aps])) == 1 @pytest.mark.gpu @pytest.mark.notebooks def test_03_notebook_run( detection_notebooks, tiny_od_keypoint_data_path,",
"training_aps])) == 1 @pytest.mark.gpu @pytest.mark.notebooks def test_02_notebook_run(detection_notebooks, tiny_od_mask_data_path): notebook_path =",
"nb_output = sb.read_notebook(OUTPUT_NOTEBOOK) assert len(nb_output.scraps[\"detection_bounding_box\"].data) > 0 @pytest.mark.gpu @pytest.mark.notebooks def",
"test suite implemented for Recommenders project # https://github.com/Microsoft/Recommenders/tree/master/tests import papermill",
"from utils_cv.common.data import unzip_url from utils_cv.detection.data import Urls # Unless",
"test_03_notebook_run( detection_notebooks, tiny_od_keypoint_data_path, tmp_session ): notebook_path = detection_notebooks[\"03\"] data_path2 =",
"test_02_notebook_run(detection_notebooks, tiny_od_mask_data_path): notebook_path = detection_notebooks[\"02\"] pm.execute_notebook( notebook_path, OUTPUT_NOTEBOOK, parameters=dict( PM_VERSION=pm.__version__,",
"modified, python3 should be # the name of the current",
"@pytest.mark.notebooks def test_12_notebook_run( detection_notebooks, tiny_od_data_path, tiny_ic_negatives_path ): notebook_path = detection_notebooks[\"12\"]",
"Microsoft Corporation. All rights reserved. # Licensed under the MIT",
"import papermill as pm import pytest import scrapbook as sb",
"> 0 training_aps = nb_output.scraps[\"training_average_precision\"].data assert len(training_aps) > 0 for",
"= detection_notebooks[\"00\"] pm.execute_notebook( notebook_path, OUTPUT_NOTEBOOK, parameters=dict(PM_VERSION=pm.__version__), kernel_name=KERNEL_NAME, ) nb_output =",
"on the activated conda environment KERNEL_NAME = \"python3\" OUTPUT_NOTEBOOK =",
") @pytest.mark.gpu @pytest.mark.notebooks def test_12_notebook_run( detection_notebooks, tiny_od_data_path, tiny_ic_negatives_path ): notebook_path",
"assert len(nb_output.scraps[\"detection_bounding_box\"].data) > 0 @pytest.mark.gpu @pytest.mark.notebooks def test_01_notebook_run(detection_notebooks, tiny_od_data_path): notebook_path",
"detection_notebooks[\"03\"] data_path2 = unzip_url( Urls.fridge_objects_keypoint_top_bottom_tiny_path, fpath=tmp_session, dest=tmp_session, exist_ok=True, ) pm.execute_notebook(",
"nb_output = sb.read_notebook(OUTPUT_NOTEBOOK) assert len(nb_output.scraps[\"keypoints\"].data) == len( nb_output.scraps[\"bboxes\"].data ) @pytest.mark.gpu",
"len(set([len(d) for d in training_aps])) == 1 @pytest.mark.gpu @pytest.mark.notebooks def",
"# Licensed under the MIT License. # This test is",
"as sb from utils_cv.common.data import unzip_url from utils_cv.detection.data import Urls",
"notebook_path, OUTPUT_NOTEBOOK, parameters=dict(PM_VERSION=pm.__version__), kernel_name=KERNEL_NAME, ) nb_output = sb.read_notebook(OUTPUT_NOTEBOOK) assert len(nb_output.scraps[\"detection_bounding_box\"].data)",
"1 @pytest.mark.gpu @pytest.mark.notebooks def test_03_notebook_run( detection_notebooks, tiny_od_keypoint_data_path, tmp_session ): notebook_path",
"https://github.com/Microsoft/Recommenders/tree/master/tests import papermill as pm import pytest import scrapbook as",
"environment KERNEL_NAME = \"python3\" OUTPUT_NOTEBOOK = \"output.ipynb\" @pytest.mark.notebooks def test_00_notebook_run(detection_notebooks):",
"from utils_cv.detection.data import Urls # Unless manually modified, python3 should",
"\"output.ipynb\" @pytest.mark.notebooks def test_00_notebook_run(detection_notebooks): notebook_path = detection_notebooks[\"00\"] pm.execute_notebook( notebook_path, OUTPUT_NOTEBOOK,",
"import pytest import scrapbook as sb from utils_cv.common.data import unzip_url",
"len(nb_output.scraps[\"keypoints\"].data) == len( nb_output.scraps[\"bboxes\"].data ) @pytest.mark.gpu @pytest.mark.notebooks def test_12_notebook_run( detection_notebooks,",
"parameters=dict( PM_VERSION=pm.__version__, DATA_PATH=tiny_od_mask_data_path, EPOCHS=1, IM_SIZE=100, ), kernel_name=KERNEL_NAME, ) nb_output =",
"All rights reserved. # Licensed under the MIT License. #",
"DATA_PATH2=data_path2, THRESHOLD=0.01, ), kernel_name=KERNEL_NAME, ) nb_output = sb.read_notebook(OUTPUT_NOTEBOOK) assert len(nb_output.scraps[\"keypoints\"].data)",
"sb.read_notebook(OUTPUT_NOTEBOOK) assert len(nb_output.scraps[\"valid_accs\"].data) == 1 assert 5 <= len(nb_output.scraps[\"hard_im_scores\"].data) <=",
"for Recommenders project # https://github.com/Microsoft/Recommenders/tree/master/tests import papermill as pm import",
"pm.execute_notebook( notebook_path, OUTPUT_NOTEBOOK, parameters=dict(PM_VERSION=pm.__version__), kernel_name=KERNEL_NAME, ) nb_output = sb.read_notebook(OUTPUT_NOTEBOOK) assert",
"for d in training_aps: assert isinstance(d, dict) assert len(set([len(d) for",
"sb.read_notebook(OUTPUT_NOTEBOOK) assert len(nb_output.scraps[\"keypoints\"].data) == len( nb_output.scraps[\"bboxes\"].data ) @pytest.mark.gpu @pytest.mark.notebooks def",
"notebook_path, OUTPUT_NOTEBOOK, parameters=dict( PM_VERSION=pm.__version__, DATA_PATH=tiny_od_data_path, NEG_DATA_PATH=tiny_ic_negatives_path, EPOCHS=1, IM_SIZE=100, ), kernel_name=KERNEL_NAME,",
"reserved. # Licensed under the MIT License. # This test",
"as pm import pytest import scrapbook as sb from utils_cv.common.data",
"= nb_output.scraps[\"training_average_precision\"].data assert len(training_aps) > 0 for d in training_aps:",
"NEG_DATA_PATH=tiny_ic_negatives_path, EPOCHS=1, IM_SIZE=100, ), kernel_name=KERNEL_NAME, ) nb_output = sb.read_notebook(OUTPUT_NOTEBOOK) assert",
"@pytest.mark.notebooks def test_01_notebook_run(detection_notebooks, tiny_od_data_path): notebook_path = detection_notebooks[\"01\"] pm.execute_notebook( notebook_path, OUTPUT_NOTEBOOK,",
"exist_ok=True, ) pm.execute_notebook( notebook_path, OUTPUT_NOTEBOOK, parameters=dict( PM_VERSION=pm.__version__, IM_SIZE=100, EPOCHS=1, DATA_PATH=tiny_od_keypoint_data_path,",
"tiny_od_data_path): notebook_path = detection_notebooks[\"01\"] pm.execute_notebook( notebook_path, OUTPUT_NOTEBOOK, parameters=dict( PM_VERSION=pm.__version__, DATA_PATH=tiny_od_data_path,",
"data_path2 = unzip_url( Urls.fridge_objects_keypoint_top_bottom_tiny_path, fpath=tmp_session, dest=tmp_session, exist_ok=True, ) pm.execute_notebook( notebook_path,",
"notebook_path, OUTPUT_NOTEBOOK, parameters=dict( PM_VERSION=pm.__version__, IM_SIZE=100, EPOCHS=1, DATA_PATH=tiny_od_keypoint_data_path, DATA_PATH2=data_path2, THRESHOLD=0.01, ),",
"0 @pytest.mark.gpu @pytest.mark.notebooks def test_01_notebook_run(detection_notebooks, tiny_od_data_path): notebook_path = detection_notebooks[\"01\"] pm.execute_notebook(",
"unzip_url from utils_cv.detection.data import Urls # Unless manually modified, python3",
"test_00_notebook_run(detection_notebooks): notebook_path = detection_notebooks[\"00\"] pm.execute_notebook( notebook_path, OUTPUT_NOTEBOOK, parameters=dict(PM_VERSION=pm.__version__), kernel_name=KERNEL_NAME, )",
"Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under",
"the activated conda environment KERNEL_NAME = \"python3\" OUTPUT_NOTEBOOK = \"output.ipynb\"",
"pm.execute_notebook( notebook_path, OUTPUT_NOTEBOOK, parameters=dict( PM_VERSION=pm.__version__, DATA_PATH=tiny_od_data_path, EPOCHS=1, IM_SIZE=100, ), kernel_name=KERNEL_NAME,",
"tiny_od_mask_data_path): notebook_path = detection_notebooks[\"02\"] pm.execute_notebook( notebook_path, OUTPUT_NOTEBOOK, parameters=dict( PM_VERSION=pm.__version__, DATA_PATH=tiny_od_mask_data_path,",
"import Urls # Unless manually modified, python3 should be #"
] |
[
"optimizer # lr is set for a batch size of",
"a batch size of 8 optimizer = dict(type='SGD', lr=0.0005, momentum=0.9,",
"dict(grad_clip=dict(max_norm=35, norm_type=2)) # learning policy lr_config = dict( policy='step', warmup='linear',",
"# learning policy lr_config = dict( policy='step', warmup='linear', warmup_iters=500, warmup_ratio=0.001,",
"<gh_stars>0 _base_ = [ '../retinanet_r50_fpn_1x_coco.py', '../../_base_/datasets/hdr_detection_minmax_glob_gamma.py', ] # optimizer #",
"optimizer_config = dict(grad_clip=None) # dict(grad_clip=dict(max_norm=35, norm_type=2)) # learning policy lr_config",
"dict( policy='step', warmup='linear', warmup_iters=500, warmup_ratio=0.001, step=[10]) runner = dict( type='EpochBasedRunner',",
"] # optimizer # lr is set for a batch",
"set for a batch size of 8 optimizer = dict(type='SGD',",
"= dict(type='SGD', lr=0.0005, momentum=0.9, weight_decay=0.0001) optimizer_config = dict(grad_clip=None) # dict(grad_clip=dict(max_norm=35,",
"size of 8 optimizer = dict(type='SGD', lr=0.0005, momentum=0.9, weight_decay=0.0001) optimizer_config",
"dict(type='SGD', lr=0.0005, momentum=0.9, weight_decay=0.0001) optimizer_config = dict(grad_clip=None) # dict(grad_clip=dict(max_norm=35, norm_type=2))",
"lr_config = dict( policy='step', warmup='linear', warmup_iters=500, warmup_ratio=0.001, step=[10]) runner =",
"norm_type=2)) # learning policy lr_config = dict( policy='step', warmup='linear', warmup_iters=500,",
"= [ '../retinanet_r50_fpn_1x_coco.py', '../../_base_/datasets/hdr_detection_minmax_glob_gamma.py', ] # optimizer # lr is",
"# dict(grad_clip=dict(max_norm=35, norm_type=2)) # learning policy lr_config = dict( policy='step',",
"'../../_base_/datasets/hdr_detection_minmax_glob_gamma.py', ] # optimizer # lr is set for a",
"for a batch size of 8 optimizer = dict(type='SGD', lr=0.0005,",
"learning policy lr_config = dict( policy='step', warmup='linear', warmup_iters=500, warmup_ratio=0.001, step=[10])",
"'../retinanet_r50_fpn_1x_coco.py', '../../_base_/datasets/hdr_detection_minmax_glob_gamma.py', ] # optimizer # lr is set for",
"weight_decay=0.0001) optimizer_config = dict(grad_clip=None) # dict(grad_clip=dict(max_norm=35, norm_type=2)) # learning policy",
"optimizer = dict(type='SGD', lr=0.0005, momentum=0.9, weight_decay=0.0001) optimizer_config = dict(grad_clip=None) #",
"momentum=0.9, weight_decay=0.0001) optimizer_config = dict(grad_clip=None) # dict(grad_clip=dict(max_norm=35, norm_type=2)) # learning",
"batch size of 8 optimizer = dict(type='SGD', lr=0.0005, momentum=0.9, weight_decay=0.0001)",
"lr=0.0005, momentum=0.9, weight_decay=0.0001) optimizer_config = dict(grad_clip=None) # dict(grad_clip=dict(max_norm=35, norm_type=2)) #",
"[ '../retinanet_r50_fpn_1x_coco.py', '../../_base_/datasets/hdr_detection_minmax_glob_gamma.py', ] # optimizer # lr is set",
"= dict(grad_clip=None) # dict(grad_clip=dict(max_norm=35, norm_type=2)) # learning policy lr_config =",
"is set for a batch size of 8 optimizer =",
"= dict( policy='step', warmup='linear', warmup_iters=500, warmup_ratio=0.001, step=[10]) runner = dict(",
"_base_ = [ '../retinanet_r50_fpn_1x_coco.py', '../../_base_/datasets/hdr_detection_minmax_glob_gamma.py', ] # optimizer # lr",
"policy lr_config = dict( policy='step', warmup='linear', warmup_iters=500, warmup_ratio=0.001, step=[10]) runner",
"8 optimizer = dict(type='SGD', lr=0.0005, momentum=0.9, weight_decay=0.0001) optimizer_config = dict(grad_clip=None)",
"lr is set for a batch size of 8 optimizer",
"policy='step', warmup='linear', warmup_iters=500, warmup_ratio=0.001, step=[10]) runner = dict( type='EpochBasedRunner', max_epochs=20)",
"# optimizer # lr is set for a batch size",
"of 8 optimizer = dict(type='SGD', lr=0.0005, momentum=0.9, weight_decay=0.0001) optimizer_config =",
"# lr is set for a batch size of 8",
"dict(grad_clip=None) # dict(grad_clip=dict(max_norm=35, norm_type=2)) # learning policy lr_config = dict("
] |
[] |
[
"import numpy as np from os import path from sklearn",
"pandas as pd import numpy as np from os import",
"pytest import pandas as pd import numpy as np from",
"pd import numpy as np from os import path from",
"cognito.check import Check from cognito.table import Table import os import",
"Table import os import pytest import pandas as pd import",
"import Table import os import pytest import pandas as pd",
"as np from os import path from sklearn import preprocessing",
"import pandas as pd import numpy as np from os",
"cognito.table import Table import os import pytest import pandas as",
"import pytest import pandas as pd import numpy as np",
"as pd import numpy as np from os import path",
"import os import pytest import pandas as pd import numpy",
"<reponame>vandana-11/cognito from cognito.check import Check from cognito.table import Table import",
"os import pytest import pandas as pd import numpy as",
"from cognito.check import Check from cognito.table import Table import os",
"import Check from cognito.table import Table import os import pytest",
"numpy as np from os import path from sklearn import",
"Check from cognito.table import Table import os import pytest import",
"from cognito.table import Table import os import pytest import pandas"
] |