code
stringlengths
75
104k
code_sememe
stringlengths
47
309k
token_type
stringlengths
215
214k
code_dependency
stringlengths
75
155k
def ret_dump(self, d_ret, **kwargs): """ JSON print results to console (or caller) """ b_print = True for k, v in kwargs.items(): if k == 'JSONprint': b_print = bool(v) if b_print: print( json.dumps( d_ret, indent = 4, sort_keys = True ) )
def function[ret_dump, parameter[self, d_ret]]: constant[ JSON print results to console (or caller) ] variable[b_print] assign[=] constant[True] for taget[tuple[[<ast.Name object at 0x7da2044c1d80>, <ast.Name object at 0x7da2044c25c0>]]] in starred[call[name[kwargs].items, parameter[]]] begin[:] if compare[name[k] equal[==] constant[JSONprint]] begin[:] variable[b_print] assign[=] call[name[bool], parameter[name[v]]] if name[b_print] begin[:] call[name[print], parameter[call[name[json].dumps, parameter[name[d_ret]]]]]
keyword[def] identifier[ret_dump] ( identifier[self] , identifier[d_ret] ,** identifier[kwargs] ): literal[string] identifier[b_print] = keyword[True] keyword[for] identifier[k] , identifier[v] keyword[in] identifier[kwargs] . identifier[items] (): keyword[if] identifier[k] == literal[string] : identifier[b_print] = identifier[bool] ( identifier[v] ) keyword[if] identifier[b_print] : identifier[print] ( identifier[json] . identifier[dumps] ( identifier[d_ret] , identifier[indent] = literal[int] , identifier[sort_keys] = keyword[True] ) )
def ret_dump(self, d_ret, **kwargs): """ JSON print results to console (or caller) """ b_print = True for (k, v) in kwargs.items(): if k == 'JSONprint': b_print = bool(v) # depends on [control=['if'], data=[]] # depends on [control=['for'], data=[]] if b_print: print(json.dumps(d_ret, indent=4, sort_keys=True)) # depends on [control=['if'], data=[]]
def _transform_list_args(self, args): # type: (dict) -> None """Transforms all list arguments from json-server to model-resource ones. This modifies the given arguments. """ if '_limit' in args: args['limit'] = int(args['_limit']) del args['_limit'] if '_page' in args: page = int(args['_page']) if page < 0: page = 1 args['page'] = page del args['_page'] if 'limit' not in args: args['limit'] = 10 if '_end' in args: end = int(args['_end']) args['limit'] = end - int(args.get('_start', 0)) if '_start' in args: args['offset'] = args['_start'] del args['_start'] if '_sort' in args: args['order_by'] = args['_sort'].replace('__', '.') del args['_sort'] if args.get('_order', 'ASC') == 'DESC': args['order_by'] = '-' + args['order_by'] if '_order' in args: del args['_order'] filter_by = self._create_filter_by() if filter_by: args['filter_by'] = filter_by
def function[_transform_list_args, parameter[self, args]]: constant[Transforms all list arguments from json-server to model-resource ones. This modifies the given arguments. ] if compare[constant[_limit] in name[args]] begin[:] call[name[args]][constant[limit]] assign[=] call[name[int], parameter[call[name[args]][constant[_limit]]]] <ast.Delete object at 0x7da207f02b30> if compare[constant[_page] in name[args]] begin[:] variable[page] assign[=] call[name[int], parameter[call[name[args]][constant[_page]]]] if compare[name[page] less[<] constant[0]] begin[:] variable[page] assign[=] constant[1] call[name[args]][constant[page]] assign[=] name[page] <ast.Delete object at 0x7da1b26acb20> if compare[constant[limit] <ast.NotIn object at 0x7da2590d7190> name[args]] begin[:] call[name[args]][constant[limit]] assign[=] constant[10] if compare[constant[_end] in name[args]] begin[:] variable[end] assign[=] call[name[int], parameter[call[name[args]][constant[_end]]]] call[name[args]][constant[limit]] assign[=] binary_operation[name[end] - call[name[int], parameter[call[name[args].get, parameter[constant[_start], constant[0]]]]]] if compare[constant[_start] in name[args]] begin[:] call[name[args]][constant[offset]] assign[=] call[name[args]][constant[_start]] <ast.Delete object at 0x7da1b26af370> if compare[constant[_sort] in name[args]] begin[:] call[name[args]][constant[order_by]] assign[=] call[call[name[args]][constant[_sort]].replace, parameter[constant[__], constant[.]]] <ast.Delete object at 0x7da1b196f430> if compare[call[name[args].get, parameter[constant[_order], constant[ASC]]] equal[==] constant[DESC]] begin[:] call[name[args]][constant[order_by]] assign[=] binary_operation[constant[-] + call[name[args]][constant[order_by]]] if compare[constant[_order] in name[args]] begin[:] <ast.Delete object at 0x7da1b196c460> variable[filter_by] assign[=] call[name[self]._create_filter_by, parameter[]] if name[filter_by] begin[:] call[name[args]][constant[filter_by]] assign[=] name[filter_by]
keyword[def] identifier[_transform_list_args] ( identifier[self] , identifier[args] ): literal[string] keyword[if] literal[string] keyword[in] identifier[args] : identifier[args] [ literal[string] ]= identifier[int] ( identifier[args] [ literal[string] ]) keyword[del] identifier[args] [ literal[string] ] keyword[if] literal[string] keyword[in] identifier[args] : identifier[page] = identifier[int] ( identifier[args] [ literal[string] ]) keyword[if] identifier[page] < literal[int] : identifier[page] = literal[int] identifier[args] [ literal[string] ]= identifier[page] keyword[del] identifier[args] [ literal[string] ] keyword[if] literal[string] keyword[not] keyword[in] identifier[args] : identifier[args] [ literal[string] ]= literal[int] keyword[if] literal[string] keyword[in] identifier[args] : identifier[end] = identifier[int] ( identifier[args] [ literal[string] ]) identifier[args] [ literal[string] ]= identifier[end] - identifier[int] ( identifier[args] . identifier[get] ( literal[string] , literal[int] )) keyword[if] literal[string] keyword[in] identifier[args] : identifier[args] [ literal[string] ]= identifier[args] [ literal[string] ] keyword[del] identifier[args] [ literal[string] ] keyword[if] literal[string] keyword[in] identifier[args] : identifier[args] [ literal[string] ]= identifier[args] [ literal[string] ]. identifier[replace] ( literal[string] , literal[string] ) keyword[del] identifier[args] [ literal[string] ] keyword[if] identifier[args] . identifier[get] ( literal[string] , literal[string] )== literal[string] : identifier[args] [ literal[string] ]= literal[string] + identifier[args] [ literal[string] ] keyword[if] literal[string] keyword[in] identifier[args] : keyword[del] identifier[args] [ literal[string] ] identifier[filter_by] = identifier[self] . identifier[_create_filter_by] () keyword[if] identifier[filter_by] : identifier[args] [ literal[string] ]= identifier[filter_by]
def _transform_list_args(self, args): # type: (dict) -> None 'Transforms all list arguments from json-server to model-resource ones.\n\n This modifies the given arguments.\n ' if '_limit' in args: args['limit'] = int(args['_limit']) del args['_limit'] # depends on [control=['if'], data=['args']] if '_page' in args: page = int(args['_page']) if page < 0: page = 1 # depends on [control=['if'], data=['page']] args['page'] = page del args['_page'] if 'limit' not in args: args['limit'] = 10 # depends on [control=['if'], data=['args']] # depends on [control=['if'], data=['args']] if '_end' in args: end = int(args['_end']) args['limit'] = end - int(args.get('_start', 0)) # depends on [control=['if'], data=['args']] if '_start' in args: args['offset'] = args['_start'] del args['_start'] # depends on [control=['if'], data=['args']] if '_sort' in args: args['order_by'] = args['_sort'].replace('__', '.') del args['_sort'] if args.get('_order', 'ASC') == 'DESC': args['order_by'] = '-' + args['order_by'] # depends on [control=['if'], data=[]] # depends on [control=['if'], data=['args']] if '_order' in args: del args['_order'] # depends on [control=['if'], data=['args']] filter_by = self._create_filter_by() if filter_by: args['filter_by'] = filter_by # depends on [control=['if'], data=[]]
def _sm_stop_from_pain(self, *args, **kwargs): """ Stop chaos while there is a blockade event in progress """ _logger.info("Stopping chaos for blockade %s" % self._blockade_name) self._do_reset_all()
def function[_sm_stop_from_pain, parameter[self]]: constant[ Stop chaos while there is a blockade event in progress ] call[name[_logger].info, parameter[binary_operation[constant[Stopping chaos for blockade %s] <ast.Mod object at 0x7da2590d6920> name[self]._blockade_name]]] call[name[self]._do_reset_all, parameter[]]
keyword[def] identifier[_sm_stop_from_pain] ( identifier[self] ,* identifier[args] ,** identifier[kwargs] ): literal[string] identifier[_logger] . identifier[info] ( literal[string] % identifier[self] . identifier[_blockade_name] ) identifier[self] . identifier[_do_reset_all] ()
def _sm_stop_from_pain(self, *args, **kwargs): """ Stop chaos while there is a blockade event in progress """ _logger.info('Stopping chaos for blockade %s' % self._blockade_name) self._do_reset_all()
def get_relevant_policy_section(self, policy_name, group=None): """ Look up the policy corresponding to the provided policy name and group (optional). Log any issues found during the look up. """ policy_bundle = self._operation_policies.get(policy_name) if not policy_bundle: self._logger.warning( "The '{}' policy does not exist.".format(policy_name) ) return None if group: groups_policy_bundle = policy_bundle.get('groups') if not groups_policy_bundle: self._logger.debug( "The '{}' policy does not support groups.".format( policy_name ) ) return None else: group_policy = groups_policy_bundle.get(group) if not group_policy: self._logger.debug( "The '{}' policy does not support group '{}'.".format( policy_name, group ) ) return None else: return group_policy else: return policy_bundle.get('preset')
def function[get_relevant_policy_section, parameter[self, policy_name, group]]: constant[ Look up the policy corresponding to the provided policy name and group (optional). Log any issues found during the look up. ] variable[policy_bundle] assign[=] call[name[self]._operation_policies.get, parameter[name[policy_name]]] if <ast.UnaryOp object at 0x7da18f58c880> begin[:] call[name[self]._logger.warning, parameter[call[constant[The '{}' policy does not exist.].format, parameter[name[policy_name]]]]] return[constant[None]] if name[group] begin[:] variable[groups_policy_bundle] assign[=] call[name[policy_bundle].get, parameter[constant[groups]]] if <ast.UnaryOp object at 0x7da18f58c490> begin[:] call[name[self]._logger.debug, parameter[call[constant[The '{}' policy does not support groups.].format, parameter[name[policy_name]]]]] return[constant[None]]
keyword[def] identifier[get_relevant_policy_section] ( identifier[self] , identifier[policy_name] , identifier[group] = keyword[None] ): literal[string] identifier[policy_bundle] = identifier[self] . identifier[_operation_policies] . identifier[get] ( identifier[policy_name] ) keyword[if] keyword[not] identifier[policy_bundle] : identifier[self] . identifier[_logger] . identifier[warning] ( literal[string] . identifier[format] ( identifier[policy_name] ) ) keyword[return] keyword[None] keyword[if] identifier[group] : identifier[groups_policy_bundle] = identifier[policy_bundle] . identifier[get] ( literal[string] ) keyword[if] keyword[not] identifier[groups_policy_bundle] : identifier[self] . identifier[_logger] . identifier[debug] ( literal[string] . identifier[format] ( identifier[policy_name] ) ) keyword[return] keyword[None] keyword[else] : identifier[group_policy] = identifier[groups_policy_bundle] . identifier[get] ( identifier[group] ) keyword[if] keyword[not] identifier[group_policy] : identifier[self] . identifier[_logger] . identifier[debug] ( literal[string] . identifier[format] ( identifier[policy_name] , identifier[group] ) ) keyword[return] keyword[None] keyword[else] : keyword[return] identifier[group_policy] keyword[else] : keyword[return] identifier[policy_bundle] . identifier[get] ( literal[string] )
def get_relevant_policy_section(self, policy_name, group=None): """ Look up the policy corresponding to the provided policy name and group (optional). Log any issues found during the look up. """ policy_bundle = self._operation_policies.get(policy_name) if not policy_bundle: self._logger.warning("The '{}' policy does not exist.".format(policy_name)) return None # depends on [control=['if'], data=[]] if group: groups_policy_bundle = policy_bundle.get('groups') if not groups_policy_bundle: self._logger.debug("The '{}' policy does not support groups.".format(policy_name)) return None # depends on [control=['if'], data=[]] else: group_policy = groups_policy_bundle.get(group) if not group_policy: self._logger.debug("The '{}' policy does not support group '{}'.".format(policy_name, group)) return None # depends on [control=['if'], data=[]] else: return group_policy # depends on [control=['if'], data=[]] else: return policy_bundle.get('preset')
def report_object(self, key, filename, anchor_text=None, anchor_image=None, annotation=None): """ Writes a string to self.pipeline_objects_file. Used to report figures and others. :param str key: name (key) of the object :param str filename: relative path to the file (relative to parent output dir) :param str anchor_text: text used as the link anchor test or caption to refer to the object. If not provided, defaults to the key. :param str anchor_image: a path to an HTML-displayable image thumbnail (so, .png or .jpg, for example). If a path, the path should be relative to the parent output dir. :param str annotation: By default, the figures will be annotated with the pipeline name, so you can tell which pipeline records which figures. If you want, you can change this. """ # Default annotation is current pipeline name. annotation = str(annotation or self.name) # In case the value is passed with trailing whitespace. filename = str(filename).strip() if anchor_text: anchor_text = str(anchor_text).strip() else: anchor_text = str(key).strip() # better to use a relative path in this file # convert any absolute paths into relative paths relative_filename = os.path.relpath(filename, self.outfolder) \ if os.path.isabs(filename) else filename if anchor_image: relative_anchor_image = os.path.relpath(anchor_image, self.outfolder) \ if os.path.isabs(anchor_image) else anchor_image else: relative_anchor_image = "None" message_raw = "{key}\t{filename}\t{anchor_text}\t{anchor_image}\t{annotation}".format( key=key, filename=relative_filename, anchor_text=anchor_text, anchor_image=relative_anchor_image, annotation=annotation) message_markdown = "> `{key}`\t{filename}\t{anchor_text}\t{anchor_image}\t{annotation}\t_OBJ_".format( key=key, filename=relative_filename, anchor_text=anchor_text, anchor_image=relative_anchor_image,annotation=annotation) print(message_markdown) self._safe_write_to_file(self.pipeline_objects_file, message_raw)
def function[report_object, parameter[self, key, filename, anchor_text, anchor_image, annotation]]: constant[ Writes a string to self.pipeline_objects_file. Used to report figures and others. :param str key: name (key) of the object :param str filename: relative path to the file (relative to parent output dir) :param str anchor_text: text used as the link anchor test or caption to refer to the object. If not provided, defaults to the key. :param str anchor_image: a path to an HTML-displayable image thumbnail (so, .png or .jpg, for example). If a path, the path should be relative to the parent output dir. :param str annotation: By default, the figures will be annotated with the pipeline name, so you can tell which pipeline records which figures. If you want, you can change this. ] variable[annotation] assign[=] call[name[str], parameter[<ast.BoolOp object at 0x7da1b032b100>]] variable[filename] assign[=] call[call[name[str], parameter[name[filename]]].strip, parameter[]] if name[anchor_text] begin[:] variable[anchor_text] assign[=] call[call[name[str], parameter[name[anchor_text]]].strip, parameter[]] variable[relative_filename] assign[=] <ast.IfExp object at 0x7da1b0328fa0> if name[anchor_image] begin[:] variable[relative_anchor_image] assign[=] <ast.IfExp object at 0x7da1b032be50> variable[message_raw] assign[=] call[constant[{key} {filename} {anchor_text} {anchor_image} {annotation}].format, parameter[]] variable[message_markdown] assign[=] call[constant[> `{key}` {filename} {anchor_text} {anchor_image} {annotation} _OBJ_].format, parameter[]] call[name[print], parameter[name[message_markdown]]] call[name[self]._safe_write_to_file, parameter[name[self].pipeline_objects_file, name[message_raw]]]
keyword[def] identifier[report_object] ( identifier[self] , identifier[key] , identifier[filename] , identifier[anchor_text] = keyword[None] , identifier[anchor_image] = keyword[None] , identifier[annotation] = keyword[None] ): literal[string] identifier[annotation] = identifier[str] ( identifier[annotation] keyword[or] identifier[self] . identifier[name] ) identifier[filename] = identifier[str] ( identifier[filename] ). identifier[strip] () keyword[if] identifier[anchor_text] : identifier[anchor_text] = identifier[str] ( identifier[anchor_text] ). identifier[strip] () keyword[else] : identifier[anchor_text] = identifier[str] ( identifier[key] ). identifier[strip] () identifier[relative_filename] = identifier[os] . identifier[path] . identifier[relpath] ( identifier[filename] , identifier[self] . identifier[outfolder] ) keyword[if] identifier[os] . identifier[path] . identifier[isabs] ( identifier[filename] ) keyword[else] identifier[filename] keyword[if] identifier[anchor_image] : identifier[relative_anchor_image] = identifier[os] . identifier[path] . identifier[relpath] ( identifier[anchor_image] , identifier[self] . identifier[outfolder] ) keyword[if] identifier[os] . identifier[path] . identifier[isabs] ( identifier[anchor_image] ) keyword[else] identifier[anchor_image] keyword[else] : identifier[relative_anchor_image] = literal[string] identifier[message_raw] = literal[string] . identifier[format] ( identifier[key] = identifier[key] , identifier[filename] = identifier[relative_filename] , identifier[anchor_text] = identifier[anchor_text] , identifier[anchor_image] = identifier[relative_anchor_image] , identifier[annotation] = identifier[annotation] ) identifier[message_markdown] = literal[string] . identifier[format] ( identifier[key] = identifier[key] , identifier[filename] = identifier[relative_filename] , identifier[anchor_text] = identifier[anchor_text] , identifier[anchor_image] = identifier[relative_anchor_image] , identifier[annotation] = identifier[annotation] ) identifier[print] ( identifier[message_markdown] ) identifier[self] . identifier[_safe_write_to_file] ( identifier[self] . identifier[pipeline_objects_file] , identifier[message_raw] )
def report_object(self, key, filename, anchor_text=None, anchor_image=None, annotation=None): """ Writes a string to self.pipeline_objects_file. Used to report figures and others. :param str key: name (key) of the object :param str filename: relative path to the file (relative to parent output dir) :param str anchor_text: text used as the link anchor test or caption to refer to the object. If not provided, defaults to the key. :param str anchor_image: a path to an HTML-displayable image thumbnail (so, .png or .jpg, for example). If a path, the path should be relative to the parent output dir. :param str annotation: By default, the figures will be annotated with the pipeline name, so you can tell which pipeline records which figures. If you want, you can change this. """ # Default annotation is current pipeline name. annotation = str(annotation or self.name) # In case the value is passed with trailing whitespace. filename = str(filename).strip() if anchor_text: anchor_text = str(anchor_text).strip() # depends on [control=['if'], data=[]] else: anchor_text = str(key).strip() # better to use a relative path in this file # convert any absolute paths into relative paths relative_filename = os.path.relpath(filename, self.outfolder) if os.path.isabs(filename) else filename if anchor_image: relative_anchor_image = os.path.relpath(anchor_image, self.outfolder) if os.path.isabs(anchor_image) else anchor_image # depends on [control=['if'], data=[]] else: relative_anchor_image = 'None' message_raw = '{key}\t{filename}\t{anchor_text}\t{anchor_image}\t{annotation}'.format(key=key, filename=relative_filename, anchor_text=anchor_text, anchor_image=relative_anchor_image, annotation=annotation) message_markdown = '> `{key}`\t{filename}\t{anchor_text}\t{anchor_image}\t{annotation}\t_OBJ_'.format(key=key, filename=relative_filename, anchor_text=anchor_text, anchor_image=relative_anchor_image, annotation=annotation) print(message_markdown) self._safe_write_to_file(self.pipeline_objects_file, message_raw)
def visit_constant(self, node, parent): """visit a Constant node by returning a fresh instance of Const""" return nodes.Const( node.value, getattr(node, "lineno", None), getattr(node, "col_offset", None), parent, )
def function[visit_constant, parameter[self, node, parent]]: constant[visit a Constant node by returning a fresh instance of Const] return[call[name[nodes].Const, parameter[name[node].value, call[name[getattr], parameter[name[node], constant[lineno], constant[None]]], call[name[getattr], parameter[name[node], constant[col_offset], constant[None]]], name[parent]]]]
keyword[def] identifier[visit_constant] ( identifier[self] , identifier[node] , identifier[parent] ): literal[string] keyword[return] identifier[nodes] . identifier[Const] ( identifier[node] . identifier[value] , identifier[getattr] ( identifier[node] , literal[string] , keyword[None] ), identifier[getattr] ( identifier[node] , literal[string] , keyword[None] ), identifier[parent] , )
def visit_constant(self, node, parent): """visit a Constant node by returning a fresh instance of Const""" return nodes.Const(node.value, getattr(node, 'lineno', None), getattr(node, 'col_offset', None), parent)
def report(self, align_bam, ref_file, is_paired, bait_file, target_file, variant_region_file, config): """Produce report metrics using Picard with sorted aligned BAM file. """ dup_metrics = self._get_current_dup_metrics(align_bam) align_metrics = self._collect_align_metrics(align_bam, ref_file) # Prefer the GC metrics in FastQC instead of Picard # gc_graph, gc_metrics = self._gc_bias(align_bam, ref_file) gc_graph = None insert_graph, insert_metrics, hybrid_metrics = (None, None, None) if is_paired: insert_graph, insert_metrics = self._insert_sizes(align_bam) if bait_file and target_file: assert os.path.exists(bait_file), (bait_file, "does not exist!") assert os.path.exists(target_file), (target_file, "does not exist!") hybrid_metrics = self._hybrid_select_metrics(align_bam, bait_file, target_file) elif (variant_region_file and config["algorithm"].get("coverage_interval", "").lower() in ["exome"]): assert os.path.exists(variant_region_file), (variant_region_file, "does not exist") hybrid_metrics = self._hybrid_select_metrics( align_bam, variant_region_file, variant_region_file) vrn_vals = self._variant_eval_metrics(align_bam) summary_info = self._parser.get_summary_metrics(align_metrics, dup_metrics, insert_metrics, hybrid_metrics, vrn_vals) graphs = [] if gc_graph and os.path.exists(gc_graph): graphs.append((gc_graph, "Distribution of GC content across reads")) if insert_graph and os.path.exists(insert_graph): graphs.append((insert_graph, "Distribution of paired end insert sizes")) return summary_info, graphs
def function[report, parameter[self, align_bam, ref_file, is_paired, bait_file, target_file, variant_region_file, config]]: constant[Produce report metrics using Picard with sorted aligned BAM file. ] variable[dup_metrics] assign[=] call[name[self]._get_current_dup_metrics, parameter[name[align_bam]]] variable[align_metrics] assign[=] call[name[self]._collect_align_metrics, parameter[name[align_bam], name[ref_file]]] variable[gc_graph] assign[=] constant[None] <ast.Tuple object at 0x7da20c6a9e10> assign[=] tuple[[<ast.Constant object at 0x7da20c6a8df0>, <ast.Constant object at 0x7da20c6aa230>, <ast.Constant object at 0x7da20c6aa020>]] if name[is_paired] begin[:] <ast.Tuple object at 0x7da20c6a8be0> assign[=] call[name[self]._insert_sizes, parameter[name[align_bam]]] if <ast.BoolOp object at 0x7da20c6a8610> begin[:] assert[call[name[os].path.exists, parameter[name[bait_file]]]] assert[call[name[os].path.exists, parameter[name[target_file]]]] variable[hybrid_metrics] assign[=] call[name[self]._hybrid_select_metrics, parameter[name[align_bam], name[bait_file], name[target_file]]] variable[vrn_vals] assign[=] call[name[self]._variant_eval_metrics, parameter[name[align_bam]]] variable[summary_info] assign[=] call[name[self]._parser.get_summary_metrics, parameter[name[align_metrics], name[dup_metrics], name[insert_metrics], name[hybrid_metrics], name[vrn_vals]]] variable[graphs] assign[=] list[[]] if <ast.BoolOp object at 0x7da20c6aaf50> begin[:] call[name[graphs].append, parameter[tuple[[<ast.Name object at 0x7da20c6a97e0>, <ast.Constant object at 0x7da20c6aa320>]]]] if <ast.BoolOp object at 0x7da20c6ab340> begin[:] call[name[graphs].append, parameter[tuple[[<ast.Name object at 0x7da20c6a98d0>, <ast.Constant object at 0x7da20c6a9840>]]]] return[tuple[[<ast.Name object at 0x7da20c6aa740>, <ast.Name object at 0x7da20c6ab010>]]]
keyword[def] identifier[report] ( identifier[self] , identifier[align_bam] , identifier[ref_file] , identifier[is_paired] , identifier[bait_file] , identifier[target_file] , identifier[variant_region_file] , identifier[config] ): literal[string] identifier[dup_metrics] = identifier[self] . identifier[_get_current_dup_metrics] ( identifier[align_bam] ) identifier[align_metrics] = identifier[self] . identifier[_collect_align_metrics] ( identifier[align_bam] , identifier[ref_file] ) identifier[gc_graph] = keyword[None] identifier[insert_graph] , identifier[insert_metrics] , identifier[hybrid_metrics] =( keyword[None] , keyword[None] , keyword[None] ) keyword[if] identifier[is_paired] : identifier[insert_graph] , identifier[insert_metrics] = identifier[self] . identifier[_insert_sizes] ( identifier[align_bam] ) keyword[if] identifier[bait_file] keyword[and] identifier[target_file] : keyword[assert] identifier[os] . identifier[path] . identifier[exists] ( identifier[bait_file] ),( identifier[bait_file] , literal[string] ) keyword[assert] identifier[os] . identifier[path] . identifier[exists] ( identifier[target_file] ),( identifier[target_file] , literal[string] ) identifier[hybrid_metrics] = identifier[self] . identifier[_hybrid_select_metrics] ( identifier[align_bam] , identifier[bait_file] , identifier[target_file] ) keyword[elif] ( identifier[variant_region_file] keyword[and] identifier[config] [ literal[string] ]. identifier[get] ( literal[string] , literal[string] ). identifier[lower] () keyword[in] [ literal[string] ]): keyword[assert] identifier[os] . identifier[path] . identifier[exists] ( identifier[variant_region_file] ),( identifier[variant_region_file] , literal[string] ) identifier[hybrid_metrics] = identifier[self] . identifier[_hybrid_select_metrics] ( identifier[align_bam] , identifier[variant_region_file] , identifier[variant_region_file] ) identifier[vrn_vals] = identifier[self] . identifier[_variant_eval_metrics] ( identifier[align_bam] ) identifier[summary_info] = identifier[self] . identifier[_parser] . identifier[get_summary_metrics] ( identifier[align_metrics] , identifier[dup_metrics] , identifier[insert_metrics] , identifier[hybrid_metrics] , identifier[vrn_vals] ) identifier[graphs] =[] keyword[if] identifier[gc_graph] keyword[and] identifier[os] . identifier[path] . identifier[exists] ( identifier[gc_graph] ): identifier[graphs] . identifier[append] (( identifier[gc_graph] , literal[string] )) keyword[if] identifier[insert_graph] keyword[and] identifier[os] . identifier[path] . identifier[exists] ( identifier[insert_graph] ): identifier[graphs] . identifier[append] (( identifier[insert_graph] , literal[string] )) keyword[return] identifier[summary_info] , identifier[graphs]
def report(self, align_bam, ref_file, is_paired, bait_file, target_file, variant_region_file, config): """Produce report metrics using Picard with sorted aligned BAM file. """ dup_metrics = self._get_current_dup_metrics(align_bam) align_metrics = self._collect_align_metrics(align_bam, ref_file) # Prefer the GC metrics in FastQC instead of Picard # gc_graph, gc_metrics = self._gc_bias(align_bam, ref_file) gc_graph = None (insert_graph, insert_metrics, hybrid_metrics) = (None, None, None) if is_paired: (insert_graph, insert_metrics) = self._insert_sizes(align_bam) # depends on [control=['if'], data=[]] if bait_file and target_file: assert os.path.exists(bait_file), (bait_file, 'does not exist!') assert os.path.exists(target_file), (target_file, 'does not exist!') hybrid_metrics = self._hybrid_select_metrics(align_bam, bait_file, target_file) # depends on [control=['if'], data=[]] elif variant_region_file and config['algorithm'].get('coverage_interval', '').lower() in ['exome']: assert os.path.exists(variant_region_file), (variant_region_file, 'does not exist') hybrid_metrics = self._hybrid_select_metrics(align_bam, variant_region_file, variant_region_file) # depends on [control=['if'], data=[]] vrn_vals = self._variant_eval_metrics(align_bam) summary_info = self._parser.get_summary_metrics(align_metrics, dup_metrics, insert_metrics, hybrid_metrics, vrn_vals) graphs = [] if gc_graph and os.path.exists(gc_graph): graphs.append((gc_graph, 'Distribution of GC content across reads')) # depends on [control=['if'], data=[]] if insert_graph and os.path.exists(insert_graph): graphs.append((insert_graph, 'Distribution of paired end insert sizes')) # depends on [control=['if'], data=[]] return (summary_info, graphs)
def dispatch(self, request, *args, **kwargs): """Adds useful objects to the class and performs security checks.""" self._add_next_and_user(request) self.content_object = None self.content_type = None self.object_id = kwargs.get('object_id', None) if kwargs.get('content_type'): # Check if the user forged the URL and posted a non existant # content type try: self.content_type = ContentType.objects.get( model=kwargs.get('content_type')) except ContentType.DoesNotExist: raise Http404 if self.content_type: # Check if the user forged the URL and tries to append the image to # an object that does not exist try: self.content_object = \ self.content_type.get_object_for_this_type( pk=self.object_id) except ObjectDoesNotExist: raise Http404 if self.content_object and hasattr(self.content_object, 'user'): # Check if the user forged the URL and tries to append the image to # an object that does not belong to him if not self.content_object.user == self.user: raise Http404 return super(CreateImageView, self).dispatch(request, *args, **kwargs)
def function[dispatch, parameter[self, request]]: constant[Adds useful objects to the class and performs security checks.] call[name[self]._add_next_and_user, parameter[name[request]]] name[self].content_object assign[=] constant[None] name[self].content_type assign[=] constant[None] name[self].object_id assign[=] call[name[kwargs].get, parameter[constant[object_id], constant[None]]] if call[name[kwargs].get, parameter[constant[content_type]]] begin[:] <ast.Try object at 0x7da1b0fd7ee0> if name[self].content_type begin[:] <ast.Try object at 0x7da1b0fd5630> if <ast.BoolOp object at 0x7da1b0fd59c0> begin[:] if <ast.UnaryOp object at 0x7da1b0fd52a0> begin[:] <ast.Raise object at 0x7da1b0fd4ca0> return[call[call[name[super], parameter[name[CreateImageView], name[self]]].dispatch, parameter[name[request], <ast.Starred object at 0x7da1b0fd7910>]]]
keyword[def] identifier[dispatch] ( identifier[self] , identifier[request] ,* identifier[args] ,** identifier[kwargs] ): literal[string] identifier[self] . identifier[_add_next_and_user] ( identifier[request] ) identifier[self] . identifier[content_object] = keyword[None] identifier[self] . identifier[content_type] = keyword[None] identifier[self] . identifier[object_id] = identifier[kwargs] . identifier[get] ( literal[string] , keyword[None] ) keyword[if] identifier[kwargs] . identifier[get] ( literal[string] ): keyword[try] : identifier[self] . identifier[content_type] = identifier[ContentType] . identifier[objects] . identifier[get] ( identifier[model] = identifier[kwargs] . identifier[get] ( literal[string] )) keyword[except] identifier[ContentType] . identifier[DoesNotExist] : keyword[raise] identifier[Http404] keyword[if] identifier[self] . identifier[content_type] : keyword[try] : identifier[self] . identifier[content_object] = identifier[self] . identifier[content_type] . identifier[get_object_for_this_type] ( identifier[pk] = identifier[self] . identifier[object_id] ) keyword[except] identifier[ObjectDoesNotExist] : keyword[raise] identifier[Http404] keyword[if] identifier[self] . identifier[content_object] keyword[and] identifier[hasattr] ( identifier[self] . identifier[content_object] , literal[string] ): keyword[if] keyword[not] identifier[self] . identifier[content_object] . identifier[user] == identifier[self] . identifier[user] : keyword[raise] identifier[Http404] keyword[return] identifier[super] ( identifier[CreateImageView] , identifier[self] ). identifier[dispatch] ( identifier[request] ,* identifier[args] ,** identifier[kwargs] )
def dispatch(self, request, *args, **kwargs): """Adds useful objects to the class and performs security checks.""" self._add_next_and_user(request) self.content_object = None self.content_type = None self.object_id = kwargs.get('object_id', None) if kwargs.get('content_type'): # Check if the user forged the URL and posted a non existant # content type try: self.content_type = ContentType.objects.get(model=kwargs.get('content_type')) # depends on [control=['try'], data=[]] except ContentType.DoesNotExist: raise Http404 # depends on [control=['except'], data=[]] # depends on [control=['if'], data=[]] if self.content_type: # Check if the user forged the URL and tries to append the image to # an object that does not exist try: self.content_object = self.content_type.get_object_for_this_type(pk=self.object_id) # depends on [control=['try'], data=[]] except ObjectDoesNotExist: raise Http404 # depends on [control=['except'], data=[]] # depends on [control=['if'], data=[]] if self.content_object and hasattr(self.content_object, 'user'): # Check if the user forged the URL and tries to append the image to # an object that does not belong to him if not self.content_object.user == self.user: raise Http404 # depends on [control=['if'], data=[]] # depends on [control=['if'], data=[]] return super(CreateImageView, self).dispatch(request, *args, **kwargs)
def _3d_in_file(in_file): ''' if self.inputs.in_file is 3d, return it. if 4d, pick an arbitrary volume and return that. if in_file is a list of files, return an arbitrary file from the list, and an arbitrary volume from that file ''' in_file = filemanip.filename_to_list(in_file)[0] try: in_file = nb.load(in_file) except AttributeError: in_file = in_file if in_file.get_data().ndim == 3: return in_file return nlimage.index_img(in_file, 0)
def function[_3d_in_file, parameter[in_file]]: constant[ if self.inputs.in_file is 3d, return it. if 4d, pick an arbitrary volume and return that. if in_file is a list of files, return an arbitrary file from the list, and an arbitrary volume from that file ] variable[in_file] assign[=] call[call[name[filemanip].filename_to_list, parameter[name[in_file]]]][constant[0]] <ast.Try object at 0x7da1b0608fa0> if compare[call[name[in_file].get_data, parameter[]].ndim equal[==] constant[3]] begin[:] return[name[in_file]] return[call[name[nlimage].index_img, parameter[name[in_file], constant[0]]]]
keyword[def] identifier[_3d_in_file] ( identifier[in_file] ): literal[string] identifier[in_file] = identifier[filemanip] . identifier[filename_to_list] ( identifier[in_file] )[ literal[int] ] keyword[try] : identifier[in_file] = identifier[nb] . identifier[load] ( identifier[in_file] ) keyword[except] identifier[AttributeError] : identifier[in_file] = identifier[in_file] keyword[if] identifier[in_file] . identifier[get_data] (). identifier[ndim] == literal[int] : keyword[return] identifier[in_file] keyword[return] identifier[nlimage] . identifier[index_img] ( identifier[in_file] , literal[int] )
def _3d_in_file(in_file): """ if self.inputs.in_file is 3d, return it. if 4d, pick an arbitrary volume and return that. if in_file is a list of files, return an arbitrary file from the list, and an arbitrary volume from that file """ in_file = filemanip.filename_to_list(in_file)[0] try: in_file = nb.load(in_file) # depends on [control=['try'], data=[]] except AttributeError: in_file = in_file # depends on [control=['except'], data=[]] if in_file.get_data().ndim == 3: return in_file # depends on [control=['if'], data=[]] return nlimage.index_img(in_file, 0)
def export_key(keyids=None, secret=False, user=None, gnupghome=None): ''' Export a key from the GPG keychain keyids The key ID(s) of the key(s) to be exported. Can be specified as a comma separated string or a list. Anything which GnuPG itself accepts to identify a key - for example, the key ID or the fingerprint could be used. secret Export the secret key identified by the ``keyids`` information passed. user Which user's keychain to access, defaults to user Salt is running as. Passing the user as ``salt`` will set the GnuPG home directory to the ``/etc/salt/gpgkeys``. gnupghome Specify the location where GPG keyring and related files are stored. CLI Example: .. code-block:: bash salt '*' gpg.export_key keyids=3FAD9F1E salt '*' gpg.export_key keyids=3FAD9F1E secret=True salt '*' gpg.export_key keyids="['3FAD9F1E','3FBD8F1E']" user=username ''' gpg = _create_gpg(user, gnupghome) if isinstance(keyids, six.string_types): keyids = keyids.split(',') return gpg.export_keys(keyids, secret)
def function[export_key, parameter[keyids, secret, user, gnupghome]]: constant[ Export a key from the GPG keychain keyids The key ID(s) of the key(s) to be exported. Can be specified as a comma separated string or a list. Anything which GnuPG itself accepts to identify a key - for example, the key ID or the fingerprint could be used. secret Export the secret key identified by the ``keyids`` information passed. user Which user's keychain to access, defaults to user Salt is running as. Passing the user as ``salt`` will set the GnuPG home directory to the ``/etc/salt/gpgkeys``. gnupghome Specify the location where GPG keyring and related files are stored. CLI Example: .. code-block:: bash salt '*' gpg.export_key keyids=3FAD9F1E salt '*' gpg.export_key keyids=3FAD9F1E secret=True salt '*' gpg.export_key keyids="['3FAD9F1E','3FBD8F1E']" user=username ] variable[gpg] assign[=] call[name[_create_gpg], parameter[name[user], name[gnupghome]]] if call[name[isinstance], parameter[name[keyids], name[six].string_types]] begin[:] variable[keyids] assign[=] call[name[keyids].split, parameter[constant[,]]] return[call[name[gpg].export_keys, parameter[name[keyids], name[secret]]]]
keyword[def] identifier[export_key] ( identifier[keyids] = keyword[None] , identifier[secret] = keyword[False] , identifier[user] = keyword[None] , identifier[gnupghome] = keyword[None] ): literal[string] identifier[gpg] = identifier[_create_gpg] ( identifier[user] , identifier[gnupghome] ) keyword[if] identifier[isinstance] ( identifier[keyids] , identifier[six] . identifier[string_types] ): identifier[keyids] = identifier[keyids] . identifier[split] ( literal[string] ) keyword[return] identifier[gpg] . identifier[export_keys] ( identifier[keyids] , identifier[secret] )
def export_key(keyids=None, secret=False, user=None, gnupghome=None): """ Export a key from the GPG keychain keyids The key ID(s) of the key(s) to be exported. Can be specified as a comma separated string or a list. Anything which GnuPG itself accepts to identify a key - for example, the key ID or the fingerprint could be used. secret Export the secret key identified by the ``keyids`` information passed. user Which user's keychain to access, defaults to user Salt is running as. Passing the user as ``salt`` will set the GnuPG home directory to the ``/etc/salt/gpgkeys``. gnupghome Specify the location where GPG keyring and related files are stored. CLI Example: .. code-block:: bash salt '*' gpg.export_key keyids=3FAD9F1E salt '*' gpg.export_key keyids=3FAD9F1E secret=True salt '*' gpg.export_key keyids="['3FAD9F1E','3FBD8F1E']" user=username """ gpg = _create_gpg(user, gnupghome) if isinstance(keyids, six.string_types): keyids = keyids.split(',') # depends on [control=['if'], data=[]] return gpg.export_keys(keyids, secret)
def _setup_progIsTrack(self): """If progIsTrack, the progenitor orbit that was passed to the streamdf initialization is the track at zero angle separation; this routine computes an actual progenitor position that gives the desired track given the parameters of the streamdf""" # We need to flip the sign of the offset, to go to the progenitor self._sigMeanSign*= -1. # Use _determine_stream_track_single to calculate the track-progenitor # offset at zero angle separation prog_stream_offset=\ _determine_stream_track_single(self._aA, self._progenitor, 0., #time = 0 self._progenitor_angle, self._sigMeanSign, self._dsigomeanProgDirection, lambda x: self.meanOmega(x,use_physical=False), 0.) #angle = 0 # Setup the new progenitor orbit progenitor= Orbit(prog_stream_offset[3]) # Flip the offset sign again self._sigMeanSign*= -1. # Now re-do the previous setup self._progenitor_setup(progenitor,self._leading,False) self._offset_setup(self._sigangle,self._leading, self._deltaAngleTrack) return None
def function[_setup_progIsTrack, parameter[self]]: constant[If progIsTrack, the progenitor orbit that was passed to the streamdf initialization is the track at zero angle separation; this routine computes an actual progenitor position that gives the desired track given the parameters of the streamdf] <ast.AugAssign object at 0x7da1b0c96320> variable[prog_stream_offset] assign[=] call[name[_determine_stream_track_single], parameter[name[self]._aA, name[self]._progenitor, constant[0.0], name[self]._progenitor_angle, name[self]._sigMeanSign, name[self]._dsigomeanProgDirection, <ast.Lambda object at 0x7da1b0c966e0>, constant[0.0]]] variable[progenitor] assign[=] call[name[Orbit], parameter[call[name[prog_stream_offset]][constant[3]]]] <ast.AugAssign object at 0x7da1b0c96a10> call[name[self]._progenitor_setup, parameter[name[progenitor], name[self]._leading, constant[False]]] call[name[self]._offset_setup, parameter[name[self]._sigangle, name[self]._leading, name[self]._deltaAngleTrack]] return[constant[None]]
keyword[def] identifier[_setup_progIsTrack] ( identifier[self] ): literal[string] identifier[self] . identifier[_sigMeanSign] *=- literal[int] identifier[prog_stream_offset] = identifier[_determine_stream_track_single] ( identifier[self] . identifier[_aA] , identifier[self] . identifier[_progenitor] , literal[int] , identifier[self] . identifier[_progenitor_angle] , identifier[self] . identifier[_sigMeanSign] , identifier[self] . identifier[_dsigomeanProgDirection] , keyword[lambda] identifier[x] : identifier[self] . identifier[meanOmega] ( identifier[x] , identifier[use_physical] = keyword[False] ), literal[int] ) identifier[progenitor] = identifier[Orbit] ( identifier[prog_stream_offset] [ literal[int] ]) identifier[self] . identifier[_sigMeanSign] *=- literal[int] identifier[self] . identifier[_progenitor_setup] ( identifier[progenitor] , identifier[self] . identifier[_leading] , keyword[False] ) identifier[self] . identifier[_offset_setup] ( identifier[self] . identifier[_sigangle] , identifier[self] . identifier[_leading] , identifier[self] . identifier[_deltaAngleTrack] ) keyword[return] keyword[None]
def _setup_progIsTrack(self): """If progIsTrack, the progenitor orbit that was passed to the streamdf initialization is the track at zero angle separation; this routine computes an actual progenitor position that gives the desired track given the parameters of the streamdf""" # We need to flip the sign of the offset, to go to the progenitor self._sigMeanSign *= -1.0 # Use _determine_stream_track_single to calculate the track-progenitor # offset at zero angle separation #time = 0 prog_stream_offset = _determine_stream_track_single(self._aA, self._progenitor, 0.0, self._progenitor_angle, self._sigMeanSign, self._dsigomeanProgDirection, lambda x: self.meanOmega(x, use_physical=False), 0.0) #angle = 0 # Setup the new progenitor orbit progenitor = Orbit(prog_stream_offset[3]) # Flip the offset sign again self._sigMeanSign *= -1.0 # Now re-do the previous setup self._progenitor_setup(progenitor, self._leading, False) self._offset_setup(self._sigangle, self._leading, self._deltaAngleTrack) return None
def Dir(self, name, create=True): """ Looks up or creates a directory node named 'name' relative to this directory. """ return self.fs.Dir(name, self, create)
def function[Dir, parameter[self, name, create]]: constant[ Looks up or creates a directory node named 'name' relative to this directory. ] return[call[name[self].fs.Dir, parameter[name[name], name[self], name[create]]]]
keyword[def] identifier[Dir] ( identifier[self] , identifier[name] , identifier[create] = keyword[True] ): literal[string] keyword[return] identifier[self] . identifier[fs] . identifier[Dir] ( identifier[name] , identifier[self] , identifier[create] )
def Dir(self, name, create=True): """ Looks up or creates a directory node named 'name' relative to this directory. """ return self.fs.Dir(name, self, create)
def get_keys(self, keymap): """Extract keys pressed from transformed keymap""" keys = dict(modifiers=[], regular=[]) # loop on keymap bytes for keymap_index, keymap_byte in enumerate(keymap): try: keymap_values = self._keymap_values_dict[keymap_index] except KeyError: continue # loop on keymap_values for that keymap byte for key, value in keymap_values.items(): if not keymap_byte & key: continue elif value in self._modifiers: keys['modifiers'].append(value) elif not keys['regular']: keys['regular'].append(value) return keys
def function[get_keys, parameter[self, keymap]]: constant[Extract keys pressed from transformed keymap] variable[keys] assign[=] call[name[dict], parameter[]] for taget[tuple[[<ast.Name object at 0x7da18f7234c0>, <ast.Name object at 0x7da18f720a60>]]] in starred[call[name[enumerate], parameter[name[keymap]]]] begin[:] <ast.Try object at 0x7da18f7202b0> for taget[tuple[[<ast.Name object at 0x7da18f721330>, <ast.Name object at 0x7da18f720bb0>]]] in starred[call[name[keymap_values].items, parameter[]]] begin[:] if <ast.UnaryOp object at 0x7da18f721b70> begin[:] continue return[name[keys]]
keyword[def] identifier[get_keys] ( identifier[self] , identifier[keymap] ): literal[string] identifier[keys] = identifier[dict] ( identifier[modifiers] =[], identifier[regular] =[]) keyword[for] identifier[keymap_index] , identifier[keymap_byte] keyword[in] identifier[enumerate] ( identifier[keymap] ): keyword[try] : identifier[keymap_values] = identifier[self] . identifier[_keymap_values_dict] [ identifier[keymap_index] ] keyword[except] identifier[KeyError] : keyword[continue] keyword[for] identifier[key] , identifier[value] keyword[in] identifier[keymap_values] . identifier[items] (): keyword[if] keyword[not] identifier[keymap_byte] & identifier[key] : keyword[continue] keyword[elif] identifier[value] keyword[in] identifier[self] . identifier[_modifiers] : identifier[keys] [ literal[string] ]. identifier[append] ( identifier[value] ) keyword[elif] keyword[not] identifier[keys] [ literal[string] ]: identifier[keys] [ literal[string] ]. identifier[append] ( identifier[value] ) keyword[return] identifier[keys]
def get_keys(self, keymap): """Extract keys pressed from transformed keymap""" keys = dict(modifiers=[], regular=[]) # loop on keymap bytes for (keymap_index, keymap_byte) in enumerate(keymap): try: keymap_values = self._keymap_values_dict[keymap_index] # depends on [control=['try'], data=[]] except KeyError: continue # depends on [control=['except'], data=[]] # loop on keymap_values for that keymap byte for (key, value) in keymap_values.items(): if not keymap_byte & key: continue # depends on [control=['if'], data=[]] elif value in self._modifiers: keys['modifiers'].append(value) # depends on [control=['if'], data=['value']] elif not keys['regular']: keys['regular'].append(value) # depends on [control=['if'], data=[]] # depends on [control=['for'], data=[]] # depends on [control=['for'], data=[]] return keys
def append_sint32(self, value): """Appends a 32-bit integer to our buffer, zigzag-encoded and then varint-encoded. """ zigzag_value = wire_format.zig_zag_encode(value) self._stream.append_var_uint32(zigzag_value)
def function[append_sint32, parameter[self, value]]: constant[Appends a 32-bit integer to our buffer, zigzag-encoded and then varint-encoded. ] variable[zigzag_value] assign[=] call[name[wire_format].zig_zag_encode, parameter[name[value]]] call[name[self]._stream.append_var_uint32, parameter[name[zigzag_value]]]
keyword[def] identifier[append_sint32] ( identifier[self] , identifier[value] ): literal[string] identifier[zigzag_value] = identifier[wire_format] . identifier[zig_zag_encode] ( identifier[value] ) identifier[self] . identifier[_stream] . identifier[append_var_uint32] ( identifier[zigzag_value] )
def append_sint32(self, value): """Appends a 32-bit integer to our buffer, zigzag-encoded and then varint-encoded. """ zigzag_value = wire_format.zig_zag_encode(value) self._stream.append_var_uint32(zigzag_value)
def find(self, chrom, start, end): """find the intersecting elements :param chrom: chromosome :param start: start :param end: end :return: a list of intersecting elements""" tree = self._trees.get( chrom, None ) if tree: return tree.find( start, end ) #return always a list return []
def function[find, parameter[self, chrom, start, end]]: constant[find the intersecting elements :param chrom: chromosome :param start: start :param end: end :return: a list of intersecting elements] variable[tree] assign[=] call[name[self]._trees.get, parameter[name[chrom], constant[None]]] if name[tree] begin[:] return[call[name[tree].find, parameter[name[start], name[end]]]] return[list[[]]]
keyword[def] identifier[find] ( identifier[self] , identifier[chrom] , identifier[start] , identifier[end] ): literal[string] identifier[tree] = identifier[self] . identifier[_trees] . identifier[get] ( identifier[chrom] , keyword[None] ) keyword[if] identifier[tree] : keyword[return] identifier[tree] . identifier[find] ( identifier[start] , identifier[end] ) keyword[return] []
def find(self, chrom, start, end): """find the intersecting elements :param chrom: chromosome :param start: start :param end: end :return: a list of intersecting elements""" tree = self._trees.get(chrom, None) if tree: return tree.find(start, end) # depends on [control=['if'], data=[]] #return always a list return []
def killall(self, wait = None): """ Kill all active workers. @wait: Seconds to wait until last worker ends. If None it waits forever. """ with self.tasks.mutex: self.tasks.queue.clear() self.count_lock.acquire() self.kill(self.workers) self.count_lock.release() self.kill_event.wait(wait)
def function[killall, parameter[self, wait]]: constant[ Kill all active workers. @wait: Seconds to wait until last worker ends. If None it waits forever. ] with name[self].tasks.mutex begin[:] call[name[self].tasks.queue.clear, parameter[]] call[name[self].count_lock.acquire, parameter[]] call[name[self].kill, parameter[name[self].workers]] call[name[self].count_lock.release, parameter[]] call[name[self].kill_event.wait, parameter[name[wait]]]
keyword[def] identifier[killall] ( identifier[self] , identifier[wait] = keyword[None] ): literal[string] keyword[with] identifier[self] . identifier[tasks] . identifier[mutex] : identifier[self] . identifier[tasks] . identifier[queue] . identifier[clear] () identifier[self] . identifier[count_lock] . identifier[acquire] () identifier[self] . identifier[kill] ( identifier[self] . identifier[workers] ) identifier[self] . identifier[count_lock] . identifier[release] () identifier[self] . identifier[kill_event] . identifier[wait] ( identifier[wait] )
def killall(self, wait=None): """ Kill all active workers. @wait: Seconds to wait until last worker ends. If None it waits forever. """ with self.tasks.mutex: self.tasks.queue.clear() # depends on [control=['with'], data=[]] self.count_lock.acquire() self.kill(self.workers) self.count_lock.release() self.kill_event.wait(wait)
def _do_validate_resourcescenario(resourcescenario, template_id=None): """ Perform a check to ensure a resource scenario's datasets are correct given what the definition of that resource (its type) specifies. """ res = resourcescenario.resourceattr.get_resource() types = res.types dataset = resourcescenario.dataset if len(types) == 0: return if template_id is not None: if template_id not in [r.templatetype.template_id for r in res.types]: raise HydraError("Template %s is not used for resource attribute %s in scenario %s"%\ (template_id, resourcescenario.resourceattr.attr.name, resourcescenario.scenario.name)) #Validate against all the types for the resource for resourcetype in types: #If a specific type has been specified, then only validate #against that type and ignore all the others if template_id is not None: if resourcetype.templatetype.template_id != template_id: continue #Identify the template types for the template tmpltype = resourcetype.templatetype for ta in tmpltype.typeattrs: #If we find a template type which mactches the current attribute. #we can do some validation. if ta.attr_id == resourcescenario.resourceattr.attr_id: if ta.data_restriction: log.debug("Validating against %s", ta.data_restriction) validation_dict = eval(ta.data_restriction) dataset_util.validate_value(validation_dict, dataset.get_val())
def function[_do_validate_resourcescenario, parameter[resourcescenario, template_id]]: constant[ Perform a check to ensure a resource scenario's datasets are correct given what the definition of that resource (its type) specifies. ] variable[res] assign[=] call[name[resourcescenario].resourceattr.get_resource, parameter[]] variable[types] assign[=] name[res].types variable[dataset] assign[=] name[resourcescenario].dataset if compare[call[name[len], parameter[name[types]]] equal[==] constant[0]] begin[:] return[None] if compare[name[template_id] is_not constant[None]] begin[:] if compare[name[template_id] <ast.NotIn object at 0x7da2590d7190> <ast.ListComp object at 0x7da20cabc7c0>] begin[:] <ast.Raise object at 0x7da20cabdbd0> for taget[name[resourcetype]] in starred[name[types]] begin[:] if compare[name[template_id] is_not constant[None]] begin[:] if compare[name[resourcetype].templatetype.template_id not_equal[!=] name[template_id]] begin[:] continue variable[tmpltype] assign[=] name[resourcetype].templatetype for taget[name[ta]] in starred[name[tmpltype].typeattrs] begin[:] if compare[name[ta].attr_id equal[==] name[resourcescenario].resourceattr.attr_id] begin[:] if name[ta].data_restriction begin[:] call[name[log].debug, parameter[constant[Validating against %s], name[ta].data_restriction]] variable[validation_dict] assign[=] call[name[eval], parameter[name[ta].data_restriction]] call[name[dataset_util].validate_value, parameter[name[validation_dict], call[name[dataset].get_val, parameter[]]]]
keyword[def] identifier[_do_validate_resourcescenario] ( identifier[resourcescenario] , identifier[template_id] = keyword[None] ): literal[string] identifier[res] = identifier[resourcescenario] . identifier[resourceattr] . identifier[get_resource] () identifier[types] = identifier[res] . identifier[types] identifier[dataset] = identifier[resourcescenario] . identifier[dataset] keyword[if] identifier[len] ( identifier[types] )== literal[int] : keyword[return] keyword[if] identifier[template_id] keyword[is] keyword[not] keyword[None] : keyword[if] identifier[template_id] keyword[not] keyword[in] [ identifier[r] . identifier[templatetype] . identifier[template_id] keyword[for] identifier[r] keyword[in] identifier[res] . identifier[types] ]: keyword[raise] identifier[HydraError] ( literal[string] %( identifier[template_id] , identifier[resourcescenario] . identifier[resourceattr] . identifier[attr] . identifier[name] , identifier[resourcescenario] . identifier[scenario] . identifier[name] )) keyword[for] identifier[resourcetype] keyword[in] identifier[types] : keyword[if] identifier[template_id] keyword[is] keyword[not] keyword[None] : keyword[if] identifier[resourcetype] . identifier[templatetype] . identifier[template_id] != identifier[template_id] : keyword[continue] identifier[tmpltype] = identifier[resourcetype] . identifier[templatetype] keyword[for] identifier[ta] keyword[in] identifier[tmpltype] . identifier[typeattrs] : keyword[if] identifier[ta] . identifier[attr_id] == identifier[resourcescenario] . identifier[resourceattr] . identifier[attr_id] : keyword[if] identifier[ta] . identifier[data_restriction] : identifier[log] . identifier[debug] ( literal[string] , identifier[ta] . identifier[data_restriction] ) identifier[validation_dict] = identifier[eval] ( identifier[ta] . identifier[data_restriction] ) identifier[dataset_util] . identifier[validate_value] ( identifier[validation_dict] , identifier[dataset] . identifier[get_val] ())
def _do_validate_resourcescenario(resourcescenario, template_id=None): """ Perform a check to ensure a resource scenario's datasets are correct given what the definition of that resource (its type) specifies. """ res = resourcescenario.resourceattr.get_resource() types = res.types dataset = resourcescenario.dataset if len(types) == 0: return # depends on [control=['if'], data=[]] if template_id is not None: if template_id not in [r.templatetype.template_id for r in res.types]: raise HydraError('Template %s is not used for resource attribute %s in scenario %s' % (template_id, resourcescenario.resourceattr.attr.name, resourcescenario.scenario.name)) # depends on [control=['if'], data=['template_id']] # depends on [control=['if'], data=['template_id']] #Validate against all the types for the resource for resourcetype in types: #If a specific type has been specified, then only validate #against that type and ignore all the others if template_id is not None: if resourcetype.templatetype.template_id != template_id: continue # depends on [control=['if'], data=[]] # depends on [control=['if'], data=['template_id']] #Identify the template types for the template tmpltype = resourcetype.templatetype for ta in tmpltype.typeattrs: #If we find a template type which mactches the current attribute. #we can do some validation. if ta.attr_id == resourcescenario.resourceattr.attr_id: if ta.data_restriction: log.debug('Validating against %s', ta.data_restriction) validation_dict = eval(ta.data_restriction) dataset_util.validate_value(validation_dict, dataset.get_val()) # depends on [control=['if'], data=[]] # depends on [control=['if'], data=[]] # depends on [control=['for'], data=['ta']] # depends on [control=['for'], data=['resourcetype']]
def init_language_data(self, lang, lang_data_type): """ Initialize language data store :param lang: language code :param lang_data_type: 'label', 'description' or 'aliases' :return: None """ if lang not in self.loaded_langs: self.loaded_langs[lang] = {} if lang_data_type not in self.loaded_langs[lang]: result = self._query_lang(lang=lang, lang_data_type=lang_data_type) data = self._process_lang(result) self.loaded_langs[lang].update({lang_data_type: data})
def function[init_language_data, parameter[self, lang, lang_data_type]]: constant[ Initialize language data store :param lang: language code :param lang_data_type: 'label', 'description' or 'aliases' :return: None ] if compare[name[lang] <ast.NotIn object at 0x7da2590d7190> name[self].loaded_langs] begin[:] call[name[self].loaded_langs][name[lang]] assign[=] dictionary[[], []] if compare[name[lang_data_type] <ast.NotIn object at 0x7da2590d7190> call[name[self].loaded_langs][name[lang]]] begin[:] variable[result] assign[=] call[name[self]._query_lang, parameter[]] variable[data] assign[=] call[name[self]._process_lang, parameter[name[result]]] call[call[name[self].loaded_langs][name[lang]].update, parameter[dictionary[[<ast.Name object at 0x7da18dc05210>], [<ast.Name object at 0x7da18dc058d0>]]]]
keyword[def] identifier[init_language_data] ( identifier[self] , identifier[lang] , identifier[lang_data_type] ): literal[string] keyword[if] identifier[lang] keyword[not] keyword[in] identifier[self] . identifier[loaded_langs] : identifier[self] . identifier[loaded_langs] [ identifier[lang] ]={} keyword[if] identifier[lang_data_type] keyword[not] keyword[in] identifier[self] . identifier[loaded_langs] [ identifier[lang] ]: identifier[result] = identifier[self] . identifier[_query_lang] ( identifier[lang] = identifier[lang] , identifier[lang_data_type] = identifier[lang_data_type] ) identifier[data] = identifier[self] . identifier[_process_lang] ( identifier[result] ) identifier[self] . identifier[loaded_langs] [ identifier[lang] ]. identifier[update] ({ identifier[lang_data_type] : identifier[data] })
def init_language_data(self, lang, lang_data_type): """ Initialize language data store :param lang: language code :param lang_data_type: 'label', 'description' or 'aliases' :return: None """ if lang not in self.loaded_langs: self.loaded_langs[lang] = {} # depends on [control=['if'], data=['lang']] if lang_data_type not in self.loaded_langs[lang]: result = self._query_lang(lang=lang, lang_data_type=lang_data_type) data = self._process_lang(result) self.loaded_langs[lang].update({lang_data_type: data}) # depends on [control=['if'], data=['lang_data_type']]
def append(self, row_dict): """Add a row to the spreadsheet, returns the new row""" # TODO validate row_dict.keys() match # TODO check self.is_authed entry = self.client.InsertRow(row_dict, self.key, self.worksheet) self.feed.entry.append(entry) return GDataRow(entry, sheet=self, deferred_save=self.deferred_save)
def function[append, parameter[self, row_dict]]: constant[Add a row to the spreadsheet, returns the new row] variable[entry] assign[=] call[name[self].client.InsertRow, parameter[name[row_dict], name[self].key, name[self].worksheet]] call[name[self].feed.entry.append, parameter[name[entry]]] return[call[name[GDataRow], parameter[name[entry]]]]
keyword[def] identifier[append] ( identifier[self] , identifier[row_dict] ): literal[string] identifier[entry] = identifier[self] . identifier[client] . identifier[InsertRow] ( identifier[row_dict] , identifier[self] . identifier[key] , identifier[self] . identifier[worksheet] ) identifier[self] . identifier[feed] . identifier[entry] . identifier[append] ( identifier[entry] ) keyword[return] identifier[GDataRow] ( identifier[entry] , identifier[sheet] = identifier[self] , identifier[deferred_save] = identifier[self] . identifier[deferred_save] )
def append(self, row_dict): """Add a row to the spreadsheet, returns the new row""" # TODO validate row_dict.keys() match # TODO check self.is_authed entry = self.client.InsertRow(row_dict, self.key, self.worksheet) self.feed.entry.append(entry) return GDataRow(entry, sheet=self, deferred_save=self.deferred_save)
def get_json_body(self, required=None, validators=None): """Get JSON from the request body :param required: optionally provide a list of keys that should be in the JSON body (raises a 400 HTTPError if any are missing) :param validator: optionally provide a dictionary of items that should be in the body with a method that validates the item. The method must be synchronous and return a boolean, no exceptions. :raises: HTTPError """ content_type = self.request.headers.get('Content-Type', 'application/json') if 'application/json' not in content_type.split(';'): raise HTTPError(415, 'Content-Type should be application/json') if not self.request.body: error = 'Request body is empty' logging.warning(error) raise HTTPError(400, error) try: body = json.loads(self.request.body) except (ValueError, TypeError): error = 'Error parsing JSON' logging.warning(error) raise HTTPError(400, error) if required: _check_required(body, required) if validators: _validate(body, validators) return body
def function[get_json_body, parameter[self, required, validators]]: constant[Get JSON from the request body :param required: optionally provide a list of keys that should be in the JSON body (raises a 400 HTTPError if any are missing) :param validator: optionally provide a dictionary of items that should be in the body with a method that validates the item. The method must be synchronous and return a boolean, no exceptions. :raises: HTTPError ] variable[content_type] assign[=] call[name[self].request.headers.get, parameter[constant[Content-Type], constant[application/json]]] if compare[constant[application/json] <ast.NotIn object at 0x7da2590d7190> call[name[content_type].split, parameter[constant[;]]]] begin[:] <ast.Raise object at 0x7da18bc706a0> if <ast.UnaryOp object at 0x7da18f7207f0> begin[:] variable[error] assign[=] constant[Request body is empty] call[name[logging].warning, parameter[name[error]]] <ast.Raise object at 0x7da18f722fb0> <ast.Try object at 0x7da18fe90160> if name[required] begin[:] call[name[_check_required], parameter[name[body], name[required]]] if name[validators] begin[:] call[name[_validate], parameter[name[body], name[validators]]] return[name[body]]
keyword[def] identifier[get_json_body] ( identifier[self] , identifier[required] = keyword[None] , identifier[validators] = keyword[None] ): literal[string] identifier[content_type] = identifier[self] . identifier[request] . identifier[headers] . identifier[get] ( literal[string] , literal[string] ) keyword[if] literal[string] keyword[not] keyword[in] identifier[content_type] . identifier[split] ( literal[string] ): keyword[raise] identifier[HTTPError] ( literal[int] , literal[string] ) keyword[if] keyword[not] identifier[self] . identifier[request] . identifier[body] : identifier[error] = literal[string] identifier[logging] . identifier[warning] ( identifier[error] ) keyword[raise] identifier[HTTPError] ( literal[int] , identifier[error] ) keyword[try] : identifier[body] = identifier[json] . identifier[loads] ( identifier[self] . identifier[request] . identifier[body] ) keyword[except] ( identifier[ValueError] , identifier[TypeError] ): identifier[error] = literal[string] identifier[logging] . identifier[warning] ( identifier[error] ) keyword[raise] identifier[HTTPError] ( literal[int] , identifier[error] ) keyword[if] identifier[required] : identifier[_check_required] ( identifier[body] , identifier[required] ) keyword[if] identifier[validators] : identifier[_validate] ( identifier[body] , identifier[validators] ) keyword[return] identifier[body]
def get_json_body(self, required=None, validators=None): """Get JSON from the request body :param required: optionally provide a list of keys that should be in the JSON body (raises a 400 HTTPError if any are missing) :param validator: optionally provide a dictionary of items that should be in the body with a method that validates the item. The method must be synchronous and return a boolean, no exceptions. :raises: HTTPError """ content_type = self.request.headers.get('Content-Type', 'application/json') if 'application/json' not in content_type.split(';'): raise HTTPError(415, 'Content-Type should be application/json') # depends on [control=['if'], data=[]] if not self.request.body: error = 'Request body is empty' logging.warning(error) raise HTTPError(400, error) # depends on [control=['if'], data=[]] try: body = json.loads(self.request.body) # depends on [control=['try'], data=[]] except (ValueError, TypeError): error = 'Error parsing JSON' logging.warning(error) raise HTTPError(400, error) # depends on [control=['except'], data=[]] if required: _check_required(body, required) # depends on [control=['if'], data=[]] if validators: _validate(body, validators) # depends on [control=['if'], data=[]] return body
def get_title(self, obj): """Set search entry title for object""" search_title = self.get_model_config_value(obj, 'search_title') if not search_title: return super().get_title(obj) return search_title.format(**obj.__dict__)
def function[get_title, parameter[self, obj]]: constant[Set search entry title for object] variable[search_title] assign[=] call[name[self].get_model_config_value, parameter[name[obj], constant[search_title]]] if <ast.UnaryOp object at 0x7da20c7c9450> begin[:] return[call[call[name[super], parameter[]].get_title, parameter[name[obj]]]] return[call[name[search_title].format, parameter[]]]
keyword[def] identifier[get_title] ( identifier[self] , identifier[obj] ): literal[string] identifier[search_title] = identifier[self] . identifier[get_model_config_value] ( identifier[obj] , literal[string] ) keyword[if] keyword[not] identifier[search_title] : keyword[return] identifier[super] (). identifier[get_title] ( identifier[obj] ) keyword[return] identifier[search_title] . identifier[format] (** identifier[obj] . identifier[__dict__] )
def get_title(self, obj): """Set search entry title for object""" search_title = self.get_model_config_value(obj, 'search_title') if not search_title: return super().get_title(obj) # depends on [control=['if'], data=[]] return search_title.format(**obj.__dict__)
def filter_float(n: Node, query: str) -> float: """ Filter and ensure that the returned value is of type int. """ return _scalariter2item(n, query, float)
def function[filter_float, parameter[n, query]]: constant[ Filter and ensure that the returned value is of type int. ] return[call[name[_scalariter2item], parameter[name[n], name[query], name[float]]]]
keyword[def] identifier[filter_float] ( identifier[n] : identifier[Node] , identifier[query] : identifier[str] )-> identifier[float] : literal[string] keyword[return] identifier[_scalariter2item] ( identifier[n] , identifier[query] , identifier[float] )
def filter_float(n: Node, query: str) -> float: """ Filter and ensure that the returned value is of type int. """ return _scalariter2item(n, query, float)
def DSP_callback_toc(self): """ Add new toc time to the DSP_toc list. Will not be called if Tcapture = 0. """ if self.Tcapture > 0: self.DSP_toc.append(time.time()-self.start_time)
def function[DSP_callback_toc, parameter[self]]: constant[ Add new toc time to the DSP_toc list. Will not be called if Tcapture = 0. ] if compare[name[self].Tcapture greater[>] constant[0]] begin[:] call[name[self].DSP_toc.append, parameter[binary_operation[call[name[time].time, parameter[]] - name[self].start_time]]]
keyword[def] identifier[DSP_callback_toc] ( identifier[self] ): literal[string] keyword[if] identifier[self] . identifier[Tcapture] > literal[int] : identifier[self] . identifier[DSP_toc] . identifier[append] ( identifier[time] . identifier[time] ()- identifier[self] . identifier[start_time] )
def DSP_callback_toc(self): """ Add new toc time to the DSP_toc list. Will not be called if Tcapture = 0. """ if self.Tcapture > 0: self.DSP_toc.append(time.time() - self.start_time) # depends on [control=['if'], data=[]]
def attention(query: torch.Tensor, key: torch.Tensor, value: torch.Tensor, mask: torch.Tensor = None, dropout: Callable = None) -> Tuple[torch.Tensor, torch.Tensor]: """Compute 'Scaled Dot Product Attention'""" d_k = query.size(-1) scores = torch.matmul(query, key.transpose(-2, -1)) / math.sqrt(d_k) if mask is not None: scores = scores.masked_fill(mask == 0, -1e9) p_attn = F.softmax(scores, dim=-1) if dropout is not None: p_attn = dropout(p_attn) return torch.matmul(p_attn, value), p_attn
def function[attention, parameter[query, key, value, mask, dropout]]: constant[Compute 'Scaled Dot Product Attention'] variable[d_k] assign[=] call[name[query].size, parameter[<ast.UnaryOp object at 0x7da20c991ea0>]] variable[scores] assign[=] binary_operation[call[name[torch].matmul, parameter[name[query], call[name[key].transpose, parameter[<ast.UnaryOp object at 0x7da20c9923b0>, <ast.UnaryOp object at 0x7da20c992650>]]]] / call[name[math].sqrt, parameter[name[d_k]]]] if compare[name[mask] is_not constant[None]] begin[:] variable[scores] assign[=] call[name[scores].masked_fill, parameter[compare[name[mask] equal[==] constant[0]], <ast.UnaryOp object at 0x7da204346ec0>]] variable[p_attn] assign[=] call[name[F].softmax, parameter[name[scores]]] if compare[name[dropout] is_not constant[None]] begin[:] variable[p_attn] assign[=] call[name[dropout], parameter[name[p_attn]]] return[tuple[[<ast.Call object at 0x7da20c992680>, <ast.Name object at 0x7da20c9931f0>]]]
keyword[def] identifier[attention] ( identifier[query] : identifier[torch] . identifier[Tensor] , identifier[key] : identifier[torch] . identifier[Tensor] , identifier[value] : identifier[torch] . identifier[Tensor] , identifier[mask] : identifier[torch] . identifier[Tensor] = keyword[None] , identifier[dropout] : identifier[Callable] = keyword[None] )-> identifier[Tuple] [ identifier[torch] . identifier[Tensor] , identifier[torch] . identifier[Tensor] ]: literal[string] identifier[d_k] = identifier[query] . identifier[size] (- literal[int] ) identifier[scores] = identifier[torch] . identifier[matmul] ( identifier[query] , identifier[key] . identifier[transpose] (- literal[int] ,- literal[int] ))/ identifier[math] . identifier[sqrt] ( identifier[d_k] ) keyword[if] identifier[mask] keyword[is] keyword[not] keyword[None] : identifier[scores] = identifier[scores] . identifier[masked_fill] ( identifier[mask] == literal[int] ,- literal[int] ) identifier[p_attn] = identifier[F] . identifier[softmax] ( identifier[scores] , identifier[dim] =- literal[int] ) keyword[if] identifier[dropout] keyword[is] keyword[not] keyword[None] : identifier[p_attn] = identifier[dropout] ( identifier[p_attn] ) keyword[return] identifier[torch] . identifier[matmul] ( identifier[p_attn] , identifier[value] ), identifier[p_attn]
def attention(query: torch.Tensor, key: torch.Tensor, value: torch.Tensor, mask: torch.Tensor=None, dropout: Callable=None) -> Tuple[torch.Tensor, torch.Tensor]: """Compute 'Scaled Dot Product Attention'""" d_k = query.size(-1) scores = torch.matmul(query, key.transpose(-2, -1)) / math.sqrt(d_k) if mask is not None: scores = scores.masked_fill(mask == 0, -1000000000.0) # depends on [control=['if'], data=['mask']] p_attn = F.softmax(scores, dim=-1) if dropout is not None: p_attn = dropout(p_attn) # depends on [control=['if'], data=['dropout']] return (torch.matmul(p_attn, value), p_attn)
def has_site_permission(user): """ Checks if a staff user has staff-level access for the current site. The actual permission lookup occurs in ``SitePermissionMiddleware`` which then marks the request with the ``has_site_permission`` flag, so that we only query the db once per request, so this function serves as the entry point for everything else to check access. We also fall back to an ``is_staff`` check if the middleware is not installed, to ease migration. """ mw = "yacms.core.middleware.SitePermissionMiddleware" if mw not in get_middleware_setting(): from warnings import warn warn(mw + " missing from settings.MIDDLEWARE - per site" "permissions not applied") return user.is_staff and user.is_active return getattr(user, "has_site_permission", False)
def function[has_site_permission, parameter[user]]: constant[ Checks if a staff user has staff-level access for the current site. The actual permission lookup occurs in ``SitePermissionMiddleware`` which then marks the request with the ``has_site_permission`` flag, so that we only query the db once per request, so this function serves as the entry point for everything else to check access. We also fall back to an ``is_staff`` check if the middleware is not installed, to ease migration. ] variable[mw] assign[=] constant[yacms.core.middleware.SitePermissionMiddleware] if compare[name[mw] <ast.NotIn object at 0x7da2590d7190> call[name[get_middleware_setting], parameter[]]] begin[:] from relative_module[warnings] import module[warn] call[name[warn], parameter[binary_operation[name[mw] + constant[ missing from settings.MIDDLEWARE - per sitepermissions not applied]]]] return[<ast.BoolOp object at 0x7da2054a4e50>] return[call[name[getattr], parameter[name[user], constant[has_site_permission], constant[False]]]]
keyword[def] identifier[has_site_permission] ( identifier[user] ): literal[string] identifier[mw] = literal[string] keyword[if] identifier[mw] keyword[not] keyword[in] identifier[get_middleware_setting] (): keyword[from] identifier[warnings] keyword[import] identifier[warn] identifier[warn] ( identifier[mw] + literal[string] literal[string] ) keyword[return] identifier[user] . identifier[is_staff] keyword[and] identifier[user] . identifier[is_active] keyword[return] identifier[getattr] ( identifier[user] , literal[string] , keyword[False] )
def has_site_permission(user): """ Checks if a staff user has staff-level access for the current site. The actual permission lookup occurs in ``SitePermissionMiddleware`` which then marks the request with the ``has_site_permission`` flag, so that we only query the db once per request, so this function serves as the entry point for everything else to check access. We also fall back to an ``is_staff`` check if the middleware is not installed, to ease migration. """ mw = 'yacms.core.middleware.SitePermissionMiddleware' if mw not in get_middleware_setting(): from warnings import warn warn(mw + ' missing from settings.MIDDLEWARE - per sitepermissions not applied') return user.is_staff and user.is_active # depends on [control=['if'], data=['mw']] return getattr(user, 'has_site_permission', False)
def detect_fault(self, body): """ Detect I{hidden} soapenv:Fault element in the soap body. @param body: The soap envelope body. @type body: L{Element} @raise WebFault: When found. """ fault = body.getChild('Fault', envns) if fault is None: return unmarshaller = self.unmarshaller(False) p = unmarshaller.process(fault) if self.options().faults: raise WebFault(p, fault) return self
def function[detect_fault, parameter[self, body]]: constant[ Detect I{hidden} soapenv:Fault element in the soap body. @param body: The soap envelope body. @type body: L{Element} @raise WebFault: When found. ] variable[fault] assign[=] call[name[body].getChild, parameter[constant[Fault], name[envns]]] if compare[name[fault] is constant[None]] begin[:] return[None] variable[unmarshaller] assign[=] call[name[self].unmarshaller, parameter[constant[False]]] variable[p] assign[=] call[name[unmarshaller].process, parameter[name[fault]]] if call[name[self].options, parameter[]].faults begin[:] <ast.Raise object at 0x7da1b084d450> return[name[self]]
keyword[def] identifier[detect_fault] ( identifier[self] , identifier[body] ): literal[string] identifier[fault] = identifier[body] . identifier[getChild] ( literal[string] , identifier[envns] ) keyword[if] identifier[fault] keyword[is] keyword[None] : keyword[return] identifier[unmarshaller] = identifier[self] . identifier[unmarshaller] ( keyword[False] ) identifier[p] = identifier[unmarshaller] . identifier[process] ( identifier[fault] ) keyword[if] identifier[self] . identifier[options] (). identifier[faults] : keyword[raise] identifier[WebFault] ( identifier[p] , identifier[fault] ) keyword[return] identifier[self]
def detect_fault(self, body): """ Detect I{hidden} soapenv:Fault element in the soap body. @param body: The soap envelope body. @type body: L{Element} @raise WebFault: When found. """ fault = body.getChild('Fault', envns) if fault is None: return # depends on [control=['if'], data=[]] unmarshaller = self.unmarshaller(False) p = unmarshaller.process(fault) if self.options().faults: raise WebFault(p, fault) # depends on [control=['if'], data=[]] return self
def publish(self, request, **kwargs): """sets the `published` value of the `Content` :param request: a WSGI request object :param kwargs: keyword arguments (optional) :return: `rest_framework.response.Response` """ content = self.get_object() if "published" in get_request_data(request): if not get_request_data(request)["published"]: content.published = None else: publish_dt = parse_datetime(get_request_data(request)["published"]) if publish_dt: publish_dt = publish_dt.astimezone(timezone.utc) else: publish_dt = None content.published = publish_dt else: content.published = timezone.now() content.save() LogEntry.objects.log(request.user, content, content.get_status()) return Response({"status": content.get_status(), "published": content.published})
def function[publish, parameter[self, request]]: constant[sets the `published` value of the `Content` :param request: a WSGI request object :param kwargs: keyword arguments (optional) :return: `rest_framework.response.Response` ] variable[content] assign[=] call[name[self].get_object, parameter[]] if compare[constant[published] in call[name[get_request_data], parameter[name[request]]]] begin[:] if <ast.UnaryOp object at 0x7da1b0a717e0> begin[:] name[content].published assign[=] constant[None] call[name[content].save, parameter[]] call[name[LogEntry].objects.log, parameter[name[request].user, name[content], call[name[content].get_status, parameter[]]]] return[call[name[Response], parameter[dictionary[[<ast.Constant object at 0x7da1b0a71c90>, <ast.Constant object at 0x7da1b0a708b0>], [<ast.Call object at 0x7da1b0a71d80>, <ast.Attribute object at 0x7da18f09dc30>]]]]]
keyword[def] identifier[publish] ( identifier[self] , identifier[request] ,** identifier[kwargs] ): literal[string] identifier[content] = identifier[self] . identifier[get_object] () keyword[if] literal[string] keyword[in] identifier[get_request_data] ( identifier[request] ): keyword[if] keyword[not] identifier[get_request_data] ( identifier[request] )[ literal[string] ]: identifier[content] . identifier[published] = keyword[None] keyword[else] : identifier[publish_dt] = identifier[parse_datetime] ( identifier[get_request_data] ( identifier[request] )[ literal[string] ]) keyword[if] identifier[publish_dt] : identifier[publish_dt] = identifier[publish_dt] . identifier[astimezone] ( identifier[timezone] . identifier[utc] ) keyword[else] : identifier[publish_dt] = keyword[None] identifier[content] . identifier[published] = identifier[publish_dt] keyword[else] : identifier[content] . identifier[published] = identifier[timezone] . identifier[now] () identifier[content] . identifier[save] () identifier[LogEntry] . identifier[objects] . identifier[log] ( identifier[request] . identifier[user] , identifier[content] , identifier[content] . identifier[get_status] ()) keyword[return] identifier[Response] ({ literal[string] : identifier[content] . identifier[get_status] (), literal[string] : identifier[content] . identifier[published] })
def publish(self, request, **kwargs): """sets the `published` value of the `Content` :param request: a WSGI request object :param kwargs: keyword arguments (optional) :return: `rest_framework.response.Response` """ content = self.get_object() if 'published' in get_request_data(request): if not get_request_data(request)['published']: content.published = None # depends on [control=['if'], data=[]] else: publish_dt = parse_datetime(get_request_data(request)['published']) if publish_dt: publish_dt = publish_dt.astimezone(timezone.utc) # depends on [control=['if'], data=[]] else: publish_dt = None content.published = publish_dt # depends on [control=['if'], data=[]] else: content.published = timezone.now() content.save() LogEntry.objects.log(request.user, content, content.get_status()) return Response({'status': content.get_status(), 'published': content.published})
def recall(truth, recommend, k=None): """Recall@k. Args: truth (numpy 1d array): Set of truth samples. recommend (numpy 1d array): Ordered set of recommended samples. k (int): Top-k items in `recommend` will be recommended. Returns: float: Recall@k. """ if len(truth) == 0: if len(recommend) == 0: return 1. return 0. if k is None: k = len(recommend) return count_true_positive(truth, recommend[:k]) / float(truth.size)
def function[recall, parameter[truth, recommend, k]]: constant[Recall@k. Args: truth (numpy 1d array): Set of truth samples. recommend (numpy 1d array): Ordered set of recommended samples. k (int): Top-k items in `recommend` will be recommended. Returns: float: Recall@k. ] if compare[call[name[len], parameter[name[truth]]] equal[==] constant[0]] begin[:] if compare[call[name[len], parameter[name[recommend]]] equal[==] constant[0]] begin[:] return[constant[1.0]] return[constant[0.0]] if compare[name[k] is constant[None]] begin[:] variable[k] assign[=] call[name[len], parameter[name[recommend]]] return[binary_operation[call[name[count_true_positive], parameter[name[truth], call[name[recommend]][<ast.Slice object at 0x7da1b06cfbe0>]]] / call[name[float], parameter[name[truth].size]]]]
keyword[def] identifier[recall] ( identifier[truth] , identifier[recommend] , identifier[k] = keyword[None] ): literal[string] keyword[if] identifier[len] ( identifier[truth] )== literal[int] : keyword[if] identifier[len] ( identifier[recommend] )== literal[int] : keyword[return] literal[int] keyword[return] literal[int] keyword[if] identifier[k] keyword[is] keyword[None] : identifier[k] = identifier[len] ( identifier[recommend] ) keyword[return] identifier[count_true_positive] ( identifier[truth] , identifier[recommend] [: identifier[k] ])/ identifier[float] ( identifier[truth] . identifier[size] )
def recall(truth, recommend, k=None): """Recall@k. Args: truth (numpy 1d array): Set of truth samples. recommend (numpy 1d array): Ordered set of recommended samples. k (int): Top-k items in `recommend` will be recommended. Returns: float: Recall@k. """ if len(truth) == 0: if len(recommend) == 0: return 1.0 # depends on [control=['if'], data=[]] return 0.0 # depends on [control=['if'], data=[]] if k is None: k = len(recommend) # depends on [control=['if'], data=['k']] return count_true_positive(truth, recommend[:k]) / float(truth.size)
def _build_late_dispatcher(func_name): """Return a function that calls method 'func_name' on objects. This is useful for building late-bound dynamic dispatch. Arguments: func_name: The name of the instance method that should be called. Returns: A function that takes an 'obj' parameter, followed by *args and returns the result of calling the instance method with the same name as the contents of 'func_name' on the 'obj' object with the arguments from *args. """ def _late_dynamic_dispatcher(obj, *args): method = getattr(obj, func_name, None) if not callable(method): raise NotImplementedError( "Instance method %r is not implemented by %r." % ( func_name, obj)) return method(*args) return _late_dynamic_dispatcher
def function[_build_late_dispatcher, parameter[func_name]]: constant[Return a function that calls method 'func_name' on objects. This is useful for building late-bound dynamic dispatch. Arguments: func_name: The name of the instance method that should be called. Returns: A function that takes an 'obj' parameter, followed by *args and returns the result of calling the instance method with the same name as the contents of 'func_name' on the 'obj' object with the arguments from *args. ] def function[_late_dynamic_dispatcher, parameter[obj]]: variable[method] assign[=] call[name[getattr], parameter[name[obj], name[func_name], constant[None]]] if <ast.UnaryOp object at 0x7da1b0f2b550> begin[:] <ast.Raise object at 0x7da1b0f2a9e0> return[call[name[method], parameter[<ast.Starred object at 0x7da1b0f2ab60>]]] return[name[_late_dynamic_dispatcher]]
keyword[def] identifier[_build_late_dispatcher] ( identifier[func_name] ): literal[string] keyword[def] identifier[_late_dynamic_dispatcher] ( identifier[obj] ,* identifier[args] ): identifier[method] = identifier[getattr] ( identifier[obj] , identifier[func_name] , keyword[None] ) keyword[if] keyword[not] identifier[callable] ( identifier[method] ): keyword[raise] identifier[NotImplementedError] ( literal[string] %( identifier[func_name] , identifier[obj] )) keyword[return] identifier[method] (* identifier[args] ) keyword[return] identifier[_late_dynamic_dispatcher]
def _build_late_dispatcher(func_name): """Return a function that calls method 'func_name' on objects. This is useful for building late-bound dynamic dispatch. Arguments: func_name: The name of the instance method that should be called. Returns: A function that takes an 'obj' parameter, followed by *args and returns the result of calling the instance method with the same name as the contents of 'func_name' on the 'obj' object with the arguments from *args. """ def _late_dynamic_dispatcher(obj, *args): method = getattr(obj, func_name, None) if not callable(method): raise NotImplementedError('Instance method %r is not implemented by %r.' % (func_name, obj)) # depends on [control=['if'], data=[]] return method(*args) return _late_dynamic_dispatcher
def create_vacation(body): """ Create a vacation. """ arequest = requests.post(VACATIONS_URL, headers=HEADERS, data=json.dumps(body)) status_code = str(arequest.status_code) if status_code != '200': _LOGGER.error("Failed to create vacation. " + status_code) _LOGGER.error(arequest.json()) return False return arequest.json()
def function[create_vacation, parameter[body]]: constant[ Create a vacation. ] variable[arequest] assign[=] call[name[requests].post, parameter[name[VACATIONS_URL]]] variable[status_code] assign[=] call[name[str], parameter[name[arequest].status_code]] if compare[name[status_code] not_equal[!=] constant[200]] begin[:] call[name[_LOGGER].error, parameter[binary_operation[constant[Failed to create vacation. ] + name[status_code]]]] call[name[_LOGGER].error, parameter[call[name[arequest].json, parameter[]]]] return[constant[False]] return[call[name[arequest].json, parameter[]]]
keyword[def] identifier[create_vacation] ( identifier[body] ): literal[string] identifier[arequest] = identifier[requests] . identifier[post] ( identifier[VACATIONS_URL] , identifier[headers] = identifier[HEADERS] , identifier[data] = identifier[json] . identifier[dumps] ( identifier[body] )) identifier[status_code] = identifier[str] ( identifier[arequest] . identifier[status_code] ) keyword[if] identifier[status_code] != literal[string] : identifier[_LOGGER] . identifier[error] ( literal[string] + identifier[status_code] ) identifier[_LOGGER] . identifier[error] ( identifier[arequest] . identifier[json] ()) keyword[return] keyword[False] keyword[return] identifier[arequest] . identifier[json] ()
def create_vacation(body): """ Create a vacation. """ arequest = requests.post(VACATIONS_URL, headers=HEADERS, data=json.dumps(body)) status_code = str(arequest.status_code) if status_code != '200': _LOGGER.error('Failed to create vacation. ' + status_code) _LOGGER.error(arequest.json()) return False # depends on [control=['if'], data=['status_code']] return arequest.json()
def partial_transform(self, traj): """Featurize an MD trajectory into a vector space. Parameters ---------- traj : mdtraj.Trajectory A molecular dynamics trajectory to featurize. Returns ------- features : np.ndarray, dtype=float, shape=(n_samples, n_features) A featurized trajectory is a 2D array of shape `(length_of_trajectory x n_features)` where each `features[i]` vector is computed by applying the featurization function to the `i`th snapshot of the input trajectory. """ return np.concatenate([self.features[feat].partial_transform(traj) for feat in self.which_feat], axis=1)
def function[partial_transform, parameter[self, traj]]: constant[Featurize an MD trajectory into a vector space. Parameters ---------- traj : mdtraj.Trajectory A molecular dynamics trajectory to featurize. Returns ------- features : np.ndarray, dtype=float, shape=(n_samples, n_features) A featurized trajectory is a 2D array of shape `(length_of_trajectory x n_features)` where each `features[i]` vector is computed by applying the featurization function to the `i`th snapshot of the input trajectory. ] return[call[name[np].concatenate, parameter[<ast.ListComp object at 0x7da1b072f3a0>]]]
keyword[def] identifier[partial_transform] ( identifier[self] , identifier[traj] ): literal[string] keyword[return] identifier[np] . identifier[concatenate] ([ identifier[self] . identifier[features] [ identifier[feat] ]. identifier[partial_transform] ( identifier[traj] ) keyword[for] identifier[feat] keyword[in] identifier[self] . identifier[which_feat] ], identifier[axis] = literal[int] )
def partial_transform(self, traj): """Featurize an MD trajectory into a vector space. Parameters ---------- traj : mdtraj.Trajectory A molecular dynamics trajectory to featurize. Returns ------- features : np.ndarray, dtype=float, shape=(n_samples, n_features) A featurized trajectory is a 2D array of shape `(length_of_trajectory x n_features)` where each `features[i]` vector is computed by applying the featurization function to the `i`th snapshot of the input trajectory. """ return np.concatenate([self.features[feat].partial_transform(traj) for feat in self.which_feat], axis=1)
def _transformBy(self, matrix, **kwargs): """ Subclasses may override this method. """ t = transform.Transform(*matrix) transformation = t.transform(self.transformation) self.transformation = tuple(transformation)
def function[_transformBy, parameter[self, matrix]]: constant[ Subclasses may override this method. ] variable[t] assign[=] call[name[transform].Transform, parameter[<ast.Starred object at 0x7da20c6ab3a0>]] variable[transformation] assign[=] call[name[t].transform, parameter[name[self].transformation]] name[self].transformation assign[=] call[name[tuple], parameter[name[transformation]]]
keyword[def] identifier[_transformBy] ( identifier[self] , identifier[matrix] ,** identifier[kwargs] ): literal[string] identifier[t] = identifier[transform] . identifier[Transform] (* identifier[matrix] ) identifier[transformation] = identifier[t] . identifier[transform] ( identifier[self] . identifier[transformation] ) identifier[self] . identifier[transformation] = identifier[tuple] ( identifier[transformation] )
def _transformBy(self, matrix, **kwargs): """ Subclasses may override this method. """ t = transform.Transform(*matrix) transformation = t.transform(self.transformation) self.transformation = tuple(transformation)
def set_lacp_timeout(self, name, value=None): """Configures the Port-Channel LACP fallback timeout The fallback timeout configures the period an interface in fallback mode remains in LACP mode without receiving a PDU. Args: name(str): The Port-Channel interface name value(int): port-channel lacp fallback timeout in seconds Returns: True if the operation succeeds otherwise False is returned """ commands = ['interface %s' % name] string = 'port-channel lacp fallback timeout' commands.append(self.command_builder(string, value=value)) return self.configure(commands)
def function[set_lacp_timeout, parameter[self, name, value]]: constant[Configures the Port-Channel LACP fallback timeout The fallback timeout configures the period an interface in fallback mode remains in LACP mode without receiving a PDU. Args: name(str): The Port-Channel interface name value(int): port-channel lacp fallback timeout in seconds Returns: True if the operation succeeds otherwise False is returned ] variable[commands] assign[=] list[[<ast.BinOp object at 0x7da2041d8880>]] variable[string] assign[=] constant[port-channel lacp fallback timeout] call[name[commands].append, parameter[call[name[self].command_builder, parameter[name[string]]]]] return[call[name[self].configure, parameter[name[commands]]]]
keyword[def] identifier[set_lacp_timeout] ( identifier[self] , identifier[name] , identifier[value] = keyword[None] ): literal[string] identifier[commands] =[ literal[string] % identifier[name] ] identifier[string] = literal[string] identifier[commands] . identifier[append] ( identifier[self] . identifier[command_builder] ( identifier[string] , identifier[value] = identifier[value] )) keyword[return] identifier[self] . identifier[configure] ( identifier[commands] )
def set_lacp_timeout(self, name, value=None): """Configures the Port-Channel LACP fallback timeout The fallback timeout configures the period an interface in fallback mode remains in LACP mode without receiving a PDU. Args: name(str): The Port-Channel interface name value(int): port-channel lacp fallback timeout in seconds Returns: True if the operation succeeds otherwise False is returned """ commands = ['interface %s' % name] string = 'port-channel lacp fallback timeout' commands.append(self.command_builder(string, value=value)) return self.configure(commands)
def _uptime_linux(): """Returns uptime in seconds or None, on Linux.""" # With procfs try: f = open('/proc/uptime', 'r') up = float(f.readline().split()[0]) f.close() return up except (IOError, ValueError): pass # Without procfs (really?) try: libc = ctypes.CDLL('libc.so') except AttributeError: return None except OSError: # Debian and derivatives do the wrong thing because /usr/lib/libc.so # is a GNU ld script rather than an ELF object. To get around this, we # have to be more specific. # We don't want to use ctypes.util.find_library because that creates a # new process on Linux. We also don't want to try too hard because at # this point we're already pretty sure this isn't Linux. try: libc = ctypes.CDLL('libc.so.6') except OSError: return None if not hasattr(libc, 'sysinfo'): # Not Linux. return None buf = ctypes.create_string_buffer(128) # 64 suffices on 32-bit, whatever. if libc.sysinfo(buf) < 0: return None up = struct.unpack_from('@l', buf.raw)[0] if up < 0: up = None return up
def function[_uptime_linux, parameter[]]: constant[Returns uptime in seconds or None, on Linux.] <ast.Try object at 0x7da1aff1f0a0> <ast.Try object at 0x7da1aff1ebf0> if <ast.UnaryOp object at 0x7da1aff1d240> begin[:] return[constant[None]] variable[buf] assign[=] call[name[ctypes].create_string_buffer, parameter[constant[128]]] if compare[call[name[libc].sysinfo, parameter[name[buf]]] less[<] constant[0]] begin[:] return[constant[None]] variable[up] assign[=] call[call[name[struct].unpack_from, parameter[constant[@l], name[buf].raw]]][constant[0]] if compare[name[up] less[<] constant[0]] begin[:] variable[up] assign[=] constant[None] return[name[up]]
keyword[def] identifier[_uptime_linux] (): literal[string] keyword[try] : identifier[f] = identifier[open] ( literal[string] , literal[string] ) identifier[up] = identifier[float] ( identifier[f] . identifier[readline] (). identifier[split] ()[ literal[int] ]) identifier[f] . identifier[close] () keyword[return] identifier[up] keyword[except] ( identifier[IOError] , identifier[ValueError] ): keyword[pass] keyword[try] : identifier[libc] = identifier[ctypes] . identifier[CDLL] ( literal[string] ) keyword[except] identifier[AttributeError] : keyword[return] keyword[None] keyword[except] identifier[OSError] : keyword[try] : identifier[libc] = identifier[ctypes] . identifier[CDLL] ( literal[string] ) keyword[except] identifier[OSError] : keyword[return] keyword[None] keyword[if] keyword[not] identifier[hasattr] ( identifier[libc] , literal[string] ): keyword[return] keyword[None] identifier[buf] = identifier[ctypes] . identifier[create_string_buffer] ( literal[int] ) keyword[if] identifier[libc] . identifier[sysinfo] ( identifier[buf] )< literal[int] : keyword[return] keyword[None] identifier[up] = identifier[struct] . identifier[unpack_from] ( literal[string] , identifier[buf] . identifier[raw] )[ literal[int] ] keyword[if] identifier[up] < literal[int] : identifier[up] = keyword[None] keyword[return] identifier[up]
def _uptime_linux(): """Returns uptime in seconds or None, on Linux.""" # With procfs try: f = open('/proc/uptime', 'r') up = float(f.readline().split()[0]) f.close() return up # depends on [control=['try'], data=[]] except (IOError, ValueError): pass # depends on [control=['except'], data=[]] # Without procfs (really?) try: libc = ctypes.CDLL('libc.so') # depends on [control=['try'], data=[]] except AttributeError: return None # depends on [control=['except'], data=[]] except OSError: # Debian and derivatives do the wrong thing because /usr/lib/libc.so # is a GNU ld script rather than an ELF object. To get around this, we # have to be more specific. # We don't want to use ctypes.util.find_library because that creates a # new process on Linux. We also don't want to try too hard because at # this point we're already pretty sure this isn't Linux. try: libc = ctypes.CDLL('libc.so.6') # depends on [control=['try'], data=[]] except OSError: return None # depends on [control=['except'], data=[]] # depends on [control=['except'], data=[]] if not hasattr(libc, 'sysinfo'): # Not Linux. return None # depends on [control=['if'], data=[]] buf = ctypes.create_string_buffer(128) # 64 suffices on 32-bit, whatever. if libc.sysinfo(buf) < 0: return None # depends on [control=['if'], data=[]] up = struct.unpack_from('@l', buf.raw)[0] if up < 0: up = None # depends on [control=['if'], data=['up']] return up
def transformation_matrix(self): """Get the 4x4 homogeneous transformation matrix equivalent of the quaternion rotation. Returns: A 4x4 homogeneous transformation matrix as a 4x4 Numpy array Note: This feature only makes sense when referring to a unit quaternion. Calling this method will implicitly normalise the Quaternion object to a unit quaternion if it is not already one. """ t = np.array([[0.0], [0.0], [0.0]]) Rt = np.hstack([self.rotation_matrix, t]) return np.vstack([Rt, np.array([0.0, 0.0, 0.0, 1.0])])
def function[transformation_matrix, parameter[self]]: constant[Get the 4x4 homogeneous transformation matrix equivalent of the quaternion rotation. Returns: A 4x4 homogeneous transformation matrix as a 4x4 Numpy array Note: This feature only makes sense when referring to a unit quaternion. Calling this method will implicitly normalise the Quaternion object to a unit quaternion if it is not already one. ] variable[t] assign[=] call[name[np].array, parameter[list[[<ast.List object at 0x7da1b0846d40>, <ast.List object at 0x7da1b0846020>, <ast.List object at 0x7da1b0847df0>]]]] variable[Rt] assign[=] call[name[np].hstack, parameter[list[[<ast.Attribute object at 0x7da1b08448e0>, <ast.Name object at 0x7da1b0847970>]]]] return[call[name[np].vstack, parameter[list[[<ast.Name object at 0x7da1b0845d80>, <ast.Call object at 0x7da1b08445e0>]]]]]
keyword[def] identifier[transformation_matrix] ( identifier[self] ): literal[string] identifier[t] = identifier[np] . identifier[array] ([[ literal[int] ],[ literal[int] ],[ literal[int] ]]) identifier[Rt] = identifier[np] . identifier[hstack] ([ identifier[self] . identifier[rotation_matrix] , identifier[t] ]) keyword[return] identifier[np] . identifier[vstack] ([ identifier[Rt] , identifier[np] . identifier[array] ([ literal[int] , literal[int] , literal[int] , literal[int] ])])
def transformation_matrix(self): """Get the 4x4 homogeneous transformation matrix equivalent of the quaternion rotation. Returns: A 4x4 homogeneous transformation matrix as a 4x4 Numpy array Note: This feature only makes sense when referring to a unit quaternion. Calling this method will implicitly normalise the Quaternion object to a unit quaternion if it is not already one. """ t = np.array([[0.0], [0.0], [0.0]]) Rt = np.hstack([self.rotation_matrix, t]) return np.vstack([Rt, np.array([0.0, 0.0, 0.0, 1.0])])
def media_in_content(self, content): """ check if the content contains and url of an image for the moment, check twitter media url could be elaborate with other service when needed :param content: :return: """ local_file = '' if 'https://t.co' in content: content = re.sub(r'https://t.co/(\w+)', '', content) if 'https://pbs.twimg.com/media/' in content: m = re.search('https://pbs.twimg.com/media/([\w\-_]+).jpg', content) # NOQA url = 'https://pbs.twimg.com/media/{}.jpg'.format(m.group(1)) local_file = download_image(url) content = re.sub(r'https://pbs.twimg.com/media/([\w\-_]+).jpg', '', # NOQA content) return content, local_file return content, local_file
def function[media_in_content, parameter[self, content]]: constant[ check if the content contains and url of an image for the moment, check twitter media url could be elaborate with other service when needed :param content: :return: ] variable[local_file] assign[=] constant[] if compare[constant[https://t.co] in name[content]] begin[:] variable[content] assign[=] call[name[re].sub, parameter[constant[https://t.co/(\w+)], constant[], name[content]]] if compare[constant[https://pbs.twimg.com/media/] in name[content]] begin[:] variable[m] assign[=] call[name[re].search, parameter[constant[https://pbs.twimg.com/media/([\w\-_]+).jpg], name[content]]] variable[url] assign[=] call[constant[https://pbs.twimg.com/media/{}.jpg].format, parameter[call[name[m].group, parameter[constant[1]]]]] variable[local_file] assign[=] call[name[download_image], parameter[name[url]]] variable[content] assign[=] call[name[re].sub, parameter[constant[https://pbs.twimg.com/media/([\w\-_]+).jpg], constant[], name[content]]] return[tuple[[<ast.Name object at 0x7da20c6e4850>, <ast.Name object at 0x7da20c6e6440>]]] return[tuple[[<ast.Name object at 0x7da20c6e7550>, <ast.Name object at 0x7da20c6e56f0>]]]
keyword[def] identifier[media_in_content] ( identifier[self] , identifier[content] ): literal[string] identifier[local_file] = literal[string] keyword[if] literal[string] keyword[in] identifier[content] : identifier[content] = identifier[re] . identifier[sub] ( literal[string] , literal[string] , identifier[content] ) keyword[if] literal[string] keyword[in] identifier[content] : identifier[m] = identifier[re] . identifier[search] ( literal[string] , identifier[content] ) identifier[url] = literal[string] . identifier[format] ( identifier[m] . identifier[group] ( literal[int] )) identifier[local_file] = identifier[download_image] ( identifier[url] ) identifier[content] = identifier[re] . identifier[sub] ( literal[string] , literal[string] , identifier[content] ) keyword[return] identifier[content] , identifier[local_file] keyword[return] identifier[content] , identifier[local_file]
def media_in_content(self, content): """ check if the content contains and url of an image for the moment, check twitter media url could be elaborate with other service when needed :param content: :return: """ local_file = '' if 'https://t.co' in content: content = re.sub('https://t.co/(\\w+)', '', content) # depends on [control=['if'], data=['content']] if 'https://pbs.twimg.com/media/' in content: m = re.search('https://pbs.twimg.com/media/([\\w\\-_]+).jpg', content) # NOQA url = 'https://pbs.twimg.com/media/{}.jpg'.format(m.group(1)) local_file = download_image(url) # NOQA content = re.sub('https://pbs.twimg.com/media/([\\w\\-_]+).jpg', '', content) return (content, local_file) # depends on [control=['if'], data=['content']] return (content, local_file)
def bind_arguments(func, args, kwargs): """Bind the arguments provided into a dict. When passed a function, a tuple of arguments and a dict of keyword arguments `bind_arguments` returns a dict of names as the function would see it. This can be useful to implement a cache decorator that uses the function arguments to build the cache key based on the values of the arguments. :param func: the function the arguments should be bound for. :param args: tuple of positional arguments. :param kwargs: a dict of keyword arguments. :return: a :class:`dict` of bound keyword arguments. """ ( args, kwargs, missing, extra, extra_positional, arg_spec, vararg_var, kwarg_var, ) = _parse_signature(func)(args, kwargs) values = {} for (name, _has_default, _default), value in zip(arg_spec, args): values[name] = value if vararg_var is not None: values[vararg_var] = tuple(extra_positional) elif extra_positional: raise TypeError("too many positional arguments") if kwarg_var is not None: multikw = set(extra) & set([x[0] for x in arg_spec]) if multikw: raise TypeError( "got multiple values for keyword argument " + repr(next(iter(multikw))) ) values[kwarg_var] = extra elif extra: raise TypeError("got unexpected keyword argument " + repr(next(iter(extra)))) return values
def function[bind_arguments, parameter[func, args, kwargs]]: constant[Bind the arguments provided into a dict. When passed a function, a tuple of arguments and a dict of keyword arguments `bind_arguments` returns a dict of names as the function would see it. This can be useful to implement a cache decorator that uses the function arguments to build the cache key based on the values of the arguments. :param func: the function the arguments should be bound for. :param args: tuple of positional arguments. :param kwargs: a dict of keyword arguments. :return: a :class:`dict` of bound keyword arguments. ] <ast.Tuple object at 0x7da2046214e0> assign[=] call[call[name[_parse_signature], parameter[name[func]]], parameter[name[args], name[kwargs]]] variable[values] assign[=] dictionary[[], []] for taget[tuple[[<ast.Tuple object at 0x7da204962320>, <ast.Name object at 0x7da2049623e0>]]] in starred[call[name[zip], parameter[name[arg_spec], name[args]]]] begin[:] call[name[values]][name[name]] assign[=] name[value] if compare[name[vararg_var] is_not constant[None]] begin[:] call[name[values]][name[vararg_var]] assign[=] call[name[tuple], parameter[name[extra_positional]]] if compare[name[kwarg_var] is_not constant[None]] begin[:] variable[multikw] assign[=] binary_operation[call[name[set], parameter[name[extra]]] <ast.BitAnd object at 0x7da2590d6b60> call[name[set], parameter[<ast.ListComp object at 0x7da2046238b0>]]] if name[multikw] begin[:] <ast.Raise object at 0x7da204623fa0> call[name[values]][name[kwarg_var]] assign[=] name[extra] return[name[values]]
keyword[def] identifier[bind_arguments] ( identifier[func] , identifier[args] , identifier[kwargs] ): literal[string] ( identifier[args] , identifier[kwargs] , identifier[missing] , identifier[extra] , identifier[extra_positional] , identifier[arg_spec] , identifier[vararg_var] , identifier[kwarg_var] , )= identifier[_parse_signature] ( identifier[func] )( identifier[args] , identifier[kwargs] ) identifier[values] ={} keyword[for] ( identifier[name] , identifier[_has_default] , identifier[_default] ), identifier[value] keyword[in] identifier[zip] ( identifier[arg_spec] , identifier[args] ): identifier[values] [ identifier[name] ]= identifier[value] keyword[if] identifier[vararg_var] keyword[is] keyword[not] keyword[None] : identifier[values] [ identifier[vararg_var] ]= identifier[tuple] ( identifier[extra_positional] ) keyword[elif] identifier[extra_positional] : keyword[raise] identifier[TypeError] ( literal[string] ) keyword[if] identifier[kwarg_var] keyword[is] keyword[not] keyword[None] : identifier[multikw] = identifier[set] ( identifier[extra] )& identifier[set] ([ identifier[x] [ literal[int] ] keyword[for] identifier[x] keyword[in] identifier[arg_spec] ]) keyword[if] identifier[multikw] : keyword[raise] identifier[TypeError] ( literal[string] + identifier[repr] ( identifier[next] ( identifier[iter] ( identifier[multikw] ))) ) identifier[values] [ identifier[kwarg_var] ]= identifier[extra] keyword[elif] identifier[extra] : keyword[raise] identifier[TypeError] ( literal[string] + identifier[repr] ( identifier[next] ( identifier[iter] ( identifier[extra] )))) keyword[return] identifier[values]
def bind_arguments(func, args, kwargs): """Bind the arguments provided into a dict. When passed a function, a tuple of arguments and a dict of keyword arguments `bind_arguments` returns a dict of names as the function would see it. This can be useful to implement a cache decorator that uses the function arguments to build the cache key based on the values of the arguments. :param func: the function the arguments should be bound for. :param args: tuple of positional arguments. :param kwargs: a dict of keyword arguments. :return: a :class:`dict` of bound keyword arguments. """ (args, kwargs, missing, extra, extra_positional, arg_spec, vararg_var, kwarg_var) = _parse_signature(func)(args, kwargs) values = {} for ((name, _has_default, _default), value) in zip(arg_spec, args): values[name] = value # depends on [control=['for'], data=[]] if vararg_var is not None: values[vararg_var] = tuple(extra_positional) # depends on [control=['if'], data=['vararg_var']] elif extra_positional: raise TypeError('too many positional arguments') # depends on [control=['if'], data=[]] if kwarg_var is not None: multikw = set(extra) & set([x[0] for x in arg_spec]) if multikw: raise TypeError('got multiple values for keyword argument ' + repr(next(iter(multikw)))) # depends on [control=['if'], data=[]] values[kwarg_var] = extra # depends on [control=['if'], data=['kwarg_var']] elif extra: raise TypeError('got unexpected keyword argument ' + repr(next(iter(extra)))) # depends on [control=['if'], data=[]] return values
def selectin(table, field, value, complement=False): """Select rows where the given field is a member of the given value.""" return select(table, field, lambda v: v in value, complement=complement)
def function[selectin, parameter[table, field, value, complement]]: constant[Select rows where the given field is a member of the given value.] return[call[name[select], parameter[name[table], name[field], <ast.Lambda object at 0x7da1b08e55d0>]]]
keyword[def] identifier[selectin] ( identifier[table] , identifier[field] , identifier[value] , identifier[complement] = keyword[False] ): literal[string] keyword[return] identifier[select] ( identifier[table] , identifier[field] , keyword[lambda] identifier[v] : identifier[v] keyword[in] identifier[value] , identifier[complement] = identifier[complement] )
def selectin(table, field, value, complement=False): """Select rows where the given field is a member of the given value.""" return select(table, field, lambda v: v in value, complement=complement)
def stop(self, timeout=None): """ Stop OpenVPN process group :param timeout: time in seconds to wait for process to stop :return: """ if not timeout: timeout = self.timeout os.killpg(os.getpgid(self.process.pid), signal.SIGTERM) self.thread.join(timeout) if self.stopped: logging.info("OpenVPN stopped") if self in OpenVPN.connected_instances: OpenVPN.connected_instances.remove(self) else: logging.error("Cannot stop OpenVPN!") for line in self.notifications.split('\n'): logging.warn("OpenVPN output:\t\t%s" % line)
def function[stop, parameter[self, timeout]]: constant[ Stop OpenVPN process group :param timeout: time in seconds to wait for process to stop :return: ] if <ast.UnaryOp object at 0x7da1b2851c90> begin[:] variable[timeout] assign[=] name[self].timeout call[name[os].killpg, parameter[call[name[os].getpgid, parameter[name[self].process.pid]], name[signal].SIGTERM]] call[name[self].thread.join, parameter[name[timeout]]] if name[self].stopped begin[:] call[name[logging].info, parameter[constant[OpenVPN stopped]]] if compare[name[self] in name[OpenVPN].connected_instances] begin[:] call[name[OpenVPN].connected_instances.remove, parameter[name[self]]]
keyword[def] identifier[stop] ( identifier[self] , identifier[timeout] = keyword[None] ): literal[string] keyword[if] keyword[not] identifier[timeout] : identifier[timeout] = identifier[self] . identifier[timeout] identifier[os] . identifier[killpg] ( identifier[os] . identifier[getpgid] ( identifier[self] . identifier[process] . identifier[pid] ), identifier[signal] . identifier[SIGTERM] ) identifier[self] . identifier[thread] . identifier[join] ( identifier[timeout] ) keyword[if] identifier[self] . identifier[stopped] : identifier[logging] . identifier[info] ( literal[string] ) keyword[if] identifier[self] keyword[in] identifier[OpenVPN] . identifier[connected_instances] : identifier[OpenVPN] . identifier[connected_instances] . identifier[remove] ( identifier[self] ) keyword[else] : identifier[logging] . identifier[error] ( literal[string] ) keyword[for] identifier[line] keyword[in] identifier[self] . identifier[notifications] . identifier[split] ( literal[string] ): identifier[logging] . identifier[warn] ( literal[string] % identifier[line] )
def stop(self, timeout=None): """ Stop OpenVPN process group :param timeout: time in seconds to wait for process to stop :return: """ if not timeout: timeout = self.timeout # depends on [control=['if'], data=[]] os.killpg(os.getpgid(self.process.pid), signal.SIGTERM) self.thread.join(timeout) if self.stopped: logging.info('OpenVPN stopped') if self in OpenVPN.connected_instances: OpenVPN.connected_instances.remove(self) # depends on [control=['if'], data=['self']] # depends on [control=['if'], data=[]] else: logging.error('Cannot stop OpenVPN!') for line in self.notifications.split('\n'): logging.warn('OpenVPN output:\t\t%s' % line) # depends on [control=['for'], data=['line']]
def parse_request_body_response(self, body, scope=None, **kwargs): """Parse the JSON response body. If the access token request is valid and authorized, the authorization server issues an access token as described in `Section 5.1`_. A refresh token SHOULD NOT be included. If the request failed client authentication or is invalid, the authorization server returns an error response as described in `Section 5.2`_. :param body: The response body from the token request. :param scope: Scopes originally requested. :return: Dictionary of token parameters. :raises: Warning if scope has changed. OAuth2Error if response is invalid. These response are json encoded and could easily be parsed without the assistance of OAuthLib. However, there are a few subtle issues to be aware of regarding the response which are helpfully addressed through the raising of various errors. A successful response should always contain **access_token** The access token issued by the authorization server. Often a random string. **token_type** The type of the token issued as described in `Section 7.1`_. Commonly ``Bearer``. While it is not mandated it is recommended that the provider include **expires_in** The lifetime in seconds of the access token. For example, the value "3600" denotes that the access token will expire in one hour from the time the response was generated. If omitted, the authorization server SHOULD provide the expiration time via other means or document the default value. **scope** Providers may supply this in all responses but are required to only if it has changed since the authorization request. .. _`Section 5.1`: https://tools.ietf.org/html/rfc6749#section-5.1 .. _`Section 5.2`: https://tools.ietf.org/html/rfc6749#section-5.2 .. _`Section 7.1`: https://tools.ietf.org/html/rfc6749#section-7.1 """ self.token = parse_token_response(body, scope=scope) self.populate_token_attributes(self.token) return self.token
def function[parse_request_body_response, parameter[self, body, scope]]: constant[Parse the JSON response body. If the access token request is valid and authorized, the authorization server issues an access token as described in `Section 5.1`_. A refresh token SHOULD NOT be included. If the request failed client authentication or is invalid, the authorization server returns an error response as described in `Section 5.2`_. :param body: The response body from the token request. :param scope: Scopes originally requested. :return: Dictionary of token parameters. :raises: Warning if scope has changed. OAuth2Error if response is invalid. These response are json encoded and could easily be parsed without the assistance of OAuthLib. However, there are a few subtle issues to be aware of regarding the response which are helpfully addressed through the raising of various errors. A successful response should always contain **access_token** The access token issued by the authorization server. Often a random string. **token_type** The type of the token issued as described in `Section 7.1`_. Commonly ``Bearer``. While it is not mandated it is recommended that the provider include **expires_in** The lifetime in seconds of the access token. For example, the value "3600" denotes that the access token will expire in one hour from the time the response was generated. If omitted, the authorization server SHOULD provide the expiration time via other means or document the default value. **scope** Providers may supply this in all responses but are required to only if it has changed since the authorization request. .. _`Section 5.1`: https://tools.ietf.org/html/rfc6749#section-5.1 .. _`Section 5.2`: https://tools.ietf.org/html/rfc6749#section-5.2 .. _`Section 7.1`: https://tools.ietf.org/html/rfc6749#section-7.1 ] name[self].token assign[=] call[name[parse_token_response], parameter[name[body]]] call[name[self].populate_token_attributes, parameter[name[self].token]] return[name[self].token]
keyword[def] identifier[parse_request_body_response] ( identifier[self] , identifier[body] , identifier[scope] = keyword[None] ,** identifier[kwargs] ): literal[string] identifier[self] . identifier[token] = identifier[parse_token_response] ( identifier[body] , identifier[scope] = identifier[scope] ) identifier[self] . identifier[populate_token_attributes] ( identifier[self] . identifier[token] ) keyword[return] identifier[self] . identifier[token]
def parse_request_body_response(self, body, scope=None, **kwargs): """Parse the JSON response body. If the access token request is valid and authorized, the authorization server issues an access token as described in `Section 5.1`_. A refresh token SHOULD NOT be included. If the request failed client authentication or is invalid, the authorization server returns an error response as described in `Section 5.2`_. :param body: The response body from the token request. :param scope: Scopes originally requested. :return: Dictionary of token parameters. :raises: Warning if scope has changed. OAuth2Error if response is invalid. These response are json encoded and could easily be parsed without the assistance of OAuthLib. However, there are a few subtle issues to be aware of regarding the response which are helpfully addressed through the raising of various errors. A successful response should always contain **access_token** The access token issued by the authorization server. Often a random string. **token_type** The type of the token issued as described in `Section 7.1`_. Commonly ``Bearer``. While it is not mandated it is recommended that the provider include **expires_in** The lifetime in seconds of the access token. For example, the value "3600" denotes that the access token will expire in one hour from the time the response was generated. If omitted, the authorization server SHOULD provide the expiration time via other means or document the default value. **scope** Providers may supply this in all responses but are required to only if it has changed since the authorization request. .. _`Section 5.1`: https://tools.ietf.org/html/rfc6749#section-5.1 .. _`Section 5.2`: https://tools.ietf.org/html/rfc6749#section-5.2 .. _`Section 7.1`: https://tools.ietf.org/html/rfc6749#section-7.1 """ self.token = parse_token_response(body, scope=scope) self.populate_token_attributes(self.token) return self.token
def colorpalette(self, colorpalette): """ Set the colorpalette which should be used """ if isinstance(colorpalette, str): # we assume it's a path to a color file colorpalette = colors.parse_colors(colorpalette) self._colorpalette = colors.sanitize_color_palette(colorpalette)
def function[colorpalette, parameter[self, colorpalette]]: constant[ Set the colorpalette which should be used ] if call[name[isinstance], parameter[name[colorpalette], name[str]]] begin[:] variable[colorpalette] assign[=] call[name[colors].parse_colors, parameter[name[colorpalette]]] name[self]._colorpalette assign[=] call[name[colors].sanitize_color_palette, parameter[name[colorpalette]]]
keyword[def] identifier[colorpalette] ( identifier[self] , identifier[colorpalette] ): literal[string] keyword[if] identifier[isinstance] ( identifier[colorpalette] , identifier[str] ): identifier[colorpalette] = identifier[colors] . identifier[parse_colors] ( identifier[colorpalette] ) identifier[self] . identifier[_colorpalette] = identifier[colors] . identifier[sanitize_color_palette] ( identifier[colorpalette] )
def colorpalette(self, colorpalette): """ Set the colorpalette which should be used """ if isinstance(colorpalette, str): # we assume it's a path to a color file colorpalette = colors.parse_colors(colorpalette) # depends on [control=['if'], data=[]] self._colorpalette = colors.sanitize_color_palette(colorpalette)
async def terminal(self, device): """ Launch terminal on the mount path of the specified device. :param device: device object, block device path or mount path :returns: whether the program was successfully launched. """ device = self._find_device(device) if not device.is_mounted: self._log.error(_("not opening terminal {0}: not mounted", device)) return False if not self._terminal: self._log.error(_("not opening terminal {0}: no program", device)) return False self._log.debug(_('opening {0} on {0.mount_paths[0]}', device)) self._terminal(device.mount_paths[0]) self._log.info(_('opened {0} on {0.mount_paths[0]}', device)) return True
<ast.AsyncFunctionDef object at 0x7da207f02710>
keyword[async] keyword[def] identifier[terminal] ( identifier[self] , identifier[device] ): literal[string] identifier[device] = identifier[self] . identifier[_find_device] ( identifier[device] ) keyword[if] keyword[not] identifier[device] . identifier[is_mounted] : identifier[self] . identifier[_log] . identifier[error] ( identifier[_] ( literal[string] , identifier[device] )) keyword[return] keyword[False] keyword[if] keyword[not] identifier[self] . identifier[_terminal] : identifier[self] . identifier[_log] . identifier[error] ( identifier[_] ( literal[string] , identifier[device] )) keyword[return] keyword[False] identifier[self] . identifier[_log] . identifier[debug] ( identifier[_] ( literal[string] , identifier[device] )) identifier[self] . identifier[_terminal] ( identifier[device] . identifier[mount_paths] [ literal[int] ]) identifier[self] . identifier[_log] . identifier[info] ( identifier[_] ( literal[string] , identifier[device] )) keyword[return] keyword[True]
async def terminal(self, device): """ Launch terminal on the mount path of the specified device. :param device: device object, block device path or mount path :returns: whether the program was successfully launched. """ device = self._find_device(device) if not device.is_mounted: self._log.error(_('not opening terminal {0}: not mounted', device)) return False # depends on [control=['if'], data=[]] if not self._terminal: self._log.error(_('not opening terminal {0}: no program', device)) return False # depends on [control=['if'], data=[]] self._log.debug(_('opening {0} on {0.mount_paths[0]}', device)) self._terminal(device.mount_paths[0]) self._log.info(_('opened {0} on {0.mount_paths[0]}', device)) return True
def get_root_resource(server_host, server_port=None, username="admin", password="admin", use_tls=False, version=API_CURRENT_VERSION): """ See ApiResource. """ return ApiResource(server_host, server_port, username, password, use_tls, version)
def function[get_root_resource, parameter[server_host, server_port, username, password, use_tls, version]]: constant[ See ApiResource. ] return[call[name[ApiResource], parameter[name[server_host], name[server_port], name[username], name[password], name[use_tls], name[version]]]]
keyword[def] identifier[get_root_resource] ( identifier[server_host] , identifier[server_port] = keyword[None] , identifier[username] = literal[string] , identifier[password] = literal[string] , identifier[use_tls] = keyword[False] , identifier[version] = identifier[API_CURRENT_VERSION] ): literal[string] keyword[return] identifier[ApiResource] ( identifier[server_host] , identifier[server_port] , identifier[username] , identifier[password] , identifier[use_tls] , identifier[version] )
def get_root_resource(server_host, server_port=None, username='admin', password='admin', use_tls=False, version=API_CURRENT_VERSION): """ See ApiResource. """ return ApiResource(server_host, server_port, username, password, use_tls, version)
def canvases_with(drawable): """ Return a list of all canvases where `drawable` has been painted. Note: This function is inefficient because it inspects all objects on all canvases, recursively. Avoid calling it if you have a large number of canvases and primitives. """ return [c for c in ROOT.gROOT.GetListOfCanvases() if drawable in find_all_primitives(c)]
def function[canvases_with, parameter[drawable]]: constant[ Return a list of all canvases where `drawable` has been painted. Note: This function is inefficient because it inspects all objects on all canvases, recursively. Avoid calling it if you have a large number of canvases and primitives. ] return[<ast.ListComp object at 0x7da1b11f1360>]
keyword[def] identifier[canvases_with] ( identifier[drawable] ): literal[string] keyword[return] [ identifier[c] keyword[for] identifier[c] keyword[in] identifier[ROOT] . identifier[gROOT] . identifier[GetListOfCanvases] () keyword[if] identifier[drawable] keyword[in] identifier[find_all_primitives] ( identifier[c] )]
def canvases_with(drawable): """ Return a list of all canvases where `drawable` has been painted. Note: This function is inefficient because it inspects all objects on all canvases, recursively. Avoid calling it if you have a large number of canvases and primitives. """ return [c for c in ROOT.gROOT.GetListOfCanvases() if drawable in find_all_primitives(c)]
def get_pool_for_host(self, host_id): """Returns the connection pool for the given host. This connection pool is used by the redis clients to make sure that it does not have to reconnect constantly. If you want to use a custom redis client you can pass this in as connection pool manually. """ if isinstance(host_id, HostInfo): host_info = host_id host_id = host_info.host_id else: host_info = self.hosts.get(host_id) if host_info is None: raise LookupError('Host %r does not exist' % (host_id,)) rv = self._pools.get(host_id) if rv is not None: return rv with self._lock: rv = self._pools.get(host_id) if rv is None: opts = dict(self.pool_options or ()) opts['db'] = host_info.db opts['password'] = host_info.password if host_info.unix_socket_path is not None: opts['path'] = host_info.unix_socket_path opts['connection_class'] = UnixDomainSocketConnection if host_info.ssl: raise TypeError('SSL is not supported for unix ' 'domain sockets.') else: opts['host'] = host_info.host opts['port'] = host_info.port if host_info.ssl: if SSLConnection is None: raise TypeError('This version of py-redis does ' 'not support SSL connections.') opts['connection_class'] = SSLConnection opts.update(('ssl_' + k, v) for k, v in (host_info.ssl_options or {}).iteritems()) rv = self.pool_cls(**opts) self._pools[host_id] = rv return rv
def function[get_pool_for_host, parameter[self, host_id]]: constant[Returns the connection pool for the given host. This connection pool is used by the redis clients to make sure that it does not have to reconnect constantly. If you want to use a custom redis client you can pass this in as connection pool manually. ] if call[name[isinstance], parameter[name[host_id], name[HostInfo]]] begin[:] variable[host_info] assign[=] name[host_id] variable[host_id] assign[=] name[host_info].host_id variable[rv] assign[=] call[name[self]._pools.get, parameter[name[host_id]]] if compare[name[rv] is_not constant[None]] begin[:] return[name[rv]] with name[self]._lock begin[:] variable[rv] assign[=] call[name[self]._pools.get, parameter[name[host_id]]] if compare[name[rv] is constant[None]] begin[:] variable[opts] assign[=] call[name[dict], parameter[<ast.BoolOp object at 0x7da1b10edd80>]] call[name[opts]][constant[db]] assign[=] name[host_info].db call[name[opts]][constant[password]] assign[=] name[host_info].password if compare[name[host_info].unix_socket_path is_not constant[None]] begin[:] call[name[opts]][constant[path]] assign[=] name[host_info].unix_socket_path call[name[opts]][constant[connection_class]] assign[=] name[UnixDomainSocketConnection] if name[host_info].ssl begin[:] <ast.Raise object at 0x7da1b10ef580> variable[rv] assign[=] call[name[self].pool_cls, parameter[]] call[name[self]._pools][name[host_id]] assign[=] name[rv] return[name[rv]]
keyword[def] identifier[get_pool_for_host] ( identifier[self] , identifier[host_id] ): literal[string] keyword[if] identifier[isinstance] ( identifier[host_id] , identifier[HostInfo] ): identifier[host_info] = identifier[host_id] identifier[host_id] = identifier[host_info] . identifier[host_id] keyword[else] : identifier[host_info] = identifier[self] . identifier[hosts] . identifier[get] ( identifier[host_id] ) keyword[if] identifier[host_info] keyword[is] keyword[None] : keyword[raise] identifier[LookupError] ( literal[string] %( identifier[host_id] ,)) identifier[rv] = identifier[self] . identifier[_pools] . identifier[get] ( identifier[host_id] ) keyword[if] identifier[rv] keyword[is] keyword[not] keyword[None] : keyword[return] identifier[rv] keyword[with] identifier[self] . identifier[_lock] : identifier[rv] = identifier[self] . identifier[_pools] . identifier[get] ( identifier[host_id] ) keyword[if] identifier[rv] keyword[is] keyword[None] : identifier[opts] = identifier[dict] ( identifier[self] . identifier[pool_options] keyword[or] ()) identifier[opts] [ literal[string] ]= identifier[host_info] . identifier[db] identifier[opts] [ literal[string] ]= identifier[host_info] . identifier[password] keyword[if] identifier[host_info] . identifier[unix_socket_path] keyword[is] keyword[not] keyword[None] : identifier[opts] [ literal[string] ]= identifier[host_info] . identifier[unix_socket_path] identifier[opts] [ literal[string] ]= identifier[UnixDomainSocketConnection] keyword[if] identifier[host_info] . identifier[ssl] : keyword[raise] identifier[TypeError] ( literal[string] literal[string] ) keyword[else] : identifier[opts] [ literal[string] ]= identifier[host_info] . identifier[host] identifier[opts] [ literal[string] ]= identifier[host_info] . identifier[port] keyword[if] identifier[host_info] . identifier[ssl] : keyword[if] identifier[SSLConnection] keyword[is] keyword[None] : keyword[raise] identifier[TypeError] ( literal[string] literal[string] ) identifier[opts] [ literal[string] ]= identifier[SSLConnection] identifier[opts] . identifier[update] (( literal[string] + identifier[k] , identifier[v] ) keyword[for] identifier[k] , identifier[v] keyword[in] ( identifier[host_info] . identifier[ssl_options] keyword[or] {}). identifier[iteritems] ()) identifier[rv] = identifier[self] . identifier[pool_cls] (** identifier[opts] ) identifier[self] . identifier[_pools] [ identifier[host_id] ]= identifier[rv] keyword[return] identifier[rv]
def get_pool_for_host(self, host_id): """Returns the connection pool for the given host. This connection pool is used by the redis clients to make sure that it does not have to reconnect constantly. If you want to use a custom redis client you can pass this in as connection pool manually. """ if isinstance(host_id, HostInfo): host_info = host_id host_id = host_info.host_id # depends on [control=['if'], data=[]] else: host_info = self.hosts.get(host_id) if host_info is None: raise LookupError('Host %r does not exist' % (host_id,)) # depends on [control=['if'], data=[]] rv = self._pools.get(host_id) if rv is not None: return rv # depends on [control=['if'], data=['rv']] with self._lock: rv = self._pools.get(host_id) if rv is None: opts = dict(self.pool_options or ()) opts['db'] = host_info.db opts['password'] = host_info.password if host_info.unix_socket_path is not None: opts['path'] = host_info.unix_socket_path opts['connection_class'] = UnixDomainSocketConnection if host_info.ssl: raise TypeError('SSL is not supported for unix domain sockets.') # depends on [control=['if'], data=[]] # depends on [control=['if'], data=[]] else: opts['host'] = host_info.host opts['port'] = host_info.port if host_info.ssl: if SSLConnection is None: raise TypeError('This version of py-redis does not support SSL connections.') # depends on [control=['if'], data=[]] opts['connection_class'] = SSLConnection opts.update((('ssl_' + k, v) for (k, v) in (host_info.ssl_options or {}).iteritems())) # depends on [control=['if'], data=[]] rv = self.pool_cls(**opts) self._pools[host_id] = rv # depends on [control=['if'], data=['rv']] return rv # depends on [control=['with'], data=[]]
def heaviest_increasing_subsequence(a, debug=False): """ Returns the heaviest increasing subsequence for array a. Elements are (key, weight) pairs. >>> heaviest_increasing_subsequence([(3, 3), (2, 2), (1, 1), (0, 5)]) ([(0, 5)], 5) """ # Stores the smallest idx of last element of a subsequence of weight w L = {0: -1} bestsofar = [(0, -1)] * len(a) # (best weight, from_idx) for i, (key, weight) in enumerate(a): for w, j in L.items(): if j != -1 and a[j][0] >= key: continue new_weight = w + weight if new_weight in L and a[L[new_weight]][0] <= key: continue L[new_weight] = i newbest = (new_weight, j) if newbest > bestsofar[i]: bestsofar[i] = newbest if debug: #print (key, weight), L print((key, weight), bestsofar) tb = reversed(list(backtracking(a, L, bestsofar))) return [a[x] for x in tb], max(L.items())[0]
def function[heaviest_increasing_subsequence, parameter[a, debug]]: constant[ Returns the heaviest increasing subsequence for array a. Elements are (key, weight) pairs. >>> heaviest_increasing_subsequence([(3, 3), (2, 2), (1, 1), (0, 5)]) ([(0, 5)], 5) ] variable[L] assign[=] dictionary[[<ast.Constant object at 0x7da2041da320>], [<ast.UnaryOp object at 0x7da2041d8760>]] variable[bestsofar] assign[=] binary_operation[list[[<ast.Tuple object at 0x7da2041d9390>]] * call[name[len], parameter[name[a]]]] for taget[tuple[[<ast.Name object at 0x7da2041d87f0>, <ast.Tuple object at 0x7da2041dba90>]]] in starred[call[name[enumerate], parameter[name[a]]]] begin[:] for taget[tuple[[<ast.Name object at 0x7da2041daef0>, <ast.Name object at 0x7da2041d97e0>]]] in starred[call[name[L].items, parameter[]]] begin[:] if <ast.BoolOp object at 0x7da2041d8e50> begin[:] continue variable[new_weight] assign[=] binary_operation[name[w] + name[weight]] if <ast.BoolOp object at 0x7da2041d9d80> begin[:] continue call[name[L]][name[new_weight]] assign[=] name[i] variable[newbest] assign[=] tuple[[<ast.Name object at 0x7da2047ea350>, <ast.Name object at 0x7da2047e86d0>]] if compare[name[newbest] greater[>] call[name[bestsofar]][name[i]]] begin[:] call[name[bestsofar]][name[i]] assign[=] name[newbest] if name[debug] begin[:] call[name[print], parameter[tuple[[<ast.Name object at 0x7da2047e9150>, <ast.Name object at 0x7da2047e8280>]], name[bestsofar]]] variable[tb] assign[=] call[name[reversed], parameter[call[name[list], parameter[call[name[backtracking], parameter[name[a], name[L], name[bestsofar]]]]]]] return[tuple[[<ast.ListComp object at 0x7da2047e99f0>, <ast.Subscript object at 0x7da20c76ceb0>]]]
keyword[def] identifier[heaviest_increasing_subsequence] ( identifier[a] , identifier[debug] = keyword[False] ): literal[string] identifier[L] ={ literal[int] :- literal[int] } identifier[bestsofar] =[( literal[int] ,- literal[int] )]* identifier[len] ( identifier[a] ) keyword[for] identifier[i] ,( identifier[key] , identifier[weight] ) keyword[in] identifier[enumerate] ( identifier[a] ): keyword[for] identifier[w] , identifier[j] keyword[in] identifier[L] . identifier[items] (): keyword[if] identifier[j] !=- literal[int] keyword[and] identifier[a] [ identifier[j] ][ literal[int] ]>= identifier[key] : keyword[continue] identifier[new_weight] = identifier[w] + identifier[weight] keyword[if] identifier[new_weight] keyword[in] identifier[L] keyword[and] identifier[a] [ identifier[L] [ identifier[new_weight] ]][ literal[int] ]<= identifier[key] : keyword[continue] identifier[L] [ identifier[new_weight] ]= identifier[i] identifier[newbest] =( identifier[new_weight] , identifier[j] ) keyword[if] identifier[newbest] > identifier[bestsofar] [ identifier[i] ]: identifier[bestsofar] [ identifier[i] ]= identifier[newbest] keyword[if] identifier[debug] : identifier[print] (( identifier[key] , identifier[weight] ), identifier[bestsofar] ) identifier[tb] = identifier[reversed] ( identifier[list] ( identifier[backtracking] ( identifier[a] , identifier[L] , identifier[bestsofar] ))) keyword[return] [ identifier[a] [ identifier[x] ] keyword[for] identifier[x] keyword[in] identifier[tb] ], identifier[max] ( identifier[L] . identifier[items] ())[ literal[int] ]
def heaviest_increasing_subsequence(a, debug=False): """ Returns the heaviest increasing subsequence for array a. Elements are (key, weight) pairs. >>> heaviest_increasing_subsequence([(3, 3), (2, 2), (1, 1), (0, 5)]) ([(0, 5)], 5) """ # Stores the smallest idx of last element of a subsequence of weight w L = {0: -1} bestsofar = [(0, -1)] * len(a) # (best weight, from_idx) for (i, (key, weight)) in enumerate(a): for (w, j) in L.items(): if j != -1 and a[j][0] >= key: continue # depends on [control=['if'], data=[]] new_weight = w + weight if new_weight in L and a[L[new_weight]][0] <= key: continue # depends on [control=['if'], data=[]] L[new_weight] = i newbest = (new_weight, j) if newbest > bestsofar[i]: bestsofar[i] = newbest # depends on [control=['if'], data=['newbest']] # depends on [control=['for'], data=[]] if debug: #print (key, weight), L print((key, weight), bestsofar) # depends on [control=['if'], data=[]] # depends on [control=['for'], data=[]] tb = reversed(list(backtracking(a, L, bestsofar))) return ([a[x] for x in tb], max(L.items())[0])
def camera_marker(camera, marker_height=0.4, origin_size=None): """ Create a visual marker for a camera object, including an axis and FOV. Parameters --------------- camera : trimesh.scene.Camera Camera object with FOV and transform defined marker_height : float How far along the camera Z should FOV indicators be origin_size : float Sphere radius of the origin (default: marker_height / 10.0) Returns ------------ meshes : list Contains Trimesh and Path3D objects which can be visualized """ camera_transform = camera.transform if camera_transform is None: camera_transform = np.eye(4) # append the visualizations to an array meshes = [axis(origin_size=marker_height / 10.0)] meshes[0].apply_transform(camera_transform) try: # path is a soft dependency from .path.exchange.load import load_path except ImportError: # they probably don't have shapely installed log.warning('unable to create FOV visualization!', exc_info=True) return meshes # create sane origin size from marker height if origin_size is None: origin_size = marker_height / 10.0 # calculate vertices from camera FOV angles x = marker_height * np.tan(np.deg2rad(camera.fov[0]) / 2.0) y = marker_height * np.tan(np.deg2rad(camera.fov[1]) / 2.0) z = marker_height # combine the points into the vertices of an FOV visualization points = np.array( [(0, 0, 0), (-x, -y, z), (x, -y, z), (x, y, z), (-x, y, z)], dtype=float) # create line segments for the FOV visualization # a segment from the origin to each bound of the FOV segments = np.column_stack( (np.zeros_like(points), points)).reshape( (-1, 3)) # add a loop for the outside of the FOV then reshape # the whole thing into multiple line segments segments = np.vstack((segments, points[[1, 2, 2, 3, 3, 4, 4, 1]])).reshape((-1, 2, 3)) # add a single Path3D object for all line segments meshes.append(load_path(segments)) meshes[-1].apply_transform(camera_transform) return meshes
def function[camera_marker, parameter[camera, marker_height, origin_size]]: constant[ Create a visual marker for a camera object, including an axis and FOV. Parameters --------------- camera : trimesh.scene.Camera Camera object with FOV and transform defined marker_height : float How far along the camera Z should FOV indicators be origin_size : float Sphere radius of the origin (default: marker_height / 10.0) Returns ------------ meshes : list Contains Trimesh and Path3D objects which can be visualized ] variable[camera_transform] assign[=] name[camera].transform if compare[name[camera_transform] is constant[None]] begin[:] variable[camera_transform] assign[=] call[name[np].eye, parameter[constant[4]]] variable[meshes] assign[=] list[[<ast.Call object at 0x7da20c6abdf0>]] call[call[name[meshes]][constant[0]].apply_transform, parameter[name[camera_transform]]] <ast.Try object at 0x7da20c6a8520> if compare[name[origin_size] is constant[None]] begin[:] variable[origin_size] assign[=] binary_operation[name[marker_height] / constant[10.0]] variable[x] assign[=] binary_operation[name[marker_height] * call[name[np].tan, parameter[binary_operation[call[name[np].deg2rad, parameter[call[name[camera].fov][constant[0]]]] / constant[2.0]]]]] variable[y] assign[=] binary_operation[name[marker_height] * call[name[np].tan, parameter[binary_operation[call[name[np].deg2rad, parameter[call[name[camera].fov][constant[1]]]] / constant[2.0]]]]] variable[z] assign[=] name[marker_height] variable[points] assign[=] call[name[np].array, parameter[list[[<ast.Tuple object at 0x7da207f98940>, <ast.Tuple object at 0x7da207f9bb50>, <ast.Tuple object at 0x7da207f98d60>, <ast.Tuple object at 0x7da204962860>, <ast.Tuple object at 0x7da204962da0>]]]] variable[segments] assign[=] call[call[name[np].column_stack, parameter[tuple[[<ast.Call object at 0x7da204960490>, <ast.Name object at 0x7da204961810>]]]].reshape, parameter[tuple[[<ast.UnaryOp object at 0x7da2049601c0>, <ast.Constant object at 0x7da204963460>]]]] variable[segments] assign[=] call[call[name[np].vstack, parameter[tuple[[<ast.Name object at 0x7da2049626b0>, <ast.Subscript object at 0x7da204960190>]]]].reshape, parameter[tuple[[<ast.UnaryOp object at 0x7da2049624d0>, <ast.Constant object at 0x7da204962ef0>, <ast.Constant object at 0x7da204960580>]]]] call[name[meshes].append, parameter[call[name[load_path], parameter[name[segments]]]]] call[call[name[meshes]][<ast.UnaryOp object at 0x7da2049616c0>].apply_transform, parameter[name[camera_transform]]] return[name[meshes]]
keyword[def] identifier[camera_marker] ( identifier[camera] , identifier[marker_height] = literal[int] , identifier[origin_size] = keyword[None] ): literal[string] identifier[camera_transform] = identifier[camera] . identifier[transform] keyword[if] identifier[camera_transform] keyword[is] keyword[None] : identifier[camera_transform] = identifier[np] . identifier[eye] ( literal[int] ) identifier[meshes] =[ identifier[axis] ( identifier[origin_size] = identifier[marker_height] / literal[int] )] identifier[meshes] [ literal[int] ]. identifier[apply_transform] ( identifier[camera_transform] ) keyword[try] : keyword[from] . identifier[path] . identifier[exchange] . identifier[load] keyword[import] identifier[load_path] keyword[except] identifier[ImportError] : identifier[log] . identifier[warning] ( literal[string] , identifier[exc_info] = keyword[True] ) keyword[return] identifier[meshes] keyword[if] identifier[origin_size] keyword[is] keyword[None] : identifier[origin_size] = identifier[marker_height] / literal[int] identifier[x] = identifier[marker_height] * identifier[np] . identifier[tan] ( identifier[np] . identifier[deg2rad] ( identifier[camera] . identifier[fov] [ literal[int] ])/ literal[int] ) identifier[y] = identifier[marker_height] * identifier[np] . identifier[tan] ( identifier[np] . identifier[deg2rad] ( identifier[camera] . identifier[fov] [ literal[int] ])/ literal[int] ) identifier[z] = identifier[marker_height] identifier[points] = identifier[np] . identifier[array] ( [( literal[int] , literal[int] , literal[int] ), (- identifier[x] ,- identifier[y] , identifier[z] ), ( identifier[x] ,- identifier[y] , identifier[z] ), ( identifier[x] , identifier[y] , identifier[z] ), (- identifier[x] , identifier[y] , identifier[z] )], identifier[dtype] = identifier[float] ) identifier[segments] = identifier[np] . identifier[column_stack] ( ( identifier[np] . identifier[zeros_like] ( identifier[points] ), identifier[points] )). identifier[reshape] ( (- literal[int] , literal[int] )) identifier[segments] = identifier[np] . identifier[vstack] (( identifier[segments] , identifier[points] [[ literal[int] , literal[int] , literal[int] , literal[int] , literal[int] , literal[int] , literal[int] , literal[int] ]])). identifier[reshape] ((- literal[int] , literal[int] , literal[int] )) identifier[meshes] . identifier[append] ( identifier[load_path] ( identifier[segments] )) identifier[meshes] [- literal[int] ]. identifier[apply_transform] ( identifier[camera_transform] ) keyword[return] identifier[meshes]
def camera_marker(camera, marker_height=0.4, origin_size=None): """ Create a visual marker for a camera object, including an axis and FOV. Parameters --------------- camera : trimesh.scene.Camera Camera object with FOV and transform defined marker_height : float How far along the camera Z should FOV indicators be origin_size : float Sphere radius of the origin (default: marker_height / 10.0) Returns ------------ meshes : list Contains Trimesh and Path3D objects which can be visualized """ camera_transform = camera.transform if camera_transform is None: camera_transform = np.eye(4) # depends on [control=['if'], data=['camera_transform']] # append the visualizations to an array meshes = [axis(origin_size=marker_height / 10.0)] meshes[0].apply_transform(camera_transform) try: # path is a soft dependency from .path.exchange.load import load_path # depends on [control=['try'], data=[]] except ImportError: # they probably don't have shapely installed log.warning('unable to create FOV visualization!', exc_info=True) return meshes # depends on [control=['except'], data=[]] # create sane origin size from marker height if origin_size is None: origin_size = marker_height / 10.0 # depends on [control=['if'], data=['origin_size']] # calculate vertices from camera FOV angles x = marker_height * np.tan(np.deg2rad(camera.fov[0]) / 2.0) y = marker_height * np.tan(np.deg2rad(camera.fov[1]) / 2.0) z = marker_height # combine the points into the vertices of an FOV visualization points = np.array([(0, 0, 0), (-x, -y, z), (x, -y, z), (x, y, z), (-x, y, z)], dtype=float) # create line segments for the FOV visualization # a segment from the origin to each bound of the FOV segments = np.column_stack((np.zeros_like(points), points)).reshape((-1, 3)) # add a loop for the outside of the FOV then reshape # the whole thing into multiple line segments segments = np.vstack((segments, points[[1, 2, 2, 3, 3, 4, 4, 1]])).reshape((-1, 2, 3)) # add a single Path3D object for all line segments meshes.append(load_path(segments)) meshes[-1].apply_transform(camera_transform) return meshes
def finalize_response(self, request, response, *args, **kwargs): """ Returns the final response object. """ # Make the error obvious if a proper response is not returned assert isinstance(response, HttpResponseBase), ( 'Expected a `Response`, `HttpResponse` or `HttpStreamingResponse` ' 'to be returned from the view, but received a `%s`' % type(response) ) if isinstance(response, Response): if not getattr(request, 'accepted_renderer', None): neg = self.perform_content_negotiation(request, force=True) request.accepted_renderer, request.accepted_media_type = neg response.accepted_renderer = request.accepted_renderer response.accepted_media_type = request.accepted_media_type response.renderer_context = self.get_renderer_context() for key, value in self.headers.items(): response[key] = value return response
def function[finalize_response, parameter[self, request, response]]: constant[ Returns the final response object. ] assert[call[name[isinstance], parameter[name[response], name[HttpResponseBase]]]] if call[name[isinstance], parameter[name[response], name[Response]]] begin[:] if <ast.UnaryOp object at 0x7da1b1529510> begin[:] variable[neg] assign[=] call[name[self].perform_content_negotiation, parameter[name[request]]] <ast.Tuple object at 0x7da1b1303010> assign[=] name[neg] name[response].accepted_renderer assign[=] name[request].accepted_renderer name[response].accepted_media_type assign[=] name[request].accepted_media_type name[response].renderer_context assign[=] call[name[self].get_renderer_context, parameter[]] for taget[tuple[[<ast.Name object at 0x7da1b13007c0>, <ast.Name object at 0x7da1b1300a60>]]] in starred[call[name[self].headers.items, parameter[]]] begin[:] call[name[response]][name[key]] assign[=] name[value] return[name[response]]
keyword[def] identifier[finalize_response] ( identifier[self] , identifier[request] , identifier[response] ,* identifier[args] ,** identifier[kwargs] ): literal[string] keyword[assert] identifier[isinstance] ( identifier[response] , identifier[HttpResponseBase] ),( literal[string] literal[string] % identifier[type] ( identifier[response] ) ) keyword[if] identifier[isinstance] ( identifier[response] , identifier[Response] ): keyword[if] keyword[not] identifier[getattr] ( identifier[request] , literal[string] , keyword[None] ): identifier[neg] = identifier[self] . identifier[perform_content_negotiation] ( identifier[request] , identifier[force] = keyword[True] ) identifier[request] . identifier[accepted_renderer] , identifier[request] . identifier[accepted_media_type] = identifier[neg] identifier[response] . identifier[accepted_renderer] = identifier[request] . identifier[accepted_renderer] identifier[response] . identifier[accepted_media_type] = identifier[request] . identifier[accepted_media_type] identifier[response] . identifier[renderer_context] = identifier[self] . identifier[get_renderer_context] () keyword[for] identifier[key] , identifier[value] keyword[in] identifier[self] . identifier[headers] . identifier[items] (): identifier[response] [ identifier[key] ]= identifier[value] keyword[return] identifier[response]
def finalize_response(self, request, response, *args, **kwargs): """ Returns the final response object. """ # Make the error obvious if a proper response is not returned assert isinstance(response, HttpResponseBase), 'Expected a `Response`, `HttpResponse` or `HttpStreamingResponse` to be returned from the view, but received a `%s`' % type(response) if isinstance(response, Response): if not getattr(request, 'accepted_renderer', None): neg = self.perform_content_negotiation(request, force=True) (request.accepted_renderer, request.accepted_media_type) = neg # depends on [control=['if'], data=[]] response.accepted_renderer = request.accepted_renderer response.accepted_media_type = request.accepted_media_type response.renderer_context = self.get_renderer_context() # depends on [control=['if'], data=[]] for (key, value) in self.headers.items(): response[key] = value # depends on [control=['for'], data=[]] return response
def tf_demo_loss(self, states, actions, terminal, reward, internals, update, reference=None): """ Extends the q-model loss via the dqfd large-margin loss. """ embedding = self.network.apply(x=states, internals=internals, update=update) deltas = list() for name in sorted(actions): action = actions[name] distr_params = self.distributions[name].parameterize(x=embedding) state_action_value = self.distributions[name].state_action_value(distr_params=distr_params, action=action) # Create the supervised margin loss # Zero for the action taken, one for all other actions, now multiply by expert margin if self.actions_spec[name]['type'] == 'bool': num_actions = 2 action = tf.cast(x=action, dtype=util.tf_dtype('int')) else: num_actions = self.actions_spec[name]['num_actions'] one_hot = tf.one_hot(indices=action, depth=num_actions) ones = tf.ones_like(tensor=one_hot, dtype=tf.float32) inverted_one_hot = ones - one_hot # max_a([Q(s,a) + l(s,a_E,a)], l(s,a_E, a) is 0 for expert action and margin value for others state_action_values = self.distributions[name].state_action_value(distr_params=distr_params) state_action_values = state_action_values + inverted_one_hot * self.expert_margin supervised_selector = tf.reduce_max(input_tensor=state_action_values, axis=-1) # J_E(Q) = max_a([Q(s,a) + l(s,a_E,a)] - Q(s,a_E) delta = supervised_selector - state_action_value action_size = util.prod(self.actions_spec[name]['shape']) delta = tf.reshape(tensor=delta, shape=(-1, action_size)) deltas.append(delta) loss_per_instance = tf.reduce_mean(input_tensor=tf.concat(values=deltas, axis=1), axis=1) loss_per_instance = tf.square(x=loss_per_instance) return tf.reduce_mean(input_tensor=loss_per_instance, axis=0)
def function[tf_demo_loss, parameter[self, states, actions, terminal, reward, internals, update, reference]]: constant[ Extends the q-model loss via the dqfd large-margin loss. ] variable[embedding] assign[=] call[name[self].network.apply, parameter[]] variable[deltas] assign[=] call[name[list], parameter[]] for taget[name[name]] in starred[call[name[sorted], parameter[name[actions]]]] begin[:] variable[action] assign[=] call[name[actions]][name[name]] variable[distr_params] assign[=] call[call[name[self].distributions][name[name]].parameterize, parameter[]] variable[state_action_value] assign[=] call[call[name[self].distributions][name[name]].state_action_value, parameter[]] if compare[call[call[name[self].actions_spec][name[name]]][constant[type]] equal[==] constant[bool]] begin[:] variable[num_actions] assign[=] constant[2] variable[action] assign[=] call[name[tf].cast, parameter[]] variable[one_hot] assign[=] call[name[tf].one_hot, parameter[]] variable[ones] assign[=] call[name[tf].ones_like, parameter[]] variable[inverted_one_hot] assign[=] binary_operation[name[ones] - name[one_hot]] variable[state_action_values] assign[=] call[call[name[self].distributions][name[name]].state_action_value, parameter[]] variable[state_action_values] assign[=] binary_operation[name[state_action_values] + binary_operation[name[inverted_one_hot] * name[self].expert_margin]] variable[supervised_selector] assign[=] call[name[tf].reduce_max, parameter[]] variable[delta] assign[=] binary_operation[name[supervised_selector] - name[state_action_value]] variable[action_size] assign[=] call[name[util].prod, parameter[call[call[name[self].actions_spec][name[name]]][constant[shape]]]] variable[delta] assign[=] call[name[tf].reshape, parameter[]] call[name[deltas].append, parameter[name[delta]]] variable[loss_per_instance] assign[=] call[name[tf].reduce_mean, parameter[]] variable[loss_per_instance] assign[=] call[name[tf].square, parameter[]] return[call[name[tf].reduce_mean, parameter[]]]
keyword[def] identifier[tf_demo_loss] ( identifier[self] , identifier[states] , identifier[actions] , identifier[terminal] , identifier[reward] , identifier[internals] , identifier[update] , identifier[reference] = keyword[None] ): literal[string] identifier[embedding] = identifier[self] . identifier[network] . identifier[apply] ( identifier[x] = identifier[states] , identifier[internals] = identifier[internals] , identifier[update] = identifier[update] ) identifier[deltas] = identifier[list] () keyword[for] identifier[name] keyword[in] identifier[sorted] ( identifier[actions] ): identifier[action] = identifier[actions] [ identifier[name] ] identifier[distr_params] = identifier[self] . identifier[distributions] [ identifier[name] ]. identifier[parameterize] ( identifier[x] = identifier[embedding] ) identifier[state_action_value] = identifier[self] . identifier[distributions] [ identifier[name] ]. identifier[state_action_value] ( identifier[distr_params] = identifier[distr_params] , identifier[action] = identifier[action] ) keyword[if] identifier[self] . identifier[actions_spec] [ identifier[name] ][ literal[string] ]== literal[string] : identifier[num_actions] = literal[int] identifier[action] = identifier[tf] . identifier[cast] ( identifier[x] = identifier[action] , identifier[dtype] = identifier[util] . identifier[tf_dtype] ( literal[string] )) keyword[else] : identifier[num_actions] = identifier[self] . identifier[actions_spec] [ identifier[name] ][ literal[string] ] identifier[one_hot] = identifier[tf] . identifier[one_hot] ( identifier[indices] = identifier[action] , identifier[depth] = identifier[num_actions] ) identifier[ones] = identifier[tf] . identifier[ones_like] ( identifier[tensor] = identifier[one_hot] , identifier[dtype] = identifier[tf] . identifier[float32] ) identifier[inverted_one_hot] = identifier[ones] - identifier[one_hot] identifier[state_action_values] = identifier[self] . identifier[distributions] [ identifier[name] ]. identifier[state_action_value] ( identifier[distr_params] = identifier[distr_params] ) identifier[state_action_values] = identifier[state_action_values] + identifier[inverted_one_hot] * identifier[self] . identifier[expert_margin] identifier[supervised_selector] = identifier[tf] . identifier[reduce_max] ( identifier[input_tensor] = identifier[state_action_values] , identifier[axis] =- literal[int] ) identifier[delta] = identifier[supervised_selector] - identifier[state_action_value] identifier[action_size] = identifier[util] . identifier[prod] ( identifier[self] . identifier[actions_spec] [ identifier[name] ][ literal[string] ]) identifier[delta] = identifier[tf] . identifier[reshape] ( identifier[tensor] = identifier[delta] , identifier[shape] =(- literal[int] , identifier[action_size] )) identifier[deltas] . identifier[append] ( identifier[delta] ) identifier[loss_per_instance] = identifier[tf] . identifier[reduce_mean] ( identifier[input_tensor] = identifier[tf] . identifier[concat] ( identifier[values] = identifier[deltas] , identifier[axis] = literal[int] ), identifier[axis] = literal[int] ) identifier[loss_per_instance] = identifier[tf] . identifier[square] ( identifier[x] = identifier[loss_per_instance] ) keyword[return] identifier[tf] . identifier[reduce_mean] ( identifier[input_tensor] = identifier[loss_per_instance] , identifier[axis] = literal[int] )
def tf_demo_loss(self, states, actions, terminal, reward, internals, update, reference=None): """ Extends the q-model loss via the dqfd large-margin loss. """ embedding = self.network.apply(x=states, internals=internals, update=update) deltas = list() for name in sorted(actions): action = actions[name] distr_params = self.distributions[name].parameterize(x=embedding) state_action_value = self.distributions[name].state_action_value(distr_params=distr_params, action=action) # Create the supervised margin loss # Zero for the action taken, one for all other actions, now multiply by expert margin if self.actions_spec[name]['type'] == 'bool': num_actions = 2 action = tf.cast(x=action, dtype=util.tf_dtype('int')) # depends on [control=['if'], data=[]] else: num_actions = self.actions_spec[name]['num_actions'] one_hot = tf.one_hot(indices=action, depth=num_actions) ones = tf.ones_like(tensor=one_hot, dtype=tf.float32) inverted_one_hot = ones - one_hot # max_a([Q(s,a) + l(s,a_E,a)], l(s,a_E, a) is 0 for expert action and margin value for others state_action_values = self.distributions[name].state_action_value(distr_params=distr_params) state_action_values = state_action_values + inverted_one_hot * self.expert_margin supervised_selector = tf.reduce_max(input_tensor=state_action_values, axis=-1) # J_E(Q) = max_a([Q(s,a) + l(s,a_E,a)] - Q(s,a_E) delta = supervised_selector - state_action_value action_size = util.prod(self.actions_spec[name]['shape']) delta = tf.reshape(tensor=delta, shape=(-1, action_size)) deltas.append(delta) # depends on [control=['for'], data=['name']] loss_per_instance = tf.reduce_mean(input_tensor=tf.concat(values=deltas, axis=1), axis=1) loss_per_instance = tf.square(x=loss_per_instance) return tf.reduce_mean(input_tensor=loss_per_instance, axis=0)
def nameop_set_collided( cls, nameop, history_id_key, history_id ): """ Mark a nameop as collided """ nameop['__collided__'] = True nameop['__collided_history_id_key__'] = history_id_key nameop['__collided_history_id__'] = history_id
def function[nameop_set_collided, parameter[cls, nameop, history_id_key, history_id]]: constant[ Mark a nameop as collided ] call[name[nameop]][constant[__collided__]] assign[=] constant[True] call[name[nameop]][constant[__collided_history_id_key__]] assign[=] name[history_id_key] call[name[nameop]][constant[__collided_history_id__]] assign[=] name[history_id]
keyword[def] identifier[nameop_set_collided] ( identifier[cls] , identifier[nameop] , identifier[history_id_key] , identifier[history_id] ): literal[string] identifier[nameop] [ literal[string] ]= keyword[True] identifier[nameop] [ literal[string] ]= identifier[history_id_key] identifier[nameop] [ literal[string] ]= identifier[history_id]
def nameop_set_collided(cls, nameop, history_id_key, history_id): """ Mark a nameop as collided """ nameop['__collided__'] = True nameop['__collided_history_id_key__'] = history_id_key nameop['__collided_history_id__'] = history_id
def signup(remote_app): """Extra signup step.""" if remote_app not in current_oauthclient.signup_handlers: return abort(404) res = current_oauthclient.signup_handlers[remote_app]['view']() return abort(404) if res is None else res
def function[signup, parameter[remote_app]]: constant[Extra signup step.] if compare[name[remote_app] <ast.NotIn object at 0x7da2590d7190> name[current_oauthclient].signup_handlers] begin[:] return[call[name[abort], parameter[constant[404]]]] variable[res] assign[=] call[call[call[name[current_oauthclient].signup_handlers][name[remote_app]]][constant[view]], parameter[]] return[<ast.IfExp object at 0x7da1b255ce20>]
keyword[def] identifier[signup] ( identifier[remote_app] ): literal[string] keyword[if] identifier[remote_app] keyword[not] keyword[in] identifier[current_oauthclient] . identifier[signup_handlers] : keyword[return] identifier[abort] ( literal[int] ) identifier[res] = identifier[current_oauthclient] . identifier[signup_handlers] [ identifier[remote_app] ][ literal[string] ]() keyword[return] identifier[abort] ( literal[int] ) keyword[if] identifier[res] keyword[is] keyword[None] keyword[else] identifier[res]
def signup(remote_app): """Extra signup step.""" if remote_app not in current_oauthclient.signup_handlers: return abort(404) # depends on [control=['if'], data=[]] res = current_oauthclient.signup_handlers[remote_app]['view']() return abort(404) if res is None else res
def fastq(args): """ %prog fastq bamfile prefix Convert BAM files to paired FASTQ files. """ p = OptionParser(fastq.__doc__) opts, args = p.parse_args(args) if len(args) != 2: sys.exit(not p.print_help()) bamfile, pf = args singletons = pf + ".se.fastq" a = pf + ".read1.fastq" b = pf + ".read2.fastq" cmd = "samtools collate -uOn 128 {} tmp-prefix".format(bamfile) cmd += " | samtools fastq -s {} -1 {} -2 {} -"\ .format(singletons, a, b) sh(cmd) if os.stat(singletons).st_size == 0: # singleton file is empty os.remove(singletons) return a, b
def function[fastq, parameter[args]]: constant[ %prog fastq bamfile prefix Convert BAM files to paired FASTQ files. ] variable[p] assign[=] call[name[OptionParser], parameter[name[fastq].__doc__]] <ast.Tuple object at 0x7da18fe92d70> assign[=] call[name[p].parse_args, parameter[name[args]]] if compare[call[name[len], parameter[name[args]]] not_equal[!=] constant[2]] begin[:] call[name[sys].exit, parameter[<ast.UnaryOp object at 0x7da18fe92200>]] <ast.Tuple object at 0x7da18fe90f40> assign[=] name[args] variable[singletons] assign[=] binary_operation[name[pf] + constant[.se.fastq]] variable[a] assign[=] binary_operation[name[pf] + constant[.read1.fastq]] variable[b] assign[=] binary_operation[name[pf] + constant[.read2.fastq]] variable[cmd] assign[=] call[constant[samtools collate -uOn 128 {} tmp-prefix].format, parameter[name[bamfile]]] <ast.AugAssign object at 0x7da18fe92da0> call[name[sh], parameter[name[cmd]]] if compare[call[name[os].stat, parameter[name[singletons]]].st_size equal[==] constant[0]] begin[:] call[name[os].remove, parameter[name[singletons]]] return[tuple[[<ast.Name object at 0x7da20c6e6110>, <ast.Name object at 0x7da20c6e7bb0>]]]
keyword[def] identifier[fastq] ( identifier[args] ): literal[string] identifier[p] = identifier[OptionParser] ( identifier[fastq] . identifier[__doc__] ) identifier[opts] , identifier[args] = identifier[p] . identifier[parse_args] ( identifier[args] ) keyword[if] identifier[len] ( identifier[args] )!= literal[int] : identifier[sys] . identifier[exit] ( keyword[not] identifier[p] . identifier[print_help] ()) identifier[bamfile] , identifier[pf] = identifier[args] identifier[singletons] = identifier[pf] + literal[string] identifier[a] = identifier[pf] + literal[string] identifier[b] = identifier[pf] + literal[string] identifier[cmd] = literal[string] . identifier[format] ( identifier[bamfile] ) identifier[cmd] += literal[string] . identifier[format] ( identifier[singletons] , identifier[a] , identifier[b] ) identifier[sh] ( identifier[cmd] ) keyword[if] identifier[os] . identifier[stat] ( identifier[singletons] ). identifier[st_size] == literal[int] : identifier[os] . identifier[remove] ( identifier[singletons] ) keyword[return] identifier[a] , identifier[b]
def fastq(args): """ %prog fastq bamfile prefix Convert BAM files to paired FASTQ files. """ p = OptionParser(fastq.__doc__) (opts, args) = p.parse_args(args) if len(args) != 2: sys.exit(not p.print_help()) # depends on [control=['if'], data=[]] (bamfile, pf) = args singletons = pf + '.se.fastq' a = pf + '.read1.fastq' b = pf + '.read2.fastq' cmd = 'samtools collate -uOn 128 {} tmp-prefix'.format(bamfile) cmd += ' | samtools fastq -s {} -1 {} -2 {} -'.format(singletons, a, b) sh(cmd) if os.stat(singletons).st_size == 0: # singleton file is empty os.remove(singletons) # depends on [control=['if'], data=[]] return (a, b)
def from_envvars(prefix=None, environ=None, envvars=None, as_json=True): """Load environment variables in a dictionary Values are parsed as JSON. If parsing fails with a ValueError, values are instead used as verbatim strings. :param prefix: If ``None`` is passed as envvars, all variables from ``environ`` starting with this prefix are imported. The prefix is stripped upon import. :param envvars: A dictionary of mappings of environment-variable-names to Flask configuration names. If a list is passed instead, names are mapped 1:1. If ``None``, see prefix argument. :param environ: use this dictionary instead of os.environ; this is here mostly for mockability :param as_json: If False, values will not be parsed as JSON first. """ conf = {} if environ is None: environ = os.environ if prefix is None and envvars is None: raise RuntimeError('Must either give prefix or envvars argument') # if it's a list, convert to dict if isinstance(envvars, list): envvars = {k: k for k in envvars} if not envvars: envvars = {k: k[len(prefix):] for k in environ.keys() if k.startswith(prefix)} for env_name, name in envvars.items(): if env_name not in environ: continue if as_json: try: conf[name] = json.loads(environ[env_name]) except ValueError: conf[name] = environ[env_name] else: conf[name] = environ[env_name] return conf
def function[from_envvars, parameter[prefix, environ, envvars, as_json]]: constant[Load environment variables in a dictionary Values are parsed as JSON. If parsing fails with a ValueError, values are instead used as verbatim strings. :param prefix: If ``None`` is passed as envvars, all variables from ``environ`` starting with this prefix are imported. The prefix is stripped upon import. :param envvars: A dictionary of mappings of environment-variable-names to Flask configuration names. If a list is passed instead, names are mapped 1:1. If ``None``, see prefix argument. :param environ: use this dictionary instead of os.environ; this is here mostly for mockability :param as_json: If False, values will not be parsed as JSON first. ] variable[conf] assign[=] dictionary[[], []] if compare[name[environ] is constant[None]] begin[:] variable[environ] assign[=] name[os].environ if <ast.BoolOp object at 0x7da1b26d55d0> begin[:] <ast.Raise object at 0x7da1b26d5270> if call[name[isinstance], parameter[name[envvars], name[list]]] begin[:] variable[envvars] assign[=] <ast.DictComp object at 0x7da1b26d6440> if <ast.UnaryOp object at 0x7da1b26d41f0> begin[:] variable[envvars] assign[=] <ast.DictComp object at 0x7da1b26d5360> for taget[tuple[[<ast.Name object at 0x7da1b26d42e0>, <ast.Name object at 0x7da1b26d6dd0>]]] in starred[call[name[envvars].items, parameter[]]] begin[:] if compare[name[env_name] <ast.NotIn object at 0x7da2590d7190> name[environ]] begin[:] continue if name[as_json] begin[:] <ast.Try object at 0x7da1b26a3e20> return[name[conf]]
keyword[def] identifier[from_envvars] ( identifier[prefix] = keyword[None] , identifier[environ] = keyword[None] , identifier[envvars] = keyword[None] , identifier[as_json] = keyword[True] ): literal[string] identifier[conf] ={} keyword[if] identifier[environ] keyword[is] keyword[None] : identifier[environ] = identifier[os] . identifier[environ] keyword[if] identifier[prefix] keyword[is] keyword[None] keyword[and] identifier[envvars] keyword[is] keyword[None] : keyword[raise] identifier[RuntimeError] ( literal[string] ) keyword[if] identifier[isinstance] ( identifier[envvars] , identifier[list] ): identifier[envvars] ={ identifier[k] : identifier[k] keyword[for] identifier[k] keyword[in] identifier[envvars] } keyword[if] keyword[not] identifier[envvars] : identifier[envvars] ={ identifier[k] : identifier[k] [ identifier[len] ( identifier[prefix] ):] keyword[for] identifier[k] keyword[in] identifier[environ] . identifier[keys] () keyword[if] identifier[k] . identifier[startswith] ( identifier[prefix] )} keyword[for] identifier[env_name] , identifier[name] keyword[in] identifier[envvars] . identifier[items] (): keyword[if] identifier[env_name] keyword[not] keyword[in] identifier[environ] : keyword[continue] keyword[if] identifier[as_json] : keyword[try] : identifier[conf] [ identifier[name] ]= identifier[json] . identifier[loads] ( identifier[environ] [ identifier[env_name] ]) keyword[except] identifier[ValueError] : identifier[conf] [ identifier[name] ]= identifier[environ] [ identifier[env_name] ] keyword[else] : identifier[conf] [ identifier[name] ]= identifier[environ] [ identifier[env_name] ] keyword[return] identifier[conf]
def from_envvars(prefix=None, environ=None, envvars=None, as_json=True): """Load environment variables in a dictionary Values are parsed as JSON. If parsing fails with a ValueError, values are instead used as verbatim strings. :param prefix: If ``None`` is passed as envvars, all variables from ``environ`` starting with this prefix are imported. The prefix is stripped upon import. :param envvars: A dictionary of mappings of environment-variable-names to Flask configuration names. If a list is passed instead, names are mapped 1:1. If ``None``, see prefix argument. :param environ: use this dictionary instead of os.environ; this is here mostly for mockability :param as_json: If False, values will not be parsed as JSON first. """ conf = {} if environ is None: environ = os.environ # depends on [control=['if'], data=['environ']] if prefix is None and envvars is None: raise RuntimeError('Must either give prefix or envvars argument') # depends on [control=['if'], data=[]] # if it's a list, convert to dict if isinstance(envvars, list): envvars = {k: k for k in envvars} # depends on [control=['if'], data=[]] if not envvars: envvars = {k: k[len(prefix):] for k in environ.keys() if k.startswith(prefix)} # depends on [control=['if'], data=[]] for (env_name, name) in envvars.items(): if env_name not in environ: continue # depends on [control=['if'], data=[]] if as_json: try: conf[name] = json.loads(environ[env_name]) # depends on [control=['try'], data=[]] except ValueError: conf[name] = environ[env_name] # depends on [control=['except'], data=[]] # depends on [control=['if'], data=[]] else: conf[name] = environ[env_name] # depends on [control=['for'], data=[]] return conf
def get_sequence_sliding_window_properties(self, scale, window, representative_only=True): """Run Biopython ProteinAnalysis with a sliding window to calculate a given property. Results are stored in the protein's respective SeqProp objects at ``.letter_annotations`` Args: scale (str): Scale name window (int): Sliding window size representative_only (bool): If analysis should only be run on the representative sequence """ if representative_only: # Check if a representative sequence was set if not self.representative_sequence: log.warning('{}: no representative sequence set, cannot get sequence properties'.format(self.id)) return # Also need to check if a sequence has been stored if not self.representative_sequence.seq: log.warning('{}: representative sequence {} set, but no sequence stored. ' 'Cannot get sequence properties.'.format(self.id, self.representative_sequence.id)) return self.representative_sequence.get_sliding_window_properties(scale=scale, window=window) if not representative_only: for s in self.sequences: # Need to check if a sequence has been stored if not s.seq: log.warning('{}: no sequence stored. ' 'Cannot get sequence properties.'.format(s.id)) continue else: s.get_sliding_window_properties(scale=scale, window=window)
def function[get_sequence_sliding_window_properties, parameter[self, scale, window, representative_only]]: constant[Run Biopython ProteinAnalysis with a sliding window to calculate a given property. Results are stored in the protein's respective SeqProp objects at ``.letter_annotations`` Args: scale (str): Scale name window (int): Sliding window size representative_only (bool): If analysis should only be run on the representative sequence ] if name[representative_only] begin[:] if <ast.UnaryOp object at 0x7da1b0ed0880> begin[:] call[name[log].warning, parameter[call[constant[{}: no representative sequence set, cannot get sequence properties].format, parameter[name[self].id]]]] return[None] if <ast.UnaryOp object at 0x7da1b0ed2e60> begin[:] call[name[log].warning, parameter[call[constant[{}: representative sequence {} set, but no sequence stored. Cannot get sequence properties.].format, parameter[name[self].id, name[self].representative_sequence.id]]]] return[None] call[name[self].representative_sequence.get_sliding_window_properties, parameter[]] if <ast.UnaryOp object at 0x7da1b0ed1720> begin[:] for taget[name[s]] in starred[name[self].sequences] begin[:] if <ast.UnaryOp object at 0x7da1b0ed11e0> begin[:] call[name[log].warning, parameter[call[constant[{}: no sequence stored. Cannot get sequence properties.].format, parameter[name[s].id]]]] continue
keyword[def] identifier[get_sequence_sliding_window_properties] ( identifier[self] , identifier[scale] , identifier[window] , identifier[representative_only] = keyword[True] ): literal[string] keyword[if] identifier[representative_only] : keyword[if] keyword[not] identifier[self] . identifier[representative_sequence] : identifier[log] . identifier[warning] ( literal[string] . identifier[format] ( identifier[self] . identifier[id] )) keyword[return] keyword[if] keyword[not] identifier[self] . identifier[representative_sequence] . identifier[seq] : identifier[log] . identifier[warning] ( literal[string] literal[string] . identifier[format] ( identifier[self] . identifier[id] , identifier[self] . identifier[representative_sequence] . identifier[id] )) keyword[return] identifier[self] . identifier[representative_sequence] . identifier[get_sliding_window_properties] ( identifier[scale] = identifier[scale] , identifier[window] = identifier[window] ) keyword[if] keyword[not] identifier[representative_only] : keyword[for] identifier[s] keyword[in] identifier[self] . identifier[sequences] : keyword[if] keyword[not] identifier[s] . identifier[seq] : identifier[log] . identifier[warning] ( literal[string] literal[string] . identifier[format] ( identifier[s] . identifier[id] )) keyword[continue] keyword[else] : identifier[s] . identifier[get_sliding_window_properties] ( identifier[scale] = identifier[scale] , identifier[window] = identifier[window] )
def get_sequence_sliding_window_properties(self, scale, window, representative_only=True): """Run Biopython ProteinAnalysis with a sliding window to calculate a given property. Results are stored in the protein's respective SeqProp objects at ``.letter_annotations`` Args: scale (str): Scale name window (int): Sliding window size representative_only (bool): If analysis should only be run on the representative sequence """ if representative_only: # Check if a representative sequence was set if not self.representative_sequence: log.warning('{}: no representative sequence set, cannot get sequence properties'.format(self.id)) return # depends on [control=['if'], data=[]] # Also need to check if a sequence has been stored if not self.representative_sequence.seq: log.warning('{}: representative sequence {} set, but no sequence stored. Cannot get sequence properties.'.format(self.id, self.representative_sequence.id)) return # depends on [control=['if'], data=[]] self.representative_sequence.get_sliding_window_properties(scale=scale, window=window) # depends on [control=['if'], data=[]] if not representative_only: for s in self.sequences: # Need to check if a sequence has been stored if not s.seq: log.warning('{}: no sequence stored. Cannot get sequence properties.'.format(s.id)) continue # depends on [control=['if'], data=[]] else: s.get_sliding_window_properties(scale=scale, window=window) # depends on [control=['for'], data=['s']] # depends on [control=['if'], data=[]]
def get_opener(self, protocol): # type: (Text) -> Opener """Get the opener class associated to a given protocol. Arguments: protocol (str): A filesystem protocol. Returns: Opener: an opener instance. Raises: ~fs.opener.errors.UnsupportedProtocol: If no opener could be found for the given protocol. EntryPointLoadingError: If the returned entry point is not an `Opener` subclass or could not be loaded successfully. """ protocol = protocol or self.default_opener if self.load_extern: entry_point = next( pkg_resources.iter_entry_points("fs.opener", protocol), None ) else: entry_point = None # If not entry point was loaded from the extensions, try looking # into the registered protocols if entry_point is None: if protocol in self._protocols: opener_instance = self._protocols[protocol] else: raise UnsupportedProtocol( "protocol '{}' is not supported".format(protocol) ) # If an entry point was found in an extension, attempt to load it else: try: opener = entry_point.load() except Exception as exception: raise EntryPointError( "could not load entry point; {}".format(exception) ) if not issubclass(opener, Opener): raise EntryPointError("entry point did not return an opener") try: opener_instance = opener() except Exception as exception: raise EntryPointError( "could not instantiate opener; {}".format(exception) ) return opener_instance
def function[get_opener, parameter[self, protocol]]: constant[Get the opener class associated to a given protocol. Arguments: protocol (str): A filesystem protocol. Returns: Opener: an opener instance. Raises: ~fs.opener.errors.UnsupportedProtocol: If no opener could be found for the given protocol. EntryPointLoadingError: If the returned entry point is not an `Opener` subclass or could not be loaded successfully. ] variable[protocol] assign[=] <ast.BoolOp object at 0x7da1b16c1e70> if name[self].load_extern begin[:] variable[entry_point] assign[=] call[name[next], parameter[call[name[pkg_resources].iter_entry_points, parameter[constant[fs.opener], name[protocol]]], constant[None]]] if compare[name[entry_point] is constant[None]] begin[:] if compare[name[protocol] in name[self]._protocols] begin[:] variable[opener_instance] assign[=] call[name[self]._protocols][name[protocol]] return[name[opener_instance]]
keyword[def] identifier[get_opener] ( identifier[self] , identifier[protocol] ): literal[string] identifier[protocol] = identifier[protocol] keyword[or] identifier[self] . identifier[default_opener] keyword[if] identifier[self] . identifier[load_extern] : identifier[entry_point] = identifier[next] ( identifier[pkg_resources] . identifier[iter_entry_points] ( literal[string] , identifier[protocol] ), keyword[None] ) keyword[else] : identifier[entry_point] = keyword[None] keyword[if] identifier[entry_point] keyword[is] keyword[None] : keyword[if] identifier[protocol] keyword[in] identifier[self] . identifier[_protocols] : identifier[opener_instance] = identifier[self] . identifier[_protocols] [ identifier[protocol] ] keyword[else] : keyword[raise] identifier[UnsupportedProtocol] ( literal[string] . identifier[format] ( identifier[protocol] ) ) keyword[else] : keyword[try] : identifier[opener] = identifier[entry_point] . identifier[load] () keyword[except] identifier[Exception] keyword[as] identifier[exception] : keyword[raise] identifier[EntryPointError] ( literal[string] . identifier[format] ( identifier[exception] ) ) keyword[if] keyword[not] identifier[issubclass] ( identifier[opener] , identifier[Opener] ): keyword[raise] identifier[EntryPointError] ( literal[string] ) keyword[try] : identifier[opener_instance] = identifier[opener] () keyword[except] identifier[Exception] keyword[as] identifier[exception] : keyword[raise] identifier[EntryPointError] ( literal[string] . identifier[format] ( identifier[exception] ) ) keyword[return] identifier[opener_instance]
def get_opener(self, protocol): # type: (Text) -> Opener 'Get the opener class associated to a given protocol.\n\n Arguments:\n protocol (str): A filesystem protocol.\n\n Returns:\n Opener: an opener instance.\n\n Raises:\n ~fs.opener.errors.UnsupportedProtocol: If no opener\n could be found for the given protocol.\n EntryPointLoadingError: If the returned entry point\n is not an `Opener` subclass or could not be loaded\n successfully.\n\n ' protocol = protocol or self.default_opener if self.load_extern: entry_point = next(pkg_resources.iter_entry_points('fs.opener', protocol), None) # depends on [control=['if'], data=[]] else: entry_point = None # If not entry point was loaded from the extensions, try looking # into the registered protocols if entry_point is None: if protocol in self._protocols: opener_instance = self._protocols[protocol] # depends on [control=['if'], data=['protocol']] else: raise UnsupportedProtocol("protocol '{}' is not supported".format(protocol)) # depends on [control=['if'], data=[]] else: # If an entry point was found in an extension, attempt to load it try: opener = entry_point.load() # depends on [control=['try'], data=[]] except Exception as exception: raise EntryPointError('could not load entry point; {}'.format(exception)) # depends on [control=['except'], data=['exception']] if not issubclass(opener, Opener): raise EntryPointError('entry point did not return an opener') # depends on [control=['if'], data=[]] try: opener_instance = opener() # depends on [control=['try'], data=[]] except Exception as exception: raise EntryPointError('could not instantiate opener; {}'.format(exception)) # depends on [control=['except'], data=['exception']] return opener_instance
def potential(__func__=None, **kwds): """ Decorator function instantiating potentials. Usage: @potential def B(parent_name = ., ...) return baz(parent_name, ...) where baz returns the deterministic B's value conditional on its parents. :SeeAlso: Deterministic, deterministic, Stochastic, Potential, stochastic, data, Model """ def instantiate_pot(__func__): junk, parents = _extract( __func__, kwds, keys, 'Potential', probe=False) return Potential(parents=parents, **kwds) keys = ['logp'] instantiate_pot.kwds = kwds if __func__: return instantiate_pot(__func__) return instantiate_pot
def function[potential, parameter[__func__]]: constant[ Decorator function instantiating potentials. Usage: @potential def B(parent_name = ., ...) return baz(parent_name, ...) where baz returns the deterministic B's value conditional on its parents. :SeeAlso: Deterministic, deterministic, Stochastic, Potential, stochastic, data, Model ] def function[instantiate_pot, parameter[__func__]]: <ast.Tuple object at 0x7da2041db6a0> assign[=] call[name[_extract], parameter[name[__func__], name[kwds], name[keys], constant[Potential]]] return[call[name[Potential], parameter[]]] variable[keys] assign[=] list[[<ast.Constant object at 0x7da2041d9600>]] name[instantiate_pot].kwds assign[=] name[kwds] if name[__func__] begin[:] return[call[name[instantiate_pot], parameter[name[__func__]]]] return[name[instantiate_pot]]
keyword[def] identifier[potential] ( identifier[__func__] = keyword[None] ,** identifier[kwds] ): literal[string] keyword[def] identifier[instantiate_pot] ( identifier[__func__] ): identifier[junk] , identifier[parents] = identifier[_extract] ( identifier[__func__] , identifier[kwds] , identifier[keys] , literal[string] , identifier[probe] = keyword[False] ) keyword[return] identifier[Potential] ( identifier[parents] = identifier[parents] ,** identifier[kwds] ) identifier[keys] =[ literal[string] ] identifier[instantiate_pot] . identifier[kwds] = identifier[kwds] keyword[if] identifier[__func__] : keyword[return] identifier[instantiate_pot] ( identifier[__func__] ) keyword[return] identifier[instantiate_pot]
def potential(__func__=None, **kwds): """ Decorator function instantiating potentials. Usage: @potential def B(parent_name = ., ...) return baz(parent_name, ...) where baz returns the deterministic B's value conditional on its parents. :SeeAlso: Deterministic, deterministic, Stochastic, Potential, stochastic, data, Model """ def instantiate_pot(__func__): (junk, parents) = _extract(__func__, kwds, keys, 'Potential', probe=False) return Potential(parents=parents, **kwds) keys = ['logp'] instantiate_pot.kwds = kwds if __func__: return instantiate_pot(__func__) # depends on [control=['if'], data=[]] return instantiate_pot
def write_data(data, out_file): """write json file from seqcluster cluster""" with open(out_file, 'w') as handle_out: handle_out.write(json.dumps([data], skipkeys=True, indent=2))
def function[write_data, parameter[data, out_file]]: constant[write json file from seqcluster cluster] with call[name[open], parameter[name[out_file], constant[w]]] begin[:] call[name[handle_out].write, parameter[call[name[json].dumps, parameter[list[[<ast.Name object at 0x7da1b033bdc0>]]]]]]
keyword[def] identifier[write_data] ( identifier[data] , identifier[out_file] ): literal[string] keyword[with] identifier[open] ( identifier[out_file] , literal[string] ) keyword[as] identifier[handle_out] : identifier[handle_out] . identifier[write] ( identifier[json] . identifier[dumps] ([ identifier[data] ], identifier[skipkeys] = keyword[True] , identifier[indent] = literal[int] ))
def write_data(data, out_file): """write json file from seqcluster cluster""" with open(out_file, 'w') as handle_out: handle_out.write(json.dumps([data], skipkeys=True, indent=2)) # depends on [control=['with'], data=['handle_out']]
def _check_reliability(self, old_value=None, new_value=None): """This function is called when the object is created and after one of its configuration properties has changed. The new and old value parameters are ignored, this is called after the property has been changed and this is only concerned with the current value.""" if _debug: LocalScheduleObject._debug("_check_reliability %r %r", old_value, new_value) try: schedule_default = self.scheduleDefault if schedule_default is None: raise ValueError("scheduleDefault expected") if not isinstance(schedule_default, Atomic): raise TypeError("scheduleDefault must be an instance of an atomic type") schedule_datatype = schedule_default.__class__ if _debug: LocalScheduleObject._debug(" - schedule_datatype: %r", schedule_datatype) if (self.weeklySchedule is None) and (self.exceptionSchedule is None): raise ValueError("schedule required") # check the weekly schedule values if self.weeklySchedule: for daily_schedule in self.weeklySchedule: for time_value in daily_schedule.daySchedule: if _debug: LocalScheduleObject._debug(" - daily time_value: %r", time_value) if time_value is None: pass elif not isinstance(time_value.value, (Null, schedule_datatype)): if _debug: LocalScheduleObject._debug(" - wrong type: expected %r, got %r", schedule_datatype, time_value.__class__, ) raise TypeError("wrong type") elif 255 in time_value.time: if _debug: LocalScheduleObject._debug(" - wildcard in time") raise ValueError("must be a specific time") # check the exception schedule values if self.exceptionSchedule: for special_event in self.exceptionSchedule: for time_value in special_event.listOfTimeValues: if _debug: LocalScheduleObject._debug(" - special event time_value: %r", time_value) if time_value is None: pass elif not isinstance(time_value.value, (Null, schedule_datatype)): if _debug: LocalScheduleObject._debug(" - wrong type: expected %r, got %r", schedule_datatype, time_value.__class__, ) raise TypeError("wrong type") # check list of object property references obj_prop_refs = self.listOfObjectPropertyReferences if obj_prop_refs: for obj_prop_ref in obj_prop_refs: if obj_prop_ref.deviceIdentifier: raise RuntimeError("no external references") # get the datatype of the property to be written obj_type = obj_prop_ref.objectIdentifier[0] datatype = get_datatype(obj_type, obj_prop_ref.propertyIdentifier) if _debug: LocalScheduleObject._debug(" - datatype: %r", datatype) if issubclass(datatype, Array) and (obj_prop_ref.propertyArrayIndex is not None): if obj_prop_ref.propertyArrayIndex == 0: datatype = Unsigned else: datatype = datatype.subtype if _debug: LocalScheduleObject._debug(" - datatype: %r", datatype) if datatype is not schedule_datatype: if _debug: LocalScheduleObject._debug(" - wrong type: expected %r, got %r", datatype, schedule_datatype, ) raise TypeError("wrong type") # all good self.reliability = 'noFaultDetected' if _debug: LocalScheduleObject._debug(" - no fault detected") except Exception as err: if _debug: LocalScheduleObject._debug(" - exception: %r", err) self.reliability = 'configurationError'
def function[_check_reliability, parameter[self, old_value, new_value]]: constant[This function is called when the object is created and after one of its configuration properties has changed. The new and old value parameters are ignored, this is called after the property has been changed and this is only concerned with the current value.] if name[_debug] begin[:] call[name[LocalScheduleObject]._debug, parameter[constant[_check_reliability %r %r], name[old_value], name[new_value]]] <ast.Try object at 0x7da1b26afe50>
keyword[def] identifier[_check_reliability] ( identifier[self] , identifier[old_value] = keyword[None] , identifier[new_value] = keyword[None] ): literal[string] keyword[if] identifier[_debug] : identifier[LocalScheduleObject] . identifier[_debug] ( literal[string] , identifier[old_value] , identifier[new_value] ) keyword[try] : identifier[schedule_default] = identifier[self] . identifier[scheduleDefault] keyword[if] identifier[schedule_default] keyword[is] keyword[None] : keyword[raise] identifier[ValueError] ( literal[string] ) keyword[if] keyword[not] identifier[isinstance] ( identifier[schedule_default] , identifier[Atomic] ): keyword[raise] identifier[TypeError] ( literal[string] ) identifier[schedule_datatype] = identifier[schedule_default] . identifier[__class__] keyword[if] identifier[_debug] : identifier[LocalScheduleObject] . identifier[_debug] ( literal[string] , identifier[schedule_datatype] ) keyword[if] ( identifier[self] . identifier[weeklySchedule] keyword[is] keyword[None] ) keyword[and] ( identifier[self] . identifier[exceptionSchedule] keyword[is] keyword[None] ): keyword[raise] identifier[ValueError] ( literal[string] ) keyword[if] identifier[self] . identifier[weeklySchedule] : keyword[for] identifier[daily_schedule] keyword[in] identifier[self] . identifier[weeklySchedule] : keyword[for] identifier[time_value] keyword[in] identifier[daily_schedule] . identifier[daySchedule] : keyword[if] identifier[_debug] : identifier[LocalScheduleObject] . identifier[_debug] ( literal[string] , identifier[time_value] ) keyword[if] identifier[time_value] keyword[is] keyword[None] : keyword[pass] keyword[elif] keyword[not] identifier[isinstance] ( identifier[time_value] . identifier[value] ,( identifier[Null] , identifier[schedule_datatype] )): keyword[if] identifier[_debug] : identifier[LocalScheduleObject] . identifier[_debug] ( literal[string] , identifier[schedule_datatype] , identifier[time_value] . identifier[__class__] , ) keyword[raise] identifier[TypeError] ( literal[string] ) keyword[elif] literal[int] keyword[in] identifier[time_value] . identifier[time] : keyword[if] identifier[_debug] : identifier[LocalScheduleObject] . identifier[_debug] ( literal[string] ) keyword[raise] identifier[ValueError] ( literal[string] ) keyword[if] identifier[self] . identifier[exceptionSchedule] : keyword[for] identifier[special_event] keyword[in] identifier[self] . identifier[exceptionSchedule] : keyword[for] identifier[time_value] keyword[in] identifier[special_event] . identifier[listOfTimeValues] : keyword[if] identifier[_debug] : identifier[LocalScheduleObject] . identifier[_debug] ( literal[string] , identifier[time_value] ) keyword[if] identifier[time_value] keyword[is] keyword[None] : keyword[pass] keyword[elif] keyword[not] identifier[isinstance] ( identifier[time_value] . identifier[value] ,( identifier[Null] , identifier[schedule_datatype] )): keyword[if] identifier[_debug] : identifier[LocalScheduleObject] . identifier[_debug] ( literal[string] , identifier[schedule_datatype] , identifier[time_value] . identifier[__class__] , ) keyword[raise] identifier[TypeError] ( literal[string] ) identifier[obj_prop_refs] = identifier[self] . identifier[listOfObjectPropertyReferences] keyword[if] identifier[obj_prop_refs] : keyword[for] identifier[obj_prop_ref] keyword[in] identifier[obj_prop_refs] : keyword[if] identifier[obj_prop_ref] . identifier[deviceIdentifier] : keyword[raise] identifier[RuntimeError] ( literal[string] ) identifier[obj_type] = identifier[obj_prop_ref] . identifier[objectIdentifier] [ literal[int] ] identifier[datatype] = identifier[get_datatype] ( identifier[obj_type] , identifier[obj_prop_ref] . identifier[propertyIdentifier] ) keyword[if] identifier[_debug] : identifier[LocalScheduleObject] . identifier[_debug] ( literal[string] , identifier[datatype] ) keyword[if] identifier[issubclass] ( identifier[datatype] , identifier[Array] ) keyword[and] ( identifier[obj_prop_ref] . identifier[propertyArrayIndex] keyword[is] keyword[not] keyword[None] ): keyword[if] identifier[obj_prop_ref] . identifier[propertyArrayIndex] == literal[int] : identifier[datatype] = identifier[Unsigned] keyword[else] : identifier[datatype] = identifier[datatype] . identifier[subtype] keyword[if] identifier[_debug] : identifier[LocalScheduleObject] . identifier[_debug] ( literal[string] , identifier[datatype] ) keyword[if] identifier[datatype] keyword[is] keyword[not] identifier[schedule_datatype] : keyword[if] identifier[_debug] : identifier[LocalScheduleObject] . identifier[_debug] ( literal[string] , identifier[datatype] , identifier[schedule_datatype] , ) keyword[raise] identifier[TypeError] ( literal[string] ) identifier[self] . identifier[reliability] = literal[string] keyword[if] identifier[_debug] : identifier[LocalScheduleObject] . identifier[_debug] ( literal[string] ) keyword[except] identifier[Exception] keyword[as] identifier[err] : keyword[if] identifier[_debug] : identifier[LocalScheduleObject] . identifier[_debug] ( literal[string] , identifier[err] ) identifier[self] . identifier[reliability] = literal[string]
def _check_reliability(self, old_value=None, new_value=None): """This function is called when the object is created and after one of its configuration properties has changed. The new and old value parameters are ignored, this is called after the property has been changed and this is only concerned with the current value.""" if _debug: LocalScheduleObject._debug('_check_reliability %r %r', old_value, new_value) # depends on [control=['if'], data=[]] try: schedule_default = self.scheduleDefault if schedule_default is None: raise ValueError('scheduleDefault expected') # depends on [control=['if'], data=[]] if not isinstance(schedule_default, Atomic): raise TypeError('scheduleDefault must be an instance of an atomic type') # depends on [control=['if'], data=[]] schedule_datatype = schedule_default.__class__ if _debug: LocalScheduleObject._debug(' - schedule_datatype: %r', schedule_datatype) # depends on [control=['if'], data=[]] if self.weeklySchedule is None and self.exceptionSchedule is None: raise ValueError('schedule required') # depends on [control=['if'], data=[]] # check the weekly schedule values if self.weeklySchedule: for daily_schedule in self.weeklySchedule: for time_value in daily_schedule.daySchedule: if _debug: LocalScheduleObject._debug(' - daily time_value: %r', time_value) # depends on [control=['if'], data=[]] if time_value is None: pass # depends on [control=['if'], data=[]] elif not isinstance(time_value.value, (Null, schedule_datatype)): if _debug: LocalScheduleObject._debug(' - wrong type: expected %r, got %r', schedule_datatype, time_value.__class__) # depends on [control=['if'], data=[]] raise TypeError('wrong type') # depends on [control=['if'], data=[]] elif 255 in time_value.time: if _debug: LocalScheduleObject._debug(' - wildcard in time') # depends on [control=['if'], data=[]] raise ValueError('must be a specific time') # depends on [control=['if'], data=[]] # depends on [control=['for'], data=['time_value']] # depends on [control=['for'], data=['daily_schedule']] # depends on [control=['if'], data=[]] # check the exception schedule values if self.exceptionSchedule: for special_event in self.exceptionSchedule: for time_value in special_event.listOfTimeValues: if _debug: LocalScheduleObject._debug(' - special event time_value: %r', time_value) # depends on [control=['if'], data=[]] if time_value is None: pass # depends on [control=['if'], data=[]] elif not isinstance(time_value.value, (Null, schedule_datatype)): if _debug: LocalScheduleObject._debug(' - wrong type: expected %r, got %r', schedule_datatype, time_value.__class__) # depends on [control=['if'], data=[]] raise TypeError('wrong type') # depends on [control=['if'], data=[]] # depends on [control=['for'], data=['time_value']] # depends on [control=['for'], data=['special_event']] # depends on [control=['if'], data=[]] # check list of object property references obj_prop_refs = self.listOfObjectPropertyReferences if obj_prop_refs: for obj_prop_ref in obj_prop_refs: if obj_prop_ref.deviceIdentifier: raise RuntimeError('no external references') # depends on [control=['if'], data=[]] # get the datatype of the property to be written obj_type = obj_prop_ref.objectIdentifier[0] datatype = get_datatype(obj_type, obj_prop_ref.propertyIdentifier) if _debug: LocalScheduleObject._debug(' - datatype: %r', datatype) # depends on [control=['if'], data=[]] if issubclass(datatype, Array) and obj_prop_ref.propertyArrayIndex is not None: if obj_prop_ref.propertyArrayIndex == 0: datatype = Unsigned # depends on [control=['if'], data=[]] else: datatype = datatype.subtype if _debug: LocalScheduleObject._debug(' - datatype: %r', datatype) # depends on [control=['if'], data=[]] # depends on [control=['if'], data=[]] if datatype is not schedule_datatype: if _debug: LocalScheduleObject._debug(' - wrong type: expected %r, got %r', datatype, schedule_datatype) # depends on [control=['if'], data=[]] raise TypeError('wrong type') # depends on [control=['if'], data=['datatype', 'schedule_datatype']] # depends on [control=['for'], data=['obj_prop_ref']] # depends on [control=['if'], data=[]] # all good self.reliability = 'noFaultDetected' if _debug: LocalScheduleObject._debug(' - no fault detected') # depends on [control=['if'], data=[]] # depends on [control=['try'], data=[]] except Exception as err: if _debug: LocalScheduleObject._debug(' - exception: %r', err) # depends on [control=['if'], data=[]] self.reliability = 'configurationError' # depends on [control=['except'], data=['err']]
def power(attrs, inputs, proto_obj): """Returns element-wise result of base element raised to powers from exp element.""" new_attrs = translation_utils._fix_attribute_names(attrs, {'exponent':'exp'}) if 'broadcast' in attrs: new_attrs = translation_utils._remove_attributes(new_attrs, ['broadcast']) if attrs['broadcast'] == 1: return 'broadcast_power', new_attrs, inputs else: mxnet_op = symbol.pow(inputs[0], inputs[1]) return mxnet_op, new_attrs, inputs mxnet_op = symbol.broadcast_power(inputs[0], inputs[1]) return mxnet_op, new_attrs, inputs
def function[power, parameter[attrs, inputs, proto_obj]]: constant[Returns element-wise result of base element raised to powers from exp element.] variable[new_attrs] assign[=] call[name[translation_utils]._fix_attribute_names, parameter[name[attrs], dictionary[[<ast.Constant object at 0x7da1b204fca0>], [<ast.Constant object at 0x7da1b204dc30>]]]] if compare[constant[broadcast] in name[attrs]] begin[:] variable[new_attrs] assign[=] call[name[translation_utils]._remove_attributes, parameter[name[new_attrs], list[[<ast.Constant object at 0x7da1b204ea70>]]]] if compare[call[name[attrs]][constant[broadcast]] equal[==] constant[1]] begin[:] return[tuple[[<ast.Constant object at 0x7da1b204f550>, <ast.Name object at 0x7da1b204e380>, <ast.Name object at 0x7da1b204c4c0>]]] variable[mxnet_op] assign[=] call[name[symbol].broadcast_power, parameter[call[name[inputs]][constant[0]], call[name[inputs]][constant[1]]]] return[tuple[[<ast.Name object at 0x7da1b204cac0>, <ast.Name object at 0x7da1b204ed10>, <ast.Name object at 0x7da1b204fac0>]]]
keyword[def] identifier[power] ( identifier[attrs] , identifier[inputs] , identifier[proto_obj] ): literal[string] identifier[new_attrs] = identifier[translation_utils] . identifier[_fix_attribute_names] ( identifier[attrs] ,{ literal[string] : literal[string] }) keyword[if] literal[string] keyword[in] identifier[attrs] : identifier[new_attrs] = identifier[translation_utils] . identifier[_remove_attributes] ( identifier[new_attrs] ,[ literal[string] ]) keyword[if] identifier[attrs] [ literal[string] ]== literal[int] : keyword[return] literal[string] , identifier[new_attrs] , identifier[inputs] keyword[else] : identifier[mxnet_op] = identifier[symbol] . identifier[pow] ( identifier[inputs] [ literal[int] ], identifier[inputs] [ literal[int] ]) keyword[return] identifier[mxnet_op] , identifier[new_attrs] , identifier[inputs] identifier[mxnet_op] = identifier[symbol] . identifier[broadcast_power] ( identifier[inputs] [ literal[int] ], identifier[inputs] [ literal[int] ]) keyword[return] identifier[mxnet_op] , identifier[new_attrs] , identifier[inputs]
def power(attrs, inputs, proto_obj): """Returns element-wise result of base element raised to powers from exp element.""" new_attrs = translation_utils._fix_attribute_names(attrs, {'exponent': 'exp'}) if 'broadcast' in attrs: new_attrs = translation_utils._remove_attributes(new_attrs, ['broadcast']) if attrs['broadcast'] == 1: return ('broadcast_power', new_attrs, inputs) # depends on [control=['if'], data=[]] else: mxnet_op = symbol.pow(inputs[0], inputs[1]) return (mxnet_op, new_attrs, inputs) # depends on [control=['if'], data=['attrs']] mxnet_op = symbol.broadcast_power(inputs[0], inputs[1]) return (mxnet_op, new_attrs, inputs)
def process_account(self, message): """ This is used for processing of account Updates. It will return instances of :class:bitshares.account.AccountUpdate` """ self.on_account(AccountUpdate(message, blockchain_instance=self.blockchain))
def function[process_account, parameter[self, message]]: constant[ This is used for processing of account Updates. It will return instances of :class:bitshares.account.AccountUpdate` ] call[name[self].on_account, parameter[call[name[AccountUpdate], parameter[name[message]]]]]
keyword[def] identifier[process_account] ( identifier[self] , identifier[message] ): literal[string] identifier[self] . identifier[on_account] ( identifier[AccountUpdate] ( identifier[message] , identifier[blockchain_instance] = identifier[self] . identifier[blockchain] ))
def process_account(self, message): """ This is used for processing of account Updates. It will return instances of :class:bitshares.account.AccountUpdate` """ self.on_account(AccountUpdate(message, blockchain_instance=self.blockchain))
def get_sticker_set(self, name): """ Use this method to get a sticker set. On success, a StickerSet object is returned. :param name: :return: """ result = apihelper.get_sticker_set(self.token, name) return types.StickerSet.de_json(result)
def function[get_sticker_set, parameter[self, name]]: constant[ Use this method to get a sticker set. On success, a StickerSet object is returned. :param name: :return: ] variable[result] assign[=] call[name[apihelper].get_sticker_set, parameter[name[self].token, name[name]]] return[call[name[types].StickerSet.de_json, parameter[name[result]]]]
keyword[def] identifier[get_sticker_set] ( identifier[self] , identifier[name] ): literal[string] identifier[result] = identifier[apihelper] . identifier[get_sticker_set] ( identifier[self] . identifier[token] , identifier[name] ) keyword[return] identifier[types] . identifier[StickerSet] . identifier[de_json] ( identifier[result] )
def get_sticker_set(self, name): """ Use this method to get a sticker set. On success, a StickerSet object is returned. :param name: :return: """ result = apihelper.get_sticker_set(self.token, name) return types.StickerSet.de_json(result)
def get_all_neighbors(self, r, include_index=False, include_image=False): """ Get neighbors for each atom in the unit cell, out to a distance r Returns a list of list of neighbors for each site in structure. Use this method if you are planning on looping over all sites in the crystal. If you only want neighbors for a particular site, use the method get_neighbors as it may not have to build such a large supercell However if you are looping over all sites in the crystal, this method is more efficient since it only performs one pass over a large enough supercell to contain all possible atoms out to a distance r. The return type is a [(site, dist) ...] since most of the time, subsequent processing requires the distance. A note about periodic images: Before computing the neighbors, this operation translates all atoms to within the unit cell (having fractional coordinates within [0,1)). This means that the "image" of a site does not correspond to how much it has been translates from its current position, but which image of the unit cell it resides. Args: r (float): Radius of sphere. include_index (bool): Whether to include the non-supercell site in the returned data include_image (bool): Whether to include the supercell image in the returned data Returns: A list of a list of nearest neighbors for each site, i.e., [[(site, dist, index) ...], ..] Index only supplied if include_index = True. The index is the index of the site in the original (non-supercell) structure. This is needed for ewaldmatrix by keeping track of which sites contribute to the ewald sum. Image only supplied if include_image = True """ # Use same algorithm as get_sites_in_sphere to determine supercell but # loop over all atoms in crystal recp_len = np.array(self.lattice.reciprocal_lattice.abc) maxr = np.ceil((r + 0.15) * recp_len / (2 * math.pi)) nmin = np.floor(np.min(self.frac_coords, axis=0)) - maxr nmax = np.ceil(np.max(self.frac_coords, axis=0)) + maxr all_ranges = [np.arange(x, y) for x, y in zip(nmin, nmax)] latt = self._lattice neighbors = [list() for _ in range(len(self._sites))] all_fcoords = np.mod(self.frac_coords, 1) coords_in_cell = latt.get_cartesian_coords(all_fcoords) site_coords = self.cart_coords indices = np.arange(len(self)) for image in itertools.product(*all_ranges): coords = latt.get_cartesian_coords(image) + coords_in_cell all_dists = all_distances(coords, site_coords) all_within_r = np.bitwise_and(all_dists <= r, all_dists > 1e-8) for (j, d, within_r) in zip(indices, all_dists, all_within_r): nnsite = PeriodicSite(self[j].species, coords[j], latt, properties=self[j].properties, coords_are_cartesian=True) for i in indices[within_r]: item = (nnsite, d[i], j) if include_index else ( nnsite, d[i]) # Add the image, if requested if include_image: item += (image,) neighbors[i].append(item) return neighbors
def function[get_all_neighbors, parameter[self, r, include_index, include_image]]: constant[ Get neighbors for each atom in the unit cell, out to a distance r Returns a list of list of neighbors for each site in structure. Use this method if you are planning on looping over all sites in the crystal. If you only want neighbors for a particular site, use the method get_neighbors as it may not have to build such a large supercell However if you are looping over all sites in the crystal, this method is more efficient since it only performs one pass over a large enough supercell to contain all possible atoms out to a distance r. The return type is a [(site, dist) ...] since most of the time, subsequent processing requires the distance. A note about periodic images: Before computing the neighbors, this operation translates all atoms to within the unit cell (having fractional coordinates within [0,1)). This means that the "image" of a site does not correspond to how much it has been translates from its current position, but which image of the unit cell it resides. Args: r (float): Radius of sphere. include_index (bool): Whether to include the non-supercell site in the returned data include_image (bool): Whether to include the supercell image in the returned data Returns: A list of a list of nearest neighbors for each site, i.e., [[(site, dist, index) ...], ..] Index only supplied if include_index = True. The index is the index of the site in the original (non-supercell) structure. This is needed for ewaldmatrix by keeping track of which sites contribute to the ewald sum. Image only supplied if include_image = True ] variable[recp_len] assign[=] call[name[np].array, parameter[name[self].lattice.reciprocal_lattice.abc]] variable[maxr] assign[=] call[name[np].ceil, parameter[binary_operation[binary_operation[binary_operation[name[r] + constant[0.15]] * name[recp_len]] / binary_operation[constant[2] * name[math].pi]]]] variable[nmin] assign[=] binary_operation[call[name[np].floor, parameter[call[name[np].min, parameter[name[self].frac_coords]]]] - name[maxr]] variable[nmax] assign[=] binary_operation[call[name[np].ceil, parameter[call[name[np].max, parameter[name[self].frac_coords]]]] + name[maxr]] variable[all_ranges] assign[=] <ast.ListComp object at 0x7da18bc72830> variable[latt] assign[=] name[self]._lattice variable[neighbors] assign[=] <ast.ListComp object at 0x7da18bc70460> variable[all_fcoords] assign[=] call[name[np].mod, parameter[name[self].frac_coords, constant[1]]] variable[coords_in_cell] assign[=] call[name[latt].get_cartesian_coords, parameter[name[all_fcoords]]] variable[site_coords] assign[=] name[self].cart_coords variable[indices] assign[=] call[name[np].arange, parameter[call[name[len], parameter[name[self]]]]] for taget[name[image]] in starred[call[name[itertools].product, parameter[<ast.Starred object at 0x7da20c6c6b90>]]] begin[:] variable[coords] assign[=] binary_operation[call[name[latt].get_cartesian_coords, parameter[name[image]]] + name[coords_in_cell]] variable[all_dists] assign[=] call[name[all_distances], parameter[name[coords], name[site_coords]]] variable[all_within_r] assign[=] call[name[np].bitwise_and, parameter[compare[name[all_dists] less_or_equal[<=] name[r]], compare[name[all_dists] greater[>] constant[1e-08]]]] for taget[tuple[[<ast.Name object at 0x7da20c6c4580>, <ast.Name object at 0x7da20c6c7400>, <ast.Name object at 0x7da20c6c5690>]]] in starred[call[name[zip], parameter[name[indices], name[all_dists], name[all_within_r]]]] begin[:] variable[nnsite] assign[=] call[name[PeriodicSite], parameter[call[name[self]][name[j]].species, call[name[coords]][name[j]], name[latt]]] for taget[name[i]] in starred[call[name[indices]][name[within_r]]] begin[:] variable[item] assign[=] <ast.IfExp object at 0x7da20c6c5540> if name[include_image] begin[:] <ast.AugAssign object at 0x7da20c6c7a30> call[call[name[neighbors]][name[i]].append, parameter[name[item]]] return[name[neighbors]]
keyword[def] identifier[get_all_neighbors] ( identifier[self] , identifier[r] , identifier[include_index] = keyword[False] , identifier[include_image] = keyword[False] ): literal[string] identifier[recp_len] = identifier[np] . identifier[array] ( identifier[self] . identifier[lattice] . identifier[reciprocal_lattice] . identifier[abc] ) identifier[maxr] = identifier[np] . identifier[ceil] (( identifier[r] + literal[int] )* identifier[recp_len] /( literal[int] * identifier[math] . identifier[pi] )) identifier[nmin] = identifier[np] . identifier[floor] ( identifier[np] . identifier[min] ( identifier[self] . identifier[frac_coords] , identifier[axis] = literal[int] ))- identifier[maxr] identifier[nmax] = identifier[np] . identifier[ceil] ( identifier[np] . identifier[max] ( identifier[self] . identifier[frac_coords] , identifier[axis] = literal[int] ))+ identifier[maxr] identifier[all_ranges] =[ identifier[np] . identifier[arange] ( identifier[x] , identifier[y] ) keyword[for] identifier[x] , identifier[y] keyword[in] identifier[zip] ( identifier[nmin] , identifier[nmax] )] identifier[latt] = identifier[self] . identifier[_lattice] identifier[neighbors] =[ identifier[list] () keyword[for] identifier[_] keyword[in] identifier[range] ( identifier[len] ( identifier[self] . identifier[_sites] ))] identifier[all_fcoords] = identifier[np] . identifier[mod] ( identifier[self] . identifier[frac_coords] , literal[int] ) identifier[coords_in_cell] = identifier[latt] . identifier[get_cartesian_coords] ( identifier[all_fcoords] ) identifier[site_coords] = identifier[self] . identifier[cart_coords] identifier[indices] = identifier[np] . identifier[arange] ( identifier[len] ( identifier[self] )) keyword[for] identifier[image] keyword[in] identifier[itertools] . identifier[product] (* identifier[all_ranges] ): identifier[coords] = identifier[latt] . identifier[get_cartesian_coords] ( identifier[image] )+ identifier[coords_in_cell] identifier[all_dists] = identifier[all_distances] ( identifier[coords] , identifier[site_coords] ) identifier[all_within_r] = identifier[np] . identifier[bitwise_and] ( identifier[all_dists] <= identifier[r] , identifier[all_dists] > literal[int] ) keyword[for] ( identifier[j] , identifier[d] , identifier[within_r] ) keyword[in] identifier[zip] ( identifier[indices] , identifier[all_dists] , identifier[all_within_r] ): identifier[nnsite] = identifier[PeriodicSite] ( identifier[self] [ identifier[j] ]. identifier[species] , identifier[coords] [ identifier[j] ], identifier[latt] , identifier[properties] = identifier[self] [ identifier[j] ]. identifier[properties] , identifier[coords_are_cartesian] = keyword[True] ) keyword[for] identifier[i] keyword[in] identifier[indices] [ identifier[within_r] ]: identifier[item] =( identifier[nnsite] , identifier[d] [ identifier[i] ], identifier[j] ) keyword[if] identifier[include_index] keyword[else] ( identifier[nnsite] , identifier[d] [ identifier[i] ]) keyword[if] identifier[include_image] : identifier[item] +=( identifier[image] ,) identifier[neighbors] [ identifier[i] ]. identifier[append] ( identifier[item] ) keyword[return] identifier[neighbors]
def get_all_neighbors(self, r, include_index=False, include_image=False): """ Get neighbors for each atom in the unit cell, out to a distance r Returns a list of list of neighbors for each site in structure. Use this method if you are planning on looping over all sites in the crystal. If you only want neighbors for a particular site, use the method get_neighbors as it may not have to build such a large supercell However if you are looping over all sites in the crystal, this method is more efficient since it only performs one pass over a large enough supercell to contain all possible atoms out to a distance r. The return type is a [(site, dist) ...] since most of the time, subsequent processing requires the distance. A note about periodic images: Before computing the neighbors, this operation translates all atoms to within the unit cell (having fractional coordinates within [0,1)). This means that the "image" of a site does not correspond to how much it has been translates from its current position, but which image of the unit cell it resides. Args: r (float): Radius of sphere. include_index (bool): Whether to include the non-supercell site in the returned data include_image (bool): Whether to include the supercell image in the returned data Returns: A list of a list of nearest neighbors for each site, i.e., [[(site, dist, index) ...], ..] Index only supplied if include_index = True. The index is the index of the site in the original (non-supercell) structure. This is needed for ewaldmatrix by keeping track of which sites contribute to the ewald sum. Image only supplied if include_image = True """ # Use same algorithm as get_sites_in_sphere to determine supercell but # loop over all atoms in crystal recp_len = np.array(self.lattice.reciprocal_lattice.abc) maxr = np.ceil((r + 0.15) * recp_len / (2 * math.pi)) nmin = np.floor(np.min(self.frac_coords, axis=0)) - maxr nmax = np.ceil(np.max(self.frac_coords, axis=0)) + maxr all_ranges = [np.arange(x, y) for (x, y) in zip(nmin, nmax)] latt = self._lattice neighbors = [list() for _ in range(len(self._sites))] all_fcoords = np.mod(self.frac_coords, 1) coords_in_cell = latt.get_cartesian_coords(all_fcoords) site_coords = self.cart_coords indices = np.arange(len(self)) for image in itertools.product(*all_ranges): coords = latt.get_cartesian_coords(image) + coords_in_cell all_dists = all_distances(coords, site_coords) all_within_r = np.bitwise_and(all_dists <= r, all_dists > 1e-08) for (j, d, within_r) in zip(indices, all_dists, all_within_r): nnsite = PeriodicSite(self[j].species, coords[j], latt, properties=self[j].properties, coords_are_cartesian=True) for i in indices[within_r]: item = (nnsite, d[i], j) if include_index else (nnsite, d[i]) # Add the image, if requested if include_image: item += (image,) # depends on [control=['if'], data=[]] neighbors[i].append(item) # depends on [control=['for'], data=['i']] # depends on [control=['for'], data=[]] # depends on [control=['for'], data=['image']] return neighbors
def stdrepr_short(self, obj, *, cls=None, tag='span'): """ Standard short representation for objects, used for objects at a depth that exceeds ``hrepr_object.config.max_depth``. That representation is just the object's type between ``<>``s, e.g. ``<MyClass>``. This behavior can be overriden with a ``__hrepr_short__`` method on the object, or an entry in ``hrepr_object.type_handlers_short``. Args: obj: The object to represent. cls (optional): The class name for the representation. If None, stdrepr will use ``'hrepr-' + obj.__class__.___name__`` tag (optional): The tag for the representation, defaults to 'span'. """ cls_name = obj.__class__.__name__ if cls is None: cls = f'hrepr-short-{cls_name}' return getattr(self.H, tag)[cls](f'<{cls_name}>')
def function[stdrepr_short, parameter[self, obj]]: constant[ Standard short representation for objects, used for objects at a depth that exceeds ``hrepr_object.config.max_depth``. That representation is just the object's type between ``<>``s, e.g. ``<MyClass>``. This behavior can be overriden with a ``__hrepr_short__`` method on the object, or an entry in ``hrepr_object.type_handlers_short``. Args: obj: The object to represent. cls (optional): The class name for the representation. If None, stdrepr will use ``'hrepr-' + obj.__class__.___name__`` tag (optional): The tag for the representation, defaults to 'span'. ] variable[cls_name] assign[=] name[obj].__class__.__name__ if compare[name[cls] is constant[None]] begin[:] variable[cls] assign[=] <ast.JoinedStr object at 0x7da20c76c5b0> return[call[call[call[name[getattr], parameter[name[self].H, name[tag]]]][name[cls]], parameter[<ast.JoinedStr object at 0x7da20c76d600>]]]
keyword[def] identifier[stdrepr_short] ( identifier[self] , identifier[obj] ,*, identifier[cls] = keyword[None] , identifier[tag] = literal[string] ): literal[string] identifier[cls_name] = identifier[obj] . identifier[__class__] . identifier[__name__] keyword[if] identifier[cls] keyword[is] keyword[None] : identifier[cls] = literal[string] keyword[return] identifier[getattr] ( identifier[self] . identifier[H] , identifier[tag] )[ identifier[cls] ]( literal[string] )
def stdrepr_short(self, obj, *, cls=None, tag='span'): """ Standard short representation for objects, used for objects at a depth that exceeds ``hrepr_object.config.max_depth``. That representation is just the object's type between ``<>``s, e.g. ``<MyClass>``. This behavior can be overriden with a ``__hrepr_short__`` method on the object, or an entry in ``hrepr_object.type_handlers_short``. Args: obj: The object to represent. cls (optional): The class name for the representation. If None, stdrepr will use ``'hrepr-' + obj.__class__.___name__`` tag (optional): The tag for the representation, defaults to 'span'. """ cls_name = obj.__class__.__name__ if cls is None: cls = f'hrepr-short-{cls_name}' # depends on [control=['if'], data=['cls']] return getattr(self.H, tag)[cls](f'<{cls_name}>')
def announcement_posted_hook(request, obj): """Runs whenever a new announcement is created, or a request is approved and posted. obj: The Announcement object """ logger.debug("Announcement posted") if obj.notify_post: logger.debug("Announcement notify on") announcement_posted_twitter(request, obj) try: notify_all = obj.notify_email_all except AttributeError: notify_all = False try: if notify_all: announcement_posted_email(request, obj, True) else: announcement_posted_email(request, obj) except Exception as e: logger.error("Exception when emailing announcement: {}".format(e)) messages.error(request, "Exception when emailing announcement: {}".format(e)) raise e else: logger.debug("Announcement notify off")
def function[announcement_posted_hook, parameter[request, obj]]: constant[Runs whenever a new announcement is created, or a request is approved and posted. obj: The Announcement object ] call[name[logger].debug, parameter[constant[Announcement posted]]] if name[obj].notify_post begin[:] call[name[logger].debug, parameter[constant[Announcement notify on]]] call[name[announcement_posted_twitter], parameter[name[request], name[obj]]] <ast.Try object at 0x7da1b04be3e0> <ast.Try object at 0x7da1b04bf4f0>
keyword[def] identifier[announcement_posted_hook] ( identifier[request] , identifier[obj] ): literal[string] identifier[logger] . identifier[debug] ( literal[string] ) keyword[if] identifier[obj] . identifier[notify_post] : identifier[logger] . identifier[debug] ( literal[string] ) identifier[announcement_posted_twitter] ( identifier[request] , identifier[obj] ) keyword[try] : identifier[notify_all] = identifier[obj] . identifier[notify_email_all] keyword[except] identifier[AttributeError] : identifier[notify_all] = keyword[False] keyword[try] : keyword[if] identifier[notify_all] : identifier[announcement_posted_email] ( identifier[request] , identifier[obj] , keyword[True] ) keyword[else] : identifier[announcement_posted_email] ( identifier[request] , identifier[obj] ) keyword[except] identifier[Exception] keyword[as] identifier[e] : identifier[logger] . identifier[error] ( literal[string] . identifier[format] ( identifier[e] )) identifier[messages] . identifier[error] ( identifier[request] , literal[string] . identifier[format] ( identifier[e] )) keyword[raise] identifier[e] keyword[else] : identifier[logger] . identifier[debug] ( literal[string] )
def announcement_posted_hook(request, obj): """Runs whenever a new announcement is created, or a request is approved and posted. obj: The Announcement object """ logger.debug('Announcement posted') if obj.notify_post: logger.debug('Announcement notify on') announcement_posted_twitter(request, obj) try: notify_all = obj.notify_email_all # depends on [control=['try'], data=[]] except AttributeError: notify_all = False # depends on [control=['except'], data=[]] try: if notify_all: announcement_posted_email(request, obj, True) # depends on [control=['if'], data=[]] else: announcement_posted_email(request, obj) # depends on [control=['try'], data=[]] except Exception as e: logger.error('Exception when emailing announcement: {}'.format(e)) messages.error(request, 'Exception when emailing announcement: {}'.format(e)) raise e # depends on [control=['except'], data=['e']] # depends on [control=['if'], data=[]] else: logger.debug('Announcement notify off')
def complete_token_filtered(aliases, prefix, expanded): """Find all starting matches in dictionary *aliases* that start with *prefix*, but filter out any matches already in *expanded*""" complete_ary = aliases.keys() return [cmd for cmd in complete_ary if cmd.startswith(prefix)]
def function[complete_token_filtered, parameter[aliases, prefix, expanded]]: constant[Find all starting matches in dictionary *aliases* that start with *prefix*, but filter out any matches already in *expanded*] variable[complete_ary] assign[=] call[name[aliases].keys, parameter[]] return[<ast.ListComp object at 0x7da1b03b80a0>]
keyword[def] identifier[complete_token_filtered] ( identifier[aliases] , identifier[prefix] , identifier[expanded] ): literal[string] identifier[complete_ary] = identifier[aliases] . identifier[keys] () keyword[return] [ identifier[cmd] keyword[for] identifier[cmd] keyword[in] identifier[complete_ary] keyword[if] identifier[cmd] . identifier[startswith] ( identifier[prefix] )]
def complete_token_filtered(aliases, prefix, expanded): """Find all starting matches in dictionary *aliases* that start with *prefix*, but filter out any matches already in *expanded*""" complete_ary = aliases.keys() return [cmd for cmd in complete_ary if cmd.startswith(prefix)]
def missing_labels(self): """ A 1D `~numpy.ndarray` of the sorted non-zero labels that are missing in the consecutive sequence from zero to the maximum label number. """ return np.array(sorted(set(range(0, self.max_label + 1)). difference(np.insert(self.labels, 0, 0))))
def function[missing_labels, parameter[self]]: constant[ A 1D `~numpy.ndarray` of the sorted non-zero labels that are missing in the consecutive sequence from zero to the maximum label number. ] return[call[name[np].array, parameter[call[name[sorted], parameter[call[call[name[set], parameter[call[name[range], parameter[constant[0], binary_operation[name[self].max_label + constant[1]]]]]].difference, parameter[call[name[np].insert, parameter[name[self].labels, constant[0], constant[0]]]]]]]]]]
keyword[def] identifier[missing_labels] ( identifier[self] ): literal[string] keyword[return] identifier[np] . identifier[array] ( identifier[sorted] ( identifier[set] ( identifier[range] ( literal[int] , identifier[self] . identifier[max_label] + literal[int] )). identifier[difference] ( identifier[np] . identifier[insert] ( identifier[self] . identifier[labels] , literal[int] , literal[int] ))))
def missing_labels(self): """ A 1D `~numpy.ndarray` of the sorted non-zero labels that are missing in the consecutive sequence from zero to the maximum label number. """ return np.array(sorted(set(range(0, self.max_label + 1)).difference(np.insert(self.labels, 0, 0))))
def superclasses_bug_fix(data): ''' PHP returns "id" in superclass but only accepts superclass_tid ''' for i, value in enumerate(data['superclasses']): data['superclasses'][i]['superclass_tid'] = data['superclasses'][i].pop('id') return data
def function[superclasses_bug_fix, parameter[data]]: constant[ PHP returns "id" in superclass but only accepts superclass_tid ] for taget[tuple[[<ast.Name object at 0x7da1b1be7f70>, <ast.Name object at 0x7da1b1be5870>]]] in starred[call[name[enumerate], parameter[call[name[data]][constant[superclasses]]]]] begin[:] call[call[call[name[data]][constant[superclasses]]][name[i]]][constant[superclass_tid]] assign[=] call[call[call[name[data]][constant[superclasses]]][name[i]].pop, parameter[constant[id]]] return[name[data]]
keyword[def] identifier[superclasses_bug_fix] ( identifier[data] ): literal[string] keyword[for] identifier[i] , identifier[value] keyword[in] identifier[enumerate] ( identifier[data] [ literal[string] ]): identifier[data] [ literal[string] ][ identifier[i] ][ literal[string] ]= identifier[data] [ literal[string] ][ identifier[i] ]. identifier[pop] ( literal[string] ) keyword[return] identifier[data]
def superclasses_bug_fix(data): """ PHP returns "id" in superclass but only accepts superclass_tid """ for (i, value) in enumerate(data['superclasses']): data['superclasses'][i]['superclass_tid'] = data['superclasses'][i].pop('id') # depends on [control=['for'], data=[]] return data
def _parse_remind(self, filename, lines=''): """Calls remind and parses the output into a dict filename -- the remind file (included files will be used as well) lines -- used as stdin to remind (filename will be set to -) """ files = {} reminders = {} if lines: filename = '-' files[filename] = lines reminders[filename] = {} cmd = ['remind', '-l', '-s%d' % self._month, '-b1', '-y', '-r', filename, str(self._startdate)] try: rem = Popen(cmd, stdin=PIPE, stdout=PIPE).communicate(input=lines.encode('utf-8'))[0].decode('utf-8') except OSError: raise OSError('Error running: %s' % ' '.join(cmd)) rem = rem.splitlines() for (fileinfo, line) in zip(rem[::2], rem[1::2]): fileinfo = fileinfo.split() src_filename = fileinfo[3] if src_filename not in files: # There is a race condition with the remind call above here. # This could be solved by parsing the remind -de output, # but I don't see an easy way to do that. files[src_filename] = open(src_filename).readlines() reminders[src_filename] = {} mtime = getmtime(src_filename) if mtime > self._mtime: self._mtime = mtime text = files[src_filename][int(fileinfo[2]) - 1] event = self._parse_remind_line(line, text) if event['uid'] in reminders[src_filename]: reminders[src_filename][event['uid']]['dtstart'] += event['dtstart'] reminders[src_filename][event['uid']]['line'] += line else: reminders[src_filename][event['uid']] = event reminders[src_filename][event['uid']]['line'] = line # Find included files without reminders and add them to the file list for source in files.values(): for line in source: if line.startswith('include'): new_file = line.split(' ')[1].strip() if new_file not in reminders: reminders[new_file] = {} mtime = getmtime(new_file) if mtime > self._mtime: self._mtime = mtime return reminders
def function[_parse_remind, parameter[self, filename, lines]]: constant[Calls remind and parses the output into a dict filename -- the remind file (included files will be used as well) lines -- used as stdin to remind (filename will be set to -) ] variable[files] assign[=] dictionary[[], []] variable[reminders] assign[=] dictionary[[], []] if name[lines] begin[:] variable[filename] assign[=] constant[-] call[name[files]][name[filename]] assign[=] name[lines] call[name[reminders]][name[filename]] assign[=] dictionary[[], []] variable[cmd] assign[=] list[[<ast.Constant object at 0x7da1b2407130>, <ast.Constant object at 0x7da1b24047c0>, <ast.BinOp object at 0x7da1b2406620>, <ast.Constant object at 0x7da1b2407100>, <ast.Constant object at 0x7da1b24079d0>, <ast.Constant object at 0x7da1b2405b70>, <ast.Name object at 0x7da1b2404970>, <ast.Call object at 0x7da1b2405090>]] <ast.Try object at 0x7da1b2407f10> variable[rem] assign[=] call[name[rem].splitlines, parameter[]] for taget[tuple[[<ast.Name object at 0x7da1b2405390>, <ast.Name object at 0x7da1b2407400>]]] in starred[call[name[zip], parameter[call[name[rem]][<ast.Slice object at 0x7da1b2407d60>], call[name[rem]][<ast.Slice object at 0x7da1b24045b0>]]]] begin[:] variable[fileinfo] assign[=] call[name[fileinfo].split, parameter[]] variable[src_filename] assign[=] call[name[fileinfo]][constant[3]] if compare[name[src_filename] <ast.NotIn object at 0x7da2590d7190> name[files]] begin[:] call[name[files]][name[src_filename]] assign[=] call[call[name[open], parameter[name[src_filename]]].readlines, parameter[]] call[name[reminders]][name[src_filename]] assign[=] dictionary[[], []] variable[mtime] assign[=] call[name[getmtime], parameter[name[src_filename]]] if compare[name[mtime] greater[>] name[self]._mtime] begin[:] name[self]._mtime assign[=] name[mtime] variable[text] assign[=] call[call[name[files]][name[src_filename]]][binary_operation[call[name[int], parameter[call[name[fileinfo]][constant[2]]]] - constant[1]]] variable[event] assign[=] call[name[self]._parse_remind_line, parameter[name[line], name[text]]] if compare[call[name[event]][constant[uid]] in call[name[reminders]][name[src_filename]]] begin[:] <ast.AugAssign object at 0x7da1b246fc40> <ast.AugAssign object at 0x7da1b246faf0> for taget[name[source]] in starred[call[name[files].values, parameter[]]] begin[:] for taget[name[line]] in starred[name[source]] begin[:] if call[name[line].startswith, parameter[constant[include]]] begin[:] variable[new_file] assign[=] call[call[call[name[line].split, parameter[constant[ ]]]][constant[1]].strip, parameter[]] if compare[name[new_file] <ast.NotIn object at 0x7da2590d7190> name[reminders]] begin[:] call[name[reminders]][name[new_file]] assign[=] dictionary[[], []] variable[mtime] assign[=] call[name[getmtime], parameter[name[new_file]]] if compare[name[mtime] greater[>] name[self]._mtime] begin[:] name[self]._mtime assign[=] name[mtime] return[name[reminders]]
keyword[def] identifier[_parse_remind] ( identifier[self] , identifier[filename] , identifier[lines] = literal[string] ): literal[string] identifier[files] ={} identifier[reminders] ={} keyword[if] identifier[lines] : identifier[filename] = literal[string] identifier[files] [ identifier[filename] ]= identifier[lines] identifier[reminders] [ identifier[filename] ]={} identifier[cmd] =[ literal[string] , literal[string] , literal[string] % identifier[self] . identifier[_month] , literal[string] , literal[string] , literal[string] , identifier[filename] , identifier[str] ( identifier[self] . identifier[_startdate] )] keyword[try] : identifier[rem] = identifier[Popen] ( identifier[cmd] , identifier[stdin] = identifier[PIPE] , identifier[stdout] = identifier[PIPE] ). identifier[communicate] ( identifier[input] = identifier[lines] . identifier[encode] ( literal[string] ))[ literal[int] ]. identifier[decode] ( literal[string] ) keyword[except] identifier[OSError] : keyword[raise] identifier[OSError] ( literal[string] % literal[string] . identifier[join] ( identifier[cmd] )) identifier[rem] = identifier[rem] . identifier[splitlines] () keyword[for] ( identifier[fileinfo] , identifier[line] ) keyword[in] identifier[zip] ( identifier[rem] [:: literal[int] ], identifier[rem] [ literal[int] :: literal[int] ]): identifier[fileinfo] = identifier[fileinfo] . identifier[split] () identifier[src_filename] = identifier[fileinfo] [ literal[int] ] keyword[if] identifier[src_filename] keyword[not] keyword[in] identifier[files] : identifier[files] [ identifier[src_filename] ]= identifier[open] ( identifier[src_filename] ). identifier[readlines] () identifier[reminders] [ identifier[src_filename] ]={} identifier[mtime] = identifier[getmtime] ( identifier[src_filename] ) keyword[if] identifier[mtime] > identifier[self] . identifier[_mtime] : identifier[self] . identifier[_mtime] = identifier[mtime] identifier[text] = identifier[files] [ identifier[src_filename] ][ identifier[int] ( identifier[fileinfo] [ literal[int] ])- literal[int] ] identifier[event] = identifier[self] . identifier[_parse_remind_line] ( identifier[line] , identifier[text] ) keyword[if] identifier[event] [ literal[string] ] keyword[in] identifier[reminders] [ identifier[src_filename] ]: identifier[reminders] [ identifier[src_filename] ][ identifier[event] [ literal[string] ]][ literal[string] ]+= identifier[event] [ literal[string] ] identifier[reminders] [ identifier[src_filename] ][ identifier[event] [ literal[string] ]][ literal[string] ]+= identifier[line] keyword[else] : identifier[reminders] [ identifier[src_filename] ][ identifier[event] [ literal[string] ]]= identifier[event] identifier[reminders] [ identifier[src_filename] ][ identifier[event] [ literal[string] ]][ literal[string] ]= identifier[line] keyword[for] identifier[source] keyword[in] identifier[files] . identifier[values] (): keyword[for] identifier[line] keyword[in] identifier[source] : keyword[if] identifier[line] . identifier[startswith] ( literal[string] ): identifier[new_file] = identifier[line] . identifier[split] ( literal[string] )[ literal[int] ]. identifier[strip] () keyword[if] identifier[new_file] keyword[not] keyword[in] identifier[reminders] : identifier[reminders] [ identifier[new_file] ]={} identifier[mtime] = identifier[getmtime] ( identifier[new_file] ) keyword[if] identifier[mtime] > identifier[self] . identifier[_mtime] : identifier[self] . identifier[_mtime] = identifier[mtime] keyword[return] identifier[reminders]
def _parse_remind(self, filename, lines=''): """Calls remind and parses the output into a dict filename -- the remind file (included files will be used as well) lines -- used as stdin to remind (filename will be set to -) """ files = {} reminders = {} if lines: filename = '-' files[filename] = lines reminders[filename] = {} # depends on [control=['if'], data=[]] cmd = ['remind', '-l', '-s%d' % self._month, '-b1', '-y', '-r', filename, str(self._startdate)] try: rem = Popen(cmd, stdin=PIPE, stdout=PIPE).communicate(input=lines.encode('utf-8'))[0].decode('utf-8') # depends on [control=['try'], data=[]] except OSError: raise OSError('Error running: %s' % ' '.join(cmd)) # depends on [control=['except'], data=[]] rem = rem.splitlines() for (fileinfo, line) in zip(rem[::2], rem[1::2]): fileinfo = fileinfo.split() src_filename = fileinfo[3] if src_filename not in files: # There is a race condition with the remind call above here. # This could be solved by parsing the remind -de output, # but I don't see an easy way to do that. files[src_filename] = open(src_filename).readlines() reminders[src_filename] = {} mtime = getmtime(src_filename) if mtime > self._mtime: self._mtime = mtime # depends on [control=['if'], data=['mtime']] # depends on [control=['if'], data=['src_filename', 'files']] text = files[src_filename][int(fileinfo[2]) - 1] event = self._parse_remind_line(line, text) if event['uid'] in reminders[src_filename]: reminders[src_filename][event['uid']]['dtstart'] += event['dtstart'] reminders[src_filename][event['uid']]['line'] += line # depends on [control=['if'], data=[]] else: reminders[src_filename][event['uid']] = event reminders[src_filename][event['uid']]['line'] = line # depends on [control=['for'], data=[]] # Find included files without reminders and add them to the file list for source in files.values(): for line in source: if line.startswith('include'): new_file = line.split(' ')[1].strip() if new_file not in reminders: reminders[new_file] = {} mtime = getmtime(new_file) if mtime > self._mtime: self._mtime = mtime # depends on [control=['if'], data=['mtime']] # depends on [control=['if'], data=['new_file', 'reminders']] # depends on [control=['if'], data=[]] # depends on [control=['for'], data=['line']] # depends on [control=['for'], data=['source']] return reminders
def path_segment(self, index, value=None, default=None): """ Return the path segment at the given index :param integer index: :param string value: the new segment value :param string default: the default value to return if no path segment exists with the given index """ if value is not None: segments = list(self.path_segments()) segments[index] = unicode_quote_path_segment(value) new_path = '/' + '/'.join(segments) if self._tuple.path.endswith('/'): new_path += '/' return URL._mutate(self, path=new_path) try: return self.path_segments()[index] except IndexError: return default
def function[path_segment, parameter[self, index, value, default]]: constant[ Return the path segment at the given index :param integer index: :param string value: the new segment value :param string default: the default value to return if no path segment exists with the given index ] if compare[name[value] is_not constant[None]] begin[:] variable[segments] assign[=] call[name[list], parameter[call[name[self].path_segments, parameter[]]]] call[name[segments]][name[index]] assign[=] call[name[unicode_quote_path_segment], parameter[name[value]]] variable[new_path] assign[=] binary_operation[constant[/] + call[constant[/].join, parameter[name[segments]]]] if call[name[self]._tuple.path.endswith, parameter[constant[/]]] begin[:] <ast.AugAssign object at 0x7da1b0fcee60> return[call[name[URL]._mutate, parameter[name[self]]]] <ast.Try object at 0x7da1b0fcf5b0>
keyword[def] identifier[path_segment] ( identifier[self] , identifier[index] , identifier[value] = keyword[None] , identifier[default] = keyword[None] ): literal[string] keyword[if] identifier[value] keyword[is] keyword[not] keyword[None] : identifier[segments] = identifier[list] ( identifier[self] . identifier[path_segments] ()) identifier[segments] [ identifier[index] ]= identifier[unicode_quote_path_segment] ( identifier[value] ) identifier[new_path] = literal[string] + literal[string] . identifier[join] ( identifier[segments] ) keyword[if] identifier[self] . identifier[_tuple] . identifier[path] . identifier[endswith] ( literal[string] ): identifier[new_path] += literal[string] keyword[return] identifier[URL] . identifier[_mutate] ( identifier[self] , identifier[path] = identifier[new_path] ) keyword[try] : keyword[return] identifier[self] . identifier[path_segments] ()[ identifier[index] ] keyword[except] identifier[IndexError] : keyword[return] identifier[default]
def path_segment(self, index, value=None, default=None): """ Return the path segment at the given index :param integer index: :param string value: the new segment value :param string default: the default value to return if no path segment exists with the given index """ if value is not None: segments = list(self.path_segments()) segments[index] = unicode_quote_path_segment(value) new_path = '/' + '/'.join(segments) if self._tuple.path.endswith('/'): new_path += '/' # depends on [control=['if'], data=[]] return URL._mutate(self, path=new_path) # depends on [control=['if'], data=['value']] try: return self.path_segments()[index] # depends on [control=['try'], data=[]] except IndexError: return default # depends on [control=['except'], data=[]]
def add_data_to_attribute(scenario_id, resource_attr_id, dataset,**kwargs): """ Add data to a resource scenario outside of a network update """ user_id = kwargs.get('user_id') _check_can_edit_scenario(scenario_id, user_id) scenario_i = _get_scenario(scenario_id, user_id) try: r_scen_i = db.DBSession.query(ResourceScenario).filter( ResourceScenario.scenario_id==scenario_id, ResourceScenario.resource_attr_id==resource_attr_id).one() log.info("Existing resource scenario found for %s in scenario %s", resource_attr_id, scenario_id) except NoResultFound: log.info("No existing resource scenarios found for %s in scenario %s. Adding a new one.", resource_attr_id, scenario_id) r_scen_i = ResourceScenario() r_scen_i.scenario_id = scenario_id r_scen_i.resource_attr_id = resource_attr_id scenario_i.resourcescenarios.append(r_scen_i) data_type = dataset.type.lower() value = dataset.parse_value() dataset_metadata = dataset.get_metadata_as_dict(user_id=kwargs.get('user_id'), source=kwargs.get('source')) if value is None: raise HydraError("Cannot set value to attribute. " "No value was sent with dataset %s", dataset.id) data_hash = dataset.get_hash(value, dataset_metadata) assign_value(r_scen_i, data_type, value, dataset.unit_id, dataset.name, metadata=dataset_metadata, data_hash=data_hash, user_id=user_id) db.DBSession.flush() return r_scen_i
def function[add_data_to_attribute, parameter[scenario_id, resource_attr_id, dataset]]: constant[ Add data to a resource scenario outside of a network update ] variable[user_id] assign[=] call[name[kwargs].get, parameter[constant[user_id]]] call[name[_check_can_edit_scenario], parameter[name[scenario_id], name[user_id]]] variable[scenario_i] assign[=] call[name[_get_scenario], parameter[name[scenario_id], name[user_id]]] <ast.Try object at 0x7da20c991060> variable[data_type] assign[=] call[name[dataset].type.lower, parameter[]] variable[value] assign[=] call[name[dataset].parse_value, parameter[]] variable[dataset_metadata] assign[=] call[name[dataset].get_metadata_as_dict, parameter[]] if compare[name[value] is constant[None]] begin[:] <ast.Raise object at 0x7da20c9901f0> variable[data_hash] assign[=] call[name[dataset].get_hash, parameter[name[value], name[dataset_metadata]]] call[name[assign_value], parameter[name[r_scen_i], name[data_type], name[value], name[dataset].unit_id, name[dataset].name]] call[name[db].DBSession.flush, parameter[]] return[name[r_scen_i]]
keyword[def] identifier[add_data_to_attribute] ( identifier[scenario_id] , identifier[resource_attr_id] , identifier[dataset] ,** identifier[kwargs] ): literal[string] identifier[user_id] = identifier[kwargs] . identifier[get] ( literal[string] ) identifier[_check_can_edit_scenario] ( identifier[scenario_id] , identifier[user_id] ) identifier[scenario_i] = identifier[_get_scenario] ( identifier[scenario_id] , identifier[user_id] ) keyword[try] : identifier[r_scen_i] = identifier[db] . identifier[DBSession] . identifier[query] ( identifier[ResourceScenario] ). identifier[filter] ( identifier[ResourceScenario] . identifier[scenario_id] == identifier[scenario_id] , identifier[ResourceScenario] . identifier[resource_attr_id] == identifier[resource_attr_id] ). identifier[one] () identifier[log] . identifier[info] ( literal[string] , identifier[resource_attr_id] , identifier[scenario_id] ) keyword[except] identifier[NoResultFound] : identifier[log] . identifier[info] ( literal[string] , identifier[resource_attr_id] , identifier[scenario_id] ) identifier[r_scen_i] = identifier[ResourceScenario] () identifier[r_scen_i] . identifier[scenario_id] = identifier[scenario_id] identifier[r_scen_i] . identifier[resource_attr_id] = identifier[resource_attr_id] identifier[scenario_i] . identifier[resourcescenarios] . identifier[append] ( identifier[r_scen_i] ) identifier[data_type] = identifier[dataset] . identifier[type] . identifier[lower] () identifier[value] = identifier[dataset] . identifier[parse_value] () identifier[dataset_metadata] = identifier[dataset] . identifier[get_metadata_as_dict] ( identifier[user_id] = identifier[kwargs] . identifier[get] ( literal[string] ), identifier[source] = identifier[kwargs] . identifier[get] ( literal[string] )) keyword[if] identifier[value] keyword[is] keyword[None] : keyword[raise] identifier[HydraError] ( literal[string] literal[string] , identifier[dataset] . identifier[id] ) identifier[data_hash] = identifier[dataset] . identifier[get_hash] ( identifier[value] , identifier[dataset_metadata] ) identifier[assign_value] ( identifier[r_scen_i] , identifier[data_type] , identifier[value] , identifier[dataset] . identifier[unit_id] , identifier[dataset] . identifier[name] , identifier[metadata] = identifier[dataset_metadata] , identifier[data_hash] = identifier[data_hash] , identifier[user_id] = identifier[user_id] ) identifier[db] . identifier[DBSession] . identifier[flush] () keyword[return] identifier[r_scen_i]
def add_data_to_attribute(scenario_id, resource_attr_id, dataset, **kwargs): """ Add data to a resource scenario outside of a network update """ user_id = kwargs.get('user_id') _check_can_edit_scenario(scenario_id, user_id) scenario_i = _get_scenario(scenario_id, user_id) try: r_scen_i = db.DBSession.query(ResourceScenario).filter(ResourceScenario.scenario_id == scenario_id, ResourceScenario.resource_attr_id == resource_attr_id).one() log.info('Existing resource scenario found for %s in scenario %s', resource_attr_id, scenario_id) # depends on [control=['try'], data=[]] except NoResultFound: log.info('No existing resource scenarios found for %s in scenario %s. Adding a new one.', resource_attr_id, scenario_id) r_scen_i = ResourceScenario() r_scen_i.scenario_id = scenario_id r_scen_i.resource_attr_id = resource_attr_id scenario_i.resourcescenarios.append(r_scen_i) # depends on [control=['except'], data=[]] data_type = dataset.type.lower() value = dataset.parse_value() dataset_metadata = dataset.get_metadata_as_dict(user_id=kwargs.get('user_id'), source=kwargs.get('source')) if value is None: raise HydraError('Cannot set value to attribute. No value was sent with dataset %s', dataset.id) # depends on [control=['if'], data=[]] data_hash = dataset.get_hash(value, dataset_metadata) assign_value(r_scen_i, data_type, value, dataset.unit_id, dataset.name, metadata=dataset_metadata, data_hash=data_hash, user_id=user_id) db.DBSession.flush() return r_scen_i
def decode_full_layer_uri(full_layer_uri_string): """Decode the full layer URI. :param full_layer_uri_string: The full URI provided by our helper. :type full_layer_uri_string: basestring :return: A tuple with the QGIS URI and the provider key. :rtype: tuple """ if not full_layer_uri_string: return None, None split = full_layer_uri_string.split('|qgis_provider=') if len(split) == 1: return split[0], None else: return split
def function[decode_full_layer_uri, parameter[full_layer_uri_string]]: constant[Decode the full layer URI. :param full_layer_uri_string: The full URI provided by our helper. :type full_layer_uri_string: basestring :return: A tuple with the QGIS URI and the provider key. :rtype: tuple ] if <ast.UnaryOp object at 0x7da20c76d7b0> begin[:] return[tuple[[<ast.Constant object at 0x7da20c76dcc0>, <ast.Constant object at 0x7da20c76e980>]]] variable[split] assign[=] call[name[full_layer_uri_string].split, parameter[constant[|qgis_provider=]]] if compare[call[name[len], parameter[name[split]]] equal[==] constant[1]] begin[:] return[tuple[[<ast.Subscript object at 0x7da20c76f0a0>, <ast.Constant object at 0x7da1b0c529b0>]]]
keyword[def] identifier[decode_full_layer_uri] ( identifier[full_layer_uri_string] ): literal[string] keyword[if] keyword[not] identifier[full_layer_uri_string] : keyword[return] keyword[None] , keyword[None] identifier[split] = identifier[full_layer_uri_string] . identifier[split] ( literal[string] ) keyword[if] identifier[len] ( identifier[split] )== literal[int] : keyword[return] identifier[split] [ literal[int] ], keyword[None] keyword[else] : keyword[return] identifier[split]
def decode_full_layer_uri(full_layer_uri_string): """Decode the full layer URI. :param full_layer_uri_string: The full URI provided by our helper. :type full_layer_uri_string: basestring :return: A tuple with the QGIS URI and the provider key. :rtype: tuple """ if not full_layer_uri_string: return (None, None) # depends on [control=['if'], data=[]] split = full_layer_uri_string.split('|qgis_provider=') if len(split) == 1: return (split[0], None) # depends on [control=['if'], data=[]] else: return split
def b64decode(s, altchars=None, validate=False): """Decode bytes encoded with the standard Base64 alphabet. Argument ``s`` is a :term:`bytes-like object` or ASCII string to decode. Optional ``altchars`` must be a :term:`bytes-like object` or ASCII string of length 2 which specifies the alternative alphabet used instead of the '+' and '/' characters. If ``validate`` is ``False`` (the default), characters that are neither in the normal base-64 alphabet nor the alternative alphabet are discarded prior to the padding check. If ``validate`` is ``True``, these non-alphabet characters in the input result in a :exc:`binascii.Error`. The result is returned as a :class:`bytes` object. A :exc:`binascii.Error` is raised if ``s`` is incorrectly padded. """ if version_info < (3, 0) or validate: if validate and len(s) % 4 != 0: raise BinAsciiError('Incorrect padding') s = _get_bytes(s) if altchars is not None: altchars = _get_bytes(altchars) assert len(altchars) == 2, repr(altchars) if version_info < (3, 0): map = maketrans(altchars, b'+/') else: map = bytes.maketrans(altchars, b'+/') s = s.translate(map) try: result = builtin_decode(s, altchars) except TypeError as e: raise BinAsciiError(str(e)) if validate: # check length of result vs length of input padding = 0 if len(s) > 1 and s[-2] in (b'=', 61): padding = padding + 1 if len(s) > 0 and s[-1] in (b'=', 61): padding = padding + 1 if 3 * (len(s) / 4) - padding != len(result): raise BinAsciiError('Non-base64 digit found') return result return builtin_decode(s, altchars)
def function[b64decode, parameter[s, altchars, validate]]: constant[Decode bytes encoded with the standard Base64 alphabet. Argument ``s`` is a :term:`bytes-like object` or ASCII string to decode. Optional ``altchars`` must be a :term:`bytes-like object` or ASCII string of length 2 which specifies the alternative alphabet used instead of the '+' and '/' characters. If ``validate`` is ``False`` (the default), characters that are neither in the normal base-64 alphabet nor the alternative alphabet are discarded prior to the padding check. If ``validate`` is ``True``, these non-alphabet characters in the input result in a :exc:`binascii.Error`. The result is returned as a :class:`bytes` object. A :exc:`binascii.Error` is raised if ``s`` is incorrectly padded. ] if <ast.BoolOp object at 0x7da2043454e0> begin[:] if <ast.BoolOp object at 0x7da204345f30> begin[:] <ast.Raise object at 0x7da2043463e0> variable[s] assign[=] call[name[_get_bytes], parameter[name[s]]] if compare[name[altchars] is_not constant[None]] begin[:] variable[altchars] assign[=] call[name[_get_bytes], parameter[name[altchars]]] assert[compare[call[name[len], parameter[name[altchars]]] equal[==] constant[2]]] if compare[name[version_info] less[<] tuple[[<ast.Constant object at 0x7da20c7942b0>, <ast.Constant object at 0x7da20c796530>]]] begin[:] variable[map] assign[=] call[name[maketrans], parameter[name[altchars], constant[b'+/']]] variable[s] assign[=] call[name[s].translate, parameter[name[map]]] <ast.Try object at 0x7da2044c2260> if name[validate] begin[:] variable[padding] assign[=] constant[0] if <ast.BoolOp object at 0x7da18eb549d0> begin[:] variable[padding] assign[=] binary_operation[name[padding] + constant[1]] if <ast.BoolOp object at 0x7da18eb56980> begin[:] variable[padding] assign[=] binary_operation[name[padding] + constant[1]] if compare[binary_operation[binary_operation[constant[3] * binary_operation[call[name[len], parameter[name[s]]] / constant[4]]] - name[padding]] not_equal[!=] call[name[len], parameter[name[result]]]] begin[:] <ast.Raise object at 0x7da18eb56080> return[name[result]] return[call[name[builtin_decode], parameter[name[s], name[altchars]]]]
keyword[def] identifier[b64decode] ( identifier[s] , identifier[altchars] = keyword[None] , identifier[validate] = keyword[False] ): literal[string] keyword[if] identifier[version_info] <( literal[int] , literal[int] ) keyword[or] identifier[validate] : keyword[if] identifier[validate] keyword[and] identifier[len] ( identifier[s] )% literal[int] != literal[int] : keyword[raise] identifier[BinAsciiError] ( literal[string] ) identifier[s] = identifier[_get_bytes] ( identifier[s] ) keyword[if] identifier[altchars] keyword[is] keyword[not] keyword[None] : identifier[altchars] = identifier[_get_bytes] ( identifier[altchars] ) keyword[assert] identifier[len] ( identifier[altchars] )== literal[int] , identifier[repr] ( identifier[altchars] ) keyword[if] identifier[version_info] <( literal[int] , literal[int] ): identifier[map] = identifier[maketrans] ( identifier[altchars] , literal[string] ) keyword[else] : identifier[map] = identifier[bytes] . identifier[maketrans] ( identifier[altchars] , literal[string] ) identifier[s] = identifier[s] . identifier[translate] ( identifier[map] ) keyword[try] : identifier[result] = identifier[builtin_decode] ( identifier[s] , identifier[altchars] ) keyword[except] identifier[TypeError] keyword[as] identifier[e] : keyword[raise] identifier[BinAsciiError] ( identifier[str] ( identifier[e] )) keyword[if] identifier[validate] : identifier[padding] = literal[int] keyword[if] identifier[len] ( identifier[s] )> literal[int] keyword[and] identifier[s] [- literal[int] ] keyword[in] ( literal[string] , literal[int] ): identifier[padding] = identifier[padding] + literal[int] keyword[if] identifier[len] ( identifier[s] )> literal[int] keyword[and] identifier[s] [- literal[int] ] keyword[in] ( literal[string] , literal[int] ): identifier[padding] = identifier[padding] + literal[int] keyword[if] literal[int] *( identifier[len] ( identifier[s] )/ literal[int] )- identifier[padding] != identifier[len] ( identifier[result] ): keyword[raise] identifier[BinAsciiError] ( literal[string] ) keyword[return] identifier[result] keyword[return] identifier[builtin_decode] ( identifier[s] , identifier[altchars] )
def b64decode(s, altchars=None, validate=False): """Decode bytes encoded with the standard Base64 alphabet. Argument ``s`` is a :term:`bytes-like object` or ASCII string to decode. Optional ``altchars`` must be a :term:`bytes-like object` or ASCII string of length 2 which specifies the alternative alphabet used instead of the '+' and '/' characters. If ``validate`` is ``False`` (the default), characters that are neither in the normal base-64 alphabet nor the alternative alphabet are discarded prior to the padding check. If ``validate`` is ``True``, these non-alphabet characters in the input result in a :exc:`binascii.Error`. The result is returned as a :class:`bytes` object. A :exc:`binascii.Error` is raised if ``s`` is incorrectly padded. """ if version_info < (3, 0) or validate: if validate and len(s) % 4 != 0: raise BinAsciiError('Incorrect padding') # depends on [control=['if'], data=[]] s = _get_bytes(s) if altchars is not None: altchars = _get_bytes(altchars) assert len(altchars) == 2, repr(altchars) if version_info < (3, 0): map = maketrans(altchars, b'+/') # depends on [control=['if'], data=[]] else: map = bytes.maketrans(altchars, b'+/') s = s.translate(map) # depends on [control=['if'], data=['altchars']] try: result = builtin_decode(s, altchars) # depends on [control=['try'], data=[]] except TypeError as e: raise BinAsciiError(str(e)) # depends on [control=['except'], data=['e']] if validate: # check length of result vs length of input padding = 0 if len(s) > 1 and s[-2] in (b'=', 61): padding = padding + 1 # depends on [control=['if'], data=[]] if len(s) > 0 and s[-1] in (b'=', 61): padding = padding + 1 # depends on [control=['if'], data=[]] if 3 * (len(s) / 4) - padding != len(result): raise BinAsciiError('Non-base64 digit found') # depends on [control=['if'], data=[]] # depends on [control=['if'], data=[]] return result # depends on [control=['if'], data=[]] return builtin_decode(s, altchars)
def request(self, method, url, **kwargs): """ Override, wraps Session.request in caching. Cache is only used if key_for_request returns a valid key and should_cache_response was true as well. """ # short circuit if cache isn't configured if not self.cache_storage: resp = super(CachingSession, self).request(method, url, **kwargs) resp.fromcache = False return resp resp = None method = method.lower() request_key = self.key_for_request(method, url, **kwargs) if request_key and not self.cache_write_only: resp = self.cache_storage.get(request_key) if resp: resp.fromcache = True else: resp = super(CachingSession, self).request(method, url, **kwargs) # save to cache if request and response meet criteria if request_key and self.should_cache_response(resp): self.cache_storage.set(request_key, resp) resp.fromcache = False return resp
def function[request, parameter[self, method, url]]: constant[ Override, wraps Session.request in caching. Cache is only used if key_for_request returns a valid key and should_cache_response was true as well. ] if <ast.UnaryOp object at 0x7da20c6c6dd0> begin[:] variable[resp] assign[=] call[call[name[super], parameter[name[CachingSession], name[self]]].request, parameter[name[method], name[url]]] name[resp].fromcache assign[=] constant[False] return[name[resp]] variable[resp] assign[=] constant[None] variable[method] assign[=] call[name[method].lower, parameter[]] variable[request_key] assign[=] call[name[self].key_for_request, parameter[name[method], name[url]]] if <ast.BoolOp object at 0x7da1b26aead0> begin[:] variable[resp] assign[=] call[name[self].cache_storage.get, parameter[name[request_key]]] if name[resp] begin[:] name[resp].fromcache assign[=] constant[True] return[name[resp]]
keyword[def] identifier[request] ( identifier[self] , identifier[method] , identifier[url] ,** identifier[kwargs] ): literal[string] keyword[if] keyword[not] identifier[self] . identifier[cache_storage] : identifier[resp] = identifier[super] ( identifier[CachingSession] , identifier[self] ). identifier[request] ( identifier[method] , identifier[url] ,** identifier[kwargs] ) identifier[resp] . identifier[fromcache] = keyword[False] keyword[return] identifier[resp] identifier[resp] = keyword[None] identifier[method] = identifier[method] . identifier[lower] () identifier[request_key] = identifier[self] . identifier[key_for_request] ( identifier[method] , identifier[url] ,** identifier[kwargs] ) keyword[if] identifier[request_key] keyword[and] keyword[not] identifier[self] . identifier[cache_write_only] : identifier[resp] = identifier[self] . identifier[cache_storage] . identifier[get] ( identifier[request_key] ) keyword[if] identifier[resp] : identifier[resp] . identifier[fromcache] = keyword[True] keyword[else] : identifier[resp] = identifier[super] ( identifier[CachingSession] , identifier[self] ). identifier[request] ( identifier[method] , identifier[url] ,** identifier[kwargs] ) keyword[if] identifier[request_key] keyword[and] identifier[self] . identifier[should_cache_response] ( identifier[resp] ): identifier[self] . identifier[cache_storage] . identifier[set] ( identifier[request_key] , identifier[resp] ) identifier[resp] . identifier[fromcache] = keyword[False] keyword[return] identifier[resp]
def request(self, method, url, **kwargs): """ Override, wraps Session.request in caching. Cache is only used if key_for_request returns a valid key and should_cache_response was true as well. """ # short circuit if cache isn't configured if not self.cache_storage: resp = super(CachingSession, self).request(method, url, **kwargs) resp.fromcache = False return resp # depends on [control=['if'], data=[]] resp = None method = method.lower() request_key = self.key_for_request(method, url, **kwargs) if request_key and (not self.cache_write_only): resp = self.cache_storage.get(request_key) # depends on [control=['if'], data=[]] if resp: resp.fromcache = True # depends on [control=['if'], data=[]] else: resp = super(CachingSession, self).request(method, url, **kwargs) # save to cache if request and response meet criteria if request_key and self.should_cache_response(resp): self.cache_storage.set(request_key, resp) # depends on [control=['if'], data=[]] resp.fromcache = False return resp
def _annotate( cls, item, timestamp, stack_depth ): """ :param itemt: A LogItemTHE TYPE OF MESSAGE :param stack_depth: FOR TRACKING WHAT LINE THIS CAME FROM :return: """ item.timestamp = timestamp item.machine = machine_metadata item.template = strings.limit(item.template, 10000) item.format = strings.limit(item.format, 10000) if item.format == None: format = text_type(item) else: format = item.format.replace("{{", "{{params.") if not format.startswith(CR) and format.find(CR) > -1: format = CR + format if cls.trace: log_format = item.format = "{{machine.name}} (pid {{machine.pid}}) - {{timestamp|datetime}} - {{thread.name}} - \"{{location.file}}:{{location.line}}\" - ({{location.method}}) - " + format f = sys._getframe(stack_depth + 1) item.location = { "line": f.f_lineno, "file": text_type(f.f_code.co_filename), "method": text_type(f.f_code.co_name) } thread = _Thread.current() item.thread = {"name": thread.name, "id": thread.id} else: log_format = item.format = "{{timestamp|datetime}} - " + format cls.main_log.write(log_format, item.__data__())
def function[_annotate, parameter[cls, item, timestamp, stack_depth]]: constant[ :param itemt: A LogItemTHE TYPE OF MESSAGE :param stack_depth: FOR TRACKING WHAT LINE THIS CAME FROM :return: ] name[item].timestamp assign[=] name[timestamp] name[item].machine assign[=] name[machine_metadata] name[item].template assign[=] call[name[strings].limit, parameter[name[item].template, constant[10000]]] name[item].format assign[=] call[name[strings].limit, parameter[name[item].format, constant[10000]]] if compare[name[item].format equal[==] constant[None]] begin[:] variable[format] assign[=] call[name[text_type], parameter[name[item]]] if <ast.BoolOp object at 0x7da18f09f790> begin[:] variable[format] assign[=] binary_operation[name[CR] + name[format]] if name[cls].trace begin[:] variable[log_format] assign[=] binary_operation[constant[{{machine.name}} (pid {{machine.pid}}) - {{timestamp|datetime}} - {{thread.name}} - "{{location.file}}:{{location.line}}" - ({{location.method}}) - ] + name[format]] variable[f] assign[=] call[name[sys]._getframe, parameter[binary_operation[name[stack_depth] + constant[1]]]] name[item].location assign[=] dictionary[[<ast.Constant object at 0x7da18f09fd60>, <ast.Constant object at 0x7da18f09d690>, <ast.Constant object at 0x7da18bcc9450>], [<ast.Attribute object at 0x7da18bcc8430>, <ast.Call object at 0x7da18bccbd60>, <ast.Call object at 0x7da18bcc9d80>]] variable[thread] assign[=] call[name[_Thread].current, parameter[]] name[item].thread assign[=] dictionary[[<ast.Constant object at 0x7da18bcca5c0>, <ast.Constant object at 0x7da18bcc8df0>], [<ast.Attribute object at 0x7da18bcca350>, <ast.Attribute object at 0x7da18bcca680>]] call[name[cls].main_log.write, parameter[name[log_format], call[name[item].__data__, parameter[]]]]
keyword[def] identifier[_annotate] ( identifier[cls] , identifier[item] , identifier[timestamp] , identifier[stack_depth] ): literal[string] identifier[item] . identifier[timestamp] = identifier[timestamp] identifier[item] . identifier[machine] = identifier[machine_metadata] identifier[item] . identifier[template] = identifier[strings] . identifier[limit] ( identifier[item] . identifier[template] , literal[int] ) identifier[item] . identifier[format] = identifier[strings] . identifier[limit] ( identifier[item] . identifier[format] , literal[int] ) keyword[if] identifier[item] . identifier[format] == keyword[None] : identifier[format] = identifier[text_type] ( identifier[item] ) keyword[else] : identifier[format] = identifier[item] . identifier[format] . identifier[replace] ( literal[string] , literal[string] ) keyword[if] keyword[not] identifier[format] . identifier[startswith] ( identifier[CR] ) keyword[and] identifier[format] . identifier[find] ( identifier[CR] )>- literal[int] : identifier[format] = identifier[CR] + identifier[format] keyword[if] identifier[cls] . identifier[trace] : identifier[log_format] = identifier[item] . identifier[format] = literal[string] + identifier[format] identifier[f] = identifier[sys] . identifier[_getframe] ( identifier[stack_depth] + literal[int] ) identifier[item] . identifier[location] ={ literal[string] : identifier[f] . identifier[f_lineno] , literal[string] : identifier[text_type] ( identifier[f] . identifier[f_code] . identifier[co_filename] ), literal[string] : identifier[text_type] ( identifier[f] . identifier[f_code] . identifier[co_name] ) } identifier[thread] = identifier[_Thread] . identifier[current] () identifier[item] . identifier[thread] ={ literal[string] : identifier[thread] . identifier[name] , literal[string] : identifier[thread] . identifier[id] } keyword[else] : identifier[log_format] = identifier[item] . identifier[format] = literal[string] + identifier[format] identifier[cls] . identifier[main_log] . identifier[write] ( identifier[log_format] , identifier[item] . identifier[__data__] ())
def _annotate(cls, item, timestamp, stack_depth): """ :param itemt: A LogItemTHE TYPE OF MESSAGE :param stack_depth: FOR TRACKING WHAT LINE THIS CAME FROM :return: """ item.timestamp = timestamp item.machine = machine_metadata item.template = strings.limit(item.template, 10000) item.format = strings.limit(item.format, 10000) if item.format == None: format = text_type(item) # depends on [control=['if'], data=[]] else: format = item.format.replace('{{', '{{params.') if not format.startswith(CR) and format.find(CR) > -1: format = CR + format # depends on [control=['if'], data=[]] if cls.trace: log_format = item.format = '{{machine.name}} (pid {{machine.pid}}) - {{timestamp|datetime}} - {{thread.name}} - "{{location.file}}:{{location.line}}" - ({{location.method}}) - ' + format f = sys._getframe(stack_depth + 1) item.location = {'line': f.f_lineno, 'file': text_type(f.f_code.co_filename), 'method': text_type(f.f_code.co_name)} thread = _Thread.current() item.thread = {'name': thread.name, 'id': thread.id} # depends on [control=['if'], data=[]] else: log_format = item.format = '{{timestamp|datetime}} - ' + format cls.main_log.write(log_format, item.__data__())
def create_api_environment_vip(self): """Get an instance of Api Environment Vip services facade.""" return ApiEnvironmentVip( self.networkapi_url, self.user, self.password, self.user_ldap)
def function[create_api_environment_vip, parameter[self]]: constant[Get an instance of Api Environment Vip services facade.] return[call[name[ApiEnvironmentVip], parameter[name[self].networkapi_url, name[self].user, name[self].password, name[self].user_ldap]]]
keyword[def] identifier[create_api_environment_vip] ( identifier[self] ): literal[string] keyword[return] identifier[ApiEnvironmentVip] ( identifier[self] . identifier[networkapi_url] , identifier[self] . identifier[user] , identifier[self] . identifier[password] , identifier[self] . identifier[user_ldap] )
def create_api_environment_vip(self): """Get an instance of Api Environment Vip services facade.""" return ApiEnvironmentVip(self.networkapi_url, self.user, self.password, self.user_ldap)
def __execute_cmd(name, cmd): ''' Execute Riak commands ''' return __salt__['cmd.run_all']( '{0} {1}'.format(salt.utils.path.which(name), cmd) )
def function[__execute_cmd, parameter[name, cmd]]: constant[ Execute Riak commands ] return[call[call[name[__salt__]][constant[cmd.run_all]], parameter[call[constant[{0} {1}].format, parameter[call[name[salt].utils.path.which, parameter[name[name]]], name[cmd]]]]]]
keyword[def] identifier[__execute_cmd] ( identifier[name] , identifier[cmd] ): literal[string] keyword[return] identifier[__salt__] [ literal[string] ]( literal[string] . identifier[format] ( identifier[salt] . identifier[utils] . identifier[path] . identifier[which] ( identifier[name] ), identifier[cmd] ) )
def __execute_cmd(name, cmd): """ Execute Riak commands """ return __salt__['cmd.run_all']('{0} {1}'.format(salt.utils.path.which(name), cmd))
def updateCheckState( self ): """ Updates the items to reflect the current check state system. """ checkable = self.isCheckable() model = self.model() flags = Qt.ItemIsSelectable | Qt.ItemIsEnabled for i in range(self.count()): item = model.item(i) if not (checkable and item.text()): item.setCheckable(False) item.setFlags(flags) # only allow checking for items with text else: item.setCheckable(True) item.setFlags(flags | Qt.ItemIsUserCheckable)
def function[updateCheckState, parameter[self]]: constant[ Updates the items to reflect the current check state system. ] variable[checkable] assign[=] call[name[self].isCheckable, parameter[]] variable[model] assign[=] call[name[self].model, parameter[]] variable[flags] assign[=] binary_operation[name[Qt].ItemIsSelectable <ast.BitOr object at 0x7da2590d6aa0> name[Qt].ItemIsEnabled] for taget[name[i]] in starred[call[name[range], parameter[call[name[self].count, parameter[]]]]] begin[:] variable[item] assign[=] call[name[model].item, parameter[name[i]]] if <ast.UnaryOp object at 0x7da18c4cd210> begin[:] call[name[item].setCheckable, parameter[constant[False]]] call[name[item].setFlags, parameter[name[flags]]]
keyword[def] identifier[updateCheckState] ( identifier[self] ): literal[string] identifier[checkable] = identifier[self] . identifier[isCheckable] () identifier[model] = identifier[self] . identifier[model] () identifier[flags] = identifier[Qt] . identifier[ItemIsSelectable] | identifier[Qt] . identifier[ItemIsEnabled] keyword[for] identifier[i] keyword[in] identifier[range] ( identifier[self] . identifier[count] ()): identifier[item] = identifier[model] . identifier[item] ( identifier[i] ) keyword[if] keyword[not] ( identifier[checkable] keyword[and] identifier[item] . identifier[text] ()): identifier[item] . identifier[setCheckable] ( keyword[False] ) identifier[item] . identifier[setFlags] ( identifier[flags] ) keyword[else] : identifier[item] . identifier[setCheckable] ( keyword[True] ) identifier[item] . identifier[setFlags] ( identifier[flags] | identifier[Qt] . identifier[ItemIsUserCheckable] )
def updateCheckState(self): """ Updates the items to reflect the current check state system. """ checkable = self.isCheckable() model = self.model() flags = Qt.ItemIsSelectable | Qt.ItemIsEnabled for i in range(self.count()): item = model.item(i) if not (checkable and item.text()): item.setCheckable(False) item.setFlags(flags) # depends on [control=['if'], data=[]] else: # only allow checking for items with text item.setCheckable(True) item.setFlags(flags | Qt.ItemIsUserCheckable) # depends on [control=['for'], data=['i']]
def get(self, variable_path: str, default: t.Optional[t.Any] = None, coerce_type: t.Optional[t.Type] = None, coercer: t.Optional[t.Callable] = None, **kwargs): """ Inherited method should take all specified arguments. :param variable_path: a delimiter-separated path to a nested value :param default: default value if there's no object by specified path :param coerce_type: cast a type of a value to a specified one :param coercer: perform a type casting with specified callback :param kwargs: additional arguments inherited parser may need :return: value or default """ raise NotImplementedError
def function[get, parameter[self, variable_path, default, coerce_type, coercer]]: constant[ Inherited method should take all specified arguments. :param variable_path: a delimiter-separated path to a nested value :param default: default value if there's no object by specified path :param coerce_type: cast a type of a value to a specified one :param coercer: perform a type casting with specified callback :param kwargs: additional arguments inherited parser may need :return: value or default ] <ast.Raise object at 0x7da1b10b2200>
keyword[def] identifier[get] ( identifier[self] , identifier[variable_path] : identifier[str] , identifier[default] : identifier[t] . identifier[Optional] [ identifier[t] . identifier[Any] ]= keyword[None] , identifier[coerce_type] : identifier[t] . identifier[Optional] [ identifier[t] . identifier[Type] ]= keyword[None] , identifier[coercer] : identifier[t] . identifier[Optional] [ identifier[t] . identifier[Callable] ]= keyword[None] , ** identifier[kwargs] ): literal[string] keyword[raise] identifier[NotImplementedError]
def get(self, variable_path: str, default: t.Optional[t.Any]=None, coerce_type: t.Optional[t.Type]=None, coercer: t.Optional[t.Callable]=None, **kwargs): """ Inherited method should take all specified arguments. :param variable_path: a delimiter-separated path to a nested value :param default: default value if there's no object by specified path :param coerce_type: cast a type of a value to a specified one :param coercer: perform a type casting with specified callback :param kwargs: additional arguments inherited parser may need :return: value or default """ raise NotImplementedError
def storage_keys(self): """ Return a list of the keys for values stored for the module. Keys will contain the following metadata entries: - '_ctime': storage creation timestamp - '_mtime': storage last modification timestamp """ if not self._module: return [] self._storage_init() module_name = self._module.module_full_name return self._storage.storage_keys(module_name)
def function[storage_keys, parameter[self]]: constant[ Return a list of the keys for values stored for the module. Keys will contain the following metadata entries: - '_ctime': storage creation timestamp - '_mtime': storage last modification timestamp ] if <ast.UnaryOp object at 0x7da1b1de1b70> begin[:] return[list[[]]] call[name[self]._storage_init, parameter[]] variable[module_name] assign[=] name[self]._module.module_full_name return[call[name[self]._storage.storage_keys, parameter[name[module_name]]]]
keyword[def] identifier[storage_keys] ( identifier[self] ): literal[string] keyword[if] keyword[not] identifier[self] . identifier[_module] : keyword[return] [] identifier[self] . identifier[_storage_init] () identifier[module_name] = identifier[self] . identifier[_module] . identifier[module_full_name] keyword[return] identifier[self] . identifier[_storage] . identifier[storage_keys] ( identifier[module_name] )
def storage_keys(self): """ Return a list of the keys for values stored for the module. Keys will contain the following metadata entries: - '_ctime': storage creation timestamp - '_mtime': storage last modification timestamp """ if not self._module: return [] # depends on [control=['if'], data=[]] self._storage_init() module_name = self._module.module_full_name return self._storage.storage_keys(module_name)
def get_var_properties(self): """ Get some properties of the variables in the current namespace """ from spyder_kernels.utils.nsview import get_remote_data settings = self.namespace_view_settings if settings: ns = self._get_current_namespace() data = get_remote_data(ns, settings, mode='editable', more_excluded_names=EXCLUDED_NAMES) properties = {} for name, value in list(data.items()): properties[name] = { 'is_list': isinstance(value, (tuple, list)), 'is_dict': isinstance(value, dict), 'is_set': isinstance(value, set), 'len': self._get_len(value), 'is_array': self._is_array(value), 'is_image': self._is_image(value), 'is_data_frame': self._is_data_frame(value), 'is_series': self._is_series(value), 'array_shape': self._get_array_shape(value), 'array_ndim': self._get_array_ndim(value) } return repr(properties) else: return repr(None)
def function[get_var_properties, parameter[self]]: constant[ Get some properties of the variables in the current namespace ] from relative_module[spyder_kernels.utils.nsview] import module[get_remote_data] variable[settings] assign[=] name[self].namespace_view_settings if name[settings] begin[:] variable[ns] assign[=] call[name[self]._get_current_namespace, parameter[]] variable[data] assign[=] call[name[get_remote_data], parameter[name[ns], name[settings]]] variable[properties] assign[=] dictionary[[], []] for taget[tuple[[<ast.Name object at 0x7da20c6e4640>, <ast.Name object at 0x7da20c6e6d70>]]] in starred[call[name[list], parameter[call[name[data].items, parameter[]]]]] begin[:] call[name[properties]][name[name]] assign[=] dictionary[[<ast.Constant object at 0x7da20e9579a0>, <ast.Constant object at 0x7da20e955c30>, <ast.Constant object at 0x7da20e957970>, <ast.Constant object at 0x7da20e957df0>, <ast.Constant object at 0x7da20e957310>, <ast.Constant object at 0x7da20e954310>, <ast.Constant object at 0x7da20e955150>, <ast.Constant object at 0x7da20e956020>, <ast.Constant object at 0x7da20e956a40>, <ast.Constant object at 0x7da20e954e80>], [<ast.Call object at 0x7da20e955870>, <ast.Call object at 0x7da20e956740>, <ast.Call object at 0x7da20e9557b0>, <ast.Call object at 0x7da20e955720>, <ast.Call object at 0x7da20e955f00>, <ast.Call object at 0x7da20e954a60>, <ast.Call object at 0x7da20e954130>, <ast.Call object at 0x7da20e9550f0>, <ast.Call object at 0x7da20e957040>, <ast.Call object at 0x7da20e956890>]] return[call[name[repr], parameter[name[properties]]]]
keyword[def] identifier[get_var_properties] ( identifier[self] ): literal[string] keyword[from] identifier[spyder_kernels] . identifier[utils] . identifier[nsview] keyword[import] identifier[get_remote_data] identifier[settings] = identifier[self] . identifier[namespace_view_settings] keyword[if] identifier[settings] : identifier[ns] = identifier[self] . identifier[_get_current_namespace] () identifier[data] = identifier[get_remote_data] ( identifier[ns] , identifier[settings] , identifier[mode] = literal[string] , identifier[more_excluded_names] = identifier[EXCLUDED_NAMES] ) identifier[properties] ={} keyword[for] identifier[name] , identifier[value] keyword[in] identifier[list] ( identifier[data] . identifier[items] ()): identifier[properties] [ identifier[name] ]={ literal[string] : identifier[isinstance] ( identifier[value] ,( identifier[tuple] , identifier[list] )), literal[string] : identifier[isinstance] ( identifier[value] , identifier[dict] ), literal[string] : identifier[isinstance] ( identifier[value] , identifier[set] ), literal[string] : identifier[self] . identifier[_get_len] ( identifier[value] ), literal[string] : identifier[self] . identifier[_is_array] ( identifier[value] ), literal[string] : identifier[self] . identifier[_is_image] ( identifier[value] ), literal[string] : identifier[self] . identifier[_is_data_frame] ( identifier[value] ), literal[string] : identifier[self] . identifier[_is_series] ( identifier[value] ), literal[string] : identifier[self] . identifier[_get_array_shape] ( identifier[value] ), literal[string] : identifier[self] . identifier[_get_array_ndim] ( identifier[value] ) } keyword[return] identifier[repr] ( identifier[properties] ) keyword[else] : keyword[return] identifier[repr] ( keyword[None] )
def get_var_properties(self): """ Get some properties of the variables in the current namespace """ from spyder_kernels.utils.nsview import get_remote_data settings = self.namespace_view_settings if settings: ns = self._get_current_namespace() data = get_remote_data(ns, settings, mode='editable', more_excluded_names=EXCLUDED_NAMES) properties = {} for (name, value) in list(data.items()): properties[name] = {'is_list': isinstance(value, (tuple, list)), 'is_dict': isinstance(value, dict), 'is_set': isinstance(value, set), 'len': self._get_len(value), 'is_array': self._is_array(value), 'is_image': self._is_image(value), 'is_data_frame': self._is_data_frame(value), 'is_series': self._is_series(value), 'array_shape': self._get_array_shape(value), 'array_ndim': self._get_array_ndim(value)} # depends on [control=['for'], data=[]] return repr(properties) # depends on [control=['if'], data=[]] else: return repr(None)
def ProcessLine(filename, file_extension, clean_lines, line, include_state, function_state, nesting_state, error, extra_check_functions=[]): """Processes a single line in the file. Args: filename: Filename of the file that is being processed. file_extension: The extension (dot not included) of the file. clean_lines: An array of strings, each representing a line of the file, with comments stripped. line: Number of line being processed. include_state: An _IncludeState instance in which the headers are inserted. function_state: A _FunctionState instance which counts function lines, etc. nesting_state: A NestingState instance which maintains information about the current stack of nested blocks being parsed. error: A callable to which errors are reported, which takes 4 arguments: filename, line number, error level, and message extra_check_functions: An array of additional check functions that will be run on each source line. Each function takes 4 arguments: filename, clean_lines, line, error """ raw_lines = clean_lines.raw_lines ParseNolintSuppressions(filename, raw_lines[line], line, error) nesting_state.Update(filename, clean_lines, line, error) CheckForNamespaceIndentation(filename, nesting_state, clean_lines, line, error) if nesting_state.InAsmBlock(): return CheckForFunctionLengths(filename, clean_lines, line, function_state, error) CheckForMultilineCommentsAndStrings(filename, clean_lines, line, error) CheckStyle(filename, clean_lines, line, file_extension, nesting_state, error) CheckLanguage(filename, clean_lines, line, file_extension, include_state, nesting_state, error) CheckForNonConstReference(filename, clean_lines, line, nesting_state, error) CheckForNonStandardConstructs(filename, clean_lines, line, nesting_state, error) CheckVlogArguments(filename, clean_lines, line, error) CheckPosixThreading(filename, clean_lines, line, error) CheckInvalidIncrement(filename, clean_lines, line, error) CheckMakePairUsesDeduction(filename, clean_lines, line, error) CheckDefaultLambdaCaptures(filename, clean_lines, line, error) CheckRedundantVirtual(filename, clean_lines, line, error) CheckRedundantOverrideOrFinal(filename, clean_lines, line, error) for check_fn in extra_check_functions: check_fn(filename, clean_lines, line, error)
def function[ProcessLine, parameter[filename, file_extension, clean_lines, line, include_state, function_state, nesting_state, error, extra_check_functions]]: constant[Processes a single line in the file. Args: filename: Filename of the file that is being processed. file_extension: The extension (dot not included) of the file. clean_lines: An array of strings, each representing a line of the file, with comments stripped. line: Number of line being processed. include_state: An _IncludeState instance in which the headers are inserted. function_state: A _FunctionState instance which counts function lines, etc. nesting_state: A NestingState instance which maintains information about the current stack of nested blocks being parsed. error: A callable to which errors are reported, which takes 4 arguments: filename, line number, error level, and message extra_check_functions: An array of additional check functions that will be run on each source line. Each function takes 4 arguments: filename, clean_lines, line, error ] variable[raw_lines] assign[=] name[clean_lines].raw_lines call[name[ParseNolintSuppressions], parameter[name[filename], call[name[raw_lines]][name[line]], name[line], name[error]]] call[name[nesting_state].Update, parameter[name[filename], name[clean_lines], name[line], name[error]]] call[name[CheckForNamespaceIndentation], parameter[name[filename], name[nesting_state], name[clean_lines], name[line], name[error]]] if call[name[nesting_state].InAsmBlock, parameter[]] begin[:] return[None] call[name[CheckForFunctionLengths], parameter[name[filename], name[clean_lines], name[line], name[function_state], name[error]]] call[name[CheckForMultilineCommentsAndStrings], parameter[name[filename], name[clean_lines], name[line], name[error]]] call[name[CheckStyle], parameter[name[filename], name[clean_lines], name[line], name[file_extension], name[nesting_state], name[error]]] call[name[CheckLanguage], parameter[name[filename], name[clean_lines], name[line], name[file_extension], name[include_state], name[nesting_state], name[error]]] call[name[CheckForNonConstReference], parameter[name[filename], name[clean_lines], name[line], name[nesting_state], name[error]]] call[name[CheckForNonStandardConstructs], parameter[name[filename], name[clean_lines], name[line], name[nesting_state], name[error]]] call[name[CheckVlogArguments], parameter[name[filename], name[clean_lines], name[line], name[error]]] call[name[CheckPosixThreading], parameter[name[filename], name[clean_lines], name[line], name[error]]] call[name[CheckInvalidIncrement], parameter[name[filename], name[clean_lines], name[line], name[error]]] call[name[CheckMakePairUsesDeduction], parameter[name[filename], name[clean_lines], name[line], name[error]]] call[name[CheckDefaultLambdaCaptures], parameter[name[filename], name[clean_lines], name[line], name[error]]] call[name[CheckRedundantVirtual], parameter[name[filename], name[clean_lines], name[line], name[error]]] call[name[CheckRedundantOverrideOrFinal], parameter[name[filename], name[clean_lines], name[line], name[error]]] for taget[name[check_fn]] in starred[name[extra_check_functions]] begin[:] call[name[check_fn], parameter[name[filename], name[clean_lines], name[line], name[error]]]
keyword[def] identifier[ProcessLine] ( identifier[filename] , identifier[file_extension] , identifier[clean_lines] , identifier[line] , identifier[include_state] , identifier[function_state] , identifier[nesting_state] , identifier[error] , identifier[extra_check_functions] =[]): literal[string] identifier[raw_lines] = identifier[clean_lines] . identifier[raw_lines] identifier[ParseNolintSuppressions] ( identifier[filename] , identifier[raw_lines] [ identifier[line] ], identifier[line] , identifier[error] ) identifier[nesting_state] . identifier[Update] ( identifier[filename] , identifier[clean_lines] , identifier[line] , identifier[error] ) identifier[CheckForNamespaceIndentation] ( identifier[filename] , identifier[nesting_state] , identifier[clean_lines] , identifier[line] , identifier[error] ) keyword[if] identifier[nesting_state] . identifier[InAsmBlock] (): keyword[return] identifier[CheckForFunctionLengths] ( identifier[filename] , identifier[clean_lines] , identifier[line] , identifier[function_state] , identifier[error] ) identifier[CheckForMultilineCommentsAndStrings] ( identifier[filename] , identifier[clean_lines] , identifier[line] , identifier[error] ) identifier[CheckStyle] ( identifier[filename] , identifier[clean_lines] , identifier[line] , identifier[file_extension] , identifier[nesting_state] , identifier[error] ) identifier[CheckLanguage] ( identifier[filename] , identifier[clean_lines] , identifier[line] , identifier[file_extension] , identifier[include_state] , identifier[nesting_state] , identifier[error] ) identifier[CheckForNonConstReference] ( identifier[filename] , identifier[clean_lines] , identifier[line] , identifier[nesting_state] , identifier[error] ) identifier[CheckForNonStandardConstructs] ( identifier[filename] , identifier[clean_lines] , identifier[line] , identifier[nesting_state] , identifier[error] ) identifier[CheckVlogArguments] ( identifier[filename] , identifier[clean_lines] , identifier[line] , identifier[error] ) identifier[CheckPosixThreading] ( identifier[filename] , identifier[clean_lines] , identifier[line] , identifier[error] ) identifier[CheckInvalidIncrement] ( identifier[filename] , identifier[clean_lines] , identifier[line] , identifier[error] ) identifier[CheckMakePairUsesDeduction] ( identifier[filename] , identifier[clean_lines] , identifier[line] , identifier[error] ) identifier[CheckDefaultLambdaCaptures] ( identifier[filename] , identifier[clean_lines] , identifier[line] , identifier[error] ) identifier[CheckRedundantVirtual] ( identifier[filename] , identifier[clean_lines] , identifier[line] , identifier[error] ) identifier[CheckRedundantOverrideOrFinal] ( identifier[filename] , identifier[clean_lines] , identifier[line] , identifier[error] ) keyword[for] identifier[check_fn] keyword[in] identifier[extra_check_functions] : identifier[check_fn] ( identifier[filename] , identifier[clean_lines] , identifier[line] , identifier[error] )
def ProcessLine(filename, file_extension, clean_lines, line, include_state, function_state, nesting_state, error, extra_check_functions=[]): """Processes a single line in the file. Args: filename: Filename of the file that is being processed. file_extension: The extension (dot not included) of the file. clean_lines: An array of strings, each representing a line of the file, with comments stripped. line: Number of line being processed. include_state: An _IncludeState instance in which the headers are inserted. function_state: A _FunctionState instance which counts function lines, etc. nesting_state: A NestingState instance which maintains information about the current stack of nested blocks being parsed. error: A callable to which errors are reported, which takes 4 arguments: filename, line number, error level, and message extra_check_functions: An array of additional check functions that will be run on each source line. Each function takes 4 arguments: filename, clean_lines, line, error """ raw_lines = clean_lines.raw_lines ParseNolintSuppressions(filename, raw_lines[line], line, error) nesting_state.Update(filename, clean_lines, line, error) CheckForNamespaceIndentation(filename, nesting_state, clean_lines, line, error) if nesting_state.InAsmBlock(): return # depends on [control=['if'], data=[]] CheckForFunctionLengths(filename, clean_lines, line, function_state, error) CheckForMultilineCommentsAndStrings(filename, clean_lines, line, error) CheckStyle(filename, clean_lines, line, file_extension, nesting_state, error) CheckLanguage(filename, clean_lines, line, file_extension, include_state, nesting_state, error) CheckForNonConstReference(filename, clean_lines, line, nesting_state, error) CheckForNonStandardConstructs(filename, clean_lines, line, nesting_state, error) CheckVlogArguments(filename, clean_lines, line, error) CheckPosixThreading(filename, clean_lines, line, error) CheckInvalidIncrement(filename, clean_lines, line, error) CheckMakePairUsesDeduction(filename, clean_lines, line, error) CheckDefaultLambdaCaptures(filename, clean_lines, line, error) CheckRedundantVirtual(filename, clean_lines, line, error) CheckRedundantOverrideOrFinal(filename, clean_lines, line, error) for check_fn in extra_check_functions: check_fn(filename, clean_lines, line, error) # depends on [control=['for'], data=['check_fn']]
def on_checked_changed(self, value): """ See https://stackoverflow.com/questions/19628310/ """ #: Since iOS decides to call this like 100 times for each defer it d = self.declaration with self.widget.setValue.suppressed(): d.progress = int(value)
def function[on_checked_changed, parameter[self, value]]: constant[ See https://stackoverflow.com/questions/19628310/ ] variable[d] assign[=] name[self].declaration with call[name[self].widget.setValue.suppressed, parameter[]] begin[:] name[d].progress assign[=] call[name[int], parameter[name[value]]]
keyword[def] identifier[on_checked_changed] ( identifier[self] , identifier[value] ): literal[string] identifier[d] = identifier[self] . identifier[declaration] keyword[with] identifier[self] . identifier[widget] . identifier[setValue] . identifier[suppressed] (): identifier[d] . identifier[progress] = identifier[int] ( identifier[value] )
def on_checked_changed(self, value): """ See https://stackoverflow.com/questions/19628310/ """ #: Since iOS decides to call this like 100 times for each defer it d = self.declaration with self.widget.setValue.suppressed(): d.progress = int(value) # depends on [control=['with'], data=[]]
def followers(self): """ :class:`Feed <pypump.models.feed.Feed>` with all :class:`Person <pypump.models.person.Person>` objects following the person. Example: >>> alice = pump.Person('alice@example.org') >>> for follower in alice.followers[:2]: ... print(follower.id) ... acct:bob@example.org acct:carol@example.org """ if self._followers is None: self._followers = Followers(self.links['followers'], pypump=self._pump) return self._followers
def function[followers, parameter[self]]: constant[ :class:`Feed <pypump.models.feed.Feed>` with all :class:`Person <pypump.models.person.Person>` objects following the person. Example: >>> alice = pump.Person('alice@example.org') >>> for follower in alice.followers[:2]: ... print(follower.id) ... acct:bob@example.org acct:carol@example.org ] if compare[name[self]._followers is constant[None]] begin[:] name[self]._followers assign[=] call[name[Followers], parameter[call[name[self].links][constant[followers]]]] return[name[self]._followers]
keyword[def] identifier[followers] ( identifier[self] ): literal[string] keyword[if] identifier[self] . identifier[_followers] keyword[is] keyword[None] : identifier[self] . identifier[_followers] = identifier[Followers] ( identifier[self] . identifier[links] [ literal[string] ], identifier[pypump] = identifier[self] . identifier[_pump] ) keyword[return] identifier[self] . identifier[_followers]
def followers(self): """ :class:`Feed <pypump.models.feed.Feed>` with all :class:`Person <pypump.models.person.Person>` objects following the person. Example: >>> alice = pump.Person('alice@example.org') >>> for follower in alice.followers[:2]: ... print(follower.id) ... acct:bob@example.org acct:carol@example.org """ if self._followers is None: self._followers = Followers(self.links['followers'], pypump=self._pump) # depends on [control=['if'], data=[]] return self._followers
def auto_assign_shifts(semester=None, pool=None, profiles=None, shifts=None): """ Auto-assigns profiles to regular workshifts. Parameters ---------- semester : workshift.models.Semester, optional pool : workshift.models.WorkshiftPool, optional profiles : list of workshift.models.WorkshiftProfile, optional shifts : list of workshift.models.RegularWorkshift, optional """ if semester is None: try: semester = Semester.objects.get(current=True) except (Semester.DoesNotExist, Semester.MultipleObjectsReturned): return if pool is None: pool = WorkshiftPool.objects.get( semester=semester, is_primary=True, ) if profiles is None: profiles = WorkshiftProfile.objects.filter( semester=semester, ).order_by('preference_save_time') if shifts is None: shifts = RegularWorkshift.objects.filter( pool=pool, workshift_type__assignment=WorkshiftType.AUTO_ASSIGN, ) shifts = set([ shift for shift in shifts if shift.current_assignees.count() < shift.count ]) profiles = list(profiles) # List of hours assigned to each profile hours_mapping = defaultdict(float) # Pre-process, rank shifts by their times / preferences rankings = defaultdict(set) # Initialize with already-assigned shifts for profile in profiles: pool_hours = profile.pool_hours.get(pool=pool) hours_mapping[profile] = float(pool_hours.assigned_hours) for shift in shifts: # Skip shifts that put a member over their hour requirement added_hours = float(shift.hours) + hours_mapping[profile] if added_hours > float(pool_hours.hours): continue # Check how well this shift fits the member's schedule status = is_available(profile, shift) if not status or status == TimeBlock.BUSY: continue try: rating = profile.ratings.get( workshift_type=shift.workshift_type, ).rating except WorkshiftRating.DoesNotExist: rating = WorkshiftRating.INDIFFERENT if rating == WorkshiftRating.DISLIKE: rank = 5 elif rating == WorkshiftRating.INDIFFERENT: rank = 3 else: rank = 1 if status != TimeBlock.PREFERRED: rank += 1 rankings[profile, rank].add(shift) # Assign shifts in a round-robin manner, run until we can't assign anyone # any more shifts while any(rankings.values()): for profile in profiles[:]: pool_hours = profile.pool_hours.get(pool=pool) # Assign a shift, picking from the most preferable groups first for rank in range(1, 7): # Update the rankings with the list of available shifts rankings[profile, rank].intersection_update(shifts) if rankings[profile, rank]: # Select the shift, starting with those that take the most # hours and fit the best into the workshifter's allotted # hours shift = max(rankings[profile, rank], key=lambda x: x.hours) # Assign the person to their shift shift.current_assignees.add(profile) hours_mapping[profile] += float(shift.hours) # Remove shift from shifts if it has been completely filled if shift.current_assignees.count() >= shift.count: shifts.remove(shift) break # Remove profiles when their hours have all been assigned if float(pool_hours.hours) <= hours_mapping[profile]: profiles.remove(profile) for rank in range(1, 7): if (profile, rank) in rankings: del rankings[profile, rank] continue # Otherwise, Remove shifts that put people above their weekly # allocation for rank in range(1, 7): rankings[profile, rank] = set( shift for shift in rankings[profile, rank] if float(shift.hours) + hours_mapping[profile] <= float(pool_hours.hours) ) # Return profiles that were incompletely assigned shifts return profiles
def function[auto_assign_shifts, parameter[semester, pool, profiles, shifts]]: constant[ Auto-assigns profiles to regular workshifts. Parameters ---------- semester : workshift.models.Semester, optional pool : workshift.models.WorkshiftPool, optional profiles : list of workshift.models.WorkshiftProfile, optional shifts : list of workshift.models.RegularWorkshift, optional ] if compare[name[semester] is constant[None]] begin[:] <ast.Try object at 0x7da20cabdd80> if compare[name[pool] is constant[None]] begin[:] variable[pool] assign[=] call[name[WorkshiftPool].objects.get, parameter[]] if compare[name[profiles] is constant[None]] begin[:] variable[profiles] assign[=] call[call[name[WorkshiftProfile].objects.filter, parameter[]].order_by, parameter[constant[preference_save_time]]] if compare[name[shifts] is constant[None]] begin[:] variable[shifts] assign[=] call[name[RegularWorkshift].objects.filter, parameter[]] variable[shifts] assign[=] call[name[set], parameter[<ast.ListComp object at 0x7da18f811540>]] variable[profiles] assign[=] call[name[list], parameter[name[profiles]]] variable[hours_mapping] assign[=] call[name[defaultdict], parameter[name[float]]] variable[rankings] assign[=] call[name[defaultdict], parameter[name[set]]] for taget[name[profile]] in starred[name[profiles]] begin[:] variable[pool_hours] assign[=] call[name[profile].pool_hours.get, parameter[]] call[name[hours_mapping]][name[profile]] assign[=] call[name[float], parameter[name[pool_hours].assigned_hours]] for taget[name[shift]] in starred[name[shifts]] begin[:] variable[added_hours] assign[=] binary_operation[call[name[float], parameter[name[shift].hours]] + call[name[hours_mapping]][name[profile]]] if compare[name[added_hours] greater[>] call[name[float], parameter[name[pool_hours].hours]]] begin[:] continue variable[status] assign[=] call[name[is_available], parameter[name[profile], name[shift]]] if <ast.BoolOp object at 0x7da18f8132e0> begin[:] continue <ast.Try object at 0x7da18f8138e0> if compare[name[rating] equal[==] name[WorkshiftRating].DISLIKE] begin[:] variable[rank] assign[=] constant[5] if compare[name[status] not_equal[!=] name[TimeBlock].PREFERRED] begin[:] <ast.AugAssign object at 0x7da18f810310> call[call[name[rankings]][tuple[[<ast.Name object at 0x7da18f813640>, <ast.Name object at 0x7da18f813e20>]]].add, parameter[name[shift]]] while call[name[any], parameter[call[name[rankings].values, parameter[]]]] begin[:] for taget[name[profile]] in starred[call[name[profiles]][<ast.Slice object at 0x7da18f811b70>]] begin[:] variable[pool_hours] assign[=] call[name[profile].pool_hours.get, parameter[]] for taget[name[rank]] in starred[call[name[range], parameter[constant[1], constant[7]]]] begin[:] call[call[name[rankings]][tuple[[<ast.Name object at 0x7da18f810940>, <ast.Name object at 0x7da18f8107c0>]]].intersection_update, parameter[name[shifts]]] if call[name[rankings]][tuple[[<ast.Name object at 0x7da18f813730>, <ast.Name object at 0x7da18f8127d0>]]] begin[:] variable[shift] assign[=] call[name[max], parameter[call[name[rankings]][tuple[[<ast.Name object at 0x7da18f812980>, <ast.Name object at 0x7da18f812140>]]]]] call[name[shift].current_assignees.add, parameter[name[profile]]] <ast.AugAssign object at 0x7da207f01720> if compare[call[name[shift].current_assignees.count, parameter[]] greater_or_equal[>=] name[shift].count] begin[:] call[name[shifts].remove, parameter[name[shift]]] break if compare[call[name[float], parameter[name[pool_hours].hours]] less_or_equal[<=] call[name[hours_mapping]][name[profile]]] begin[:] call[name[profiles].remove, parameter[name[profile]]] for taget[name[rank]] in starred[call[name[range], parameter[constant[1], constant[7]]]] begin[:] if compare[tuple[[<ast.Name object at 0x7da207f01fc0>, <ast.Name object at 0x7da207f01de0>]] in name[rankings]] begin[:] <ast.Delete object at 0x7da207f026e0> continue for taget[name[rank]] in starred[call[name[range], parameter[constant[1], constant[7]]]] begin[:] call[name[rankings]][tuple[[<ast.Name object at 0x7da207f023e0>, <ast.Name object at 0x7da207f00970>]]] assign[=] call[name[set], parameter[<ast.GeneratorExp object at 0x7da207f02110>]] return[name[profiles]]
keyword[def] identifier[auto_assign_shifts] ( identifier[semester] = keyword[None] , identifier[pool] = keyword[None] , identifier[profiles] = keyword[None] , identifier[shifts] = keyword[None] ): literal[string] keyword[if] identifier[semester] keyword[is] keyword[None] : keyword[try] : identifier[semester] = identifier[Semester] . identifier[objects] . identifier[get] ( identifier[current] = keyword[True] ) keyword[except] ( identifier[Semester] . identifier[DoesNotExist] , identifier[Semester] . identifier[MultipleObjectsReturned] ): keyword[return] keyword[if] identifier[pool] keyword[is] keyword[None] : identifier[pool] = identifier[WorkshiftPool] . identifier[objects] . identifier[get] ( identifier[semester] = identifier[semester] , identifier[is_primary] = keyword[True] , ) keyword[if] identifier[profiles] keyword[is] keyword[None] : identifier[profiles] = identifier[WorkshiftProfile] . identifier[objects] . identifier[filter] ( identifier[semester] = identifier[semester] , ). identifier[order_by] ( literal[string] ) keyword[if] identifier[shifts] keyword[is] keyword[None] : identifier[shifts] = identifier[RegularWorkshift] . identifier[objects] . identifier[filter] ( identifier[pool] = identifier[pool] , identifier[workshift_type__assignment] = identifier[WorkshiftType] . identifier[AUTO_ASSIGN] , ) identifier[shifts] = identifier[set] ([ identifier[shift] keyword[for] identifier[shift] keyword[in] identifier[shifts] keyword[if] identifier[shift] . identifier[current_assignees] . identifier[count] ()< identifier[shift] . identifier[count] ]) identifier[profiles] = identifier[list] ( identifier[profiles] ) identifier[hours_mapping] = identifier[defaultdict] ( identifier[float] ) identifier[rankings] = identifier[defaultdict] ( identifier[set] ) keyword[for] identifier[profile] keyword[in] identifier[profiles] : identifier[pool_hours] = identifier[profile] . identifier[pool_hours] . identifier[get] ( identifier[pool] = identifier[pool] ) identifier[hours_mapping] [ identifier[profile] ]= identifier[float] ( identifier[pool_hours] . identifier[assigned_hours] ) keyword[for] identifier[shift] keyword[in] identifier[shifts] : identifier[added_hours] = identifier[float] ( identifier[shift] . identifier[hours] )+ identifier[hours_mapping] [ identifier[profile] ] keyword[if] identifier[added_hours] > identifier[float] ( identifier[pool_hours] . identifier[hours] ): keyword[continue] identifier[status] = identifier[is_available] ( identifier[profile] , identifier[shift] ) keyword[if] keyword[not] identifier[status] keyword[or] identifier[status] == identifier[TimeBlock] . identifier[BUSY] : keyword[continue] keyword[try] : identifier[rating] = identifier[profile] . identifier[ratings] . identifier[get] ( identifier[workshift_type] = identifier[shift] . identifier[workshift_type] , ). identifier[rating] keyword[except] identifier[WorkshiftRating] . identifier[DoesNotExist] : identifier[rating] = identifier[WorkshiftRating] . identifier[INDIFFERENT] keyword[if] identifier[rating] == identifier[WorkshiftRating] . identifier[DISLIKE] : identifier[rank] = literal[int] keyword[elif] identifier[rating] == identifier[WorkshiftRating] . identifier[INDIFFERENT] : identifier[rank] = literal[int] keyword[else] : identifier[rank] = literal[int] keyword[if] identifier[status] != identifier[TimeBlock] . identifier[PREFERRED] : identifier[rank] += literal[int] identifier[rankings] [ identifier[profile] , identifier[rank] ]. identifier[add] ( identifier[shift] ) keyword[while] identifier[any] ( identifier[rankings] . identifier[values] ()): keyword[for] identifier[profile] keyword[in] identifier[profiles] [:]: identifier[pool_hours] = identifier[profile] . identifier[pool_hours] . identifier[get] ( identifier[pool] = identifier[pool] ) keyword[for] identifier[rank] keyword[in] identifier[range] ( literal[int] , literal[int] ): identifier[rankings] [ identifier[profile] , identifier[rank] ]. identifier[intersection_update] ( identifier[shifts] ) keyword[if] identifier[rankings] [ identifier[profile] , identifier[rank] ]: identifier[shift] = identifier[max] ( identifier[rankings] [ identifier[profile] , identifier[rank] ], identifier[key] = keyword[lambda] identifier[x] : identifier[x] . identifier[hours] ) identifier[shift] . identifier[current_assignees] . identifier[add] ( identifier[profile] ) identifier[hours_mapping] [ identifier[profile] ]+= identifier[float] ( identifier[shift] . identifier[hours] ) keyword[if] identifier[shift] . identifier[current_assignees] . identifier[count] ()>= identifier[shift] . identifier[count] : identifier[shifts] . identifier[remove] ( identifier[shift] ) keyword[break] keyword[if] identifier[float] ( identifier[pool_hours] . identifier[hours] )<= identifier[hours_mapping] [ identifier[profile] ]: identifier[profiles] . identifier[remove] ( identifier[profile] ) keyword[for] identifier[rank] keyword[in] identifier[range] ( literal[int] , literal[int] ): keyword[if] ( identifier[profile] , identifier[rank] ) keyword[in] identifier[rankings] : keyword[del] identifier[rankings] [ identifier[profile] , identifier[rank] ] keyword[continue] keyword[for] identifier[rank] keyword[in] identifier[range] ( literal[int] , literal[int] ): identifier[rankings] [ identifier[profile] , identifier[rank] ]= identifier[set] ( identifier[shift] keyword[for] identifier[shift] keyword[in] identifier[rankings] [ identifier[profile] , identifier[rank] ] keyword[if] identifier[float] ( identifier[shift] . identifier[hours] )+ identifier[hours_mapping] [ identifier[profile] ]<= identifier[float] ( identifier[pool_hours] . identifier[hours] ) ) keyword[return] identifier[profiles]
def auto_assign_shifts(semester=None, pool=None, profiles=None, shifts=None): """ Auto-assigns profiles to regular workshifts. Parameters ---------- semester : workshift.models.Semester, optional pool : workshift.models.WorkshiftPool, optional profiles : list of workshift.models.WorkshiftProfile, optional shifts : list of workshift.models.RegularWorkshift, optional """ if semester is None: try: semester = Semester.objects.get(current=True) # depends on [control=['try'], data=[]] except (Semester.DoesNotExist, Semester.MultipleObjectsReturned): return # depends on [control=['except'], data=[]] # depends on [control=['if'], data=['semester']] if pool is None: pool = WorkshiftPool.objects.get(semester=semester, is_primary=True) # depends on [control=['if'], data=['pool']] if profiles is None: profiles = WorkshiftProfile.objects.filter(semester=semester).order_by('preference_save_time') # depends on [control=['if'], data=['profiles']] if shifts is None: shifts = RegularWorkshift.objects.filter(pool=pool, workshift_type__assignment=WorkshiftType.AUTO_ASSIGN) # depends on [control=['if'], data=['shifts']] shifts = set([shift for shift in shifts if shift.current_assignees.count() < shift.count]) profiles = list(profiles) # List of hours assigned to each profile hours_mapping = defaultdict(float) # Pre-process, rank shifts by their times / preferences rankings = defaultdict(set) # Initialize with already-assigned shifts for profile in profiles: pool_hours = profile.pool_hours.get(pool=pool) hours_mapping[profile] = float(pool_hours.assigned_hours) for shift in shifts: # Skip shifts that put a member over their hour requirement added_hours = float(shift.hours) + hours_mapping[profile] if added_hours > float(pool_hours.hours): continue # depends on [control=['if'], data=[]] # Check how well this shift fits the member's schedule status = is_available(profile, shift) if not status or status == TimeBlock.BUSY: continue # depends on [control=['if'], data=[]] try: rating = profile.ratings.get(workshift_type=shift.workshift_type).rating # depends on [control=['try'], data=[]] except WorkshiftRating.DoesNotExist: rating = WorkshiftRating.INDIFFERENT # depends on [control=['except'], data=[]] if rating == WorkshiftRating.DISLIKE: rank = 5 # depends on [control=['if'], data=[]] elif rating == WorkshiftRating.INDIFFERENT: rank = 3 # depends on [control=['if'], data=[]] else: rank = 1 if status != TimeBlock.PREFERRED: rank += 1 # depends on [control=['if'], data=[]] rankings[profile, rank].add(shift) # depends on [control=['for'], data=['shift']] # depends on [control=['for'], data=['profile']] # Assign shifts in a round-robin manner, run until we can't assign anyone # any more shifts while any(rankings.values()): for profile in profiles[:]: pool_hours = profile.pool_hours.get(pool=pool) # Assign a shift, picking from the most preferable groups first for rank in range(1, 7): # Update the rankings with the list of available shifts rankings[profile, rank].intersection_update(shifts) if rankings[profile, rank]: # Select the shift, starting with those that take the most # hours and fit the best into the workshifter's allotted # hours shift = max(rankings[profile, rank], key=lambda x: x.hours) # Assign the person to their shift shift.current_assignees.add(profile) hours_mapping[profile] += float(shift.hours) # Remove shift from shifts if it has been completely filled if shift.current_assignees.count() >= shift.count: shifts.remove(shift) # depends on [control=['if'], data=[]] break # depends on [control=['if'], data=[]] # depends on [control=['for'], data=['rank']] # Remove profiles when their hours have all been assigned if float(pool_hours.hours) <= hours_mapping[profile]: profiles.remove(profile) for rank in range(1, 7): if (profile, rank) in rankings: del rankings[profile, rank] # depends on [control=['if'], data=['rankings']] # depends on [control=['for'], data=['rank']] continue # depends on [control=['if'], data=[]] # Otherwise, Remove shifts that put people above their weekly # allocation for rank in range(1, 7): rankings[profile, rank] = set((shift for shift in rankings[profile, rank] if float(shift.hours) + hours_mapping[profile] <= float(pool_hours.hours))) # depends on [control=['for'], data=['rank']] # depends on [control=['for'], data=['profile']] # depends on [control=['while'], data=[]] # Return profiles that were incompletely assigned shifts return profiles
def render_string(self, template_name: str, **kwargs: Any) -> bytes: """Generate the given template with the given arguments. We return the generated byte string (in utf8). To generate and write a template as a response, use render() above. """ # If no template_path is specified, use the path of the calling file template_path = self.get_template_path() if not template_path: frame = sys._getframe(0) web_file = frame.f_code.co_filename while frame.f_code.co_filename == web_file: frame = frame.f_back assert frame.f_code.co_filename is not None template_path = os.path.dirname(frame.f_code.co_filename) with RequestHandler._template_loader_lock: if template_path not in RequestHandler._template_loaders: loader = self.create_template_loader(template_path) RequestHandler._template_loaders[template_path] = loader else: loader = RequestHandler._template_loaders[template_path] t = loader.load(template_name) namespace = self.get_template_namespace() namespace.update(kwargs) return t.generate(**namespace)
def function[render_string, parameter[self, template_name]]: constant[Generate the given template with the given arguments. We return the generated byte string (in utf8). To generate and write a template as a response, use render() above. ] variable[template_path] assign[=] call[name[self].get_template_path, parameter[]] if <ast.UnaryOp object at 0x7da1b1f76bf0> begin[:] variable[frame] assign[=] call[name[sys]._getframe, parameter[constant[0]]] variable[web_file] assign[=] name[frame].f_code.co_filename while compare[name[frame].f_code.co_filename equal[==] name[web_file]] begin[:] variable[frame] assign[=] name[frame].f_back assert[compare[name[frame].f_code.co_filename is_not constant[None]]] variable[template_path] assign[=] call[name[os].path.dirname, parameter[name[frame].f_code.co_filename]] with name[RequestHandler]._template_loader_lock begin[:] if compare[name[template_path] <ast.NotIn object at 0x7da2590d7190> name[RequestHandler]._template_loaders] begin[:] variable[loader] assign[=] call[name[self].create_template_loader, parameter[name[template_path]]] call[name[RequestHandler]._template_loaders][name[template_path]] assign[=] name[loader] variable[t] assign[=] call[name[loader].load, parameter[name[template_name]]] variable[namespace] assign[=] call[name[self].get_template_namespace, parameter[]] call[name[namespace].update, parameter[name[kwargs]]] return[call[name[t].generate, parameter[]]]
keyword[def] identifier[render_string] ( identifier[self] , identifier[template_name] : identifier[str] ,** identifier[kwargs] : identifier[Any] )-> identifier[bytes] : literal[string] identifier[template_path] = identifier[self] . identifier[get_template_path] () keyword[if] keyword[not] identifier[template_path] : identifier[frame] = identifier[sys] . identifier[_getframe] ( literal[int] ) identifier[web_file] = identifier[frame] . identifier[f_code] . identifier[co_filename] keyword[while] identifier[frame] . identifier[f_code] . identifier[co_filename] == identifier[web_file] : identifier[frame] = identifier[frame] . identifier[f_back] keyword[assert] identifier[frame] . identifier[f_code] . identifier[co_filename] keyword[is] keyword[not] keyword[None] identifier[template_path] = identifier[os] . identifier[path] . identifier[dirname] ( identifier[frame] . identifier[f_code] . identifier[co_filename] ) keyword[with] identifier[RequestHandler] . identifier[_template_loader_lock] : keyword[if] identifier[template_path] keyword[not] keyword[in] identifier[RequestHandler] . identifier[_template_loaders] : identifier[loader] = identifier[self] . identifier[create_template_loader] ( identifier[template_path] ) identifier[RequestHandler] . identifier[_template_loaders] [ identifier[template_path] ]= identifier[loader] keyword[else] : identifier[loader] = identifier[RequestHandler] . identifier[_template_loaders] [ identifier[template_path] ] identifier[t] = identifier[loader] . identifier[load] ( identifier[template_name] ) identifier[namespace] = identifier[self] . identifier[get_template_namespace] () identifier[namespace] . identifier[update] ( identifier[kwargs] ) keyword[return] identifier[t] . identifier[generate] (** identifier[namespace] )
def render_string(self, template_name: str, **kwargs: Any) -> bytes: """Generate the given template with the given arguments. We return the generated byte string (in utf8). To generate and write a template as a response, use render() above. """ # If no template_path is specified, use the path of the calling file template_path = self.get_template_path() if not template_path: frame = sys._getframe(0) web_file = frame.f_code.co_filename while frame.f_code.co_filename == web_file: frame = frame.f_back # depends on [control=['while'], data=[]] assert frame.f_code.co_filename is not None template_path = os.path.dirname(frame.f_code.co_filename) # depends on [control=['if'], data=[]] with RequestHandler._template_loader_lock: if template_path not in RequestHandler._template_loaders: loader = self.create_template_loader(template_path) RequestHandler._template_loaders[template_path] = loader # depends on [control=['if'], data=['template_path']] else: loader = RequestHandler._template_loaders[template_path] # depends on [control=['with'], data=[]] t = loader.load(template_name) namespace = self.get_template_namespace() namespace.update(kwargs) return t.generate(**namespace)
def select(self, selector, index_only=False): """ Retrieves a subset of :class:`.Paper`\s based on selection criteria. There are a variety of ways to select :class:`.Paper`\s. .. code-block:: python >>> corpus = Corpus(papers) >>> corpus[0] # Integer indices yield a single Paper. <tethne.classes.paper.Paper object at 0x103037c10> >>> corpus[range(0,5)] # A list of indices yields a list of Papers. [<tethne.classes.paper.Paper object at 0x103037c10>, <tethne.classes.paper.Paper object at 0x10301c890>, ... <tethne.classes.paper.Paper object at 0x10302f5d0>] >>> corpus[('date', 1995)] # Select based on indexed fields. [<tethne.classes.paper.Paper object at 0x103037c10>, <tethne.classes.paper.Paper object at 0x10301c890>, ... <tethne.classes.paper.Paper object at 0x10302f5d0>] >>> corpus['citations', ('DOLE RJ 1952 CELL')] # Citing papers! [<tethne.classes.paper.Paper object at 0x103037c10>, <tethne.classes.paper.Paper object at 0x10301c890>, ... <tethne.classes.paper.Paper object at 0x10302f5d0>] >>> corpus[('date', range(1993, 1995))] # Multiple values are OK. [<tethne.classes.paper.Paper object at 0x103037c10>, <tethne.classes.paper.Paper object at 0x10301c890>, ... <tethne.classes.paper.Paper object at 0x10302f5d0>] If you prefer to retrieve a :class:`.Corpus` rather than simply a list of :class:`.Paper` instances (e.g. to build networks), use :meth:`.Corpus.subcorpus`\. Parameters ---------- selector : object See method description. Returns ------- list A list of :class:`.Paper`\s. """ papers = [] if type(selector) is tuple: # Select papers by index. index, value = selector if type(value) is list: # Set of index values. papers = [p for v in value for p in self.select((index, v), index_only=index_only)] else: if value in self.indices[index]: if index_only: papers = self.indices[index][value] else: papers = [self.indexed_papers[p] for p # Single index value. in self.indices[index][value]] else: papers = [] elif type(selector) is list: if selector[0] in self.indexed_papers: # Selector is a list of primary indices. if index_only: papers = selector else: papers = [self.indexed_papers[s] for s in selector] elif type(selector[0]) is int: if index_only: papers = [self.indexed_papers.keys()[i] for i in selector] else: papers = [self.papers[i] for i in selector] elif type(selector) is int: if index_only: papers = self.indexed_papers.keys()[selector] else: papers = self.papers[selector] elif type(selector) in [str, unicode]: if selector in self.indexed_papers: if index_only: papers = selector else: papers = self.indexed_papers[selector] return papers
def function[select, parameter[self, selector, index_only]]: constant[ Retrieves a subset of :class:`.Paper`\s based on selection criteria. There are a variety of ways to select :class:`.Paper`\s. .. code-block:: python >>> corpus = Corpus(papers) >>> corpus[0] # Integer indices yield a single Paper. <tethne.classes.paper.Paper object at 0x103037c10> >>> corpus[range(0,5)] # A list of indices yields a list of Papers. [<tethne.classes.paper.Paper object at 0x103037c10>, <tethne.classes.paper.Paper object at 0x10301c890>, ... <tethne.classes.paper.Paper object at 0x10302f5d0>] >>> corpus[('date', 1995)] # Select based on indexed fields. [<tethne.classes.paper.Paper object at 0x103037c10>, <tethne.classes.paper.Paper object at 0x10301c890>, ... <tethne.classes.paper.Paper object at 0x10302f5d0>] >>> corpus['citations', ('DOLE RJ 1952 CELL')] # Citing papers! [<tethne.classes.paper.Paper object at 0x103037c10>, <tethne.classes.paper.Paper object at 0x10301c890>, ... <tethne.classes.paper.Paper object at 0x10302f5d0>] >>> corpus[('date', range(1993, 1995))] # Multiple values are OK. [<tethne.classes.paper.Paper object at 0x103037c10>, <tethne.classes.paper.Paper object at 0x10301c890>, ... <tethne.classes.paper.Paper object at 0x10302f5d0>] If you prefer to retrieve a :class:`.Corpus` rather than simply a list of :class:`.Paper` instances (e.g. to build networks), use :meth:`.Corpus.subcorpus`\. Parameters ---------- selector : object See method description. Returns ------- list A list of :class:`.Paper`\s. ] variable[papers] assign[=] list[[]] if compare[call[name[type], parameter[name[selector]]] is name[tuple]] begin[:] <ast.Tuple object at 0x7da1b11a78b0> assign[=] name[selector] if compare[call[name[type], parameter[name[value]]] is name[list]] begin[:] variable[papers] assign[=] <ast.ListComp object at 0x7da1b11a47f0> return[name[papers]]
keyword[def] identifier[select] ( identifier[self] , identifier[selector] , identifier[index_only] = keyword[False] ): literal[string] identifier[papers] =[] keyword[if] identifier[type] ( identifier[selector] ) keyword[is] identifier[tuple] : identifier[index] , identifier[value] = identifier[selector] keyword[if] identifier[type] ( identifier[value] ) keyword[is] identifier[list] : identifier[papers] =[ identifier[p] keyword[for] identifier[v] keyword[in] identifier[value] keyword[for] identifier[p] keyword[in] identifier[self] . identifier[select] (( identifier[index] , identifier[v] ), identifier[index_only] = identifier[index_only] )] keyword[else] : keyword[if] identifier[value] keyword[in] identifier[self] . identifier[indices] [ identifier[index] ]: keyword[if] identifier[index_only] : identifier[papers] = identifier[self] . identifier[indices] [ identifier[index] ][ identifier[value] ] keyword[else] : identifier[papers] =[ identifier[self] . identifier[indexed_papers] [ identifier[p] ] keyword[for] identifier[p] keyword[in] identifier[self] . identifier[indices] [ identifier[index] ][ identifier[value] ]] keyword[else] : identifier[papers] =[] keyword[elif] identifier[type] ( identifier[selector] ) keyword[is] identifier[list] : keyword[if] identifier[selector] [ literal[int] ] keyword[in] identifier[self] . identifier[indexed_papers] : keyword[if] identifier[index_only] : identifier[papers] = identifier[selector] keyword[else] : identifier[papers] =[ identifier[self] . identifier[indexed_papers] [ identifier[s] ] keyword[for] identifier[s] keyword[in] identifier[selector] ] keyword[elif] identifier[type] ( identifier[selector] [ literal[int] ]) keyword[is] identifier[int] : keyword[if] identifier[index_only] : identifier[papers] =[ identifier[self] . identifier[indexed_papers] . identifier[keys] ()[ identifier[i] ] keyword[for] identifier[i] keyword[in] identifier[selector] ] keyword[else] : identifier[papers] =[ identifier[self] . identifier[papers] [ identifier[i] ] keyword[for] identifier[i] keyword[in] identifier[selector] ] keyword[elif] identifier[type] ( identifier[selector] ) keyword[is] identifier[int] : keyword[if] identifier[index_only] : identifier[papers] = identifier[self] . identifier[indexed_papers] . identifier[keys] ()[ identifier[selector] ] keyword[else] : identifier[papers] = identifier[self] . identifier[papers] [ identifier[selector] ] keyword[elif] identifier[type] ( identifier[selector] ) keyword[in] [ identifier[str] , identifier[unicode] ]: keyword[if] identifier[selector] keyword[in] identifier[self] . identifier[indexed_papers] : keyword[if] identifier[index_only] : identifier[papers] = identifier[selector] keyword[else] : identifier[papers] = identifier[self] . identifier[indexed_papers] [ identifier[selector] ] keyword[return] identifier[papers]
def select(self, selector, index_only=False): """ Retrieves a subset of :class:`.Paper`\\s based on selection criteria. There are a variety of ways to select :class:`.Paper`\\s. .. code-block:: python >>> corpus = Corpus(papers) >>> corpus[0] # Integer indices yield a single Paper. <tethne.classes.paper.Paper object at 0x103037c10> >>> corpus[range(0,5)] # A list of indices yields a list of Papers. [<tethne.classes.paper.Paper object at 0x103037c10>, <tethne.classes.paper.Paper object at 0x10301c890>, ... <tethne.classes.paper.Paper object at 0x10302f5d0>] >>> corpus[('date', 1995)] # Select based on indexed fields. [<tethne.classes.paper.Paper object at 0x103037c10>, <tethne.classes.paper.Paper object at 0x10301c890>, ... <tethne.classes.paper.Paper object at 0x10302f5d0>] >>> corpus['citations', ('DOLE RJ 1952 CELL')] # Citing papers! [<tethne.classes.paper.Paper object at 0x103037c10>, <tethne.classes.paper.Paper object at 0x10301c890>, ... <tethne.classes.paper.Paper object at 0x10302f5d0>] >>> corpus[('date', range(1993, 1995))] # Multiple values are OK. [<tethne.classes.paper.Paper object at 0x103037c10>, <tethne.classes.paper.Paper object at 0x10301c890>, ... <tethne.classes.paper.Paper object at 0x10302f5d0>] If you prefer to retrieve a :class:`.Corpus` rather than simply a list of :class:`.Paper` instances (e.g. to build networks), use :meth:`.Corpus.subcorpus`\\. Parameters ---------- selector : object See method description. Returns ------- list A list of :class:`.Paper`\\s. """ papers = [] if type(selector) is tuple: # Select papers by index. (index, value) = selector if type(value) is list: # Set of index values. papers = [p for v in value for p in self.select((index, v), index_only=index_only)] # depends on [control=['if'], data=[]] elif value in self.indices[index]: if index_only: papers = self.indices[index][value] # depends on [control=['if'], data=[]] else: # Single index value. papers = [self.indexed_papers[p] for p in self.indices[index][value]] # depends on [control=['if'], data=['value']] else: papers = [] # depends on [control=['if'], data=[]] elif type(selector) is list: if selector[0] in self.indexed_papers: # Selector is a list of primary indices. if index_only: papers = selector # depends on [control=['if'], data=[]] else: papers = [self.indexed_papers[s] for s in selector] # depends on [control=['if'], data=[]] elif type(selector[0]) is int: if index_only: papers = [self.indexed_papers.keys()[i] for i in selector] # depends on [control=['if'], data=[]] else: papers = [self.papers[i] for i in selector] # depends on [control=['if'], data=[]] # depends on [control=['if'], data=[]] elif type(selector) is int: if index_only: papers = self.indexed_papers.keys()[selector] # depends on [control=['if'], data=[]] else: papers = self.papers[selector] # depends on [control=['if'], data=[]] elif type(selector) in [str, unicode]: if selector in self.indexed_papers: if index_only: papers = selector # depends on [control=['if'], data=[]] else: papers = self.indexed_papers[selector] # depends on [control=['if'], data=['selector']] # depends on [control=['if'], data=[]] return papers
def hide_ticks(plot, min_tick_value=None, max_tick_value=None): """Hide tick values that are outside of [min_tick_value, max_tick_value]""" for tick, tick_value in zip(plot.get_yticklabels(), plot.get_yticks()): tick_label = as_numeric(tick_value) if tick_label: if (min_tick_value is not None and tick_label < min_tick_value or max_tick_value is not None and tick_label > max_tick_value): tick.set_visible(False)
def function[hide_ticks, parameter[plot, min_tick_value, max_tick_value]]: constant[Hide tick values that are outside of [min_tick_value, max_tick_value]] for taget[tuple[[<ast.Name object at 0x7da1b10a76d0>, <ast.Name object at 0x7da1b10a7f10>]]] in starred[call[name[zip], parameter[call[name[plot].get_yticklabels, parameter[]], call[name[plot].get_yticks, parameter[]]]]] begin[:] variable[tick_label] assign[=] call[name[as_numeric], parameter[name[tick_value]]] if name[tick_label] begin[:] if <ast.BoolOp object at 0x7da1b10a48e0> begin[:] call[name[tick].set_visible, parameter[constant[False]]]
keyword[def] identifier[hide_ticks] ( identifier[plot] , identifier[min_tick_value] = keyword[None] , identifier[max_tick_value] = keyword[None] ): literal[string] keyword[for] identifier[tick] , identifier[tick_value] keyword[in] identifier[zip] ( identifier[plot] . identifier[get_yticklabels] (), identifier[plot] . identifier[get_yticks] ()): identifier[tick_label] = identifier[as_numeric] ( identifier[tick_value] ) keyword[if] identifier[tick_label] : keyword[if] ( identifier[min_tick_value] keyword[is] keyword[not] keyword[None] keyword[and] identifier[tick_label] < identifier[min_tick_value] keyword[or] identifier[max_tick_value] keyword[is] keyword[not] keyword[None] keyword[and] identifier[tick_label] > identifier[max_tick_value] ): identifier[tick] . identifier[set_visible] ( keyword[False] )
def hide_ticks(plot, min_tick_value=None, max_tick_value=None): """Hide tick values that are outside of [min_tick_value, max_tick_value]""" for (tick, tick_value) in zip(plot.get_yticklabels(), plot.get_yticks()): tick_label = as_numeric(tick_value) if tick_label: if min_tick_value is not None and tick_label < min_tick_value or (max_tick_value is not None and tick_label > max_tick_value): tick.set_visible(False) # depends on [control=['if'], data=[]] # depends on [control=['if'], data=[]] # depends on [control=['for'], data=[]]
def p_pkg_cr_text_value_1(self, p): """pkg_cr_text_value : TEXT""" if six.PY2: p[0] = p[1].decode(encoding='utf-8') else: p[0] = p[1]
def function[p_pkg_cr_text_value_1, parameter[self, p]]: constant[pkg_cr_text_value : TEXT] if name[six].PY2 begin[:] call[name[p]][constant[0]] assign[=] call[call[name[p]][constant[1]].decode, parameter[]]
keyword[def] identifier[p_pkg_cr_text_value_1] ( identifier[self] , identifier[p] ): literal[string] keyword[if] identifier[six] . identifier[PY2] : identifier[p] [ literal[int] ]= identifier[p] [ literal[int] ]. identifier[decode] ( identifier[encoding] = literal[string] ) keyword[else] : identifier[p] [ literal[int] ]= identifier[p] [ literal[int] ]
def p_pkg_cr_text_value_1(self, p): """pkg_cr_text_value : TEXT""" if six.PY2: p[0] = p[1].decode(encoding='utf-8') # depends on [control=['if'], data=[]] else: p[0] = p[1]
def ULT(self, o): """ Unsigned less than. :param o: The other operand :return: TrueResult(), FalseResult(), or MaybeResult() """ unsigned_bounds_1 = self._unsigned_bounds() unsigned_bounds_2 = o._unsigned_bounds() ret = [] for lb_1, ub_1 in unsigned_bounds_1: for lb_2, ub_2 in unsigned_bounds_2: if ub_1 < lb_2: ret.append(TrueResult()) elif lb_1 >= ub_2: ret.append(FalseResult()) else: ret.append(MaybeResult()) if all(r.identical(TrueResult()) for r in ret): return TrueResult() elif all(r.identical(FalseResult()) for r in ret): return FalseResult() else: return MaybeResult()
def function[ULT, parameter[self, o]]: constant[ Unsigned less than. :param o: The other operand :return: TrueResult(), FalseResult(), or MaybeResult() ] variable[unsigned_bounds_1] assign[=] call[name[self]._unsigned_bounds, parameter[]] variable[unsigned_bounds_2] assign[=] call[name[o]._unsigned_bounds, parameter[]] variable[ret] assign[=] list[[]] for taget[tuple[[<ast.Name object at 0x7da1b2345720>, <ast.Name object at 0x7da1b2345900>]]] in starred[name[unsigned_bounds_1]] begin[:] for taget[tuple[[<ast.Name object at 0x7da1b2345b70>, <ast.Name object at 0x7da1b23462c0>]]] in starred[name[unsigned_bounds_2]] begin[:] if compare[name[ub_1] less[<] name[lb_2]] begin[:] call[name[ret].append, parameter[call[name[TrueResult], parameter[]]]] if call[name[all], parameter[<ast.GeneratorExp object at 0x7da1b2345060>]] begin[:] return[call[name[TrueResult], parameter[]]]
keyword[def] identifier[ULT] ( identifier[self] , identifier[o] ): literal[string] identifier[unsigned_bounds_1] = identifier[self] . identifier[_unsigned_bounds] () identifier[unsigned_bounds_2] = identifier[o] . identifier[_unsigned_bounds] () identifier[ret] =[] keyword[for] identifier[lb_1] , identifier[ub_1] keyword[in] identifier[unsigned_bounds_1] : keyword[for] identifier[lb_2] , identifier[ub_2] keyword[in] identifier[unsigned_bounds_2] : keyword[if] identifier[ub_1] < identifier[lb_2] : identifier[ret] . identifier[append] ( identifier[TrueResult] ()) keyword[elif] identifier[lb_1] >= identifier[ub_2] : identifier[ret] . identifier[append] ( identifier[FalseResult] ()) keyword[else] : identifier[ret] . identifier[append] ( identifier[MaybeResult] ()) keyword[if] identifier[all] ( identifier[r] . identifier[identical] ( identifier[TrueResult] ()) keyword[for] identifier[r] keyword[in] identifier[ret] ): keyword[return] identifier[TrueResult] () keyword[elif] identifier[all] ( identifier[r] . identifier[identical] ( identifier[FalseResult] ()) keyword[for] identifier[r] keyword[in] identifier[ret] ): keyword[return] identifier[FalseResult] () keyword[else] : keyword[return] identifier[MaybeResult] ()
def ULT(self, o): """ Unsigned less than. :param o: The other operand :return: TrueResult(), FalseResult(), or MaybeResult() """ unsigned_bounds_1 = self._unsigned_bounds() unsigned_bounds_2 = o._unsigned_bounds() ret = [] for (lb_1, ub_1) in unsigned_bounds_1: for (lb_2, ub_2) in unsigned_bounds_2: if ub_1 < lb_2: ret.append(TrueResult()) # depends on [control=['if'], data=[]] elif lb_1 >= ub_2: ret.append(FalseResult()) # depends on [control=['if'], data=[]] else: ret.append(MaybeResult()) # depends on [control=['for'], data=[]] # depends on [control=['for'], data=[]] if all((r.identical(TrueResult()) for r in ret)): return TrueResult() # depends on [control=['if'], data=[]] elif all((r.identical(FalseResult()) for r in ret)): return FalseResult() # depends on [control=['if'], data=[]] else: return MaybeResult()
def forget(self, key): """ Remove an item from the cache. :param key: The cache key :type key: str :rtype: bool """ if key in self._storage: del self._storage[key] return True return False
def function[forget, parameter[self, key]]: constant[ Remove an item from the cache. :param key: The cache key :type key: str :rtype: bool ] if compare[name[key] in name[self]._storage] begin[:] <ast.Delete object at 0x7da1b196f910> return[constant[True]] return[constant[False]]
keyword[def] identifier[forget] ( identifier[self] , identifier[key] ): literal[string] keyword[if] identifier[key] keyword[in] identifier[self] . identifier[_storage] : keyword[del] identifier[self] . identifier[_storage] [ identifier[key] ] keyword[return] keyword[True] keyword[return] keyword[False]
def forget(self, key): """ Remove an item from the cache. :param key: The cache key :type key: str :rtype: bool """ if key in self._storage: del self._storage[key] return True # depends on [control=['if'], data=['key']] return False
def get_shared(func): """ return shared. """ shared = [] if not hasattr(func, '__cls__'): return shared if not hasattr(func.__cls__, '__shared_arguments__'): return shared if hasattr(func, '__no_share__'): if func.__no_share__ is True: return shared else: shared += [ s for s in func.__cls__.__shared_arguments__ if (s[0][-1].replace('--', '').replace('-', '_')) not in func.__no_share__] else: shared = func.__cls__.__shared_arguments__ return shared
def function[get_shared, parameter[func]]: constant[ return shared. ] variable[shared] assign[=] list[[]] if <ast.UnaryOp object at 0x7da1b24adab0> begin[:] return[name[shared]] if <ast.UnaryOp object at 0x7da1b24ac250> begin[:] return[name[shared]] if call[name[hasattr], parameter[name[func], constant[__no_share__]]] begin[:] if compare[name[func].__no_share__ is constant[True]] begin[:] return[name[shared]] return[name[shared]]
keyword[def] identifier[get_shared] ( identifier[func] ): literal[string] identifier[shared] =[] keyword[if] keyword[not] identifier[hasattr] ( identifier[func] , literal[string] ): keyword[return] identifier[shared] keyword[if] keyword[not] identifier[hasattr] ( identifier[func] . identifier[__cls__] , literal[string] ): keyword[return] identifier[shared] keyword[if] identifier[hasattr] ( identifier[func] , literal[string] ): keyword[if] identifier[func] . identifier[__no_share__] keyword[is] keyword[True] : keyword[return] identifier[shared] keyword[else] : identifier[shared] +=[ identifier[s] keyword[for] identifier[s] keyword[in] identifier[func] . identifier[__cls__] . identifier[__shared_arguments__] keyword[if] ( identifier[s] [ literal[int] ][- literal[int] ]. identifier[replace] ( literal[string] , literal[string] ). identifier[replace] ( literal[string] , literal[string] )) keyword[not] keyword[in] identifier[func] . identifier[__no_share__] ] keyword[else] : identifier[shared] = identifier[func] . identifier[__cls__] . identifier[__shared_arguments__] keyword[return] identifier[shared]
def get_shared(func): """ return shared. """ shared = [] if not hasattr(func, '__cls__'): return shared # depends on [control=['if'], data=[]] if not hasattr(func.__cls__, '__shared_arguments__'): return shared # depends on [control=['if'], data=[]] if hasattr(func, '__no_share__'): if func.__no_share__ is True: return shared # depends on [control=['if'], data=[]] else: shared += [s for s in func.__cls__.__shared_arguments__ if s[0][-1].replace('--', '').replace('-', '_') not in func.__no_share__] # depends on [control=['if'], data=[]] else: shared = func.__cls__.__shared_arguments__ return shared
def cyvcf2(context, vcf, include, exclude, chrom, start, end, loglevel, silent, individual, no_inds): """fast vcf parsing with cython + htslib""" coloredlogs.install(log_level=loglevel) start_parsing = datetime.now() log.info("Running cyvcf2 version %s", __version__) if include and exclude: log.warning("Can not use include and exclude at the same time") context.abort() region = '' if (chrom or start or end): if not (chrom and start and end): log.warning("Please specify chromosome, start and end for region") context.abort() else: region = "{0}:{1}-{2}".format(chrom, start, end) vcf_obj = VCF(vcf) for inclusion in include: if vcf_obj.contains(inclusion): log.info("Including %s in output", inclusion) else: log.warning("%s does not exist in header", inclusion) context.abort() for exclusion in exclude: if vcf_obj.contains(exclusion): log.info("Excluding %s in output", exclusion) else: log.warning("%s does not exist in header", exclusion) context.abort() if individual: # Check if the choosen individuals exists in vcf test = True for ind_id in individual: if ind_id not in vcf_obj.samples: log.warning("Individual '%s' does not exist in vcf", ind_id) test = False if not test: context.abort() # Convert individuals to list for VCF.set_individuals individual = list(individual) else: individual = None # Set individual to be empty list to skip all genotypes if no_inds: individual = [] if not silent: print_header(vcf_obj, include, exclude, individual) nr_variants = None try: for nr_variants, variant in enumerate(vcf_obj(region)): if not silent: print_variant(variant, include, exclude) except Exception as err: log.warning(err) context.abort() if nr_variants is None: log.info("No variants in vcf") return log.info("{0} variants parsed".format(nr_variants+1)) log.info("Time to parse variants: {0}".format(datetime.now() - start_parsing))
def function[cyvcf2, parameter[context, vcf, include, exclude, chrom, start, end, loglevel, silent, individual, no_inds]]: constant[fast vcf parsing with cython + htslib] call[name[coloredlogs].install, parameter[]] variable[start_parsing] assign[=] call[name[datetime].now, parameter[]] call[name[log].info, parameter[constant[Running cyvcf2 version %s], name[__version__]]] if <ast.BoolOp object at 0x7da2054a4c40> begin[:] call[name[log].warning, parameter[constant[Can not use include and exclude at the same time]]] call[name[context].abort, parameter[]] variable[region] assign[=] constant[] if <ast.BoolOp object at 0x7da2054a6350> begin[:] if <ast.UnaryOp object at 0x7da2054a5f00> begin[:] call[name[log].warning, parameter[constant[Please specify chromosome, start and end for region]]] call[name[context].abort, parameter[]] variable[vcf_obj] assign[=] call[name[VCF], parameter[name[vcf]]] for taget[name[inclusion]] in starred[name[include]] begin[:] if call[name[vcf_obj].contains, parameter[name[inclusion]]] begin[:] call[name[log].info, parameter[constant[Including %s in output], name[inclusion]]] for taget[name[exclusion]] in starred[name[exclude]] begin[:] if call[name[vcf_obj].contains, parameter[name[exclusion]]] begin[:] call[name[log].info, parameter[constant[Excluding %s in output], name[exclusion]]] if name[individual] begin[:] variable[test] assign[=] constant[True] for taget[name[ind_id]] in starred[name[individual]] begin[:] if compare[name[ind_id] <ast.NotIn object at 0x7da2590d7190> name[vcf_obj].samples] begin[:] call[name[log].warning, parameter[constant[Individual '%s' does not exist in vcf], name[ind_id]]] variable[test] assign[=] constant[False] if <ast.UnaryOp object at 0x7da18c4cd030> begin[:] call[name[context].abort, parameter[]] variable[individual] assign[=] call[name[list], parameter[name[individual]]] if name[no_inds] begin[:] variable[individual] assign[=] list[[]] if <ast.UnaryOp object at 0x7da18c4cfe50> begin[:] call[name[print_header], parameter[name[vcf_obj], name[include], name[exclude], name[individual]]] variable[nr_variants] assign[=] constant[None] <ast.Try object at 0x7da18c4cc4c0> if compare[name[nr_variants] is constant[None]] begin[:] call[name[log].info, parameter[constant[No variants in vcf]]] return[None] call[name[log].info, parameter[call[constant[{0} variants parsed].format, parameter[binary_operation[name[nr_variants] + constant[1]]]]]] call[name[log].info, parameter[call[constant[Time to parse variants: {0}].format, parameter[binary_operation[call[name[datetime].now, parameter[]] - name[start_parsing]]]]]]
keyword[def] identifier[cyvcf2] ( identifier[context] , identifier[vcf] , identifier[include] , identifier[exclude] , identifier[chrom] , identifier[start] , identifier[end] , identifier[loglevel] , identifier[silent] , identifier[individual] , identifier[no_inds] ): literal[string] identifier[coloredlogs] . identifier[install] ( identifier[log_level] = identifier[loglevel] ) identifier[start_parsing] = identifier[datetime] . identifier[now] () identifier[log] . identifier[info] ( literal[string] , identifier[__version__] ) keyword[if] identifier[include] keyword[and] identifier[exclude] : identifier[log] . identifier[warning] ( literal[string] ) identifier[context] . identifier[abort] () identifier[region] = literal[string] keyword[if] ( identifier[chrom] keyword[or] identifier[start] keyword[or] identifier[end] ): keyword[if] keyword[not] ( identifier[chrom] keyword[and] identifier[start] keyword[and] identifier[end] ): identifier[log] . identifier[warning] ( literal[string] ) identifier[context] . identifier[abort] () keyword[else] : identifier[region] = literal[string] . identifier[format] ( identifier[chrom] , identifier[start] , identifier[end] ) identifier[vcf_obj] = identifier[VCF] ( identifier[vcf] ) keyword[for] identifier[inclusion] keyword[in] identifier[include] : keyword[if] identifier[vcf_obj] . identifier[contains] ( identifier[inclusion] ): identifier[log] . identifier[info] ( literal[string] , identifier[inclusion] ) keyword[else] : identifier[log] . identifier[warning] ( literal[string] , identifier[inclusion] ) identifier[context] . identifier[abort] () keyword[for] identifier[exclusion] keyword[in] identifier[exclude] : keyword[if] identifier[vcf_obj] . identifier[contains] ( identifier[exclusion] ): identifier[log] . identifier[info] ( literal[string] , identifier[exclusion] ) keyword[else] : identifier[log] . identifier[warning] ( literal[string] , identifier[exclusion] ) identifier[context] . identifier[abort] () keyword[if] identifier[individual] : identifier[test] = keyword[True] keyword[for] identifier[ind_id] keyword[in] identifier[individual] : keyword[if] identifier[ind_id] keyword[not] keyword[in] identifier[vcf_obj] . identifier[samples] : identifier[log] . identifier[warning] ( literal[string] , identifier[ind_id] ) identifier[test] = keyword[False] keyword[if] keyword[not] identifier[test] : identifier[context] . identifier[abort] () identifier[individual] = identifier[list] ( identifier[individual] ) keyword[else] : identifier[individual] = keyword[None] keyword[if] identifier[no_inds] : identifier[individual] =[] keyword[if] keyword[not] identifier[silent] : identifier[print_header] ( identifier[vcf_obj] , identifier[include] , identifier[exclude] , identifier[individual] ) identifier[nr_variants] = keyword[None] keyword[try] : keyword[for] identifier[nr_variants] , identifier[variant] keyword[in] identifier[enumerate] ( identifier[vcf_obj] ( identifier[region] )): keyword[if] keyword[not] identifier[silent] : identifier[print_variant] ( identifier[variant] , identifier[include] , identifier[exclude] ) keyword[except] identifier[Exception] keyword[as] identifier[err] : identifier[log] . identifier[warning] ( identifier[err] ) identifier[context] . identifier[abort] () keyword[if] identifier[nr_variants] keyword[is] keyword[None] : identifier[log] . identifier[info] ( literal[string] ) keyword[return] identifier[log] . identifier[info] ( literal[string] . identifier[format] ( identifier[nr_variants] + literal[int] )) identifier[log] . identifier[info] ( literal[string] . identifier[format] ( identifier[datetime] . identifier[now] ()- identifier[start_parsing] ))
def cyvcf2(context, vcf, include, exclude, chrom, start, end, loglevel, silent, individual, no_inds): """fast vcf parsing with cython + htslib""" coloredlogs.install(log_level=loglevel) start_parsing = datetime.now() log.info('Running cyvcf2 version %s', __version__) if include and exclude: log.warning('Can not use include and exclude at the same time') context.abort() # depends on [control=['if'], data=[]] region = '' if chrom or start or end: if not (chrom and start and end): log.warning('Please specify chromosome, start and end for region') context.abort() # depends on [control=['if'], data=[]] else: region = '{0}:{1}-{2}'.format(chrom, start, end) # depends on [control=['if'], data=[]] vcf_obj = VCF(vcf) for inclusion in include: if vcf_obj.contains(inclusion): log.info('Including %s in output', inclusion) # depends on [control=['if'], data=[]] else: log.warning('%s does not exist in header', inclusion) context.abort() # depends on [control=['for'], data=['inclusion']] for exclusion in exclude: if vcf_obj.contains(exclusion): log.info('Excluding %s in output', exclusion) # depends on [control=['if'], data=[]] else: log.warning('%s does not exist in header', exclusion) context.abort() # depends on [control=['for'], data=['exclusion']] if individual: # Check if the choosen individuals exists in vcf test = True for ind_id in individual: if ind_id not in vcf_obj.samples: log.warning("Individual '%s' does not exist in vcf", ind_id) test = False # depends on [control=['if'], data=['ind_id']] if not test: context.abort() # depends on [control=['if'], data=[]] # depends on [control=['for'], data=['ind_id']] # Convert individuals to list for VCF.set_individuals individual = list(individual) # depends on [control=['if'], data=[]] else: individual = None # Set individual to be empty list to skip all genotypes if no_inds: individual = [] # depends on [control=['if'], data=[]] if not silent: print_header(vcf_obj, include, exclude, individual) # depends on [control=['if'], data=[]] nr_variants = None try: for (nr_variants, variant) in enumerate(vcf_obj(region)): if not silent: print_variant(variant, include, exclude) # depends on [control=['if'], data=[]] # depends on [control=['for'], data=[]] # depends on [control=['try'], data=[]] except Exception as err: log.warning(err) context.abort() # depends on [control=['except'], data=['err']] if nr_variants is None: log.info('No variants in vcf') return # depends on [control=['if'], data=[]] log.info('{0} variants parsed'.format(nr_variants + 1)) log.info('Time to parse variants: {0}'.format(datetime.now() - start_parsing))
def set_include_entities(self, include): """ Sets 'include entities' parameter to either \ include or exclude the entities node within the results :param include: Boolean to trigger the 'include entities' parameter :raises: TwitterSearchException """ if not isinstance(include, bool): raise TwitterSearchException(1008) self.arguments.update( {'include_entities': 'true' if include else 'false'} )
def function[set_include_entities, parameter[self, include]]: constant[ Sets 'include entities' parameter to either include or exclude the entities node within the results :param include: Boolean to trigger the 'include entities' parameter :raises: TwitterSearchException ] if <ast.UnaryOp object at 0x7da18f58e7d0> begin[:] <ast.Raise object at 0x7da20e961630> call[name[self].arguments.update, parameter[dictionary[[<ast.Constant object at 0x7da20e960bb0>], [<ast.IfExp object at 0x7da20e962680>]]]]
keyword[def] identifier[set_include_entities] ( identifier[self] , identifier[include] ): literal[string] keyword[if] keyword[not] identifier[isinstance] ( identifier[include] , identifier[bool] ): keyword[raise] identifier[TwitterSearchException] ( literal[int] ) identifier[self] . identifier[arguments] . identifier[update] ( { literal[string] : literal[string] keyword[if] identifier[include] keyword[else] literal[string] } )
def set_include_entities(self, include): """ Sets 'include entities' parameter to either include or exclude the entities node within the results :param include: Boolean to trigger the 'include entities' parameter :raises: TwitterSearchException """ if not isinstance(include, bool): raise TwitterSearchException(1008) # depends on [control=['if'], data=[]] self.arguments.update({'include_entities': 'true' if include else 'false'})
def withconfig(self, keysuffix): """ Load configurations with this decorator """ def decorator(cls): return self.loadconfig(keysuffix, cls) return decorator
def function[withconfig, parameter[self, keysuffix]]: constant[ Load configurations with this decorator ] def function[decorator, parameter[cls]]: return[call[name[self].loadconfig, parameter[name[keysuffix], name[cls]]]] return[name[decorator]]
keyword[def] identifier[withconfig] ( identifier[self] , identifier[keysuffix] ): literal[string] keyword[def] identifier[decorator] ( identifier[cls] ): keyword[return] identifier[self] . identifier[loadconfig] ( identifier[keysuffix] , identifier[cls] ) keyword[return] identifier[decorator]
def withconfig(self, keysuffix): """ Load configurations with this decorator """ def decorator(cls): return self.loadconfig(keysuffix, cls) return decorator
def parents(self, table_name, primary=None): """ :param table_name: `schema`.`table` :param primary: if None, then all parents are returned. If True, then only foreign keys composed of primary key attributes are considered. If False, the only foreign keys including at least one non-primary attribute are considered. :return: dict of tables referenced by the foreign keys of table """ return dict(p[::2] for p in self.in_edges(table_name, data=True) if primary is None or p[2]['primary'] == primary)
def function[parents, parameter[self, table_name, primary]]: constant[ :param table_name: `schema`.`table` :param primary: if None, then all parents are returned. If True, then only foreign keys composed of primary key attributes are considered. If False, the only foreign keys including at least one non-primary attribute are considered. :return: dict of tables referenced by the foreign keys of table ] return[call[name[dict], parameter[<ast.GeneratorExp object at 0x7da2044c3e50>]]]
keyword[def] identifier[parents] ( identifier[self] , identifier[table_name] , identifier[primary] = keyword[None] ): literal[string] keyword[return] identifier[dict] ( identifier[p] [:: literal[int] ] keyword[for] identifier[p] keyword[in] identifier[self] . identifier[in_edges] ( identifier[table_name] , identifier[data] = keyword[True] ) keyword[if] identifier[primary] keyword[is] keyword[None] keyword[or] identifier[p] [ literal[int] ][ literal[string] ]== identifier[primary] )
def parents(self, table_name, primary=None): """ :param table_name: `schema`.`table` :param primary: if None, then all parents are returned. If True, then only foreign keys composed of primary key attributes are considered. If False, the only foreign keys including at least one non-primary attribute are considered. :return: dict of tables referenced by the foreign keys of table """ return dict((p[::2] for p in self.in_edges(table_name, data=True) if primary is None or p[2]['primary'] == primary))
def syncStateCall(self, method, url, params={}, **kwargs): """ Follow and track sync state URLs provided by an API endpoint, in order to implicitly handle pagination. In the first call, ``url`` and ``params`` are used as-is. If a ``syncState`` endpoint is provided in the response, subsequent calls go to the latest URL instead. Args: method (str): HTTP request method url (str): full URL to connect to params (dict): query parameters to include in the URL kwargs (dict): any extra parameters to pass to :meth:`__call__` """ try: states = self.syncStates[(method, url)] except KeyError: states = self.syncStates[(method, url)] = [] if states: # We have a state link, use it to replace the URL and query string. url = states[-1] params = {} resp = self(method, url, params=params, **kwargs) try: json = resp.json() except ValueError: # Don't do anything if not a JSON response. pass else: # If a state link exists in the response, store it for later. state = json.get("_metadata", {}).get("syncState") if state: states.append(state) return resp
def function[syncStateCall, parameter[self, method, url, params]]: constant[ Follow and track sync state URLs provided by an API endpoint, in order to implicitly handle pagination. In the first call, ``url`` and ``params`` are used as-is. If a ``syncState`` endpoint is provided in the response, subsequent calls go to the latest URL instead. Args: method (str): HTTP request method url (str): full URL to connect to params (dict): query parameters to include in the URL kwargs (dict): any extra parameters to pass to :meth:`__call__` ] <ast.Try object at 0x7da18f721b70> if name[states] begin[:] variable[url] assign[=] call[name[states]][<ast.UnaryOp object at 0x7da18f722bc0>] variable[params] assign[=] dictionary[[], []] variable[resp] assign[=] call[name[self], parameter[name[method], name[url]]] <ast.Try object at 0x7da18f7218d0> return[name[resp]]
keyword[def] identifier[syncStateCall] ( identifier[self] , identifier[method] , identifier[url] , identifier[params] ={},** identifier[kwargs] ): literal[string] keyword[try] : identifier[states] = identifier[self] . identifier[syncStates] [( identifier[method] , identifier[url] )] keyword[except] identifier[KeyError] : identifier[states] = identifier[self] . identifier[syncStates] [( identifier[method] , identifier[url] )]=[] keyword[if] identifier[states] : identifier[url] = identifier[states] [- literal[int] ] identifier[params] ={} identifier[resp] = identifier[self] ( identifier[method] , identifier[url] , identifier[params] = identifier[params] ,** identifier[kwargs] ) keyword[try] : identifier[json] = identifier[resp] . identifier[json] () keyword[except] identifier[ValueError] : keyword[pass] keyword[else] : identifier[state] = identifier[json] . identifier[get] ( literal[string] ,{}). identifier[get] ( literal[string] ) keyword[if] identifier[state] : identifier[states] . identifier[append] ( identifier[state] ) keyword[return] identifier[resp]
def syncStateCall(self, method, url, params={}, **kwargs): """ Follow and track sync state URLs provided by an API endpoint, in order to implicitly handle pagination. In the first call, ``url`` and ``params`` are used as-is. If a ``syncState`` endpoint is provided in the response, subsequent calls go to the latest URL instead. Args: method (str): HTTP request method url (str): full URL to connect to params (dict): query parameters to include in the URL kwargs (dict): any extra parameters to pass to :meth:`__call__` """ try: states = self.syncStates[method, url] # depends on [control=['try'], data=[]] except KeyError: states = self.syncStates[method, url] = [] # depends on [control=['except'], data=[]] if states: # We have a state link, use it to replace the URL and query string. url = states[-1] params = {} # depends on [control=['if'], data=[]] resp = self(method, url, params=params, **kwargs) try: json = resp.json() # depends on [control=['try'], data=[]] except ValueError: # Don't do anything if not a JSON response. pass # depends on [control=['except'], data=[]] else: # If a state link exists in the response, store it for later. state = json.get('_metadata', {}).get('syncState') if state: states.append(state) # depends on [control=['if'], data=[]] return resp
def complex_exists(self, complex: str) -> bool: """ Shortcut to check if complex exists in our database. """ try: self.check_complex(complex) except exceptions.RumetrComplexNotFound: return False return True
def function[complex_exists, parameter[self, complex]]: constant[ Shortcut to check if complex exists in our database. ] <ast.Try object at 0x7da1b14d02b0> return[constant[True]]
keyword[def] identifier[complex_exists] ( identifier[self] , identifier[complex] : identifier[str] )-> identifier[bool] : literal[string] keyword[try] : identifier[self] . identifier[check_complex] ( identifier[complex] ) keyword[except] identifier[exceptions] . identifier[RumetrComplexNotFound] : keyword[return] keyword[False] keyword[return] keyword[True]
def complex_exists(self, complex: str) -> bool: """ Shortcut to check if complex exists in our database. """ try: self.check_complex(complex) # depends on [control=['try'], data=[]] except exceptions.RumetrComplexNotFound: return False # depends on [control=['except'], data=[]] return True
def parse(self, text): """Parse the given code and add it to :attr:`scripts`. The syntax matches :attr:`Script.stringify()`. See :mod:`kurt.text` for reference. """ self.scripts.append(kurt.text.parse(text, self))
def function[parse, parameter[self, text]]: constant[Parse the given code and add it to :attr:`scripts`. The syntax matches :attr:`Script.stringify()`. See :mod:`kurt.text` for reference. ] call[name[self].scripts.append, parameter[call[name[kurt].text.parse, parameter[name[text], name[self]]]]]
keyword[def] identifier[parse] ( identifier[self] , identifier[text] ): literal[string] identifier[self] . identifier[scripts] . identifier[append] ( identifier[kurt] . identifier[text] . identifier[parse] ( identifier[text] , identifier[self] ))
def parse(self, text): """Parse the given code and add it to :attr:`scripts`. The syntax matches :attr:`Script.stringify()`. See :mod:`kurt.text` for reference. """ self.scripts.append(kurt.text.parse(text, self))
def bottomup(cls): """Get all bottomup `Relationship` instances. Example: >>> from pronto import Relationship >>> for r in Relationship.bottomup(): ... print(r) Relationship('is_a') Relationship('part_of') Relationship('develops_from') """ return tuple(unique_everseen(r for r in cls._instances.values() if r.direction=='bottomup'))
def function[bottomup, parameter[cls]]: constant[Get all bottomup `Relationship` instances. Example: >>> from pronto import Relationship >>> for r in Relationship.bottomup(): ... print(r) Relationship('is_a') Relationship('part_of') Relationship('develops_from') ] return[call[name[tuple], parameter[call[name[unique_everseen], parameter[<ast.GeneratorExp object at 0x7da1b138b190>]]]]]
keyword[def] identifier[bottomup] ( identifier[cls] ): literal[string] keyword[return] identifier[tuple] ( identifier[unique_everseen] ( identifier[r] keyword[for] identifier[r] keyword[in] identifier[cls] . identifier[_instances] . identifier[values] () keyword[if] identifier[r] . identifier[direction] == literal[string] ))
def bottomup(cls): """Get all bottomup `Relationship` instances. Example: >>> from pronto import Relationship >>> for r in Relationship.bottomup(): ... print(r) Relationship('is_a') Relationship('part_of') Relationship('develops_from') """ return tuple(unique_everseen((r for r in cls._instances.values() if r.direction == 'bottomup')))
def get_stp_mst_detail_output_msti_port_port_priority(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") get_stp_mst_detail = ET.Element("get_stp_mst_detail") config = get_stp_mst_detail output = ET.SubElement(get_stp_mst_detail, "output") msti = ET.SubElement(output, "msti") instance_id_key = ET.SubElement(msti, "instance-id") instance_id_key.text = kwargs.pop('instance_id') port = ET.SubElement(msti, "port") port_priority = ET.SubElement(port, "port-priority") port_priority.text = kwargs.pop('port_priority') callback = kwargs.pop('callback', self._callback) return callback(config)
def function[get_stp_mst_detail_output_msti_port_port_priority, parameter[self]]: constant[Auto Generated Code ] variable[config] assign[=] call[name[ET].Element, parameter[constant[config]]] variable[get_stp_mst_detail] assign[=] call[name[ET].Element, parameter[constant[get_stp_mst_detail]]] variable[config] assign[=] name[get_stp_mst_detail] variable[output] assign[=] call[name[ET].SubElement, parameter[name[get_stp_mst_detail], constant[output]]] variable[msti] assign[=] call[name[ET].SubElement, parameter[name[output], constant[msti]]] variable[instance_id_key] assign[=] call[name[ET].SubElement, parameter[name[msti], constant[instance-id]]] name[instance_id_key].text assign[=] call[name[kwargs].pop, parameter[constant[instance_id]]] variable[port] assign[=] call[name[ET].SubElement, parameter[name[msti], constant[port]]] variable[port_priority] assign[=] call[name[ET].SubElement, parameter[name[port], constant[port-priority]]] name[port_priority].text assign[=] call[name[kwargs].pop, parameter[constant[port_priority]]] variable[callback] assign[=] call[name[kwargs].pop, parameter[constant[callback], name[self]._callback]] return[call[name[callback], parameter[name[config]]]]
keyword[def] identifier[get_stp_mst_detail_output_msti_port_port_priority] ( identifier[self] ,** identifier[kwargs] ): literal[string] identifier[config] = identifier[ET] . identifier[Element] ( literal[string] ) identifier[get_stp_mst_detail] = identifier[ET] . identifier[Element] ( literal[string] ) identifier[config] = identifier[get_stp_mst_detail] identifier[output] = identifier[ET] . identifier[SubElement] ( identifier[get_stp_mst_detail] , literal[string] ) identifier[msti] = identifier[ET] . identifier[SubElement] ( identifier[output] , literal[string] ) identifier[instance_id_key] = identifier[ET] . identifier[SubElement] ( identifier[msti] , literal[string] ) identifier[instance_id_key] . identifier[text] = identifier[kwargs] . identifier[pop] ( literal[string] ) identifier[port] = identifier[ET] . identifier[SubElement] ( identifier[msti] , literal[string] ) identifier[port_priority] = identifier[ET] . identifier[SubElement] ( identifier[port] , literal[string] ) identifier[port_priority] . identifier[text] = identifier[kwargs] . identifier[pop] ( literal[string] ) identifier[callback] = identifier[kwargs] . identifier[pop] ( literal[string] , identifier[self] . identifier[_callback] ) keyword[return] identifier[callback] ( identifier[config] )
def get_stp_mst_detail_output_msti_port_port_priority(self, **kwargs): """Auto Generated Code """ config = ET.Element('config') get_stp_mst_detail = ET.Element('get_stp_mst_detail') config = get_stp_mst_detail output = ET.SubElement(get_stp_mst_detail, 'output') msti = ET.SubElement(output, 'msti') instance_id_key = ET.SubElement(msti, 'instance-id') instance_id_key.text = kwargs.pop('instance_id') port = ET.SubElement(msti, 'port') port_priority = ET.SubElement(port, 'port-priority') port_priority.text = kwargs.pop('port_priority') callback = kwargs.pop('callback', self._callback) return callback(config)