code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
arguments = cli_common(__doc__, argv=argv) campaign_path = arguments['CAMPAIGN-DIR'] driver = CampaignDriver(campaign_path, expandcampvars=False) with pushd(campaign_path): render( template=arguments['--template'], ostr=arguments['--output'], campaign=dri...
def main(argv=None)
ben-doc entry point
10.377258
9.54017
1.087744
mod_str = obj.__module__ name_str = obj.__name__ if mod_str == '__main__': return name_str else: return '.'.join([mod_str, name_str])
def class_to_str(obj)
get class string from object Examples -------- >>> class_to_str(list).split('.')[1] 'list'
2.476873
3.044244
0.813625
return pathlib.Path( os.path.dirname(os.path.abspath(inspect.getfile(module))))
def get_module_path(module)
return a directory path to a module
3.550566
3.144691
1.129067
basepath = os.path.dirname(os.path.abspath(inspect.getfile(module))) if isinstance(data, basestring): data = [data] dirpath = os.path.join(basepath, *data) if check_exists: assert os.path.exists(dirpath), '{0} does not exist'.format(dirpath) return pathlib.Path(dirpath)
def get_data_path(data, module, check_exists=True)
return a directory path to data within a module Parameters ---------- data : str or list[str] file name or list of sub-directories and file name (e.g. ['lammps','data.txt'])
2.314403
2.72417
0.849581
try: import psutil import os except ImportError: return _memory_usage_ps() process = psutil.Process(os.getpid()) mem = process.memory_info()[0] / float(2 ** 20) return mem
def memory_usage()
return memory usage of python process in MB from http://fa.bianp.net/blog/2013/different-ways-to-get-memory-consumption-or-lessons-learned-from-memory_profiler/ psutil is quicker >>> isinstance(memory_usage(),float) True
2.893445
2.847261
1.016221
out = subprocess.Popen( ['ps', 'v', '-p', str(os.getpid())], stdout=subprocess.PIPE).communicate()[0].split(b'\n') vsz_index = out[0].split().index(b'RSS') mem = float(out[1].split()[vsz_index]) / 1024 return mem
def _memory_usage_ps()
return memory usage of python process in MB >>> isinstance(_memory_usage_ps(),float) True
2.28202
2.803617
0.813956
from IPython.core.magic import Magics, line_magic, magics_class from memory_profiler import memory_usage as _mu try: ip = get_ipython() except NameError as err: raise Exception('not in ipython/jupyter kernel:\n {}'.format(err)) @magics_class class MemMagics(Magics): ...
def load_memit()
load memory usage ipython magic, require memory_profiler package to be installed to get usage: %memit? Author: Vlad Niculae <vlad@vene.ro> Makes use of memory_profiler from Fabian Pedregosa available at https://github.com/fabianp/memory_profiler
3.290951
3.235895
1.017014
d = dict() for n, l in locs.items(): try: if l[1] == 'text': d[n] = node.find(l[0]).text elif l[1] == 'child': child = node.find(l[0]).getchildren() if len(child) > 1: raise AmbiguousElementException( ...
def parse_tree_from_dict(node, locs)
Processes key locations. Parameters ---------- node: xml.etree.ElementTree.ElementTree.element Current node. locs: dict A dictionary mapping key to a tuple. The tuple can either be 2 or 3 elements long. The first element maps to the location in the current node. The seco...
2.546762
2.20776
1.15355
if isinstance(xml, str): if '<' in xml: return ElementTree.fromstring(xml) else: with open(xml) as fh: xml_to_root(fh) tree = ElementTree.parse(xml) return tree.getroot()
def xml_to_root(xml: Union[str, IO]) -> ElementTree.Element
Parse XML into an ElemeTree object. Parameters ---------- xml : str or file-like object A filename, file object or string version of xml can be passed. Returns ------- Elementree.Element
2.58733
3.444735
0.751097
self.layers.append(Layer(effect = effect)) self.activeLayer = len(self.layers)-1
def newLayer(self, effect='')
Creates a new :py:class:`Layer` and set that as the active. :param effect: A string with the blend mode for that layer that will be used when during the rendering process. The accepted values are: :code:`'soft_light','lighten','screen','dodge','addition','darken','multiply','hard_light','difference','subtract','gr...
3.366257
3.791838
0.887764
activeLayer = self.layers[self.activeLayer] newLayer = Layer(data=activeLayer.data, effect=activeLayer.effect) self.layers.append(newLayer) self.activeLayer = len(self.layers)-1
def duplicateActiveLayer(self)
Duplicates the current active :py:class:`Layer`. :rtype: Nothing.
2.672706
3.125134
0.855229
start = time.time() while(len(self.layers)>1): self.mergeBottomLayers() print('merge time:'+str(time.time()-start)) return self.layers[0]
def mergeAllLayers(self)
Merge all the layers together. :rtype: The result :py:class:`Layer` object.
3.726079
4.2365
0.879518
syns = {} for k, v in self._declared_terms.items(): k = k.strip() if v.get('synonym'): syns[k.lower()] = v['synonym'] if not '.' in k: syns[ROOT_TERM + '.' + k.lower()] = v['synonym'] return syns
def synonyms(self)
Return a dict of term synonyms
4.474574
3.986561
1.122414
# If the doc already has super terms, we've already parsed something, so # assume we parsed the declaration, and can use re-use the old decls. if self.doc and self.doc.super_terms: return self.doc.super_terms return {k.lower(): v['inheritsfrom'].lower() ...
def super_terms(self)
Return a dictionary mapping term names to their super terms
10.557757
9.896525
1.066815
# Run the parser, if it has not been run yet. if not self.root: for _ in self: pass return { 'sections': self._declared_sections, 'terms': self._declared_terms, 'synonyms': self.synonyms }
def declare_dict(self)
Return declared sections, terms and synonyms as a dict
6.934649
4.401777
1.57542
if nt.join_lc in self.synonyms: nt.parent_term, nt.record_term = Term.split_term_lower(self.synonyms[nt.join_lc]);
def substitute_synonym(self, nt)
Replace the record_term and parent_term with a synonym :param nt: :return:
12.642677
6.63539
1.90534
errors = [] for e in self.errors: errors.append({ 'file': e.term.file_name, 'row': e.term.row if e.term else '<unknown>', 'col': e.term.col if e.term else '<unknown>', 'term': e.term.join if e.term else '<unknown>', ...
def errors_as_dict(self)
Return parse errors as a dict
3.455771
3.262469
1.05925
path = None while True: if exists(name): path =name break try: # Look for a local document path = declaration_path(name) break except IncludeError: pass ...
def find_declare_doc(self, d, name)
Given a name, try to resolve the name to a path or URL to a declaration document. It will try: * The name as a filesystem path * The name as a file name in the directory d * The name + '.csv' as a name in the directory d * The name as a URL * The name as a key in th...
5.482069
4.403709
1.244875
from metatab import parse_app_url include_ref = name.strip('/') if include_ref.startswith('http'): path = include_ref else: if not d: raise IncludeError("Can't include '{}' because don't know current path " ...
def find_include_doc(self, d, name)
Resolve a name or path for an include doc to a an absolute path or url :param name:
7.219683
7.312679
0.987283
last_section = root t = None if isinstance(ref, Source): row_gen = ref ref_path = row_gen.__class__.__name__ else: row_gen = get_generator(ref) ref_path = ref.path try: for line_n, row in enumerate(row_gen, ...
def generate_terms(self, ref, root, file_type=None)
An generator that yields term objects, handling includes and argument children. :param file_type: :param doc: :param root: :param ref:
4.353942
4.356625
0.999384
if not t.get('inheritsfrom'): return if not 'section' in t: raise DeclarationError("DeclareTerm for '{}' must specify a section to use InheritsFrom" .format(t['term'])) t_p, t_r = Term.split_term(t['term']) ih_p, ih_r...
def inherited_children(self, t)
Generate inherited children based on a terms InhertsFrom property. The input term must have both an InheritsFrom property and a defined Section :param t: A subclassed terms -- has an InheritsFrom value
5.61768
5.038578
1.114934
''' listPeer 返回列表 { "rtn":0, "peerList": [{ "category": "", "status": 0, "name": "GUNNER_HOME", "vodPort": 43566, "company": "XUNLEI_MIPS_BE_MIPS32", "pid": "8498352EB4F5208X00...
def get_remote_peer_list(self)
listPeer 返回列表 { "rtn":0, "peerList": [{ "category": "", "status": 0, "name": "GUNNER_HOME", "vodPort": 43566, "company": "XUNLEI_MIPS_BE_MIPS32", "pid": "8498352EB4F5208X0001", ...
8.736002
1.451481
6.018682
''' list 返回列表 { "recycleNum": 0, "serverFailNum": 0, "rtn": 0, "completeNum": 34, "sync": 0, "tasks": [{ "failCode": 15414, "vipChannel": { "available": 0, ...
def get_remote_task_list( self, peer_id, list_type=ListType.downloading, pos=0, number=10)
list 返回列表 { "recycleNum": 0, "serverFailNum": 0, "rtn": 0, "completeNum": 34, "sync": 0, "tasks": [{ "failCode": 15414, "vipChannel": { "available": 0, "failCode": 0, ...
5.352445
1.308466
4.090626
''' urlCheck 返回数据 { "rtn": 0, "taskInfo": { "failCode": 0, "name": ".HDTVrip.1024X576.mkv", "url": "ed2k://|file|%E6%B0%", "type": 1, "id": "0", "size": 505005442 }...
def check_url(self, pid, url_list)
urlCheck 返回数据 { "rtn": 0, "taskInfo": { "failCode": 0, "name": ".HDTVrip.1024X576.mkv", "url": "ed2k://|file|%E6%B0%", "type": 1, "id": "0", "size": 505005442 } }
4.255108
1.973464
2.156162
''' post data: { "path":"C:/TDDOWNLOAD/", "tasks":[{ "url":"ed2k://|file|%E6%B0%B8%E6%81%92.Forever...", "name":"永恒.Forever.S01E02.中英字幕.WEB-HR.mkv", "gcid":"", "cid":"", "filesize":512807020 ...
def add_tasks_to_remote(self, pid, path='C:/TDDOWNLOAD/', task_list=[])
post data: { "path":"C:/TDDOWNLOAD/", "tasks":[{ "url":"ed2k://|file|%E6%B0%B8%E6%81%92.Forever...", "name":"永恒.Forever.S01E02.中英字幕.WEB-HR.mkv", "gcid":"", "cid":"", "filesize":512807020 }] ...
4.483734
1.536368
2.918398
x = [] for i in range(0, len(NAUTILUSRESOLVER.getMetadata(text).citation)): x.append(NAUTILUSRESOLVER.getReffs(text, level=i)) return x
def read_levels(text)
Read text and get there reffs :param text: Collection (Readable) :return:
14.359053
10.409968
1.379356
global NAUTILUSRESOLVER NAUTILUSRESOLVER = resolver @click.group() @click.option('--verbose', default=False) def CLI(verbose): click.echo("Command Line Interface of Flask") resolver.logger.disabled = not verbose @CLI.command() def flush_resolver(): ...
def FlaskNautilusManager(resolver, flask_nautilus)
Provides a manager for flask scripts to perform specific maintenance operations :param resolver: Nautilus Extension Instance :type resolver: NautilusCtsResolver :param flask_nautilus: Flask Application :type flask_nautilus: FlaskNautilus :return: CLI :rtype: click.group Import with .....
4.556003
4.560917
0.998923
if isinstance(obj, list) or isinstance(obj, tuple): return True return False
def is_iter_non_string(obj)
test if object is a list or tuple
3.90223
2.774614
1.406405
for a in attr: if not hasattr(obj, a): return False return True
def is_dict_like(obj, attr=('keys', 'items'))
test if object is dict like
2.941292
2.611124
1.126447
try: if len(obj) == 0: return False return all([is_dict_like(i, attr) for i in obj]) except Exception: return False
def is_list_of_dict_like(obj, attr=('keys', 'items'))
test if object is a list only containing dict like items
2.767035
2.44187
1.133162
for a in attr: if not hasattr(obj, a): return False return True
def is_path_like(obj, attr=('name', 'is_file', 'is_dir', 'iterdir'))
test if object is pathlib.Path like
2.986312
2.805097
1.064602
if not in_place: out_dict = copy.deepcopy(d) else: out_dict = d def _convert(obj): if isinstance(obj, intype): try: obj = outtype(obj) except Exception: pass elif isinstance(obj, list) and convert_list: ...
def convert_type(d, intype, outtype, convert_list=True, in_place=True)
convert all values of one type to another Parameters ---------- d : dict intype : type_class outtype : type_class convert_list : bool whether to convert instances inside lists and tuples in_place : bool if True, applies conversions to original dict, else returns copy Ex...
1.79111
2.140497
0.836773
path = [] if path is None else path d_new = copy.deepcopy(d) d_sub = d_new for key in path[:-1]: d_sub = d_sub[key] key = path[-1] d_extract = {key: d_sub[key]} d_sub.pop(key) return d_new, d_extract
def extract(d, path=None)
extract section of dictionary Parameters ---------- d : dict path : list[str] keys to section Returns ------- new_dict : dict original, without extracted section extract_dict : dict extracted section Examples -------- >>> from pprint import pprint ...
2.956018
3.83648
0.770503
keys = [] if keys is None else keys assert hasattr(dic, 'keys') new = dic.copy() old_key = None for key in keys: if not hasattr(new, 'keys'): raise KeyError('No indexes after: {}'.format(old_key)) old_key = key new = new[key] return new
def indexes(dic, keys=None)
index dictionary by multiple keys Parameters ---------- dic : dict keys : list Examples -------- >>> d = {1:{"a":"A"},2:{"b":"B"}} >>> indexes(d,[1,'a']) 'A'
4.018621
5.645563
0.711819
def expand(key, value): if is_dict_like(value): flatten_dict = flatten(value, key_as_tuple, sep, list_of_dicts, all_iters) if key_as_tuple: return [(key + k, v) for k, v in flatten_dict.items()] else: ...
def flatten(d, key_as_tuple=True, sep='.', list_of_dicts=None, all_iters=None)
get nested dict as flat {key:val,...}, where key is tuple/string of all nested keys Parameters ---------- d : object key_as_tuple : bool whether keys are list of nested keys or delimited string of nested keys sep : str if key_as_tuple=False, delimiter for keys list_of_dicts:...
1.522823
1.517151
1.003738
r if not d: return d if deepcopy: try: d = copy.deepcopy(d) except Exception: warnings.warn( 'error in deepcopy, so using references to input dict') if key_as_tuple: result = d.pop(()) if () in d else {} else: result =...
def unflatten(d, key_as_tuple=True, delim='.', list_of_dicts=None, deepcopy=True)
r""" unflatten dictionary with keys as tuples or delimited strings Parameters ---------- d : dict key_as_tuple : bool if true, keys are tuples, else, keys are delimited strings delim : str if keys are strings, then split by delim list_of_dicts: str or None if key starts ...
2.662446
2.46644
1.07947
if error_path is None: error_path = [] if list_of_dicts and is_list_of_dict_like(a) and is_list_of_dict_like(b): if len(a) != len(b): raise ValueError( 'list of dicts are of different lengths at ' '"{0}": old: {1}, new: {2}'.format('.'.join(error...
def _single_merge(a, b, error_path=None, overwrite=False, append=False, list_of_dicts=False)
merges b into a
1.557506
1.548172
1.006029
# noqa: E501 outdict = copy.deepcopy(dicts[0]) def single_merge(a, b): return _single_merge(a, b, overwrite=overwrite, append=append, list_of_dicts=list_of_dicts) reduce(single_merge, [outdict] + dicts[1:]) return outdict
def merge(dicts, overwrite=False, append=False, list_of_dicts=False)
merge dicts, starting with dicts[1] into dicts[0] Parameters ---------- dicts : list[dict] list of dictionaries overwrite : bool if true allow overwriting of current data append : bool if true and items are both lists, then add them list_of_dicts: bool treat ...
3.013042
4.746655
0.634772
return flattennd(d, 1, key_as_tuple, delim, list_of_dicts=list_of_dicts)
def flatten2d(d, key_as_tuple=True, delim='.', list_of_dicts=None)
get nested dict as {key:dict,...}, where key is tuple/string of all-1 nested keys NB: is same as flattennd(d,1,key_as_tuple,delim) Parameters ---------- d : dict key_as_tuple : bool whether keys are list of nested keys or delimited string of nested keys delim : str if key_a...
3.487318
3.832656
0.909896
keys = [] if keys is None else keys list_of_dicts = '__list__' if list_of_dicts else None def is_in(a, bs): if use_wildcards: for b in bs: try: if a == b: return True if fnmatch(a, b): ...
def remove_keys(d, keys=None, use_wildcards=True, list_of_dicts=False, deepcopy=True)
remove certain keys from nested dict, retaining preceeding paths Parameters ---------- keys: list use_wildcards : bool if true, can use * (matches everything) and ? (matches any single character) list_of_dicts: bool treat list of dicts as additional branches deepcopy: bo...
2.343955
2.704994
0.866529
keyvals = [] if keyvals is None else keyvals list_of_dicts = '__list__' if list_of_dicts else None if hasattr(keyvals, 'items'): keyvals = [(k, v) for k, v in keyvals.items()] if not hasattr(d, 'items'): return d flatd = flatten(d, list_of_dicts=list_of_dicts) def is_in(...
def remove_keyvals(d, keyvals=None, list_of_dicts=False, deepcopy=True)
remove paths with at least one branch leading to certain (key,value) pairs from dict Parameters ---------- d : dict keyvals : dict or list[tuple] (key,value) pairs to remove list_of_dicts: bool treat list of dicts as additional branches Examples -------- >>> from p...
2.50296
2.933976
0.853095
keys = [(key,) if not isinstance(key, tuple) else key for key in keys] list_of_dicts = '__list__' if list_of_dicts else None def contains(path): for k in keys: if set(k).issubset(path): return True return False flatd = flatten(d, list_of_dicts=list_of_d...
def remove_paths(d, keys, list_of_dicts=False, deepcopy=True)
remove paths containing certain keys from dict Parameters ---------- d: dict keys : list list of keys to find and remove path list_of_dicts: bool treat list of dicts as additional branches deepcopy: bool deepcopy values Examples -------- >>> from pprint imp...
2.718607
3.783761
0.718493
vals = [] if vals is None else vals list_of_dicts = '__list__' if list_of_dicts else None flatd = flatten(d, list_of_dicts=list_of_dicts) def is_in(a, b): try: return a in b except Exception: return False flatd = {k: v for k, v in flatd.items() if is_i...
def filter_values(d, vals=None, list_of_dicts=False, deepcopy=True)
filters leaf nodes of nested dictionary Parameters ---------- d : dict vals : list values to filter by list_of_dicts: bool treat list of dicts as additional branches deepcopy: bool deepcopy values Examples -------- >>> d = {1:{"a":"A"},2:{"b":"B"},4:{5:{6:'...
2.475204
3.375815
0.733217
list_of_dicts = '__list__' if list_of_dicts else None flatd = flatten(d, list_of_dicts=list_of_dicts) def is_in(a, bs): if use_wildcards: for b in bs: try: if a == b: return True if fnmatch(b, a): ...
def filter_keys(d, keys, use_wildcards=False, list_of_dicts=False, deepcopy=True)
filter dict by certain keys Parameters ---------- d : dict keys: list use_wildcards : bool if true, can use * (matches everything) and ? (matches any single character) list_of_dicts: bool treat list of dicts as additional branches deepcopy: bool deepcopy valu...
2.523227
3.399657
0.7422
list_of_dicts = '__list__' if list_of_dicts else None all_keys = [x for y in paths if isinstance(y, tuple) for x in y] all_keys += [x for x in paths if not isinstance(x, tuple)] # faster to filter first I think new_d = filter_keys(d, all_keys, list_of_dicts=list_of_dicts) new_d = flatten(d...
def filter_paths(d, paths, list_of_dicts=False, deepcopy=True)
filter dict by certain paths containing key sets Parameters ---------- d : dict paths : list[str] or list[tuple] list_of_dicts: bool treat list of dicts as additional branches deepcopy: bool deepcopy values Examples -------- >>> from pprint import pprint >>> d ...
3.077341
3.506528
0.877603
list_of_dicts = '__list__' if list_of_dicts else None keymap = {} if keymap is None else keymap flatd = flatten(d, list_of_dicts=list_of_dicts) flatd = { tuple([keymap.get(k, k) for k in path]): v for path, v in flatd.items() } return unflatten(flatd, list_of_dicts=list_of_dicts,...
def rename_keys(d, keymap=None, list_of_dicts=False, deepcopy=True)
rename keys in dict Parameters ---------- d : dict keymap : dict dictionary of key name mappings list_of_dicts: bool treat list of dicts as additional branches deepcopy: bool deepcopy values Examples -------- >>> from pprint import pprint >>> d = {'a':{...
2.526805
3.759041
0.672194
list_of_dicts = '__list__' if list_of_dicts else None flatd = flatten(d, list_of_dicts=list_of_dicts) newd = {} for path, v in flatd.items(): if key in path: newk = [] for k in path: if k == key: if before: ...
def split_key(d, key, new_keys, before=True, list_of_dicts=False, deepcopy=True)
split an existing key(s) into multiple levels Parameters ---------- d : dict or dict like key: str existing key value new_keys: list[str] new levels to add before: bool add level before existing key (else after) list_of_dicts: bool treat list of dicts...
2.24169
2.821795
0.79442
# noqa: E501 list_of_dicts = '__list__' if list_of_dicts else None if unflatten_level == 0: flatd = flatten(d, list_of_dicts=list_of_dicts) else: flatd = flattennd(d, unflatten_level, list_of_dicts=list_of_dicts) newd = {k: (func(v, **kwargs) if k[-1] == leaf_key else v) ...
def apply(d, leaf_key, func, new_name=None, remove_lkey=True, list_of_dicts=False, unflatten_level=0, deepcopy=True, **kwargs)
apply a function to all values with a certain leaf (terminal) key Parameters ---------- d : dict leaf_key : str name of leaf key func : callable function to apply new_name : str if not None, rename leaf_key remove_lkey: bool whether to remove original leaf_ke...
2.320798
3.137584
0.739677
list_of_dicts = '__list__' if list_of_dicts else None if unflatten_level is not None: flatd = flattennd(d, levels=unflatten_level, list_of_dicts=list_of_dicts) else: # TODO could do this better? flatd = unflatten(d, key_as_tuple=False, ...
def combine_apply(d, leaf_keys, func, new_name, unflatten_level=1, remove_lkeys=True, overwrite=False, list_of_dicts=False, deepcopy=True, **kwargs)
combine values with certain leaf (terminal) keys by a function Parameters ---------- d : dict leaf_keys : list names of leaf keys func : callable function to apply, must take at least len(leaf_keys) arguments new_name : str new key name unflatten_level : int ...
2.897889
3.347471
0.865695
# noqa: E501 flattened = flatten2d(d) new_d = {} for key, value in flattened.items(): if set(split_keys).issubset(value.keys()): # combine_d = {} combine_d = [] sub_d = {} length = None for subkey, subvalue in value.items(): ...
def split_lists(d, split_keys, new_name='split', check_length=True, deepcopy=True)
split_lists key:list pairs into dicts for each item in the lists NB: will only split if all split_keys are present Parameters ---------- d : dict split_keys : list keys to split new_name : str top level key for split items check_length : bool if true, raise error if ...
2.914275
2.882672
1.010963
# noqa: E501 if isinstance(d, list): init_list = True d = {'dummy_key843': d} else: init_list = False flattened = flatten(d, list_of_dicts=None) for key, value in list(flattened.items()): if keys is not None: try: if not key[-1] in keys:...
def combine_lists(d, keys=None, deepcopy=True)
combine lists of dicts Parameters ---------- d : dict or list[dict] keys : list keys to combine (all if None) deepcopy: bool deepcopy values Example ------- >>> from pprint import pprint >>> d = {'path_key': {'a': 1, 'split': [{'x': 1, 'y': 3}, {'x': 2, 'y': 4}]}} ...
2.742191
3.096475
0.885585
assert all([is_dict_like(d) for d in lst]) if key is not None: assert all([key in d for d in lst]) new_dict = {} for i, d in enumerate(lst): d = unflatten(flatten(d)) if key is None: new_dict[str(i)] = d else: if remove_key: k...
def list_to_dict(lst, key=None, remove_key=True)
convert a list of dicts to a dict with root keys Parameters ---------- lst : list[dict] key : str or None a key contained by all of the dicts if None use index number string remove_key : bool remove key from dicts in list Examples -------- >>> from pprint import...
2.302903
2.69213
0.85542
if np_allclose: try: import numpy except ImportError: raise ValueError("to use np_allclose, numpy must be installed") dct1_flat = flatten(new_dict, all_iters=iter_prefix) dct2_flat = flatten(old_dict, all_iters=iter_prefix) outcome = {'insertions': [], 'del...
def diff(new_dict, old_dict, iter_prefix='__iter__', np_allclose=False, **kwargs)
return the difference between two dict_like objects Parameters ---------- new_dict: dict old_dict: dict iter_prefix: str prefix to use for list and tuple indexes np_allclose: bool if True, try using numpy.allclose to assess differences **kwargs: keyword arguments to ...
2.224524
2.054057
1.08299
to_json(dct, jfile, overwrite=overwrite, dirlevel=dirlevel, sort_keys=sort_keys, indent=indent, default_name=default_name, **kwargs)
def dump(dct, jfile, overwrite=False, dirlevel=0, sort_keys=True, indent=2, default_name='root.json', **kwargs)
output dict to json Parameters ---------- dct : dict jfile : str or file_like if file_like, must have write method overwrite : bool whether to overwrite existing files dirlevel : int if jfile is path to folder, defines how many key levels to set as sub-folders ...
1.808889
2.556424
0.707585
if key in d: if no_duplicates: new_items = filter(lambda x: x not in d[key], new_items) if isinstance(d[key], set): map(d[key].add, new_items) elif isinstance(d[key], list): map(d[key].append, new_items) else: d[key] = d[key] + new...
def expand_collection_in_dict(d, key, new_items, no_duplicates=True)
Parameters d: dict dict in which a key will be inserted/expanded key: hashable key in d new_items: iterable d[key] will be extended with items in new_items no_duplicates: bool avoid inserting duplicates in d[key] (default: True)
1.841359
1.861052
0.989418
# Handle virtual working directory if cwd: if not os.path.isabs(src): src = os.path.join(cwd, src) if not os.path.isabs(dst): dst = os.path.join(cwd, dst) # Make sure source file extists if not os.path.exists(src): # Source needs to exist msg...
def copy(src, dst, only_update=False, copystat=True, cwd=None, dest_is_dir=False, create_dest_dirs=False, logger=None)
Augmented shutil.copy with extra options and slightly modified behaviour Parameters ========== src: string path to source file dst: string path to destingation only_update: bool only copy if source is newer than destination (returns None if it was newer), default...
2.840868
2.763542
1.027981
md = md5() with open(path, 'rb') as f: for chunk in iter(lambda: f.read(nblocks*md.block_size), b''): md.update(chunk) return md
def md5_of_file(path, nblocks=128)
Computes the md5 hash of a file. Parameters ========== path: string path to file to compute hash of Returns ======= hashlib md5 hash object. Use .digest() or .hexdigest() on returned object to get binary or hex encoded string.
1.918165
2.075672
0.924118
cwd = cwd or '.' path = get_abspath(path, cwd=cwd) other_path = get_abspath(other_path, cwd=cwd) if not os.path.exists(path): return True if os.path.getmtime(other_path) - 1e-6 >= os.path.getmtime(path): # 1e-6 is needed beacuse http://stackoverflow.com/questions/17086426/ ...
def missing_or_other_newer(path, other_path, cwd=None)
Investigate if path is non-existant or older than provided reference path. Parameters ========== path: string path to path which might be missing or too old other_path: string reference path cwd: string working directory (root of relative paths) Returns ======= ...
3.13584
3.560359
0.880765
import imp path, name = os.path.split(filename) name, ext = os.path.splitext(name) name = name.split('.')[0] fobj, filename, data = imp.find_module(name, [path]) if only_if_newer_than: for dep in only_if_newer_than: if os.path.getmtime(filename) < os.path.getmtime(dep): ...
def import_module_from_file(filename, only_if_newer_than=None)
Imports (cython generated) shared object file (.so) Provide a list of paths in `only_if_newer_than` to check timestamps of dependencies. import_ raises an ImportError if any is newer. Word of warning: Python's caching or the OS caching (unclear to author) is horrible for reimporting same path of a...
2.08885
2.283373
0.914809
from distutils.spawn import find_executable for c in candidates: binary_path = find_executable(c) if c and binary_path: return c, binary_path raise RuntimeError('No binary located for candidates: {}'.format( candidates))
def find_binary_of_command(candidates)
Calls `find_executable` from distuils for provided candidates and returns first hit. If no candidate mathces, a RuntimeError is raised
4.576154
4.150033
1.102679
for line in open(path, 'rt'): if line.startswith('#') and '=' in line: splitted = line.split('=') if len(splitted) != 2: continue lhs, rhs = splitted if lhs.strip().split()[-1].lower() == 'language' and \ rhs.strip().split()...
def pyx_is_cplus(path)
Inspect a Cython source file (.pyx) and look for comment line like: # distutils: language = c++ Returns True if such a file is present in the file, else False.
2.692785
2.433412
1.106588
result = [] for x in l: if x not in result: result.append(x) return result
def uniquify(l)
Uniquify a list (skip duplicate items).
2.175748
2.209759
0.984609
fullpath = os.path.join(dirpath, cls.metadata_filename) if os.path.exists(fullpath): d = pickle.load(open(fullpath, 'rb')) return d[key] else: raise FileNotFoundError( "No such file: {0}".format(fullpath))
def get_from_metadata_file(cls, dirpath, key)
Get value of key in metadata file dict.
2.473547
2.31349
1.069184
fullpath = os.path.join(dirpath, cls.metadata_filename) if os.path.exists(fullpath): d = pickle.load(open(fullpath, 'rb')) d.update({key: value}) pickle.dump(d, open(fullpath, 'wb')) else: pickle.dump({key: value}, open(fullpath, 'wb'))
def save_to_metadata_file(cls, dirpath, key, value)
Store `key: value` in metadata file dict.
1.826333
1.731161
1.054976
if category is not None: return sorted(_plugins_interface[category][:]) else: return {k: v[:] for k, v in _plugins_interface.items()}
def view_interfaces(category=None)
return a view of the plugin minimal class attribute interface(s) Parameters ---------- category : None or str if str, apply for single plugin category Examples -------- >>> from pprint import pprint >>> pprint(view_interfaces()) {'decoders': ['plugin_name', 'plugin_descript', ...
5.609068
5.895801
0.951367
if category is not None: if category == 'parsers': return { name: {"descript": klass.plugin_descript, "regex": klass.file_regex} for name, klass in _all_plugins[category].items() } return { name: klass.pl...
def view_plugins(category=None)
return a view of the loaded plugin names and descriptions Parameters ---------- category : None or str if str, apply for single plugin category Examples -------- >>> from pprint import pprint >>> pprint(view_plugins()) {'decoders': {}, 'encoders': {}, 'parsers': {}} >>> c...
2.913017
2.871125
1.014591
if category is not None: _all_plugins[category].pop(name) else: for cat in _all_plugins: if name in _all_plugins[cat]: _all_plugins[cat].pop(name)
def unload_plugin(name, category=None)
remove single plugin Parameters ---------- name : str plugin name category : str plugin category Examples -------- >>> from pprint import pprint >>> pprint(view_plugins()) {'decoders': {}, 'encoders': {}, 'parsers': {}} >>> class DecoderPlugin(object): ......
2.291626
3.340991
0.685912
load_errors = [] for klass in classes: for pcat, pinterface in _plugins_interface.items(): if category is not None and not pcat == category: continue if all([hasattr(klass, attr) for attr in pinterface]): if klass.plugin_name in _all_plugins[p...
def load_plugin_classes(classes, category=None, overwrite=False)
load plugins from class objects Parameters ---------- classes: list list of classes category : None or str if str, apply for single plugin category overwrite : bool if True, allow existing plugins to be overwritten Examples -------- >>> from pprint import pprin...
3.081241
3.528548
0.873232
original = {cat: list(_all_plugins[cat].keys()) for cat in _all_plugins} load_plugin_classes(classes, category, overwrite=True) # if errors: # for cat in _all_plugins: # for name, kls in list(_all_plugins[cat].items()): # if name not in original[cat]: # ...
def plugins_context(classes, category=None)
context manager to load plugin class(es) then unload on exit Parameters ---------- classes: list list of classes category : None or str if str, apply for single plugin category Examples -------- >>> from pprint import pprint >>> class DecoderPlugin(object): ... ...
2.862964
3.1159
0.918824
# get potential plugin python files if hasattr(path, 'glob'): pypaths = path.glob('*.py') else: pypaths = glob.glob(os.path.join(path, '*.py')) load_errors = [] for pypath in pypaths: # use uuid to ensure no conflicts in name space mod_name = str(uuid.uuid4()) ...
def load_plugins_dir(path, category=None, overwrite=False)
load plugins from a directory Parameters ---------- path : str or path_like category : None or str if str, apply for single plugin category overwrite : bool if True, allow existing plugins to be overwritten
3.150761
3.177562
0.991565
# noqa: E501 load_errors = [] for cat, path in _plugins_builtin.items(): if cat != category and category is not None: continue load_errors += load_plugins_dir(path, cat, overwrite=overwrite) return load_errors
def load_builtin_plugins(category=None, overwrite=False)
load plugins from builtin directories Parameters ---------- name: None or str category : None or str if str, apply for single plugin category Examples -------- >>> from pprint import pprint >>> pprint(view_plugins()) {'decoders': {}, 'encoders': {}, 'parsers': {}} >>>...
3.834795
5.117991
0.749277
for encoder in get_plugins('encoders').values(): if (isinstance(obj, encoder.objclass) and hasattr(encoder, 'to_{}'.format(outtype))): return getattr(encoder, 'to_{}'.format(outtype))(obj) break if raise_error: raise ValueError( "No JSON ...
def encode(obj, outtype='json', raise_error=False)
encode objects, via encoder plugins, to new types Parameters ---------- outtype: str use encoder method to_<outtype> to encode raise_error : bool if True, raise ValueError if no suitable plugin found Examples -------- >>> load_builtin_plugins('encoders') [] >>> fro...
3.7524
3.982995
0.942105
for decoder in get_plugins('decoders').values(): if (set(list(decoder.dict_signature)).issubset(dct.keys()) and hasattr(decoder, 'from_{}'.format(intype)) and getattr(decoder, 'allow_other_keys', False)): return getattr(decoder, 'from_{}'.format(intype))(dct) ...
def decode(dct, intype='json', raise_error=False)
decode dict objects, via decoder plugins, to new type Parameters ---------- intype: str use decoder method from_<intype> to encode raise_error : bool if True, raise ValueError if no suitable plugin found Examples -------- >>> load_builtin_plugins('decoders') [] >>>...
3.270131
2.971438
1.100521
if isinstance(fpath, basestring): fname = fpath elif hasattr(fpath, 'open') and hasattr(fpath, 'name'): fname = fpath.name elif hasattr(fpath, 'readline') and hasattr(fpath, 'name'): fname = fpath.name else: raise ValueError( 'fpath should be a str or fil...
def parser_available(fpath)
test if parser plugin available for fpath Examples -------- >>> load_builtin_plugins('parsers') [] >>> test_file = StringIO('{"a":[1,2,3.4]}') >>> test_file.name = 'test.json' >>> parser_available(test_file) True >>> test_file.name = 'test.other' >>> parser_available(test_file)...
2.688213
3.070679
0.875446
if isinstance(fpath, basestring): fname = fpath elif hasattr(fpath, 'open') and hasattr(fpath, 'name'): fname = fpath.name elif hasattr(fpath, 'readline') and hasattr(fpath, 'name'): fname = fpath.name else: raise ValueError( 'fpath should be a str or fil...
def parse(fpath, **kwargs)
parse file contents, via parser plugins, to dict like object NB: the longest file regex will be used from plugins Parameters ---------- fpath : file_like string, object with 'open' and 'name' attributes, or object with 'readline' and 'name' attributes kwargs : to pass to p...
2.31218
2.031667
1.138071
_RESET = '\033[0m' __ISON = True if __ISON and os.getenv('ANSI_COLORS_DISABLED') is None: fmt_str = '\033[%dm%s' if color is not None: text = fmt_str % (_COLORS[color], text) if on_color is not None: text = fmt_str % (_HIGHLIGHTS[on_color], text) ...
def colortxt(text, color=None, on_color=None, attrs=None)
Colorize text. Available text colors: red, green, yellow, blue, magenta, cyan, white. Available text highlights: on_red, on_green, on_yellow, on_blue, on_magenta, on_cyan, on_white. Available attributes: bold, dark, underline, blink, reverse, concealed. Examples -------- ...
2.552898
3.220742
0.792643
stream = ZipReader(path, filename).readlines(encoding) return cls(stream, dialect, fields, converters)
def from_zipfile(cls, path, filename, encoding, dialect, fields, converters)
Read delimited text from zipfile.
6.08773
5.960353
1.021371
return cls(open(path, 'r', encoding=encoding), dialect, fields, converters, field_index)
def from_file(cls, path, encoding, dialect, fields, converters, field_index)
Read delimited text from a text file.
3.625269
3.401224
1.065872
with ZipFile(self.path, mode='r') as archive: return archive.read(self.filename)
def read_bytes(self)
Read content into byte string.
6.662992
5.176149
1.287249
with open_zipfile_archive(self.path, self.filename) as file: for line in file: yield line.rstrip(b'\r\n')
def readlines_bytes(self)
Read content into byte str line iterator.
6.950451
5.476147
1.269223
if self.CACHE_FULL_TEI is True: return self.get_or( _cache_key("Nautilus", self.name, "File", "Tree", file.name), super(ProtoNautilusCtsResolver, self).xmlparse, file ) return super(ProtoNautilusCtsResolver, self).xmlparse(file)
def xmlparse(self, file)
Parse a XML file :param file: Opened File :return: Tree
10.675941
11.09042
0.962627
cached = self.cache.get(cache_key) if cached is not None: return cached else: try: output = callback(*args, **kwargs) except MyCapytain.errors.UnknownCollection as E: raise UnknownCollection(str(E)) except E...
def get_or(self, cache_key, callback, *args, **kwargs)
Get or set the cache using callback and arguments :param cache_key: Cache key for given resource :param callback: Callback if object does not exist :param args: Ordered Argument for the callback :param kwargs: Keyword argument for the callback :return: Output of the callback
3.588096
4.176849
0.859044
if self.CACHE_FULL_TEI is True: o = self.cache.get(_cache_key(self.texts_parsed_cache_key, identifier)) if o is not None: return o else: with open(path) as f: o = Text(urn=identifier, resource=self.xmlparse(f)) ...
def read(self, identifier, path=None)
Read a text object given an identifier and a path :param identifier: Identifier of the text :param path: Path of the text files :return: Text
3.581194
3.712929
0.96452
if resource is None: resource = self.__resources__ self.inventory = self.dispatcher.collection try: self._parse(resource) except MyCapytain.errors.UndispatchedTextError as E: if self.RAISE_ON_UNDISPATCHED is True: raise Undis...
def parse(self, resource=None)
Parse a list of directories ans :param resource: List of folders
8.680533
9.544025
0.909525
return self.get_or( self.__cache_key_reffs__(textId, level, subreference), super(ProtoNautilusCtsResolver, self).getReffs, textId, level, subreference )
def getReffs(self, textId, level=1, subreference=None)
Retrieve the siblings of a textual node :param textId: PrototypeText Identifier :type textId: str :param level: Depth for retrieval :type level: int :param subreference: Passage Reference :type subreference: str :return: List of references :rtype: [str]
8.805589
9.503151
0.926597
key = _cache_key("Nautilus", self.name, "Passage", textId, subreference) o = self.cache.get(key) if o is not None: return o text, text_metadata = self.__getText__(textId) if subreference is not None: subreference = Reference(subreference) ...
def getTextualNode(self, textId, subreference=None, prevnext=False, metadata=False)
Retrieve a text node from the API :param textId: PrototypeText Identifier :type textId: str :param subreference: Passage Reference :type subreference: str :param prevnext: Retrieve graph representing previous and next passage :type prevnext: boolean :param metada...
4.649611
4.336383
1.072233
key = _cache_key("Nautilus", self.name, "Siblings", textId, subreference) o = self.cache.get(key) if o is not None: return o passage = self.getTextualNode(textId, subreference, prevnext=True) siblings = passage.siblingsId self.cache.set(key, siblings)...
def getSiblings(self, textId, subreference)
Retrieve the siblings of a textual node :param textId: PrototypeText Identifier :type textId: str :param subreference: Passage Reference :type subreference: str :return: Tuple of references :rtype: (str, str)
4.843879
4.742453
1.021387
return self.get_or( _cache_key("Nautilus", self.name, "GetMetadata", objectId), super(ProtoNautilusCtsResolver, self).getMetadata, objectId )
def getMetadata(self, objectId=None, **filters)
Request metadata about a text or a collection :param objectId: Object Identifier to filter on :type objectId: str :param filters: Kwargs parameters. :type filters: dict :return: Collection
17.767138
24.565918
0.723243
self.dispatcher.dispatch(textgroup, path=directory)
def _dispatch(self, textgroup, directory)
Sparql dispatcher do not need to dispatch works, as the link is DB stored through Textgroup :param textgroup: A Textgroup object :param directory: The path in which we found the textgroup :return:
10.639848
13.833302
0.769147
response = default_answer def should_ignore_tty(): ret_to_bool = {"yes": True, "no": False, "true": True, "false": False} envs = [os.getenv("CI", default="no"), os.getenv("TEST", default="no")] vals = [ret_to_bool[val] for val in envs if val in ret_to_bool] return ...
def ask(question, default_answer=False, default_answer_str="no")
Ask for user input. This asks a yes/no question with a preset default. You can bypass the user-input and fetch the default answer, if you set Args: question: The question to ask on stdout. default_answer: The default value to return. default_answer_str: The default ...
3.67123
4.179051
0.878484
try: with open(path, 'rb') as csvfile: reader = DictReader(csvfile, delimiter=delimiter) for row in reader: yield row except (OSError, IOError): raise ClientException("File not found: {}".format(path))
def load_csv(path, delimiter=',')
Load CSV file from path and yield CSV rows Usage: for row in load_csv('/path/to/file'): print(row) or list(load_csv('/path/to/file')) :param path: file path :param delimiter: CSV delimiter :return: a generator where __next__ is a row of the CSV
2.801693
3.182171
0.880435
try: with open(path, 'r') as json_file: return json.load(json_file) except (OSError, IOError): raise ClientException("File not found: {}".format(path))
def load_json(path)
Load JSON file from path :param path: file path :return: A Python object (e.g. a dict)
2.832284
3.159025
0.896569
data = data[key] for i in range(0, len(data), thresh): yield {key: data[i:i + thresh]}
def partition_payload(data, key, thresh)
Yield partitions of a payload e.g. with a threshold of 2: { "dataElements": [1, 2, 3] } --> { "dataElements": [1, 2] } and { "dataElements": [3] } :param data: the payload :param key: the key of the dict to partition :param thresh: the maximum value of a chunk :return: a ge...
3.278603
3.695139
0.887274
if 'DHIS_HOME' in os.environ: return os.path.join(os.environ['DHIS_HOME'], filename) else: home_path = os.path.expanduser(os.path.join('~')) for root, dirs, files in os.walk(home_path): if filename in files: return os.path.join(root, filename) raise C...
def search_auth_file(filename='dish.json')
Search filename in - A) DHIS_HOME (env variable) - B) current user's home folder :param filename: the filename to search for :return: full path of filename
2.88907
2.517169
1.147746
# remove '-SNAPSHOT' value = value.replace('-SNAPSHOT', '') # remove '-RCx' if '-RC' in value: value = value.split('-RC', 1)[0] try: return int(value.split('.')[1]) except (ValueError, IndexError): return
def version_to_int(value)
Convert version info to integer :param value: the version received from system/info, e.g. "2.28" :return: integer from version, e.g. 28, None if it couldn't be parsed
3.087419
3.320138
0.929907
# first must be a letter first = random.choice(string.ascii_letters) # rest must be letters or numbers rest = ''.join(random.choice(string.ascii_letters + string.digits) for _ in range(10)) return first + rest
def generate_uid()
Create DHIS2 UID matching to Regex ^[A-Za-z][A-Za-z0-9]{10}$ :return: UID string
2.881282
2.989886
0.963676
pattern = r'^[A-Za-z][A-Za-z0-9]{10}$' if not isinstance(uid, string_types): return False return bool(re.compile(pattern).match(uid))
def is_valid_uid(uid)
:return: True if it is a valid DHIS2 UID, False if not
2.987844
2.627697
1.137058
if isinstance(obj, string_types): try: obj = json.loads(obj) except ValueError: raise ClientException("`obj` is not a json string") json_str = json.dumps(obj, sort_keys=True, indent=2) print(highlight(json_str, JsonLexer(), TerminalFormatter()))
def pretty_json(obj)
Print JSON with indentation and colours :param obj: the object to print - can be a dict or a string
2.884909
2.778135
1.038434
if isinstance(remove, string_types): remove = [remove] try: iter(remove) except TypeError: raise ClientException("`remove` could not be removed from object: {}".format(repr(remove))) else: if isinstance(obj, dict): obj = { key: clean_obj(v...
def clean_obj(obj, remove)
Recursively remove keys from list/dict/dict-of-lists/list-of-keys/nested ..., e.g. remove all sharing keys or remove all 'user' fields This should result in the same as if running in bash: `jq del(.. | .publicAccess?, .userGroupAccesses?)` :param obj: the dict to remove keys from :param remove: keys to...
2.250785
2.298748
0.979135
for child in self._children: with open(osp.join(child, YAML_REPORT_FILE)) as istr: command = yaml.safe_load(istr)['command'] yield ' '.join(map(six.moves.shlex_quote, command))
def commands(self)
Get all commands of the benchmark category :return generator of string
7.284717
7.579125
0.961155